gunk-dev/the-valley

valley

source4cf069f09fc8main's published tip history
54.9 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# .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, and again by review's [a]sk, which
17# needs the attest helper —
18# graduation is now owed; recording the decision node is part of taking it.);
19# - its behavior gets subtle enough to need real tests
20# (CROSSED by checks: glob matching is pinned by the policy-deriver
21# flake check, not by reading the code.);
22# - it needs nontrivial parsing or concurrency
23# (CROSSED by checks: glob-to-regex translation and -z diff parsing.).
24# The size tripwire (~300 lines) is crossed too. Which way to take the
25# graduation is dcr-2aa1a12, still `proposed`.
26# Graduation is a deliberate act, recorded as a decision node.
27# Precedent: klaus — born in cosmo, graduated deliberately.
28
29set -euo pipefail
30
31die() {
32 printf 'valley: %s\n' "$*" >&2
33 exit 1
34}
35
36usage() {
37 cat <<'EOF'
38valley — S1 integrator verbs for a valley project
39
40usage: valley <verb> [args]
41
42 pending list branches on origin not merged into origin/main
43 review <branch> page through the branch's log and diff vs origin/main,
44 then choose:
45 [a]sk file an integration request. runs the
46 checks the composed policy requires of
47 this change over a throwaway worktree of
48 the branch, signs each result as an
49 attestation, and publishes the evidence
50 and the request ref to origin in ONE
51 atomic push. main is never touched: the
52 integrator judges the request and lands
53 it. the policy is composed from the
54 target's tip and the owning valley's, as
55 checks describes below, so your checkout
56 can be on any branch. a change the policy
57 requires no check of is filed too, as a
58 request with no evidence, and says so.
59 needs the attest helper and
60 VALLEY_ATTEST_KEY, the ed25519 key this
61 host signs with, whenever a check is
62 owed; VALLEY_ATTEST_NAME is the name it
63 signs under, defaulting to this host's.
64 [r]eject delete the remote branch (confirmed first)
65 [s]kip do nothing
66 [a]sk is the only way a change reaches main from here.
67 Nothing in this script writes the protected ref: the
68 integrator does, having judged the request.
69 a stale branch (won't fast-forward from main) is first
70 offered:
71 [b]ase rebase it onto origin/main in a throwaway
72 worktree, push --force-with-lease, then
73 re-review the diff that would actually land
74 [a]sk is offered there too: a stale branch is nothing
75 the integrator cannot apply, so it need not be rebased
76 first.
77 while paging, press v: less opens the diff in $EDITOR.
78 every line you insert there is a note. it is anchored to
79 the file and new-side line it sits on — to the file alone
80 when it sits above the first hunk — then appended to
81 $XDG_STATE_HOME/valley/notes/<branch>.md (default
82 ~/.local/state) and printed after the verdict. notes
83 survive [b]ase. lines you change or delete instead of
84 inserting are ignored, with a warning.
85 checks [<base> [<head>]]
86 print the check names the change between two commits owes
87 under the composed verification policy (dcr-f41f718), and
88 which class made each one required. It prints: no check is
89 run, nothing is gated, nothing is written.
90 base defaults to the merge base with main, head to HEAD.
91 by default both layers come from the target's tip
92 (origin/main), never from your checkout: the project's
93 own layer is policy/project there, and the owning valley
94 is named one line at policy/valley there, fetched and
95 read at policy/instance in that repository's integrated
96 tip. a valley's own config repository carries
97 policy/instance and uses it. a target carrying no
98 policy/project is derived under the floor alone; a floor
99 that is not there is refused. this is what the
100 integrator reads, so the answer is the same from any
101 branch, however stale. an option overrides each layer,
102 which is the only way to derive against a layer that
103 does not govern — the worked example under
104 examples/policy/, say:
105 --schema FILE default schema/verification.cue
106 --instance DIR default the owning valley's floor
107 --project DIR default policy/project at the target
108 naming a layer stops this reading the source it
109 replaced. the schema is the shape a policy is written
110 in rather than a layer, so it comes from this checkout.
111 tail [subject] watch bus events scroll by (default subject: valley.>);
112 the server comes from the nats CLI's own config
113 (NATS_URL or a nats context; default localhost)
114 replay [dir] publish one ref-updated event per current ref of the
115 repo at dir (default: .) — rebuilds the stream's
116 projection, e.g. after nats stream purge valley
117 help show this help
118
119Runs from any checkout of the project; needs only git and coreutils,
120except tail and replay, which also need the nats CLI (natscli), checks,
121which also needs the cue CLI, review's notes, which need less, and
122review's [a]sk, which needs both the cue CLI and the attest helper.
123Deriving a policy fetches the owning valley's repository, so checks and
124[a]sk also need whatever reaching it takes.
125No config, no batch mode, and no state but the notes file — the judgment
126stays with the human.
127EOF
128}
129
130fetch_origin() {
131 git fetch --prune --quiet origin
132}
133
134# Resolve the pager as git would for a diff: pager.diff first (per-command
135# pager configs — e.g. home-manager's delta module — set pager.diff and leave
136# core.pager alone), then git var GIT_PAGER (core.pager, GIT_PAGER, PAGER,
137# less). pager.<cmd> may legally be a boolean; treat true/false — and an
138# empty or missing value — as unset and fall back. The value is
139# shell-interpreted, hence sh -c.
140diff_pager() {
141 local pager
142 pager="$(git config --get pager.diff || true)"
143 case "$pager" in '' | true | false) pager="$(git var GIT_PAGER)" ;; esac
144 printf '%s' "$pager"
145}
146
147# Page a file rather than a pipe, so less's v key has something to hand
148# $EDITOR: with a real file open, v runs LESSEDIT, whose default
149# `%E ?lm+%lm. %g` is the editor, +<line>, and the file name. That file is
150# the review buffer, and editing it is how notes get written (see
151# collect_notes). A pipe has no name, so less refuses to edit one — which is
152# why review no longer pipes.
153#
154# The configured diff pager stays the renderer, but as less's input
155# preprocessor rather than as the pager. It still reads the buffer on stdin
156# exactly as it did when it was the pager, less displays what it emits, and
157# less still calls the raw buffer "the current file" — so v edits the diff
158# and not the rendering. The alternative was to page the buffer with no
159# filter at all: exact, and it throws delta's rendering away, which is the
160# worse trade for a verb whose whole job is reading a diff.
161#
162# What this costs is the line number. A filter that restructures the diff —
163# delta's default rendering does — makes %lm a line of the rendered view, so
164# the editor opens near the cursor rather than on it. A structure-preserving
165# filter (pager.diff = `delta --color-only`) makes it exact. No anchor
166# depends on it: a note is anchored by where it was inserted, not by where
167# the editor opened.
168page_file() {
169 local file="$1" pager
170 [ -t 1 ] || { cat -- "$file"; return; } # a non-tty just cats
171 pager="$(diff_pager)"
172 case "${pager%%[[:space:]]*}" in
173 less | */less)
174 # Already less: give it the file and there is no filter to run.
175 sh -c "$pager \"\$1\"" sh "$file"
176 return
177 ;;
178 esac
179 # Without less there is no editor key; fall back to filtering into a pipe.
180 command -v less > /dev/null 2>&1 || {
181 sh -c "$pager" < "$file"
182 return
183 }
184 # -R because the filter's color is the whole point of running it, and no
185 # LESSCLOSE because a stray one would run against a buffer we still read.
186 LESSOPEN="|$pager < %s" env -u LESSCLOSE less -R -- "$file"
187}
188
189pending_line() {
190 local ref="$1" age author ahead stat
191 age="$(git log -1 --format='%cr' "$ref")"
192 author="$(git log -1 --format='%an' "$ref")"
193 ahead="$(git rev-list --count "origin/main..$ref")"
194 stat="$(git diff --shortstat "origin/main...$ref")"
195 stat="${stat# }"
196 printf '%s | %s | %s | ahead %s | %s\n' \
197 "${ref#origin/}" "$age" "$author" "$ahead" "${stat:-no file changes}"
198}
199
200cmd_pending() {
201 [ $# -eq 0 ] || die "pending takes no arguments"
202 fetch_origin
203 local ref found=0
204 while IFS= read -r ref; do
205 case "$ref" in
206 origin/HEAD | origin/main) continue ;;
207 esac
208 found=1
209 pending_line "$ref"
210 done < <(git for-each-ref --format='%(refname:short)' \
211 --no-merged=origin/main refs/remotes/origin)
212 [ "$found" -eq 1 ] || echo "nothing pending"
213}
214
215reject() {
216 local branch="$1" answer
217 printf 'really delete origin/%s? [y/N] ' "$branch"
218 read -r answer || answer=""
219 case "$answer" in
220 y | Y | yes)
221 git push --quiet origin --delete "$branch"
222 echo "rejected $branch: deleted from origin"
223 ;;
224 *) echo "kept $branch" ;;
225 esac
226}
227
228# ----------------------------------------------------------------------
229# review notes — the lines the reviewer inserts into the paged diff.
230#
231# The buffer the reviewer pages is a file, so the pager's editor key can open
232# it (page_file). Whatever comes back with lines inserted is read as notes:
233# no marker, no syntax, no mode — an inserted line is a note because it was
234# not there before. What a note is *about* is where it sits, so each one is
235# anchored to the file and the new-side line number of the diff line above
236# it, which is the pair a reviewer would otherwise have to copy out by hand.
237
238# The scratch directory holding the buffer and its pristine copy, and the
239# notes taken so far in this review — a global because [b]ase pages a second
240# time and the notes from the first pass are not thereby withdrawn.
241REVIEW_TMP=""
242NOTES=()
243
244cleanup_review_tmp() {
245 [ -n "$REVIEW_TMP" ] || return 0
246 rm -rf "$REVIEW_TMP"
247 REVIEW_TMP=""
248}
249
250# Where a branch's notes live. XDG_STATE_HOME is the right home for them:
251# they are neither config nor cache, and losing them loses judgment.
252notes_file() {
253 printf '%s/valley/notes/%s.md\n' "${XDG_STATE_HOME:-$HOME/.local/state}" "$1"
254}
255
256# The anchor of every line of the buffer, by line: the file that line belongs
257# to, and the new-side line number it sits on. Built in one pass so that
258# anchoring a note is a lookup. An empty path means the line is above every
259# file (the log); line 0 means the line is a file header, above every hunk.
260ANCHOR_PATH=()
261ANCHOR_LINE=()
262
263anchor_buffer() {
264 local file="$1" line path="" at=0 next=0 inhunk=0 rest
265 ANCHOR_PATH=()
266 ANCHOR_LINE=()
267 while IFS= read -r line; do
268 # Header lines are only headers outside a hunk: inside one, every line
269 # carries a +/-/space prefix, so a diff of a diff cannot be misread.
270 if [ "$inhunk" -eq 1 ]; then
271 case "$line" in
272 ' '* | '+'* | '')
273 at="$next" # this line's own new-side number
274 next=$((next + 1))
275 ;;
276 '-'* | \\*) ;; # a removal or the no-newline marker: no new-side line
277 *) inhunk=0 ;;
278 esac
279 fi
280 if [ "$inhunk" -eq 0 ]; then
281 case "$line" in
282 'diff --git '*)
283 path=""
284 # The b/ side, so a rename anchors to the name it will have.
285 if [[ "$line" =~ ^diff\ --git\ a/(.*)\ b/(.*)$ ]]; then
286 path="${BASH_REMATCH[2]}"
287 fi
288 at=0
289 ;;
290 '@@ '*)
291 rest="${line#*+}" # -12,7 +34,9 @@ -> 34,9 @@
292 at="${rest%%[!0-9]*}"
293 [ -n "$at" ] || at=0
294 next="$at"
295 inhunk=1
296 ;;
297 esac
298 fi
299 ANCHOR_PATH+=("$path")
300 ANCHOR_LINE+=("$at")
301 done < "$file"
302}
303
304# The anchor for a note inserted after buffer line n, as it is written down.
305anchor_of() {
306 local n="$1" path line
307 [ "$n" -ge 1 ] || { printf '(unanchored)'; return; }
308 path="${ANCHOR_PATH[n - 1]:-}"
309 line="${ANCHOR_LINE[n - 1]:-0}"
310 if [ -z "$path" ]; then
311 printf '(unanchored)'
312 elif [ "$line" -eq 0 ]; then
313 printf '%s' "$path"
314 else
315 printf '%s:%s' "$path" "$line"
316 fi
317}
318
319# The notes in an edited buffer, one `anchor: text` line each. git says where
320# the reviewer's lines landed; a hunk that removes nothing is an insertion,
321# and the line it was inserted after is the anchor. A hunk that removes
322# something is an edit of the diff itself — it anchors to nothing, since the
323# line it would name is the line it changed — so it is dropped with a count.
324notes_in() {
325 local orig="$1" edited="$2" line rest at old insert=0 touched=0 text
326 anchor_buffer "$orig"
327 while IFS= read -r line; do
328 case "$line" in
329 '@@ '*)
330 rest="${line#@@ -}" # 12,0 +13,2 @@ -> 12,0 +13,2 @@
331 at="${rest%%[!0-9]*}"
332 rest="${rest#"$at"}"
333 old=1
334 case "$rest" in
335 ,*)
336 rest="${rest#,}"
337 old="${rest%%[!0-9]*}"
338 ;;
339 esac
340 if [ "$old" -eq 0 ]; then
341 insert=1
342 else
343 insert=0
344 touched=$((touched + old))
345 fi
346 ;;
347 '+'*)
348 # Only inside an insertion hunk: the +++ of git's own header is not
349 # a note, and neither is the new side of an edit.
350 [ "$insert" -eq 1 ] || continue
351 text="${line#+}"
352 text="${text#"${text%%[![:space:]]*}"}"
353 [ -n "$text" ] || continue # a blank line says nothing
354 printf '%s: %s\n' "$(anchor_of "$at")" "$text"
355 ;;
356 esac
357 done < <(git --no-pager diff --no-ext-diff --no-index -U0 -- "$orig" "$edited")
358 [ "$touched" -eq 0 ] || printf \
359 'valley: warning: %d changed or deleted diff line(s) ignored — a note is a line you insert\n' \
360 "$touched" >&2
361}
362
363# Read the notes out of the paged buffer and keep them: appended to the
364# branch's notes file under the commit they were taken against, and held for
365# the print that follows the verdict. A notes file that cannot be written is
366# a warning, never a failure — the notes are still printed, and a review is
367# not undone by a missing directory.
368collect_notes() {
369 local branch="$1" sha="$2" file dir
370 local -a found=()
371 mapfile -t found < <(notes_in "$REVIEW_TMP/review.orig" "$REVIEW_TMP/review.diff")
372 [ "${#found[@]}" -gt 0 ] || return 0
373 NOTES+=("${found[@]}")
374 file="$(notes_file "$branch")"
375 dir="${file%/*}"
376 mkdir -p "$dir" 2> /dev/null && {
377 printf '## %s at %s\n\n' "$branch" "$sha"
378 printf '%s\n' "${found[@]}"
379 printf '\n'
380 } >> "$file" 2> /dev/null && return 0
381 printf 'valley: warning: could not write %s — the notes are printed only\n' \
382 "$file" >&2
383}
384
385print_notes() {
386 local branch="$1"
387 [ "${#NOTES[@]}" -gt 0 ] || return 0
388 printf '\n%d note(s) on %s, appended to %s:\n' \
389 "${#NOTES[@]}" "$branch" "$(notes_file "$branch")"
390 printf ' %s\n' "${NOTES[@]}"
391}
392
393show_review() {
394 local branch="$1" sha
395 sha="$(git rev-parse --short "refs/remotes/origin/$branch")"
396 REVIEW_TMP="$(mktemp -d)"
397 {
398 printf 'branch %s, log against origin/main:\n\n' "$branch"
399 git --no-pager log --oneline "origin/main..origin/$branch"
400 printf '\n'
401 git --no-pager diff "origin/main...origin/$branch"
402 } > "$REVIEW_TMP/review.diff"
403 cp "$REVIEW_TMP/review.diff" "$REVIEW_TMP/review.orig"
404 page_file "$REVIEW_TMP/review.diff" || true # quitting the pager early is not an error
405 collect_notes "$branch" "$sha"
406 cleanup_review_tmp
407}
408
409# Throwaway worktree for review's [b]ase choice; a global so the traps can
410# always clean it up — success, conflict, or ctrl-C. Never a mid-rebase state.
411REBASE_WT=""
412cleanup_rebase_wt() {
413 [ -n "$REBASE_WT" ] || return 0
414 git -C "$REBASE_WT" rebase --abort >/dev/null 2>&1 || true
415 git worktree remove --force "$REBASE_WT" >/dev/null 2>&1 || true
416 rm -rf "$REBASE_WT"
417 REBASE_WT=""
418}
419
420# Everything review leaves outside the repository: the two throwaway
421# worktrees, the paged buffer, the two policy layers read out of their
422# tips, and the scratch the policy deriver writes into. One handler,
423# installed once by cmd_review, so that no path through the verb — and no
424# ctrl-C in the pager — leaves any of them behind.
425cleanup_review() {
426 cleanup_rebase_wt
427 cleanup_ask_wt
428 cleanup_policy_tmp
429 cleanup_instance_tmp
430 cleanup_project_tmp
431 cleanup_review_tmp
432}
433
434# Rebase origin/<branch> onto origin/main in an isolated worktree — the
435# user's checkout is never touched — and push with a lease so a concurrently
436# updated branch is never clobbered. Mechanics only; the judgment on the
437# rebased diff stays with the human, back at the review prompt.
438rebase_onto_main() {
439 local branch="$1"
440 REBASE_WT="$(mktemp -d)"
441 git worktree add --quiet --detach "$REBASE_WT" "refs/remotes/origin/$branch"
442 if ! git -C "$REBASE_WT" rebase --quiet refs/remotes/origin/main; then
443 cleanup_rebase_wt
444 die "$branch conflicts with main — resolve by hand; nothing changed"
445 fi
446 if ! git -C "$REBASE_WT" push --quiet --force-with-lease \
447 origin "HEAD:refs/heads/$branch"; then
448 cleanup_rebase_wt
449 die "lease on origin/$branch failed (it moved since the fetch); nothing pushed"
450 fi
451 cleanup_rebase_wt
452 echo "rebased $branch onto origin/main, pushed with --force-with-lease"
453}
454
455# ----------------------------------------------------------------------
456# ask — file an integration request for the branch under review.
457#
458# This is the one way a change reaches main from here: the checks the
459# policy requires are run over the branch's tree and signed, the evidence
460# and one request ref are published, and the integrator judges the request
461# and lands it (design/integration.md). main is never touched from here.
462#
463# Nothing in this script writes the protected ref. Whether a given pusher
464# may write it is a fact about origin's pre-receive hook, so origin is
465# where it is answered, and a verb that merged onto main locally would only
466# be asking the same question in a worse place.
467#
468# What this verb removes is a second push. `attest run --push` publishes
469# the branch and the attestation refs in one atomic push and knows nothing
470# about a request ref, so filing a request by hand is two beats: the
471# evidence, then the request after it. In between, evidence stands
472# published for a change nobody has asked to land. So this verb does not
473# use --push at all. `attest run` without it stores each note at its ref in
474# the repository and stops, and one `git push --atomic` then carries the
475# evidence and the request together — all of it or none of it. Nothing in
476# attest had to change for that; the sequencing was the whole of it.
477#
478# The branch itself is not in that push. What is under review is
479# origin/<branch>, so the commit the request names is already on origin and
480# the objects with it.
481
482# The tree the checks run over: a throwaway worktree of the branch, as
483# [b]ase uses, so that what is checked is the branch's tree and not the
484# operator's working copy. A global, so the traps clean it up whatever
485# happens.
486ASK_WT=""
487cleanup_ask_wt() {
488 [ -n "$ASK_WT" ] || return 0
489 git worktree remove --force "$ASK_WT" > /dev/null 2>&1 || true
490 rm -rf "$ASK_WT"
491 ASK_WT=""
492}
493
494# Report and fail, without leaving the review. A refusal here is not a
495# reason to end the session: the branch is still under review and the
496# operator can still answer. die() is for the verbs that have nothing left
497# to offer.
498refuse() {
499 printf 'valley: %s\n' "$*" >&2
500 return 1
501}
502
503# The change segment of a request ref. The integrator reads a request as
504# <prefix>/<target>/<change> and refuses a change segment holding a slash
505# (integrator/refs.go), so a branch name with one is written with dashes
506# instead. The ref that results is printed, never left to be assumed.
507change_name() {
508 printf '%s' "${1//\//-}"
509}
510
511# File the request. Called from the review prompt in a condition, which
512# suspends `set -e` for the whole call — so every step below is checked by
513# hand, and the failures say what was published before they happened.
514ask() {
515 local branch="$1" target=main tip change head base digest root ref check spec
516 local key
517 local -a signer=() owed=() run=() evidence=()
518
519 root="$(git rev-parse --show-toplevel)" || {
520 refuse "not a git repository; nothing published"
521 return 1
522 }
523 tip=refs/remotes/origin/main
524 head="$(git rev-parse "refs/remotes/origin/$branch")" || {
525 refuse "no such branch on origin: $branch; nothing published"
526 return 1
527 }
528 base="$(git merge-base "$tip" "$head")" || {
529 refuse "$branch and main share no history; nothing published"
530 return 1
531 }
532 change="$(change_name "$branch")"
533 ref="refs/the-valley/integration-requests/$target/$change"
534
535 # What the change owes, read out of exactly the sources the integrator
536 # reads: both layers from the target's tip, which review has just
537 # fetched, and the floor from the owning valley's own tip. A change never
538 # supplies the policy that gates it, and neither does the checkout this
539 # runs from — so the answer here is the same answer the integrator will
540 # derive, from whatever branch the operator happens to be on. It is
541 # printed for exactly that reason.
542 policy_defaults "$root"
543 resolve_instance_layer "$root" "$tip" || return 1
544 resolve_project_layer "$root" "$tip" || return 1
545 derive_owed "$POLICY_SCHEMA" "$POLICY_INSTANCE" "$POLICY_PROJECT" \
546 "$base" "$head" || return 1
547 [ "${#DERIVED_OWED[@]}" -eq 0 ] \
548 || mapfile -t owed < <(printf '%s\n' "${!DERIVED_OWED[@]}" | sort)
549
550 # A change the policy asks nothing of is still a change, and asking is
551 # how one reaches main. The integrator already lands a request owing no
552 # check and records the landing as one that required nothing
553 # (design/integration.md), so refusing to file it here would strand
554 # exactly the changes the policy requires nothing of. Nothing is owed, so
555 # nothing is signed and no key is needed: what gets published is one
556 # request ref and no evidence at all.
557 if [ "${#owed[@]}" -gt 0 ]; then
558 key="${VALLEY_ATTEST_KEY:-}"
559 [ -n "$key" ] || {
560 refuse "no signing key: set VALLEY_ATTEST_KEY to the ed25519 key this host attests with. The host signs; nothing published"
561 return 1
562 }
563 [ -f "$key" ] || {
564 refuse "no signing key at $key; nothing published"
565 return 1
566 }
567 command -v attest > /dev/null 2>&1 || {
568 refuse "this choice needs the attest helper; nix run .#valley bundles it. Nothing published"
569 return 1
570 }
571 signer=(--key "$key")
572 [ -z "${VALLEY_ATTEST_NAME:-}" ] || signer+=(--name "$VALLEY_ATTEST_NAME")
573
574 for check in "${owed[@]}"; do
575 case "${CHECK_RUNNER[$check]:-}" in
576 nix) run+=(--check "$check=${CHECK_ATTRIBUTE[$check]}") ;;
577 command) run+=(--command "$check=${CHECK_COMMAND[$check]}") ;;
578 *)
579 refuse "the policy requires $check but does not say how to run it; nothing published"
580 return 1
581 ;;
582 esac
583 done
584
585 cleanup_ask_wt
586 ASK_WT="$(mktemp -d)" || {
587 refuse "no scratch directory to check $branch in; nothing published"
588 return 1
589 }
590 git worktree add --quiet --detach "$ASK_WT" "$head" || {
591 cleanup_ask_wt
592 refuse "could not check $branch out to run its checks; nothing published"
593 return 1
594 }
595
596 printf '\nchecking %s at %s: %s\n' "$branch" "$(git rev-parse --short "$head")" \
597 "$(printf '%s\n' "${owed[@]}" | join_lines)"
598 if ! attest run --repo "$ASK_WT" "${signer[@]}" "${run[@]}"; then
599 cleanup_ask_wt
600 refuse "the checks did not pass; nothing published, main untouched"
601 return 1
602 fi
603 digest="$(attest digest --repo "$ASK_WT")" || {
604 cleanup_ask_wt
605 refuse "could not digest the tree that was checked; nothing published"
606 return 1
607 }
608 cleanup_ask_wt
609 digest="${digest#*:}"
610
611 # Every attestation stored for this tree, whoever signed it: the
612 # evidence for this change is what the subject digest is keyed by, not
613 # what this run happened to add to it.
614 mapfile -t evidence < <(git for-each-ref --format='%(refname)' \
615 "refs/the-valley/attestations/$digest")
616 [ "${#evidence[@]}" -gt 0 ] || {
617 refuse "no attestation is stored for $digest; nothing published"
618 return 1
619 }
620 else
621 printf '\n%s owes no check under %s + %s; filing the request with no evidence\n' \
622 "$branch" "$POLICY_INSTANCE_LABEL" "$POLICY_PROJECT_LABEL"
623 fi
624
625 # The one push: every evidence ref as it stands, and the request ref at
626 # the branch's head. --atomic, so a hook that refuses any of them leaves
627 # origin exactly as it was. With nothing owed it carries the request
628 # alone, which is the same push with the empty half left out.
629 local -a push=()
630 for spec in ${evidence[@]+"${evidence[@]}"}; do push+=("$spec:$spec"); done
631 push+=("$head:$ref")
632 if ! git push --atomic --quiet origin "${push[@]}"; then
633 if [ "${#evidence[@]}" -eq 0 ]; then
634 refuse "origin refused the push; nothing was published there and main is untouched"
635 else
636 refuse "origin refused the push; nothing was published there and main is untouched. The evidence is stored locally at:"
637 printf ' %s\n' "${evidence[@]}" >&2
638 fi
639 return 1
640 fi
641
642 printf '\nrequested %s -> refs/heads/%s\n' "$branch" "$target"
643 printf ' request %s -> %s\n' "$ref" "$(git rev-parse --short "$head")"
644 if [ "${#evidence[@]}" -eq 0 ]; then
645 printf ' evidence none — nothing was owed, so nothing was signed\n'
646 printf ' checks none — the policy requires no check of this change\n'
647 else
648 printf ' evidence %s\n' "${evidence[@]}"
649 printf ' checks %s\n' "$(printf '%s\n' "${owed[@]}" | join_lines)"
650 fi
651 printf ' main is untouched; the integrator judges the request and lands it\n'
652}
653
654# Page the branch and take the verdict. Split out of cmd_review so that
655# every way out of it — ask, reject, skip — is followed by the notes.
656read_and_decide() {
657 local branch="$1" choice
658 show_review "$branch"
659 # A stale branch's pre-rebase diff is not what would land; offer to rebase it
660 # mechanically, then re-review what actually would. [a]sk is offered here as
661 # well, because the integrator applies a delta to the tip rather than
662 # fast-forwarding: a stale branch is a request it can judge, and rebasing
663 # first is a convenience rather than a precondition.
664 while ! git merge-base --is-ancestor refs/remotes/origin/main \
665 "refs/remotes/origin/$branch"; do
666 printf '%s does not fast-forward from main: [a]sk, [b]ase onto main, [r]eject, [s]kip? ' \
667 "$branch"
668 read -r choice || die "stdin closed before an answer; nothing done"
669 case "$choice" in
670 a) ask "$branch" && return ;;
671 b)
672 rebase_onto_main "$branch"
673 fetch_origin
674 show_review "$branch"
675 ;;
676 r) reject "$branch" && return ;;
677 s)
678 echo "skipped $branch; nothing done"
679 return
680 ;;
681 *) echo "answer a, b, r, or s" ;;
682 esac
683 done
684 while true; do
685 printf '%s: [a]sk, [r]eject, [s]kip? ' "$branch"
686 read -r choice || die "stdin closed before an answer; nothing done"
687 case "$choice" in
688 # A refusal from ask is not a verdict: it says what it did not do and
689 # the prompt comes back, so the branch can still be asked about again,
690 # rejected or skipped.
691 a) ask "$branch" && return ;;
692 r) reject "$branch" && return ;;
693 s)
694 echo "skipped $branch; nothing done"
695 return
696 ;;
697 *) echo "answer a, r, or s" ;;
698 esac
699 done
700}
701
702cmd_review() {
703 [ $# -eq 1 ] || die "usage: valley review <branch>"
704 local branch="${1#origin/}"
705 fetch_origin
706 git rev-parse --verify --quiet "refs/remotes/origin/$branch" >/dev/null \
707 || die "no such branch on origin: $branch"
708 trap cleanup_review EXIT
709 trap 'exit 130' INT TERM
710 read_and_decide "$branch"
711 # The verdict disposes of the branch; the notes are what the human made of
712 # it, so they are printed whatever the verdict was.
713 print_notes "$branch"
714}
715
716# tail and replay are thin wrappers over the nats CLI — anything they do,
717# plain nats and git can do. They are the only verbs needing more than git
718# and coreutils.
719need_nats() {
720 command -v nats >/dev/null 2>&1 \
721 || die "this verb needs the nats CLI (natscli); nix run .#valley bundles it"
722}
723
724cmd_tail() {
725 [ $# -le 1 ] || die "usage: valley tail [subject]"
726 need_nats
727 exec nats sub "${1:-valley.>}"
728}
729
730# One ref-updated event per existing ref, from git for-each-ref alone. A
731# ref's prior value is not derivable from the repository, so `old` is the
732# all-zero id — the same payload a push creating the ref would produce.
733# The payload construction mirrors the host module's publisher hook
734# (nix/valley-host.nix); change one only with the other.
735cmd_replay() {
736 [ $# -le 1 ] || die "usage: valley replay [repo-dir]"
737 need_nats
738 local dir="${1:-.}" repo sha ref event count=0
739 git -C "$dir" rev-parse --git-dir >/dev/null 2>&1 \
740 || die "not a git repository: $dir"
741 if [ "$(git -C "$dir" rev-parse --is-bare-repository)" = true ]; then
742 repo="$(basename "$(git -C "$dir" rev-parse --absolute-git-dir)" .git)"
743 else
744 repo="$(basename "$(git -C "$dir" rev-parse --show-toplevel)")"
745 fi
746 while read -r sha ref; do
747 # " is the only JSON-significant character a refname can contain (git
748 # forbids \ and control characters); names and object ids are safe.
749 event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \
750 "$repo" "${ref//\"/\\\"}" "${sha//?/0}" "$sha")"
751 nats pub "valley.git.$repo.ref-updated" "$event" >/dev/null
752 count=$((count + 1))
753 done < <(git -C "$dir" for-each-ref --format='%(objectname) %(refname)')
754 echo "replayed $count refs of $repo onto the bus"
755}
756
757# ----------------------------------------------------------------------
758# checks — the verification-policy deriver (dcr-f41f718). It composes the
759# instance layer with the project layer, matches every side of a diff
760# against the composed classes, and prints the check names the change owes
761# with the class or classes that made each one required. It reports: no
762# check is run, nothing is gated, nothing is written.
763#
764# Composition is CUE's, never this script's. The whole of the mandatory-
765# versus-overridable distinction is unification, so reimplementing it here
766# would be reimplementing the decision. What this script does that CUE
767# cannot is glob matching and reading a diff.
768
769need_cue() {
770 command -v cue >/dev/null 2>&1 \
771 || die "this verb needs the cue CLI; nix run .#valley bundles it"
772}
773
774# One glob segment as an ERE fragment: `*` and `?` are wildcards that never
775# cross a `/`, and every ERE metacharacter is escaped.
776segment_ere() {
777 local seg="$1" out="" i c
778 for ((i = 0; i < ${#seg}; i++)); do
779 c="${seg:i:1}"
780 case "$c" in
781 '*') out+='[^/]*' ;;
782 '?') out+='[^/]' ;;
783 '.' | '^' | '$' | '+' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | \\) out+="\\$c" ;;
784 *) out+="$c" ;;
785 esac
786 done
787 printf '%s' "$out"
788}
789
790# A path glob as an anchored ERE, segment by segment. A `**` segment matches
791# any number of segments including none, so it swallows the separator that
792# would otherwise follow it and `a/**/b` matches `a/b`; every other segment
793# matches exactly one.
794glob_ere() {
795 local ere='^' i last
796 local -a segs=()
797 IFS=/ read -r -a segs <<<"$1"
798 last=$((${#segs[@]} - 1))
799 for ((i = 0; i <= last; i++)); do
800 if [ "${segs[i]}" = '**' ]; then
801 if [ "$i" -eq "$last" ]; then ere+='.*'; else ere+='(.*/)?'; fi
802 else
803 ere+="$(segment_ere "${segs[i]}")"
804 [ "$i" -eq "$last" ] || ere+='/'
805 fi
806 done
807 printf '%s$' "$ere"
808}
809
810# The composed policy as one tab-separated line per covered pattern, per
811# required check, and per field of the check catalogue, so the shell never
812# parses CUE. Every line is three fields — a kind, a name, and a value —
813# whatever the kind, so one reader takes them all. The field is hidden
814# because the schema's sentinel rejects unknown top-level fields, and
815# `unclassified` is rendered as a class of that name: it is one more source
816# a check can come from.
817#
818# The catalogue is rendered because a caller that runs a check needs what
819# the policy says a check IS — its runner, and the attribute or command
820# line that runner takes. `checks` only reports and does not read it;
821# review's [a]sk turns it into the arguments attest is given.
822render_cue() {
823 cat <<'EOF'
824package verification
825
826import (
827 "list"
828 "strings"
829)
830
831_render: strings.Join(list.Concat([[
832 for cn, c in policy.classes
833 for p, on in c.paths if on {"path\t\(cn)\t\(p)"}
834], [
835 for cn, c in policy.classes
836 for k, on in c.requires if on {"requires\t\(cn)\t\(k)"}
837], [
838 for k, on in policy.unclassified if on {"requires\tunclassified\t\(k)"}
839], [
840 for n, c in policy.checks {"runner\t\(n)\t\(c.runner)"}
841], [
842 for n, c in policy.checks if c.runner == "nix" {"attribute\t\(n)\t\(c.attribute)"}
843], [
844 for n, c in policy.checks if c.runner == "command" {"command\t\(n)\t\(c.command)"}
845]]), "\n")
846EOF
847}
848
849# The composed layer, and a scratch directory for the documents the
850# derivation writes into the composition. Globals so the probe below can
851# see them.
852POLICY_LAYER=()
853POLICY_TMP=""
854
855cleanup_policy_tmp() {
856 [ -n "$POLICY_TMP" ] || return 0
857 rm -rf "$POLICY_TMP"
858 POLICY_TMP=""
859}
860
861# Where the schema and the two policy layers come from in a project
862# following the convention (dcr-f41f718).
863#
864# The client derives from exactly the sources the integrator uses
865# (integrator/policy.go), and the working tree is not among them. The
866# project's own layer is read from the TARGET's tip, the pointer naming the
867# owning valley is read from the target's tip, and the floor is read from
868# that valley's integrated tip. A change never supplies the policy that
869# gates it, and neither does whoever happens to be reviewing it: the
870# reviewer's checkout may be any branch, however stale, and derivation
871# gives the same answer from all of them.
872#
873# The schema is not a policy layer. It is the shape a policy is written in,
874# it ships with this tool, and the integrator takes its own from its
875# deployment rather than from the tip for the same reason.
876#
877# Neither layer is ever the worked example under examples/policy/ — a gate
878# derived from an example is a gate nobody wrote. `checks` takes an option
879# for each, so a reader can point it at the example or anywhere else on
880# purpose; review's [a]sk takes no such option, because a request is filed
881# against the policy that governs the project and nowhere else.
882#
883# Neither layer is a path in this tree, so policy_defaults leaves both
884# empty and the two resolvers answer for them. That split is also what
885# keeps `checks --instance DIR` from fetching a repository whose layer it
886# was told to ignore, and `checks --project DIR` from reading a tip whose
887# layer it was told to ignore.
888POLICY_SCHEMA=""
889POLICY_INSTANCE=""
890POLICY_INSTANCE_LABEL=""
891POLICY_PROJECT=""
892POLICY_PROJECT_LABEL=""
893policy_defaults() {
894 POLICY_SCHEMA="$1/schema/verification.cue"
895 POLICY_INSTANCE=""
896 POLICY_INSTANCE_LABEL=""
897 POLICY_PROJECT=""
898 POLICY_PROJECT_LABEL=""
899}
900
901# The floor, copied out of a fetch of the owning valley's repository, and
902# the project's own layer, copied out of the target's tip. Globals, so the
903# traps clean them up whatever happens.
904INSTANCE_TMP=""
905cleanup_instance_tmp() {
906 [ -n "$INSTANCE_TMP" ] || return 0
907 rm -rf "$INSTANCE_TMP"
908 INSTANCE_TMP=""
909}
910
911PROJECT_TMP=""
912cleanup_project_tmp() {
913 [ -n "$PROJECT_TMP" ] || return 0
914 rm -rf "$PROJECT_TMP"
915 PROJECT_TMP=""
916}
917
918# The directory each layer lives in, the file naming this project's owning
919# valley, and the ref of that valley whose tip carries the floor. The floor
920# resolves at the integrated tip, because a floor a project could pin is
921# not a floor (dcr-f41f718).
922INSTANCE_DIR=policy/instance
923PROJECT_DIR=policy/project
924VALLEY_POINTER=policy/valley
925VALLEY_POINTER_REF=refs/heads/main
926
927# The *.cue documents of one directory at one tree-ish, copied out of a
928# repository into a directory on disk. Reading a tip with ls-tree and
929# cat-file rather than checking it out is what lets the layers come from
930# the target while the checkout stays on whatever branch the reviewer is
931# on. 0 copied something, 1 the directory holds no *.cue, 2 the read
932# failed.
933#
934# -z because a path may hold anything but NUL, and *.cue because the layer
935# is the directory's documents — the same reading the composer takes.
936copy_layer() {
937 local gitdir="$1" treeish="$2" dir="$3" dest="$4" path name copied=0
938 while IFS= read -r -d '' path; do
939 case "$path" in *.cue) ;; *) continue ;; esac
940 name="${path##*/}"
941 git -C "$gitdir" cat-file blob "$treeish:$path" > "$dest/$name" || return 2
942 copied=1
943 done < <(git -C "$gitdir" ls-tree --name-only -z "$treeish" "$dir/")
944 [ "$copied" -eq 1 ]
945}
946
947# The ref whose tip supplies the policy, printed the way a person names it,
948# with the commit it stood at. Staleness in a remote-tracking ref is a real
949# thing to see, so the report says which commit the layers came out of
950# rather than only which ref.
951target_label() {
952 local ref="$1" short
953 short="$(git rev-parse --short "$ref")" || short='?'
954 ref="${ref#refs/remotes/}"
955 ref="${ref#refs/heads/}"
956 printf '%s %s' "$ref" "$short"
957}
958
959# Resolve the project's own layer, out of the target's tip, into
960# POLICY_PROJECT, and set POLICY_PROJECT_LABEL to where it came from.
961#
962# A target carrying no layer of its own is derived under the floor alone.
963# The project layer only ever adds (dcr-f41f718), so the identity of "adds"
964# is "adds nothing"; refusing instead would make a repository underivable
965# until its first policy commit, and that commit could not derive either.
966# This is the integrator's own reading (integrator/policy.go), and the two
967# have to agree about an absent layer as much as about a present one.
968#
969# Absence is answered with a document that adds nothing rather than with an
970# argument left off, because the composer is handed a directory of *.cue
971# and has no spelling for "no layer".
972#
973# It reports and returns rather than dying, for the reason derive_owed
974# does: a refusal inside the review loop is not the end of the session.
975resolve_project_layer() {
976 local root="$1" target="$2" rc
977
978 cleanup_project_tmp
979 PROJECT_TMP="$(mktemp -d)" || {
980 refuse "no scratch directory to read the project layer into; nothing derived"
981 return 1
982 }
983 copy_layer "$root" "$target" "$PROJECT_DIR" "$PROJECT_TMP" && rc=0 || rc=$?
984 case "$rc" in
985 0)
986 POLICY_PROJECT="$PROJECT_TMP"
987 POLICY_PROJECT_LABEL="$PROJECT_DIR@$(target_label "$target")"
988 ;;
989 1)
990 printf 'package verification\n' > "$PROJECT_TMP/adds-nothing.cue" || {
991 cleanup_project_tmp
992 refuse "could not compose an empty project layer; nothing derived"
993 return 1
994 }
995 POLICY_PROJECT="$PROJECT_TMP"
996 POLICY_PROJECT_LABEL="no $PROJECT_DIR@$(target_label "$target") — the floor alone"
997 ;;
998 *)
999 cleanup_project_tmp
1000 refuse "could not read $PROJECT_DIR/ at $(target_label "$target"); nothing derived"
1001 return 1
1002 ;;
1003 esac
1004}
1005
1006# The first line of the pointer that is neither blank nor a comment. Read
1007# in the shell so that naming an owning valley needs nothing beyond what
1008# the rest of this script needs.
1009pointer_url() {
1010 local line url=""
1011 while IFS= read -r line || [ -n "$line" ]; do
1012 line="${line%%#*}"
1013 line="${line#"${line%%[![:space:]]*}"}"
1014 line="${line%"${line##*[![:space:]]}"}"
1015 [ -n "$line" ] || continue
1016 url="$line"
1017 break
1018 done < "$1"
1019 printf '%s' "$url"
1020}
1021
1022# Resolve the floor to a directory on disk, into POLICY_INSTANCE, and set
1023# POLICY_INSTANCE_LABEL to where it came from — a temporary directory is
1024# not an answer a reader can check.
1025#
1026# Every project has exactly one owning valley, and the floor is that
1027# valley's (dcr-9b5da04). It is read from the valley's own repository and
1028# never from the project's tree, which is the tree under judgment. Two
1029# shapes, and the first is a special case of the second:
1030#
1031# - a valley's config repository carries policy/instance itself, and is
1032# governed by that floor like every other project. It uses its own,
1033# and fetches nothing.
1034# - every other project names its owning valley at policy/valley. That
1035# repository is fetched into scratch and its policy/instance is read
1036# at the integrated tip. Fetching is all this needs, and anyone the
1037# valley governs necessarily holds fetch on it.
1038#
1039# Both the pointer and a valley's own floor are read from the TARGET's tip
1040# and never from the working tree. The pointer is a file a branch can edit,
1041# so reading it from the branch would let a change name the valley that
1042# gates it; reading it from the checkout would let whoever is reviewing
1043# decide the same thing by accident, which is the failure this fixes. An
1044# absent floor is refused — that is the direction absence defaults in for
1045# this layer, because the floor is the minimum (dcr-f41f718).
1046#
1047# It reports and returns rather than dying, for the reason derive_owed
1048# does: a refusal inside the review loop is not the end of the session.
1049resolve_instance_layer() {
1050 local root="$1" target="$2" url bare dest rc
1051 cleanup_instance_tmp
1052 INSTANCE_TMP="$(mktemp -d)" || {
1053 refuse "no scratch directory to read the floor into; nothing derived"
1054 return 1
1055 }
1056 dest="$INSTANCE_TMP/instance"
1057 mkdir -p "$dest"
1058
1059 copy_layer "$root" "$target" "$INSTANCE_DIR" "$dest" && rc=0 || rc=$?
1060 case "$rc" in
1061 0)
1062 POLICY_INSTANCE="$dest"
1063 POLICY_INSTANCE_LABEL="$INSTANCE_DIR@$(target_label "$target") (this repository is its own valley)"
1064 return 0
1065 ;;
1066 1) ;; # no floor of its own: the pointer names the valley that has one
1067 *)
1068 cleanup_instance_tmp
1069 refuse "could not read $INSTANCE_DIR/ at $(target_label "$target"); nothing derived"
1070 return 1
1071 ;;
1072 esac
1073
1074 git -C "$root" cat-file blob "$target:$VALLEY_POINTER" > "$INSTANCE_TMP/pointer" 2> /dev/null || {
1075 cleanup_instance_tmp
1076 refuse "no owning valley: $VALLEY_POINTER names the repository whose $INSTANCE_DIR is this project's floor, and $(target_label "$target") carries no such file. A valley's own config repository carries $INSTANCE_DIR instead. Nothing derived"
1077 return 1
1078 }
1079 url="$(pointer_url "$INSTANCE_TMP/pointer")"
1080 [ -n "$url" ] || {
1081 cleanup_instance_tmp
1082 refuse "$VALLEY_POINTER at $(target_label "$target") names no repository — it wants one line, the owning valley as git fetch takes it; nothing derived"
1083 return 1
1084 }
1085
1086 bare="$INSTANCE_TMP/valley.git"
1087 git init --quiet --bare "$bare" || {
1088 cleanup_instance_tmp
1089 refuse "no scratch repository to fetch the floor into; nothing derived"
1090 return 1
1091 }
1092 git -C "$bare" fetch --quiet --depth 1 "$url" "$VALLEY_POINTER_REF" || {
1093 cleanup_instance_tmp
1094 refuse "could not fetch the owning valley $url at $VALLEY_POINTER_REF (named by $VALLEY_POINTER at $(target_label "$target")); nothing derived"
1095 return 1
1096 }
1097
1098 copy_layer "$bare" FETCH_HEAD "$INSTANCE_DIR" "$dest" && rc=0 || rc=$?
1099 case "$rc" in
1100 0) ;;
1101 1)
1102 cleanup_instance_tmp
1103 refuse "the owning valley $url holds no *.cue in $INSTANCE_DIR/ at $VALLEY_POINTER_REF; nothing derived"
1104 return 1
1105 ;;
1106 *)
1107 cleanup_instance_tmp
1108 refuse "could not read $INSTANCE_DIR/ from $url; nothing derived"
1109 return 1
1110 ;;
1111 esac
1112
1113 POLICY_INSTANCE="$dest"
1114 POLICY_INSTANCE_LABEL="$url $INSTANCE_DIR@$VALLEY_POINTER_REF"
1115}
1116
1117# Is this check mandatory in this class, or a default the project left
1118# alone? The bit is the form of the composed value, so the test is CUE's
1119# own: a project supplying `false` either conflicts or unifies cleanly.
1120# Answering by unifying rather than by inspecting syntax means the script
1121# cannot disagree with `cue vet`.
1122check_is_mandatory() {
1123 local class="$1" check="$2" field
1124 if [ "$class" = unclassified ]; then
1125 field="policy: unclassified: \"$check\": false"
1126 else
1127 field="policy: classes: \"$class\": requires: \"$check\": false"
1128 fi
1129 printf 'package verification\n%s\n' "$field" > "$POLICY_TMP/probe.cue"
1130 ! cue vet "${POLICY_LAYER[@]}" "$POLICY_TMP/probe.cue" > /dev/null 2>&1
1131}
1132
1133# Every side of the diff: an added, modified or deleted path, and both the
1134# old and the new path of a rename or copy. -z because a path may contain
1135# anything but NUL.
1136diff_paths() {
1137 local base="$1" head="$2" status path
1138 while IFS= read -r -d '' status; do
1139 IFS= read -r -d '' path || die "truncated diff output; nothing derived"
1140 printf '%s\n' "$path"
1141 case "$status" in
1142 R* | C*)
1143 IFS= read -r -d '' path || die "truncated diff output; nothing derived"
1144 printf '%s\n' "$path"
1145 ;;
1146 esac
1147 done < <(git diff --no-relative --name-status -M -z "$base" "$head")
1148}
1149
1150# Lines in, one comma-separated line out.
1151join_lines() {
1152 local out="" line
1153 while IFS= read -r line; do out="${out:+$out, }$line"; done
1154 printf '%s' "$out"
1155}
1156
1157# The target: the ref a change is derived against, and the tip both policy
1158# layers are read out of. origin's answer is preferred, because the target
1159# is the branch as the integrator holds it and not as this checkout last
1160# built it.
1161target_ref() {
1162 git rev-parse --verify --quiet refs/remotes/origin/main > /dev/null \
1163 && { echo refs/remotes/origin/main; return; }
1164 git rev-parse --verify --quiet refs/heads/main > /dev/null \
1165 && { echo refs/heads/main; return; }
1166 return 1
1167}
1168
1169# ----------------------------------------------------------------------
1170# The derivation itself, and the globals it answers with. Everything a
1171# caller could want from the policy comes out of one pass, because every
1172# part of it is a function of the same composition: `checks` prints the
1173# answer, review's [a]sk runs what it names.
1174#
1175# It reports and returns rather than dying, so that a caller inside the
1176# review loop is refused rather than ended. Its callers are all in a
1177# condition, which suspends `set -e` for the whole call, so every step is
1178# checked by hand.
1179DERIVED_PATHS=() # every side of the diff, sorted
1180DERIVED_MATCHED=() # the class names at least one path matched, sorted
1181DERIVED_UNCOVERED=() # the paths no class covered
1182DERIVED_OWES=0 # whether `unclassified` is what owes something
1183declare -A DERIVED_OWED=() # check -> the classes that required it
1184declare -A DERIVED_PINNED=() # check -> mandatory | default
1185declare -A CHECK_RUNNER=() # check -> nix | command
1186declare -A CHECK_ATTRIBUTE=() # check -> the flake check attribute
1187declare -A CHECK_COMMAND=() # check -> the command line
1188
1189derive_owed() {
1190 local schema="$1" instance="$2" project="$3" base="$4" head="$5"
1191
1192 need_cue
1193 [ -f "$schema" ] || {
1194 refuse "no policy schema at $schema; nothing derived"
1195 return 1
1196 }
1197 # An unmatched glob stays literal, so the first entry is a real file
1198 # exactly when the directory holds a document.
1199 local -a instance_docs=("$instance"/*.cue) project_docs=("$project"/*.cue)
1200 [ -f "${instance_docs[0]}" ] || {
1201 refuse "no instance policy layer at $instance; nothing derived"
1202 return 1
1203 }
1204 [ -f "${project_docs[0]}" ] || {
1205 refuse "no project policy layer at $project: a project's own layer is the *.cue documents under $PROJECT_DIR/ (dcr-f41f718). Nothing derived"
1206 return 1
1207 }
1208
1209 DERIVED_PATHS=()
1210 mapfile -t DERIVED_PATHS < <(diff_paths "$base" "$head" | sort -u)
1211
1212 cleanup_policy_tmp
1213 POLICY_LAYER=("$schema" "${instance_docs[@]}" "${project_docs[@]}")
1214 POLICY_TMP="$(mktemp -d)" || {
1215 refuse "no scratch directory to compose the policy in; nothing derived"
1216 return 1
1217 }
1218 render_cue > "$POLICY_TMP/render.cue"
1219 cue vet -c "${POLICY_LAYER[@]}" || {
1220 refuse "the policy layers do not compose; nothing derived"
1221 return 1
1222 }
1223
1224 # Sorted once here, so every list below comes out in a stable order.
1225 local -a rendered=()
1226 mapfile -t rendered < <(cue eval --out text -e _render \
1227 "${POLICY_LAYER[@]}" "$POLICY_TMP/render.cue" | sort)
1228
1229 unset CHECK_RUNNER CHECK_ATTRIBUTE CHECK_COMMAND DERIVED_OWED DERIVED_PINNED
1230 declare -gA CHECK_RUNNER=() CHECK_ATTRIBUTE=() CHECK_COMMAND=() \
1231 DERIVED_OWED=() DERIVED_PINNED=()
1232
1233 # The middle field is a class name for a coverage or requirement line and
1234 # a check name for a catalogue one; `key` is what both are.
1235 local -a pat_class=() pat_ere=() req_class=() req_check=()
1236 local line kind key value
1237 for line in "${rendered[@]}"; do
1238 kind="${line%%$'\t'*}"
1239 key="${line#*$'\t'}"
1240 value="${key#*$'\t'}"
1241 key="${key%%$'\t'*}"
1242 case "$kind" in
1243 path)
1244 pat_class+=("$key")
1245 pat_ere+=("$(glob_ere "$value")")
1246 ;;
1247 requires)
1248 req_class+=("$key")
1249 req_check+=("$value")
1250 ;;
1251 runner) CHECK_RUNNER["$key"]="$value" ;;
1252 attribute) CHECK_ATTRIBUTE["$key"]="$value" ;;
1253 command) CHECK_COMMAND["$key"]="$value" ;;
1254 esac
1255 done
1256
1257 local -A matched=()
1258 local path i hit
1259 DERIVED_UNCOVERED=()
1260 for path in "${DERIVED_PATHS[@]}"; do
1261 hit=0
1262 for ((i = 0; i < ${#pat_ere[@]}; i++)); do
1263 if [[ "$path" =~ ${pat_ere[i]} ]]; then
1264 matched["${pat_class[i]}"]=1
1265 hit=1
1266 fi
1267 done
1268 [ "$hit" -eq 1 ] || DERIVED_UNCOVERED+=("$path")
1269 done
1270 # A path no class covers is answered by the policy's `unclassified` set,
1271 # which is why it is treated as one more matched class rather than as an
1272 # absence.
1273 [ "${#DERIVED_UNCOVERED[@]}" -eq 0 ] || matched[unclassified]=1
1274
1275 local check
1276 DERIVED_OWES=0
1277 for ((i = 0; i < ${#req_check[@]}; i++)); do
1278 key="${req_class[i]}"
1279 check="${req_check[i]}"
1280 [ -n "${matched[$key]:-}" ] || continue
1281 [ "$key" != unclassified ] || DERIVED_OWES=1
1282 DERIVED_OWED["$check"]="${DERIVED_OWED[$check]:+${DERIVED_OWED[$check]}, }$key"
1283 if check_is_mandatory "$key" "$check"; then
1284 DERIVED_PINNED["$check"]=mandatory
1285 else
1286 DERIVED_PINNED["$check"]="${DERIVED_PINNED[$check]:-default}"
1287 fi
1288 done
1289
1290 DERIVED_MATCHED=()
1291 [ "${#matched[@]}" -eq 0 ] \
1292 || mapfile -t DERIVED_MATCHED < <(printf '%s\n' "${!matched[@]}" | sort)
1293}
1294
1295cmd_checks() {
1296 local root schema instance="" label project="" plabel base head target=""
1297 root="$(git rev-parse --show-toplevel 2> /dev/null)" \
1298 || die "not a git repository"
1299 policy_defaults "$root"
1300 schema="$POLICY_SCHEMA"
1301 while [ $# -gt 0 ]; do
1302 case "$1" in
1303 --schema) [ $# -ge 2 ] || die "--schema needs a file"; schema="$2"; shift 2 ;;
1304 --instance) [ $# -ge 2 ] || die "--instance needs a directory"; instance="$2"; shift 2 ;;
1305 --project) [ $# -ge 2 ] || die "--project needs a directory"; project="$2"; shift 2 ;;
1306 --) shift; break ;;
1307 -*) die "unknown option: $1" ;;
1308 *) break ;;
1309 esac
1310 done
1311 [ $# -le 2 ] || die "usage: valley checks [options] [<base> [<head>]]"
1312
1313 head="$(git rev-parse --verify --quiet "${2:-HEAD}^{commit}")" \
1314 || die "no such commit: ${2:-HEAD}"
1315 # The target is what the layers are read out of, so it is needed whenever
1316 # either layer is left to its default — and it is what an unnamed base
1317 # is the merge base with.
1318 if [ -z "$instance" ] || [ -z "$project" ] || [ $# -lt 1 ]; then
1319 target="$(target_ref)" \
1320 || die "no main branch: the target's tip is where the policy layers are read from, and there is none here"
1321 fi
1322 if [ $# -ge 1 ]; then
1323 base="$(git rev-parse --verify --quiet "$1^{commit}")" \
1324 || die "no such commit: $1"
1325 else
1326 base="$(git merge-base "$target" "$head")" \
1327 || die "$head and ${target#refs/} do not share history — name a base"
1328 fi
1329
1330 trap 'cleanup_policy_tmp; cleanup_instance_tmp; cleanup_project_tmp' EXIT
1331 # Each layer is resolved only when nobody named one. --instance and
1332 # --project are a reader pointing this at a layer on purpose, and
1333 # honouring that means not fetching the repository, and not reading the
1334 # tip, that the named layer replaced.
1335 if [ -n "$instance" ]; then
1336 label="${instance#"$root"/}"
1337 else
1338 resolve_instance_layer "$root" "$target" || exit 1
1339 instance="$POLICY_INSTANCE"
1340 label="$POLICY_INSTANCE_LABEL"
1341 fi
1342 if [ -n "$project" ]; then
1343 plabel="${project#"$root"/}"
1344 else
1345 resolve_project_layer "$root" "$target" || exit 1
1346 project="$POLICY_PROJECT"
1347 plabel="$POLICY_PROJECT_LABEL"
1348 fi
1349 derive_owed "$schema" "$instance" "$project" "$base" "$head" || exit 1
1350
1351 local check width=0
1352 for check in "${!DERIVED_OWED[@]}"; do
1353 [ "${#check}" -le "$width" ] || width="${#check}"
1354 done
1355
1356 printf '%s..%s: %d changed path(s)\n' \
1357 "$(git rev-parse --short "$base")" "$(git rev-parse --short "$head")" \
1358 "${#DERIVED_PATHS[@]}"
1359 printf 'policy: %s + %s\n' "$label" "$plabel"
1360 if [ "${#DERIVED_MATCHED[@]}" -eq 0 ]; then
1361 printf 'classes matched: none\n\n'
1362 else
1363 printf 'classes matched: %s\n\n' \
1364 "$(printf '%s\n' "${DERIVED_MATCHED[@]}" | join_lines)"
1365 fi
1366
1367 if [ "${#DERIVED_OWED[@]}" -eq 0 ]; then
1368 echo "required checks: none"
1369 else
1370 echo "required checks:"
1371 while IFS= read -r check; do
1372 printf ' %-*s %-9s %s\n' \
1373 "$width" "$check" "${DERIVED_PINNED[$check]}" "${DERIVED_OWED[$check]}"
1374 done < <(printf '%s\n' "${!DERIVED_OWED[@]}" | sort)
1375 fi
1376
1377 if [ "${#DERIVED_UNCOVERED[@]}" -gt 0 ]; then
1378 printf '\nunclassified: %d path(s) matched no class\n' "${#DERIVED_UNCOVERED[@]}"
1379 printf ' %s\n' "${DERIVED_UNCOVERED[@]}"
1380 # The failure the `unclassified` field exists to prevent: paths outside
1381 # every class that the policy then asks nothing of.
1382 [ "$DERIVED_OWES" -eq 1 ] \
1383 || echo " the policy requires nothing of them — it is behind the tree"
1384 fi
1385}
1386
1387main() {
1388 local verb="${1:-help}"
1389 if [ $# -gt 0 ]; then shift; fi
1390 # The verb set is mirrored in completions/ (valley.bash, _valley) —
1391 # update both when it changes.
1392 case "$verb" in
1393 pending) cmd_pending "$@" ;;
1394 review) cmd_review "$@" ;;
1395 checks) cmd_checks "$@" ;;
1396 tail) cmd_tail "$@" ;;
1397 replay) cmd_replay "$@" ;;
1398 help | -h | --help) usage ;;
1399 *)
1400 printf 'valley: unknown verb: %s\n\n' "$verb" >&2
1401 usage >&2
1402 exit 1
1403 ;;
1404 esac
1405}
1406
1407main "$@"