gunk-dev/the-valley

valley

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