#!/usr/bin/env bash
# valley — the S1 integrator's verbs, as a plain shell script.
#
# EVICTION CLAUSE (owner-ratified; the decision node is
# .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, and again by review's [a]sk, which
#     needs the attest helper —
#     graduation is now owed; recording the decision node is part of taking it.);
#   - its behavior gets subtle enough to need real tests
#     (CROSSED by checks: glob matching is pinned by the policy-deriver
#     flake check, not by reading the code.);
#   - it needs nontrivial parsing or concurrency
#     (CROSSED by checks: glob-to-regex translation and -z diff parsing.).
# The size tripwire (~300 lines) is crossed too. Which way to take the
# graduation is dcr-2aa1a12, still `proposed`.
# Graduation is a deliberate act, recorded as a decision node.
# Precedent: klaus — born in cosmo, graduated deliberately.

set -euo pipefail

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

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

usage: valley <verb> [args]

  pending          list branches on origin not merged into origin/main
  review <branch>  page through the branch's log and diff vs origin/main,
                   then choose:
                     [a]sk        file an integration request. runs the
                                  checks the composed policy requires of
                                  this change over a throwaway worktree of
                                  the branch, signs each result as an
                                  attestation, and publishes the evidence
                                  and the request ref to origin in ONE
                                  atomic push. main is never touched: the
                                  integrator judges the request and lands
                                  it. needs the attest helper and
                                  VALLEY_ATTEST_KEY, the ed25519 key this
                                  host signs with; VALLEY_ATTEST_NAME is
                                  the name it signs under, defaulting to
                                  this host's.
                     [i]ntegrate  ff-only merge onto main, push origin main,
                                  delete the merged branch from origin
                     [r]eject     delete the remote branch (confirmed first)
                     [s]kip       do nothing
                   [a]sk and [i]ntegrate are the two ways a change reaches
                   main, and both stay: [i] writes the protected ref here,
                   [a] asks the integrator to write it. Nothing here knows
                   or asks which of the two the operator is entitled to —
                   origin answers that.
                   a stale branch (won't fast-forward from main) is first
                   offered:
                     [b]ase       rebase it onto origin/main in a throwaway
                                  worktree, push --force-with-lease, then
                                  re-review the diff that would actually land
                   [a]sk is offered there too: a stale branch is nothing
                   the integrator cannot apply, so it need not be rebased
                   first.
                   while paging, press v: less opens the diff in $EDITOR.
                   every line you insert there is a note. it is anchored to
                   the file and new-side line it sits on — to the file alone
                   when it sits above the first hunk — then appended to
                   $XDG_STATE_HOME/valley/notes/<branch>.md (default
                   ~/.local/state) and printed after the verdict. notes
                   survive [b]ase. lines you change or delete instead of
                   inserting are ignored, with a warning.
  checks [<base> [<head>]]
                   print the check names the change between two commits owes
                   under the composed verification policy (dcr-f41f718), and
                   which class made each one required. It prints: no check is
                   run, nothing is gated, nothing is written.
                   base defaults to the merge base with main, head to HEAD.
                   the policy layers are not discovered — they are named:
                     --schema FILE    default schema/verification.cue
                     --instance DIR   default examples/policy/instance
                     --project DIR    default examples/policy/project
                   all three relative to the repository root.
  tail [subject]   watch bus events scroll by (default subject: valley.>);
                   the server comes from the nats CLI's own config
                   (NATS_URL or a nats context; default localhost)
  replay [dir]     publish one ref-updated event per current ref of the
                   repo at dir (default: .) — rebuilds the stream's
                   projection, e.g. after nats stream purge valley
  help             show this help

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, and
review's [a]sk, which needs both the cue CLI and the attest helper.
No config, no batch mode, and no state but the notes file — the judgment
stays with the human.
EOF
}

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

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

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

pending_line() {
  local ref="$1" age author ahead stat
  age="$(git log -1 --format='%cr' "$ref")"
  author="$(git log -1 --format='%an' "$ref")"
  ahead="$(git rev-list --count "origin/main..$ref")"
  stat="$(git diff --shortstat "origin/main...$ref")"
  stat="${stat# }"
  printf '%s | %s | %s | ahead %s | %s\n' \
    "${ref#origin/}" "$age" "$author" "$ahead" "${stat:-no file changes}"
}

