gunk-dev/the-valley

valley

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