gunk-dev/the-valley

valley

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