gunk-dev/the-valley

valley

source32276166ab1fmain's published tip history
90.3 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# archive/.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, again by review's [a]pprove, which
17# needs the attest helper, and again by status, ready, unready and
18# withdraw, which are a Go program (status/) this script runs —
19# graduation is now owed; recording the decision node is part of taking it.);
20# - its behavior gets subtle enough to need real tests
21# (CROSSED by checks: glob matching is pinned by the policy-deriver
22# flake check, not by reading the code.);
23# - it needs nontrivial parsing or concurrency
24# (CROSSED by checks: glob-to-regex translation and -z diff parsing.).
25# The size tripwire (~300 lines) is crossed too. Which way to take the
26# graduation is dcr-2aa1a12, still `proposed`.
27# Graduation is a deliberate act, recorded as a decision node.
28# Precedent: klaus — born in cosmo, graduated deliberately.
29
30set -euo pipefail
31
32# Every verb reads the repository's own objects. A replacement ref makes one
33# object stand in for another wherever git looks it up, so a fetched or
34# planted refs/replace/* could change the diff a reviewer reads, the policy
35# a derivation composes, and the tree a request is filed for. git is told
36# to ignore them, whatever configuration says, and the variables that point
37# it at other objects or at another replacement namespace are dropped. What
38# chooses the repository and the person's own configuration are kept: a
39# fetch of the owning valley needs that configuration, and neither changes
40# what an object id reads as once replacement refs are off.
41export GIT_NO_REPLACE_OBJECTS=1
42unset GIT_REPLACE_REF_BASE GIT_GRAFT_FILE GIT_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES
43
44die() {
45 printf 'valley: %s\n' "$*" >&2
46 exit 1
47}
48
49usage() {
50 cat <<'EOF'
51valley — S1 integrator verbs for a valley project
52
53usage: valley <verb> [args]
54
55 pending list branches on origin not merged into origin/main,
56 one line each: branch | head subject | age | author |
57 ahead N | diffstat. then, under drafts, the changes
58 whose record says they are drafts, one line each, the
59 same way, for the head of the active version: handle
60 and version, and the branch the version names. a branch
61 at a draft's head is listed only there. drafts need the
62 valley-go helper.
63 review <change> page through the change's branch: its log and diff vs
64 origin/main. then choose:
65 [a]pprove file an integration request. runs the
66 checks the composed policy requires of
67 this change over a throwaway worktree of
68 the branch, signs each result as an
69 attestation, and publishes the evidence
70 and the request ref to origin in ONE
71 atomic push. this files the request;
72 it does not wait for integration or
73 update your local checkout. use status
74 to read the result. the policy comes
75 from the target's tip and the owning
76 valley's, as checks describes below,
77 so your checkout
78 can be on any branch. a change the policy
79 requires no check of is filed too, as a
80 request with no evidence, and says so.
81 approving a change already requested is
82 how it is filed again. at a head rebased
83 onto a moved main it replaces the request
84 ref under a lease and names the head it
85 replaced; at the same head it leaves the
86 ref alone and publishes only the new
87 evidence, which the create-only
88 attestation namespace refuses when this
89 signer has already attested that tree
90 (bd-7b7d58f). every write of the request
91 ref is leased, filing included, so an
92 approval that lost a race is refused
93 rather than clobbering the one that won.
94 needs the attest helper and
95 VALLEY_ATTEST_KEY, the ed25519 key this
96 host signs with, whenever a check is
97 owed; VALLEY_ATTEST_NAME is the name it
98 signs under, defaulting to this host's.
99 [r]eject delete the remote branch (confirmed first)
100 [s]kip do nothing
101 [a]pprove is the only way a change reaches main from
102 here, and approve below is the same act without the
103 pager.
104 Nothing in this script writes the protected ref: the
105 integrator does, having judged the request.
106 a stale branch (won't fast-forward from main) is first
107 offered:
108 [b]ase rebase it onto origin/main in a throwaway
109 worktree, push --force-with-lease, then
110 re-review the diff that would actually land
111 [a]pprove is offered there too: a stale branch is nothing
112 the integrator cannot apply, so it need not be rebased
113 first.
114 while paging, press v: less opens the diff in $EDITOR.
115 every line you insert there is a note. it is anchored to
116 the file and new-side line it sits on — to the file alone
117 when it sits above the first hunk — then appended to
118 $XDG_STATE_HOME/valley/notes/<branch>.md (default
119 ~/.local/state) and printed after the verdict. notes
120 survive [b]ase. lines you change or delete instead of
121 inserting are ignored, with a warning.
122 approve <change> do what review's [a]pprove does for the change, without
123 paging it: the same checks, the same refusals, the same
124 leased request write and the same output. exits non-zero
125 when it refuses.
126 rebase <change> do what review's [b]ase does for the change: rebase it
127 onto origin/main in a throwaway worktree and push it
128 with --force-with-lease, then print its new head. it
129 does not re-review the result. a change that already
130 fast-forwards from main is left as it is.
131 status [--json] <change>
132 read the request and the integrator's last decision from
133 origin. distinguish waiting, a decision that needs
134 attention, and a change integrated into origin/main.
135 after integration, show how to update the local checkout.
136 fetches objects without moving local branches or files;
137 no checks run and no request is filed.
138 --json print the status as one JSON object,
139 valley-status/v1, for front ends to read
140 (docs/architecture.md). an error prints
141 no object: it goes to stderr and the exit
142 status is non-zero.
143 needs the valley-go helper.
144 ready [--head <sha>] [--change <id>] [--stamp] [<branch>]
145 mark a head of the branch ready, as a new version of its
146 change, in the change's record on origin:
147 refs/the-valley/changes/main/<change id>. the branch
148 defaults to the current one. the head is --head, or else
149 origin/<branch>, and it must be on origin already. the
150 first ready of a change makes v1; each later one adds
151 the next version, at a head other than the active
152 version's. a draft or a withdrawn change comes back this
153 way: at the active version's head, it is ready again at
154 that version, and at another head it gains the next
155 version. prints the handle and version, e.g.
156 `cosmo nxvp v2 ready`.
157 the change id is --change, else the head commit's jj
158 change-id header, else a Change-Id: trailer in its
159 message, else a new one, which is printed. a header and
160 a trailer that disagree are refused. so is a change
161 whose commits from its merge base with origin/main hold
162 a merge, or that has more than one merge base.
163 --stamp amend the head of your local branch to
164 carry the id as a Change-Id: trailer and
165 push the branch, leased, before marking it
166 ready. it only starts a new change: it
167 is refused for a change that has a
168 record on origin already, and for a head
169 already on origin.
170 the record names the principal your key pushes as, read
171 from git config valley.principal; the host refuses one
172 naming anyone else. the record ref is pushed leased on
173 the value read. a new change is owned by the principal
174 that readies it, and a later version may come from its
175 owner or the operator, who holds the request grant.
176 records are observational: nothing reads them for
177 authority, and approve is still the only way to main.
178 needs the valley-go helper.
179 unready <change>
180 make a ready change a draft in its record on origin, as
181 its owner or the operator. a draft is a pause: it voids
182 nothing, and approvals of its active version stand when
183 it is readied again. ready brings it back. prints e.g.
184 `cosmo nxvp v2 draft`. needs the valley-go helper.
185 withdraw <change>
186 mark a ready change or a draft withdrawn in its record
187 on origin, as its owner or the operator. withdrawing
188 voids everything outstanding on the change: its
189 integration requests, and the approvals and reviews of
190 every version, so a change brought back needs fresh
191 approvals. ready brings it back, at the same version
192 or a new one. prints e.g. `cosmo nxvp v2 withdrawn`.
193 needs the valley-go helper.
194 the integrator does not read records yet, so neither
195 unready nor withdraw stops a pending integration
196 request from landing the change. each warns when origin
197 holds one, under the branch-derived name or c-<change
198 id>: only a holder of the request grant may touch a
199 request ref, so the operator must drop it.
200 checks [<base> [<head>]]
201 print the check names the change between two commits owes
202 under the composed verification policy (dcr-f41f718), and
203 which class made each one required. It prints: no check is
204 run, nothing is gated, nothing is written.
205 base defaults to the merge base with main, head to HEAD.
206 by default both layers come from the target's tip
207 (origin/main), never from your checkout: the project's
208 own layer is policy/project there, and the owning valley
209 is named one line at policy/valley there, fetched and
210 read at policy/instance in that repository's integrated
211 tip. a valley's own config repository carries
212 policy/instance and uses it. a target carrying no
213 policy/project is derived under the floor alone; a floor
214 that is not there is refused. this is what the
215 integrator reads, so the answer is the same from any
216 branch, however stale. an option overrides each layer,
217 which is the only way to derive against a layer that
218 does not govern — the worked example under
219 examples/policy/, say:
220 --schema FILE default $VALLEY_VERIFICATION_SCHEMA
221 --instance DIR default the owning valley's floor
222 --project DIR default policy/project at the target
223 naming a layer stops this reading the source it
224 replaced. the schema is the shape a policy is written
225 in rather than a layer, so it ships with this tool: the
226 package sets VALLEY_VERIFICATION_SCHEMA to its own copy.
227 with that unset, as when this script runs straight from
228 a the-valley checkout, it is schema/verification.cue in
229 the checkout.
230 after the report, two lines group the owed checks by
231 the cost the policy declares, `quick` or `slow`. a slow
232 check takes minutes or needs special hardware. the cost
233 changes nothing owed: approving runs every owed check
234 whatever its cost, and the integrator requires evidence
235 for every one.
236 --names print only the owed check names,
237 one per line
238 --cost COST with --names, only the quick or
239 the slow ones, e.g.
240 `valley checks --names --cost slow`
241 tail [subject] watch bus events scroll by (default subject: valley.>);
242 the server comes from the nats CLI's own config
243 (NATS_URL or a nats context; default localhost)
244 replay [dir] publish one ref-updated event per current ref of the
245 repo at dir (default: .) — rebuilds the stream's
246 projection, e.g. after nats stream purge valley
247 help show this help
248
249A change is named by its full change id, by its handle — the shortest
250prefix of the id, four letters at least, that no other change recorded on
251origin shares — or by its branch. A name written origin/<branch> is always
252a branch. A handle that is also a branch on origin is refused unless the
253change is on that branch. Named by id or handle, a change is reviewed,
254approved and rebased at the head its active version records, never at
255its branch's tip: review shows that head, and approve, rebase and review's
256[r]eject refuse, naming both, when the branch's tip on origin is another
257commit. [r]eject deletes the branch under a lease on the recorded head.
258approve, rebase, and review's [a]pprove and [b]ase refuse a change whose
259record is not ready, naming its state. Naming a change by id or handle
260needs the valley-go helper, and without it every name is a branch.
261
262Runs from any checkout of the project; needs only git and coreutils,
263except tail and replay, which also need the nats CLI (natscli), checks,
264which also needs the cue CLI, review's notes, which need less, approve
265and review's [a]pprove, which need both the cue CLI and the attest
266helper, and status, ready, unready and withdraw, which need the valley-go
267helper, as pending does for drafts.
268nix run .#valley bundles all of them. Deriving a policy fetches the owning
269valley's repository, so checks and approving also need whatever reaching
270it takes.
271No config but valley.principal, which ready reads; no batch mode; and no
272state but the notes file — the judgment stays with the human.
273EOF
274}
275
276fetch_origin() {
277 git fetch --prune --quiet origin
278}
279
280# Resolve the pager as git would for a diff: pager.diff first (per-command
281# pager configs — e.g. home-manager's delta module — set pager.diff and leave
282# core.pager alone), then git var GIT_PAGER (core.pager, GIT_PAGER, PAGER,
283# less). pager.<cmd> may legally be a boolean; treat true/false — and an
284# empty or missing value — as unset and fall back. The value is
285# shell-interpreted, hence sh -c.
286diff_pager() {
287 local pager
288 pager="$(git config --get pager.diff || true)"
289 case "$pager" in '' | true | false) pager="$(git var GIT_PAGER)" ;; esac
290 printf '%s' "$pager"
291}
292
293# Page a file rather than a pipe, so less's v key has something to hand
294# $EDITOR: with a real file open, v runs LESSEDIT, whose default
295# `%E ?lm+%lm. %g` is the editor, +<line>, and the file name. That file is
296# the review buffer, and editing it is how notes get written (see
297# collect_notes). A pipe has no name, so less refuses to edit one — which is
298# why review no longer pipes.
299#
300# The configured diff pager stays the renderer, but as less's input
301# preprocessor rather than as the pager. It still reads the buffer on stdin
302# exactly as it did when it was the pager, less displays what it emits, and
303# less still calls the raw buffer "the current file" — so v edits the diff
304# and not the rendering. The alternative was to page the buffer with no
305# filter at all: exact, and it throws delta's rendering away, which is the
306# worse trade for a verb whose whole job is reading a diff.
307#
308# What this costs is the line number. A filter that restructures the diff —
309# delta's default rendering does — makes %lm a line of the rendered view, so
310# the editor opens near the cursor rather than on it. A structure-preserving
311# filter (pager.diff = `delta --color-only`) makes it exact. No anchor
312# depends on it: a note is anchored by where it was inserted, not by where
313# the editor opened.
314page_file() {
315 local file="$1" pager
316 [ -t 1 ] || { cat -- "$file"; return; } # a non-tty just cats
317 pager="$(diff_pager)"
318 case "${pager%%[[:space:]]*}" in
319 less | */less)
320 # Already less: give it the file and there is no filter to run.
321 sh -c "$pager \"\$1\"" sh "$file"
322 return
323 ;;
324 esac
325 # Without less there is no editor key; fall back to filtering into a pipe.
326 command -v less > /dev/null 2>&1 || {
327 sh -c "$pager" < "$file"
328 return
329 }
330 # -R because the filter's color is the whole point of running it, and no
331 # LESSCLOSE because a stray one would run against a buffer we still read.
332 LESSOPEN="|$pager < %s" env -u LESSCLOSE less -R -- "$file"
333}
334
335# One line of pending: the label, then the subject, age, author, distance
336# from main and diffstat of the commit named.
337pending_line() {
338 local label="$1" ref="$2" subject age author ahead stat
339 subject="$(git log -1 --format='%s' "$ref")"
340 [ "${#subject}" -le 60 ] || subject="${subject:0:57}..."
341 age="$(git log -1 --format='%cr' "$ref")"
342 author="$(git log -1 --format='%an' "$ref")"
343 ahead="$(git rev-list --count "origin/main..$ref")"
344 stat="$(git diff --shortstat "origin/main...$ref")"
345 stat="${stat# }"
346 printf '%s | %s | %s | %s | ahead %s | %s\n' \
347 "$label" "$subject" "$age" "$author" "$ahead" "${stat:-no file changes}"
348}
349
350# pending lists the branches on origin not merged into main. With the
351# helper, it also lists the changes whose record says they are drafts, in
352# a section of their own, each at the head of its active version. A branch
353# whose tip is a draft's head is that draft, and is listed with it rather
354# than among the branches.
355cmd_pending() {
356 [ $# -eq 0 ] || die "pending takes no arguments"
357 fetch_origin
358 local ref line handle version head branch found=0
359 local -a drafts=()
360 local -A drafted=()
361 if command -v valley-go > /dev/null 2>&1; then
362 line="$(valley-go drafts)" || exit 1
363 [ -z "$line" ] || mapfile -t drafts <<< "$line"
364 fi
365 for line in ${drafts[@]+"${drafts[@]}"}; do
366 IFS=$'\t' read -r handle version head branch <<< "$line"
367 if [ -n "$branch" ] \
368 && [ "$(git rev-parse --verify --quiet "refs/remotes/origin/$branch")" = "$head" ]; then
369 drafted["origin/$branch"]=1
370 fi
371 done
372 while IFS= read -r ref; do
373 case "$ref" in
374 origin/HEAD | origin/main) continue ;;
375 esac
376 [ -z "${drafted[$ref]:-}" ] || continue
377 found=1
378 pending_line "${ref#origin/}" "$ref"
379 done < <(git for-each-ref --format='%(refname:short)' \
380 --no-merged=origin/main refs/remotes/origin)
381 [ "$found" -eq 1 ] || echo "nothing pending"
382 [ "${#drafts[@]}" -gt 0 ] || return 0
383 printf '\ndrafts\n'
384 for line in "${drafts[@]}"; do
385 IFS=$'\t' read -r handle version head branch <<< "$line"
386 pending_line "$handle v$version${branch:+ on $branch}" "$head"
387 done
388}
389
390# For a change named by ID or handle, what is rejected is the head its
391# record names. So the branch is deleted only while its tip is that head,
392# and the delete is leased on it. When the tip is another commit, reject
393# refuses and names both, and deletes nothing. A branch named as a branch
394# is deleted as before.
395#
396# reject runs inside a condition, where bash suspends `set -e`, so the push
397# is checked by hand.
398reject() {
399 local branch="$1" answer
400 local -a lease=()
401 if [ -n "$CHANGE_HEAD" ]; then
402 check_recorded_tip "$branch" "nothing deleted" || return 1
403 lease=("--force-with-lease=refs/heads/$branch:$CHANGE_HEAD")
404 fi
405 printf 'really delete origin/%s? [y/N] ' "$branch"
406 read -r answer || answer=""
407 case "$answer" in
408 y | Y | yes)
409 if ! git push --quiet "${lease[@]}" origin --delete "$branch"; then
410 refuse "origin did not delete $branch, which may have moved since the fetch; nothing deleted"
411 return 1
412 fi
413 echo "rejected $branch: deleted from origin"
414 ;;
415 *) echo "kept $branch" ;;
416 esac
417}
418
419# ----------------------------------------------------------------------
420# review notes — the lines the reviewer inserts into the paged diff.
421#
422# The buffer the reviewer pages is a file, so the pager's editor key can open
423# it (page_file). Whatever comes back with lines inserted is read as notes:
424# no marker, no syntax, no mode — an inserted line is a note because it was
425# not there before. What a note is *about* is where it sits, so each one is
426# anchored to the file and the new-side line number of the diff line above
427# it, which is the pair a reviewer would otherwise have to copy out by hand.
428
429# The scratch directory holding the buffer and its pristine copy, and the
430# notes taken so far in this review — a global because [b]ase pages a second
431# time and the notes from the first pass are not thereby withdrawn.
432REVIEW_TMP=""
433NOTES=()
434
435cleanup_review_tmp() {
436 [ -n "$REVIEW_TMP" ] || return 0
437 rm -rf "$REVIEW_TMP"
438 REVIEW_TMP=""
439}
440
441# Where a branch's notes live. XDG_STATE_HOME is the right home for them:
442# they are neither config nor cache, and losing them loses judgment.
443notes_file() {
444 printf '%s/valley/notes/%s.md\n' "${XDG_STATE_HOME:-$HOME/.local/state}" "$1"
445}
446
447# The anchor of every line of the buffer, by line: the file that line belongs
448# to, and the new-side line number it sits on. Built in one pass so that
449# anchoring a note is a lookup. An empty path means the line is above every
450# file (the log); line 0 means the line is a file header, above every hunk.
451ANCHOR_PATH=()
452ANCHOR_LINE=()
453
454anchor_buffer() {
455 local file="$1" line path="" at=0 next=0 inhunk=0 rest
456 ANCHOR_PATH=()
457 ANCHOR_LINE=()
458 while IFS= read -r line; do
459 # Header lines are only headers outside a hunk: inside one, every line
460 # carries a +/-/space prefix, so a diff of a diff cannot be misread.
461 if [ "$inhunk" -eq 1 ]; then
462 case "$line" in
463 ' '* | '+'* | '')
464 at="$next" # this line's own new-side number
465 next=$((next + 1))
466 ;;
467 '-'* | \\*) ;; # a removal or the no-newline marker: no new-side line
468 *) inhunk=0 ;;
469 esac
470 fi
471 if [ "$inhunk" -eq 0 ]; then
472 case "$line" in
473 'diff --git '*)
474 path=""
475 # The b/ side, so a rename anchors to the name it will have.
476 if [[ "$line" =~ ^diff\ --git\ a/(.*)\ b/(.*)$ ]]; then
477 path="${BASH_REMATCH[2]}"
478 fi
479 at=0
480 ;;
481 '@@ '*)
482 rest="${line#*+}" # -12,7 +34,9 @@ -> 34,9 @@
483 at="${rest%%[!0-9]*}"
484 [ -n "$at" ] || at=0
485 next="$at"
486 inhunk=1
487 ;;
488 esac
489 fi
490 ANCHOR_PATH+=("$path")
491 ANCHOR_LINE+=("$at")
492 done < "$file"
493}
494
495# The anchor for a note inserted after buffer line n, as it is written down.
496anchor_of() {
497 local n="$1" path line
498 [ "$n" -ge 1 ] || { printf '(unanchored)'; return; }
499 path="${ANCHOR_PATH[n - 1]:-}"
500 line="${ANCHOR_LINE[n - 1]:-0}"
501 if [ -z "$path" ]; then
502 printf '(unanchored)'
503 elif [ "$line" -eq 0 ]; then
504 printf '%s' "$path"
505 else
506 printf '%s:%s' "$path" "$line"
507 fi
508}
509
510# The notes in an edited buffer, one `anchor: text` line each. git says where
511# the reviewer's lines landed; a hunk that removes nothing is an insertion,
512# and the line it was inserted after is the anchor. A hunk that removes
513# something is an edit of the diff itself — it anchors to nothing, since the
514# line it would name is the line it changed — so it is dropped with a count.
515notes_in() {
516 local orig="$1" edited="$2" line rest at old insert=0 touched=0 text
517 anchor_buffer "$orig"
518 while IFS= read -r line; do
519 case "$line" in
520 '@@ '*)
521 rest="${line#@@ -}" # 12,0 +13,2 @@ -> 12,0 +13,2 @@
522 at="${rest%%[!0-9]*}"
523 rest="${rest#"$at"}"
524 old=1
525 case "$rest" in
526 ,*)
527 rest="${rest#,}"
528 old="${rest%%[!0-9]*}"
529 ;;
530 esac
531 if [ "$old" -eq 0 ]; then
532 insert=1
533 else
534 insert=0
535 touched=$((touched + old))
536 fi
537 ;;
538 '+'*)
539 # Only inside an insertion hunk: the +++ of git's own header is not
540 # a note, and neither is the new side of an edit.
541 [ "$insert" -eq 1 ] || continue
542 text="${line#+}"
543 text="${text#"${text%%[![:space:]]*}"}"
544 [ -n "$text" ] || continue # a blank line says nothing
545 printf '%s: %s\n' "$(anchor_of "$at")" "$text"
546 ;;
547 esac
548 done < <(git --no-pager diff --no-ext-diff --no-index -U0 -- "$orig" "$edited")
549 [ "$touched" -eq 0 ] || printf \
550 'valley: warning: %d changed or deleted diff line(s) ignored — a note is a line you insert\n' \
551 "$touched" >&2
552}
553
554# Read the notes out of the paged buffer and keep them: appended to the
555# branch's notes file under the commit they were taken against, and held for
556# the print that follows the verdict. A notes file that cannot be written is
557# a warning, never a failure — the notes are still printed, and a review is
558# not undone by a missing directory.
559collect_notes() {
560 local branch="$1" sha="$2" file dir
561 local -a found=()
562 mapfile -t found < <(notes_in "$REVIEW_TMP/review.orig" "$REVIEW_TMP/review.diff")
563 [ "${#found[@]}" -gt 0 ] || return 0
564 NOTES+=("${found[@]}")
565 file="$(notes_file "$branch")"
566 dir="${file%/*}"
567 mkdir -p "$dir" 2> /dev/null && {
568 printf '## %s at %s\n\n' "$branch" "$sha"
569 printf '%s\n' "${found[@]}"
570 printf '\n'
571 } >> "$file" 2> /dev/null && return 0
572 printf 'valley: warning: could not write %s — the notes are printed only\n' \
573 "$file" >&2
574}
575
576print_notes() {
577 local branch="$1"
578 [ "${#NOTES[@]}" -gt 0 ] || return 0
579 printf '\n%d note(s) on %s, appended to %s:\n' \
580 "${#NOTES[@]}" "$branch" "$(notes_file "$branch")"
581 printf ' %s\n' "${NOTES[@]}"
582}
583
584show_review() {
585 local branch="$1" head sha
586 head="$(change_head "$branch")"
587 sha="$(git rev-parse --short "$head")"
588 REVIEW_TMP="$(mktemp -d)"
589 {
590 if [ -n "$CHANGE_HEAD" ]; then
591 printf 'change %s v%s at %s, on branch %s, log against origin/main:\n\n' \
592 "$CHANGE_HANDLE" "$CHANGE_VERSION" "$sha" "$branch"
593 else
594 printf 'branch %s, log against origin/main:\n\n' "$branch"
595 fi
596 git --no-pager log --oneline "origin/main..$head"
597 printf '\n'
598 git --no-pager diff "origin/main...$head"
599 } > "$REVIEW_TMP/review.diff"
600 cp "$REVIEW_TMP/review.diff" "$REVIEW_TMP/review.orig"
601 page_file "$REVIEW_TMP/review.diff" || true # quitting the pager early is not an error
602 collect_notes "$branch" "$sha"
603 cleanup_review_tmp
604}
605
606# Throwaway worktree for review's [b]ase choice; a global so the traps can
607# always clean it up — success, conflict, or ctrl-C. Never a mid-rebase state.
608REBASE_WT=""
609cleanup_rebase_wt() {
610 [ -n "$REBASE_WT" ] || return 0
611 git -C "$REBASE_WT" rebase --abort >/dev/null 2>&1 || true
612 git worktree remove --force "$REBASE_WT" >/dev/null 2>&1 || true
613 rm -rf "$REBASE_WT"
614 REBASE_WT=""
615}
616
617# Everything review, approve and rebase leave outside the repository: the
618# two throwaway worktrees, the paged buffer, the two policy layers read out
619# of their tips, and the scratch the policy deriver writes into. One
620# handler, installed once by each of those verbs, so that no path through
621# them — and no ctrl-C in the pager — leaves any of them behind.
622cleanup_scratch() {
623 cleanup_rebase_wt
624 cleanup_approve_wt
625 cleanup_policy_tmp
626 cleanup_instance_tmp
627 cleanup_project_tmp
628 cleanup_review_tmp
629}
630
631# Rebase origin/<branch> onto origin/main in an isolated worktree — the
632# user's checkout is never touched — and push with a lease so a concurrently
633# updated branch is never clobbered. Mechanics only; the judgment on the
634# rebased diff stays with the human, back at the review prompt or in
635# whatever front end ran the rebase verb.
636#
637# Every step is checked by hand rather than left to `set -e`, because
638# rebase_change runs this inside a condition, where bash suspends `set -e`
639# for the whole call. An unchecked step that failed there would leave
640# REBASE_WT empty, and `git -C ""` would rebase and push the user's own
641# checkout.
642#
643# The commit rebased is the second argument when given, the head a change's
644# record names, and otherwise origin/<branch> as the fetch left it. It is
645# read once, and the push is leased on exactly that commit, so a fetch that
646# moves origin/<branch> meanwhile changes neither.
647rebase_onto_main() {
648 local branch="$1" from="${2:-}" rebased
649 if [ -z "$from" ]; then
650 from="$(git rev-parse --verify --quiet "refs/remotes/origin/$branch^{commit}")" \
651 || die "no such branch on origin: $branch; nothing changed"
652 fi
653 REBASE_WT="$(mktemp -d)" && [ -d "$REBASE_WT" ] || {
654 REBASE_WT=""
655 die "could not make a directory for the rebase; nothing changed"
656 }
657 git worktree add --quiet --detach "$REBASE_WT" "$from" || {
658 cleanup_rebase_wt
659 die "could not check out origin/$branch for the rebase; nothing changed"
660 }
661 if ! git -C "$REBASE_WT" rebase --quiet refs/remotes/origin/main; then
662 cleanup_rebase_wt
663 die "$branch conflicts with main — resolve by hand; nothing changed"
664 fi
665 rebased="$(git -C "$REBASE_WT" rev-parse HEAD)" || {
666 cleanup_rebase_wt
667 die "could not read the rebased head of $branch; nothing pushed"
668 }
669 if ! git -C "$REBASE_WT" push --quiet "--force-with-lease=refs/heads/$branch:$from" \
670 origin "HEAD:refs/heads/$branch"; then
671 cleanup_rebase_wt
672 die "lease on origin/$branch failed (it moved since the fetch); nothing pushed"
673 fi
674 cleanup_rebase_wt
675 echo "rebased $branch onto origin/main, pushed with --force-with-lease"
676 printf ' head %s\n' "$rebased"
677}
678
679# ----------------------------------------------------------------------
680# approve — file an integration request for the branch under review.
681#
682# This is the one way a change reaches main from here: the checks the
683# policy requires are run over the branch's tree and signed, the evidence
684# and one request ref are published, and the integrator judges the request
685# and lands it (archive/design/integration.md). main is never touched from here.
686#
687# Nothing in this script writes the protected ref. Whether a given pusher
688# may write it is a fact about origin's pre-receive hook, so origin is
689# where it is answered, and a verb that merged onto main locally would only
690# be asking the same question in a worse place.
691#
692# What this verb removes is a second push. `attest run --push` publishes
693# the branch and the attestation refs in one atomic push and knows nothing
694# about a request ref, so filing a request by hand is two beats: the
695# evidence, then the request after it. In between, evidence stands
696# published for a change nobody has approved. So this verb does not
697# use --push at all. `attest run` without it stores each note at its ref in
698# the repository and stops, and one `git push --atomic` then carries the
699# evidence and the request together — all of it or none of it. Nothing in
700# attest had to change for that; the sequencing was the whole of it.
701#
702# The branch itself is not in that push. What is under review is
703# origin/<branch>, so the commit the request names is already on origin and
704# the objects with it.
705
706# The tree the checks run over: a throwaway worktree of the branch, as
707# [b]ase uses, so that what is checked is the branch's tree and not the
708# operator's working copy. A global, so the traps clean it up whatever
709# happens.
710APPROVE_WT=""
711cleanup_approve_wt() {
712 [ -n "$APPROVE_WT" ] || return 0
713 git worktree remove --force "$APPROVE_WT" > /dev/null 2>&1 || true
714 rm -rf "$APPROVE_WT"
715 APPROVE_WT=""
716}
717
718# Report and fail, without leaving the review. A refusal here is not a
719# reason to end the session: the branch is still under review and the
720# operator can still answer. die() is for the verbs that have nothing left
721# to offer. The approve verb has nothing left to offer either, and turns a
722# refusal into its exit status itself.
723refuse() {
724 printf 'valley: %s\n' "$*" >&2
725 return 1
726}
727
728# The change segment of a request ref. The integrator reads a request as
729# <prefix>/<target>/<change> and refuses a change segment holding a slash
730# (integrator/refs.go), so a branch name with one is written with dashes
731# instead. The ref that results is printed, never left to be assumed.
732#
733# The mapping is lossy: `topic/x` and `topic-x` are one change name and so
734# one request ref, and this verb cannot tell a sibling's request from its
735# own. That is bd-57f7f9f, and what is done about it here is to print the
736# subject of any request being replaced, so a collision is visible at the
737# moment it happens rather than after it.
738change_name() {
739 printf '%s' "${1//\//-}"
740}
741
742# One line of a commit, for saying which commit is meant. A request being
743# replaced is usually this operator's own pre-rebase head and so is in
744# this repository; one another operator filed may not be, and saying so is
745# better than printing an id alone.
746subject_of() {
747 local s
748 if s="$(git log -1 --format=%s "$1" 2>/dev/null)" && [ -n "$s" ]; then
749 printf '%s' "$s"
750 else
751 printf 'subject not in this repository'
752 fi
753}
754
755# The value of a ref on origin, as one id or the empty string. Failing to
756# read it is not the same as reading that it is absent, so the two are
757# separate answers: this returns 1 for a read that did not happen.
758remote_ref() {
759 local out
760 out="$(git ls-remote origin "$1" 2>/dev/null)" || return 1
761 printf '%s' "$out" | cut -f1
762 return 0
763}
764
765# Where the checks this run signed are stored, for every failure that
766# happens after they have run. One stanza, so no failure path invents its
767# own wording. Called with no refs it says nothing.
768report_local_evidence() {
769 [ "$#" -gt 0 ] || return 0
770 printf 'valley: the evidence is stored locally at:\n' >&2
771 printf ' %s\n' "$@" >&2
772}
773
774# Whether origin already holds one of these attestation refs at a value
775# other than the one being pushed. The namespace admits creations only, so
776# that is the one refusal approving again will never clear: it is what a
777# re-observation of a tree this signer has already attested runs into
778# (bd-7b7d58f).
779attestation_stands_elsewhere() {
780 local digest="$1" remote spec have want
781 shift
782 remote="$(git ls-remote origin "refs/the-valley/attestations/$digest/*" 2>/dev/null)" || return 1
783 for spec in "$@"; do
784 have="$(printf '%s\n' "$remote" | awk -v r="$spec" '$2 == r { print $1 }')"
785 [ -n "$have" ] || continue
786 want="$(git rev-parse "$spec" 2>/dev/null)" || continue
787 [ "$have" = "$want" ] || return 0
788 done
789 return 1
790}
791
792# Why a push carrying the request ref failed, said as precisely as the
793# state allows. Every such push is leased, and a lease refuses when the
794# ref it named is not where the read before it saw it — which covers three
795# different events. Reading the ref again is what tells them apart, and a
796# read that does not happen is its own answer rather than a guess.
797#
798# Anything the lease is not responsible for is origin's own refusal, and
799# git has already printed it.
800diagnose_request_push() {
801 local ref="$1" pending="$2" now
802 if ! now="$(remote_ref "$ref")"; then
803 refuse "origin refused the push, and $ref could not be read again to say why. Nothing was published there and main is untouched"
804 return 0
805 fi
806 if [ "$now" = "$pending" ]; then
807 refuse "origin refused the push; nothing was published there and main is untouched"
808 elif [ -z "$now" ]; then
809 refuse "the pending request was consumed while this one was being prepared, which is what the integrator does when a change lands. The lease on $ref refused and nothing was published; fetch and review the branch again before approving it a second time"
810 elif [ -z "$pending" ]; then
811 refuse "a request for this change appeared while this one was being prepared, at $(git rev-parse --short "$now") ($(subject_of "$now")); the lease on $ref refused and nothing was published"
812 else
813 refuse "the pending request moved from $(git rev-parse --short "$pending") to $(git rev-parse --short "$now") while this one was being prepared; the lease on $ref refused, nothing was published, and the request stands where the other approval put it"
814 fi
815}
816
817# File the request. Called in a condition, from the review prompt and from
818# the approve verb alike, which suspends `set -e` for the whole call — so
819# every step below is checked by hand, and the failures say what was
820# published before they happened.
821approve() {
822 local branch="$1" target=main tip change head base digest root ref check spec
823 local key
824 local -a signer=() owed=() run=() evidence=()
825
826 root="$(git rev-parse --show-toplevel)" || {
827 refuse "not a git repository; nothing published"
828 return 1
829 }
830 tip=refs/remotes/origin/main
831 head="$(git rev-parse "refs/remotes/origin/$branch")" || {
832 refuse "no such branch on origin: $branch; nothing published"
833 return 1
834 }
835 # A change named by ID or handle is filed only while its record says it
836 # is ready, at the head its record names, and only while its branch is
837 # there too.
838 if [ -n "$CHANGE_HEAD" ]; then
839 check_ready "nothing published" || return 1
840 check_recorded_tip "$branch" "nothing published" || return 1
841 head="$CHANGE_HEAD"
842 fi
843 base="$(git merge-base "$tip" "$head")" || {
844 refuse "$branch and main share no history; nothing published"
845 return 1
846 }
847 change="$(change_name "$branch")"
848 ref="refs/the-valley/integration-requests/$target/$change"
849
850 # What the change owes, read out of exactly the sources the integrator
851 # reads: both layers from the target's tip, which review has just
852 # fetched, and the floor from the owning valley's own tip. A change never
853 # supplies the policy that gates it, and neither does the checkout this
854 # runs from — so the answer here is the same answer the integrator will
855 # derive, from whatever branch the operator happens to be on. It is
856 # printed for exactly that reason.
857 policy_defaults "$root"
858 resolve_instance_layer "$root" "$tip" || return 1
859 resolve_project_layer "$root" "$tip" || return 1
860 derive_owed "$POLICY_SCHEMA" "$POLICY_INSTANCE" "$POLICY_PROJECT" \
861 "$base" "$head" || return 1
862 sort_into owed "${!DERIVED_OWED[@]}" || {
863 refuse "could not sort the owed checks; nothing published"
864 return 1
865 }
866
867 # A change the policy asks nothing of is still a change, and approving
868 # is how one reaches main. The integrator already lands a request owing no
869 # check and records the landing as one that required nothing
870 # (archive/design/integration.md), so refusing to file it here would strand
871 # exactly the changes the policy requires nothing of. Nothing is owed, so
872 # nothing is signed and no key is needed: what gets published is one
873 # request ref and no evidence at all.
874 if [ "${#owed[@]}" -gt 0 ]; then
875 key="${VALLEY_ATTEST_KEY:-}"
876 [ -n "$key" ] || {
877 refuse "no signing key: set VALLEY_ATTEST_KEY to the ed25519 key this host attests with. The host signs; nothing published"
878 return 1
879 }
880 [ -f "$key" ] || {
881 refuse "no signing key at $key; nothing published"
882 return 1
883 }
884 command -v attest > /dev/null 2>&1 || {
885 refuse "this choice needs the attest helper; nix run .#valley bundles it. Nothing published"
886 return 1
887 }
888 signer=(--key "$key")
889 [ -z "${VALLEY_ATTEST_NAME:-}" ] || signer+=(--name "$VALLEY_ATTEST_NAME")
890
891 for check in "${owed[@]}"; do
892 case "${CHECK_RUNNER[$check]:-}" in
893 nix) run+=(--check "$check=${CHECK_ATTRIBUTE[$check]}") ;;
894 command) run+=(--command "$check=${CHECK_COMMAND[$check]}") ;;
895 *)
896 refuse "the policy requires $check but does not say how to run it; nothing published"
897 return 1
898 ;;
899 esac
900 done
901
902 cleanup_approve_wt
903 APPROVE_WT="$(mktemp -d)" || {
904 refuse "no scratch directory to check $branch in; nothing published"
905 return 1
906 }
907 git worktree add --quiet --detach "$APPROVE_WT" "$head" || {
908 cleanup_approve_wt
909 refuse "could not check $branch out to run its checks; nothing published"
910 return 1
911 }
912
913 printf '\nchecking %s at %s: %s\n' "$branch" "$(git rev-parse --short "$head")" \
914 "$(printf '%s\n' "${owed[@]}" | join_lines)"
915 if ! attest run --repo "$APPROVE_WT" "${signer[@]}" "${run[@]}"; then
916 cleanup_approve_wt
917 refuse "the checks did not pass; nothing published, main untouched"
918 return 1
919 fi
920 digest="$(attest digest --repo "$APPROVE_WT")" || {
921 cleanup_approve_wt
922 refuse "could not digest the tree that was checked; nothing published"
923 return 1
924 }
925 cleanup_approve_wt
926 digest="${digest#*:}"
927
928 # Every attestation stored for this tree, whoever signed it: the
929 # evidence for this change is what the subject digest is keyed by, not
930 # what this run happened to add to it.
931 mapfile -t evidence < <(git for-each-ref --format='%(refname)' \
932 "refs/the-valley/attestations/$digest")
933 [ "${#evidence[@]}" -gt 0 ] || {
934 refuse "no attestation is stored for $digest; nothing published"
935 return 1
936 }
937 else
938 printf '\n%s owes no check under %s + %s; filing the request with no evidence\n' \
939 "$branch" "$POLICY_INSTANCE_LABEL" "$POLICY_PROJECT_LABEL"
940 fi
941
942 # What origin already holds for this request, read once and remembered.
943 # Approving the same change twice is ordinary: evidence expires, and a
944 # change whose input closure moved under it is told to re-attest. So the
945 # request ref may already exist, and what to do about it depends on
946 # where it points. A read that does not happen is not a read that found
947 # nothing, so it ends the verb here.
948 local pending
949 if ! pending="$(remote_ref "$ref")"; then
950 refuse "could not read $ref from origin; nothing published"
951 report_local_evidence ${evidence[@]+"${evidence[@]}"}
952 return 1
953 fi
954
955 # The one push: every evidence ref as it stands, and the request ref
956 # wherever it has to go. --atomic, so a hook that refuses any of them
957 # leaves origin exactly as it was.
958 #
959 # Every write of the request ref is leased against exactly what the read
960 # above saw, including when it saw nothing: git spells that expectation
961 # `--force-with-lease=<ref>:` with an empty value, and it refuses if the
962 # ref exists at all. So filing a change for the first time is a
963 # compare-and-swap too. Without it, two operators filing one change at
964 # once would have the second silently fast-forward the first away.
965 #
966 # A pending request at this same head is a re-attestation of the tree
967 # already approved. The evidence is new and the ref does not move, so
968 # the ref is left out of the refspec entirely — a push cannot carry a
969 # compare-and-swap on a ref it is not changing, because git leaves an
970 # up-to-date ref out of what it sends. Nothing this run does establishes
971 # where that ref stands afterwards, so it is read again below.
972 #
973 # A pending request at a different head is a replacement. This is the
974 # shape a change takes when main moved through its checks' input
975 # closures: no attestation over the old tree can transfer again, so the
976 # cure is a new head rebased onto the moved main — and that head is not
977 # a descendant of the old one, which makes replacing the ref a
978 # non-fast-forward update that git refuses unless told.
979 #
980 # The lease is the whole of the force, and the refspec carries no `+`.
981 # A leading `+` sets git's per-ref force flag, and that flag defeats
982 # every rejection the push rules produce — the lease's stale-info among
983 # them. The two together are a plain force wearing a lease's name.
984 local -a push=() lease=()
985 for spec in ${evidence[@]+"${evidence[@]}"}; do push+=("$spec:$spec"); done
986 if [ "$pending" != "$head" ]; then
987 lease+=("--force-with-lease=$ref:$pending")
988 push+=("$head:$ref")
989 fi
990
991 # Nothing owed and the request already standing at this head leaves
992 # nothing to push at all, and a push assembled with an empty refspec
993 # would fall back to origin's default one. So none is made.
994 local made_push=no
995 if [ "${#push[@]}" -gt 0 ]; then
996 made_push=yes
997 if ! git push --atomic --quiet ${lease[@]+"${lease[@]}"} origin "${push[@]}"; then
998 if [ "${#lease[@]}" -eq 0 ] \
999 && attestation_stands_elsewhere "$digest" ${evidence[@]+"${evidence[@]}"}; then
1000 refuse "origin already holds an attestation for this tree from this signer, and that namespace admits creations only, so a second observation of the same tree has nowhere to go. That is bd-7b7d58f rather than anything approving again will clear. Nothing was published and main is untouched"
1001 else
1002 diagnose_request_push "$ref" "$pending"
1003 fi
1004 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1005 return 1
1006 fi
1007 fi
1008
1009 # The lines under the request line, which differ by what was found and
1010 # what was done about it.
1011 local -a standing=()
1012
1013 if [ "$pending" = "$head" ]; then
1014 # The request ref was not in that push, so where it stands now is not
1015 # something this run established. Read it again rather than repeat
1016 # what was read before it: in between, the integrator may have landed
1017 # the change and consumed the ref, or another approval may have
1018 # replaced it.
1019 #
1020 # Nothing here writes it back. Re-creating a consumed request would
1021 # file a change already in the stream, which the commit rule calls out
1022 # as the state it consumes the ref to avoid; replacing a request
1023 # another approval has just filed would clobber the winner; and
1024 # either would be a second push behind the one this verb promises. So
1025 # what this does is say what is true and stop. Approving again is the
1026 # repair, and by then it takes the create or the replace path against
1027 # what is actually there.
1028 local after
1029 if ! after="$(remote_ref "$ref")"; then
1030 refuse "$ref could not be read again, so whether the request still stands at this head is not known here"
1031 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1032 return 1
1033 fi
1034 if [ -z "$after" ]; then
1035 refuse "the request was consumed while this run was working, which is what the integrator does when a change lands. Nothing here re-filed it: a request for a change already in the stream is judged against an empty delta on every pass. Fetch and review $branch again, and approve it once more if it has not landed"
1036 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1037 return 1
1038 fi
1039 if [ "$after" != "$head" ]; then
1040 refuse "the request moved to $(git rev-parse --short "$after") ($(subject_of "$after")) while this run was working, so another approval filed it. Nothing here replaced it; approve again to replace it deliberately"
1041 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1042 return 1
1043 fi
1044 if [ "$made_push" = yes ]; then
1045 standing+=("the request already stood at this head; the evidence is what was published")
1046 else
1047 standing+=("the request already stood at this head and nothing was owed, so nothing needed publishing")
1048 fi
1049 elif [ -n "$pending" ]; then
1050 standing+=("replaced the pending request, which stood at $(git rev-parse --short "$pending") ($(subject_of "$pending"))")
1051 fi
1052
1053 printf '\nApproved %s (%s): its integration request for origin/%s is filed.\n' \
1054 "$branch" "$(git rev-parse --short "$head")" "$target"
1055 printf 'The integrator will decide whether this change can land.\n'
1056 printf 'Your local checkout has not changed.\n\n'
1057 printf 'Check the result: valley status %q\n\n' "$branch"
1058 printf ' request %s -> %s\n' "$ref" "$(git rev-parse --short "$head")"
1059 [ "${#standing[@]}" -eq 0 ] || printf ' %s\n' "${standing[@]}"
1060 if [ "${#evidence[@]}" -eq 0 ]; then
1061 printf ' evidence none — nothing was owed, so nothing was signed\n'
1062 printf ' checks none — the policy requires no check of this change\n'
1063 else
1064 printf ' evidence %s\n' "${evidence[@]}"
1065 printf ' checks %s\n' "$(printf '%s\n' "${owed[@]}" | join_lines)"
1066 fi
1067}
1068
1069# status, ready, unready and withdraw are a Go program, valley-go
1070# (status/). status reads a change's request and outcome from origin,
1071# because what front ends read from it is a JSON contract, and because the
1072# read is subtle enough to want a real parser: an outcome record it does
1073# not recognise must read as unknown, never as success. It writes nothing
1074# and moves no local branch. ready, unready and withdraw write a change's
1075# record, in the one format the push hook reads it in (change/).
1076cmd_go() {
1077 command -v valley-go > /dev/null 2>&1 \
1078 || die "$1 needs the valley-go helper; nix run .#valley bundles it"
1079 exec valley-go "$@"
1080}
1081
1082# A change is named by its full change ID, its handle, or its branch.
1083# resolve_change reads the name with the helper and sets CHANGE_BRANCH, the
1084# branch to act on. For a change named by ID or handle it also sets the
1085# change's ID, handle, active version and state, and CHANGE_HEAD, the head
1086# that version records. Without the helper a name is a branch name, as
1087# every name was before changes had records.
1088#
1089# A change named by ID or handle is acted on at CHANGE_HEAD, and never at
1090# the branch's tip. The branch a record names is only where its head is
1091# expected to be, and anyone who can push the branch can move it, in the
1092# same push as the record if they like.
1093CHANGE_ID="" CHANGE_HANDLE="" CHANGE_VERSION="" CHANGE_HEAD="" CHANGE_BRANCH="" CHANGE_STATE=""
1094resolve_change() {
1095 local line kind
1096 if ! command -v valley-go > /dev/null 2>&1; then
1097 CHANGE_BRANCH="${1#origin/}"
1098 return 0
1099 fi
1100 line="$(valley-go resolve "$1")" || return 1
1101 IFS=$'\t' read -r kind CHANGE_ID CHANGE_HANDLE CHANGE_VERSION CHANGE_HEAD CHANGE_BRANCH CHANGE_STATE <<< "$line"
1102 case "$kind" in
1103 branch)
1104 CHANGE_BRANCH="$CHANGE_ID"
1105 CHANGE_ID=""
1106 ;;
1107 change)
1108 [[ "$CHANGE_HEAD" =~ ^[0-9a-f]{40}$ ]] \
1109 || die "valley-go resolve named the head $CHANGE_HEAD, which is no object ID"
1110 case "$CHANGE_STATE" in
1111 ready | draft | withdrawn) ;;
1112 *) die "valley-go resolve named the state $CHANGE_STATE, which this script does not read" ;;
1113 esac
1114 ;;
1115 *) die "valley-go resolve answered $line, which this script does not read" ;;
1116 esac
1117}
1118
1119# The commit review, approve and rebase act on: the recorded head for a
1120# change named by ID or handle, and otherwise the branch's head on origin.
1121change_head() {
1122 if [ -n "$CHANGE_HEAD" ]; then
1123 printf '%s\n' "$CHANGE_HEAD"
1124 else
1125 git rev-parse "refs/remotes/origin/$1"
1126 fi
1127}
1128
1129# For a change named by ID or handle, refuse unless the branch's tip on
1130# origin is the recorded head, and name both. Acting on the branch would
1131# act on a commit no version records; acting on the recorded head while the
1132# branch is elsewhere would file or rebase something the branch no longer
1133# says. The second argument is what the refusal leaves undone.
1134check_recorded_tip() {
1135 local branch="$1" undone="$2" tip
1136 [ -n "$CHANGE_HEAD" ] || return 0
1137 tip="$(git rev-parse "refs/remotes/origin/$branch")" || {
1138 refuse "no such branch on origin: $branch; $undone"
1139 return 1
1140 }
1141 [ "$tip" = "$CHANGE_HEAD" ] && return 0
1142 refuse "change $CHANGE_HANDLE v$CHANGE_VERSION records the head $CHANGE_HEAD, and origin/$branch is at $tip; $undone. Ready the branch's head as a new version of $CHANGE_HANDLE, or name the branch as origin/$branch to act on its tip"
1143}
1144
1145# For a change named by ID or handle, refuse unless its record says it is
1146# ready, and name the state it is in. A draft is paused and a withdrawn
1147# change given up, and neither is approved or rebased until it is readied
1148# again. The argument is what the refusal leaves undone.
1149check_ready() {
1150 [ -n "$CHANGE_ID" ] || return 0
1151 [ "$CHANGE_STATE" = ready ] && return 0
1152 refuse "change $CHANGE_HANDLE v$CHANGE_VERSION is $CHANGE_STATE, not ready; $1. Ready it first: valley ready --change $CHANGE_ID $(printf '%q' "$CHANGE_BRANCH")"
1153}
1154
1155# rebase for a change named by ID or handle rebases the recorded head
1156# alone, so the branch must still be at it. The rebased head is a commit no
1157# version records, so the change is readied again before its handle names
1158# it.
1159rebase_change() {
1160 local branch="$1"
1161 check_ready "nothing rebased" || return 1
1162 check_recorded_tip "$branch" "nothing rebased" || return 1
1163 rebase_onto_main "$branch" "$CHANGE_HEAD"
1164 if [ -n "$CHANGE_HEAD" ]; then
1165 printf 'No version of %s records the rebased head yet. Record it: valley ready --change %s %q\n' \
1166 "$CHANGE_HANDLE" "$CHANGE_ID" "$branch"
1167 fi
1168}
1169
1170# Page the branch and take the verdict. Split out of cmd_review so that
1171# every way out of it — approve, reject, skip — is followed by the notes.
1172read_and_decide() {
1173 local branch="$1" choice
1174 show_review "$branch"
1175 # A stale branch's pre-rebase diff is not what would land; offer to rebase it
1176 # mechanically, then re-review what actually would. [a]pprove is offered
1177 # here as well, because the integrator applies a delta to the tip rather
1178 # than fast-forwarding: a stale branch is a request it can judge, and
1179 # rebasing first is a convenience rather than a precondition.
1180 while ! git merge-base --is-ancestor refs/remotes/origin/main \
1181 "$(change_head "$branch")"; do
1182 printf '%s does not fast-forward from main: [a]pprove, [b]ase onto main, [r]eject, [s]kip? ' \
1183 "$branch"
1184 read -r choice || die "stdin closed before an answer; nothing done"
1185 case "$choice" in
1186 a) approve "$branch" && return ;;
1187 b)
1188 # The rebased head of a change named by its handle is no version
1189 # of it yet, so there is nothing more to review by that handle.
1190 if [ -n "$CHANGE_HEAD" ]; then
1191 rebase_change "$branch" && return
1192 else
1193 rebase_onto_main "$branch"
1194 fetch_origin
1195 show_review "$branch"
1196 fi
1197 ;;
1198 r) reject "$branch" && return ;;
1199 s)
1200 echo "skipped $branch; nothing done"
1201 return
1202 ;;
1203 *) echo "answer a, b, r, or s" ;;
1204 esac
1205 done
1206 while true; do
1207 printf '%s: [a]pprove, [r]eject, [s]kip? ' "$branch"
1208 read -r choice || die "stdin closed before an answer; nothing done"
1209 case "$choice" in
1210 # A refusal from approve is not a verdict: it says what it did not do
1211 # and the prompt comes back, so the branch can still be approved,
1212 # rejected or skipped.
1213 a) approve "$branch" && return ;;
1214 r) reject "$branch" && return ;;
1215 s)
1216 echo "skipped $branch; nothing done"
1217 return
1218 ;;
1219 *) echo "answer a, r, or s" ;;
1220 esac
1221 done
1222}
1223
1224cmd_review() {
1225 [ $# -eq 1 ] || die "usage: valley review <change>"
1226 resolve_change "$1" || exit 1
1227 local branch="$CHANGE_BRANCH"
1228 fetch_origin
1229 git rev-parse --verify --quiet "refs/remotes/origin/$branch" >/dev/null \
1230 || die "no such branch on origin: $branch"
1231 trap cleanup_scratch EXIT
1232 trap 'exit 130' INT TERM
1233 read_and_decide "$branch"
1234 # The verdict disposes of the branch; the notes are what the human made of
1235 # it, so they are printed whatever the verdict was.
1236 print_notes "$branch"
1237}
1238
1239# approve and rebase are review's [a]pprove and [b]ase without the pager,
1240# for a front end that has shown the change its own way. Each runs the
1241# function its key runs, so the verb and the key cannot drift apart. A
1242# change is named as resolve_change reads it.
1243cmd_approve() {
1244 [ $# -eq 1 ] || die "usage: valley approve <change>"
1245 resolve_change "$1" || exit 1
1246 local branch="$CHANGE_BRANCH"
1247 fetch_origin
1248 git rev-parse --verify --quiet "refs/remotes/origin/$branch" >/dev/null \
1249 || die "no such branch on origin: $branch"
1250 trap cleanup_scratch EXIT
1251 trap 'exit 130' INT TERM
1252 # In a condition, as the review prompt calls it: approve checks each of
1253 # its own steps, and has already said why when it refuses.
1254 approve "$branch" || exit 1
1255}
1256
1257cmd_rebase() {
1258 [ $# -eq 1 ] || die "usage: valley rebase <change>"
1259 resolve_change "$1" || exit 1
1260 local branch="$CHANGE_BRANCH"
1261 fetch_origin
1262 git rev-parse --verify --quiet "refs/remotes/origin/$branch" >/dev/null \
1263 || die "no such branch on origin: $branch"
1264 check_ready "nothing rebased" || exit 1
1265 check_recorded_tip "$branch" "nothing rebased" || exit 1
1266 # review offers [b]ase only to a stale branch. One that fast-forwards
1267 # already is left alone, rather than rewritten for nothing.
1268 if git merge-base --is-ancestor refs/remotes/origin/main \
1269 "refs/remotes/origin/$branch"; then
1270 echo "$branch already fast-forwards from origin/main; nothing rebased"
1271 printf ' head %s\n' "$(git rev-parse "refs/remotes/origin/$branch")"
1272 return
1273 fi
1274 trap cleanup_scratch EXIT
1275 trap 'exit 130' INT TERM
1276 rebase_change "$branch" || exit 1
1277}
1278
1279# tail and replay are thin wrappers over the nats CLI — anything they do,
1280# plain nats and git can do. They are the only verbs needing more than git
1281# and coreutils.
1282need_nats() {
1283 command -v nats >/dev/null 2>&1 \
1284 || die "this verb needs the nats CLI (natscli); nix run .#valley bundles it"
1285}
1286
1287cmd_tail() {
1288 [ $# -le 1 ] || die "usage: valley tail [subject]"
1289 need_nats
1290 exec nats sub "${1:-valley.>}"
1291}
1292
1293# One ref-updated event per existing ref, from git for-each-ref alone. A
1294# ref's prior value is not derivable from the repository, so `old` is the
1295# all-zero id — the same payload a push creating the ref would produce.
1296# The payload construction mirrors the host module's publisher hook
1297# (nix/valley-host.nix); change one only with the other.
1298cmd_replay() {
1299 [ $# -le 1 ] || die "usage: valley replay [repo-dir]"
1300 need_nats
1301 local dir="${1:-.}" repo sha ref event count=0
1302 git -C "$dir" rev-parse --git-dir >/dev/null 2>&1 \
1303 || die "not a git repository: $dir"
1304 if [ "$(git -C "$dir" rev-parse --is-bare-repository)" = true ]; then
1305 repo="$(basename "$(git -C "$dir" rev-parse --absolute-git-dir)" .git)"
1306 else
1307 repo="$(basename "$(git -C "$dir" rev-parse --show-toplevel)")"
1308 fi
1309 while read -r sha ref; do
1310 # " is the only JSON-significant character a refname can contain (git
1311 # forbids \ and control characters); names and object ids are safe.
1312 event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \
1313 "$repo" "${ref//\"/\\\"}" "${sha//?/0}" "$sha")"
1314 nats pub "valley.git.$repo.ref-updated" "$event" >/dev/null
1315 count=$((count + 1))
1316 done < <(git -C "$dir" for-each-ref --format='%(objectname) %(refname)')
1317 echo "replayed $count refs of $repo onto the bus"
1318}
1319
1320# ----------------------------------------------------------------------
1321# checks — the verification-policy deriver (dcr-f41f718). It composes the
1322# instance layer with the project layer, matches every side of a diff
1323# against the composed classes, and prints the check names the change owes
1324# with the class or classes that made each one required. It reports: no
1325# check is run, nothing is gated, nothing is written.
1326#
1327# Composition is CUE's, never this script's. The whole of the mandatory-
1328# versus-overridable distinction is unification, so reimplementing it here
1329# would be reimplementing the decision. What this script does that CUE
1330# cannot is glob matching and reading a diff.
1331
1332need_cue() {
1333 command -v cue >/dev/null 2>&1 \
1334 || die "this verb needs the cue CLI; nix run .#valley bundles it"
1335}
1336
1337# One glob segment as an ERE fragment: `*` and `?` are wildcards that never
1338# cross a `/`, and every ERE metacharacter is escaped.
1339segment_ere() {
1340 local seg="$1" out="" i c
1341 for ((i = 0; i < ${#seg}; i++)); do
1342 c="${seg:i:1}"
1343 case "$c" in
1344 '*') out+='[^/]*' ;;
1345 '?') out+='[^/]' ;;
1346 '.' | '^' | '$' | '+' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | \\) out+="\\$c" ;;
1347 *) out+="$c" ;;
1348 esac
1349 done
1350 printf '%s' "$out"
1351}
1352
1353# A path glob as an anchored ERE, segment by segment. A `**` segment matches
1354# any number of segments including none, so it swallows the separator that
1355# would otherwise follow it and `a/**/b` matches `a/b`; every other segment
1356# matches exactly one.
1357glob_ere() {
1358 local ere='^' i last
1359 local -a segs=()
1360 IFS=/ read -r -a segs <<<"$1"
1361 last=$((${#segs[@]} - 1))
1362 for ((i = 0; i <= last; i++)); do
1363 if [ "${segs[i]}" = '**' ]; then
1364 if [ "$i" -eq "$last" ]; then ere+='.*'; else ere+='(.*/)?'; fi
1365 else
1366 ere+="$(segment_ere "${segs[i]}")"
1367 [ "$i" -eq "$last" ] || ere+='/'
1368 fi
1369 done
1370 printf '%s$' "$ere"
1371}
1372
1373# The composed policy as one tab-separated line per covered pattern, per
1374# required check, and per field of the check catalogue, so the shell never
1375# parses CUE. Every line is three fields — a kind, a name, and a value —
1376# whatever the kind, so one reader takes them all. The field is hidden
1377# because the schema's sentinel rejects unknown top-level fields, and
1378# `unclassified` is rendered as a class of that name: it is one more source
1379# a check can come from.
1380#
1381# The catalogue is rendered because a caller that runs a check needs what
1382# the policy says a check IS — its runner, and the attribute or command
1383# line that runner takes — and a tool that groups the owed checks needs
1384# their cost. `checks` reads only the cost, to group the owed checks by
1385# it; approve turns the rest into the arguments attest is given.
1386render_cue() {
1387 cat <<'EOF'
1388package verification
1389
1390import (
1391 "list"
1392 "strings"
1393)
1394
1395_render: strings.Join(list.Concat([[
1396 for cn, c in policy.classes
1397 for p, on in c.paths if on {"path\t\(cn)\t\(p)"}
1398], [
1399 for cn, c in policy.classes
1400 for k, on in c.requires if on {"requires\t\(cn)\t\(k)"}
1401], [
1402 for k, on in policy.unclassified if on {"requires\tunclassified\t\(k)"}
1403], [
1404 for n, c in policy.checks {"runner\t\(n)\t\(c.runner)"}
1405], [
1406 for n, c in policy.checks if c.runner == "nix" {"attribute\t\(n)\t\(c.attribute)"}
1407], [
1408 for n, c in policy.checks if c.runner == "command" {"command\t\(n)\t\(c.command)"}
1409], [
1410 for n, c in policy.checks {"cost\t\(n)\t\(c.cost)"}
1411]]), "\n")
1412EOF
1413}
1414
1415# The composed layer, and a scratch directory for the documents the
1416# derivation writes into the composition. Globals so the probe below can
1417# see them.
1418POLICY_LAYER=()
1419POLICY_TMP=""
1420
1421cleanup_policy_tmp() {
1422 [ -n "$POLICY_TMP" ] || return 0
1423 rm -rf "$POLICY_TMP"
1424 POLICY_TMP=""
1425}
1426
1427# Where the schema and the two policy layers come from in a project
1428# following the convention (dcr-f41f718).
1429#
1430# The client derives from exactly the sources the integrator uses
1431# (integrator/policy.go), and the working tree is not among them. The
1432# project's own layer is read from the TARGET's tip, the pointer naming the
1433# owning valley is read from the target's tip, and the floor is read from
1434# that valley's integrated tip. A change never supplies the policy that
1435# gates it, and neither does whoever happens to be reviewing it: the
1436# reviewer's checkout may be any branch, however stale, and derivation
1437# gives the same answer from all of them.
1438#
1439# The schema is not a policy layer. It is the shape a policy is written in,
1440# and it ships with this tool: the package sets VALLEY_VERIFICATION_SCHEMA
1441# to the copy it was built with, as the integrator's package does. Only
1442# the-valley's own tree carries schema/, so this script reads the schema
1443# there only when it runs straight from such a checkout with the variable
1444# unset.
1445#
1446# Neither layer is ever the worked example under examples/policy/ — a gate
1447# derived from an example is a gate nobody wrote. `checks` takes an option
1448# for each, so a reader can point it at the example or anywhere else on
1449# purpose; approve takes no such option, because a request is filed
1450# against the policy that governs the project and nowhere else.
1451#
1452# Neither layer is a path in this tree, so policy_defaults leaves both
1453# empty and the two resolvers answer for them. That split is also what
1454# keeps `checks --instance DIR` from fetching a repository whose layer it
1455# was told to ignore, and `checks --project DIR` from reading a tip whose
1456# layer it was told to ignore.
1457POLICY_SCHEMA=""
1458POLICY_INSTANCE=""
1459POLICY_INSTANCE_LABEL=""
1460POLICY_PROJECT=""
1461POLICY_PROJECT_LABEL=""
1462policy_defaults() {
1463 POLICY_SCHEMA="${VALLEY_VERIFICATION_SCHEMA:-$1/schema/verification.cue}"
1464 POLICY_INSTANCE=""
1465 POLICY_INSTANCE_LABEL=""
1466 POLICY_PROJECT=""
1467 POLICY_PROJECT_LABEL=""
1468}
1469
1470# The floor, copied out of a fetch of the owning valley's repository, and
1471# the project's own layer, copied out of the target's tip. Globals, so the
1472# traps clean them up whatever happens.
1473INSTANCE_TMP=""
1474cleanup_instance_tmp() {
1475 [ -n "$INSTANCE_TMP" ] || return 0
1476 rm -rf "$INSTANCE_TMP"
1477 INSTANCE_TMP=""
1478}
1479
1480PROJECT_TMP=""
1481cleanup_project_tmp() {
1482 [ -n "$PROJECT_TMP" ] || return 0
1483 rm -rf "$PROJECT_TMP"
1484 PROJECT_TMP=""
1485}
1486
1487# The directory each layer lives in, the file naming this project's owning
1488# valley, and the ref of that valley whose tip carries the floor. The floor
1489# resolves at the integrated tip, because a floor a project could pin is
1490# not a floor (dcr-f41f718).
1491INSTANCE_DIR=policy/instance
1492PROJECT_DIR=policy/project
1493VALLEY_POINTER=policy/valley
1494VALLEY_POINTER_REF=refs/heads/main
1495
1496# The *.cue documents of one directory at one tree-ish, copied out of a
1497# repository into a directory on disk. Reading a tip with ls-tree and
1498# cat-file rather than checking it out is what lets the layers come from
1499# the target while the checkout stays on whatever branch the reviewer is
1500# on. 0 copied something, 1 the directory holds no *.cue, 2 the read
1501# failed.
1502#
1503# -z because a path may hold anything but NUL, and *.cue because the layer
1504# is the directory's documents — the same reading the composer takes.
1505#
1506# The listing is written out and its status checked before it is read. A
1507# listing read straight from a process substitution that failed reads as a
1508# directory holding nothing, and for the project layer that is the floor
1509# alone: fewer checks owed, from a read that never happened. The listing's
1510# name is not a *.cue name, so the composer never reads it.
1511copy_layer() {
1512 local gitdir="$1" treeish="$2" dir="$3" dest="$4" path name copied=0
1513 local listing="$dest/.listing"
1514 git -C "$gitdir" ls-tree --name-only -z "$treeish" "$dir/" > "$listing" \
1515 || return 2
1516 while IFS= read -r -d '' path; do
1517 case "$path" in *.cue) ;; *) continue ;; esac
1518 name="${path##*/}"
1519 git -C "$gitdir" cat-file blob "$treeish:$path" > "$dest/$name" || return 2
1520 copied=1
1521 done < "$listing"
1522 rm -f "$listing"
1523 [ "$copied" -eq 1 ]
1524}
1525
1526# The ref whose tip supplies the policy, printed the way a person names it,
1527# with the commit it stood at. Staleness in a remote-tracking ref is a real
1528# thing to see, so the report says which commit the layers came out of
1529# rather than only which ref. A ref that cannot be read fails, so that no
1530# report names a tip nobody read.
1531target_label() {
1532 local ref="$1" short
1533 short="$(git rev-parse --short "$ref")" || return 1
1534 ref="${ref#refs/remotes/}"
1535 ref="${ref#refs/heads/}"
1536 printf '%s %s' "$ref" "$short"
1537}
1538
1539# Resolve the project's own layer, out of the target's tip, into
1540# POLICY_PROJECT, and set POLICY_PROJECT_LABEL to where it came from.
1541#
1542# A target carrying no layer of its own is derived under the floor alone.
1543# The project layer only ever adds (dcr-f41f718), so the identity of "adds"
1544# is "adds nothing"; refusing instead would make a repository underivable
1545# until its first policy commit, and that commit could not derive either.
1546# This is the integrator's own reading (integrator/policy.go), and the two
1547# have to agree about an absent layer as much as about a present one.
1548#
1549# Absence is answered with a document that adds nothing rather than with an
1550# argument left off, because the composer is handed a directory of *.cue
1551# and has no spelling for "no layer".
1552#
1553# It reports and returns rather than dying, for the reason derive_owed
1554# does: a refusal inside the review loop is not the end of the session.
1555resolve_project_layer() {
1556 local root="$1" target="$2" rc at
1557
1558 at="$(target_label "$target")" || {
1559 refuse "could not read $target; nothing derived"
1560 return 1
1561 }
1562 cleanup_project_tmp
1563 PROJECT_TMP="$(mktemp -d)" || {
1564 refuse "no scratch directory to read the project layer into; nothing derived"
1565 return 1
1566 }
1567 copy_layer "$root" "$target" "$PROJECT_DIR" "$PROJECT_TMP" && rc=0 || rc=$?
1568 case "$rc" in
1569 0)
1570 POLICY_PROJECT="$PROJECT_TMP"
1571 POLICY_PROJECT_LABEL="$PROJECT_DIR@$at"
1572 ;;
1573 1)
1574 printf 'package verification\n' > "$PROJECT_TMP/adds-nothing.cue" || {
1575 cleanup_project_tmp
1576 refuse "could not compose an empty project layer; nothing derived"
1577 return 1
1578 }
1579 POLICY_PROJECT="$PROJECT_TMP"
1580 POLICY_PROJECT_LABEL="no $PROJECT_DIR@$at — the floor alone"
1581 ;;
1582 *)
1583 cleanup_project_tmp
1584 refuse "could not read $PROJECT_DIR/ at $at; nothing derived"
1585 return 1
1586 ;;
1587 esac
1588}
1589
1590# The first line of the pointer that is neither blank nor a comment. Read
1591# in the shell so that naming an owning valley needs nothing beyond what
1592# the rest of this script needs.
1593pointer_url() {
1594 local line url=""
1595 while IFS= read -r line || [ -n "$line" ]; do
1596 line="${line%%#*}"
1597 line="${line#"${line%%[![:space:]]*}"}"
1598 line="${line%"${line##*[![:space:]]}"}"
1599 [ -n "$line" ] || continue
1600 url="$line"
1601 break
1602 done < "$1"
1603 printf '%s' "$url"
1604}
1605
1606# Resolve the floor to a directory on disk, into POLICY_INSTANCE, and set
1607# POLICY_INSTANCE_LABEL to where it came from — a temporary directory is
1608# not an answer a reader can check.
1609#
1610# Every project has exactly one owning valley, and the floor is that
1611# valley's (dcr-9b5da04). It is read from the valley's own repository and
1612# never from the project's tree, which is the tree under judgment. Two
1613# shapes, and the first is a special case of the second:
1614#
1615# - a valley's config repository carries policy/instance itself, and is
1616# governed by that floor like every other project. It uses its own,
1617# and fetches nothing.
1618# - every other project names its owning valley at policy/valley. That
1619# repository is fetched into scratch and its policy/instance is read
1620# at the integrated tip. Fetching is all this needs, and anyone the
1621# valley governs necessarily holds fetch on it.
1622#
1623# Both the pointer and a valley's own floor are read from the TARGET's tip
1624# and never from the working tree. The pointer is a file a branch can edit,
1625# so reading it from the branch would let a change name the valley that
1626# gates it; reading it from the checkout would let whoever is reviewing
1627# decide the same thing by accident, which is the failure this fixes. An
1628# absent floor is refused — that is the direction absence defaults in for
1629# this layer, because the floor is the minimum (dcr-f41f718).
1630#
1631# It reports and returns rather than dying, for the reason derive_owed
1632# does: a refusal inside the review loop is not the end of the session.
1633resolve_instance_layer() {
1634 local root="$1" target="$2" url bare dest rc at
1635 at="$(target_label "$target")" || {
1636 refuse "could not read $target; nothing derived"
1637 return 1
1638 }
1639 cleanup_instance_tmp
1640 INSTANCE_TMP="$(mktemp -d)" || {
1641 refuse "no scratch directory to read the floor into; nothing derived"
1642 return 1
1643 }
1644 dest="$INSTANCE_TMP/instance"
1645 mkdir -p "$dest"
1646
1647 copy_layer "$root" "$target" "$INSTANCE_DIR" "$dest" && rc=0 || rc=$?
1648 case "$rc" in
1649 0)
1650 POLICY_INSTANCE="$dest"
1651 POLICY_INSTANCE_LABEL="$INSTANCE_DIR@$at (this repository is its own valley)"
1652 return 0
1653 ;;
1654 1) ;; # no floor of its own: the pointer names the valley that has one
1655 *)
1656 cleanup_instance_tmp
1657 refuse "could not read $INSTANCE_DIR/ at $at; nothing derived"
1658 return 1
1659 ;;
1660 esac
1661
1662 git -C "$root" cat-file blob "$target:$VALLEY_POINTER" > "$INSTANCE_TMP/pointer" 2> /dev/null || {
1663 cleanup_instance_tmp
1664 refuse "no owning valley: $VALLEY_POINTER names the repository whose $INSTANCE_DIR is this project's floor, and $at carries no such file. A valley's own config repository carries $INSTANCE_DIR instead. Nothing derived"
1665 return 1
1666 }
1667 url="$(pointer_url "$INSTANCE_TMP/pointer")"
1668 [ -n "$url" ] || {
1669 cleanup_instance_tmp
1670 refuse "$VALLEY_POINTER at $at names no repository — it wants one line, the owning valley as git fetch takes it; nothing derived"
1671 return 1
1672 }
1673
1674 bare="$INSTANCE_TMP/valley.git"
1675 git init --quiet --bare "$bare" || {
1676 cleanup_instance_tmp
1677 refuse "no scratch repository to fetch the floor into; nothing derived"
1678 return 1
1679 }
1680 git -C "$bare" fetch --quiet --depth 1 "$url" "$VALLEY_POINTER_REF" || {
1681 cleanup_instance_tmp
1682 refuse "could not fetch the owning valley $url at $VALLEY_POINTER_REF (named by $VALLEY_POINTER at $at); nothing derived"
1683 return 1
1684 }
1685
1686 copy_layer "$bare" FETCH_HEAD "$INSTANCE_DIR" "$dest" && rc=0 || rc=$?
1687 case "$rc" in
1688 0) ;;
1689 1)
1690 cleanup_instance_tmp
1691 refuse "the owning valley $url holds no *.cue in $INSTANCE_DIR/ at $VALLEY_POINTER_REF; nothing derived"
1692 return 1
1693 ;;
1694 *)
1695 cleanup_instance_tmp
1696 refuse "could not read $INSTANCE_DIR/ from $url; nothing derived"
1697 return 1
1698 ;;
1699 esac
1700
1701 POLICY_INSTANCE="$dest"
1702 POLICY_INSTANCE_LABEL="$url $INSTANCE_DIR@$VALLEY_POINTER_REF"
1703}
1704
1705# Is this check mandatory in this class, or a default the project left
1706# alone? The bit is the form of the composed value, so the test is CUE's
1707# own: a project supplying `false` either conflicts or unifies cleanly.
1708# Answering by unifying rather than by inspecting syntax means the script
1709# cannot disagree with `cue vet`.
1710#
1711# This is the one producer whose failure does not end the derivation. A
1712# probe that fails for any other reason, or that cannot be written, reads as
1713# mandatory, which is the strict answer, and the bit never changes which
1714# checks are owed.
1715check_is_mandatory() {
1716 local class="$1" check="$2" field
1717 if [ "$class" = unclassified ]; then
1718 field="policy: unclassified: \"$check\": false"
1719 else
1720 field="policy: classes: \"$class\": requires: \"$check\": false"
1721 fi
1722 # A probe that could not be written may leave the last one in its place,
1723 # and that one answers for another check. Mandatory is the strict answer.
1724 printf 'package verification\n%s\n' "$field" > "$POLICY_TMP/probe.cue" \
1725 || return 0
1726 ! cue vet "${POLICY_LAYER[@]}" "$POLICY_TMP/probe.cue" > /dev/null 2>&1
1727}
1728
1729# Every side of the diff: an added, modified or deleted path, and both the
1730# old and the new path of a rename or copy. It reads `git diff -z
1731# --name-status` on stdin, because a path may contain anything but NUL, and
1732# fails on a record cut short — including one cut inside its status, which
1733# a plain `while read` would end on quietly, dropping the record. It also
1734# fails when a write fails: the caller runs without `errexit`, so a lost
1735# path would otherwise end in a normal EOF and a status of 0.
1736diff_paths() {
1737 local status path
1738 while IFS= read -r -d '' status || { [ -z "$status" ] || return 1; false; }; do
1739 IFS= read -r -d '' path || return 1
1740 printf '%s\n' "$path" || return 1
1741 case "$status" in
1742 R* | C*)
1743 IFS= read -r -d '' path || return 1
1744 printf '%s\n' "$path" || return 1
1745 ;;
1746 esac
1747 done
1748}
1749
1750# Lines in, one comma-separated line out.
1751join_lines() {
1752 local out="" line
1753 while IFS= read -r line; do out="${out:+$out, }$line"; done
1754 printf '%s' "$out"
1755}
1756
1757# Arguments in, one comma-separated line out, or `none` when there are none.
1758join_or_none() {
1759 if [ $# -eq 0 ]; then echo none; else printf '%s\n' "$@" | join_lines; fi
1760}
1761
1762# The remaining arguments, sorted, into the array the first one names. The
1763# sort is captured and its status returned: a sort read through a process
1764# substitution that fails reads as a sort of nothing, and for a list of
1765# owed checks that is a change owing none.
1766#
1767# The destination is a nameref, so what is assigned is the caller's array,
1768# and the linter cannot see that array being read.
1769# shellcheck disable=SC2034
1770sort_into() {
1771 local -n sort_into_dest="$1"
1772 local sorted
1773 shift
1774 sort_into_dest=()
1775 [ $# -gt 0 ] || return 0
1776 sorted="$(printf '%s\n' "$@" | sort)" || return 1
1777 mapfile -t sort_into_dest <<<"$sorted"
1778}
1779
1780# The target: the ref a change is derived against, and the tip both policy
1781# layers are read out of. origin's answer is preferred, because the target
1782# is the branch as the integrator holds it and not as this checkout last
1783# built it.
1784#
1785# Only a ref that is not there falls through to the next. show-ref says
1786# "not there" with 1 and fails any other way with another status, so a
1787# read of origin's ref that failed ends here: falling through would read
1788# the policy out of the local main, which may be older. 1 no main at all,
1789# 2 a read failed.
1790target_ref() {
1791 local ref rc
1792 for ref in refs/remotes/origin/main refs/heads/main; do
1793 git show-ref --verify --quiet "$ref" && rc=0 || rc=$?
1794 case "$rc" in
1795 0) echo "$ref"; return 0 ;;
1796 1) ;;
1797 *) return 2 ;;
1798 esac
1799 done
1800 return 1
1801}
1802
1803# ----------------------------------------------------------------------
1804# The derivation itself, and the globals it answers with. Everything a
1805# caller could want from the policy comes out of one pass, because every
1806# part of it is a function of the same composition: `checks` prints the
1807# answer, approve runs what it names.
1808#
1809# It reports and returns rather than dying, so that a caller inside the
1810# review loop is refused rather than ended. Its callers are all in a
1811# condition, which suspends `set -e` for the whole call, so every step is
1812# checked by hand.
1813#
1814# Every producer — git, cue, sort — writes a file or a variable, and its
1815# status is checked before anything reads what it wrote. A producer read
1816# through a process substitution loses its status, and a failed one then
1817# reads as an empty list: no changed paths, no catalogue, no classes. Each
1818# of those derives a change that owes nothing, which is the one answer a
1819# failure must never give.
1820DERIVED_PATHS=() # every side of the diff, sorted
1821DERIVED_MATCHED=() # the class names at least one path matched, sorted
1822DERIVED_UNCOVERED=() # the paths no class covered
1823DERIVED_OWES=0 # whether `unclassified` is what owes something
1824declare -A DERIVED_OWED=() # check -> the classes that required it
1825declare -A DERIVED_PINNED=() # check -> mandatory | default
1826declare -A CHECK_RUNNER=() # check -> nix | command
1827declare -A CHECK_ATTRIBUTE=() # check -> the flake check attribute
1828declare -A CHECK_COMMAND=() # check -> the command line
1829declare -A CHECK_COST=() # check -> quick | slow
1830
1831derive_owed() {
1832 local schema="$1" instance="$2" project="$3" base="$4" head="$5"
1833
1834 need_cue
1835 [ -f "$schema" ] || {
1836 refuse "no policy schema at $schema; nothing derived"
1837 return 1
1838 }
1839 # An unmatched glob stays literal, so the first entry is a real file
1840 # exactly when the directory holds a document.
1841 local -a instance_docs=("$instance"/*.cue) project_docs=("$project"/*.cue)
1842 [ -f "${instance_docs[0]}" ] || {
1843 refuse "no instance policy layer at $instance; nothing derived"
1844 return 1
1845 }
1846 [ -f "${project_docs[0]}" ] || {
1847 refuse "no project policy layer at $project: a project's own layer is the *.cue documents under $PROJECT_DIR/ (dcr-f41f718). Nothing derived"
1848 return 1
1849 }
1850
1851 cleanup_policy_tmp
1852 POLICY_LAYER=("$schema" "${instance_docs[@]}" "${project_docs[@]}")
1853 POLICY_TMP="$(mktemp -d)" || {
1854 refuse "no scratch directory to compose the policy in; nothing derived"
1855 return 1
1856 }
1857
1858 git diff --no-relative --name-status -M -z "$base" "$head" > "$POLICY_TMP/diff" || {
1859 refuse "could not diff $base..$head; nothing derived"
1860 return 1
1861 }
1862 diff_paths < "$POLICY_TMP/diff" > "$POLICY_TMP/paths" || {
1863 refuse "truncated diff output; nothing derived"
1864 return 1
1865 }
1866 sort -u "$POLICY_TMP/paths" > "$POLICY_TMP/paths.sorted" || {
1867 refuse "could not sort the changed paths; nothing derived"
1868 return 1
1869 }
1870 DERIVED_PATHS=()
1871 mapfile -t DERIVED_PATHS < "$POLICY_TMP/paths.sorted"
1872
1873 render_cue > "$POLICY_TMP/render.cue" || {
1874 refuse "could not write the policy render; nothing derived"
1875 return 1
1876 }
1877 cue vet -c "${POLICY_LAYER[@]}" || {
1878 refuse "the policy layers do not compose; nothing derived"
1879 return 1
1880 }
1881
1882 # The render is checked before it is read. A render that fails prints
1883 # nothing, and an empty render reads as a policy that owes nothing. A
1884 # schema older than this script fails it, by lacking a field it reads.
1885 cue eval --out text -e _render "${POLICY_LAYER[@]}" "$POLICY_TMP/render.cue" \
1886 > "$POLICY_TMP/rendered" || {
1887 refuse "the composed policy does not render (a schema older than this script is one cause); nothing derived"
1888 return 1
1889 }
1890 # Sorted once here, so every list below comes out in a stable order.
1891 sort "$POLICY_TMP/rendered" > "$POLICY_TMP/rendered.sorted" || {
1892 refuse "could not sort the composed policy; nothing derived"
1893 return 1
1894 }
1895 local -a rendered=()
1896 mapfile -t rendered < "$POLICY_TMP/rendered.sorted"
1897
1898 unset CHECK_RUNNER CHECK_ATTRIBUTE CHECK_COMMAND CHECK_COST DERIVED_OWED \
1899 DERIVED_PINNED
1900 declare -gA CHECK_RUNNER=() CHECK_ATTRIBUTE=() CHECK_COMMAND=() \
1901 CHECK_COST=() DERIVED_OWED=() DERIVED_PINNED=()
1902
1903 # The middle field is a class name for a coverage or requirement line and
1904 # a check name for a catalogue one; `key` is what both are.
1905 local -a pat_class=() pat_ere=() req_class=() req_check=()
1906 local line kind key value
1907 for line in "${rendered[@]}"; do
1908 kind="${line%%$'\t'*}"
1909 key="${line#*$'\t'}"
1910 value="${key#*$'\t'}"
1911 key="${key%%$'\t'*}"
1912 case "$kind" in
1913 path)
1914 pat_class+=("$key")
1915 pat_ere+=("$(glob_ere "$value")")
1916 ;;
1917 requires)
1918 req_class+=("$key")
1919 req_check+=("$value")
1920 ;;
1921 runner) CHECK_RUNNER["$key"]="$value" ;;
1922 attribute) CHECK_ATTRIBUTE["$key"]="$value" ;;
1923 command) CHECK_COMMAND["$key"]="$value" ;;
1924 cost) CHECK_COST["$key"]="$value" ;;
1925 esac
1926 done
1927
1928 # A pattern bash cannot compile answers 2, not 1. Read as "no match", it
1929 # would drop the pattern's class from every change it covers.
1930 local -A matched=()
1931 local path i hit rc
1932 DERIVED_UNCOVERED=()
1933 for path in "${DERIVED_PATHS[@]}"; do
1934 hit=0
1935 for ((i = 0; i < ${#pat_ere[@]}; i++)); do
1936 [[ "$path" =~ ${pat_ere[i]} ]] && rc=0 || rc=$?
1937 case "$rc" in
1938 0)
1939 matched["${pat_class[i]}"]=1
1940 hit=1
1941 ;;
1942 1) ;;
1943 *)
1944 refuse "class ${pat_class[i]} has a path pattern that does not compile (${pat_ere[i]}); nothing derived"
1945 return 1
1946 ;;
1947 esac
1948 done
1949 [ "$hit" -eq 1 ] || DERIVED_UNCOVERED+=("$path")
1950 done
1951 # A path no class covers is answered by the policy's `unclassified` set,
1952 # which is why it is treated as one more matched class rather than as an
1953 # absence.
1954 [ "${#DERIVED_UNCOVERED[@]}" -eq 0 ] || matched[unclassified]=1
1955
1956 local check
1957 DERIVED_OWES=0
1958 for ((i = 0; i < ${#req_check[@]}; i++)); do
1959 key="${req_class[i]}"
1960 check="${req_check[i]}"
1961 [ -n "${matched[$key]:-}" ] || continue
1962 [ "$key" != unclassified ] || DERIVED_OWES=1
1963 DERIVED_OWED["$check"]="${DERIVED_OWED[$check]:+${DERIVED_OWED[$check]}, }$key"
1964 if check_is_mandatory "$key" "$check"; then
1965 DERIVED_PINNED["$check"]=mandatory
1966 else
1967 DERIVED_PINNED["$check"]="${DERIVED_PINNED[$check]:-default}"
1968 fi
1969 done
1970
1971 sort_into DERIVED_MATCHED "${!matched[@]}" || {
1972 refuse "could not sort the matched classes; nothing derived"
1973 return 1
1974 }
1975}
1976
1977cmd_checks() {
1978 local root schema instance="" label project="" plabel base head target=""
1979 local names=0 cost="" costed=0 short_base short_head
1980 root="$(git rev-parse --show-toplevel 2> /dev/null)" \
1981 || die "not a git repository"
1982 policy_defaults "$root"
1983 schema="$POLICY_SCHEMA"
1984 while [ $# -gt 0 ]; do
1985 case "$1" in
1986 --schema) [ $# -ge 2 ] || die "--schema needs a file"; schema="$2"; shift 2 ;;
1987 --instance) [ $# -ge 2 ] || die "--instance needs a directory"; instance="$2"; shift 2 ;;
1988 --project) [ $# -ge 2 ] || die "--project needs a directory"; project="$2"; shift 2 ;;
1989 --names) names=1; shift ;;
1990 --cost) [ $# -ge 2 ] || die "--cost needs quick or slow"; cost="$2"; costed=1; shift 2 ;;
1991 --) shift; break ;;
1992 -*) die "unknown option: $1" ;;
1993 *) break ;;
1994 esac
1995 done
1996 [ $# -le 2 ] || die "usage: valley checks [options] [<base> [<head>]]"
1997 if [ "$costed" -eq 1 ]; then
1998 case "$cost" in
1999 quick | slow) ;;
2000 *) die "--cost takes quick or slow, not '$cost'" ;;
2001 esac
2002 [ "$names" -eq 1 ] || die "--cost filters the --names list; pass --names too"
2003 fi
2004
2005 head="$(git rev-parse --verify --quiet "${2:-HEAD}^{commit}")" \
2006 || die "no such commit: ${2:-HEAD}"
2007 # The target is what the layers are read out of, so it is needed whenever
2008 # either layer is left to its default — and it is what an unnamed base
2009 # is the merge base with.
2010 if [ -z "$instance" ] || [ -z "$project" ] || [ $# -lt 1 ]; then
2011 target="$(target_ref)" || {
2012 [ $? -eq 1 ] || die "could not read the main branch; nothing derived"
2013 die "no main branch: the target's tip is where the policy layers are read from, and there is none here"
2014 }
2015 fi
2016 if [ $# -ge 1 ]; then
2017 base="$(git rev-parse --verify --quiet "$1^{commit}")" \
2018 || die "no such commit: $1"
2019 else
2020 base="$(git merge-base "$target" "$head")" \
2021 || die "$head and ${target#refs/} do not share history — name a base"
2022 fi
2023
2024 trap 'cleanup_policy_tmp; cleanup_instance_tmp; cleanup_project_tmp' EXIT
2025 # Each layer is resolved only when nobody named one. --instance and
2026 # --project are a reader pointing this at a layer on purpose, and
2027 # honouring that means not fetching the repository, and not reading the
2028 # tip, that the named layer replaced.
2029 if [ -n "$instance" ]; then
2030 label="${instance#"$root"/}"
2031 else
2032 resolve_instance_layer "$root" "$target" || exit 1
2033 instance="$POLICY_INSTANCE"
2034 label="$POLICY_INSTANCE_LABEL"
2035 fi
2036 if [ -n "$project" ]; then
2037 plabel="${project#"$root"/}"
2038 else
2039 resolve_project_layer "$root" "$target" || exit 1
2040 project="$POLICY_PROJECT"
2041 plabel="$POLICY_PROJECT_LABEL"
2042 fi
2043 derive_owed "$schema" "$instance" "$project" "$base" "$head" || exit 1
2044
2045 # The owed checks, sorted, and grouped by the cost the policy declares.
2046 # The grouping changes nothing owed: approve runs every owed check, and
2047 # the integrator requires evidence for every one, whatever it costs.
2048 local check width=0
2049 local -a owed=() quick=() slow=() listed=()
2050 sort_into owed "${!DERIVED_OWED[@]}" \
2051 || die "could not sort the owed checks; nothing derived"
2052 for check in "${owed[@]}"; do
2053 [ "${#check}" -le "$width" ] || width="${#check}"
2054 if [ "${CHECK_COST[$check]}" = slow ]; then
2055 slow+=("$check")
2056 else
2057 quick+=("$check")
2058 fi
2059 done
2060
2061 # The form for agents and scripts: the names alone, one per line.
2062 if [ "$names" -eq 1 ]; then
2063 case "$cost" in
2064 quick) listed=("${quick[@]}") ;;
2065 slow) listed=("${slow[@]}") ;;
2066 *) listed=("${owed[@]}") ;;
2067 esac
2068 [ "${#listed[@]}" -eq 0 ] || printf '%s\n' "${listed[@]}"
2069 return
2070 fi
2071
2072 # Read before the first line is printed, so a read that fails leaves no
2073 # partial report behind.
2074 short_base="$(git rev-parse --short "$base")" \
2075 || die "could not read $base; nothing derived"
2076 short_head="$(git rev-parse --short "$head")" \
2077 || die "could not read $head; nothing derived"
2078
2079 printf '%s..%s: %d changed path(s)\n' "$short_base" "$short_head" \
2080 "${#DERIVED_PATHS[@]}"
2081 printf 'policy: %s + %s\n' "$label" "$plabel"
2082 if [ "${#DERIVED_MATCHED[@]}" -eq 0 ]; then
2083 printf 'classes matched: none\n\n'
2084 else
2085 printf 'classes matched: %s\n\n' \
2086 "$(printf '%s\n' "${DERIVED_MATCHED[@]}" | join_lines)"
2087 fi
2088
2089 if [ "${#DERIVED_OWED[@]}" -eq 0 ]; then
2090 echo "required checks: none"
2091 else
2092 echo "required checks:"
2093 for check in "${owed[@]}"; do
2094 printf ' %-*s %-9s %s\n' \
2095 "$width" "$check" "${DERIVED_PINNED[$check]}" "${DERIVED_OWED[$check]}"
2096 done
2097 fi
2098
2099 if [ "${#DERIVED_UNCOVERED[@]}" -gt 0 ]; then
2100 printf '\nunclassified: %d path(s) matched no class\n' "${#DERIVED_UNCOVERED[@]}"
2101 printf ' %s\n' "${DERIVED_UNCOVERED[@]}"
2102 # The failure the `unclassified` field exists to prevent: paths outside
2103 # every class that the policy then asks nothing of.
2104 [ "$DERIVED_OWES" -eq 1 ] \
2105 || echo " the policy requires nothing of them — it is behind the tree"
2106 fi
2107
2108 # Below every line the integrator reads (integrator/policy.go), and
2109 # unindented, so neither line can read as a required check.
2110 if [ "${#owed[@]}" -gt 0 ]; then
2111 printf '\nquick: %s\n' "$(join_or_none "${quick[@]}")"
2112 printf 'slow: %s\n' "$(join_or_none "${slow[@]}")"
2113 fi
2114}
2115
2116main() {
2117 local verb="${1:-help}"
2118 if [ $# -gt 0 ]; then shift; fi
2119 # The verb set is mirrored in completions/ (valley.bash, _valley) —
2120 # update both when it changes.
2121 case "$verb" in
2122 pending) cmd_pending "$@" ;;
2123 review) cmd_review "$@" ;;
2124 approve) cmd_approve "$@" ;;
2125 rebase) cmd_rebase "$@" ;;
2126 status | ready | unready | withdraw) cmd_go "$verb" "$@" ;;
2127 checks) cmd_checks "$@" ;;
2128 tail) cmd_tail "$@" ;;
2129 replay) cmd_replay "$@" ;;
2130 help | -h | --help) usage ;;
2131 *)
2132 printf 'valley: unknown verb: %s\n\n' "$verb" >&2
2133 usage >&2
2134 exit 1
2135 ;;
2136 esac
2137}
2138
2139main "$@"