cmd_pending() {
  [ $# -eq 0 ] || die "pending takes no arguments"
  fetch_origin
  local ref found=0
  while IFS= read -r ref; do
    case "$ref" in
      origin/HEAD | origin/main) continue ;;
    esac
    found=1
    pending_line "$ref"
  done < <(git for-each-ref --format='%(refname:short)' \
    --no-merged=origin/main refs/remotes/origin)
  [ "$found" -eq 1 ] || echo "nothing pending"
}

integrate() {
  local branch="$1" local_main origin_main
  local_main="$(git rev-parse --verify --quiet refs/heads/main)" \
    || die "no local main branch to fast-forward — nothing merged"
  origin_main="$(git rev-parse refs/remotes/origin/main)"
  [ "$local_main" = "$origin_main" ] \
    || die "local main is not at origin/main — sync it first; nothing merged"
  git merge-base --is-ancestor refs/heads/main "refs/remotes/origin/$branch" \
    || die "$branch does not fast-forward from main — resolve by hand; nothing merged"
  git checkout --quiet main
  git merge --ff-only --quiet "refs/remotes/origin/$branch"
  git push --quiet origin main
  echo "integrated $branch: main is now $(git rev-parse --short main), pushed to origin"
  # The branch tip is now an ancestor of the main just pushed, so deleting it
  # loses nothing; without this every integration leaves a fully-merged ghost
  # ref that later reads as a confusing "empty" branch. Best-effort: a failed
  # delete must not report the integration as failed.
  if git push --quiet origin --delete "$branch"; then
    echo "deleted merged branch $branch from origin"
  else
    printf 'valley: warning: could not delete origin/%s — delete it by hand\n' \
      "$branch" >&2
  fi
}

reject() {
  local branch="$1" answer
  printf 'really delete origin/%s? [y/N] ' "$branch"
  read -r answer || answer=""
  case "$answer" in
    y | Y | yes)
      git push --quiet origin --delete "$branch"
      echo "rejected $branch: deleted from origin"
      ;;
    *) echo "kept $branch" ;;
  esac
}

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

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

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

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

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

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

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

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

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

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

show_review() {
  local branch="$1" sha
  sha="$(git rev-parse --short "refs/remotes/origin/$branch")"
  REVIEW_TMP="$(mktemp -d)"
  {
    printf 'branch %s, log against origin/main:\n\n' "$branch"
    git --no-pager log --oneline "origin/main..origin/$branch"
    printf '\n'
    git --no-pager diff "origin/main...origin/$branch"
  } > "$REVIEW_TMP/review.diff"
  cp "$REVIEW_TMP/review.diff" "$REVIEW_TMP/review.orig"
  page_file "$REVIEW_TMP/review.diff" || true # quitting the pager early is not an error
  collect_notes "$branch" "$sha"
  cleanup_review_tmp
}

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

# Everything review leaves outside the repository: the two throwaway
# worktrees, the paged buffer, and the scratch the policy deriver writes
# into. One handler, installed once by cmd_review, so that no path through
# the verb — and no ctrl-C in the pager — leaves any of them behind.
cleanup_review() {
  cleanup_rebase_wt
  cleanup_ask_wt
  cleanup_policy_tmp
  cleanup_review_tmp
}

# Rebase origin/<branch> onto origin/main in an isolated worktree — the
# user's checkout is never touched — and push with a lease so a concurrently
# updated branch is never clobbered. Mechanics only; the judgment on the
# rebased diff stays with the human, back at the review prompt.
rebase_onto_main() {
  local branch="$1"
  REBASE_WT="$(mktemp -d)"
  git worktree add --quiet --detach "$REBASE_WT" "refs/remotes/origin/$branch"
  if ! git -C "$REBASE_WT" rebase --quiet refs/remotes/origin/main; then
    cleanup_rebase_wt
    die "$branch conflicts with main — resolve by hand; nothing changed"
  fi
  if ! git -C "$REBASE_WT" push --quiet --force-with-lease \
    origin "HEAD:refs/heads/$branch"; then
    cleanup_rebase_wt
    die "lease on origin/$branch failed (it moved since the fetch); nothing pushed"
  fi
  cleanup_rebase_wt
  echo "rebased $branch onto origin/main, pushed with --force-with-lease"
}

