gunk-dev/the-valley

valley

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