#!/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 due; 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.

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

# The version the package stamped on this script when nix built it
# (nix/packages.nix): the CLI's version and the commit it was built from.
# A script run straight from a checkout has none. It is taken here and
# unset, so no program this script runs inherits a stamp that is not its
# own; self-update is handed it explicitly.
VALLEY_STAMP="${VALLEY_VERSION:-}"
unset VALLEY_VERSION

# When this invocation started, in microseconds, for its command record
# (valley help telemetry). Reading the clock starts no process.
TEL_T0="${EPOCHREALTIME/[.,]/}"

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

usage() {
  cat <<'EOF'
usage: valley <verb> [args]

valley — S1 integrator verbs for a valley project: author, review, approve, and
track changes and the plan graph.

Authoring and updating changes:
  ready        mark a branch head ready as a new version of its change
  unready      pause a ready change by marking it a draft
  withdraw     mark a ready or draft change withdrawn
  rebase       rebase a change and its stack onto origin/main
  checks       print the checks the composed policy requires of a diff

Reviewing, approving, and inspecting changes:
  pending      list what needs an approval, in landing order, and what moves
  review       page through a change or stack to approve, rebase, or reject
  approve      run required checks and file an integration request
  status       read a change's integration request and last outcome
  changes      print every recorded change as valley-changes/v1 JSON

Planning work:
  plan         show the project's plan graph as a milestone tree
  knot         read and write knots in the plan graph at refs/the-valley/knots

Bus and client maintenance:
  tail         watch NATS bus events scroll by
  replay       publish ref-updated events for the current refs of a repo
  self-update  build, test, and install the tip of a branch of the-valley
  telemetry    read a valley host's diagnostics over ssh (observe grant)

A change is named by its 32-letter change id, its handle (shortest unique
prefix, at least 4 letters, or <repo>:<handle>), or its branch name.
Runs from any checkout; nix run .#valley bundles git, valley-go, attest, cue,
less, and natscli (self-update also needs nix). Judgment stays with the human:
nothing here writes main.

`valley --version` prints the package's version and commit (e.g. 0.1.0-97db597,
with -dirty for uncommitted changes, -unknown when nix knew no commit, or
unstamped when run straight from a checkout).
Run `valley help <verb>` (or `valley <verb> --help`) for a verb's flags and
rules. See docs/reference.md for the full CLI, ref, and schema reference.
EOF
}

help_naming() {
  cat <<'EOF'

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 that has landed as any version — 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, unless its active version was made on that landing, 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,
and rebase refuse a change whose record is not ready, naming its state,
and review offers neither [a]pprove nor [r]eject for a change that is not
ready when it shows it. approve and rebase read the record again just
before they act, and again before approve files or rebase pushes, and
refuse when the change is not ready. review reads the change again before
its [a]pprove or [r]eject acts. When the change has moved since review
showed it, returned to draft, withdrawn, given a new version or landed,
review says so in one line and moves on, without asking again. rebase also refuses when the change's
record has changed at all since it began, and approve when the head it
approves is not a version's. A name that read as a plain branch is
read again before approve files or rebase pushes. If it names a change by
then, rebase refuses, and approve files only while the change is ready at
the head it 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
that would bring a version of a change that is not ready, whatever the
request is named.
The integrator reads the records last just before it moves main, so a
change paused in that moment can still land at the head the operator
approved, and never at any other.
EOF
}

help_runtime() {
  cat <<'EOF'

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, changes, knot, plan and
self-update do. nix run .#valley bundles all of them. self-update also
needs nix. 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, rebase, knot and plan read,
and valley.selfUpdate.repo and .branch, which self-update reads; no batch
mode; and no state but the notes file, the handle cache pending and
changes write for completion, and self-update's record of what it
installed — the judgment stays with the human.
EOF
}

help_unready_withdraw_requests() {
  cat <<'EOF'
                   the integrator lands no request that would bring a
                   version 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. withdrawing voids the request: the
                   integrator deletes it on its next pass while the change
                   is still withdrawn. withdraw warns, since a ready before
                   then leaves the request standing: only a holder of the
                   approve grant (also accepted as request) may touch a
                   request ref, so the operator must drop it then.
EOF
}

help_pending() {
  cat <<'EOF'
usage: valley pending [--all] [--repo <name>] [--checks] [--drafts] [--branches] [--json] [-v] [--known-signers <file>] [--integrator-name <name>]

  pending [--all] [--repo <name>] [--checks] [--drafts] [--branches]
          [--json] [-v] [--known-signers <file>] [--integrator-name <name>]
                   list what waits on you and what is moving. one line
                   on main's state comes first for each project whose
                   policy declares follow checks: clear, clearing or
                   muddy. needs you holds the ready changes that wait on
                   an approval, one numbered row each in landing order:
                   oldest ready first, as the check worker builds them,
                   then by project and change id. a row gives the
                   handle and active version, its checks as passed out of
                   required (or how many are pending), and how long it
                   has been ready, with its title under it. a stack of
                   such changes is one row, its top's, saying `stack of
                   N`: approving the top lands every layer. moving holds
                   the ready changes that need no approval now, one line
                   each: ◐ approved, waiting on checks and the
                   integrator; ✗ a check failed, named; ✗ or ◇ a restack
                   holds it. older versions are never listed. a last line
                   counts the drafts and the branches no change is on.
                   lines fit the terminal, or 80 columns off one; titles
                   are cut short with …, names never. names are bold and
                   glyphs coloured on a terminal unless NO_COLOR is set.
                     --all        every project the serving host
                                  publishes, as one listing: each line
                                  names its project, and the rows of
                                  every project share one landing order
                                  (see valley help changes)
                     --repo NAME  that one project
                     --checks     add to each row the checks the policy
                                  requires of it, by cost, as checks
                                  derives them, and its full check state,
                                  naming the checks that failed and what
                                  they cost the host's check worker to
                                  build. with --json, give each pending
                                  change its checks object
                     --drafts     list the drafts in full, in place of
                                  their count
                     --branches   list the branches no change is on in
                                  full, in place of their count. each
                                  draft and branch is a block: its name
                                  with its head's age and author, its
                                  title, then the commits and the diff
                                  it adds to the nearest listed entry
                                  its head contains, or to main. a stack
                                  is its top, then every entry the top
                                  contains, at one indentation; an entry
                                  not on the one listed after it says
                                  `on <base>`
                     --json       print valley-pending/v1: the
                                  valley-changes/v1 shape, with the
                                  pending changes in changes, each
                                  marked approved or not, and the
                                  drafts in drafts
                     -v           follow each row with its block, its
                                  stack drawn in full, with what its
                                  head includes, `uncertain` when it may
                                  have landed without its evidence
                                  stored, and its full check state; and
                                  warn on stderr when a plan graph is
                                  missing or unreadable
                     --known-signers FILE, --integrator-name NAME
                                  what a transfer statement is verified
                                  with (see changes below)
                   reading the checks costs seconds for each project
                   with a ready change. needs the valley-go helper.
EOF
  help_runtime
}

help_changes() {
  cat <<'EOF'
usage: valley changes --json [--all] [--repo <name>] [--checks] [-v] [--known-signers <file>] [--integrator-name <name>]

  changes --json [--all] [--repo <name>] [--checks] [-v]
          [--known-signers <file>] [--integrator-name <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, the knots in
                   refs/the-valley/knots that link it
                   (valley:<project>/<change id>, active first), and
                   the branches no change is on. -v warns on stderr when a
                   plan graph is missing or unreadable. --checks adds
                   checks to the active version of each ready change that
                   has not landed: each check the policy requires of it,
                   passed, failed or pending by the note the integrator
                   would judge it by on origin, and other for a check the
                   host's worker does not run (docs/reference.md). each nix
                   check also gives its build time for this version, and
                   the median of its recent builds, from the host's
                   worker telemetry; when that cannot be read, those
                   fields are left out and stderr says why. it costs a
                   few seconds for each project with such a change.
                   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. attest verifies the statement with the
                   registry's known-signers file and the integrator's
                   signing name. each is taken from the first of these
                   that gives it: --known-signers FILE or
                   --integrator-name NAME; VALLEY_KNOWN_SIGNERS or
                   VALLEY_INTEGRATOR_SIGNER; what the serving host
                   publishes at refs/the-valley/signers in its instance
                   repository, read only when a statement needs
                   verifying. a file that does not read, or holds no key
                   under the name, is reported on stderr, and then no
                   statement is verified.
                   needs the valley-go helper.
EOF
  help_runtime
}

help_review() {
  cat <<'EOF'
usage: valley review [-v] [--build-here] <change>

  review [-v] [--build-here] <change>
                   page through the change's branch: its log and diff vs
                   origin/main, or a stack layer by layer (below). above
                   each change's diff, review shows every knot in the plan
                   graph that links the change, as `does oc-6335749 (open):
                   <title>` (valley-go does). a missing or unreadable graph
                   shows no knots; -v warns on stderr. before the prompt, a
                   ready change shows the state of its checks and what
                   they cost the host's check worker to build, as pending
                   --checks shows it: `checks: 21 passed in 9m10s (eval
                   24s); worker-e2e 431s, +100s against its recent 331s`.
                   review reads them while it shows the diff and never
                   waits for them: a line not read by the prompt is not
                   shown, unless VALLEY_REVIEW_CHECKS_WAIT=<seconds> says
                   how long to wait for it. checks that cannot be read show no line; -v
                   warns on stderr. the prompt is one header line, the
                   change and its state, `nqyw v3 · checks: 4 passed ·
                   behind main (integrator merges)`, then the keys it
                   takes; a change that can't be approved says why in the
                   header and is not offered [a]pprove. -v also passes -v
                   to approve. then choose:
                     [a]pprove    file an integration request for the
                                  head shown, as approve does (valley
                                  help approve). it reuses the evidence
                                  origin holds for the checks the
                                  composed policy requires of this
                                  change. when a required nix check has
                                  none, it files the request at once
                                  all the same, builds nothing, and
                                  names the check. when evidence is
                                  published, the integrator considers
                                  the request again; it may never be
                                  published. given
                                  --build-here, review's [a]pprove builds
                                  those nix checks here instead. it runs
                                  the command checks, and any nix check
                                  it builds, 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 (valley
                                  help checks), 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 origin refuses when
                                  this signer has already attested that
                                  tree: approve publishes a signer's
                                  evidence for a tree once (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 whenever a
                                  check is required, and
                                  VALLEY_ATTEST_KEY, the ed25519 key this
                                  host signs with, whenever a check runs
                                  here; VALLEY_ATTEST_NAME is the name it
                                  signs under, defaulting to this host's.
                     [v]iew full diff
                                  page the change's whole diff, with
                                  notes taken as below, and ask again
                     [r]eject     delete the remote branch (confirmed first)
                     [s]kip       do nothing
                   a change with a record is first set against its
                   approved version: the greatest version below the one
                   shown whose exact head an integration request or a
                   land, stale or reject outcome on origin names, under
                   c-<change id> or a branch name of the change that
                   nothing else maps to (valley-go compare). with none,
                   or an ambiguous one, review pages the whole diff. when
                   each version's diff from its merge base with main
                   changes the same files the same way (valley-delta-v1),
                   review prints `<change> v<n> at <head>: clean restack
                   of approved v<m> at <old head>.`, the two bases, and
                   the commits main landed between them, and pages
                   nothing. otherwise it pages `changed since approved
                   v<m>`, the files whose change differs, git
                   range-diff of the two versions, and the shown
                   version's diff of those files. a changed commit
                   message or author is shown either way. this is
                   information only: it files nothing and skips no check.
                   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 files the head shown, for a branch no record
                   is on too: it refuses, naming both heads, when the
                   branch on origin has moved off that head since.
                   [a]pprove is the only way a change reaches main from
                   here, and approve (valley help approve) is the same act
                   without the pager.
                   Nothing in this script writes the protected ref: the
                   integrator does, having judged the request.
                   a change behind main (one that does not fast-forward
                   from it) is asked the same prompt, under one line:
                     `<branch> is behind main; the integrator lands it
                     onto main as main stands (no rebase needed).`
                   the integrator applies the change's delta onto main as
                   it stands, and the host's restacker rebases ready
                   changes itself, so review asks nothing more of it.
                   while the restacker reports a conflict for the change,
                   the line says `<branch> conflicts with main; its owner
                   is resolving it.` instead. [a]pprove is still offered,
                   and the integrator decides whether the change applies.
                   to rebase a change of your own, use valley rebase.
                   a change whose record is not ready says so above its
                   diff, and again in place of the prompt, which then
                   offers only [v]iew full diff and [s]kip:
                     `<change> v<n> is a draft: its owner (<owner>) hasn't
                     marked it ready, so it can't be approved yet.`
                     `<change> is withdrawn: there is nothing to approve.`
                   a draft is often a change an agent is still working on.
                   [a]pprove would be refused. [r]eject records nothing
                   on the change: it would only delete a branch its owner
                   may still be working on.
                   before [a]pprove or [r]eject acts, review reads the
                   change again. when it moved while you read it, review
                   says what changed in one line, does nothing, and moves
                   on to the next change or ends:
                     `<change> changed while you were reviewing: it was
                     returned to draft (since <time>), so there is
                     nothing to approve now. It comes back when it is
                     ready again.`
                     `<change> changed while you were reviewing: it was
                     withdrawn (since <time>), so there is nothing to
                     approve.`
                     `<change> moved to v<n> while you were reviewing
                     (<why>) · review it again to approve it · [v]iew
                     what changed since v<m>, [s]kip?`
                     `<change> landed as v<n> while you were reviewing;
                     there is nothing left to approve.`
                   <time> is when the record last changed, in UTC.
                   a new version with the same changes and commits, such
                   as a restack the carry mode allows, keeps the answer:
                     `<change> moved to v<n> while you were reviewing
                     (a restack of v<m>; same changes) · your answer
                     about v<m> stands`
                   and [a]pprove files v<m>, the head shown.
                   a branch no record is on has no state, and is offered
                   the usual prompt.
                   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. range-diff gives no
                   line numbers, so on a changed version a note keeps its
                   file and line only in the shown version's diff at the
                   end of the page. each note is then appended to
                   $XDG_STATE_HOME/valley/notes/<branch>.md (default
                   ~/.local/state) and printed after the verdict. notes
                   survive a stack's [b]ase onto main. lines you change
                   or delete instead of inserting are ignored, with a
                   warning.
                   a change whose active version names no branch is
                   refused, since notes and [r]eject act on a branch;
                   approve files its head without one.
                   a stack is reviewed one layer at a time, bottom first.
                   a layer below the top that is approved, as pending
                   lists it, is named in the list and not paged: it asks
                   nothing of you. the top is always paged.
                   its layers are what pending lists under the change: the
                   changes not landed and the branches no record is on
                   that its head contains (valley-go stack). review first
                   lists them, warns of a lower layer that is a draft or
                   withdrawn, since the integrator lands nothing above it,
                   and says how the review goes: [n] through the layers,
                   and approving the top lands them all. a stack whose
                   bottom does not fast-forward from main is then asked,
                   before any layer is paged, under `<top> · stack of <n>
                   · behind main`:
                     [b]ase onto main
                                  rebase the whole stack onto origin/main,
                                  as rebase does (valley help rebase), then
                                  list it again and page the rebased layers,
                                  so the heads paged are the heads approved
                     [v]iew diff  page the top's whole diff against main
                     [s]kip       end the review; nothing done
                   a rebase that is refused or left unfinished says what
                   happened, and then only [v]iew diff and [s]kip are
                   offered.
                   it then shows each layer, headed `change <k> of <n>:
                   <name> on <below>`, as a change alone is shown: set
                   against its own change's approved version, or its log
                   and diff against the layer below it paged, with notes
                   kept under that layer's branch.
                   after each lower layer it asks, naming the layer and
                   its place, as in `two, 2 of 3:`:
                     [n]ext layer go on to the layer above; the usual
                                  answer
                     [a]pprove    approve that layer at the head shown,
                                  as review of it would. this lands it
                                  and every layer under it, which the
                                  prompt names (`one alone`, `one and
                                  two`, `the <k> up to <name>`), and
                                  ends the review
                     [v]iew full diff
                                  page that layer's log and diff against
                                  the layer below it, and ask again
                     [s]top       end the review; nothing done
                   after the top it asks, as in `three, 3 of 3:`:
                     [a]pprove all <n>
                                  approve the top at the head shown,
                                  which lands every layer
                     [v]iew full diff
                                  page the top's log and diff against
                                  the layer below it, and ask again
                     [r]eject <name>
                                  delete the top's branch (confirmed
                                  first)
                     [s]top       end the review; nothing done
                   only the top is offered [r]eject. when a layer's checks
                   fail, its prompt says approving needs a new head and
                   stops offering [a]pprove, as for any change. a layer
                   that is not ready says so as a change alone does, under
                   its heading and in its prompt. neither it nor any layer
                   above it is offered [a]pprove, since approving one would
                   land it: each prompt above it says `it would bring
                   <name>, change <k> of <n>, which is a draft` (or
                   withdrawn) in its place. a top that is not ready is not
                   offered [r]eject either. every layer's notes are printed
                   at the end.