# ----------------------------------------------------------------------
# ask — file an integration request for the branch under review.
#
# [i]ntegrate is the operator moving the protected ref themself. [a]sk is
# the same keystroke over the machine path: 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
# (design/integration.md). main is never touched from here.
#
# The two coexist, and this script never asks which one the operator is
# entitled to. Whether the operator may write a protected ref is a fact
# about origin's pre-receive hook, and origin is where it is answered.
#
# 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 asked to land. So this verb does not
# use --push at all. `attest run` without it stores each note at its ref in
# the repository and stops, and one `git push --atomic` then carries the
# evidence and the request together — all of it or none of it. Nothing in
# attest had to change for that; the sequencing was the whole of it.
#
# The branch itself is not in that push. What is under review is
# origin/<branch>, so the commit the request names is already on origin and
# the objects with it.

# The tree the checks run over: a throwaway worktree of the branch, as
# [b]ase uses, so that what is checked is the branch's tree and not the
# operator's working copy. A global, so the traps clean it up whatever
# happens.
ASK_WT=""
cleanup_ask_wt() {
  [ -n "$ASK_WT" ] || return 0
  git worktree remove --force "$ASK_WT" > /dev/null 2>&1 || true
  rm -rf "$ASK_WT"
  ASK_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.
refuse() {
  printf 'valley: %s\n' "$*" >&2
  return 1
}

# The change segment of a request ref. The integrator reads a request as
# <prefix>/<target>/<change> and refuses a change segment holding a slash
# (integrator/refs.go), so a branch name with one is written with dashes
# instead. The ref that results is printed, never left to be assumed.
change_name() {
  printf '%s' "${1//\//-}"
}

# File the request. Called from the review prompt in a condition, 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.
ask() {
  local branch="$1" target=main change head base digest root ref check spec
  local key="${VALLEY_ATTEST_KEY:-}"
  local -a signer=() owed=() run=() evidence=()

  [ -n "$key" ] || {
    refuse "no signing key: set VALLEY_ATTEST_KEY to the ed25519 key this host attests with. The host signs; nothing published"
    return 1
  }
  [ -f "$key" ] || {
    refuse "no signing key at $key; nothing published"
    return 1
  }
  command -v attest > /dev/null 2>&1 || {
    refuse "this choice needs the attest helper; nix run .#valley bundles it. Nothing published"
    return 1
  }
  signer=(--key "$key")
  [ -z "${VALLEY_ATTEST_NAME:-}" ] || signer+=(--name "$VALLEY_ATTEST_NAME")

  root="$(git rev-parse --show-toplevel)" || {
    refuse "not a git repository; nothing published"
    return 1
  }
  head="$(git rev-parse "refs/remotes/origin/$branch")" || {
    refuse "no such branch on origin: $branch; nothing published"
    return 1
  }
  base="$(git merge-base refs/remotes/origin/main "$head")" || {
    refuse "$branch and main share no history; nothing published"
    return 1
  }
  change="$(change_name "$branch")"
  ref="refs/the-valley/integration-requests/$target/$change"

  # What the change owes, from the policy the project declares. The
  # integrator derives this again on its own side, from the policy at the
  # target's tip — a change never supplies the policy that gates it — so
  # this is the operator's local reading of the same question, and the
  # answer is printed for exactly that reason.
  policy_defaults "$root"
  derive_owed "$POLICY_SCHEMA" "$POLICY_INSTANCE" "$POLICY_PROJECT" \
    "$base" "$head" || return 1
  [ "${#DERIVED_OWED[@]}" -eq 0 ] \
    || mapfile -t owed < <(printf '%s\n' "${!DERIVED_OWED[@]}" | sort)
  [ "${#owed[@]}" -gt 0 ] || {
    refuse "the policy requires no check of $branch — evidence nobody asked for is not a request; nothing published"
    return 1
  }
  for check in "${owed[@]}"; do
    case "${CHECK_RUNNER[$check]:-}" in
      nix) run+=(--check "$check=${CHECK_ATTRIBUTE[$check]}") ;;
      command) run+=(--command "$check=${CHECK_COMMAND[$check]}") ;;
      *)
        refuse "the policy requires $check but does not say how to run it; nothing published"
        return 1
        ;;
    esac
  done

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

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

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

  # The one push: every evidence ref as it stands, and the request ref at
  # the branch's head. --atomic, so a hook that refuses any of them leaves
  # origin exactly as it was.
  local -a push=()
  for spec in "${evidence[@]}"; do push+=("$spec:$spec"); done
  push+=("$head:$ref")
  if ! git push --atomic --quiet origin "${push[@]}"; then
    refuse "origin refused the push; nothing was published there and main is untouched. The evidence is stored locally at:"
    printf '  %s\n' "${evidence[@]}" >&2
    return 1
  fi

  printf '\nrequested %s -> refs/heads/%s\n' "$branch" "$target"
  printf '  request  %s -> %s\n' "$ref" "$(git rev-parse --short "$head")"
  printf '  evidence %s\n' "${evidence[@]}"
  printf '  checks   %s\n' "$(printf '%s\n' "${owed[@]}" | join_lines)"
  printf '  main is untouched; the integrator judges the request and lands it\n'
}

