gunk-dev/the-valley

valley

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