gunk-dev/the-valley

valley

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