gunk-dev/the-valley

valley

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