gunk-dev/the-valley

valley

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