#!/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>
       valley review [-v] [--build-here] [--repo <name>]

  review [-v] [--build-here] [--repo <name>]
                   with no change, review each change that needs you, as
                   valley pending --all lists them, in landing order, or
                   those of the project --repo names. each step opens
                   with `[1/3] <project> · <handle> v<N> · <checks>` and
                   is the review below, run where the project is read:
                   this checkout, or the clone valley keeps of another
                   project, lent this checkout's valley.principal,
                   user.name and user.email. a change that landed, is
                   not ready or has no branch since is not reviewed; one
                   at a new version is reviewed at it. the walk ends with
                   each change's outcome and what still needs you. a
                   project that did not read is said first and last. a
                   change in a project whose main names another valley
                   ends in error: review it from that valley's checkout.
                   ctrl-c or SIGTERM ends the walk with what it walked,
                   exit 130.

  review [-v] [--build-here] <change>
                   page through the change's branch: its log, with each
                   commit's whole message, 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. its
                   first line says what changed since you approved v<m>:
                     `<change> v<n> at <head>: rebased since you approved
                     v<m> at <old head>, with the same file changes.`
                   each version's diff from its merge base with main
                   changes the same files the same way (valley-delta-v1).
                   review prints the commits main landed between the
                   bases, and pages nothing.
                     `... rebased since you approved v<m> at <old head>.`
                   the commits are the same patches, messages and
                   authors, but main also edited files the change edits.
                   review pages each file whose change differs, with the
                   landings that edited it, then the shown version's diff
                   of those files.
                     `... edited since you approved v<m> at <old head>.`
                   a commit's patch, message or author differs. review
                   pages how many commits changed, the files whose change
                   differs with the landings that edited them, git
                   range-diff of the two versions, and the shown
                   version's diff of those files, or prints a changed
                   message or author when the files are the same. -v adds
                   each file's mode and SHA-256 in each version. on a
                   terminal, unless NO_COLOR is set, the title, the
                   section headings and the hashes are styled; the buffer
                   the editor opens is plain. 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 review 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, and acts on nothing
                   unless you approve a new version it offers:
                     `<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>) · [a]pprove v<n>, [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.
                     v<n> is v<m> rebased onto the new main with no
                     other changes, so your approval covers it.`
                   and [a]pprove files v<m>, the head shown. its verdict
                   names v<n>, which lands, with v<n>'s checks. otherwise
                   <why> says whether the change's commits changed or
                   only main moved under them, and why the answer does
                   not carry. with its commits unchanged, [a]pprove v<n>
                   is offered at once; with a commit changed, only after
                   [v]iew. [a] files v<n>'s head, and is refused if the
                   change moves again first.
                   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 set against an approved version a
                   note keeps its file and line only in the section
                   headed `── v<n>'s diff of these files against main`. 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. approve never 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] | --json] [<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, whatever your locale
                   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`
                     --json           print the valley-checks/v1 document
                                      instead of the report
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
}

# pending is valley-go's (status/pending.go). The fetch first keeps this
# checkout's remote-tracking branches current, as pending always has.
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_TELEMETRY_SINCE="$TEL_T0" VALLEY_TELEMETRY_VERSION="$VALLEY_STAMP" \
    exec valley-go pending "$@"
}

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

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

# review is valley-go's (status/review.go). With no change it walks what
# needs the operator, reviewing each change in the same process
# (status/walk.go).
cmd_review() {
  command -v valley-go > /dev/null 2>&1 \
    || die "review needs the valley-go helper; nix run .#valley bundles it"
  VALLEY_TELEMETRY_SINCE="$TEL_T0" VALLEY_TELEMETRY_VERSION="$VALLEY_STAMP" \
    exec valley-go review "$@"
}

# approve is review's [a]pprove without the pager, for a front end that
# has shown the change its own way: valley-go approve (status/approve.go),
# the code the key runs, so the verb and the key cannot drift apart. It
# resolves the change before the fetch, as review does.
cmd_approve() {
  command -v valley-go > /dev/null 2>&1 \
    || die "approve needs the valley-go helper; nix run .#valley bundles it"
  VALLEY_TELEMETRY_SINCE="$TEL_T0" VALLEY_TELEMETRY_VERSION="$VALLEY_STAMP" \
    exec valley-go approve "$@"
}

# rebase is review's [b]ase onto main without the pager. It runs the code
# its key runs, valley-go rebase, and reads a change's name as review
# reads it. 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 checks the verification policy requires of a change, and
# the classes requiring each. The verb is valley-go's (status/checks.go):
# it reads the policy's layers and derives with the Go deriver (derive/).
cmd_checks() {
  command -v valley-go > /dev/null 2>&1 \
    || die "checks needs the valley-go helper; nix run .#valley bundles it"
  VALLEY_TELEMETRY_SINCE="$TEL_T0" VALLEY_TELEMETRY_VERSION="$VALLEY_STAMP" \
    exec valley-go checks "$@"
}

# 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
    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 "$@"
