gunk-dev/the-valley

valley

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