gunk-dev/the-valley

valley

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