EOF
  help_naming
  help_runtime
}

help_approve() {
  cat <<'EOF'
usage: valley approve [-v] [--head <sha>] [--build-here] <change>

  approve [-v] [--head <sha>] [--build-here] <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 (review's [a]pprove files the head it showed, and
                   refuses once the branch on origin has moved off it), 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.
                   approve first reads the evidence origin holds for that
                   head's tree, refs/the-valley/attestations/<tree>/*, byte
                   for byte. it judges each required nix check by the note
                   the integrator judges it by: the first, in ref order,
                   that attest verify accepts under the known-signers file
                   the host publishes. it reuses that note when it is pure
                   evidence for the check's name and flake attribute and
                   says it passed. VALLEY_KNOWN_SIGNERS, when set, must
                   accept it too: it can narrow what is reused, never widen
                   it. a required nix check whose judged note records a
                   failure refuses the approval, since the integrator
                   judges the check by that note. a command check is never
                   reused. a listing or a fetch of
                   origin's evidence that fails is refused, and nothing is
                   run.
                   a required nix check that origin holds no evidence for
                   does not stop the approval. approve files the request at
                   once, with the evidence origin holds, builds nothing,
                   and publishes no evidence for that check. required
                   command checks still run first, and a missing signing
                   key, a failed check, or a refused push still fails the
                   approval. approve says the approval is recorded and
                   how many checks it waits for. the integrator keeps the
                   request and considers it again when evidence is
                   published. landing still requires a clean apply and
                   acceptable evidence for every required check. an
                   enabled worker that serves the project attempts the nix
                   checks of a ready change's active version, but cannot
                   add checks to its own existing evidence ref for the
                   same tree, and a failed build publishes nothing. waiting
                   does not ensure the evidence will be published. no
                   worker builds a branch no record is on, or a version
                   that is not the active one, and approve says so and
                   offers --build-here. the
                   evidence of an approval that ran a command check
                   occupies this signer's ref for the tree, so use
                   --build-here on the initial approval.
                     --build-here build those nix checks on this
                                  machine instead, and publish their
                                  evidence with the request.
                   approve runs every command check, and every nix check
                   it builds, over a throwaway worktree of that head, signs
                   each result as an attestation, and publishes the new
                   evidence and the request ref to origin in ONE atomic
                   push. when every required check is reused, nothing
                   runs, no signing key is needed, and the push carries
                   the request alone.
                   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 (valley help
                   checks), 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. origin already holding this signer's
                   evidence for that tree, without a check that still has
                   to run, is refused before anything runs: approve
                   publishes a signer's evidence for a tree once, as a
                   ref of the new notes alone, and origin keeps every
                   note the ref holds (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 whenever a check is required,
                   and VALLEY_ATTEST_KEY, the ed25519 key this host signs
                   with, whenever a check has to run here;
                   VALLEY_ATTEST_NAME is the name it signs under,
                   defaulting to this host's. Nothing in this script writes
                   the protected ref: the integrator does, having judged
                   the request.
                   approve refuses, before any check runs, a head that does
                   not fast-forward from main and would bring a version of
                   another change that has not landed: a layer above the
                   bottom of a stale stack. the refusal names the command
                   that rebases the stack, valley rebase <change>. this is
                   the project's choice, not a rule the integrator needs:
                   approved as it is, the stack would land as one commit
                   recorded against this request alone, so the changes
                   under it would have no landing record of their own, and
                   the checks would run over a head that has to be rebased
                   anyway. a stale head with no change under it, such as
                   the bottom layer of a stack or a change alone, is
                   approved as it is, and the integrator merges it onto
                   main.
                   approve ends in one verdict line: the change, whether
                   it was approved, and what happens next, with one
                   indented line under it only when you must act:
                     ✓ nqyw v3  approved · checks passed · landing on main
                     ◐ nqyw v3  approved · lands when 3 checks pass (1/4 passed)
                     ◇ nqyw v3  approved · waiting for 2 checks (no worker building)
                       run: valley approve --build-here nqyw
                     ⊘ nqyw v3  not approved · change is a draft
                       run: valley ready --change <id> <branch>
                   a refusal goes to stderr. checks built here show one
                   line of progress, and a failed check's log. the glyphs
                   are in colour on a terminal unless NO_COLOR is set.
                     -v, --verbose  also print what approve read and
                                  published: the checks it reuses and who
                                  signed them, the tree's digest, the
                                  evidence and request refs, and the
                                  checks' own output and timings.
                   approve times each required check it runs, and
                   appends one JSON line per check to the timing log,
                   $XDG_STATE_HOME/valley/timings.jsonl (default
                   ~/.local/state/valley/timings.jsonl). the log stays on
                   this machine and is not evidence; a log that cannot be
                   written is a warning, and approving goes on.
EOF
  help_naming
  help_runtime
}

help_rebase() {
  cat <<'EOF'
usage: valley rebase [--known-signers <file>] [--integrator-name <name>] <change>

  rebase [--known-signers <file>] [--integrator-name <name>] <change>
                   rebase the change's whole stack onto origin/main, as
                   review's [b]ase onto main does: the layers valley-go stack
                   lists under the change, and the change itself. in a
                   throwaway worktree, bottom first, each layer's own commits
                   go onto the rebased layer below it, and the bottom's onto
                   origin/main, so each layer keeps its own diff. commits
                   under the bottom that a lower change landed through the
                   integrator drop out, since main holds them; that landing
                   is read as changes reads it, with the signers its two
                   flags, VALLEY_KNOWN_SIGNERS and VALLEY_INTEGRATOR_SIGNER,
                   or the host's publication give. one atomic
                   push then moves every layer's branch, each leased on the
                   tip read: every branch moves, or none does. last, bottom
                   first, each change gains its 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.
                   it refuses, with nothing changed, a stack holding a
                   change that is not ready, records no branch, or whose
                   branch is missing on origin or is not at its recorded
                   head; a plain branch that is the branch of a change not
                   in the stack; two layers on one branch; a merge among the
                   commits to be rebased, or a version head of a change
                   that is not ready or not in the stack, since a rebase
                   gives each commit a new id; and a stack holding a change
                   while git config valley.principal names no one. a
                   conflict in any layer pushes nothing, records nothing
                   and names the layer.
                   a change alone prints its new head. a
                   stack prints a manifest: one line for each layer, with
                   its old and new head, whether its branch was pushed, and
                   whether a version was added. then, for each change left
                   unfinished, the valley ready command that finishes it,
                   and the exit status is non-zero. rebasing again refuses
                   a change whose branch holds a head no version records,
                   and prints the same command. last, it names each ready
                   change or branch outside the stack that is left on an
                   old head of a layer, such as a second stack on a lower
                   layer, with the rebase that moves it; it does not move
                   it. rebase does not re-review the result. a stack that
                   already fast-forwards from main is left as it is.
EOF
  help_naming
  help_runtime
}

help_status() {
  cat <<'EOF'
usage: valley status [--json] [-v] [--known-signers <file>] [--integrator-name <name>] <change>

  status [--json] [-v] [--known-signers <file>] [--integrator-name <name>]
         <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 change that landed
                   as an older version is read at that version's head. 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), with the knots
                                  in the plan graph that link the change.
                                  an error prints no object: it goes to
                                  stderr and the exit status is non-zero.
                     -v           with --json, warn on stderr when the plan
                                  graph is missing or unreadable
                     --known-signers FILE, --integrator-name NAME
                                  what a transfer statement is verified
                                  with, as changes reads them
                   needs the valley-go helper.
EOF
  help_naming
  help_runtime
}

help_ready() {
  cat <<'EOF'
usage: valley ready [--head <sha>] [--change <id>] [--if-active <sha>] [--stamp] [<branch>]

  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.
                   `app 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, the operator, or a restack holder while the
                   change is ready.
                   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 that would
                   bring a version of a change that is not ready.
                   needs the valley-go helper.
EOF
  help_naming
  help_runtime
}

help_unready() {
  cat <<'EOF'
usage: valley unready <change>

  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.
                   `app nxvp v2 draft`. needs the valley-go helper.
EOF
  help_unready_withdraw_requests
  help_naming
  help_runtime
}

help_withdraw() {
  cat <<'EOF'
usage: valley withdraw <change>

  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. `app nxvp v2 withdrawn`.
                   needs the valley-go helper.
EOF
  help_unready_withdraw_requests
  help_naming
  help_runtime
}

help_knot() {
  cat <<'EOF'
usage: valley knot <verb> [args]

  knot <verb> [args]
                   read and write the project's plan graph: knots, at
                   refs/the-valley/knots on origin. a knot is an outcome,
                   a bug, an idea or a question; `knot schema` prints the
                   types, their statuses, active and terminal, the fields
                   and the edges. a write is one commit on the ref, made
                   without a checkout and pushed with a lease on the tip
                   it was made on; no review is involved. a write that
                   loses the lease is made again on the new tip, up to 5
                   tries. every verb takes --project NAME, another
                   project on the same host, and --json. exit status 3
                   is a conflict. needs the valley-go helper, and
                   git config valley.principal for every write.
                     new <type> <title> [--parent ID] [--blocked-by ID]...
                         [--owner P] [--target PROJECT] [--body -]
                                  make a knot. its id is the type's prefix
                                  and 7 hex digits of the sha-256 of the
                                  title's slug.
                     show <id> [--at COMMIT] [--json]
                                  its fields, body and comments, each
                                  comment with its id, and the edges both
                                  ways. --at shows the knot at a commit of
                                  the graph; claim age uses the current
                                  clock, and other projects' knots use
                                  their current tips.
                     log <id> [--json]
                                  every commit of the graph that touched
                                  the knot or its comments, newest first:
                                  time, committer, operation, and the
                                  files it added, changed or deleted
                     list [--type T] [--status S] [--owner P] [--ready]
                                  every knot. --status takes a status,
                                  active or terminal. --ready lists the
                                  active, unclaimed knots whose blockers
                                  are all terminal.
                     set <id> <field>=<value>... [--if <field>=<value>]...
                         [--force]
                                  change status, title, source, owner,
                                  target or graduated_into. a field that
                                  another write changed meanwhile is a
                                  conflict unless --force. --if requires
                                  a field to hold a value first.
                     link <id> (--blocked-by ID | --parent ID | --change X)...
                     unlink <id> (--blocked-by ID | --parent ID | --change X)...
                                  add or drop an edge. a change is
                                  valley:<project>/<change id> or a github
                                  pull request url. outcomes and bugs link
                                  the changes that do the work, and a
                                  question links the change that records
                                  its answer in the source.
                     edit <id> --body -
                                  replace the body with stdin
                     comment <id> (-m TEXT | --body -) [--edit COMMENT-ID]
                                  add a comment. --edit replaces the body
                                  of the comment with that id; its author
                                  and file stay, and it records who edited
                                  it and when. only the comment's author
                                  or a holder of the approve grant may
                                  edit it. a comment that another edit
                                  changed meanwhile is a conflict.
                                  comments are never deleted; log and
                                  show --at read every earlier text.
                     claim <id> --run RUN
                                  claim an active outcome or bug for a
                                  run; an open outcome becomes
                                  in-progress. a knot claimed already is
                                  a conflict.
                     unclaim <id>
                                  release the claim. a claim that
                                  changes before the release lands is
                                  a conflict.
                     schema [--json]
                                  print the model
EOF
  help_runtime
}

help_plan() {
  cat <<'EOF'
usage: valley plan [--project NAME | --all] [--owner P] [--json] [--known-signers <file>] [--integrator-name <name>]

  plan [--project NAME | --all] [--owner P] [--json]
       [--known-signers <file>] [--integrator-name <name>]
                   show the project's plan graph as a tree, to see where
                   things stand. the roots are the outcomes with no
                   parent, the milestones, each with its progress: its
                   descendants that are terminal and not abandoned, out
                   of those not abandoned, as a count and a bar. under
                   each come its children, indented, in the order they
                   were created, then by title. each knot has a glyph for
                   its state (○ ready, ◐ in progress, ⊘ blocked, ◇
                   active, ✓ done, ✗ abandoned), its id and title, and,
                   while active, its claim and the claim's age (marked
                   stale past a day), its owner, and what blocks it. a
                   blocker that ended abandoned, discarded, superseded or
                   dropped clears the knot, and is marked with how it
                   ended. a reference to another project's knot,
                   <project>:<id>, is marked dangling when that
                   project's graph cannot be read or holds no such knot.
                   a root whose descendants are all terminal is one
                   line. three sections follow. waiting on you: the
                   active outcomes and bugs and the open questions the
                   operator owns, then the changes ready for
                   approval, as pending lists them. in flight: the
                   claimed knots, oldest claim first. open residuals:
                   the open bugs, under their parent. the operator is
                   git config valley.principal, or --owner. lines fit
                   the terminal as pending's do; glyphs are coloured on
                   a terminal unless NO_COLOR is set.
                     --project NAME  another project on the same host
                     --all        every project the serving host
                                  publishes, each under its name, as
                                  pending --all reads them. a project
                                  that cannot be read is reported in
                                  its own section
                     --owner P    read P as the operator
                     --json       print valley-plan/v1: every knot with
                                  what the graph derives of it, and the
                                  three sections (docs/architecture.md)
                     --known-signers FILE, --integrator-name NAME
                                  what a transfer statement is verified
                                  with, for the changes ready for
                                  approval, as changes reads them
                   needs the valley-go helper.
EOF
  help_runtime
}

help_checks() {
  cat <<'EOF'
usage: valley checks [--schema FILE] [--instance DIR] [--project DIR] [--names [--cost COST]] [<base> [<head>]]

  checks [<base> [<head>]]
                   print the check names the composed verification policy
                   (dcr-f41f718) requires of the change between two
                   commits, which class made each one required, and the
                   change's carry mode: how far an approval of it carries
                   across a rebase, the strictest of exact, same-class and
                   same-paths among the classes it matched. 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.
                   a class's globs match bytes, in the C locale whatever
                   yours is: `?` is one byte, so `?.md` does not match
                   é.md, whose é is two.
                   after the report, two lines group the required checks
                   by the cost the policy declares, `quick` or `slow`. a
                   slow check takes minutes or needs special hardware. the
                   cost changes nothing required: approving runs every
                   required check whatever its cost, and the integrator
                   requires evidence for every one.
                     --names          print only the required check names,
                                      one per line
                     --cost COST      with --names, only the quick or
                                      the slow ones, e.g.
                                      `valley checks --names --cost slow`
EOF
  help_runtime
}

help_tail() {
  cat <<'EOF'
usage: valley tail [subject]

  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)
EOF
  help_runtime
}

help_replay() {
  cat <<'EOF'
usage: valley replay [dir]

  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
EOF
  help_runtime
}

help_telemetry() {
  cat <<'EOF'
usage: valley telemetry [--remote <remote>] [--json] <operation> [flags]

  sources                 every source the host declares, and its state:
                          disabled, unavailable, failed, stale, active or
                          idle, with its units, its records and how far its
                          journal reaches
  snapshot                sources, with each producer's exported state and
                          its open and latest runs
  read [--source <name>] [--since <cursor>] [--limit <n>] [--logs]
                          records after the cursor (default: the newest
                          --limit, 200, at most 1000); a source's systemd
                          lifecycle from the journal; with --logs, its own
                          output and the tail of its build logs, marked
                          untrusted
  follow [--source <name>] [--since <cursor>] [--seconds <n>] [--logs]
                          records as they are stored, and with --logs build
                          output as it is written, for --seconds (default
                          60, at most 300); ends with a cursor to resume from
  flush                   send this workstation's spooled records now

Reading needs a key whose principal holds the host's observe grant. The
remote is the checkout's valley.telemetry.remote, else origin, or the one
--remote names (a remote, an ssh URL, or user@host:path); its URL is read
and never run. --json prints the valley-telemetry/v1 answer lines as they
come. A gap, a cut-short answer or an error is said; an answer that does
not end exits 1.

With `git config valley.telemetry true`, every valley command records a
command record: its verb (and knot's or telemetry's subverb), the names of
the flags it was given, its project, its exit status and its wall time,
and for pending and status the milliseconds and processes each phase took.
It never records an argument's value, a path, a title or a body. Every
approval attempt, from approve or from review, also records its steps and
its checks' progress. Records go to an owner-only spool for the
destination the checkout's telemetry remote names, under
$XDG_STATE_HOME/valley/telemetry/spools. A background flusher sends each
spool to its own destination, with the report grant; flush does the same
now, and --remote limits it to that remote's spool. Telemetry never fails
or holds up a command, and changes nothing it prints.
EOF
}

help_self_update() {
  if command -v valley-go > /dev/null 2>&1; then
    valley-go self-update --help
    printf '\n'
  else
    cat <<'EOF'
usage: valley self-update [-v] [--retry | --rollback | --pin | --unpin]
                          [--repo <url>] [--branch <name>]

EOF
  fi
  cat <<'EOF'
  self-update [-v] [--retry | --rollback | --pin | --unpin]
              [--repo <url>] [--branch <name>]
                   install the tip of a branch of the-valley into your
                   default nix profile, in place of its valley element,
                   once that exact commit builds and passes a smoke test.
                   a commit that fails is skipped until the branch moves,
                   or until --retry. it is off until --repo or
                   git config valley.selfUpdate.repo names the
                   repository; the branch is valley.selfUpdate.branch,
                   or main. --rollback reinstalls the previous build, and
                   --pin and --unpin freeze and release the install.
                   `valley-go self-update --help` gives every step. needs
                   the valley-go helper and nix.

  --version        print this valley's version: the package's version and
                   the commit it was built from, e.g. 0.1.0-97db597, with
                   -dirty after it for a tree with uncommitted changes and
                   -unknown in its place when nix knew no commit. run
                   straight from a checkout, it says it is unstamped.
EOF
  help_runtime
}

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

# ref_oid <ref>: the object ID that ref, a full ref name, holds here, read
# by that exact name with show-ref. 1 no such ref, 2 a read that failed.
#
# git rev-parse, and every git command given a ref name, does not stop at
# the name it is given. For a missing refs/remotes/origin/main it goes on
# to try other names, refs/tags/refs/remotes/origin/main and
# refs/heads/refs/remotes/origin/main among them, and a fetch can bring the
# first from origin. So a ref is read here once, and what it held is read
# through the object ID from then on.
ref_oid() {
  local rc
  git show-ref --exists --end-of-options "$1" 2> /dev/null && rc=0 || rc=$?
  case "$rc" in
    0) git show-ref --verify --hash --end-of-options "$1" || return 2 ;;
    2) return 1 ;;
    *) return 2 ;;
  esac
}

# 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. 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.
#
# The configured diff pager stays the renderer, run once as a filter into a
# sibling file that less pages. v runs LESSEDIT, which opens the editor on
# the raw buffer, not the rendering, and renders it again when the editor
# exits, so the view less reopens shows the notes in place. The editor is
# the one less's %E names: VISUAL, then EDITOR, then vi, each a shell
# command line. Paths reach LESSEDIT through the environment, since it is a
# prompt string in which % ? . : and \ are special.
#
# What this costs is the line number. v opens the editor at +%lm, a line
# of the rendered view, so a filter that restructures the diff — delta's
# default rendering does — opens it 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" shown="${1%.diff}.shown" 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
  }
  sh -c "$pager" < "$file" > "$shown"
  # -R because the filter's color is the whole point of running it. No
  # LESSOPEN, since the filter has run and less answers v on a file read
  # through one with a warning, then runs the editor on whatever key comes
  # next, q included; and so no LESSCLOSE.
  # shellcheck disable=SC2016 # expanded by the shells LESSEDIT starts
  VALLEY_PAGE_RAW="$file" VALLEY_PAGE_SHOWN="$shown" VALLEY_PAGE_RENDER="$pager" \
    VALLEY_PAGE_EDIT='eval "${VISUAL:-${EDITOR:-vi}} \"\$@\" \"\$VALLEY_PAGE_RAW\""
      sh -c "$VALLEY_PAGE_RENDER" < "$VALLEY_PAGE_RAW" > "$VALLEY_PAGE_SHOWN"' \
    LESSEDIT='sh -c "$VALLEY_PAGE_EDIT" sh ?lm+%lm.' \
    env -u LESSOPEN -u LESSCLOSE less -R -- "$shown"
}

# 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 --checks, 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" VALLEY_TELEMETRY_SINCE="$TEL_T0" VALLEY_TELEMETRY_VERSION="$VALLEY_STAMP" \
    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)
      # The change may have moved while the confirmation waited: say so,
      # and delete nothing.
      ! moved || return 0
      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 onto main
# 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[@]}"
}

# ----------------------------------------------------------------------
# review sets the version it shows of a change against the change's
# approved version: the greatest version below it whose head a request or
# an outcome on origin names (valley-go compare, status/compare.go). The
# logic is valley-go's, and this script prints what it says:
#
#   - none: there is no approved version to compare with, so review pages
#     the whole diff, as for any change. Any note valley-go gives, such as
#     an approved version it could not compare, heads the page.
#   - clean: the file delta is the approved version's. review prints that
#     in a few lines, with the landings between the two bases, and pages
#     nothing.
#   - changed: review pages the files whose change differs, the
#     range-diff between the two versions, and the shown version's diff
#     of those files. range-diff's hunks carry no line numbers, so a note
#     taken beside them is unanchored. That last diff is in git's ordinary
#     form, so a note taken there keeps its file and line (anchor_buffer).
#
# A changed commit message or author is in valley-go's text either way.
# [v]iew full diff pages the whole diff at every prompt. The comparison
# files no request and skips no check: [a]pprove is the same act whatever
# it says.
#
# compare_shown <change ID> <version> <head>: compare the version shown,
# against main's tip as the fetch left it. Leaves none, clean or changed
# in COMPARE_KIND, and the text to show in $REVIEW_TMP/compare. A plain
# branch is none, and so is a comparison valley-go could not make, with a
# warning.
COMPARE_KIND=none
compare_shown() {
  local out="$REVIEW_TMP/compare.out" tip
  COMPARE_KIND=none
  : > "$REVIEW_TMP/compare"
  [ -n "$1" ] || return 0
  if ! tip="$(ref_oid refs/remotes/origin/main)" \
    || ! valley-go compare --tip "$tip" "$1" "$2" "$3" > "$out"; then
    printf 'valley: warning: could not compare v%s of change %s with its approved version; reviewing it in full\n' \
      "$2" "$1" >&2
    return 0
  fi
  IFS= read -r COMPARE_KIND < "$out" || COMPARE_KIND=""
  case "$COMPARE_KIND" in
    none | clean | changed) tail -n +2 "$out" > "$REVIEW_TMP/compare" ;;
    *)
      printf 'valley: warning: valley-go compare answered %s, which this script does not read; reviewing it in full\n' \
        "$COMPARE_KIND" >&2
      COMPARE_KIND=none
      ;;
  esac
}

# show_compared <notes key> <head> <heading> <knots> <writer> [<arg>…]:
# show what compare_shown found, under the heading when there is one. A
# clean restack is printed, and nothing is paged. A changed version pages
# the comparison. Otherwise the writer writes the whole diff, and it is
# paged. Notes taken in a page are kept under the notes key, against the
# head.
#
# Knots follow the heading when there is one. Otherwise they follow the
# first line of the comparison or full diff, which names the change.
show_compared() {
  local key="$1" sha heading="$3" knots="$4"
  sha="$(git rev-parse --short "$2")"
  shift 4
  {
    if [ -n "$heading" ]; then
      printf '%s\n' "$heading"
      [ -z "$knots" ] || printf '%s\n' "$knots"
      cat "$REVIEW_TMP/compare"
      [ "$COMPARE_KIND" != none ] || "$@"
    else
      {
        cat "$REVIEW_TMP/compare"
        [ "$COMPARE_KIND" != none ] || "$@"
      } | under_first "$knots"
    fi
  } > "$REVIEW_TMP/review.diff"
  if [ "$COMPARE_KIND" = clean ]; then
    cat "$REVIEW_TMP/review.diff"
    cleanup_review_tmp
  else
    page_buffer "$key" "$sha"
  fi
}

# under_first <lines>: copy stdin, inserting <lines> after the first line.
under_first() {
  local first
  IFS= read -r first || [ -n "$first" ] || return 0
  printf '%s\n' "$first"
  [ -z "$1" ] || printf '%s\n' "$1"
  cat
}

# DOES caches the output of `valley-go does` for the review (status/does.go):
# one `<change ID>\tdoes <knot ID> (<status>): <title>` line per knot.
# The checks line takes seconds to read: it reads the policy and the host's
# telemetry. So read_does starts `valley-go checkline`
# (status/versionchecks.go) in the background, and it writes one
# `<change ID>\tchecks: …` line for each ready change into REVIEW_CHECKS_TMP: the
# state of its checks and what they cost the host's check worker to build,
# as pending --checks shows it. The diff is shown without waiting for it.
# checks_line prints a change's line when the read has finished, just
# before the prompt, and prints nothing when it has not (it waits at most
# VALLEY_REVIEW_CHECKS_WAIT seconds, 0 unless set). REVIEW_CHECKS_PID is the
# background read, REVIEW_CHECKS_SHOWN the change IDs whose line is not shown
# again, REVIEW_CHECKS_IDS the changes it reads, and
# REVIEW_CHECKS_VERBOSE whether to pass on what the read said on stderr.
DOES=""
REVIEW_CHECKS_TMP=""
REVIEW_CHECKS_PID=""
REVIEW_CHECKS_SHOWN=" "
REVIEW_CHECKS_VERBOSE=""
REVIEW_CHECKS_IDS=()

# read_does [-v]: read the plan graph once for every change in the review,
# and start reading their checks. A missing or unreadable graph leaves DOES
# empty; -v warns on stderr.
read_does() {
  local ids=() k
  DOES=""
  if [ "${#L_NAME[@]}" -gt 1 ]; then
    for ((k = 0; k < ${#L_ID[@]}; k++)); do
      [ -z "${L_ID[k]}" ] || ids+=("${L_ID[k]}")
    done
  elif [ -n "$CHANGE_ID" ]; then
    ids=("$CHANGE_ID")
  fi
  [ "${#ids[@]}" -gt 0 ] || return 0
  DOES="$(valley-go does "$@" "${ids[@]}")" || DOES=""
  REVIEW_CHECKS_IDS=("${ids[@]}")
  REVIEW_CHECKS_VERBOSE="${1:-}"
  start_checks_read
}

# start_checks_read: read the checks of REVIEW_CHECKS_IDS in the background,
# in place of any read already started.
start_checks_read() {
  cleanup_checks_tmp
  REVIEW_CHECKS_TMP="$(mktemp -d)"
  REVIEW_CHECKS_SHOWN=" "
  valley-go checkline "${REVIEW_CHECKS_IDS[@]}" > "$REVIEW_CHECKS_TMP/out" 2> "$REVIEW_CHECKS_TMP/err" &
  REVIEW_CHECKS_PID=$!
}

# checks_line <change ID>: print the `checks: …` line of one change, once,
# if the background read has finished and gave it one. It never waits.
checks_line() {
  local line
  [ -n "$REVIEW_CHECKS_PID" ] && [ -n "$1" ] || return 0
  case "$REVIEW_CHECKS_SHOWN" in *" $1 "*) return 0 ;; esac
  # Normally the read has had the whole time the diff was read in. A host
  # that wants the line at the prompt can have review wait for it.
  local waited=0 limit="${VALLEY_REVIEW_CHECKS_WAIT:-0}"
  case "$limit" in '' | *[!0-9]*) limit=0 ;; esac
  while kill -0 "$REVIEW_CHECKS_PID" 2> /dev/null; do
    [ "$waited" -lt "$((limit * 10))" ] || return 0
    sleep 0.1
    waited=$((waited + 1))
  done
  if [ -n "$REVIEW_CHECKS_VERBOSE" ] && [ -s "$REVIEW_CHECKS_TMP/err" ]; then
    cat "$REVIEW_CHECKS_TMP/err" >&2
    : > "$REVIEW_CHECKS_TMP/err"
  fi
  while IFS= read -r line; do
    if [ "${line%%$'\t'*}" = "$1" ]; then
      printf '%s\n' "${line#*$'\t'}"
      REVIEW_CHECKS_SHOWN+="$1 "
    fi
  done < "$REVIEW_CHECKS_TMP/out"
}

# cleanup_checks_tmp: stop the background read of the checks, if it still
# runs, and remove what it wrote.
cleanup_checks_tmp() {
  if [ -n "$REVIEW_CHECKS_PID" ]; then
    kill "$REVIEW_CHECKS_PID" 2> /dev/null || true
    REVIEW_CHECKS_PID=""
  fi
  [ -z "$REVIEW_CHECKS_TMP" ] || rm -rf "$REVIEW_CHECKS_TMP"
  REVIEW_CHECKS_TMP=""
}

# does_of <change ID>: print the `does ...` lines for one change from DOES.
does_of() {
  local line
  [ -n "$1" ] || return 0
  while IFS= read -r line; do
    [ "${line%%$'\t'*}" != "$1" ] || printf '%s\n' "${line#*$'\t'}"
  done <<< "$DOES"
}

# full_diff <branch> <head>: the whole diff of a change alone: its log
# and its diff against origin/main. main is read by its exact name, since
# git would take a tag named origin/main for it.
full_diff() {
  local sha tip
  sha="$(git rev-parse --short "$2")"
  tip="$(ref_oid refs/remotes/origin/main)" || return 1
  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" "$1"
  else
    printf 'branch %s, log against origin/main:\n\n' "$1"
  fi
  git --no-pager log --oneline "$tip..$2"
  printf '\n'
  git --no-pager diff "$tip...$2"
}

# show_review <branch>: show a change alone. A change that is not ready
# says so first, before anything else shown of it (shown_not_ready). That
# notice becomes the heading, so the change's knots follow it.
show_review() {
  local branch="$1" head held
  head="$(change_head "$branch")"
  # [a]pprove approves exactly the head shown here (bind_review).
  [ -n "$CHANGE_ID" ] || APPROVE_HEAD="$head"
  held="$(shown_not_ready)" || held=""
  REVIEW_TMP="$(mktemp -d)"
  compare_shown "$CHANGE_ID" "$CHANGE_VERSION" "$head"
  show_compared "$branch" "$head" "$held" "$(does_of "$CHANGE_ID")" full_diff "$branch" "$head"
  REVIEW_CHECKS="$(checks_line "$CHANGE_ID")"
}

# view_full <branch>: [v]iew full diff for a change alone. It pages the
# change's whole diff, and keeps the notes taken in it.
view_full() {
  local head
  head="$(change_head "$1")"
  REVIEW_TMP="$(mktemp -d)"
  full_diff "$1" "$head" > "$REVIEW_TMP/review.diff"
  page_buffer "$1" "$(git rev-parse --short "$head")"
}

# page_buffer <branch> <sha>: page the buffer written to REVIEW_TMP, and
# keep the notes taken in it under the branch, against the commit shown.
page_buffer() {
  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 "$1" "$2"
  cleanup_review_tmp
}

# Everything review and approve leave outside the repository: approve's
# throwaway worktree, 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. The rebase's
# worktree is valley-go's, which removes it itself.
cleanup_scratch() {
  local status=$?
  # An approval attempt still open when the session exits was cut short:
  # by a signal, or by a step that ended the session.
  if [ -n "$TEL_RUN" ]; then tel_end interrupted; fi
  cleanup_approve_wt
  cleanup_policy_tmp
  cleanup_instance_tmp
  cleanup_project_tmp
  cleanup_review_tmp
  cleanup_checks_tmp
  tel_command "$status"
}

# A stack's [b]ase onto main and the rebase verb are one piece of code,
# valley-go rebase (status/rebase.go). It rebases the change's whole
# stack in a throwaway worktree of its own — the user's checkout is never
# touched — pushes
# every layer's branch in one atomic push, leased on the tips it read, and
# adds each change's rebased head to its record as a new version. A
# change alone prints what rebase always has; a stack prints a manifest
# of what became of each layer. The judgment on the rebased diff stays
# with the human, back at the review prompt or in whatever front end ran
# the rebase verb.
#
# rebase_shown <head>: [b]ase onto main for the stack under review, while
# its top is still at <head>, the head review showed of it.
rebase_shown() {
  valley-go rebase --head "$1" "${CHANGE_ID:-$CHANGE_NAME}" || return
  # What the checks read was for the heads before the rebase.
  [ -z "$REVIEW_CHECKS_PID" ] || start_checks_read
}

# ----------------------------------------------------------------------
# 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
# a rebase 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=""
# The checks line review read for the change it shows (checks_line), for
# the header of its prompt.
REVIEW_CHECKS=""
# Set by --build-here, on approve and on review: approve builds the
# required nix checks that origin holds no evidence for, on this machine.
# Without it, approve files the request without their evidence, and the
# host's check worker publishes it (approve_attempt).
BUILD_HERE=""
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
}

# Set by -v, on approve and on review: approve prints what it read and
# published, the refs, the evidence and who signed it, the tree's digest
# and the policy, above its verdict, and lets the checks' and coverage's
# own output through.
VERBOSE=""

# declined <obstruction> [--run <command> | --see <command> | --then <text>]:
# approve's refusal, as valley-go verdict prints it (status/verdict.go):
# what stops the approval on one line on stderr, and what to do about it
# on a second. A change is named by its handle and the version being
# approved, a plain branch by its name. Fails, so a caller can return it.
declined() {
  local why="$1" version=""
  shift
  [ -z "$CHANGE_ID" ] || version="${APPROVE_VERSION:-$CHANGE_VERSION}"
  valley-go verdict refused --name "${CHANGE_HANDLE:-$CHANGE_BRANCH}" \
    ${version:+--version "$version"} --why "$why" "$@"
  return 1
}

# verdict_name: the change as approve's lines name it, for the commands
# they offer: its handle, or a plain branch's name, quoted for a shell.
verdict_name() {
  printf '%q' "${CHANGE_HANDLE:-$CHANGE_BRANCH}"
}

# 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.
# ls-remote matches a pattern against the tail of a ref name, so with the
# ref absent a pushed refs/heads/<ref> would match it. Only the line
# naming the ref itself is read.
remote_ref() {
  local out
  out="$(git ls-remote origin "$1" 2>/dev/null)" || return 1
  printf '%s\n' "$out" | awk -v r="$1" '$2 == r { print $1 }'
}

# push_lookalike <ref>...: a ref origin holds whose name ends in one of
# these, other than the ref itself, printed, or nothing. git push matches
# a destination as rev-parse matches a name. With <ref> missing on origin,
# a push to <ref> writes refs/heads/<ref> instead, and with both there it
# is refused as ambiguous. So no push to these refs is made while origin
# holds such a ref. Fails for a read that did not happen.
push_lookalike() {
  local out ref
  local -a patterns=()
  for ref in "$@"; do patterns+=("$ref" "$ref/HEAD"); done
  out="$(git ls-remote origin "${patterns[@]}" 2>/dev/null)" || return 1
  printf '%s\n' "$out" | awk -v refs="$*" '
    BEGIN { n = split(refs, r, " "); for (i = 1; i <= n; i++) exact[r[i]] = 1 }
    $2 != "" && !($2 in exact) { print $2; exit }'
}

# Where the checks this run signed are stored, for every failure that
# happens after they have run, with -v. One stanza, so no failure path
# invents its own wording. Called with no refs it says nothing.
report_local_evidence() {
  [ "$#" -gt 0 ] && [ -n "$VERBOSE" ] || 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. approve pushes a ref of its own notes
# alone, and origin takes an existing one only with every note it holds
# kept, 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: the request was
# consumed, or another approval filed or moved it. Reading the ref again
# is what tells them apart. Anything the lease is not responsible for, or
# a read that does not happen, 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")" || [ "$now" = "$pending" ]; then
    declined "origin refused the push"
  elif [ -z "$now" ]; then
    declined "the pending request was consumed meanwhile" --see "valley status $(verdict_name)"
  else
    declined "another approval filed $(git rev-parse --short "$now") ($(subject_of "$now")) meanwhile" \
      --run "valley approve $(verdict_name)"
  fi
  return 0
}

# 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.
# Workstation telemetry (valley help telemetry). With valley.telemetry set
# to true in git's configuration, each approval attempt is a run of its
# own: approve records its steps, and attest the progress of the checks it
# runs, in the spool of the destination the checkout's telemetry remote
# names when the attempt starts. One flusher per session, in the
# background, sends every spool to its own destination while the session
# runs and once after it ends. A record is never evidence, and nothing
# reads one to decide anything. Every step is best effort: a record that
# cannot be stored or sent costs that record and nothing else, and
# approve's outcome never depends on it.
TEL_RUN="" TEL_SPOOL="" TEL_PROJECT="" TEL_BEGAN="" TEL_EXE="" TEL_FLUSHER=""
TEL_CTX=()

# tel_begin: start an approval attempt's run, when telemetry is on.
tel_begin() {
  TEL_RUN="" TEL_SPOOL="" TEL_PROJECT="" TEL_CTX=()
  [ "$(git config --get --bool valley.telemetry 2> /dev/null || true)" = true ] || return 0
  command -v valley-go > /dev/null 2>&1 || return 0
  local started rest
  if ! started="$(valley-go telemetry start 2>&1)"; then
    printf 'valley: telemetry: %s\n' "${started#valley: }" >&2
    return 0
  fi
  TEL_RUN="${started%%$'\t'*}" rest="${started#*$'\t'}"
  TEL_SPOOL="${rest%%$'\t'*}" TEL_PROJECT="${rest#*$'\t'}"
  TEL_BEGAN="${EPOCHREALTIME/[.,]/}"
  [ -n "$TEL_EXE" ] || TEL_EXE="$(readlink -f "${BASH_SOURCE[0]}" 2> /dev/null || true)"
  if [ -z "$TEL_FLUSHER" ]; then
    TEL_FLUSHER=started
    (valley-go telemetry flush --watch "$$" > /dev/null 2>&1 &)
  fi
}

# tel <type> [emit flags…]: record one step of this attempt. elapsed_ms
# is this machine's wall clock since the attempt began.
tel() {
  [ -n "$TEL_RUN" ] || return 0
  local type="$1"
  shift
  valley-go telemetry emit --spool "$TEL_SPOOL" --type "$type" --run "$TEL_RUN" \
    --producer-version "${VALLEY_STAMP:-unstamped}" --producer-exe "$TEL_EXE" \
    --number "elapsed_ms=$(((${EPOCHREALTIME/[.,]/} - TEL_BEGAN) / 1000))" \
    --project "$TEL_PROJECT" ${TEL_CTX[@]+"${TEL_CTX[@]}"} "$@" > /dev/null 2>&1 || true
}

# tel_end <result>: end the attempt's run, as filed, refused, or, from
# the exit trap, interrupted.
tel_end() {
  tel approve.end --data "result=$1"
  TEL_RUN="" TEL_SPOOL="" TEL_PROJECT="" TEL_CTX=()
}

# tel_command <status>: the command record of a verb this script runs
# itself, handed to valley-go as the script exits, once. valley-go decides
# whether telemetry is on; the verbs this script execs it for it records
# itself.
TEL_ARGS=()
tel_command() {
  [ ${#TEL_ARGS[@]} -gt 0 ] || return 0
  local -a args=("${TEL_ARGS[@]}")
  TEL_ARGS=()
  valley-go telemetry command --since "$TEL_T0" --version "$VALLEY_STAMP" --status "$1" \
    -- "${args[@]}" < /dev/null > /dev/null 2>&1 || true
}

# approve <branch>: one approval attempt, and its telemetry. Every way of
# approving runs it: valley approve, and each [a]pprove answer review takes,
# a stack's layers included, so each attempt is its own run. An attempt the
# session exits during is ended by cleanup_scratch.
approve() {
  # Off a terminal, the answer to review's prompt ends no line, so the
  # verdict starts its own, unless carried's line has ended it.
  [ -z "$REVIEWING" ] || [ -t 0 ] || [ -n "$CARRIED" ] || printf '\n'
  tel_begin
  local status=0
  approve_attempt "$@" || status=$?
  if [ "$status" -eq 0 ]; then tel_end filed; else tel_end refused; fi
  return "$status"
}

approve_attempt() {
  local branch="$1" target=main tip change head base digest root ref check spec what
  local key
  local -a signer=() required=() run=() timing=() evidence=()

  root="$(git rev-parse --show-toplevel)" || {
    declined "not in a git repository"
    return 1
  }
  # main's tip as the fetch left it, read once by its exact name. The
  # merge base, the fast-forward and both policy layers are read at that
  # one commit.
  tip="$(ref_oid refs/remotes/origin/main)" || {
    if [ $? -eq 1 ]; then
      declined "origin has no main to approve onto"
    else
      declined "could not read origin/main" --run "git fetch origin"
    fi
    return 1
  }
  # 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" ] || {
      declined "no head is bound to this approval"
      return 1
    }
    check_record "" "$head" || return 1
    change="c-$CHANGE_ID"
    what="$CHANGE_HANDLE v$APPROVE_VERSION"
  elif [ -n "$APPROVE_HEAD" ]; then
    # A plain branch that review showed is filed at the head shown. The
    # last check before the push refuses if the branch on origin has moved
    # off it since.
    head="$APPROVE_HEAD"
    change="$(change_name "$branch")"
    what="$branch"
  else
    head="$(ref_oid "refs/remotes/origin/$branch")" || {
      declined "origin has no branch $branch"
      return 1
    }
    change="$(change_name "$branch")"
    what="$branch"
  fi
  # c-<change ID> is the request name of the change with that ID, so a
  # branch is never filed under one.
  if [ -z "$CHANGE_ID" ] && [[ "$change" =~ ^c-[k-z]{32}$ ]]; then
    declined "the branch's request name $change is change ${change#c-}'s" \
      --then "rename the branch, or name the change by its ID"
    return 1
  fi
  base="$(git merge-base "$tip" "$head")" || {
    declined "shares no history with main"
    return 1
  }
  ref="refs/the-valley/integration-requests/$target/$change"
  local named="$branch" under
  TEL_CTX=(--change "$CHANGE_ID" --version "${APPROVE_VERSION:-0}" --head "$head")
  tel approve.start --data "what=$what" --data "request=$ref"
  [ -z "$CHANGE_ID" ] || named="$CHANGE_HANDLE"

  # A head that does not fast-forward from main, and would bring a version
  # of another change that has not landed, is a layer above the bottom of
  # a stale stack. The integrator could land it all the same, as one
  # commit recorded against this request alone, and the changes under it
  # would have no landing record of their own. So it is refused before
  # any check runs over a head that has to be rebased anyway, and the
  # stack is rebased first. This is the project's choice, not a rule the
  # integrator needs. A stale head with no change under it, such as the
  # bottom layer of a stack or a change alone, is approved as it is, and
  # the integrator merges it onto main.
  if ! git merge-base --is-ancestor "$tip" "$head"; then
    if ! under="$(valley-go brings ${CHANGE_ID:+--change "$CHANGE_ID"} "$head")"; then
      declined "could not read which changes it would bring to main"
      return 1
    fi
    if [ -n "$under" ]; then
      declined "stack is behind main (includes $(printf '%s\n' "$under" | join_lines))" \
        --run "valley rebase $(printf '%q' "$named")"
      return 1
    fi
  fi

  # What the policy requires of the change, 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"
  if ! resolve_instance_layer "$root" refs/remotes/origin/main "$tip" \
    || ! resolve_project_layer "$root" refs/remotes/origin/main "$tip" \
    || ! derive_required "$POLICY_SCHEMA" "$POLICY_INSTANCE" "$POLICY_PROJECT" "$base" "$head"; then
    declined "the policy did not derive"
    return 1
  fi
  sort_into required "${!DERIVED_REQUIRED[@]}" || {
    declined "could not sort the required checks"
    return 1
  }
  tel approve.policy --list "required=$(join_by , ${required[@]+"${required[@]}"})" \
    --data "instance=$POLICY_INSTANCE_LABEL" --data "project=$POLICY_PROJECT_LABEL"

  # A change the policy asks nothing of is still a change, and approving
  # is how one reaches main. The integrator already lands a request that
  # requires 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 required,
  # so nothing is signed and no key is needed: what gets published is one
  # request ref and no evidence at all.
  #
  # A required check whose evidence origin already holds is reused, not
  # built again: a check worker, or an earlier approval, may have published
  # it. valley-go coverage (status/coverage.go) lists origin's attestation
  # refs for the head's tree, fetches them, and says which required nix
  # checks they hold acceptable evidence for. Every command check runs
  # here, and so does every other nix check when --build-here asks for it.
  # A read of origin that fails ends the approval rather than reading as no
  # evidence. When every check is covered, nothing runs and no key is
  # needed, as when nothing is required.
  local -a missing=() reused=() failed=()
  local -A stored=() covered=()
  if [ "${#required[@]}" -gt 0 ]; then
    command -v attest > /dev/null 2>&1 || {
      declined "the attest helper is not installed" --then "nix run .#valley bundles it"
      return 1
    }
    local -a asked=()
    for check in "${required[@]}"; do
      [ "${CHECK_RUNNER[$check]:-}" != nix ] || asked+=(--check "$check=${CHECK_ATTRIBUTE[$check]}")
    done
    # Its stderr is shown only with -v, and then as the same descriptor:
    # opening /dev/stderr again waits forever on a pipe nobody reads.
    local coverage kind field value by
    if ! coverage="$(
      [ -n "$VERBOSE" ] || exec 2> /dev/null
      valley-go coverage --head "$head" ${asked[@]+"${asked[@]}"}
    )"; then
      declined "could not read the evidence origin holds" --run "valley approve -v $(verdict_name)"
      return 1
    fi
    while read -r kind field value by; do
      case "$kind" in
        digest) digest="$field" ;;
        stored) stored["$field"]="$value" ;;
        covered) covered["$field"]="$value $by" ;;
        failed) failed+=("$field") ;;
      esac
    done <<< "$coverage"
    [ -n "$digest" ] || {
      declined "valley-go coverage named no tree"
      return 1
    }
    # A check whose evidence on origin records a failure is judged by that
    # evidence, so building it again changes nothing for this tree, and
    # nothing is filed.
    if [ "${#failed[@]}" -gt 0 ]; then
      CHECKS_FAILED_AT="$head"
      local -a flags=()
      for check in "${failed[@]}"; do flags+=(--failed "$check"); done
      declined "" --required "${#required[@]}" "${flags[@]}"
      return 1
    fi
    for check in "${required[@]}"; do
      if [ -n "${covered[$check]:-}" ]; then reused+=("$check"); else missing+=("$check"); fi
    done
    local -a signed_by=()
    for check in ${reused[@]+"${reused[@]}"}; do
      signed_by+=("$check=${covered[$check]#* }")
    done
    tel approve.coverage --data "tree=$digest" \
      --list "reused=$(join_by , ${reused[@]+"${reused[@]}"})" \
      --list "reused_by=$(join_by , ${signed_by[@]+"${signed_by[@]}"})" \
      --list "missing=$(join_by , ${missing[@]+"${missing[@]}"})"
    if [ -n "$VERBOSE" ] && [ "${#reused[@]}" -gt 0 ]; then
      printf 'reusing the evidence origin holds for %s at %s, tree %s:\n' "$what" "$(git rev-parse --short "$head")" "$digest"
      for check in "${reused[@]}"; do
        printf '  %-24s signed by %s\n' "$check" "${covered[$check]#* }"
      done
    fi
  fi

  # A required nix check with no evidence on origin is built here only when
  # the operator asks for it with --build-here. The host's check worker
  # builds the same checks for a ready change, and publishes the evidence
  # when its batch ends. Approving a change and its checks passing are
  # separate, so without the flag approve files the request at once,
  # without that evidence, and leaves those checks out of what runs here.
  # The integrator holds such a request as stale for want of evidence,
  # keeps it, and judges it again when evidence arrives. Whether the
  # change then lands depends on the other gates, and whether the worker
  # publishes at all is not assured. A command check is never reused and no
  # worker runs one, so it runs here either way. From here on, missing is
  # what runs here, and unbuilt is what nothing here builds.
  local -a unbuilt=()
  local began took=""
  if [ -z "$BUILD_HERE" ]; then
    local -a here=()
    for check in ${missing[@]+"${missing[@]}"}; do
      if [ "${CHECK_RUNNER[$check]:-}" = nix ]; then unbuilt+=("$check"); else here+=("$check"); fi
    done
    missing=(${here[@]+"${here[@]}"})
  fi

  if [ "${#missing[@]}" -gt 0 ]; then
    key="${VALLEY_ATTEST_KEY:-}"
    [ -n "$key" ] || {
      declined "no signing key" --then "set VALLEY_ATTEST_KEY to the ed25519 key this host attests with"
      return 1
    }
    [ -f "$key" ] || {
      declined "no signing key at $key"
      return 1
    }
    signer=(--key "$key")
    [ -z "${VALLEY_ATTEST_NAME:-}" ] || signer+=(--name "$VALLEY_ATTEST_NAME")

    # The ref this run's evidence goes to is keyed by the tree and this
    # signer's key hash, and approve pushes it holding this run's notes
    # alone, which origin refuses once it holds the ref: it keeps every
    # note a ref holds. When origin already holds it, evidence for the
    # checks still missing has nowhere to go, so that is said before anything is built rather than
    # after (bd-7b7d58f).
    local verifier keyhash own
    verifier="$(attest key "${signer[@]}")" || {
      declined "could not read the signing key at $key"
      return 1
    }
    keyhash="${verifier#*+}"
    own="refs/the-valley/attestations/$digest/${keyhash%%+*}"
    if [ -n "${stored[$own]:-}" ]; then
      declined "this key's evidence for the tree, on origin, lacks $(printf '%s\n' "${missing[@]}" | join_lines)" \
        --then "attest with another key: set VALLEY_ATTEST_KEY"
      return 1
    fi

    # attest logs how long each check took, on this machine and outside
    # the evidence. What it cannot know itself is passed in: the change,
    # and each check's declared cost.
    timing=(--timings)
    [ -z "$CHANGE_ID" ] || timing+=(--change "$CHANGE_ID")
    [ -z "$APPROVE_VERSION" ] || timing+=(--change-version "$APPROVE_VERSION")
    for check in "${missing[@]}"; do
      case "${CHECK_RUNNER[$check]:-}" in
        nix) run+=(--check "$check=${CHECK_ATTRIBUTE[$check]}") ;;
        command) run+=(--command "$check=${CHECK_COMMAND[$check]}") ;;
        *)
          declined "the policy requires $check but says no way to run it"
          return 1
          ;;
      esac
      [ -z "${CHECK_COST[$check]:-}" ] || timing+=(--cost "$check=${CHECK_COST[$check]}")
    done

    cleanup_approve_wt
    APPROVE_WT="$(mktemp -d)" || {
      declined "no scratch directory to check it in"
      return 1
    }
    git worktree add --quiet --detach "$APPROVE_WT" "$head" || {
      cleanup_approve_wt
      declined "could not check the head out to run its checks"
      return 1
    }

    if [ -n "$TEL_RUN" ]; then
      timing+=(--telemetry "$TEL_SPOOL" --telemetry-run "$TEL_RUN-checks" --project "$TEL_PROJECT")
      tel approve.checks --data "attest_run=$TEL_RUN-checks" --list "checks=$(join_by , "${missing[@]}")"
    fi
    # valley-go verdict runs attest and shows its progress, and on a
    # failure the failed check's log and the refusal.
    local -a building=()
    for check in "${missing[@]}"; do building+=(--check "$check"); done
    began="$SECONDS"
    if ! valley-go verdict checking --name "${CHANGE_HANDLE:-$branch}" \
      ${CHANGE_ID:+--version "$APPROVE_VERSION"} --of "${#required[@]}" --passed "${#reused[@]}" \
      ${VERBOSE:+-v} "${building[@]}" \
      -- attest run --repo "$APPROVE_WT" "${signer[@]}" "${timing[@]}" "${run[@]}"; then
      cleanup_approve_wt
      CHECKS_FAILED_AT="$head"
      return 1
    fi
    took="$((SECONDS - began))s"
    cleanup_approve_wt

    # Every attestation stored here 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 ] || {
      declined "no attestation is stored for the tree"
      return 1
    }
  elif [ "${#required[@]}" -eq 0 ] && [ -n "$VERBOSE" ]; then
    printf '%s requires 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.
  #
  # A ref on origin whose name ends in the request's, or in an evidence
  # ref's, would take the push in its place (push_lookalike). So it is
  # refused here, and nothing is pushed while it stands.
  local pending lookalike
  if ! pending="$(remote_ref "$ref")" \
    || ! lookalike="$(push_lookalike "$ref" ${evidence[@]+"${evidence[@]}"})"; then
    declined "could not read the request ref on origin"
    report_local_evidence ${evidence[@]+"${evidence[@]}"}
    return 1
  fi
  if [ -n "$lookalike" ]; then
    declined "origin holds $lookalike, which git would push to in place of a ref approve pushes" \
      --then "delete $lookalike on origin"
    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 narrows the window: it lands no request that
  # would bring 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. It reads the records last just before it moves
  # the target, so only a record written in that moment is missed.
  if ! check_record "$head" "$APPROVE_HEAD"; then
    report_local_evidence ${evidence[@]+"${evidence[@]}"}
    return 1
  fi
  # A plain branch is filed at the head review showed only while the
  # branch on origin is still there. The operator reviewed a branch, and a
  # branch that moved holds commits nobody has read. A change with a
  # record is filed at its head wherever its branch is.
  if [ -z "$CHANGE_ID" ] && [ -n "$APPROVE_HEAD" ] && ! branch_at_shown "$branch"; then
    report_local_evidence ${evidence[@]+"${evidence[@]}"}
    return 1
  fi

  # With no new evidence, because nothing was required or origin already
  # held all of it, and the request already standing at this head, there
  # is nothing to push. 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
      tel approve.request --data "ref=$ref" --data "result=refused"
      if [ "${#lease[@]}" -eq 0 ] \
        && attestation_stands_elsewhere "$digest" ${evidence[@]+"${evidence[@]}"}; then
        declined "this key's evidence for the tree is on origin already" \
          --then "attest with another key: set VALLEY_ATTEST_KEY"
      else
        diagnose_request_push "$ref" "$pending"
      fi
      report_local_evidence ${evidence[@]+"${evidence[@]}"}
      return 1
    fi
    tel approve.request --data "ref=$ref" --data "result=pushed"
  fi

  # The lines -v adds 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. The approval stood
    # before this run, so a request that cannot be read, or was consumed,
    # leaves its state unknown here rather than unapproved. 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
      valley-go verdict unknown --name "${CHANGE_HANDLE:-$branch}" ${CHANGE_ID:+--version "$APPROVE_VERSION"}
      report_local_evidence ${evidence[@]+"${evidence[@]}"}
      return 1
    fi
    if [ -z "$after" ]; then
      valley-go verdict unknown --name "${CHANGE_HANDLE:-$branch}" ${CHANGE_ID:+--version "$APPROVE_VERSION"} \
        --why "request consumed meanwhile"
      report_local_evidence ${evidence[@]+"${evidence[@]}"}
      return 1
    fi
    if [ "$after" != "$head" ]; then
      declined "another approval filed $(git rev-parse --short "$after") ($(subject_of "$after")) meanwhile" \
        --run "valley approve $(verdict_name)"
      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")
    elif [ "${#unbuilt[@]}" -gt 0 ]; then
      standing+=("the request already stood at this head, and nothing was built or published")
    elif [ "${#required[@]}" -gt 0 ]; then
      standing+=("the request already stood at this head and origin already held the evidence, so nothing needed publishing")
    else
      standing+=("the request already stood at this head and nothing was required, 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

  if [ -n "$VERBOSE" ]; then
    printf '  request  %s -> %s\n' "$ref" "$(git rev-parse --short "$head")"
    [ "${#standing[@]}" -eq 0 ] || printf '  %s\n' "${standing[@]}"
    if [ "${#required[@]}" -eq 0 ]; then
      printf '  evidence none — nothing was required, so nothing was signed\n'
      printf '  checks   none — the policy requires no check of this change\n'
    else
      printf '  tree     %s\n' "$digest"
      [ "${#evidence[@]}" -eq 0 ] || printf '  evidence %s\n' "${evidence[@]}"
      # The refs on origin whose evidence was reused, each once.
      local -A shown=()
      for check in ${reused[@]+"${reused[@]}"}; do
        spec="${covered[$check]%% *}"
        [ -z "${shown[$spec]:-}" ] || continue
        shown["$spec"]=1
        printf '  reused   %s\n' "$spec"
      done
      [ "${#unbuilt[@]}" -eq 0 ] || printf '  missing  %s\n' "$(printf '%s\n' "${unbuilt[@]}" | join_lines)"
      printf '  checks   %s\n' "$(printf '%s\n' "${required[@]}" | join_lines)"
    fi
  fi

  # The verdict. Checks with no evidence yet are built by a check worker
  # only for a ready change's active version. Elsewhere approve offers to
  # build them here, unless a command check that ran here put this
  # signer's evidence for the tree on origin, which approve cannot add to,
  # so a plain branch is offered readying instead, which lets a worker
  # build it.
  local -a facts=(--required "${#required[@]}" --passed "$((${#required[@]} - ${#unbuilt[@]}))")
  [ -z "$took" ] || facts+=(--took "$took")
  for check in ${unbuilt[@]+"${unbuilt[@]}"}; do facts+=(--waiting "$check"); done
  if [ "${#unbuilt[@]}" -gt 0 ]; then
    if [ -n "$CHANGE_ID" ] && [ "$head" = "$CHANGE_HEAD" ]; then
      facts+=(--worker)
    elif [ "${#missing[@]}" -eq 0 ]; then
      facts+=(--run "valley approve --build-here ${CHANGE_ID:+--head $(git rev-parse --short "$head") }$(verdict_name)")
    elif [ -z "$CHANGE_ID" ]; then
      facts+=(--run "valley ready $(verdict_name)")
    else
      facts+=(--see "valley status $(verdict_name)")
    fi
  fi
  valley-go verdict approved --name "${CHANGE_HANDLE:-$branch}" \
    ${CHANGE_ID:+--version "$APPROVE_VERSION"} --target "$target" "${facts[@]}"
}

# 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/). knot
# reads and writes the plan graph at refs/the-valley/knots, in the one
# form the push hook validates (knot/), and plan shows that graph as a
# view.
cmd_go() {
  command -v valley-go > /dev/null 2>&1 \
    || die "$1 needs the valley-go helper; nix run .#valley bundles it"
  VALLEY_TELEMETRY_SINCE="$TEL_T0" VALLEY_TELEMETRY_VERSION="$VALLEY_STAMP" 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, state and owner, 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 at CHANGE_HEAD, and approve at the head bound
# to it (bind_head). rebase reads the record itself (status/rebase.go).
# 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=""
CHANGE_OWNER=""

# read_resolved <line> <name…>: read a line of valley-go resolve into the
# variables named, one field each. A version's branch may be empty, and
# read runs consecutive tabs together, since a tab is whitespace to it: an
# empty branch would shift the state into the branch. So each tab is made
# a unit separator first, which read keeps apart.
read_resolved() {
  local resolved="$1"
  shift
  IFS=$'\x1f' read -r "$@" <<< "${resolved//$'\t'/$'\x1f'}"
}

# Set by cmd_review. A review is the operator's, and the change under it
# is usually someone else's, so review never tells the operator to ready
# it: that is for the change's owner.
REVIEWING=""

# ready_hint <change ID> <branch> <owner>: what a refusal of a change that
# is not ready offers the caller: the valley ready command that readies the
# change again, naming the branch unless its version records none, as
# --run and its value, one per line. Only the change's owner, as git
# config valley.principal names them, is offered it, and never in a
# review. Prints nothing for anyone else.
ready_hint() {
  [ -z "$REVIEWING" ] || return 0
  [ -n "$3" ] && [ "$(git config valley.principal || true)" = "$3" ] || return 0
  printf -- '--run\nvalley ready --change %s' "$1"
  [ -z "$2" ] || printf ' %q' "$2"
}

# not_ready_declined <state> <change ID> <branch> <owner>: approve's
# refusal of a change that is not ready.
not_ready_declined() {
  local -a hint=()
  mapfile -t hint < <(ready_hint "$2" "$3" "$4")
  declined "change is $([ "$1" = draft ] && echo 'a draft' || echo "$1")" ${hint[@]+"${hint[@]}"}
}

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
  read_resolved "$line" kind CHANGE_ID CHANGE_HANDLE CHANGE_VERSION CHANGE_HEAD CHANGE_BRANCH CHANGE_STATE CHANGE_OWNER
  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
}

# need_branch <verb>: refuse a change whose active version records no
# branch. review acts on the change's branch: it files its notes under it
# and its [r]eject deletes it. rebase, which pushes it, refuses such a
# change in valley-go. approve files the head alone, so it approves such a
# change.
need_branch() {
  if [ -n "$CHANGE_ID" ] && [ -z "$CHANGE_BRANCH" ]; then
    die "change $CHANGE_HANDLE v$CHANGE_VERSION records no branch, and $1 acts on a change's branch. Approve its head alone: valley approve --head $CHANGE_HEAD $CHANGE_HANDLE"
  fi
}

# The commit review and approve 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
    ref_oid "refs/remotes/origin/$1"
  fi
}

# fast_forwards <commit>: whether the commit fast-forwards from main's tip
# as the fetch left it. A main that cannot be read is not one it
# fast-forwards from.
fast_forwards() {
  local tip
  tip="$(ref_oid refs/remotes/origin/main)" && git merge-base --is-ancestor "$tip" "$1"
}

# For a change with a record, refuse unless the branch's tip on origin is
# the recorded head, and name both. review's [r]eject acts on the branch
# itself: deleting it while it is elsewhere would delete a commit no
# version records. rebase asks the same in valley-go. 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="$(ref_oid "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 until it is readied again. The record was read when review or
# approve 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.
# 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. rebase makes its own checks in valley-go (status/rebase.go).
#
# 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 reads the original name
# again too. approve passes the head it is about to file as the first
# 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.
#
# approve binds the head it approves (APPROVE_HEAD), and passes it as the
# second 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 acting="${1:-}" bound="${2:-}" line kind id handle version head branch state owner
  if [ -z "$CHANGE_ID" ]; then
    [ -n "$acting" ] || return 0
    if ! line="$(valley-go resolve "$CHANGE_NAME")"; then
      declined "could not read origin's records again"
      return 1
    fi
    read_resolved "$line" kind id handle version head branch state owner
    [ "$kind" = change ] || return 0
    if [ "$state" != ready ]; then
      local -a hint=()
      mapfile -t hint < <(ready_hint "$id" "$branch" "$owner")
      declined "now change $handle v$version, which is $state" ${hint[@]+"${hint[@]}"}
      return 1
    fi
    if [ "$head" != "$acting" ]; then
      declined "now change $handle v$version, at another head" --run "valley review $handle"
      return 1
    fi
    return 0
  fi
  if ! line="$(valley-go resolve "$CHANGE_ID")"; then
    declined "could not read the change's record again"
    return 1
  fi
  read_resolved "$line" kind id handle version head branch state owner
  if [ "$kind" != change ] || [ "$id" != "$CHANGE_ID" ]; then
    declined "origin no longer holds the change's record"
    return 1
  fi
  if [ "$state" != ready ]; then
    not_ready_declined "$state" "$CHANGE_ID" "$branch" "$owner"
    return 1
  fi
  if [ -n "$bound" ]; then
    check_version "$bound"
    return
  fi
  if [ "$head" != "$CHANGE_HEAD" ]; then
    declined "change moved to v$version" --run "valley review $CHANGE_HANDLE"
    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.
APPROVE_VERSION="" APPROVE_TITLE=""
check_version() {
  local head="$1" out n vhead vstate title state=""
  local -a known=()
  APPROVE_VERSION="" APPROVE_TITLE=""
  if ! out="$(valley-go versions "$CHANGE_ID")"; then
    declined "could not read the change's versions"
    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
    not_ready_declined "$state" "$CHANGE_ID" "$CHANGE_BRANCH" "$CHANGE_OWNER"
    return 1
  fi
  if [ -z "$APPROVE_VERSION" ]; then
    declined "$(git rev-parse --short "$head") is none of its versions ($(printf '%s\n' "${known[@]}" | join_lines))" \
      --see "valley status $CHANGE_HANDLE"
    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
    not_ready_declined "$CHANGE_STATE" "$CHANGE_ID" "$CHANGE_BRANCH" "$CHANGE_OWNER"
    return 1
  fi
  if [ -n "$want" ]; then
    if ! [[ "$want" =~ ^[0-9a-f]{4,64}$ ]] \
      || ! sha="$(git rev-parse --verify --quiet "$want^{commit}")"; then
      declined "--head $want names no commit here" --see "valley status $CHANGE_HANDLE"
      return 1
    fi
    check_version "$sha" || return 1
    APPROVE_HEAD="$sha"
    return 0
  fi
  check_version "$CHANGE_HEAD" || return 1
  if [ ! -t 0 ]; then
    declined "no terminal to confirm the head, $APPROVE_TITLE" \
      --run "valley approve --head $CHANGE_HEAD $CHANGE_HANDLE"
    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" ;;
    *)
      declined "not confirmed"
      return 1
      ;;
  esac
}

# review shows a change with a record at its active version's head, and
# its [a]pprove approves exactly that head. A plain branch is bound to the
# head review pages, when it pages it (show_review, use_layer), and approve
# files that head. approve with no review binds nothing, and files the
# branch's tip on origin as the fetch left it.
bind_review() {
  APPROVE_HEAD="" APPROVE_VERSION=""
  if [ -n "$CHANGE_ID" ]; then
    APPROVE_HEAD="$CHANGE_HEAD"
    APPROVE_VERSION="$CHANGE_VERSION"
  fi
}

# branch_at_shown <branch>: refuse unless the branch on origin is still at
# the head bound to this approval, and name both. origin itself is read,
# not the tracking ref: a push from another checkout moves the branch
# without moving this clone's ref. ls-remote matches a pattern against the
# tail of a ref name, so each ref it lists is compared whole.
branch_at_shown() {
  local out now
  out="$(git ls-remote origin "refs/heads/$1")" || {
    declined "could not read origin/$1 again"
    return 1
  }
  now="$(printf '%s\n' "$out" | awk -v r="refs/heads/$1" '$2 == r { print $1 }')"
  if [ -z "$now" ]; then
    declined "origin/$1 is gone"
    return 1
  fi
  [ "$now" = "$APPROVE_HEAD" ] && return 0
  declined "origin/$1 moved from $(git rev-parse --short "$APPROVE_HEAD"), the head shown, to $(git rev-parse --short "$now")" \
    --run "valley review $(printf '%q' "$1")"
}

# 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"
}

# not_ready <handle> <version> <state> <owner>: the line review shows for a
# change whose record is not ready, above its diff and in its prompt.
# Prints nothing, and fails, for a ready change, and for a plain branch,
# which has no record. A draft is often a change an agent is still working
# on, so the prompt then offers only [v]iew full diff and [s]kip.
# [a]pprove would be refused. Nor is [r]eject offered, which records
# nothing on the change: it deletes the branch its owner may still be
# working on, and the record says what it said before. review still reads
# the record again before it acts, since the state can change while the
# review is open (moved).
not_ready() {
  case "$3" in
    draft) printf "%s v%s is a draft: its owner (%s) hasn't marked it ready, so it can't be approved yet." "$1" "$2" "$4" ;;
    withdrawn) printf '%s is withdrawn: there is nothing to approve.' "$1" ;;
    *) return 1 ;;
  esac
}

# shown_not_ready: not_ready for the change review is showing.
shown_not_ready() {
  not_ready "$CHANGE_HANDLE" "$CHANGE_VERSION" "$CHANGE_STATE" "$CHANGE_OWNER"
}

# Where the change under review stands now, as valley-go standing reads
# it from origin (status/standing.go), set by read_standing. The state,
# the active version and its head; when the record last changed; the
# version the change landed as, v<n>, once any has; and STANDING_CONFLICT, which is "conflict"
# while the host's restacker reports that rebasing the change onto main
# conflicted.
STANDING_STATE="" STANDING_VERSION="" STANDING_HEAD="" STANDING_SINCE=""
STANDING_LANDED="" STANDING_CONFLICT=""

# read_standing: read where the change under review stands now. A plain
# branch has no record, and reads as nothing. Fails when origin cannot be
# read.
read_standing() {
  local line
  STANDING_STATE="" STANDING_VERSION="" STANDING_HEAD="" STANDING_SINCE=""
  STANDING_LANDED="" STANDING_CONFLICT=""
  [ -n "$CHANGE_ID" ] || return 0
  line="$(valley-go standing "$CHANGE_ID")" || return 1
  read_resolved "$line" STANDING_STATE STANDING_VERSION STANDING_HEAD STANDING_SINCE \
    STANDING_LANDED STANDING_CONFLICT
}

# moved: before review acts on an answer about a change with a record, it
# reads the change again. Another principal may return it to draft, ready
# a new version, or withdraw it while the operator reads, and it may land.
# When it is no longer what review showed, moved says in one line what
# changed and what happens next, and the review of that change ends: the
# prompt's answers were about what was shown, so it is not asked again.
# A new version the answer carries to, such as a restack with the same
# changes, does not end it (carried). Fails when the change is still as
# shown or the answer carries, and for a plain branch, which approve and
# reject check themselves.
moved() {
  local h="$CHANGE_HANDLE"
  CARRIED=""
  [ -n "$CHANGE_ID" ] || return 1
  if ! read_standing; then
    echo "could not read $h again from origin; nothing done"
    return 0
  fi
  case "$STANDING_STATE" in
    withdrawn)
      echo "$h changed while you were reviewing: it was withdrawn (since $STANDING_SINCE), so there is nothing to approve."
      return 0
      ;;
    draft)
      echo "$h changed while you were reviewing: it was returned to draft (since $STANDING_SINCE), so there is nothing to approve now. It comes back when it is ready again."
      return 0
      ;;
  esac
  if [ -n "$STANDING_LANDED" ]; then
    echo "$h landed as $STANDING_LANDED while you were reviewing; there is nothing left to approve."
    return 0
  fi
  if [ "$STANDING_VERSION" != "$CHANGE_VERSION" ] || [ "$STANDING_HEAD" != "$CHANGE_HEAD" ]; then
    carried || return 0
  fi
  return 1
}

# Set by carried when the answer carries, and cleared by moved: off a
# terminal, carried's line ended the line review's prompt left open, so
# approve's verdict needs no newline of its own.
CARRIED=""

# carried: whether the answer about the version review showed carries to
# the version the change moved to, as valley-go carry decides
# (status/carry.go). When it does, carried says so in one line, and the
# answer stays bound to the head shown: an approval names what the
# reviewer read, and the integrator applies its delta onto main as main
# stands. When it does not, carried says why in one line, offers to page
# only what changed since the version shown, and fails.
carried() {
  local h="$CHANGE_HANDLE" verdict="" reason="" choice
  REVIEW_TMP="$(mktemp -d)"
  valley-go carry "$CHANGE_ID" "$CHANGE_VERSION" "$STANDING_VERSION" > "$REVIEW_TMP/carry" \
    && IFS=$'\t' read -r verdict reason < "$REVIEW_TMP/carry"
  case "$verdict" in
    carries)
      echo "$h moved to v$STANDING_VERSION while you were reviewing ($reason) · your answer about v$CHANGE_VERSION stands"
      CARRIED=yes
      cleanup_review_tmp
      return 0
      ;;
    review)
      printf '%s moved to v%s while you were reviewing (%s) · review it again to approve it · [v]iew what changed since v%s, [s]kip? ' \
        "$h" "$STANDING_VERSION" "$reason" "$CHANGE_VERSION"
      read -r choice || choice=""
      if [ "$choice" = v ]; then
        tail -n +2 "$REVIEW_TMP/carry" > "$REVIEW_TMP/changed"
        page_file "$REVIEW_TMP/changed" || true # quitting the pager early is not an error
      fi
      ;;
    *) echo "$h moved to v$STANDING_VERSION while you were reviewing; review it again to approve what would land." ;;
  esac
  cleanup_review_tmp
  return 1
}

# behind_main <branch>: the clause review's prompt shows for a change that
# does not fast-forward from main. Being behind main is normal and asks
# nothing of the operator: the integrator applies the change's delta onto
# main as main stands, with the evidence for the head approved, and the
# host's restacker rebases ready changes itself. When the restacker
# reports that rebasing the change conflicted, the clause says so instead,
# and [a]pprove stays offered: the integrator decides whether the change
# applies. Prints nothing, and fails, for a change that fast-forwards from
# main.
behind_main() {
  fast_forwards "$(change_head "$1")" && return 1
  read_standing || STANDING_CONFLICT=""
  if [ "$STANDING_CONFLICT" = conflict ]; then
    printf 'conflicts with main (owner resolving)'
  else
    printf 'behind main (integrator merges)'
  fi
}

# Show 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() {
  show_review "$1"
  decide "$1"
}

# decide <branch> [<name> <n>]: the verdict on a change alone, and on the
# top of a stack. Its prompt is one header line, the change and what
# stands in its way as clauses, and the keys it takes (valley-go verdict
# prompt, status/verdict.go). A change is named by its handle and version,
# a plain branch by its name, and a change alone carries the checks line
# review read for it. The top of a stack of <n> is named by its <name>, as
# the stack lists it, and its [a]pprove says that approving it lands all
# <n> layers. [v]iew diff pages the change's whole diff, or the top
# layer's.
#
# A change that is not ready says so in its header, and is offered only
# [v]iew diff and [s]kip, or [s]top. The top of a stack with a layer under
# it that is not ready says why it can't be approved (layer_held), as
# does a change whose checks failed at the head shown, and neither is
# offered [a]pprove. A change that can be approved and does not
# fast-forward from main says so (behind_main). Before [a]pprove and
# [r]eject act, moved reads the change again, and ends its review when it
# moved.
decide() {
  local branch="$1" name="${2:-}" n="${3:-}" choice failed answers own="" held="" behind="" clause
  local approve="[a]pprove" reject="[r]eject" stop="[s]kip"
  local stopped="skipped $1; nothing done"
  local -a header=("$1") keys=()
  if [ -n "$CHANGE_ID" ]; then
    header=("$CHANGE_HANDLE v$CHANGE_VERSION")
    case "$CHANGE_STATE" in
      draft) own="draft (its owner, $CHANGE_OWNER, has not readied it)" ;;
      withdrawn) own="withdrawn" ;;
    esac
  fi
  if [ -n "$n" ]; then
    header+=("stack of $n")
    approve="[a]pprove all $n" reject="[r]eject $name" stop="[s]top"
    stopped="stopped reviewing $name at change $n of $n; nothing done"
    held="$(layer_held $((n - 1)))" || held=""
  elif [ -n "${REVIEW_CHECKS:-}" ]; then
    header+=("$REVIEW_CHECKS")
  fi
  if [ -z "$own" ] && [ -z "$held" ]; then
    behind="$(behind_main "$branch")" || behind=""
  fi
  while true; do
    failed=""
    if [ -n "$own" ]; then
      clause="$own" keys=("[v]iew diff" "$stop") answers="v or s"
    elif [ -n "$held" ]; then
      clause="$held" keys=("[v]iew diff" "$reject" "$stop") answers="v, r, or s"
    elif failed="$(approve_failed_at "$branch")"; then
      clause="checks failed at $failed" keys=("[v]iew diff" "$reject" "$stop") answers="v, r, or s"
    else
      clause="$behind" keys=("$approve" "[v]iew diff" "$reject" "$stop") answers="a, v, r, or s"
    fi
    valley-go verdict prompt "${header[@]}" ${clause:+"$clause"} -- "${keys[@]}"
    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, nor is approving a change that is not ready. A
      # change that moved since it was shown is not acted on, and its
      # review ends.
      a)
        if [ -n "$failed" ] || [ -n "$own" ] || [ -n "$held" ]; then
          echo "answer $answers"
        elif moved || approve "$branch"; then
          return
        fi
        ;;
      v)
        if [ -n "$n" ]; then
          view_layer $((n - 1))
        else
          view_full "$branch"
        fi
        ;;
      r)
        if [ -n "$own" ]; then
          echo "answer $answers"
        elif moved; then
          return
        else
          reject "$branch" && return
        fi
        ;;
      s)
        echo "$stopped"
        return
        ;;
      *) echo "answer $answers" ;;
    esac
  done
}

# ----------------------------------------------------------------------
# A stack — a change with layers under it that have not landed — is
# reviewed one layer at a time, bottom first, each against the layer below
# it, the way it was built. Approving the top lands every layer under it,
# so reading the top against main alone would ask the operator to judge
# the whole stack as one diff.
#
# The layers are valley-go stack's (status/stack.go): one line each, bottom
# first, the change itself last, read here into one array per field.
# L_BRANCH is the branch a layer's notes are kept under: a branch's own
# name, or the branch a change's active version names. L_OWNER is a
# change's owner, as its record names it. L_NOTES holds the notes taken on
# each layer, for the print after the verdict.
L_KIND=() L_NAME=() L_BASE=() L_HEAD=() L_STATE=() L_APPROVED=() L_TITLE=()
L_ID=() L_VERSION=() L_BRANCH=() L_OWNER=() L_NOTES=()
# The name review was given, which the top is read again by.
TOP_NAME=""

# read_stack: read the stack under the change review resolved. Each change
# under the top is read again with resolve, for its ID, version, branch
# and owner, and must still be at the head the stack names. The top must be
# what review resolved. Fails, having said why, when either does not hold
# or the helper cannot read the stack. Called in a condition, so each step
# is checked by hand.
read_stack() {
  local out line kind name base head state approved title k last
  local rkind id handle version rhead branch rstate owner
  L_KIND=() L_NAME=() L_BASE=() L_HEAD=() L_STATE=() L_APPROVED=() L_TITLE=()
  L_ID=() L_VERSION=() L_BRANCH=() L_OWNER=() L_NOTES=()
  out="$(valley-go stack "${CHANGE_ID:-origin/$CHANGE_BRANCH}")" || return 1
  while IFS= read -r line; do
    read_resolved "$line" kind name base head state approved title
    if ! [[ "$kind" =~ ^(change|branch)$ && "$base" =~ ^[0-9a-f]{40}$ && "$head" =~ ^[0-9a-f]{40}$ ]]; then
      refuse "valley-go stack answered $line, which this script does not read"
      return 1
    fi
    L_KIND+=("$kind") L_NAME+=("$name") L_BASE+=("$base") L_HEAD+=("$head")
    L_STATE+=("$state") L_APPROVED+=("$approved") L_TITLE+=("$title") L_NOTES+=("")
    L_ID+=("") L_VERSION+=("") L_BRANCH+=("$name") L_OWNER+=("")
  done <<< "$out"
  last=$((${#L_NAME[@]} - 1))
  if [ "${L_HEAD[last]}" != "$(change_head "$CHANGE_BRANCH")" ] \
    || [ "${L_KIND[last]}" != "$([ -n "$CHANGE_ID" ] && echo change || echo branch)" ]; then
    refuse "$TOP_NAME moved while its stack was read"
    return 1
  fi
  L_ID[last]="$CHANGE_ID" L_VERSION[last]="$CHANGE_VERSION" L_BRANCH[last]="$CHANGE_BRANCH"
  L_OWNER[last]="$CHANGE_OWNER"
  for ((k = 0; k < last; k++)); do
    [ "${L_KIND[k]}" = change ] || continue
    line="$(valley-go resolve "${L_NAME[k]}")" || return 1
    read_resolved "$line" rkind id handle version rhead branch rstate owner
    if [ "$rkind" != change ] || [ "$rhead" != "${L_HEAD[k]}" ]; then
      refuse "change ${L_NAME[k]}, under $TOP_NAME, moved while the stack was read"
      return 1
    fi
    L_ID[k]="$id" L_VERSION[k]="$version" L_BRANCH[k]="$branch" L_STATE[k]="$rstate"
    L_OWNER[k]="$owner"
  done
}

# use_layer <k>: act on layer k as review acts on a change it was given,
# binding [a]pprove to the head the stack shows. A branch under the top is
# read again as origin/<branch>, which no handle can shadow.
use_layer() {
  local k="$1"
  CHANGE_ID="${L_ID[k]}" CHANGE_VERSION="${L_VERSION[k]}" CHANGE_BRANCH="${L_BRANCH[k]}"
  CHANGE_STATE="${L_STATE[k]}" CHANGE_OWNER="${L_OWNER[k]}" CHANGE_HANDLE="" CHANGE_HEAD=""
  CHANGE_NAME="origin/${L_NAME[k]}"
  [ "$k" -lt $((${#L_NAME[@]} - 1)) ] || CHANGE_NAME="$TOP_NAME"
  if [ -n "$CHANGE_ID" ]; then
    CHANGE_NAME="${L_NAME[k]}" CHANGE_HANDLE="${L_NAME[k]}" CHANGE_HEAD="${L_HEAD[k]}"
  fi
  bind_review
  [ -n "$CHANGE_ID" ] || APPROVE_HEAD="${L_HEAD[k]}"
}

# notes_key <k>: the branch layer k's notes are kept under. A change whose
# active version names no branch keeps them under its handle.
notes_key() {
  printf '%s' "${L_BRANCH[$1]:-${L_NAME[$1]}}"
}

# layer_skipped <k>: succeeds for a layer below the top that is approved,
# which asks nothing of the reviewer: the valley carries it to landing once
# its checks pass. The walk does not page it. The top is the change review
# was named, so it is always paged.
layer_skipped() {
  [ "$1" -lt $((${#L_NAME[@]} - 1)) ] && [ "${L_APPROVED[$1]}" = approved ]
}

# layer_label <k>: how a layer is named in the list: its name, then
# branch, or the change's state.
layer_label() {
  local k="$1"
  if [ "${L_KIND[k]}" = branch ]; then
    printf '%s (branch)' "${L_NAME[k]}"
  elif layer_skipped "$k"; then
    printf '%s (approved, not paged)' "${L_NAME[k]}"
  else
    printf '%s (%s)' "${L_NAME[k]}" "${L_STATE[k]}"
  fi
}

# What is coming: the layers bottom first, the lower layers the integrator
# would refuse, and what each answer lands.
summarize_stack() {
  local n="${#L_NAME[@]}" k
  printf '%s is a stack of %d changes; reviewing from the bottom, each against the one below it:\n' \
    "${L_NAME[n - 1]}" "$n"
  for ((k = 0; k < n; k++)); do
    printf '  %d. %s: %s\n' "$((k + 1))" "$(layer_label "$k")" "${L_TITLE[k]}"
  done
  for ((k = 0; k < n - 1; k++)); do
    case "${L_STATE[k]}" in
      draft | withdrawn)
        printf 'warning: %s, change %d of %d, is %s. The integrator refuses to land it or anything above it (refused-not-ready).\n' \
          "${L_NAME[k]}" "$((k + 1))" "$n" "$([ "${L_STATE[k]}" = draft ] && echo 'a draft' || echo withdrawn)"
        ;;
    esac
  done
  printf 'read each layer and go on with [n]; approving %s at the top lands all %d. [a] on a lower layer lands it and the layers under it, and ends the review.\n' \
    "${L_NAME[n - 1]}" "$n"
}

# base_stack: before any layer is paged, a stack whose bottom does not
# fast-forward from main is offered [b]ase, which rebases every layer as
# the rebase verb does (status/rebase.go), [v]iew diff, which pages the
# top's whole diff, or [s]kip. After a rebase the stack is read again and
# listed again, so the heads paged are the heads approved. A rebase
# refused or left unfinished has said what happened, and only [v]iew diff
# and [s]kip are offered then. Fails when the review stops here.
base_stack() {
  local n choice answers clause="behind main" stopped="; nothing done"
  local -a keys=()
  while ! fast_forwards "${L_HEAD[0]}"; do
    n="${#L_NAME[@]}"
    if [ "$clause" = "behind main" ]; then
      keys=("[b]ase onto main" "[v]iew diff" "[s]kip") answers="b, v, or s"
    else
      keys=("[v]iew diff" "[s]kip") answers="v or s"
    fi
    valley-go verdict prompt "${L_NAME[n - 1]}" "stack of $n" "$clause" -- "${keys[@]}"
    read -r choice || die "stdin closed before an answer; nothing done"
    case "$choice" in
      b)
        if [ "$clause" != "behind main" ]; then
          echo "answer $answers"
        elif rebase_shown "${L_HEAD[n - 1]}"; then
          fetch_origin
          if [ -n "$CHANGE_ID" ]; then
            resolve_change "$CHANGE_ID" || die "could not read change $CHANGE_HANDLE again after the rebase"
          fi
          bind_review
          read_stack || die "could not read the stack under $TOP_NAME again after the rebase"
          summarize_stack
        else
          clause="not rebased" stopped=""
        fi
        ;;
      v) view_full "$CHANGE_BRANCH" ;;
      s)
        echo "stopped reviewing ${L_NAME[n - 1]} before its first layer$stopped"
        return 1
        ;;
      *) echo "answer $answers" ;;
    esac
  done
}

# layer_heading <k>: the line that heads layer k wherever it is shown.
layer_heading() {
  local k="$1" below=main
  [ "$k" -eq 0 ] || below="${L_NAME[k - 1]}"
  printf 'change %d of %d: %s on %s' "$((k + 1))" "${#L_NAME[@]}" "${L_NAME[k]}" "$below"
}

# layer_held <k>: why layer k can't be approved, when it or a layer under
# it is not ready. A layer that is not ready says so as a change alone
# does (not_ready). A layer above one says which: approving it would land
# that layer too, and the integrator lands nothing that would bring a
# version of a change that is not ready. Prints nothing, and fails, when
# every layer up to k is ready or a plain branch.
layer_held() {
  local k="$1" j
  not_ready "${L_NAME[k]}" "${L_VERSION[k]}" "${L_STATE[k]}" "${L_OWNER[k]}" && return
  for ((j = k - 1; j >= 0; j--)); do
    case "${L_STATE[j]}" in
      draft | withdrawn)
        printf "it would bring %s, change %d of %d, which is %s, so it can't be approved yet." \
          "${L_NAME[j]}" "$((j + 1))" "${#L_NAME[@]}" "$([ "${L_STATE[j]}" = draft ] && echo 'a draft' || echo withdrawn)"
        return
        ;;
    esac
  done
  return 1
}

# page_layer <k>: show layer k, as show_review shows a change alone. The
# layer shown is compared with its own change's approved version, so a
# lower layer is set against its own approval, not the top's. Its whole
# diff is against the layer below it. The notes taken in it are kept
# under its own branch. When it can't be approved, layer_held's line
# follows its heading, before the layer's knots.
page_layer() {
  local k="$1" heading held
  NOTES=()
  heading="$(layer_heading "$k")"
  if held="$(layer_held "$k")"; then heading+=$'\n'"$held"; fi
  REVIEW_TMP="$(mktemp -d)"
  compare_shown "${L_ID[k]}" "${L_VERSION[k]}" "${L_HEAD[k]}"
  show_compared "$(notes_key "$k")" "${L_HEAD[k]}" "$heading" "$(does_of "${L_ID[k]}")" layer_diff "$k"
  checks_line "${L_ID[k]}"
  keep_layer_notes "$k"
}

# view_layer <k>: [v]iew full diff for layer k: its whole diff against
# the layer below it.
view_layer() {
  local k="$1"
  NOTES=()
  REVIEW_TMP="$(mktemp -d)"
  {
    layer_heading "$k"
    printf '\n'
    layer_diff "$k"
  } > "$REVIEW_TMP/review.diff"
  page_buffer "$(notes_key "$k")" "$(git rev-parse --short "${L_HEAD[k]}")"
  keep_layer_notes "$k"
}

# keep_layer_notes <k>: add the notes just taken to layer k's.
keep_layer_notes() {
  [ "${#NOTES[@]}" -gt 0 ] || return 0
  L_NOTES[$1]="${L_NOTES[$1]:+${L_NOTES[$1]}$'\n'}$(printf '%s\n' "${NOTES[@]}")"
}

# layer_diff <k>: layer k's whole diff: its log and its diff against the
# layer below it.
layer_diff() {
  local k="$1" below=main head base sha on
  [ "$k" -eq 0 ] || below="${L_NAME[k - 1]}"
  head="${L_HEAD[k]}" base="${L_BASE[k]}"
  sha="$(git rev-parse --short "$head")"
  on="$below at $(git rev-parse --short "$base")"
  if [ "${L_KIND[k]}" = branch ]; then
    printf 'branch %s, log against %s:\n\n' "${L_NAME[k]}" "$on"
  elif [ -n "${L_BRANCH[k]}" ]; then
    printf 'change %s v%s at %s, on branch %s, log against %s:\n\n' \
      "${L_NAME[k]}" "${L_VERSION[k]}" "$sha" "${L_BRANCH[k]}" "$on"
  else
    printf 'change %s v%s at %s, log against %s:\n\n' "${L_NAME[k]}" "${L_VERSION[k]}" "$sha" "$on"
  fi
  git --no-pager log --oneline "$base..$head"
  printf '\n'
  git --no-pager diff "$base...$head"
}

# Show each layer under the top and ask after each, naming the layer and
# its place: [n]ext layer goes on to the layer above, [a]pprove approves
# that layer at the head shown, which lands it and every layer under it,
# as the prompt names them, [v]iew full diff pages the layer's whole diff,
# and [s]top ends the review. [r]eject is not offered under the top:
# deleting a lower layer's branch would leave the layers above still
# holding it. [a]pprove is not offered at or above a layer that is not
# ready, and the prompt says why in its place (layer_held). After the
# top, its verdict is taken as for any change, with a prompt that names
# the top and says approving it lands all n.
review_stack() {
  local n top k choice answers failed lands held
  summarize_stack
  base_stack || return 0
  printf '\n'
  n="${#L_NAME[@]}" top=$((${#L_NAME[@]} - 1))
  for ((k = 0; k < top; k++)); do
    layer_skipped "$k" && continue
    page_layer "$k"
    case "$k" in
      0) lands="${L_NAME[0]} alone" ;;
      1) lands="${L_NAME[0]} and ${L_NAME[1]}" ;;
      *) lands="the $((k + 1)) up to ${L_NAME[k]}" ;;
    esac
    held="$(layer_held "$k")" || held=""
    while true; do
      failed=""
      [ "$CHECKS_FAILED_AT" != "${L_HEAD[k]}" ] || failed="$(git rev-parse --short "${L_HEAD[k]}")"
      if [ -n "$held" ]; then
        printf '%s, %d of %d: %s [n]ext layer, [v]iew full diff, [s]top? ' \
          "${L_NAME[k]}" "$((k + 1))" "$n" "$held"
        answers="n, v, or s"
      elif [ -n "$failed" ]; then
        printf '%s, %d of %d: its checks failed at %s, so approving needs a new head: [n]ext layer, [v]iew full diff, [s]top? ' \
          "${L_NAME[k]}" "$((k + 1))" "$n" "$failed"
        answers="n, v, or s"
      else
        printf '%s, %d of %d: [n]ext layer, [a]pprove %s, [v]iew full diff, [s]top? ' \
          "${L_NAME[k]}" "$((k + 1))" "$n" "$lands"
        answers="n, a, v, or s"
      fi
      read -r choice || die "stdin closed before an answer; nothing done"
      case "$choice" in
        n) break ;;
        a)
          if [ -n "$failed" ] || [ -n "$held" ]; then
            echo "answer $answers"
            continue
          fi
          use_layer "$k"
          if moved || approve "$CHANGE_BRANCH"; then
            return
          fi
          use_layer "$top"
          ;;
        v) view_layer "$k" ;;
        s)
          echo "stopped reviewing ${L_NAME[top]} at change $((k + 1)) of $n, ${L_NAME[k]}; nothing done"
          return
          ;;
        *) echo "answer $answers" ;;
      esac
    done
  done
  page_layer "$top"
  use_layer "$top"
  decide "${L_BRANCH[top]}" "${L_NAME[top]}" "$n"
}

# The notes taken on every layer, each under its own branch.
print_stack_notes() {
  local k
  for ((k = 0; k < ${#L_NAME[@]}; k++)); do
    [ -n "${L_NOTES[k]}" ] || continue
    mapfile -t NOTES <<< "${L_NOTES[k]}"
    print_notes "$(notes_key "$k")"
  done
}

cmd_review() {
  local name="" verbose=() arg
  local usage="usage: valley review [-v] [--build-here] <change>"
  for arg in "$@"; do
    case "$arg" in
      -v) verbose=(-v) VERBOSE=yes ;;
      --build-here) BUILD_HERE=yes ;;
      -*) die "$usage" ;;
      *)
        [ -z "$name" ] || die "$usage"
        name="$arg"
        ;;
    esac
  done
  [ -n "$name" ] || die "$usage"
  set -- "$name"
  REVIEWING=yes
  resolve_change "$1" || exit 1
  need_branch review
  local branch="$CHANGE_BRANCH"
  TOP_NAME="$1"
  fetch_origin
  ref_oid "refs/remotes/origin/$branch" >/dev/null \
    || die "no such branch on origin: $branch"
  bind_review
  trap cleanup_scratch EXIT
  trap 'exit 130' INT TERM
  # The verdict disposes of the change; the notes are what the human made
  # of it, so they are printed whatever the verdict was. A stack that
  # cannot be read is reviewed whole against main, as a change with
  # nothing under it is.
  if ! read_stack; then
    printf 'valley: warning: the stack under %s could not be read; reviewing it whole, against main\n' "$1" >&2
    L_NAME=()
  fi
  read_does "${verbose[@]}"
  if [ "${#L_NAME[@]}" -gt 1 ]; then
    review_stack
    print_stack_notes
  else
    read_and_decide "$branch"
    print_notes "$branch"
  fi
}

# approve and rebase are review's [a]pprove and [b]ase onto main without
# the pager, for a front end that has shown the change its own way. Each
# runs the code its key runs, approve and valley-go rebase, so the verb and
# the key cannot drift apart. A change is named as resolve_change reads
# it, and rebase reads its name the same way, in valley-go.
#
# 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, as the fetch
# left it, and --head, when given, must be that tip. --build-here, here and
# on review, lets approve build the nix checks origin holds no evidence
# for (approve_attempt).
cmd_approve() {
  local name="" want=""
  local usage="usage: valley approve [-v] [--head <sha>] [--build-here] <change>"
  while [ $# -gt 0 ]; do
    case "$1" in
      --build-here)
        BUILD_HERE=yes
        shift
        ;;
      -v | --verbose)
        VERBOSE=yes
        shift
        ;;
      --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="$(ref_oid "refs/remotes/origin/$branch")" \
      || die "no such branch on origin: $branch"
    if [ -n "$want" ] && [ "$(git rev-parse --verify --quiet "$want^{commit}" || true)" != "$tip" ]; then
      declined "origin/$branch is at $(git rev-parse --short "$tip"), not $want" \
        --run "valley approve $(printf '%q' "$branch")"
      exit 1
    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
}

# join_by <separator> <word…>: the words joined by the separator.
join_by() {
  local IFS="$1"
  shift
  printf '%s' "$*"
}

# The two flags that say what a transfer statement is verified with are
# valley-go's, and pass through to it untouched.
cmd_rebase() {
  local usage="usage: valley rebase [--known-signers <file>] [--integrator-name <name>] <change>"
  local name="" verify=()
  while [ $# -gt 0 ]; do
    case "$1" in
      --known-signers | --integrator-name)
        [ $# -ge 2 ] || die "$usage"
        verify+=("$1" "$2")
        shift 2
        ;;
      --known-signers=* | --integrator-name=*)
        verify+=("$1")
        shift
        ;;
      -*) die "$usage" ;;
      *)
        [ -z "$name" ] || die "$usage"
        name="$1"
        shift
        ;;
    esac
  done
  [ -n "$name" ] || die "$usage"
  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"
  fetch_origin
  VALLEY_TELEMETRY_SINCE="$TEL_T0" VALLEY_TELEMETRY_VERSION="$VALLEY_STAMP" \
    exec valley-go rebase "${verify[@]}" "$name"
}

# 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 policy
# requires of the change, 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, per class's carry mode, 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. A class's carry mode is the
# one the schema resolves (`_mode`), so the shell only picks the strictest.
#
# Each line is held to its shape (`line`): three fields, two tabs, and no
# other control character. A newline in a field would end its line and
# start one of the policy's choosing, and a tab would add a field. The
# schema already refuses control characters in every string rendered here,
# so this is a second wall: a line out of shape fails the render, and the
# deriver refuses a render that fails. The whole line is checked because a
# bound on a value inside an interpolation does not fail the string.
#
# 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 required checks
# needs their cost. `checks` reads only the cost, to group the required
# checks by it; approve turns the rest into the arguments attest is given.
render_cue() {
  cat <<'EOF'
package verification

import (
	"list"
	"strings"
)

let line = =~"^[^\\x00-\\x1f\\x7f]+\t[^\\x00-\\x1f\\x7f]+\t[^\\x00-\\x1f\\x7f]+$"

_render: strings.Join(list.Concat([[
	for cn, c in policy.classes
	for p, on in c.paths if on {"path\t\(cn)\t\(p)" & line}
], [
	for cn, c in policy.classes
	for k, on in c.requires if on {"requires\t\(cn)\t\(k)" & line}
], [
	for k, on in policy.unclassified if on {"requires\tunclassified\t\(k)" & line}
], [
	for cn, m in _mode {"carry\t\(cn)\t\(m)" & line}
], [
	for n, c in policy.checks {"runner\t\(n)\t\(c.runner)" & line}
], [
	for n, c in policy.checks if c.runner == "nix" {"attribute\t\(n)\t\(c.attribute)" & line}
], [
	for n, c in policy.checks if c.runner == "command" {"command\t\(n)\t\(c.command)" & line}
], [
	for n, c in policy.checks {"cost\t\(n)\t\(c.cost)" & line}
]]), "\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 required, 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 ]
}

# target_label <ref> <tip>: the ref whose tip supplies the policy, printed
# the way a person names it, with the commit it stood at when it was read.
# 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
# tip 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 "$2")" || return 1
  ref="${ref#refs/remotes/}"
  ref="${ref#refs/heads/}"
  printf '%s %s' "$ref" "$short"
}

# resolve_project_layer <root> <target ref> <target tip>: 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. The tip is the object ID
# the target ref held when it was read, and the layer is read at it.
#
# 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_required
# does: a refusal inside the review loop is not the end of the session.
resolve_project_layer() {
  local root="$1" target="$3" rc at

  at="$(target_label "$2" "$target")" || {
    refuse "could not read $2; 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_instance_layer <root> <target ref> <target tip>: 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. The tip is the object ID the target
# ref held when it was read, and the pointer is read at it.
#
# 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_required
# does: a refusal inside the review loop is not the end of the session.
resolve_instance_layer() {
  local root="$1" target="$3" url bare dest rc at listing valley_tip
  at="$(target_label "$2" "$target")" || {
    refuse "could not read $2; 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
  }
  # The valley's main is read by its exact name, and fetched by the object
  # it names. Given a ref name the valley lacks, fetch takes another ref
  # whose name ends in it, such as refs/heads/refs/heads/main. ls-remote
  # lists such a ref too, so each line it lists is compared whole.
  listing="$(git -C "$bare" ls-remote "$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
  }
  valley_tip="$(printf '%s\n' "$listing" | awk -v r="$VALLEY_POINTER_REF" '$2 == r { print $1 }')"
  [ -n "$valley_tip" ] || {
    cleanup_instance_tmp
    refuse "the owning valley $url has no $VALLEY_POINTER_REF (named by $VALLEY_POINTER at $at); nothing derived"
    return 1
  }
  git -C "$bare" fetch --quiet --depth 1 "$url" "$valley_tip" || {
    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" "$valley_tip" "$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 required.
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 bytewise, into the array the first one
# names. The order is the C locale's whatever the caller's is, as it is
# throughout the derivation (derive_required). 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 required checks that is a
# change that requires 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' "$@" | LC_ALL=C 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.
#
# It sets TARGET_REF to the ref, and TARGET_TIP to the object ID it held
# when it was read (ref_oid). The merge base and both layers are read at
# TARGET_TIP, so they are read at one commit, and never through a name git
# would take another ref for.
#
# Only a ref that is not there falls through to the next. 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=""
TARGET_TIP=""
target_ref() {
  local ref rc
  for ref in refs/remotes/origin/main refs/heads/main; do
    TARGET_TIP="$(ref_oid "$ref")" && rc=0 || rc=$?
    case "$rc" in
      0) TARGET_REF="$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.
#
# The derivation runs in the C locale, whatever locale its caller runs in,
# so a glob matches bytes and every list sorts bytewise. Under a UTF-8
# locale bash's regular expressions read characters instead: `?` matches é,
# and a path holding a byte that is not UTF-8 matches no pattern at all,
# not even `**`, so it would fall to `unclassified`. sort -u under
# en_US.UTF-8 also merges distinct paths that collate equally. Which checks
# a change requires would then depend on the locale of whoever derives it:
# an operator's shell for approve, the integrator's unit for the integrator.
# The Go deriver (derive/) matches bytes too, and its tests hold the two to
# the same answer under UTF-8 locales.
#
# 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 requires 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_UNCLASSIFIED=0  # whether `unclassified` requires something
DERIVED_CARRY=""        # the strictest carry mode among the matched classes
declare -A DERIVED_REQUIRED=() # 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_required() {
  local schema="$1" instance="$2" project="$3" base="$4" head="$5"
  # Exported, so sort and every other program the derivation runs reads
  # bytes too; bash restores the caller's locale when this returns.
  local -x LC_ALL=C

  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 requires nothing. A
  # schema older than this script fails it, by lacking a field it reads. So
  # does a policy string holding a control character, which a schema that
  # admits one lets through.
  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, and a policy string holding a control character, are two causes); 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_REQUIRED \
    DERIVED_PINNED
  declare -gA CHECK_RUNNER=() CHECK_ATTRIBUTE=() CHECK_COMMAND=() \
    CHECK_COST=() DERIVED_REQUIRED=() 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.
  #
  # The render states each thing once: a class has one carry mode, a check
  # one runner, and a class requires a check once. A second line for the
  # same thing is forged, and a reader that took the last one would let the
  # forgery win, so it is refused. A coverage or requirement line is one
  # member of a set, so it is identified by its value too.
  local -a pat_class=() pat_ere=() req_class=() req_check=()
  local -A class_carry=() seen=()
  local line kind key value id
  for line in "${rendered[@]}"; do
    kind="${line%%$'\t'*}"
    key="${line#*$'\t'}"
    value="${key#*$'\t'}"
    key="${key%%$'\t'*}"
    case "$kind" in
      path | requires) id="$kind $key $value" ;;
      *) id="$kind $key" ;;
    esac
    [ -z "${seen[$id]:-}" ] || {
      refuse "the composed policy rendered '$id' twice, and states each thing once; nothing derived"
      return 1
    }
    seen["$id"]=1
    case "$kind" in
      path)
        pat_class+=("$key")
        pat_ere+=("$(glob_ere "$value")")
        ;;
      requires)
        req_class+=("$key")
        req_check+=("$value")
        ;;
      carry) class_carry["$key"]="$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

  # The change's carry mode: the strictest among the classes its paths
  # matched, each as the schema resolved it. It is taken before
  # `unclassified` joins the matched classes, because an unclassified path
  # is same-paths and can make no change stricter. A matched class with no
  # mode this script knows is refused rather than read as the loosest.
  local class
  DERIVED_CARRY=same-paths
  for class in "${!matched[@]}"; do
    case "${class_carry[$class]:-}" in
      exact) DERIVED_CARRY=exact ;;
      same-class) [ "$DERIVED_CARRY" = exact ] || DERIVED_CARRY=same-class ;;
      same-paths) ;;
      *)
        refuse "class $class has no carry mode this script knows ('${class_carry[$class]:-}'); nothing derived"
        return 1
        ;;
    esac
  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_UNCLASSIFIED=0
  for ((i = 0; i < ${#req_check[@]}; i++)); do
    key="${req_class[i]}"
    check="${req_check[i]}"
    [ -n "${matched[$key]:-}" ] || continue
    [ "$key" != unclassified ] || DERIVED_UNCLASSIFIED=1
    DERIVED_REQUIRED["$check"]="${DERIVED_REQUIRED[$check]:+${DERIVED_REQUIRED[$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_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"
    }
    target="$TARGET_REF"
  fi
  if [ $# -ge 1 ]; then
    base="$(git rev-parse --verify --quiet "$1^{commit}")" \
      || die "no such commit: $1"
  else
    base="$(git merge-base "$TARGET_TIP" "$head")" \
      || die "$head and ${target#refs/} do not share history — name a base"
  fi

  trap 'tel_command $?; 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" "$TARGET_TIP" || exit 1
    instance="$POLICY_INSTANCE"
    label="$POLICY_INSTANCE_LABEL"
  fi
  if [ -n "$project" ]; then
    plabel="${project#"$root"/}"
  else
    resolve_project_layer "$root" "$target" "$TARGET_TIP" || exit 1
    project="$POLICY_PROJECT"
    plabel="$POLICY_PROJECT_LABEL"
  fi
  derive_required "$schema" "$instance" "$project" "$base" "$head" || exit 1

  # The required checks, sorted, and grouped by the cost the policy
  # declares. The grouping changes nothing required: approve runs every
  # required check, and the integrator requires evidence for every one,
  # whatever it costs.
  local check width=0
  local -a required=() quick=() slow=() listed=()
  sort_into required "${!DERIVED_REQUIRED[@]}" \
    || die "could not sort the required checks; nothing derived"
  for check in "${required[@]}"; 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=("${required[@]}") ;;
    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'
  else
    printf 'classes matched: %s\n' \
      "$(printf '%s\n' "${DERIVED_MATCHED[@]}" | join_lines)"
  fi
  # How far an approval of this change carries across a rebase. Nothing
  # here acts on it.
  printf 'carry mode: %s\n\n' "$DERIVED_CARRY"

  if [ "${#DERIVED_REQUIRED[@]}" -eq 0 ]; then
    echo "required checks: none"
  else
    echo "required checks:"
    for check in "${required[@]}"; do
      printf '  %-*s  %-9s  %s\n' \
        "$width" "$check" "${DERIVED_PINNED[$check]}" "${DERIVED_REQUIRED[$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_UNCLASSIFIED" -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 [ "${#required[@]}" -gt 0 ]; then
    printf '\nquick: %s\n' "$(join_or_none "${quick[@]}")"
    printf 'slow: %s\n' "$(join_or_none "${slow[@]}")"
  fi
}

# self-update installs the tip of a branch of the-valley into the user's
# nix profile (status/selfupdate.go). It is told this valley's stamp, which
# says what is installed until it has installed something itself.
cmd_self_update() {
  export VALLEY_VERSION="$VALLEY_STAMP"
  cmd_go self-update "$@"
}

cmd_version() {
  printf 'valley %s\n' "${VALLEY_STAMP:-unstamped (run from a checkout, not built by nix)}"
}

cmd_help() {
  [ $# -le 1 ] || die "usage: valley help [<verb>]"
  local out
  case "${1:-}" in
    '' | help | -h | --help) out="$(usage)" ;;
    pending) out="$(help_pending)" ;;
    changes) out="$(help_changes)" ;;
    review) out="$(help_review)" ;;
    approve) out="$(help_approve)" ;;
    rebase) out="$(help_rebase)" ;;
    status) out="$(help_status)" ;;
    ready) out="$(help_ready)" ;;
    unready) out="$(help_unready)" ;;
    withdraw) out="$(help_withdraw)" ;;
    knot) out="$(help_knot)" ;;
    plan) out="$(help_plan)" ;;
    checks) out="$(help_checks)" ;;
    tail) out="$(help_tail)" ;;
    replay) out="$(help_replay)" ;;
    self-update) out="$(help_self_update)" ;;
    telemetry) out="$(help_telemetry)" ;;
    *) die "unknown help topic: $1 (try 'valley help')" ;;
  esac
  printf '%s\n' "$out" 2> /dev/null || true
}

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 | changes | review | approve | rebase | status | ready | unready | withdraw | knot | plan | checks | tail | replay | self-update | telemetry)
      if [ $# -eq 1 ] && { [ "$1" = -h ] || [ "$1" = --help ]; }; then
        cmd_help "$verb"
        return
      fi
      ;;
  esac
  case "$verb" in
    review | approve | checks | tail | replay)
      TEL_ARGS=("$verb" "$@")
      trap 'tel_command $?' EXIT
      ;;
  esac
  case "$verb" in
    pending) cmd_pending "$@" ;;
    review) cmd_review "$@" ;;
    approve) cmd_approve "$@" ;;
    rebase) cmd_rebase "$@" ;;
    status | ready | unready | withdraw | changes | knot | plan) cmd_go "$verb" "$@" ;;
    checks) cmd_checks "$@" ;;
    tail) cmd_tail "$@" ;;
    replay) cmd_replay "$@" ;;
    self-update) cmd_self_update "$@" ;;
    telemetry) cmd_go telemetry "$@" ;;
    --version) cmd_version ;;
    help | -h | --help) cmd_help "$@" ;;
    *)
      printf 'valley: unknown verb: %s\n\n' "$verb" >&2
      usage >&2
      exit 1
      ;;
  esac
}

main "$@"