# Page the branch and take the verdict. Split out of cmd_review so that
# every way out of it — integrate, reject, skip — is followed by the notes.
read_and_decide() {
  local branch="$1" choice
  show_review "$branch"
  # A stale branch can't integrate, and its pre-rebase diff is not what would
  # land; offer to rebase it mechanically, then re-review what actually would.
  # [a]sk is offered here as well, because the integrator applies a delta to
  # the tip rather than fast-forwarding: a stale branch is a request it can
  # judge, and rebasing first is a convenience rather than a precondition.
  while ! git merge-base --is-ancestor refs/remotes/origin/main \
    "refs/remotes/origin/$branch"; do
    printf '%s does not fast-forward from main: [a]sk, [b]ase onto main, [r]eject, [s]kip? ' \
      "$branch"
    read -r choice || die "stdin closed before an answer; nothing done"
    case "$choice" in
      a) ask "$branch" && return ;;
      b)
        rebase_onto_main "$branch"
        fetch_origin
        show_review "$branch"
        ;;
      r) reject "$branch" && return ;;
      s)
        echo "skipped $branch; nothing done"
        return
        ;;
      *) echo "answer a, b, r, or s" ;;
    esac
  done
  while true; do
    printf '%s: [a]sk, [i]ntegrate, [r]eject, [s]kip? ' "$branch"
    read -r choice || die "stdin closed before an answer; nothing done"
    case "$choice" in
      # A refusal from ask is not a verdict: it says what it did not do and
      # the prompt comes back, so the branch can still be integrated,
      # rejected or skipped.
      a) ask "$branch" && return ;;
      i) integrate "$branch" && return ;;
      r) reject "$branch" && return ;;
      s)
        echo "skipped $branch; nothing done"
        return
        ;;
      *) echo "answer a, i, r, or s" ;;
    esac
  done
}

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

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

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

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

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

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

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

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

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

import (
	"list"
	"strings"
)

_render: strings.Join(list.Concat([[
	for cn, c in policy.classes
	for p, on in c.paths if on {"path\t\(cn)\t\(p)"}
], [
	for cn, c in policy.classes
	for k, on in c.requires if on {"requires\t\(cn)\t\(k)"}
], [
	for k, on in policy.unclassified if on {"requires\tunclassified\t\(k)"}
], [
	for n, c in policy.checks {"runner\t\(n)\t\(c.runner)"}
], [
	for n, c in policy.checks if c.runner == "nix" {"attribute\t\(n)\t\(c.attribute)"}
], [
	for n, c in policy.checks if c.runner == "command" {"command\t\(n)\t\(c.command)"}
]]), "\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 live in a project following
# the convention (dcr-f41f718). `checks` takes an option for each, so a
# reader can point it anywhere; review's [a]sk does not, because a request
# is filed against the policy the project declares and nowhere else.
POLICY_SCHEMA=""
POLICY_INSTANCE=""
POLICY_PROJECT=""
policy_defaults() {
  POLICY_SCHEMA="$1/schema/verification.cue"
  POLICY_INSTANCE="$1/examples/policy/instance"
  POLICY_PROJECT="$1/examples/policy/project"
}

# 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`.
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
  printf 'package verification\n%s\n' "$field" > "$POLICY_TMP/probe.cue"
  ! 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. -z because a path may contain
# anything but NUL.
diff_paths() {
  local base="$1" head="$2" status path
  while IFS= read -r -d '' status; do
    IFS= read -r -d '' path || die "truncated diff output; nothing derived"
    printf '%s\n' "$path"
    case "$status" in
      R* | C*)
        IFS= read -r -d '' path || die "truncated diff output; nothing derived"
        printf '%s\n' "$path"
        ;;
    esac
  done < <(git diff --no-relative --name-status -M -z "$base" "$head")
}

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

