gunk-dev/the-valley

valley

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