gunk-dev/the-valley

valley

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