gunk-dev/the-valley

valley

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