# The ref a branch is derived against, preferring what origin last said.
main_ref() {
  git rev-parse --verify --quiet refs/remotes/origin/main > /dev/null \
    && { echo refs/remotes/origin/main; return; }
  git rev-parse --verify --quiet refs/heads/main > /dev/null \
    && { echo refs/heads/main; return; }
  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, review's [a]sk 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.
DERIVED_PATHS=()     # every side of the diff, sorted
DERIVED_MATCHED=()   # the class names at least one path matched, sorted
DERIVED_UNCOVERED=() # the paths no class covered
DERIVED_OWES=0       # whether `unclassified` is what owes something
declare -A DERIVED_OWED=()    # check -> the classes that required it
declare -A DERIVED_PINNED=()  # check -> mandatory | default
declare -A CHECK_RUNNER=()    # check -> nix | command
declare -A CHECK_ATTRIBUTE=() # check -> the flake check attribute
declare -A CHECK_COMMAND=()   # check -> the command line

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

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

  DERIVED_PATHS=()
  mapfile -t DERIVED_PATHS < <(diff_paths "$base" "$head" | sort -u)

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

  # Sorted once here, so every list below comes out in a stable order.
  local -a rendered=()
  mapfile -t rendered < <(cue eval --out text -e _render \
    "${POLICY_LAYER[@]}" "$POLICY_TMP/render.cue" | sort)

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

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

  local -A matched=()
  local path i hit
  DERIVED_UNCOVERED=()
  for path in "${DERIVED_PATHS[@]}"; do
    hit=0
    for ((i = 0; i < ${#pat_ere[@]}; i++)); do
      if [[ "$path" =~ ${pat_ere[i]} ]]; then
        matched["${pat_class[i]}"]=1
        hit=1
      fi
    done
    [ "$hit" -eq 1 ] || DERIVED_UNCOVERED+=("$path")
  done
  # A path no class covers is answered by the policy's `unclassified` set,
  # which is why it is treated as one more matched class rather than as an
  # absence.
  [ "${#DERIVED_UNCOVERED[@]}" -eq 0 ] || matched[unclassified]=1

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

  DERIVED_MATCHED=()
  [ "${#matched[@]}" -eq 0 ] \
    || mapfile -t DERIVED_MATCHED < <(printf '%s\n' "${!matched[@]}" | sort)
}

cmd_checks() {
  local root schema instance project base head
  root="$(git rev-parse --show-toplevel 2> /dev/null)" \
    || die "not a git repository"
  policy_defaults "$root"
  schema="$POLICY_SCHEMA"
  instance="$POLICY_INSTANCE"
  project="$POLICY_PROJECT"
  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 ;;
      --) shift; break ;;
      -*) die "unknown option: $1" ;;
      *) break ;;
    esac
  done
  [ $# -le 2 ] || die "usage: valley checks [options] [<base> [<head>]]"

  head="$(git rev-parse --verify --quiet "${2:-HEAD}^{commit}")" \
    || die "no such commit: ${2:-HEAD}"
  if [ $# -ge 1 ]; then
    base="$(git rev-parse --verify --quiet "$1^{commit}")" \
      || die "no such commit: $1"
  else
    local against
    against="$(main_ref)" || die "no main branch to derive a base from — name one"
    base="$(git merge-base "$against" "$head")" \
      || die "$head and ${against#refs/} do not share history — name a base"
  fi

  trap cleanup_policy_tmp EXIT
  derive_owed "$schema" "$instance" "$project" "$base" "$head" || exit 1

  local check width=0
  for check in "${!DERIVED_OWED[@]}"; do
    [ "${#check}" -le "$width" ] || width="${#check}"
  done

  printf '%s..%s: %d changed path(s)\n' \
    "$(git rev-parse --short "$base")" "$(git rev-parse --short "$head")" \
    "${#DERIVED_PATHS[@]}"
  printf 'policy: %s + %s\n' "${instance#"$root"/}" "${project#"$root"/}"
  if [ "${#DERIVED_MATCHED[@]}" -eq 0 ]; then
    printf 'classes matched: none\n\n'
  else
    printf 'classes matched: %s\n\n' \
      "$(printf '%s\n' "${DERIVED_MATCHED[@]}" | join_lines)"
  fi

  if [ "${#DERIVED_OWED[@]}" -eq 0 ]; then
    echo "required checks: none"
  else
    echo "required checks:"
    while IFS= read -r check; do
      printf '  %-*s  %-9s  %s\n' \
        "$width" "$check" "${DERIVED_PINNED[$check]}" "${DERIVED_OWED[$check]}"
    done < <(printf '%s\n' "${!DERIVED_OWED[@]}" | sort)
  fi

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

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

main "$@"
