gunk-dev/the-valley

valley

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