gunk-dev/the-valley

valley

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