gunk-dev/the-valley

valley

sourcea5dbe80f1445main's published tip history
21.2 KiB
1#!/usr/bin/env bash
2# valley — the S1 integrator's verbs, as a plain shell script.
3#
4# EVICTION CLAUSE (owner-ratified; the decision node is
5# .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# - it needs dependencies beyond git + coreutils
13# (CROSSED by Phase 1's tail/replay, which need the nats CLI, and again
14# by checks, which needs the cue CLI —
15# graduation is now owed; recording the decision node is part of taking it.);
16# - its behavior gets subtle enough to need real tests
17# (CROSSED by checks: glob matching is pinned by the policy-deriver
18# flake check, not by reading the code.);
19# - it needs nontrivial parsing or concurrency
20# (CROSSED by checks: glob-to-regex translation and -z diff parsing.).
21# The size tripwire (~300 lines) is crossed too. Which way to take the
22# graduation is dcr-2aa1a12, still `proposed`.
23# Graduation is a deliberate act, recorded as a decision node.
24# Precedent: klaus — born in cosmo, graduated deliberately.
25
26set -euo pipefail
27
28die() {
29 printf 'valley: %s\n' "$*" >&2
30 exit 1
31}
32
33usage() {
34 cat <<'EOF'
35valley — S1 integrator verbs for a valley project (direct-push mode)
36
37usage: valley <verb> [args]
38
39 pending list branches on origin not merged into origin/main
40 review <branch> page through the branch's log and diff vs origin/main,
41 then choose:
42 [i]ntegrate ff-only merge onto main, push origin main,
43 delete the merged branch from origin
44 [r]eject delete the remote branch (confirmed first)
45 [s]kip do nothing
46 a stale branch (won't fast-forward from main) is first
47 offered:
48 [b]ase rebase it onto origin/main in a throwaway
49 worktree, push --force-with-lease, then
50 re-review the diff that would actually land
51 checks [<base> [<head>]]
52 print the check names the change between two commits owes
53 under the composed verification policy (dcr-f41f718), and
54 which class made each one required. It prints: no check is
55 run, nothing is gated, nothing is written.
56 base defaults to the merge base with main, head to HEAD.
57 the policy layers are not discovered — they are named:
58 --schema FILE default schema/verification.cue
59 --instance DIR default examples/policy/instance
60 --project DIR default examples/policy/project
61 all three relative to the repository root.
62 tail [subject] watch bus events scroll by (default subject: valley.>);
63 the server comes from the nats CLI's own config
64 (NATS_URL or a nats context; default localhost)
65 replay [dir] publish one ref-updated event per current ref of the
66 repo at dir (default: .) — rebuilds the stream's
67 projection, e.g. after nats stream purge valley
68 help show this help
69
70Runs from any checkout of the project; needs only git and coreutils,
71except tail and replay, which also need the nats CLI (natscli), and
72checks, which also needs the cue CLI.
73No config, no state, no batch mode — the judgment stays with the human.
74EOF
75}
76
77fetch_origin() {
78 git fetch --prune --quiet origin
79}
80
81# Resolve the pager as git would for a diff: pager.diff first (per-command
82# pager configs — e.g. home-manager's delta module — set pager.diff and leave
83# core.pager alone), then git var GIT_PAGER (core.pager, GIT_PAGER, PAGER,
84# less). pager.<cmd> may legally be a boolean; treat true/false — and an
85# empty or missing value — as unset and fall back. The value is
86# shell-interpreted, hence sh -c; a non-tty just cats.
87run_pager() {
88 [ -t 1 ] || { cat; return; }
89 local pager
90 pager="$(git config --get pager.diff || true)"
91 case "$pager" in ''|true|false) pager="$(git var GIT_PAGER)" ;; esac
92 sh -c "$pager"
93}
94
95pending_line() {
96 local ref="$1" age author ahead stat
97 age="$(git log -1 --format='%cr' "$ref")"
98 author="$(git log -1 --format='%an' "$ref")"
99 ahead="$(git rev-list --count "origin/main..$ref")"
100 stat="$(git diff --shortstat "origin/main...$ref")"
101 stat="${stat# }"
102 printf '%s | %s | %s | ahead %s | %s\n' \
103 "${ref#origin/}" "$age" "$author" "$ahead" "${stat:-no file changes}"
104}
105
106cmd_pending() {
107 [ $# -eq 0 ] || die "pending takes no arguments"
108 fetch_origin
109 local ref found=0
110 while IFS= read -r ref; do
111 case "$ref" in
112 origin/HEAD | origin/main) continue ;;
113 esac
114 found=1
115 pending_line "$ref"
116 done < <(git for-each-ref --format='%(refname:short)' \
117 --no-merged=origin/main refs/remotes/origin)
118 [ "$found" -eq 1 ] || echo "nothing pending"
119}
120
121integrate() {
122 local branch="$1" local_main origin_main
123 local_main="$(git rev-parse --verify --quiet refs/heads/main)" \
124 || die "no local main branch to fast-forward — nothing merged"
125 origin_main="$(git rev-parse refs/remotes/origin/main)"
126 [ "$local_main" = "$origin_main" ] \
127 || die "local main is not at origin/main — sync it first; nothing merged"
128 git merge-base --is-ancestor refs/heads/main "refs/remotes/origin/$branch" \
129 || die "$branch does not fast-forward from main — resolve by hand; nothing merged"
130 git checkout --quiet main
131 git merge --ff-only --quiet "refs/remotes/origin/$branch"
132 git push --quiet origin main
133 echo "integrated $branch: main is now $(git rev-parse --short main), pushed to origin"
134 # The branch tip is now an ancestor of the main just pushed, so deleting it
135 # loses nothing; without this every integration leaves a fully-merged ghost
136 # ref that later reads as a confusing "empty" branch. Best-effort: a failed
137 # delete must not report the integration as failed.
138 if git push --quiet origin --delete "$branch"; then
139 echo "deleted merged branch $branch from origin"
140 else
141 printf 'valley: warning: could not delete origin/%s — delete it by hand\n' \
142 "$branch" >&2
143 fi
144}
145
146reject() {
147 local branch="$1" answer
148 printf 'really delete origin/%s? [y/N] ' "$branch"
149 read -r answer || answer=""
150 case "$answer" in
151 y | Y | yes)
152 git push --quiet origin --delete "$branch"
153 echo "rejected $branch: deleted from origin"
154 ;;
155 *) echo "kept $branch" ;;
156 esac
157}
158
159show_review() {
160 local branch="$1"
161 {
162 printf 'branch %s, log against origin/main:\n\n' "$branch"
163 git --no-pager log --oneline "origin/main..origin/$branch"
164 printf '\n'
165 git --no-pager diff "origin/main...origin/$branch"
166 } | run_pager || true # quitting the pager early is not an error
167}
168
169# Throwaway worktree for review's [b]ase choice; a global so the traps can
170# always clean it up — success, conflict, or ctrl-C. Never a mid-rebase state.
171REBASE_WT=""
172cleanup_rebase_wt() {
173 [ -n "$REBASE_WT" ] || return 0
174 git -C "$REBASE_WT" rebase --abort >/dev/null 2>&1 || true
175 git worktree remove --force "$REBASE_WT" >/dev/null 2>&1 || true
176 rm -rf "$REBASE_WT"
177 REBASE_WT=""
178}
179
180# Rebase origin/<branch> onto origin/main in an isolated worktree — the
181# user's checkout is never touched — and push with a lease so a concurrently
182# updated branch is never clobbered. Mechanics only; the judgment on the
183# rebased diff stays with the human, back at the review prompt.
184rebase_onto_main() {
185 local branch="$1"
186 REBASE_WT="$(mktemp -d)"
187 trap cleanup_rebase_wt EXIT
188 trap 'exit 130' INT TERM
189 git worktree add --quiet --detach "$REBASE_WT" "refs/remotes/origin/$branch"
190 if ! git -C "$REBASE_WT" rebase --quiet refs/remotes/origin/main; then
191 cleanup_rebase_wt
192 die "$branch conflicts with main — resolve by hand; nothing changed"
193 fi
194 if ! git -C "$REBASE_WT" push --quiet --force-with-lease \
195 origin "HEAD:refs/heads/$branch"; then
196 cleanup_rebase_wt
197 die "lease on origin/$branch failed (it moved since the fetch); nothing pushed"
198 fi
199 cleanup_rebase_wt
200 trap - EXIT INT TERM
201 echo "rebased $branch onto origin/main, pushed with --force-with-lease"
202}
203
204cmd_review() {
205 [ $# -eq 1 ] || die "usage: valley review <branch>"
206 local branch="${1#origin/}" choice
207 fetch_origin
208 git rev-parse --verify --quiet "refs/remotes/origin/$branch" >/dev/null \
209 || die "no such branch on origin: $branch"
210 show_review "$branch"
211 # A stale branch can't integrate, and its pre-rebase diff is not what would
212 # land; offer to rebase it mechanically, then re-review what actually would.
213 while ! git merge-base --is-ancestor refs/remotes/origin/main \
214 "refs/remotes/origin/$branch"; do
215 printf '%s does not fast-forward from main: [b]ase onto main, [r]eject, [s]kip? ' \
216 "$branch"
217 read -r choice || die "stdin closed before an answer; nothing done"
218 case "$choice" in
219 b)
220 rebase_onto_main "$branch"
221 fetch_origin
222 show_review "$branch"
223 ;;
224 r) reject "$branch" && return ;;
225 s)
226 echo "skipped $branch; nothing done"
227 return
228 ;;
229 *) echo "answer b, r, or s" ;;
230 esac
231 done
232 while true; do
233 printf '%s: [i]ntegrate, [r]eject, [s]kip? ' "$branch"
234 read -r choice || die "stdin closed before an answer; nothing done"
235 case "$choice" in
236 i) integrate "$branch" && return ;;
237 r) reject "$branch" && return ;;
238 s)
239 echo "skipped $branch; nothing done"
240 return
241 ;;
242 *) echo "answer i, r, or s" ;;
243 esac
244 done
245}
246
247# tail and replay are thin wrappers over the nats CLI — anything they do,
248# plain nats and git can do. They are the only verbs needing more than git
249# and coreutils.
250need_nats() {
251 command -v nats >/dev/null 2>&1 \
252 || die "this verb needs the nats CLI (natscli); nix run .#valley bundles it"
253}
254
255cmd_tail() {
256 [ $# -le 1 ] || die "usage: valley tail [subject]"
257 need_nats
258 exec nats sub "${1:-valley.>}"
259}
260
261# One ref-updated event per existing ref, from git for-each-ref alone. A
262# ref's prior value is not derivable from the repository, so `old` is the
263# all-zero id — the same payload a push creating the ref would produce.
264# The payload construction mirrors the host module's publisher hook
265# (nix/valley-host.nix); change one only with the other.
266cmd_replay() {
267 [ $# -le 1 ] || die "usage: valley replay [repo-dir]"
268 need_nats
269 local dir="${1:-.}" repo sha ref event count=0
270 git -C "$dir" rev-parse --git-dir >/dev/null 2>&1 \
271 || die "not a git repository: $dir"
272 if [ "$(git -C "$dir" rev-parse --is-bare-repository)" = true ]; then
273 repo="$(basename "$(git -C "$dir" rev-parse --absolute-git-dir)" .git)"
274 else
275 repo="$(basename "$(git -C "$dir" rev-parse --show-toplevel)")"
276 fi
277 while read -r sha ref; do
278 # " is the only JSON-significant character a refname can contain (git
279 # forbids \ and control characters); names and object ids are safe.
280 event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \
281 "$repo" "${ref//\"/\\\"}" "${sha//?/0}" "$sha")"
282 nats pub "valley.git.$repo.ref-updated" "$event" >/dev/null
283 count=$((count + 1))
284 done < <(git -C "$dir" for-each-ref --format='%(objectname) %(refname)')
285 echo "replayed $count refs of $repo onto the bus"
286}
287
288# ----------------------------------------------------------------------
289# checks — the verification-policy deriver (dcr-f41f718). It composes the
290# instance layer with the project layer, matches every side of a diff
291# against the composed classes, and prints the check names the change owes
292# with the class or classes that made each one required. It reports: no
293# check is run, nothing is gated, nothing is written.
294#
295# Composition is CUE's, never this script's. The whole of the mandatory-
296# versus-overridable distinction is unification, so reimplementing it here
297# would be reimplementing the decision. What this script does that CUE
298# cannot is glob matching and reading a diff.
299
300need_cue() {
301 command -v cue >/dev/null 2>&1 \
302 || die "this verb needs the cue CLI; nix run .#valley bundles it"
303}
304
305# One glob segment as an ERE fragment: `*` and `?` are wildcards that never
306# cross a `/`, and every ERE metacharacter is escaped.
307segment_ere() {
308 local seg="$1" out="" i c
309 for ((i = 0; i < ${#seg}; i++)); do
310 c="${seg:i:1}"
311 case "$c" in
312 '*') out+='[^/]*' ;;
313 '?') out+='[^/]' ;;
314 '.' | '^' | '$' | '+' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | \\) out+="\\$c" ;;
315 *) out+="$c" ;;
316 esac
317 done
318 printf '%s' "$out"
319}
320
321# A path glob as an anchored ERE, segment by segment. A `**` segment matches
322# any number of segments including none, so it swallows the separator that
323# would otherwise follow it and `a/**/b` matches `a/b`; every other segment
324# matches exactly one.
325glob_ere() {
326 local ere='^' i last
327 local -a segs=()
328 IFS=/ read -r -a segs <<<"$1"
329 last=$((${#segs[@]} - 1))
330 for ((i = 0; i <= last; i++)); do
331 if [ "${segs[i]}" = '**' ]; then
332 if [ "$i" -eq "$last" ]; then ere+='.*'; else ere+='(.*/)?'; fi
333 else
334 ere+="$(segment_ere "${segs[i]}")"
335 [ "$i" -eq "$last" ] || ere+='/'
336 fi
337 done
338 printf '%s$' "$ere"
339}
340
341# The composed policy as one tab-separated line per covered pattern and per
342# required check, so the shell never parses CUE. The field is hidden because
343# the schema's sentinel rejects unknown top-level fields, and `unclassified`
344# is rendered as a class of that name — it is one more source a check can
345# come from.
346render_cue() {
347 cat <<'EOF'
348package verification
349
350import (
351 "list"
352 "strings"
353)
354
355_render: strings.Join(list.Concat([[
356 for cn, c in policy.classes
357 for p, on in c.paths if on {"path\t\(cn)\t\(p)"}
358], [
359 for cn, c in policy.classes
360 for k, on in c.requires if on {"requires\t\(cn)\t\(k)"}
361], [
362 for k, on in policy.unclassified if on {"requires\tunclassified\t\(k)"}
363]]), "\n")
364EOF
365}
366
367# The composed layer, and a scratch directory for the documents this verb
368# writes into the composition. Globals so the probe below can see them.
369POLICY_LAYER=()
370POLICY_TMP=""
371
372# Is this check mandatory in this class, or a default the project left
373# alone? The bit is the form of the composed value, so the test is CUE's
374# own: a project supplying `false` either conflicts or unifies cleanly.
375# Answering by unifying rather than by inspecting syntax means the script
376# cannot disagree with `cue vet`.
377check_is_mandatory() {
378 local class="$1" check="$2" field
379 if [ "$class" = unclassified ]; then
380 field="policy: unclassified: \"$check\": false"
381 else
382 field="policy: classes: \"$class\": requires: \"$check\": false"
383 fi
384 printf 'package verification\n%s\n' "$field" > "$POLICY_TMP/probe.cue"
385 ! cue vet "${POLICY_LAYER[@]}" "$POLICY_TMP/probe.cue" > /dev/null 2>&1
386}
387
388# Every side of the diff: an added, modified or deleted path, and both the
389# old and the new path of a rename or copy. -z because a path may contain
390# anything but NUL.
391diff_paths() {
392 local base="$1" head="$2" status path
393 while IFS= read -r -d '' status; do
394 IFS= read -r -d '' path || die "truncated diff output; nothing derived"
395 printf '%s\n' "$path"
396 case "$status" in
397 R* | C*)
398 IFS= read -r -d '' path || die "truncated diff output; nothing derived"
399 printf '%s\n' "$path"
400 ;;
401 esac
402 done < <(git diff --no-relative --name-status -M -z "$base" "$head")
403}
404
405# Lines in, one comma-separated line out.
406join_lines() {
407 local out="" line
408 while IFS= read -r line; do out="${out:+$out, }$line"; done
409 printf '%s' "$out"
410}
411
412# The ref a branch is derived against, preferring what origin last said.
413main_ref() {
414 git rev-parse --verify --quiet refs/remotes/origin/main > /dev/null \
415 && { echo refs/remotes/origin/main; return; }
416 git rev-parse --verify --quiet refs/heads/main > /dev/null \
417 && { echo refs/heads/main; return; }
418 return 1
419}
420
421cmd_checks() {
422 local root schema instance project base head
423 root="$(git rev-parse --show-toplevel 2> /dev/null)" \
424 || die "not a git repository"
425 schema="$root/schema/verification.cue"
426 instance="$root/examples/policy/instance"
427 project="$root/examples/policy/project"
428 while [ $# -gt 0 ]; do
429 case "$1" in
430 --schema) [ $# -ge 2 ] || die "--schema needs a file"; schema="$2"; shift 2 ;;
431 --instance) [ $# -ge 2 ] || die "--instance needs a directory"; instance="$2"; shift 2 ;;
432 --project) [ $# -ge 2 ] || die "--project needs a directory"; project="$2"; shift 2 ;;
433 --) shift; break ;;
434 -*) die "unknown option: $1" ;;
435 *) break ;;
436 esac
437 done
438 [ $# -le 2 ] || die "usage: valley checks [options] [<base> [<head>]]"
439
440 need_cue
441 [ -f "$schema" ] || die "no policy schema at $schema"
442 # An unmatched glob stays literal, so the first entry is a real file
443 # exactly when the directory holds a document.
444 local -a instance_docs=("$instance"/*.cue) project_docs=("$project"/*.cue)
445 [ -f "${instance_docs[0]}" ] || die "no instance policy layer at $instance"
446 [ -f "${project_docs[0]}" ] || die "no project policy layer at $project"
447
448 head="$(git rev-parse --verify --quiet "${2:-HEAD}^{commit}")" \
449 || die "no such commit: ${2:-HEAD}"
450 if [ $# -ge 1 ]; then
451 base="$(git rev-parse --verify --quiet "$1^{commit}")" \
452 || die "no such commit: $1"
453 else
454 local against
455 against="$(main_ref)" || die "no main branch to derive a base from — name one"
456 base="$(git merge-base "$against" "$head")" \
457 || die "$head and ${against#refs/} do not share history — name a base"
458 fi
459
460 local -a paths=()
461 mapfile -t paths < <(diff_paths "$base" "$head" | sort -u)
462
463 POLICY_LAYER=("$schema" "${instance_docs[@]}" "${project_docs[@]}")
464 POLICY_TMP="$(mktemp -d)"
465 # shellcheck disable=SC2064 # expand POLICY_TMP now, not at trap time
466 trap "rm -rf '$POLICY_TMP'" EXIT
467 render_cue > "$POLICY_TMP/render.cue"
468 cue vet -c "${POLICY_LAYER[@]}" \
469 || die "the policy layers do not compose; nothing derived"
470
471 # Sorted once here, so every list below comes out in a stable order.
472 local -a rendered=()
473 mapfile -t rendered < <(cue eval --out text -e _render \
474 "${POLICY_LAYER[@]}" "$POLICY_TMP/render.cue" | sort)
475
476 local -a pat_class=() pat_ere=() req_class=() req_check=()
477 local line kind class value
478 for line in "${rendered[@]}"; do
479 kind="${line%%$'\t'*}"
480 class="${line#*$'\t'}"
481 value="${class#*$'\t'}"
482 class="${class%%$'\t'*}"
483 case "$kind" in
484 path)
485 pat_class+=("$class")
486 pat_ere+=("$(glob_ere "$value")")
487 ;;
488 requires)
489 req_class+=("$class")
490 req_check+=("$value")
491 ;;
492 esac
493 done
494
495 local -A matched=()
496 local -a uncovered=()
497 local path i hit
498 for path in "${paths[@]}"; do
499 hit=0
500 for ((i = 0; i < ${#pat_ere[@]}; i++)); do
501 if [[ "$path" =~ ${pat_ere[i]} ]]; then
502 matched["${pat_class[i]}"]=1
503 hit=1
504 fi
505 done
506 [ "$hit" -eq 1 ] || uncovered+=("$path")
507 done
508 # A path no class covers is answered by the policy's `unclassified` set,
509 # which is why it is treated as one more matched class rather than as an
510 # absence.
511 [ "${#uncovered[@]}" -eq 0 ] || matched[unclassified]=1
512
513 local -A owed=() pinned=()
514 local check width=0 uncovered_owes=0
515 for ((i = 0; i < ${#req_check[@]}; i++)); do
516 class="${req_class[i]}"
517 check="${req_check[i]}"
518 [ -n "${matched[$class]:-}" ] || continue
519 [ "$class" != unclassified ] || uncovered_owes=1
520 owed["$check"]="${owed[$check]:+${owed[$check]}, }$class"
521 if check_is_mandatory "$class" "$check"; then
522 pinned["$check"]=mandatory
523 else
524 pinned["$check"]="${pinned[$check]:-default}"
525 fi
526 [ "${#check}" -le "$width" ] || width="${#check}"
527 done
528
529 printf '%s..%s: %d changed path(s)\n' \
530 "$(git rev-parse --short "$base")" "$(git rev-parse --short "$head")" \
531 "${#paths[@]}"
532 printf 'policy: %s + %s\n' "${instance#"$root"/}" "${project#"$root"/}"
533 if [ "${#matched[@]}" -eq 0 ]; then
534 printf 'classes matched: none\n\n'
535 else
536 printf 'classes matched: %s\n\n' \
537 "$(printf '%s\n' "${!matched[@]}" | sort | join_lines)"
538 fi
539
540 if [ "${#owed[@]}" -eq 0 ]; then
541 echo "required checks: none"
542 else
543 echo "required checks:"
544 while IFS= read -r check; do
545 printf ' %-*s %-9s %s\n' \
546 "$width" "$check" "${pinned[$check]}" "${owed[$check]}"
547 done < <(printf '%s\n' "${!owed[@]}" | sort)
548 fi
549
550 if [ "${#uncovered[@]}" -gt 0 ]; then
551 printf '\nunclassified: %d path(s) matched no class\n' "${#uncovered[@]}"
552 printf ' %s\n' "${uncovered[@]}"
553 # The failure the `unclassified` field exists to prevent: paths outside
554 # every class that the policy then asks nothing of.
555 [ "$uncovered_owes" -eq 1 ] \
556 || echo " the policy requires nothing of them — it is behind the tree"
557 fi
558}
559
560main() {
561 local verb="${1:-help}"
562 if [ $# -gt 0 ]; then shift; fi
563 # The verb set is mirrored in completions/ (valley.bash, _valley) —
564 # update both when it changes.
565 case "$verb" in
566 pending) cmd_pending "$@" ;;
567 review) cmd_review "$@" ;;
568 checks) cmd_checks "$@" ;;
569 tail) cmd_tail "$@" ;;
570 replay) cmd_replay "$@" ;;
571 help | -h | --help) usage ;;
572 *)
573 printf 'valley: unknown verb: %s\n\n' "$verb" >&2
574 usage >&2
575 exit 1
576 ;;
577 esac
578}
579
580main "$@"