gunk-dev/the-valley

valley

sourced92fe21bcd74main's published tip history
42.9 KiB
1#!/usr/bin/env bash
2# valley — the S1 integrator's verbs, as a plain shell script.
3#
4# EVICTION CLAUSE (owner-ratified; the decision node is
5# .the-valley/decisions/dcr-74c3158-valley-cli-lifecycle.md).
6# This tool is deliberately a shell script: it runs from any checkout with
7# nothing but git and coreutils — no machinery, the portability stance of
8# ida-b9f646c. It GRADUATES to its own repo and a real language the moment
9# ANY tripwire is crossed:
10# - it grows past ~300 lines;
11# - it needs persistent state, config, or a daemon
12# (CROSSED by review's notes, which outlive the session in
13# $XDG_STATE_HOME/valley/notes.);
14# - it needs dependencies beyond git + coreutils
15# (CROSSED by Phase 1's tail/replay, which need the nats CLI, and again
16# by checks, which needs the cue CLI, and again by review's [a]sk, which
17# needs the attest helper —
18# graduation is now owed; recording the decision node is part of taking it.);
19# - its behavior gets subtle enough to need real tests
20# (CROSSED by checks: glob matching is pinned by the policy-deriver
21# flake check, not by reading the code.);
22# - it needs nontrivial parsing or concurrency
23# (CROSSED by checks: glob-to-regex translation and -z diff parsing.).
24# The size tripwire (~300 lines) is crossed too. Which way to take the
25# graduation is dcr-2aa1a12, still `proposed`.
26# Graduation is a deliberate act, recorded as a decision node.
27# Precedent: klaus — born in cosmo, graduated deliberately.
28
29set -euo pipefail
30
31die() {
32 printf 'valley: %s\n' "$*" >&2
33 exit 1
34}
35
36usage() {
37 cat <<'EOF'
38valley — S1 integrator verbs for a valley project (direct-push mode)
39
40usage: valley <verb> [args]
41
42 pending list branches on origin not merged into origin/main
43 review <branch> page through the branch's log and diff vs origin/main,
44 then choose:
45 [a]sk file an integration request. runs the
46 checks the composed policy requires of
47 this change over a throwaway worktree of
48 the branch, signs each result as an
49 attestation, and publishes the evidence
50 and the request ref to origin in ONE
51 atomic push. main is never touched: the
52 integrator judges the request and lands
53 it. needs the attest helper and
54 VALLEY_ATTEST_KEY, the ed25519 key this
55 host signs with; VALLEY_ATTEST_NAME is
56 the name it signs under, defaulting to
57 this host's.
58 [i]ntegrate ff-only merge onto main, push origin main,
59 delete the merged branch from origin
60 [r]eject delete the remote branch (confirmed first)
61 [s]kip do nothing
62 [a]sk and [i]ntegrate are the two ways a change reaches
63 main, and both stay: [i] writes the protected ref here,
64 [a] asks the integrator to write it. Nothing here knows
65 or asks which of the two the operator is entitled to —
66 origin answers that.
67 a stale branch (won't fast-forward from main) is first
68 offered:
69 [b]ase rebase it onto origin/main in a throwaway
70 worktree, push --force-with-lease, then
71 re-review the diff that would actually land
72 [a]sk is offered there too: a stale branch is nothing
73 the integrator cannot apply, so it need not be rebased
74 first.
75 while paging, press v: less opens the diff in $EDITOR.
76 every line you insert there is a note. it is anchored to
77 the file and new-side line it sits on — to the file alone
78 when it sits above the first hunk — then appended to
79 $XDG_STATE_HOME/valley/notes/<branch>.md (default
80 ~/.local/state) and printed after the verdict. notes
81 survive [b]ase. lines you change or delete instead of
82 inserting are ignored, with a warning.
83 checks [<base> [<head>]]
84 print the check names the change between two commits owes
85 under the composed verification policy (dcr-f41f718), and
86 which class made each one required. It prints: no check is
87 run, nothing is gated, nothing is written.
88 base defaults to the merge base with main, head to HEAD.
89 the policy layers are not discovered — they are named:
90 --schema FILE default schema/verification.cue
91 --instance DIR default examples/policy/instance
92 --project DIR default examples/policy/project
93 all three relative to the repository root.
94 tail [subject] watch bus events scroll by (default subject: valley.>);
95 the server comes from the nats CLI's own config
96 (NATS_URL or a nats context; default localhost)
97 replay [dir] publish one ref-updated event per current ref of the
98 repo at dir (default: .) — rebuilds the stream's
99 projection, e.g. after nats stream purge valley
100 help show this help
101
102Runs from any checkout of the project; needs only git and coreutils,
103except tail and replay, which also need the nats CLI (natscli), checks,
104which also needs the cue CLI, review's notes, which need less, and
105review's [a]sk, which needs both the cue CLI and the attest helper.
106No config, no batch mode, and no state but the notes file — the judgment
107stays with the human.
108EOF
109}
110
111fetch_origin() {
112 git fetch --prune --quiet origin
113}
114
115# Resolve the pager as git would for a diff: pager.diff first (per-command
116# pager configs — e.g. home-manager's delta module — set pager.diff and leave
117# core.pager alone), then git var GIT_PAGER (core.pager, GIT_PAGER, PAGER,
118# less). pager.<cmd> may legally be a boolean; treat true/false — and an
119# empty or missing value — as unset and fall back. The value is
120# shell-interpreted, hence sh -c.
121diff_pager() {
122 local pager
123 pager="$(git config --get pager.diff || true)"
124 case "$pager" in '' | true | false) pager="$(git var GIT_PAGER)" ;; esac
125 printf '%s' "$pager"
126}
127
128# Page a file rather than a pipe, so less's v key has something to hand
129# $EDITOR: with a real file open, v runs LESSEDIT, whose default
130# `%E ?lm+%lm. %g` is the editor, +<line>, and the file name. That file is
131# the review buffer, and editing it is how notes get written (see
132# collect_notes). A pipe has no name, so less refuses to edit one — which is
133# why review no longer pipes.
134#
135# The configured diff pager stays the renderer, but as less's input
136# preprocessor rather than as the pager. It still reads the buffer on stdin
137# exactly as it did when it was the pager, less displays what it emits, and
138# less still calls the raw buffer "the current file" — so v edits the diff
139# and not the rendering. The alternative was to page the buffer with no
140# filter at all: exact, and it throws delta's rendering away, which is the
141# worse trade for a verb whose whole job is reading a diff.
142#
143# What this costs is the line number. A filter that restructures the diff —
144# delta's default rendering does — makes %lm a line of the rendered view, so
145# the editor opens near the cursor rather than on it. A structure-preserving
146# filter (pager.diff = `delta --color-only`) makes it exact. No anchor
147# depends on it: a note is anchored by where it was inserted, not by where
148# the editor opened.
149page_file() {
150 local file="$1" pager
151 [ -t 1 ] || { cat -- "$file"; return; } # a non-tty just cats
152 pager="$(diff_pager)"
153 case "${pager%%[[:space:]]*}" in
154 less | */less)
155 # Already less: give it the file and there is no filter to run.
156 sh -c "$pager \"\$1\"" sh "$file"
157 return
158 ;;
159 esac
160 # Without less there is no editor key; fall back to filtering into a pipe.
161 command -v less > /dev/null 2>&1 || {
162 sh -c "$pager" < "$file"
163 return
164 }
165 # -R because the filter's color is the whole point of running it, and no
166 # LESSCLOSE because a stray one would run against a buffer we still read.
167 LESSOPEN="|$pager < %s" env -u LESSCLOSE less -R -- "$file"
168}
169
170pending_line() {
171 local ref="$1" age author ahead stat
172 age="$(git log -1 --format='%cr' "$ref")"
173 author="$(git log -1 --format='%an' "$ref")"
174 ahead="$(git rev-list --count "origin/main..$ref")"
175 stat="$(git diff --shortstat "origin/main...$ref")"
176 stat="${stat# }"
177 printf '%s | %s | %s | ahead %s | %s\n' \
178 "${ref#origin/}" "$age" "$author" "$ahead" "${stat:-no file changes}"
179}
180
181cmd_pending() {
182 [ $# -eq 0 ] || die "pending takes no arguments"
183 fetch_origin
184 local ref found=0
185 while IFS= read -r ref; do
186 case "$ref" in
187 origin/HEAD | origin/main) continue ;;
188 esac
189 found=1
190 pending_line "$ref"
191 done < <(git for-each-ref --format='%(refname:short)' \
192 --no-merged=origin/main refs/remotes/origin)
193 [ "$found" -eq 1 ] || echo "nothing pending"
194}
195
196integrate() {
197 local branch="$1" local_main origin_main
198 local_main="$(git rev-parse --verify --quiet refs/heads/main)" \
199 || die "no local main branch to fast-forward — nothing merged"
200 origin_main="$(git rev-parse refs/remotes/origin/main)"
201 [ "$local_main" = "$origin_main" ] \
202 || die "local main is not at origin/main — sync it first; nothing merged"
203 git merge-base --is-ancestor refs/heads/main "refs/remotes/origin/$branch" \
204 || die "$branch does not fast-forward from main — resolve by hand; nothing merged"
205 git checkout --quiet main
206 git merge --ff-only --quiet "refs/remotes/origin/$branch"
207 git push --quiet origin main
208 echo "integrated $branch: main is now $(git rev-parse --short main), pushed to origin"
209 # The branch tip is now an ancestor of the main just pushed, so deleting it
210 # loses nothing; without this every integration leaves a fully-merged ghost
211 # ref that later reads as a confusing "empty" branch. Best-effort: a failed
212 # delete must not report the integration as failed.
213 if git push --quiet origin --delete "$branch"; then
214 echo "deleted merged branch $branch from origin"
215 else
216 printf 'valley: warning: could not delete origin/%s — delete it by hand\n' \
217 "$branch" >&2
218 fi
219}
220
221reject() {
222 local branch="$1" answer
223 printf 'really delete origin/%s? [y/N] ' "$branch"
224 read -r answer || answer=""
225 case "$answer" in
226 y | Y | yes)
227 git push --quiet origin --delete "$branch"
228 echo "rejected $branch: deleted from origin"
229 ;;
230 *) echo "kept $branch" ;;
231 esac
232}
233
234# ----------------------------------------------------------------------
235# review notes — the lines the reviewer inserts into the paged diff.
236#
237# The buffer the reviewer pages is a file, so the pager's editor key can open
238# it (page_file). Whatever comes back with lines inserted is read as notes:
239# no marker, no syntax, no mode — an inserted line is a note because it was
240# not there before. What a note is *about* is where it sits, so each one is
241# anchored to the file and the new-side line number of the diff line above
242# it, which is the pair a reviewer would otherwise have to copy out by hand.
243
244# The scratch directory holding the buffer and its pristine copy, and the
245# notes taken so far in this review — a global because [b]ase pages a second
246# time and the notes from the first pass are not thereby withdrawn.
247REVIEW_TMP=""
248NOTES=()
249
250cleanup_review_tmp() {
251 [ -n "$REVIEW_TMP" ] || return 0
252 rm -rf "$REVIEW_TMP"
253 REVIEW_TMP=""
254}
255
256# Where a branch's notes live. XDG_STATE_HOME is the right home for them:
257# they are neither config nor cache, and losing them loses judgment.
258notes_file() {
259 printf '%s/valley/notes/%s.md\n' "${XDG_STATE_HOME:-$HOME/.local/state}" "$1"
260}
261
262# The anchor of every line of the buffer, by line: the file that line belongs
263# to, and the new-side line number it sits on. Built in one pass so that
264# anchoring a note is a lookup. An empty path means the line is above every
265# file (the log); line 0 means the line is a file header, above every hunk.
266ANCHOR_PATH=()
267ANCHOR_LINE=()
268
269anchor_buffer() {
270 local file="$1" line path="" at=0 next=0 inhunk=0 rest
271 ANCHOR_PATH=()
272 ANCHOR_LINE=()
273 while IFS= read -r line; do
274 # Header lines are only headers outside a hunk: inside one, every line
275 # carries a +/-/space prefix, so a diff of a diff cannot be misread.
276 if [ "$inhunk" -eq 1 ]; then
277 case "$line" in
278 ' '* | '+'* | '')
279 at="$next" # this line's own new-side number
280 next=$((next + 1))
281 ;;
282 '-'* | \\*) ;; # a removal or the no-newline marker: no new-side line
283 *) inhunk=0 ;;
284 esac
285 fi
286 if [ "$inhunk" -eq 0 ]; then
287 case "$line" in
288 'diff --git '*)
289 path=""
290 # The b/ side, so a rename anchors to the name it will have.
291 if [[ "$line" =~ ^diff\ --git\ a/(.*)\ b/(.*)$ ]]; then
292 path="${BASH_REMATCH[2]}"
293 fi
294 at=0
295 ;;
296 '@@ '*)
297 rest="${line#*+}" # -12,7 +34,9 @@ -> 34,9 @@
298 at="${rest%%[!0-9]*}"
299 [ -n "$at" ] || at=0
300 next="$at"
301 inhunk=1
302 ;;
303 esac
304 fi
305 ANCHOR_PATH+=("$path")
306 ANCHOR_LINE+=("$at")
307 done < "$file"
308}
309
310# The anchor for a note inserted after buffer line n, as it is written down.
311anchor_of() {
312 local n="$1" path line
313 [ "$n" -ge 1 ] || { printf '(unanchored)'; return; }
314 path="${ANCHOR_PATH[n - 1]:-}"
315 line="${ANCHOR_LINE[n - 1]:-0}"
316 if [ -z "$path" ]; then
317 printf '(unanchored)'
318 elif [ "$line" -eq 0 ]; then
319 printf '%s' "$path"
320 else
321 printf '%s:%s' "$path" "$line"
322 fi
323}
324
325# The notes in an edited buffer, one `anchor: text` line each. git says where
326# the reviewer's lines landed; a hunk that removes nothing is an insertion,
327# and the line it was inserted after is the anchor. A hunk that removes
328# something is an edit of the diff itself — it anchors to nothing, since the
329# line it would name is the line it changed — so it is dropped with a count.
330notes_in() {
331 local orig="$1" edited="$2" line rest at old insert=0 touched=0 text
332 anchor_buffer "$orig"
333 while IFS= read -r line; do
334 case "$line" in
335 '@@ '*)
336 rest="${line#@@ -}" # 12,0 +13,2 @@ -> 12,0 +13,2 @@
337 at="${rest%%[!0-9]*}"
338 rest="${rest#"$at"}"
339 old=1
340 case "$rest" in
341 ,*)
342 rest="${rest#,}"
343 old="${rest%%[!0-9]*}"
344 ;;
345 esac
346 if [ "$old" -eq 0 ]; then
347 insert=1
348 else
349 insert=0
350 touched=$((touched + old))
351 fi
352 ;;
353 '+'*)
354 # Only inside an insertion hunk: the +++ of git's own header is not
355 # a note, and neither is the new side of an edit.
356 [ "$insert" -eq 1 ] || continue
357 text="${line#+}"
358 text="${text#"${text%%[![:space:]]*}"}"
359 [ -n "$text" ] || continue # a blank line says nothing
360 printf '%s: %s\n' "$(anchor_of "$at")" "$text"
361 ;;
362 esac
363 done < <(git --no-pager diff --no-ext-diff --no-index -U0 -- "$orig" "$edited")
364 [ "$touched" -eq 0 ] || printf \
365 'valley: warning: %d changed or deleted diff line(s) ignored — a note is a line you insert\n' \
366 "$touched" >&2
367}
368
369# Read the notes out of the paged buffer and keep them: appended to the
370# branch's notes file under the commit they were taken against, and held for
371# the print that follows the verdict. A notes file that cannot be written is
372# a warning, never a failure — the notes are still printed, and a review is
373# not undone by a missing directory.
374collect_notes() {
375 local branch="$1" sha="$2" file dir
376 local -a found=()
377 mapfile -t found < <(notes_in "$REVIEW_TMP/review.orig" "$REVIEW_TMP/review.diff")
378 [ "${#found[@]}" -gt 0 ] || return 0
379 NOTES+=("${found[@]}")
380 file="$(notes_file "$branch")"
381 dir="${file%/*}"
382 mkdir -p "$dir" 2> /dev/null && {
383 printf '## %s at %s\n\n' "$branch" "$sha"
384 printf '%s\n' "${found[@]}"
385 printf '\n'
386 } >> "$file" 2> /dev/null && return 0
387 printf 'valley: warning: could not write %s — the notes are printed only\n' \
388 "$file" >&2
389}
390
391print_notes() {
392 local branch="$1"
393 [ "${#NOTES[@]}" -gt 0 ] || return 0
394 printf '\n%d note(s) on %s, appended to %s:\n' \
395 "${#NOTES[@]}" "$branch" "$(notes_file "$branch")"
396 printf ' %s\n' "${NOTES[@]}"
397}
398
399show_review() {
400 local branch="$1" sha
401 sha="$(git rev-parse --short "refs/remotes/origin/$branch")"
402 REVIEW_TMP="$(mktemp -d)"
403 {
404 printf 'branch %s, log against origin/main:\n\n' "$branch"
405 git --no-pager log --oneline "origin/main..origin/$branch"
406 printf '\n'
407 git --no-pager diff "origin/main...origin/$branch"
408 } > "$REVIEW_TMP/review.diff"
409 cp "$REVIEW_TMP/review.diff" "$REVIEW_TMP/review.orig"
410 page_file "$REVIEW_TMP/review.diff" || true # quitting the pager early is not an error
411 collect_notes "$branch" "$sha"
412 cleanup_review_tmp
413}
414
415# Throwaway worktree for review's [b]ase choice; a global so the traps can
416# always clean it up — success, conflict, or ctrl-C. Never a mid-rebase state.
417REBASE_WT=""
418cleanup_rebase_wt() {
419 [ -n "$REBASE_WT" ] || return 0
420 git -C "$REBASE_WT" rebase --abort >/dev/null 2>&1 || true
421 git worktree remove --force "$REBASE_WT" >/dev/null 2>&1 || true
422 rm -rf "$REBASE_WT"
423 REBASE_WT=""
424}
425
426# Everything review leaves outside the repository: the two throwaway
427# worktrees, the paged buffer, and the scratch the policy deriver writes
428# into. One handler, installed once by cmd_review, so that no path through
429# the verb — and no ctrl-C in the pager — leaves any of them behind.
430cleanup_review() {
431 cleanup_rebase_wt
432 cleanup_ask_wt
433 cleanup_policy_tmp
434 cleanup_review_tmp
435}
436
437# Rebase origin/<branch> onto origin/main in an isolated worktree — the
438# user's checkout is never touched — and push with a lease so a concurrently
439# updated branch is never clobbered. Mechanics only; the judgment on the
440# rebased diff stays with the human, back at the review prompt.
441rebase_onto_main() {
442 local branch="$1"
443 REBASE_WT="$(mktemp -d)"
444 git worktree add --quiet --detach "$REBASE_WT" "refs/remotes/origin/$branch"
445 if ! git -C "$REBASE_WT" rebase --quiet refs/remotes/origin/main; then
446 cleanup_rebase_wt
447 die "$branch conflicts with main — resolve by hand; nothing changed"
448 fi
449 if ! git -C "$REBASE_WT" push --quiet --force-with-lease \
450 origin "HEAD:refs/heads/$branch"; then
451 cleanup_rebase_wt
452 die "lease on origin/$branch failed (it moved since the fetch); nothing pushed"
453 fi
454 cleanup_rebase_wt
455 echo "rebased $branch onto origin/main, pushed with --force-with-lease"
456}
457
458# ----------------------------------------------------------------------
459# ask — file an integration request for the branch under review.
460#
461# [i]ntegrate is the operator moving the protected ref themself. [a]sk is
462# the same keystroke over the machine path: the checks the policy requires
463# are run over the branch's tree and signed, the evidence and one request
464# ref are published, and the integrator judges the request and lands it
465# (design/integration.md). main is never touched from here.
466#
467# The two coexist, and this script never asks which one the operator is
468# entitled to. Whether the operator may write a protected ref is a fact
469# about origin's pre-receive hook, and origin is where it is answered.
470#
471# What this verb removes is a second push. `attest run --push` publishes
472# the branch and the attestation refs in one atomic push and knows nothing
473# about a request ref, so filing a request by hand is two beats: the
474# evidence, then the request after it. In between, evidence stands
475# published for a change nobody has asked to land. So this verb does not
476# use --push at all. `attest run` without it stores each note at its ref in
477# the repository and stops, and one `git push --atomic` then carries the
478# evidence and the request together — all of it or none of it. Nothing in
479# attest had to change for that; the sequencing was the whole of it.
480#
481# The branch itself is not in that push. What is under review is
482# origin/<branch>, so the commit the request names is already on origin and
483# the objects with it.
484
485# The tree the checks run over: a throwaway worktree of the branch, as
486# [b]ase uses, so that what is checked is the branch's tree and not the
487# operator's working copy. A global, so the traps clean it up whatever
488# happens.
489ASK_WT=""
490cleanup_ask_wt() {
491 [ -n "$ASK_WT" ] || return 0
492 git worktree remove --force "$ASK_WT" > /dev/null 2>&1 || true
493 rm -rf "$ASK_WT"
494 ASK_WT=""
495}
496
497# Report and fail, without leaving the review. A refusal here is not a
498# reason to end the session: the branch is still under review and the
499# operator can still answer. die() is for the verbs that have nothing left
500# to offer.
501refuse() {
502 printf 'valley: %s\n' "$*" >&2
503 return 1
504}
505
506# The change segment of a request ref. The integrator reads a request as
507# <prefix>/<target>/<change> and refuses a change segment holding a slash
508# (integrator/refs.go), so a branch name with one is written with dashes
509# instead. The ref that results is printed, never left to be assumed.
510change_name() {
511 printf '%s' "${1//\//-}"
512}
513
514# File the request. Called from the review prompt in a condition, which
515# suspends `set -e` for the whole call — so every step below is checked by
516# hand, and the failures say what was published before they happened.
517ask() {
518 local branch="$1" target=main change head base digest root ref check spec
519 local key="${VALLEY_ATTEST_KEY:-}"
520 local -a signer=() owed=() run=() evidence=()
521
522 [ -n "$key" ] || {
523 refuse "no signing key: set VALLEY_ATTEST_KEY to the ed25519 key this host attests with. The host signs; nothing published"
524 return 1
525 }
526 [ -f "$key" ] || {
527 refuse "no signing key at $key; nothing published"
528 return 1
529 }
530 command -v attest > /dev/null 2>&1 || {
531 refuse "this choice needs the attest helper; nix run .#valley bundles it. Nothing published"
532 return 1
533 }
534 signer=(--key "$key")
535 [ -z "${VALLEY_ATTEST_NAME:-}" ] || signer+=(--name "$VALLEY_ATTEST_NAME")
536
537 root="$(git rev-parse --show-toplevel)" || {
538 refuse "not a git repository; nothing published"
539 return 1
540 }
541 head="$(git rev-parse "refs/remotes/origin/$branch")" || {
542 refuse "no such branch on origin: $branch; nothing published"
543 return 1
544 }
545 base="$(git merge-base refs/remotes/origin/main "$head")" || {
546 refuse "$branch and main share no history; nothing published"
547 return 1
548 }
549 change="$(change_name "$branch")"
550 ref="refs/the-valley/integration-requests/$target/$change"
551
552 # What the change owes, from the policy the project declares. The
553 # integrator derives this again on its own side, from the policy at the
554 # target's tip — a change never supplies the policy that gates it — so
555 # this is the operator's local reading of the same question, and the
556 # answer is printed for exactly that reason.
557 policy_defaults "$root"
558 derive_owed "$POLICY_SCHEMA" "$POLICY_INSTANCE" "$POLICY_PROJECT" \
559 "$base" "$head" || return 1
560 [ "${#DERIVED_OWED[@]}" -eq 0 ] \
561 || mapfile -t owed < <(printf '%s\n' "${!DERIVED_OWED[@]}" | sort)
562 [ "${#owed[@]}" -gt 0 ] || {
563 refuse "the policy requires no check of $branch — evidence nobody asked for is not a request; nothing published"
564 return 1
565 }
566 for check in "${owed[@]}"; do
567 case "${CHECK_RUNNER[$check]:-}" in
568 nix) run+=(--check "$check=${CHECK_ATTRIBUTE[$check]}") ;;
569 command) run+=(--command "$check=${CHECK_COMMAND[$check]}") ;;
570 *)
571 refuse "the policy requires $check but does not say how to run it; nothing published"
572 return 1
573 ;;
574 esac
575 done
576
577 cleanup_ask_wt
578 ASK_WT="$(mktemp -d)" || {
579 refuse "no scratch directory to check $branch in; nothing published"
580 return 1
581 }
582 git worktree add --quiet --detach "$ASK_WT" "$head" || {
583 cleanup_ask_wt
584 refuse "could not check $branch out to run its checks; nothing published"
585 return 1
586 }
587
588 printf '\nchecking %s at %s: %s\n' "$branch" "$(git rev-parse --short "$head")" \
589 "$(printf '%s\n' "${owed[@]}" | join_lines)"
590 if ! attest run --repo "$ASK_WT" "${signer[@]}" "${run[@]}"; then
591 cleanup_ask_wt
592 refuse "the checks did not pass; nothing published, main untouched"
593 return 1
594 fi
595 digest="$(attest digest --repo "$ASK_WT")" || {
596 cleanup_ask_wt
597 refuse "could not digest the tree that was checked; nothing published"
598 return 1
599 }
600 cleanup_ask_wt
601 digest="${digest#*:}"
602
603 # Every attestation stored for this tree, whoever signed it: the evidence
604 # for this change is what the subject digest is keyed by, not what this
605 # run happened to add to it.
606 mapfile -t evidence < <(git for-each-ref --format='%(refname)' \
607 "refs/the-valley/attestations/$digest")
608 [ "${#evidence[@]}" -gt 0 ] || {
609 refuse "no attestation is stored for $digest; nothing published"
610 return 1
611 }
612
613 # The one push: every evidence ref as it stands, and the request ref at
614 # the branch's head. --atomic, so a hook that refuses any of them leaves
615 # origin exactly as it was.
616 local -a push=()
617 for spec in "${evidence[@]}"; do push+=("$spec:$spec"); done
618 push+=("$head:$ref")
619 if ! git push --atomic --quiet origin "${push[@]}"; then
620 refuse "origin refused the push; nothing was published there and main is untouched. The evidence is stored locally at:"
621 printf ' %s\n' "${evidence[@]}" >&2
622 return 1
623 fi
624
625 printf '\nrequested %s -> refs/heads/%s\n' "$branch" "$target"
626 printf ' request %s -> %s\n' "$ref" "$(git rev-parse --short "$head")"
627 printf ' evidence %s\n' "${evidence[@]}"
628 printf ' checks %s\n' "$(printf '%s\n' "${owed[@]}" | join_lines)"
629 printf ' main is untouched; the integrator judges the request and lands it\n'
630}
631
632# Page the branch and take the verdict. Split out of cmd_review so that
633# every way out of it — integrate, reject, skip — is followed by the notes.
634read_and_decide() {
635 local branch="$1" choice
636 show_review "$branch"
637 # A stale branch can't integrate, and its pre-rebase diff is not what would
638 # land; offer to rebase it mechanically, then re-review what actually would.
639 # [a]sk is offered here as well, because the integrator applies a delta to
640 # the tip rather than fast-forwarding: a stale branch is a request it can
641 # judge, and rebasing first is a convenience rather than a precondition.
642 while ! git merge-base --is-ancestor refs/remotes/origin/main \
643 "refs/remotes/origin/$branch"; do
644 printf '%s does not fast-forward from main: [a]sk, [b]ase onto main, [r]eject, [s]kip? ' \
645 "$branch"
646 read -r choice || die "stdin closed before an answer; nothing done"
647 case "$choice" in
648 a) ask "$branch" && return ;;
649 b)
650 rebase_onto_main "$branch"
651 fetch_origin
652 show_review "$branch"
653 ;;
654 r) reject "$branch" && return ;;
655 s)
656 echo "skipped $branch; nothing done"
657 return
658 ;;
659 *) echo "answer a, b, r, or s" ;;
660 esac
661 done
662 while true; do
663 printf '%s: [a]sk, [i]ntegrate, [r]eject, [s]kip? ' "$branch"
664 read -r choice || die "stdin closed before an answer; nothing done"
665 case "$choice" in
666 # A refusal from ask is not a verdict: it says what it did not do and
667 # the prompt comes back, so the branch can still be integrated,
668 # rejected or skipped.
669 a) ask "$branch" && return ;;
670 i) integrate "$branch" && return ;;
671 r) reject "$branch" && return ;;
672 s)
673 echo "skipped $branch; nothing done"
674 return
675 ;;
676 *) echo "answer a, i, r, or s" ;;
677 esac
678 done
679}
680
681cmd_review() {
682 [ $# -eq 1 ] || die "usage: valley review <branch>"
683 local branch="${1#origin/}"
684 fetch_origin
685 git rev-parse --verify --quiet "refs/remotes/origin/$branch" >/dev/null \
686 || die "no such branch on origin: $branch"
687 trap cleanup_review EXIT
688 trap 'exit 130' INT TERM
689 read_and_decide "$branch"
690 # The verdict disposes of the branch; the notes are what the human made of
691 # it, so they are printed whatever the verdict was.
692 print_notes "$branch"
693}
694
695# tail and replay are thin wrappers over the nats CLI — anything they do,
696# plain nats and git can do. They are the only verbs needing more than git
697# and coreutils.
698need_nats() {
699 command -v nats >/dev/null 2>&1 \
700 || die "this verb needs the nats CLI (natscli); nix run .#valley bundles it"
701}
702
703cmd_tail() {
704 [ $# -le 1 ] || die "usage: valley tail [subject]"
705 need_nats
706 exec nats sub "${1:-valley.>}"
707}
708
709# One ref-updated event per existing ref, from git for-each-ref alone. A
710# ref's prior value is not derivable from the repository, so `old` is the
711# all-zero id — the same payload a push creating the ref would produce.
712# The payload construction mirrors the host module's publisher hook
713# (nix/valley-host.nix); change one only with the other.
714cmd_replay() {
715 [ $# -le 1 ] || die "usage: valley replay [repo-dir]"
716 need_nats
717 local dir="${1:-.}" repo sha ref event count=0
718 git -C "$dir" rev-parse --git-dir >/dev/null 2>&1 \
719 || die "not a git repository: $dir"
720 if [ "$(git -C "$dir" rev-parse --is-bare-repository)" = true ]; then
721 repo="$(basename "$(git -C "$dir" rev-parse --absolute-git-dir)" .git)"
722 else
723 repo="$(basename "$(git -C "$dir" rev-parse --show-toplevel)")"
724 fi
725 while read -r sha ref; do
726 # " is the only JSON-significant character a refname can contain (git
727 # forbids \ and control characters); names and object ids are safe.
728 event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \
729 "$repo" "${ref//\"/\\\"}" "${sha//?/0}" "$sha")"
730 nats pub "valley.git.$repo.ref-updated" "$event" >/dev/null
731 count=$((count + 1))
732 done < <(git -C "$dir" for-each-ref --format='%(objectname) %(refname)')
733 echo "replayed $count refs of $repo onto the bus"
734}
735
736# ----------------------------------------------------------------------
737# checks — the verification-policy deriver (dcr-f41f718). It composes the
738# instance layer with the project layer, matches every side of a diff
739# against the composed classes, and prints the check names the change owes
740# with the class or classes that made each one required. It reports: no
741# check is run, nothing is gated, nothing is written.
742#
743# Composition is CUE's, never this script's. The whole of the mandatory-
744# versus-overridable distinction is unification, so reimplementing it here
745# would be reimplementing the decision. What this script does that CUE
746# cannot is glob matching and reading a diff.
747
748need_cue() {
749 command -v cue >/dev/null 2>&1 \
750 || die "this verb needs the cue CLI; nix run .#valley bundles it"
751}
752
753# One glob segment as an ERE fragment: `*` and `?` are wildcards that never
754# cross a `/`, and every ERE metacharacter is escaped.
755segment_ere() {
756 local seg="$1" out="" i c
757 for ((i = 0; i < ${#seg}; i++)); do
758 c="${seg:i:1}"
759 case "$c" in
760 '*') out+='[^/]*' ;;
761 '?') out+='[^/]' ;;
762 '.' | '^' | '$' | '+' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | \\) out+="\\$c" ;;
763 *) out+="$c" ;;
764 esac
765 done
766 printf '%s' "$out"
767}
768
769# A path glob as an anchored ERE, segment by segment. A `**` segment matches
770# any number of segments including none, so it swallows the separator that
771# would otherwise follow it and `a/**/b` matches `a/b`; every other segment
772# matches exactly one.
773glob_ere() {
774 local ere='^' i last
775 local -a segs=()
776 IFS=/ read -r -a segs <<<"$1"
777 last=$((${#segs[@]} - 1))
778 for ((i = 0; i <= last; i++)); do
779 if [ "${segs[i]}" = '**' ]; then
780 if [ "$i" -eq "$last" ]; then ere+='.*'; else ere+='(.*/)?'; fi
781 else
782 ere+="$(segment_ere "${segs[i]}")"
783 [ "$i" -eq "$last" ] || ere+='/'
784 fi
785 done
786 printf '%s$' "$ere"
787}
788
789# The composed policy as one tab-separated line per covered pattern, per
790# required check, and per field of the check catalogue, so the shell never
791# parses CUE. Every line is three fields — a kind, a name, and a value —
792# whatever the kind, so one reader takes them all. The field is hidden
793# because the schema's sentinel rejects unknown top-level fields, and
794# `unclassified` is rendered as a class of that name: it is one more source
795# a check can come from.
796#
797# The catalogue is rendered because a caller that runs a check needs what
798# the policy says a check IS — its runner, and the attribute or command
799# line that runner takes. `checks` only reports and does not read it;
800# review's [a]sk turns it into the arguments attest is given.
801render_cue() {
802 cat <<'EOF'
803package verification
804
805import (
806 "list"
807 "strings"
808)
809
810_render: strings.Join(list.Concat([[
811 for cn, c in policy.classes
812 for p, on in c.paths if on {"path\t\(cn)\t\(p)"}
813], [
814 for cn, c in policy.classes
815 for k, on in c.requires if on {"requires\t\(cn)\t\(k)"}
816], [
817 for k, on in policy.unclassified if on {"requires\tunclassified\t\(k)"}
818], [
819 for n, c in policy.checks {"runner\t\(n)\t\(c.runner)"}
820], [
821 for n, c in policy.checks if c.runner == "nix" {"attribute\t\(n)\t\(c.attribute)"}
822], [
823 for n, c in policy.checks if c.runner == "command" {"command\t\(n)\t\(c.command)"}
824]]), "\n")
825EOF
826}
827
828# The composed layer, and a scratch directory for the documents the
829# derivation writes into the composition. Globals so the probe below can
830# see them.
831POLICY_LAYER=()
832POLICY_TMP=""
833
834cleanup_policy_tmp() {
835 [ -n "$POLICY_TMP" ] || return 0
836 rm -rf "$POLICY_TMP"
837 POLICY_TMP=""
838}
839
840# Where the schema and the two policy layers live in a project following
841# the convention (dcr-f41f718). `checks` takes an option for each, so a
842# reader can point it anywhere; review's [a]sk does not, because a request
843# is filed against the policy the project declares and nowhere else.
844POLICY_SCHEMA=""
845POLICY_INSTANCE=""
846POLICY_PROJECT=""
847policy_defaults() {
848 POLICY_SCHEMA="$1/schema/verification.cue"
849 POLICY_INSTANCE="$1/examples/policy/instance"
850 POLICY_PROJECT="$1/examples/policy/project"
851}
852
853# Is this check mandatory in this class, or a default the project left
854# alone? The bit is the form of the composed value, so the test is CUE's
855# own: a project supplying `false` either conflicts or unifies cleanly.
856# Answering by unifying rather than by inspecting syntax means the script
857# cannot disagree with `cue vet`.
858check_is_mandatory() {
859 local class="$1" check="$2" field
860 if [ "$class" = unclassified ]; then
861 field="policy: unclassified: \"$check\": false"
862 else
863 field="policy: classes: \"$class\": requires: \"$check\": false"
864 fi
865 printf 'package verification\n%s\n' "$field" > "$POLICY_TMP/probe.cue"
866 ! cue vet "${POLICY_LAYER[@]}" "$POLICY_TMP/probe.cue" > /dev/null 2>&1
867}
868
869# Every side of the diff: an added, modified or deleted path, and both the
870# old and the new path of a rename or copy. -z because a path may contain
871# anything but NUL.
872diff_paths() {
873 local base="$1" head="$2" status path
874 while IFS= read -r -d '' status; do
875 IFS= read -r -d '' path || die "truncated diff output; nothing derived"
876 printf '%s\n' "$path"
877 case "$status" in
878 R* | C*)
879 IFS= read -r -d '' path || die "truncated diff output; nothing derived"
880 printf '%s\n' "$path"
881 ;;
882 esac
883 done < <(git diff --no-relative --name-status -M -z "$base" "$head")
884}
885
886# Lines in, one comma-separated line out.
887join_lines() {
888 local out="" line
889 while IFS= read -r line; do out="${out:+$out, }$line"; done
890 printf '%s' "$out"
891}
892
893# The ref a branch is derived against, preferring what origin last said.
894main_ref() {
895 git rev-parse --verify --quiet refs/remotes/origin/main > /dev/null \
896 && { echo refs/remotes/origin/main; return; }
897 git rev-parse --verify --quiet refs/heads/main > /dev/null \
898 && { echo refs/heads/main; return; }
899 return 1
900}
901
902# ----------------------------------------------------------------------
903# The derivation itself, and the globals it answers with. Everything a
904# caller could want from the policy comes out of one pass, because every
905# part of it is a function of the same composition: `checks` prints the
906# answer, review's [a]sk runs what it names.
907#
908# It reports and returns rather than dying, so that a caller inside the
909# review loop is refused rather than ended. Its callers are all in a
910# condition, which suspends `set -e` for the whole call, so every step is
911# checked by hand.
912DERIVED_PATHS=() # every side of the diff, sorted
913DERIVED_MATCHED=() # the class names at least one path matched, sorted
914DERIVED_UNCOVERED=() # the paths no class covered
915DERIVED_OWES=0 # whether `unclassified` is what owes something
916declare -A DERIVED_OWED=() # check -> the classes that required it
917declare -A DERIVED_PINNED=() # check -> mandatory | default
918declare -A CHECK_RUNNER=() # check -> nix | command
919declare -A CHECK_ATTRIBUTE=() # check -> the flake check attribute
920declare -A CHECK_COMMAND=() # check -> the command line
921
922derive_owed() {
923 local schema="$1" instance="$2" project="$3" base="$4" head="$5"
924
925 need_cue
926 [ -f "$schema" ] || {
927 refuse "no policy schema at $schema; nothing derived"
928 return 1
929 }
930 # An unmatched glob stays literal, so the first entry is a real file
931 # exactly when the directory holds a document.
932 local -a instance_docs=("$instance"/*.cue) project_docs=("$project"/*.cue)
933 [ -f "${instance_docs[0]}" ] || {
934 refuse "no instance policy layer at $instance; nothing derived"
935 return 1
936 }
937 [ -f "${project_docs[0]}" ] || {
938 refuse "no project policy layer at $project; nothing derived"
939 return 1
940 }
941
942 DERIVED_PATHS=()
943 mapfile -t DERIVED_PATHS < <(diff_paths "$base" "$head" | sort -u)
944
945 cleanup_policy_tmp
946 POLICY_LAYER=("$schema" "${instance_docs[@]}" "${project_docs[@]}")
947 POLICY_TMP="$(mktemp -d)" || {
948 refuse "no scratch directory to compose the policy in; nothing derived"
949 return 1
950 }
951 render_cue > "$POLICY_TMP/render.cue"
952 cue vet -c "${POLICY_LAYER[@]}" || {
953 refuse "the policy layers do not compose; nothing derived"
954 return 1
955 }
956
957 # Sorted once here, so every list below comes out in a stable order.
958 local -a rendered=()
959 mapfile -t rendered < <(cue eval --out text -e _render \
960 "${POLICY_LAYER[@]}" "$POLICY_TMP/render.cue" | sort)
961
962 unset CHECK_RUNNER CHECK_ATTRIBUTE CHECK_COMMAND DERIVED_OWED DERIVED_PINNED
963 declare -gA CHECK_RUNNER=() CHECK_ATTRIBUTE=() CHECK_COMMAND=() \
964 DERIVED_OWED=() DERIVED_PINNED=()
965
966 # The middle field is a class name for a coverage or requirement line and
967 # a check name for a catalogue one; `key` is what both are.
968 local -a pat_class=() pat_ere=() req_class=() req_check=()
969 local line kind key value
970 for line in "${rendered[@]}"; do
971 kind="${line%%$'\t'*}"
972 key="${line#*$'\t'}"
973 value="${key#*$'\t'}"
974 key="${key%%$'\t'*}"
975 case "$kind" in
976 path)
977 pat_class+=("$key")
978 pat_ere+=("$(glob_ere "$value")")
979 ;;
980 requires)
981 req_class+=("$key")
982 req_check+=("$value")
983 ;;
984 runner) CHECK_RUNNER["$key"]="$value" ;;
985 attribute) CHECK_ATTRIBUTE["$key"]="$value" ;;
986 command) CHECK_COMMAND["$key"]="$value" ;;
987 esac
988 done
989
990 local -A matched=()
991 local path i hit
992 DERIVED_UNCOVERED=()
993 for path in "${DERIVED_PATHS[@]}"; do
994 hit=0
995 for ((i = 0; i < ${#pat_ere[@]}; i++)); do
996 if [[ "$path" =~ ${pat_ere[i]} ]]; then
997 matched["${pat_class[i]}"]=1
998 hit=1
999 fi
1000 done
1001 [ "$hit" -eq 1 ] || DERIVED_UNCOVERED+=("$path")
1002 done
1003 # A path no class covers is answered by the policy's `unclassified` set,
1004 # which is why it is treated as one more matched class rather than as an
1005 # absence.
1006 [ "${#DERIVED_UNCOVERED[@]}" -eq 0 ] || matched[unclassified]=1
1007
1008 local check
1009 DERIVED_OWES=0
1010 for ((i = 0; i < ${#req_check[@]}; i++)); do
1011 key="${req_class[i]}"
1012 check="${req_check[i]}"
1013 [ -n "${matched[$key]:-}" ] || continue
1014 [ "$key" != unclassified ] || DERIVED_OWES=1
1015 DERIVED_OWED["$check"]="${DERIVED_OWED[$check]:+${DERIVED_OWED[$check]}, }$key"
1016 if check_is_mandatory "$key" "$check"; then
1017 DERIVED_PINNED["$check"]=mandatory
1018 else
1019 DERIVED_PINNED["$check"]="${DERIVED_PINNED[$check]:-default}"
1020 fi
1021 done
1022
1023 DERIVED_MATCHED=()
1024 [ "${#matched[@]}" -eq 0 ] \
1025 || mapfile -t DERIVED_MATCHED < <(printf '%s\n' "${!matched[@]}" | sort)
1026}
1027
1028cmd_checks() {
1029 local root schema instance project base head
1030 root="$(git rev-parse --show-toplevel 2> /dev/null)" \
1031 || die "not a git repository"
1032 policy_defaults "$root"
1033 schema="$POLICY_SCHEMA"
1034 instance="$POLICY_INSTANCE"
1035 project="$POLICY_PROJECT"
1036 while [ $# -gt 0 ]; do
1037 case "$1" in
1038 --schema) [ $# -ge 2 ] || die "--schema needs a file"; schema="$2"; shift 2 ;;
1039 --instance) [ $# -ge 2 ] || die "--instance needs a directory"; instance="$2"; shift 2 ;;
1040 --project) [ $# -ge 2 ] || die "--project needs a directory"; project="$2"; shift 2 ;;
1041 --) shift; break ;;
1042 -*) die "unknown option: $1" ;;
1043 *) break ;;
1044 esac
1045 done
1046 [ $# -le 2 ] || die "usage: valley checks [options] [<base> [<head>]]"
1047
1048 head="$(git rev-parse --verify --quiet "${2:-HEAD}^{commit}")" \
1049 || die "no such commit: ${2:-HEAD}"
1050 if [ $# -ge 1 ]; then
1051 base="$(git rev-parse --verify --quiet "$1^{commit}")" \
1052 || die "no such commit: $1"
1053 else
1054 local against
1055 against="$(main_ref)" || die "no main branch to derive a base from — name one"
1056 base="$(git merge-base "$against" "$head")" \
1057 || die "$head and ${against#refs/} do not share history — name a base"
1058 fi
1059
1060 trap cleanup_policy_tmp EXIT
1061 derive_owed "$schema" "$instance" "$project" "$base" "$head" || exit 1
1062
1063 local check width=0
1064 for check in "${!DERIVED_OWED[@]}"; do
1065 [ "${#check}" -le "$width" ] || width="${#check}"
1066 done
1067
1068 printf '%s..%s: %d changed path(s)\n' \
1069 "$(git rev-parse --short "$base")" "$(git rev-parse --short "$head")" \
1070 "${#DERIVED_PATHS[@]}"
1071 printf 'policy: %s + %s\n' "${instance#"$root"/}" "${project#"$root"/}"
1072 if [ "${#DERIVED_MATCHED[@]}" -eq 0 ]; then
1073 printf 'classes matched: none\n\n'
1074 else
1075 printf 'classes matched: %s\n\n' \
1076 "$(printf '%s\n' "${DERIVED_MATCHED[@]}" | join_lines)"
1077 fi
1078
1079 if [ "${#DERIVED_OWED[@]}" -eq 0 ]; then
1080 echo "required checks: none"
1081 else
1082 echo "required checks:"
1083 while IFS= read -r check; do
1084 printf ' %-*s %-9s %s\n' \
1085 "$width" "$check" "${DERIVED_PINNED[$check]}" "${DERIVED_OWED[$check]}"
1086 done < <(printf '%s\n' "${!DERIVED_OWED[@]}" | sort)
1087 fi
1088
1089 if [ "${#DERIVED_UNCOVERED[@]}" -gt 0 ]; then
1090 printf '\nunclassified: %d path(s) matched no class\n' "${#DERIVED_UNCOVERED[@]}"
1091 printf ' %s\n' "${DERIVED_UNCOVERED[@]}"
1092 # The failure the `unclassified` field exists to prevent: paths outside
1093 # every class that the policy then asks nothing of.
1094 [ "$DERIVED_OWES" -eq 1 ] \
1095 || echo " the policy requires nothing of them — it is behind the tree"
1096 fi
1097}
1098
1099main() {
1100 local verb="${1:-help}"
1101 if [ $# -gt 0 ]; then shift; fi
1102 # The verb set is mirrored in completions/ (valley.bash, _valley) —
1103 # update both when it changes.
1104 case "$verb" in
1105 pending) cmd_pending "$@" ;;
1106 review) cmd_review "$@" ;;
1107 checks) cmd_checks "$@" ;;
1108 tail) cmd_tail "$@" ;;
1109 replay) cmd_replay "$@" ;;
1110 help | -h | --help) usage ;;
1111 *)
1112 printf 'valley: unknown verb: %s\n\n' "$verb" >&2
1113 usage >&2
1114 exit 1
1115 ;;
1116 esac
1117}
1118
1119main "$@"