gunk-dev/the-valley

valley

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