gunk-dev/the-valley

valley

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