gunk-dev/the-valley

valley

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