gunk-dev/the-valley

valley

sourceb6ac2a46b5cdmain's published tip history
171.2 KiB
1#!/usr/bin/env bash
2# valley — the S1 integrator's verbs, as a plain shell script.
3#
4# EVICTION CLAUSE (owner-ratified; the decision node is
5# archive/.the-valley/decisions/dcr-74c3158-valley-cli-lifecycle.md).
6# This tool is deliberately a shell script: it runs from any checkout with
7# nothing but git and coreutils — no machinery, the portability stance of
8# ida-b9f646c. It GRADUATES to its own repo and a real language the moment
9# ANY tripwire is crossed:
10# - it grows past ~300 lines;
11# - it needs persistent state, config, or a daemon
12# (CROSSED by review's notes, which outlive the session in
13# $XDG_STATE_HOME/valley/notes.);
14# - it needs dependencies beyond git + coreutils
15# (CROSSED by Phase 1's tail/replay, which need the nats CLI, and again
16# by checks, which needs the cue CLI, again by review's [a]pprove, which
17# needs the attest helper, and again by status, ready, unready and
18# withdraw, which are a Go program (status/) this script runs —
19# graduation is now due; 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
44# The version the package stamped on this script when nix built it
45# (nix/packages.nix): the CLI's version and the commit it was built from.
46# A script run straight from a checkout has none. It is taken here and
47# unset, so no program this script runs inherits a stamp that is not its
48# own; self-update is handed it explicitly.
49VALLEY_STAMP="${VALLEY_VERSION:-}"
50unset VALLEY_VERSION
51
52die() {
53 printf 'valley: %s\n' "$*" >&2
54 exit 1
55}
56
57usage() {
58 cat <<'EOF'
59usage: valley <verb> [args]
60
61valley — S1 integrator verbs for a valley project: author, review, approve, and
62track changes and the plan graph.
63
64Authoring and updating changes:
65 ready mark a branch head ready as a new version of its change
66 unready pause a ready change by marking it a draft
67 withdraw mark a ready or draft change withdrawn
68 rebase rebase a change and its stack onto origin/main
69 checks print the checks the composed policy requires of a diff
70
71Reviewing, approving, and inspecting changes:
72 pending list ready changes, unrecorded branches, and drafts
73 review page through a change or stack to approve, rebase, or reject
74 approve run required checks and file an integration request
75 status read a change's integration request and last outcome
76 changes print every recorded change as valley-changes/v1 JSON
77
78Planning work:
79 plan show the project's plan graph as a milestone tree
80 knot read and write knots in the plan graph at refs/the-valley/knots
81
82Bus and client maintenance:
83 tail watch NATS bus events scroll by
84 replay publish ref-updated events for the current refs of a repo
85 self-update build, test, and install the tip of a branch of the-valley
86
87A change is named by its 32-letter change id, its handle (shortest unique
88prefix, at least 4 letters, or <repo>:<handle>), or its branch name.
89Runs from any checkout; nix run .#valley bundles git, valley-go, attest, cue,
90less, and natscli (self-update also needs nix). Judgment stays with the human:
91nothing here writes main.
92
93`valley --version` prints the package's version and commit (e.g. 0.1.0-97db597,
94with -dirty for uncommitted changes, -unknown when nix knew no commit, or
95unstamped when run straight from a checkout).
96Run `valley help <verb>` (or `valley <verb> --help`) for a verb's flags and
97rules. See docs/reference.md for the full CLI, ref, and schema reference.
98EOF
99}
100
101help_naming() {
102 cat <<'EOF'
103
104A change is named by its full change id, by its handle — the shortest
105prefix of the id, four letters at least, that no other change recorded on
106origin shares, written <repo>:<handle> too, with this repository's name —
107or by its branch. A name written origin/<branch> is always
108a branch. A handle that is also a branch on origin is refused unless the
109change is on that branch. review, approve and rebase read a branch name,
110written either way, against every record on origin: when exactly one
111record's active version is on the branch, the name is that change, as if
112its id were given, and when more than one's is, the verb refuses and lists
113their ids. A change whose active version has landed — its head is on
114main's first-parent history with no merge above it, or the integrator's
115outcome record and verified transfer statement record that exact head
116landing — is skipped, so a branch can be used again once its change has
117landed. unready, withdraw and status read a branch the same way. A
118branch no record's active version is on is acted on as a branch. A
119change with a record is reviewed, approved and rebased at the
120head its active version records, never at its branch's tip: review shows
121that head and its [a]pprove approves it, and rebase and review's
122[r]eject refuse, naming both, when the branch's tip on origin is another
123commit. approve approves the head bound to it, wherever the branch is.
124[r]eject deletes the branch under a lease on the recorded head. approve,
125rebase, and review's [a]pprove and [b]ase refuse a change whose record is
126not ready, naming its state, and review offers none of them for a change
127that is not ready when it shows it. Each reads the record again just before it
128acts, and again before approve files or rebase pushes, and refuses when
129the change is not ready. rebase also refuses when the change's
130record has changed at all since it began, and approve when the head it
131approves is not a version's. A name that read as a plain branch is
132read again before approve files or rebase pushes. If it names a change by
133then, rebase refuses, and approve files only while the change is ready at
134the head it began with. An approval already past that last check can
135still file if the change is unreadied or withdrawn in the moment before
136its push; the integrator refuses to land it, since it lands no request
137that would bring a version of a change that is not ready, whatever the
138request is named.
139The integrator reads the records last just before it moves main, so a
140change paused in that moment can still land at the head the operator
141approved, and never at any other.
142EOF
143}
144
145help_runtime() {
146 cat <<'EOF'
147
148Runs from any checkout of the project; needs only git and coreutils,
149except tail and replay, which also need the nats CLI (natscli), checks,
150which also needs the cue CLI, review's notes, which need less, approve
151and review's [a]pprove, which need both the cue CLI and the attest
152helper, and status, ready, unready, withdraw, review, approve and rebase,
153which need the valley-go helper, as pending, changes, knot, plan and
154self-update do. nix run .#valley bundles all of them. self-update also
155needs nix. Deriving a policy fetches the owning valley's repository, so
156checks and approving also need whatever reaching it takes.
157No config but valley.principal, which ready, rebase, knot and plan read,
158and valley.selfUpdate.repo and .branch, which self-update reads; no batch
159mode; and no state but the notes file, the handle cache pending and
160changes write for completion, and self-update's record of what it
161installed — the judgment stays with the human.
162EOF
163}
164
165help_unready_withdraw_requests() {
166 cat <<'EOF'
167 the integrator lands no request that would bring a
168 version of a change that is not ready, so unready and
169 withdraw both stop a
170 pending integration request, under c-<change id> or a
171 branch's request name. each says so when origin holds
172 one. a draft's request stands and lands once the change
173 is ready again. withdrawing voids the request: the
174 integrator deletes it on its next pass while the change
175 is still withdrawn. withdraw warns, since a ready before
176 then leaves the request standing: only a holder of the
177 approve grant (also accepted as request) may touch a
178 request ref, so the operator must drop it then.
179EOF
180}
181
182help_pending() {
183 cat <<'EOF'
184usage: valley pending [--all] [--repo <name>] [--checks] [--json] [-v] [--known-signers <file>] [--integrator-name <name>]
185
186 pending [--all] [--repo <name>] [--checks] [--json] [-v]
187 [--known-signers <file>] [--integrator-name <name>]
188 list what is waiting to land, in three sections: ready,
189 the ready changes whose active version has not landed;
190 branches, each branch on origin that main does not
191 reach and that is no change's active head; and drafts,
192 the changes whose record says they are drafts. each
193 entry is a block. its first line is its name, with its
194 head's age and author: handle and version for a change,
195 the branch for a branch, and handle and version on its
196 branch for a draft. under it come its title (the
197 record's for a change, followed by the first linked
198 knot's id; the subject of its first own commit for a
199 branch), then the commits and the diff it
200 adds to its base: the nearest other entry its head
201 strictly contains, or main. a stack is its top entry,
202 then every entry the top contains, listed under it at
203 one indentation, each before the entries it contains
204 (ancestry alone: approving the top lands everything
205 listed under it, and the top says how many). each
206 listed entry is on the one listed after it, or says
207 `on <base>`, as at a fork. a listed entry is marked
208 when it is from another section. a
209 change also says `includes <handle>` for a change its
210 head contains that is no entry, such as a withdrawn
211 one, and `uncertain` when the version may have landed
212 without its evidence being stored. the stack with the
213 latest commit comes first. lines fit the terminal, or
214 80 columns off one; titles are cut short with …, names
215 never. names are bold on a terminal unless NO_COLOR is
216 set.
217 --all every project the serving host
218 publishes, each headed by its name (see
219 valley help changes)
220 --repo NAME that one project
221 --checks add a line to each change with the
222 checks the policy requires of it, by
223 cost, as checks derives them
224 --json print valley-pending/v1: the
225 valley-changes/v1 shape, with the
226 pending changes in changes and the
227 drafts in drafts
228 -v warn on stderr when a plan graph is
229 missing or unreadable
230 --known-signers FILE, --integrator-name NAME
231 what a transfer statement is verified
232 with (see changes below)
233 needs the valley-go helper.
234EOF
235 help_runtime
236}
237
238help_changes() {
239 cat <<'EOF'
240usage: valley changes --json [--all] [--repo <name>] [-v] [--known-signers <file>] [--integrator-name <name>]
241
242 changes --json [--all] [--repo <name>] [-v]
243 [--known-signers <file>] [--integrator-name <name>]
244 print every change origin holds a record of, in every
245 state, as one JSON object, valley-changes/v1, for front
246 ends to read (docs/architecture.md): each version's
247 head, title and branch, how far it has landed
248 (landed, landed-recorded, uncertain or not-landed),
249 its pending request and its last outcome, the knots in
250 refs/the-valley/knots that link it
251 (valley:<project>/<change id>, active first), and
252 the branches no change is on. -v warns on stderr when a
253 plan graph is missing or unreadable.
254 handles are unique across
255 everything listed: a change id recorded in more than
256 one repository listed has the handle <repo>:<prefix>
257 in each. without --all it covers this
258 repository. --all covers every project the serving
259 host lists at refs/the-valley/projects in its instance
260 repository, which policy/valley names at main's tip on
261 origin; each project's URL is the instance's with its
262 last path segment replaced, and is read through a clone
263 kept under $XDG_CACHE_HOME/valley/repos. a url that
264 opens with a dash, names a <transport>:: helper such
265 as ext::, or has a scheme other than ssh, git, https or
266 file is refused. a repository that cannot be read is
267 listed with its error. --repo limits it to one
268 project. landed means on main's first-parent history
269 with no merge above it. landed-recorded needs a landed
270 commit with one parent and the integrator's transfer
271 statement for the version's request name, verified;
272 the integrator's outcome record for that name saying
273 land at the version's head; and the integrator's merge
274 of the head onto the landed commit's parent giving the
275 landed tree. attest verifies the statement with the
276 registry's known-signers file and the integrator's
277 signing name. each is taken from the first of these
278 that gives it: --known-signers FILE or
279 --integrator-name NAME; VALLEY_KNOWN_SIGNERS or
280 VALLEY_INTEGRATOR_SIGNER; what the serving host
281 publishes at refs/the-valley/signers in its instance
282 repository, read only when a statement needs
283 verifying. a file that does not read, or holds no key
284 under the name, is reported on stderr, and then no
285 statement is verified.
286 needs the valley-go helper.
287EOF
288 help_runtime
289}
290
291help_review() {
292 cat <<'EOF'
293usage: valley review [-v] <change>
294
295 review [-v] <change>
296 page through the change's branch: its log and diff vs
297 origin/main, or a stack layer by layer (below). above
298 each change's diff, review shows every knot in the plan
299 graph that links the change, as `does oc-6335749 (open):
300 <title>` (valley-go does). a missing or unreadable graph
301 shows no knots; -v warns on stderr. then choose:
302 [a]pprove file an integration request for the
303 head shown. runs the
304 checks the composed policy requires of
305 this change over a throwaway worktree of
306 that head, signs each result as an
307 attestation, and publishes the evidence
308 and the request ref to origin in ONE
309 atomic push. this files the request;
310 it does not wait for integration or
311 update your local checkout. use status
312 to read the result. the policy comes
313 from the target's tip and the owning
314 valley's, as checks describes (valley
315 help checks), so your checkout
316 can be on any branch. a change the policy
317 requires no check of is filed too, as a
318 request with no evidence, and says so.
319 approving a change already requested is
320 how it is filed again. at a head rebased
321 onto a moved main it replaces the request
322 ref under a lease and names the head it
323 replaced; at the same head it leaves the
324 ref alone and publishes only the new
325 evidence, which the create-only
326 attestation namespace refuses when this
327 signer has already attested that tree
328 (bd-7b7d58f). every write of the request
329 ref is leased, filing included, so an
330 approval that lost a race is refused
331 rather than clobbering the one that won.
332 needs the attest helper and
333 VALLEY_ATTEST_KEY, the ed25519 key this
334 host signs with, whenever a check is
335 required; VALLEY_ATTEST_NAME is the name it
336 signs under, defaulting to this host's.
337 [v]iew full diff
338 page the change's whole diff, with
339 notes taken as below, and ask again
340 [r]eject delete the remote branch (confirmed first)
341 [s]kip do nothing
342 a change with a record is first set against its
343 approved version: the greatest version below the one
344 shown whose exact head an integration request or a
345 land, stale or reject outcome on origin names, under
346 c-<change id> or a branch name of the change that
347 nothing else maps to (valley-go compare). with none,
348 or an ambiguous one, review pages the whole diff. when
349 each version's diff from its merge base with main
350 changes the same files the same way (valley-delta-v1),
351 review prints `<change> v<n> at <head>: clean restack
352 of approved v<m> at <old head>.`, the two bases, and
353 the commits main landed between them, and pages
354 nothing. otherwise it pages `changed since approved
355 v<m>`, the files whose change differs, git
356 range-diff of the two versions, and the shown
357 version's diff of those files. a changed commit
358 message or author is shown either way. this is
359 information only: it files nothing and skips no check.
360 when [a]pprove's checks fail, the prompt says approving
361 needs a new head and stops offering [a]pprove until the
362 change has one. any other refusal keeps the prompt as
363 it was.
364 [a]pprove files the head shown, for a branch no record
365 is on too: it refuses, naming both heads, when the
366 branch on origin has moved off that head since.
367 [a]pprove is the only way a change reaches main from
368 here, and approve (valley help approve) is the same act
369 without the pager.
370 Nothing in this script writes the protected ref: the
371 integrator does, having judged the request.
372 a stale branch (won't fast-forward from main) is first
373 offered:
374 [b]ase rebase it onto origin/main, as rebase
375 does (valley help rebase), then re-review
376 the diff that would actually land
377 [a]pprove is offered there too: a stale branch is nothing
378 the integrator cannot apply, so it need not be rebased
379 first.
380 a change whose record is not ready says so above its
381 diff, and again in place of the prompt, which then
382 offers only [v]iew full diff and [s]kip:
383 `<change> v<n> is a draft: its owner (<owner>) hasn't
384 marked it ready, so it can't be approved yet.`
385 `<change> is withdrawn: there is nothing to approve.`
386 a draft is often a change an agent is still working on.
387 [a]pprove would be refused, and so would [b]ase, since
388 adding the rebased head as a version would ready the
389 change behind its owner's back. [r]eject records
390 nothing on the change: it would only delete a branch
391 its owner may still be working on. a change unreadied
392 or withdrawn while the review is open is still refused
393 by [a]pprove and [b]ase, which read the record again.
394 a branch no record is on has no state, and is offered
395 the usual prompt.
396 while paging, press v: less opens the diff in $EDITOR.
397 every line you insert there is a note. it is anchored to
398 the file and new-side line it sits on — to the file alone
399 when it sits above the first hunk. range-diff gives no
400 line numbers, so on a changed version a note keeps its
401 file and line only in the shown version's diff at the
402 end of the page. each note is then appended to
403 $XDG_STATE_HOME/valley/notes/<branch>.md (default
404 ~/.local/state) and printed after the verdict. notes
405 survive [b]ase. lines you change or delete instead of
406 inserting are ignored, with a warning.
407 a change whose active version names no branch is
408 refused, since notes and [r]eject act on a branch;
409 approve files its head without one.
410 a stack is reviewed one layer at a time, bottom first.
411 its layers are what pending lists under the change: the
412 changes not landed and the branches no record is on
413 that its head contains (valley-go stack). review first
414 lists them, warns of a lower layer that is a draft or
415 withdrawn, since the integrator lands nothing above it,
416 and says how the review goes: [n] through the layers,
417 and approving the top lands them all. a stack whose
418 bottom does not fast-forward from main is then asked,
419 before any layer is paged, as in `one, at the bottom,
420 does not fast-forward from main:`:
421 [b]ase all <n>
422 rebase the whole stack onto origin/main,
423 as rebase does (valley help rebase), then
424 list it again and page the rebased layers,
425 so the heads paged are the heads approved
426 [s]top end the review; nothing done
427 a rebase that is refused or left unfinished says what
428 happened, and then only [s]top is offered.
429 it then shows each layer, headed `change <k> of <n>:
430 <name> on <below>`, as a change alone is shown: set
431 against its own change's approved version, or its log
432 and diff against the layer below it paged, with notes
433 kept under that layer's branch.
434 after each lower layer it asks, naming the layer and
435 its place, as in `two, 2 of 3:`:
436 [n]ext layer go on to the layer above; the usual
437 answer
438 [a]pprove approve that layer at the head shown,
439 as review of it would. this lands it
440 and every layer under it, which the
441 prompt names (`one alone`, `one and
442 two`, `the <k> up to <name>`), and
443 ends the review
444 [v]iew full diff
445 page that layer's log and diff against
446 the layer below it, and ask again
447 [s]top end the review; nothing done
448 after the top it asks, as in `three, 3 of 3:`:
449 [a]pprove all <n>
450 approve the top at the head shown,
451 which lands every layer
452 [v]iew full diff
453 page the top's log and diff against
454 the layer below it, and ask again
455 [r]eject <name>
456 delete the top's branch (confirmed
457 first)
458 [s]top end the review; nothing done
459 only the top is offered [r]eject. when a layer's checks
460 fail, its prompt says approving needs a new head and
461 stops offering [a]pprove, as for any change. a layer
462 that is not ready says so as a change alone does, under
463 its heading and in its prompt. neither it nor any layer
464 above it is offered [a]pprove, since approving one would
465 land it: each prompt above it says `it would bring
466 <name>, change <k> of <n>, which is a draft` (or
467 withdrawn) in its place. a top that is not ready is not
468 offered [r]eject either. every layer's notes are printed
469 at the end.
470EOF
471 help_naming
472 help_runtime
473}
474
475help_approve() {
476 cat <<'EOF'
477usage: valley approve [--head <sha>] <change>
478
479 approve [--head <sha>] <change>
480 do what review's [a]pprove does for the change, without
481 paging it: the same checks, the same refusals, the same
482 leased request write and the same output. exits non-zero
483 when it refuses. a change with a record is approved at
484 exactly one head, and its request is filed as
485 refs/the-valley/integration-requests/main/c-<change id>,
486 at that head:
487 --head SHA approve exactly this head, which must be
488 one of the record's version heads,
489 active or not. a front end passes the
490 head it showed, so a record that moves
491 after review cannot change what lands.
492 without --head, approve shows the active version's head
493 and title and asks to confirm them, on a terminal; off
494 one it refuses. a branch no record is on is approved at
495 its tip on origin, which --head must name if it is
496 given (review's [a]pprove files the head it showed, and
497 refuses once the branch on origin has moved off it), under
498 the branch's request name: the branch with
499 each / replaced by -. a branch whose request name would
500 be c-<change id> is refused, since that name is the
501 change's.
502 approve first reads the evidence origin holds for that
503 head's tree, refs/the-valley/attestations/<tree>/*, and
504 reuses it for each required nix check it verifies: a
505 note that attest verify accepts under the known-signers
506 file (VALLEY_KNOWN_SIGNERS, or the one the host
507 publishes), that is pure evidence for that check's name
508 and flake attribute, and that says it passed. it prints
509 each check it reuses and who signed it. for a note it
510 found and does not reuse, it says why on stderr. a
511 command check is never reused. a listing or a fetch of
512 origin's evidence that fails is refused, and nothing is
513 run.
514 approve runs every other required check over a
515 throwaway worktree of that head, signs each result as an
516 attestation, and publishes the new evidence and the
517 request ref to origin in ONE atomic push. when every
518 required check is reused, nothing runs, no signing key
519 is needed, and the push carries the request alone.
520 this files the request; it does not wait for
521 integration or update your local checkout. use status to
522 read the result. the policy comes from the target's tip
523 and the owning valley's, as checks describes (valley help
524 checks), so your checkout can be on any branch. a change
525 the policy requires no check of is filed too, as a
526 request with no evidence, and says so. approving a
527 change already requested is how it is filed again: at a
528 head rebased onto a moved main it replaces the request
529 ref under a lease and names the head it replaced; at the
530 same head it leaves the ref alone and publishes only the
531 new evidence. origin already holding this signer's
532 evidence for that tree, without a check that still has
533 to run, is refused before anything runs: the
534 attestation namespace is create-only, so the new
535 evidence would have nowhere to go (bd-7b7d58f). every
536 write of the request ref
537 is leased, filing included, so an approval that lost a
538 race is refused rather than clobbering the one that won.
539 needs the attest helper whenever a check is required,
540 and VALLEY_ATTEST_KEY, the ed25519 key this host signs
541 with, whenever a check has to run here;
542 VALLEY_ATTEST_NAME is the name it signs under,
543 defaulting to this host's. Nothing in this script writes
544 the protected ref: the integrator does, having judged
545 the request.
546 approve refuses, before any check runs, a head that does
547 not fast-forward from main and would bring a version of
548 another change that has not landed: a layer above the
549 bottom of a stale stack. the refusal names the command
550 that rebases the stack, valley rebase <change>. this is
551 the project's choice, not a rule the integrator needs:
552 approved as it is, the stack would land as one commit
553 recorded against this request alone, so the changes
554 under it would have no landing record of their own, and
555 the checks would run over a head that has to be rebased
556 anyway. a stale head with no change under it, such as
557 the bottom layer of a stack or a change alone, is
558 approved as it is, and the integrator merges it onto
559 main.
560 approve prints how long each required check took, and
561 appends one JSON line per check to the timing log,
562 $XDG_STATE_HOME/valley/timings.jsonl (default
563 ~/.local/state/valley/timings.jsonl). the log stays on
564 this machine and is not evidence; a log that cannot be
565 written is a warning, and approving goes on.
566EOF
567 help_naming
568 help_runtime
569}
570
571help_rebase() {
572 cat <<'EOF'
573usage: valley rebase [--known-signers <file>] [--integrator-name <name>] <change>
574
575 rebase [--known-signers <file>] [--integrator-name <name>] <change>
576 rebase the change's whole stack onto origin/main, as
577 review's [b]ase does: the layers valley-go stack lists
578 under the change, and the change itself. in a throwaway
579 worktree, bottom first, each layer's own commits go onto
580 the rebased layer below it, and the bottom's onto
581 origin/main, so each layer keeps its own diff. commits
582 under the bottom that a lower change landed through the
583 integrator drop out, since main holds them; that landing
584 is read as changes reads it, with the signers its two
585 flags, VALLEY_KNOWN_SIGNERS and VALLEY_INTEGRATOR_SIGNER,
586 or the host's publication give. one atomic
587 push then moves every layer's branch, each leased on the
588 tip read: every branch moves, or none does. last, bottom
589 first, each change gains its rebased head as a new
590 version, as valley.principal names, the way ready
591 --if-active does: only while the change is still ready
592 at the head the rebase began with.
593 it refuses, with nothing changed, a stack holding a
594 change that is not ready, records no branch, or whose
595 branch is missing on origin or is not at its recorded
596 head; a plain branch that is the branch of a change not
597 in the stack; two layers on one branch; a merge among the
598 commits to be rebased, or a version head of a change
599 that is not ready or not in the stack, since a rebase
600 gives each commit a new id; and a stack holding a change
601 while git config valley.principal names no one. a
602 conflict in any layer pushes nothing, records nothing
603 and names the layer.
604 a change alone prints its new head. a
605 stack prints a manifest: one line for each layer, with
606 its old and new head, whether its branch was pushed, and
607 whether a version was added. then, for each change left
608 unfinished, the valley ready command that finishes it,
609 and the exit status is non-zero. rebasing again refuses
610 a change whose branch holds a head no version records,
611 and prints the same command. last, it names each ready
612 change or branch outside the stack that is left on an
613 old head of a layer, such as a second stack on a lower
614 layer, with the rebase that moves it; it does not move
615 it. rebase does not re-review the result. a stack that
616 already fast-forwards from main is left as it is.
617EOF
618 help_naming
619 help_runtime
620}
621
622help_status() {
623 cat <<'EOF'
624usage: valley status [--json] [-v] [--known-signers <file>] [--integrator-name <name>] <change>
625
626 status [--json] [-v] [--known-signers <file>] [--integrator-name <name>]
627 <change>
628 read the request and the integrator's last decision from
629 origin. distinguish waiting, a decision that needs
630 attention, and a change integrated into origin/main.
631 a change with a record is read at its active version's
632 head, under c-<change id>, and the status says the
633 version, its title, the owner, and how far the version
634 has landed, as changes reads it. a refusal for a record
635 that is not ready, or for a merge in the change's
636 commits, is a state of its own.
637 after integration, show how to update the local checkout.
638 fetches objects without moving local branches or files;
639 no checks run and no request is filed.
640 --json print the status as one JSON object,
641 valley-status/v1, for front ends to read
642 (docs/architecture.md), with the knots
643 in the plan graph that link the change.
644 an error prints no object: it goes to
645 stderr and the exit status is non-zero.
646 -v with --json, warn on stderr when the plan
647 graph is missing or unreadable
648 --known-signers FILE, --integrator-name NAME
649 what a transfer statement is verified
650 with, as changes reads them
651 needs the valley-go helper.
652EOF
653 help_naming
654 help_runtime
655}
656
657help_ready() {
658 cat <<'EOF'
659usage: valley ready [--head <sha>] [--change <id>] [--if-active <sha>] [--stamp] [<branch>]
660
661 ready [--head <sha>] [--change <id>] [--if-active <sha>] [--stamp] [<branch>]
662 mark a head of the branch ready, as a new version of its
663 change, in the change's record on origin:
664 refs/the-valley/changes/main/<change id>. the branch
665 defaults to the current one. the head is --head, or else
666 origin/<branch>, and it must be on origin already. the
667 first ready of a change makes v1; each later one adds
668 the next version, at a head other than the active
669 version's. a draft or a withdrawn change comes back this
670 way: at the active version's head, it is ready again at
671 that version, and at another head it gains the next
672 version. prints the handle and version, e.g.
673 `cosmo nxvp v2 ready`.
674 the change id is --change, else the head commit's jj
675 change-id header, else a Change-Id: trailer in its
676 message, else a new one, which is printed. a header and
677 a trailer that disagree are refused. so is a change
678 whose commits from its merge base with origin/main hold
679 a merge, or that has more than one merge base.
680 --if-active SHA
681 add the version only while the change
682 is ready at an active version whose head
683 is SHA. the record ref is leased on the
684 record read, so nothing comes between
685 that check and the write. rebase readies
686 the head it rebased this way.
687 --stamp amend the head of your local branch to
688 carry the id as a Change-Id: trailer and
689 push the branch, leased, before marking it
690 ready. it only starts a new change: it
691 is refused for a change that has a
692 record on origin already, and for a head
693 already on origin.
694 the record names the principal your key pushes as, read
695 from git config valley.principal; the host refuses one
696 naming anyone else. the record ref is pushed leased on
697 the value read. a new change is owned by the principal
698 that readies it, and a later version may come from its
699 owner, the operator, or a restack holder while the
700 change is ready.
701 a record never makes anything land, and approve is
702 still the only way to main. the integrator reads
703 records only to refuse: it lands no request that would
704 bring a version of a change that is not ready.
705 needs the valley-go helper.
706EOF
707 help_naming
708 help_runtime
709}
710
711help_unready() {
712 cat <<'EOF'
713usage: valley unready <change>
714
715 unready <change>
716 make a ready change a draft in its record on origin, as
717 its owner or the operator. a draft is a pause: it voids
718 nothing, and approvals of its active version stand when
719 it is readied again. ready brings it back. prints e.g.
720 `cosmo nxvp v2 draft`. needs the valley-go helper.
721EOF
722 help_unready_withdraw_requests
723 help_naming
724 help_runtime
725}
726
727help_withdraw() {
728 cat <<'EOF'
729usage: valley withdraw <change>
730
731 withdraw <change>
732 mark a ready change or a draft withdrawn in its record
733 on origin, as its owner or the operator. withdrawing
734 voids everything outstanding on the change: its
735 integration requests, and the approvals and reviews of
736 every version, so a change brought back needs fresh
737 approvals. ready brings it back, at the same version
738 or a new one. prints e.g. `cosmo nxvp v2 withdrawn`.
739 needs the valley-go helper.
740EOF
741 help_unready_withdraw_requests
742 help_naming
743 help_runtime
744}
745
746help_knot() {
747 cat <<'EOF'
748usage: valley knot <verb> [args]
749
750 knot <verb> [args]
751 read and write the project's plan graph: knots, at
752 refs/the-valley/knots on origin. a knot is an outcome,
753 a bug, an idea or a question; `knot schema` prints the
754 types, their statuses, active and terminal, the fields
755 and the edges. a write is one commit on the ref, made
756 without a checkout and pushed with a lease on the tip
757 it was made on; no review is involved. a write that
758 loses the lease is made again on the new tip, up to 5
759 tries. every verb takes --project NAME, another
760 project on the same host, and --json. exit status 3
761 is a conflict. needs the valley-go helper, and
762 git config valley.principal for every write.
763 new <type> <title> [--parent ID] [--blocked-by ID]...
764 [--owner P] [--target PROJECT] [--body -]
765 make a knot. its id is the type's prefix
766 and 7 hex digits of the sha-256 of the
767 title's slug.
768 show <id> [--json]
769 its fields, body and comments, and the
770 edges both ways
771 list [--type T] [--status S] [--owner P] [--ready]
772 every knot. --status takes a status,
773 active or terminal. --ready lists the
774 active, unclaimed knots whose blockers
775 are all terminal.
776 set <id> <field>=<value>... [--if <field>=<value>]...
777 [--force]
778 change status, title, source, owner,
779 target or graduated_into. a field that
780 another write changed meanwhile is a
781 conflict unless --force. --if requires
782 a field to hold a value first.
783 link <id> (--blocked-by ID | --parent ID | --change X)...
784 unlink <id> (--blocked-by ID | --parent ID | --change X)...
785 add or drop an edge. a change is
786 valley:<project>/<change id> or a github
787 pull request url. outcomes and bugs link
788 the changes that do the work, and a
789 question links the change that records
790 its answer in the source.
791 edit <id> --body -
792 replace the body with stdin
793 comment <id> (-m TEXT | --body -)
794 add a comment. comments are never
795 changed or deleted.
796 claim <id> --run RUN
797 claim an active outcome or bug for a
798 run; an open outcome becomes
799 in-progress. a knot claimed already is
800 a conflict.
801 unclaim <id>
802 release the claim. a claim that
803 changes before the release lands is
804 a conflict.
805 schema [--json]
806 print the model
807EOF
808 help_runtime
809}
810
811help_plan() {
812 cat <<'EOF'
813usage: valley plan [--project NAME | --all] [--owner P] [--json] [--known-signers <file>] [--integrator-name <name>]
814
815 plan [--project NAME | --all] [--owner P] [--json]
816 [--known-signers <file>] [--integrator-name <name>]
817 show the project's plan graph as a tree, to see where
818 things stand. the roots are the outcomes with no
819 parent, the milestones, each with its progress: its
820 descendants that are terminal and not abandoned, out
821 of those not abandoned, as a count and a bar. under
822 each come its children, indented, in the order they
823 were created, then by title. each knot has a glyph for
824 its state (○ ready, ◐ in progress, ⊘ blocked, ◇
825 active, ✓ done, ✗ abandoned), its id and title, and,
826 while active, its claim and the claim's age (marked
827 stale past a day), its owner, and what blocks it. a
828 blocker that ended abandoned, discarded, superseded or
829 dropped clears the knot, and is marked with how it
830 ended. a reference to another project's knot,
831 <project>:<id>, is marked dangling when that
832 project's graph cannot be read or holds no such knot.
833 a root whose descendants are all terminal is one
834 line. three sections follow. waiting on you: the
835 active outcomes and bugs and the open questions the
836 operator owns, then the changes ready for
837 approval, as pending lists them. in flight: the
838 claimed knots, oldest claim first. open residuals:
839 the open bugs, under their parent. the operator is
840 git config valley.principal, or --owner. lines fit
841 the terminal as pending's do; glyphs are coloured on
842 a terminal unless NO_COLOR is set.
843 --project NAME another project on the same host
844 --all every project the serving host
845 publishes, each under its name, as
846 pending --all reads them. a project
847 that cannot be read is reported in
848 its own section
849 --owner P read P as the operator
850 --json print valley-plan/v1: every knot with
851 what the graph derives of it, and the
852 three sections (docs/architecture.md)
853 --known-signers FILE, --integrator-name NAME
854 what a transfer statement is verified
855 with, for the changes ready for
856 approval, as changes reads them
857 needs the valley-go helper.
858EOF
859 help_runtime
860}
861
862help_checks() {
863 cat <<'EOF'
864usage: valley checks [--schema FILE] [--instance DIR] [--project DIR] [--names [--cost COST]] [<base> [<head>]]
865
866 checks [<base> [<head>]]
867 print the check names the composed verification policy
868 (dcr-f41f718) requires of the change between two
869 commits, which class made each one required, and the
870 change's carry mode: how far an approval of it carries
871 across a rebase, the strictest of exact, same-class and
872 same-paths among the classes it matched. It prints: no
873 check is run, nothing is gated, nothing is written.
874 base defaults to the merge base with main, head to HEAD.
875 by default both layers come from the target's tip
876 (origin/main), never from your checkout: the project's
877 own layer is policy/project there, and the owning valley
878 is named one line at policy/valley there, fetched and
879 read at policy/instance in that repository's integrated
880 tip. a valley's own config repository carries
881 policy/instance and uses it. a target carrying no
882 policy/project is derived under the floor alone; a floor
883 that is not there is refused. this is what the
884 integrator reads, so the answer is the same from any
885 branch, however stale. an option overrides each layer,
886 which is the only way to derive against a layer that
887 does not govern — the worked example under
888 examples/policy/, say:
889 --schema FILE default $VALLEY_VERIFICATION_SCHEMA
890 --instance DIR default the owning valley's floor
891 --project DIR default policy/project at the target
892 naming a layer stops this reading the source it
893 replaced. the schema is the shape a policy is written
894 in rather than a layer, so it ships with this tool: the
895 package sets VALLEY_VERIFICATION_SCHEMA to its own copy.
896 with that unset, as when this script runs straight from
897 a the-valley checkout, it is schema/verification.cue in
898 the checkout.
899 a class's globs match bytes, in the C locale whatever
900 yours is: `?` is one byte, so `?.md` does not match
901 é.md, whose é is two.
902 after the report, two lines group the required checks
903 by the cost the policy declares, `quick` or `slow`. a
904 slow check takes minutes or needs special hardware. the
905 cost changes nothing required: approving runs every
906 required check whatever its cost, and the integrator
907 requires evidence for every one.
908 --names print only the required check names,
909 one per line
910 --cost COST with --names, only the quick or
911 the slow ones, e.g.
912 `valley checks --names --cost slow`
913EOF
914 help_runtime
915}
916
917help_tail() {
918 cat <<'EOF'
919usage: valley tail [subject]
920
921 tail [subject] watch bus events scroll by (default subject: valley.>);
922 the server comes from the nats CLI's own config
923 (NATS_URL or a nats context; default localhost)
924EOF
925 help_runtime
926}
927
928help_replay() {
929 cat <<'EOF'
930usage: valley replay [dir]
931
932 replay [dir] publish one ref-updated event per current ref of the
933 repo at dir (default: .) — rebuilds the stream's
934 projection, e.g. after nats stream purge valley
935EOF
936 help_runtime
937}
938
939help_self_update() {
940 if command -v valley-go > /dev/null 2>&1; then
941 valley-go self-update --help
942 printf '\n'
943 else
944 cat <<'EOF'
945usage: valley self-update [-v] [--retry | --rollback | --pin | --unpin]
946 [--repo <url>] [--branch <name>]
947
948EOF
949 fi
950 cat <<'EOF'
951 self-update [-v] [--retry | --rollback | --pin | --unpin]
952 [--repo <url>] [--branch <name>]
953 install the tip of a branch of the-valley into your
954 default nix profile, in place of its valley element,
955 once that exact commit builds and passes a smoke test.
956 a commit that fails is skipped until the branch moves,
957 or until --retry. it is off until --repo or
958 git config valley.selfUpdate.repo names the
959 repository; the branch is valley.selfUpdate.branch,
960 or main. --rollback reinstalls the previous build, and
961 --pin and --unpin freeze and release the install.
962 `valley-go self-update --help` gives every step. needs
963 the valley-go helper and nix.
964
965 --version print this valley's version: the package's version and
966 the commit it was built from, e.g. 0.1.0-97db597, with
967 -dirty after it for a tree with uncommitted changes and
968 -unknown in its place when nix knew no commit. run
969 straight from a checkout, it says it is unstamped.
970EOF
971 help_runtime
972}
973
974fetch_origin() {
975 git fetch --prune --quiet origin
976}
977
978# Resolve the pager as git would for a diff: pager.diff first (per-command
979# pager configs — e.g. home-manager's delta module — set pager.diff and leave
980# core.pager alone), then git var GIT_PAGER (core.pager, GIT_PAGER, PAGER,
981# less). pager.<cmd> may legally be a boolean; treat true/false — and an
982# empty or missing value — as unset and fall back. The value is
983# shell-interpreted, hence sh -c.
984diff_pager() {
985 local pager
986 pager="$(git config --get pager.diff || true)"
987 case "$pager" in '' | true | false) pager="$(git var GIT_PAGER)" ;; esac
988 printf '%s' "$pager"
989}
990
991# Page a file rather than a pipe, so less's v key has something to hand
992# $EDITOR: with a real file open, v runs LESSEDIT, whose default
993# `%E ?lm+%lm. %g` is the editor, +<line>, and the file name. That file is
994# the review buffer, and editing it is how notes get written (see
995# collect_notes). A pipe has no name, so less refuses to edit one — which is
996# why review no longer pipes.
997#
998# The configured diff pager stays the renderer, but as less's input
999# preprocessor rather than as the pager. It still reads the buffer on stdin
1000# exactly as it did when it was the pager, less displays what it emits, and
1001# less still calls the raw buffer "the current file" — so v edits the diff
1002# and not the rendering. The alternative was to page the buffer with no
1003# filter at all: exact, and it throws delta's rendering away, which is the
1004# worse trade for a verb whose whole job is reading a diff.
1005#
1006# What this costs is the line number. A filter that restructures the diff —
1007# delta's default rendering does — makes %lm a line of the rendered view, so
1008# the editor opens near the cursor rather than on it. A structure-preserving
1009# filter (pager.diff = `delta --color-only`) makes it exact. No anchor
1010# depends on it: a note is anchored by where it was inserted, not by where
1011# the editor opened.
1012page_file() {
1013 local file="$1" pager
1014 [ -t 1 ] || { cat -- "$file"; return; } # a non-tty just cats
1015 pager="$(diff_pager)"
1016 case "${pager%%[[:space:]]*}" in
1017 less | */less)
1018 # Already less: give it the file and there is no filter to run.
1019 sh -c "$pager \"\$1\"" sh "$file"
1020 return
1021 ;;
1022 esac
1023 # Without less there is no editor key; fall back to filtering into a pipe.
1024 command -v less > /dev/null 2>&1 || {
1025 sh -c "$pager" < "$file"
1026 return
1027 }
1028 # -R because the filter's color is the whole point of running it, and no
1029 # LESSCLOSE because a stray one would run against a buffer we still read.
1030 LESSOPEN="|$pager < %s" env -u LESSCLOSE less -R -- "$file"
1031}
1032
1033# pending is valley-go's (status/pending.go). The fetch first keeps this
1034# checkout's remote-tracking branches current, as pending always has. The
1035# helper runs valley checks for --checks, so it is told how this script was
1036# run.
1037cmd_pending() {
1038 command -v valley-go > /dev/null 2>&1 \
1039 || die "pending needs the valley-go helper; nix run .#valley bundles it"
1040 fetch_origin
1041 VALLEY_COMMAND="$0" exec valley-go pending "$@"
1042}
1043
1044# For a change with a record, what is rejected is the head its record
1045# names. So the branch is deleted only while its tip is that head, and the
1046# delete is leased on it. When the tip is another commit, reject refuses
1047# and names both, and deletes nothing. A branch no record names is deleted
1048# as before.
1049#
1050# reject runs inside a condition, where bash suspends `set -e`, so the push
1051# is checked by hand.
1052reject() {
1053 local branch="$1" answer
1054 local -a lease=()
1055 if [ -n "$CHANGE_HEAD" ]; then
1056 check_recorded_tip "$branch" "nothing deleted" || return 1
1057 lease=("--force-with-lease=refs/heads/$branch:$CHANGE_HEAD")
1058 fi
1059 printf 'really delete origin/%s? [y/N] ' "$branch"
1060 read -r answer || answer=""
1061 case "$answer" in
1062 y | Y | yes)
1063 if ! git push --quiet "${lease[@]}" origin --delete "$branch"; then
1064 refuse "origin did not delete $branch, which may have moved since the fetch; nothing deleted"
1065 return 1
1066 fi
1067 echo "rejected $branch: deleted from origin"
1068 ;;
1069 *) echo "kept $branch" ;;
1070 esac
1071}
1072
1073# ----------------------------------------------------------------------
1074# review notes — the lines the reviewer inserts into the paged diff.
1075#
1076# The buffer the reviewer pages is a file, so the pager's editor key can open
1077# it (page_file). Whatever comes back with lines inserted is read as notes:
1078# no marker, no syntax, no mode — an inserted line is a note because it was
1079# not there before. What a note is *about* is where it sits, so each one is
1080# anchored to the file and the new-side line number of the diff line above
1081# it, which is the pair a reviewer would otherwise have to copy out by hand.
1082
1083# The scratch directory holding the buffer and its pristine copy, and the
1084# notes taken so far in this review — a global because [b]ase pages a second
1085# time and the notes from the first pass are not thereby withdrawn.
1086REVIEW_TMP=""
1087NOTES=()
1088
1089cleanup_review_tmp() {
1090 [ -n "$REVIEW_TMP" ] || return 0
1091 rm -rf "$REVIEW_TMP"
1092 REVIEW_TMP=""
1093}
1094
1095# Where a branch's notes live. XDG_STATE_HOME is the right home for them:
1096# they are neither config nor cache, and losing them loses judgment.
1097notes_file() {
1098 printf '%s/valley/notes/%s.md\n' "${XDG_STATE_HOME:-$HOME/.local/state}" "$1"
1099}
1100
1101# The anchor of every line of the buffer, by line: the file that line belongs
1102# to, and the new-side line number it sits on. Built in one pass so that
1103# anchoring a note is a lookup. An empty path means the line is above every
1104# file (the log); line 0 means the line is a file header, above every hunk.
1105ANCHOR_PATH=()
1106ANCHOR_LINE=()
1107
1108anchor_buffer() {
1109 local file="$1" line path="" at=0 next=0 inhunk=0 rest
1110 ANCHOR_PATH=()
1111 ANCHOR_LINE=()
1112 while IFS= read -r line; do
1113 # Header lines are only headers outside a hunk: inside one, every line
1114 # carries a +/-/space prefix, so a diff of a diff cannot be misread.
1115 if [ "$inhunk" -eq 1 ]; then
1116 case "$line" in
1117 ' '* | '+'* | '')
1118 at="$next" # this line's own new-side number
1119 next=$((next + 1))
1120 ;;
1121 '-'* | \\*) ;; # a removal or the no-newline marker: no new-side line
1122 *) inhunk=0 ;;
1123 esac
1124 fi
1125 if [ "$inhunk" -eq 0 ]; then
1126 case "$line" in
1127 'diff --git '*)
1128 path=""
1129 # The b/ side, so a rename anchors to the name it will have.
1130 if [[ "$line" =~ ^diff\ --git\ a/(.*)\ b/(.*)$ ]]; then
1131 path="${BASH_REMATCH[2]}"
1132 fi
1133 at=0
1134 ;;
1135 '@@ '*)
1136 rest="${line#*+}" # -12,7 +34,9 @@ -> 34,9 @@
1137 at="${rest%%[!0-9]*}"
1138 [ -n "$at" ] || at=0
1139 next="$at"
1140 inhunk=1
1141 ;;
1142 esac
1143 fi
1144 ANCHOR_PATH+=("$path")
1145 ANCHOR_LINE+=("$at")
1146 done < "$file"
1147}
1148
1149# The anchor for a note inserted after buffer line n, as it is written down.
1150anchor_of() {
1151 local n="$1" path line
1152 [ "$n" -ge 1 ] || { printf '(unanchored)'; return; }
1153 path="${ANCHOR_PATH[n - 1]:-}"
1154 line="${ANCHOR_LINE[n - 1]:-0}"
1155 if [ -z "$path" ]; then
1156 printf '(unanchored)'
1157 elif [ "$line" -eq 0 ]; then
1158 printf '%s' "$path"
1159 else
1160 printf '%s:%s' "$path" "$line"
1161 fi
1162}
1163
1164# The notes in an edited buffer, one `anchor: text` line each. git says where
1165# the reviewer's lines landed; a hunk that removes nothing is an insertion,
1166# and the line it was inserted after is the anchor. A hunk that removes
1167# something is an edit of the diff itself — it anchors to nothing, since the
1168# line it would name is the line it changed — so it is dropped with a count.
1169notes_in() {
1170 local orig="$1" edited="$2" line rest at old insert=0 touched=0 text
1171 anchor_buffer "$orig"
1172 while IFS= read -r line; do
1173 case "$line" in
1174 '@@ '*)
1175 rest="${line#@@ -}" # 12,0 +13,2 @@ -> 12,0 +13,2 @@
1176 at="${rest%%[!0-9]*}"
1177 rest="${rest#"$at"}"
1178 old=1
1179 case "$rest" in
1180 ,*)
1181 rest="${rest#,}"
1182 old="${rest%%[!0-9]*}"
1183 ;;
1184 esac
1185 if [ "$old" -eq 0 ]; then
1186 insert=1
1187 else
1188 insert=0
1189 touched=$((touched + old))
1190 fi
1191 ;;
1192 '+'*)
1193 # Only inside an insertion hunk: the +++ of git's own header is not
1194 # a note, and neither is the new side of an edit.
1195 [ "$insert" -eq 1 ] || continue
1196 text="${line#+}"
1197 text="${text#"${text%%[![:space:]]*}"}"
1198 [ -n "$text" ] || continue # a blank line says nothing
1199 printf '%s: %s\n' "$(anchor_of "$at")" "$text"
1200 ;;
1201 esac
1202 done < <(git --no-pager diff --no-ext-diff --no-index -U0 -- "$orig" "$edited")
1203 [ "$touched" -eq 0 ] || printf \
1204 'valley: warning: %d changed or deleted diff line(s) ignored — a note is a line you insert\n' \
1205 "$touched" >&2
1206}
1207
1208# Read the notes out of the paged buffer and keep them: appended to the
1209# branch's notes file under the commit they were taken against, and held for
1210# the print that follows the verdict. A notes file that cannot be written is
1211# a warning, never a failure — the notes are still printed, and a review is
1212# not undone by a missing directory.
1213collect_notes() {
1214 local branch="$1" sha="$2" file dir
1215 local -a found=()
1216 mapfile -t found < <(notes_in "$REVIEW_TMP/review.orig" "$REVIEW_TMP/review.diff")
1217 [ "${#found[@]}" -gt 0 ] || return 0
1218 NOTES+=("${found[@]}")
1219 file="$(notes_file "$branch")"
1220 dir="${file%/*}"
1221 mkdir -p "$dir" 2> /dev/null && {
1222 printf '## %s at %s\n\n' "$branch" "$sha"
1223 printf '%s\n' "${found[@]}"
1224 printf '\n'
1225 } >> "$file" 2> /dev/null && return 0
1226 printf 'valley: warning: could not write %s — the notes are printed only\n' \
1227 "$file" >&2
1228}
1229
1230print_notes() {
1231 local branch="$1"
1232 [ "${#NOTES[@]}" -gt 0 ] || return 0
1233 printf '\n%d note(s) on %s, appended to %s:\n' \
1234 "${#NOTES[@]}" "$branch" "$(notes_file "$branch")"
1235 printf ' %s\n' "${NOTES[@]}"
1236}
1237
1238# ----------------------------------------------------------------------
1239# review sets the version it shows of a change against the change's
1240# approved version: the greatest version below it whose head a request or
1241# an outcome on origin names (valley-go compare, status/compare.go). The
1242# logic is valley-go's, and this script prints what it says:
1243#
1244# - none: there is no approved version to compare with, so review pages
1245# the whole diff, as for any change. Any note valley-go gives, such as
1246# an approved version it could not compare, heads the page.
1247# - clean: the file delta is the approved version's. review prints that
1248# in a few lines, with the landings between the two bases, and pages
1249# nothing.
1250# - changed: review pages the files whose change differs, the
1251# range-diff between the two versions, and the shown version's diff
1252# of those files. range-diff's hunks carry no line numbers, so a note
1253# taken beside them is unanchored. That last diff is in git's ordinary
1254# form, so a note taken there keeps its file and line (anchor_buffer).
1255#
1256# A changed commit message or author is in valley-go's text either way.
1257# [v]iew full diff pages the whole diff at every prompt. The comparison
1258# files no request and skips no check: [a]pprove is the same act whatever
1259# it says.
1260#
1261# compare_shown <change ID> <version> <head>: compare the version shown,
1262# against main's tip as the fetch left it. Leaves none, clean or changed
1263# in COMPARE_KIND, and the text to show in $REVIEW_TMP/compare. A plain
1264# branch is none, and so is a comparison valley-go could not make, with a
1265# warning.
1266COMPARE_KIND=none
1267compare_shown() {
1268 local out="$REVIEW_TMP/compare.out" tip
1269 COMPARE_KIND=none
1270 : > "$REVIEW_TMP/compare"
1271 [ -n "$1" ] || return 0
1272 if ! tip="$(git rev-parse --verify --quiet refs/remotes/origin/main)" \
1273 || ! valley-go compare --tip "$tip" "$1" "$2" "$3" > "$out"; then
1274 printf 'valley: warning: could not compare v%s of change %s with its approved version; reviewing it in full\n' \
1275 "$2" "$1" >&2
1276 return 0
1277 fi
1278 IFS= read -r COMPARE_KIND < "$out" || COMPARE_KIND=""
1279 case "$COMPARE_KIND" in
1280 none | clean | changed) tail -n +2 "$out" > "$REVIEW_TMP/compare" ;;
1281 *)
1282 printf 'valley: warning: valley-go compare answered %s, which this script does not read; reviewing it in full\n' \
1283 "$COMPARE_KIND" >&2
1284 COMPARE_KIND=none
1285 ;;
1286 esac
1287}
1288
1289# show_compared <notes key> <head> <heading> <knots> <writer> [<arg>…]:
1290# show what compare_shown found, under the heading when there is one. A
1291# clean restack is printed, and nothing is paged. A changed version pages
1292# the comparison. Otherwise the writer writes the whole diff, and it is
1293# paged. Notes taken in a page are kept under the notes key, against the
1294# head.
1295#
1296# Knots follow the heading when there is one. Otherwise they follow the
1297# first line of the comparison or full diff, which names the change.
1298show_compared() {
1299 local key="$1" sha heading="$3" knots="$4"
1300 sha="$(git rev-parse --short "$2")"
1301 shift 4
1302 {
1303 if [ -n "$heading" ]; then
1304 printf '%s\n' "$heading"
1305 [ -z "$knots" ] || printf '%s\n' "$knots"
1306 cat "$REVIEW_TMP/compare"
1307 [ "$COMPARE_KIND" != none ] || "$@"
1308 else
1309 {
1310 cat "$REVIEW_TMP/compare"
1311 [ "$COMPARE_KIND" != none ] || "$@"
1312 } | under_first "$knots"
1313 fi
1314 } > "$REVIEW_TMP/review.diff"
1315 if [ "$COMPARE_KIND" = clean ]; then
1316 cat "$REVIEW_TMP/review.diff"
1317 cleanup_review_tmp
1318 else
1319 page_buffer "$key" "$sha"
1320 fi
1321}
1322
1323# under_first <lines>: copy stdin, inserting <lines> after the first line.
1324under_first() {
1325 local first
1326 IFS= read -r first || [ -n "$first" ] || return 0
1327 printf '%s\n' "$first"
1328 [ -z "$1" ] || printf '%s\n' "$1"
1329 cat
1330}
1331
1332# DOES caches the output of `valley-go does` for the review (status/does.go):
1333# one `<change ID>\tdoes <knot ID> (<status>): <title>` line per knot.
1334DOES=""
1335
1336# read_does [-v]: read the plan graph once for every change in the review.
1337# A missing or unreadable graph leaves DOES empty; -v warns on stderr.
1338read_does() {
1339 local ids=() k
1340 DOES=""
1341 if [ "${#L_NAME[@]}" -gt 1 ]; then
1342 for ((k = 0; k < ${#L_ID[@]}; k++)); do
1343 [ -z "${L_ID[k]}" ] || ids+=("${L_ID[k]}")
1344 done
1345 elif [ -n "$CHANGE_ID" ]; then
1346 ids=("$CHANGE_ID")
1347 fi
1348 [ "${#ids[@]}" -gt 0 ] || return 0
1349 DOES="$(valley-go does "$@" "${ids[@]}")" || DOES=""
1350}
1351
1352# does_of <change ID>: print the `does ...` lines for one change from DOES.
1353does_of() {
1354 local line
1355 [ -n "$1" ] || return 0
1356 while IFS= read -r line; do
1357 [ "${line%%$'\t'*}" != "$1" ] || printf '%s\n' "${line#*$'\t'}"
1358 done <<< "$DOES"
1359}
1360
1361# full_diff <branch> <head>: the whole diff of a change alone: its log
1362# and its diff against origin/main.
1363full_diff() {
1364 local sha
1365 sha="$(git rev-parse --short "$2")"
1366 if [ -n "$CHANGE_HEAD" ]; then
1367 printf 'change %s v%s at %s, on branch %s, log against origin/main:\n\n' \
1368 "$CHANGE_HANDLE" "$CHANGE_VERSION" "$sha" "$1"
1369 else
1370 printf 'branch %s, log against origin/main:\n\n' "$1"
1371 fi
1372 git --no-pager log --oneline "origin/main..$2"
1373 printf '\n'
1374 git --no-pager diff "origin/main...$2"
1375}
1376
1377# show_review <branch>: show a change alone. A change that is not ready
1378# says so first, before anything else shown of it (shown_not_ready). That
1379# notice becomes the heading, so the change's knots follow it.
1380show_review() {
1381 local branch="$1" head held
1382 head="$(change_head "$branch")"
1383 # [a]pprove approves exactly the head shown here (bind_review).
1384 [ -n "$CHANGE_ID" ] || APPROVE_HEAD="$head"
1385 held="$(shown_not_ready)" || held=""
1386 REVIEW_TMP="$(mktemp -d)"
1387 compare_shown "$CHANGE_ID" "$CHANGE_VERSION" "$head"
1388 show_compared "$branch" "$head" "$held" "$(does_of "$CHANGE_ID")" full_diff "$branch" "$head"
1389}
1390
1391# view_full <branch>: [v]iew full diff for a change alone. It pages the
1392# change's whole diff, and keeps the notes taken in it.
1393view_full() {
1394 local head
1395 head="$(change_head "$1")"
1396 REVIEW_TMP="$(mktemp -d)"
1397 full_diff "$1" "$head" > "$REVIEW_TMP/review.diff"
1398 page_buffer "$1" "$(git rev-parse --short "$head")"
1399}
1400
1401# page_buffer <branch> <sha>: page the buffer written to REVIEW_TMP, and
1402# keep the notes taken in it under the branch, against the commit shown.
1403page_buffer() {
1404 cp "$REVIEW_TMP/review.diff" "$REVIEW_TMP/review.orig"
1405 page_file "$REVIEW_TMP/review.diff" || true # quitting the pager early is not an error
1406 collect_notes "$1" "$2"
1407 cleanup_review_tmp
1408}
1409
1410# Everything review and approve leave outside the repository: approve's
1411# throwaway worktree, the paged buffer, the two policy layers read out of
1412# their tips, and the scratch the policy deriver writes into. One handler,
1413# installed once by each of those verbs, so that no path through them —
1414# and no ctrl-C in the pager — leaves any of them behind. The rebase's
1415# worktree is valley-go's, which removes it itself.
1416cleanup_scratch() {
1417 cleanup_approve_wt
1418 cleanup_policy_tmp
1419 cleanup_instance_tmp
1420 cleanup_project_tmp
1421 cleanup_review_tmp
1422}
1423
1424# [b]ase and the rebase verb are one piece of code, valley-go rebase
1425# (status/rebase.go). It rebases the change's whole stack in a throwaway
1426# worktree of its own — the user's checkout is never touched — pushes
1427# every layer's branch in one atomic push, leased on the tips it read, and
1428# adds each change's rebased head to its record as a new version. A
1429# change alone prints what rebase always has; a stack prints a manifest
1430# of what became of each layer. The judgment on the rebased diff stays
1431# with the human, back at the review prompt or in whatever front end ran
1432# the rebase verb.
1433#
1434# rebase_shown <head>: [b]ase for the change under review, while it is
1435# still at <head>, the head review showed of it.
1436rebase_shown() {
1437 valley-go rebase --head "$1" "${CHANGE_ID:-$CHANGE_NAME}"
1438}
1439
1440# ----------------------------------------------------------------------
1441# approve — file an integration request for the branch under review.
1442#
1443# This is the one way a change reaches main from here: the checks the
1444# policy requires are run over the branch's tree and signed, the evidence
1445# and one request ref are published, and the integrator judges the request
1446# and lands it (archive/design/integration.md). main is never touched from here.
1447#
1448# Nothing in this script writes the protected ref. Whether a given pusher
1449# may write it is a fact about origin's pre-receive hook, so origin is
1450# where it is answered, and a verb that merged onto main locally would only
1451# be asking the same question in a worse place.
1452#
1453# What this verb removes is a second push. `attest run --push` publishes
1454# the branch and the attestation refs in one atomic push and knows nothing
1455# about a request ref, so filing a request by hand is two beats: the
1456# evidence, then the request after it. In between, evidence stands
1457# published for a change nobody has approved. So this verb does not
1458# use --push at all. `attest run` without it stores each note at its ref in
1459# the repository and stops, and one `git push --atomic` then carries the
1460# evidence and the request together — all of it or none of it. Nothing in
1461# attest had to change for that; the sequencing was the whole of it.
1462#
1463# The branch itself is not in that push. What is under review is
1464# origin/<branch>, so the commit the request names is already on origin and
1465# the objects with it.
1466
1467# The tree the checks run over: a throwaway worktree of the branch, as
1468# [b]ase uses, so that what is checked is the branch's tree and not the
1469# operator's working copy. A global, so the traps clean it up whatever
1470# happens.
1471APPROVE_WT=""
1472# The head approve last ran the checks over and saw them fail, for the
1473# review prompt: see approve_failed_at.
1474CHECKS_FAILED_AT=""
1475cleanup_approve_wt() {
1476 [ -n "$APPROVE_WT" ] || return 0
1477 git worktree remove --force "$APPROVE_WT" > /dev/null 2>&1 || true
1478 rm -rf "$APPROVE_WT"
1479 APPROVE_WT=""
1480}
1481
1482# Report and fail, without leaving the review. A refusal here is not a
1483# reason to end the session: the branch is still under review and the
1484# operator can still answer. die() is for the verbs that have nothing left
1485# to offer. The approve verb has nothing left to offer either, and turns a
1486# refusal into its exit status itself.
1487refuse() {
1488 printf 'valley: %s\n' "$*" >&2
1489 return 1
1490}
1491
1492# The change segment of a request ref. The integrator reads a request as
1493# <prefix>/<target>/<change> and refuses a change segment holding a slash
1494# (integrator/refs.go), so a branch name with one is written with dashes
1495# instead. The ref that results is printed, never left to be assumed.
1496#
1497# The mapping is lossy: `topic/x` and `topic-x` are one change name and so
1498# one request ref, and this verb cannot tell a sibling's request from its
1499# own. That is bd-57f7f9f, and what is done about it here is to print the
1500# subject of any request being replaced, so a collision is visible at the
1501# moment it happens rather than after it.
1502change_name() {
1503 printf '%s' "${1//\//-}"
1504}
1505
1506# One line of a commit, for saying which commit is meant. A request being
1507# replaced is usually this operator's own pre-rebase head and so is in
1508# this repository; one another operator filed may not be, and saying so is
1509# better than printing an id alone.
1510subject_of() {
1511 local s
1512 if s="$(git log -1 --format=%s "$1" 2>/dev/null)" && [ -n "$s" ]; then
1513 printf '%s' "$s"
1514 else
1515 printf 'subject not in this repository'
1516 fi
1517}
1518
1519# The value of a ref on origin, as one id or the empty string. Failing to
1520# read it is not the same as reading that it is absent, so the two are
1521# separate answers: this returns 1 for a read that did not happen.
1522remote_ref() {
1523 local out
1524 out="$(git ls-remote origin "$1" 2>/dev/null)" || return 1
1525 printf '%s' "$out" | cut -f1
1526 return 0
1527}
1528
1529# Where the checks this run signed are stored, for every failure that
1530# happens after they have run. One stanza, so no failure path invents its
1531# own wording. Called with no refs it says nothing.
1532report_local_evidence() {
1533 [ "$#" -gt 0 ] || return 0
1534 printf 'valley: the evidence is stored locally at:\n' >&2
1535 printf ' %s\n' "$@" >&2
1536}
1537
1538# Whether origin already holds one of these attestation refs at a value
1539# other than the one being pushed. The namespace admits creations only, so
1540# that is the one refusal approving again will never clear: it is what a
1541# re-observation of a tree this signer has already attested runs into
1542# (bd-7b7d58f).
1543attestation_stands_elsewhere() {
1544 local digest="$1" remote spec have want
1545 shift
1546 remote="$(git ls-remote origin "refs/the-valley/attestations/$digest/*" 2>/dev/null)" || return 1
1547 for spec in "$@"; do
1548 have="$(printf '%s\n' "$remote" | awk -v r="$spec" '$2 == r { print $1 }')"
1549 [ -n "$have" ] || continue
1550 want="$(git rev-parse "$spec" 2>/dev/null)" || continue
1551 [ "$have" = "$want" ] || return 0
1552 done
1553 return 1
1554}
1555
1556# Why a push carrying the request ref failed, said as precisely as the
1557# state allows. Every such push is leased, and a lease refuses when the
1558# ref it named is not where the read before it saw it — which covers three
1559# different events. Reading the ref again is what tells them apart, and a
1560# read that does not happen is its own answer rather than a guess.
1561#
1562# Anything the lease is not responsible for is origin's own refusal, and
1563# git has already printed it.
1564diagnose_request_push() {
1565 local ref="$1" pending="$2" now
1566 if ! now="$(remote_ref "$ref")"; then
1567 refuse "origin refused the push, and $ref could not be read again to say why. Nothing was published there and main is untouched"
1568 return 0
1569 fi
1570 if [ "$now" = "$pending" ]; then
1571 refuse "origin refused the push; nothing was published there and main is untouched"
1572 elif [ -z "$now" ]; then
1573 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"
1574 elif [ -z "$pending" ]; then
1575 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"
1576 else
1577 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"
1578 fi
1579}
1580
1581# File the request. Called in a condition, from the review prompt and from
1582# the approve verb alike, which suspends `set -e` for the whole call — so
1583# every step below is checked by hand, and the failures say what was
1584# published before they happened.
1585approve() {
1586 local branch="$1" target=main tip change head base digest root ref check spec what
1587 local key
1588 local -a signer=() required=() run=() timing=() evidence=()
1589
1590 root="$(git rev-parse --show-toplevel)" || {
1591 refuse "not a git repository; nothing published"
1592 return 1
1593 }
1594 tip=refs/remotes/origin/main
1595 # A change with a record is filed at exactly the head bound to this
1596 # approval, under its own request name, c-<change ID>, and only while its
1597 # record says it is ready and lists that head as a version's. Where its
1598 # branch is does not matter: the request names the head.
1599 if [ -n "$CHANGE_ID" ]; then
1600 head="$APPROVE_HEAD"
1601 [ -n "$head" ] || {
1602 refuse "no head of change $CHANGE_HANDLE is bound to this approval; nothing published"
1603 return 1
1604 }
1605 check_record "nothing published" "" "$head" || return 1
1606 change="c-$CHANGE_ID"
1607 what="$CHANGE_HANDLE v$APPROVE_VERSION"
1608 elif [ -n "$APPROVE_HEAD" ]; then
1609 # A plain branch that review showed is filed at the head shown. The
1610 # last check before the push refuses if the branch on origin has moved
1611 # off it since.
1612 head="$APPROVE_HEAD"
1613 change="$(change_name "$branch")"
1614 what="$branch"
1615 else
1616 head="$(git rev-parse "refs/remotes/origin/$branch")" || {
1617 refuse "no such branch on origin: $branch; nothing published"
1618 return 1
1619 }
1620 change="$(change_name "$branch")"
1621 what="$branch"
1622 fi
1623 # c-<change ID> is the request name of the change with that ID, so a
1624 # branch is never filed under one.
1625 if [ -z "$CHANGE_ID" ] && [[ "$change" =~ ^c-[k-z]{32}$ ]]; then
1626 refuse "the branch $branch would be requested as $change, and that name is reserved for the change with the ID ${change#c-}; rename the branch, or name the change by its ID. Nothing published"
1627 return 1
1628 fi
1629 base="$(git merge-base "$tip" "$head")" || {
1630 refuse "$what and main share no history; nothing published"
1631 return 1
1632 }
1633 ref="refs/the-valley/integration-requests/$target/$change"
1634 local named="$branch" under of
1635 [ -z "$CHANGE_ID" ] || named="$CHANGE_HANDLE"
1636
1637 # A head that does not fast-forward from main, and would bring a version
1638 # of another change that has not landed, is a layer above the bottom of
1639 # a stale stack. The integrator could land it all the same, as one
1640 # commit recorded against this request alone, and the changes under it
1641 # would have no landing record of their own. So it is refused before
1642 # any check runs over a head that has to be rebased anyway, and the
1643 # stack is rebased first. This is the project's choice, not a rule the
1644 # integrator needs. A stale head with no change under it, such as the
1645 # bottom layer of a stack or a change alone, is approved as it is, and
1646 # the integrator merges it onto main.
1647 if ! git merge-base --is-ancestor "$tip" "$head"; then
1648 if ! under="$(valley-go brings ${CHANGE_ID:+--change "$CHANGE_ID"} "$head")"; then
1649 refuse "could not read which changes $what would bring to main; nothing published"
1650 return 1
1651 fi
1652 if [ -n "$under" ]; then
1653 of="a version of $under"
1654 [ "$(printf '%s\n' "$under" | wc -l)" -eq 1 ] || of="versions of $(printf '%s\n' "$under" | join_lines)"
1655 refuse "$what does not fast-forward from main, and the commits it would bring hold $of, not landed. Approved as it is, it would land them with no landing record of their own; nothing published. Rebase the stack first: valley rebase $(printf '%q' "$named")"
1656 return 1
1657 fi
1658 fi
1659
1660 # What the policy requires of the change, read out of exactly the
1661 # sources the integrator reads: both layers from the target's tip, which
1662 # review has just fetched, and the floor from the owning valley's own
1663 # tip. A change never supplies the policy that gates it, and neither does
1664 # the checkout this runs from — so the answer here is the same answer the
1665 # integrator will derive, from whatever branch the operator happens to be
1666 # on. It is printed for exactly that reason.
1667 policy_defaults "$root"
1668 resolve_instance_layer "$root" "$tip" || return 1
1669 resolve_project_layer "$root" "$tip" || return 1
1670 derive_required "$POLICY_SCHEMA" "$POLICY_INSTANCE" "$POLICY_PROJECT" \
1671 "$base" "$head" || return 1
1672 sort_into required "${!DERIVED_REQUIRED[@]}" || {
1673 refuse "could not sort the required checks; nothing published"
1674 return 1
1675 }
1676
1677 # A change the policy asks nothing of is still a change, and approving
1678 # is how one reaches main. The integrator already lands a request that
1679 # requires no check and records the landing as one that required nothing
1680 # (archive/design/integration.md), so refusing to file it here would strand
1681 # exactly the changes the policy requires nothing of. Nothing is required,
1682 # so nothing is signed and no key is needed: what gets published is one
1683 # request ref and no evidence at all.
1684 #
1685 # A required check whose evidence origin already holds is reused, not
1686 # built again: a check worker, or an earlier approval, may have published
1687 # it. valley-go coverage (status/coverage.go) lists origin's attestation
1688 # refs for the head's tree, fetches them, and says which required nix
1689 # checks they hold acceptable evidence for. Every other check, and every
1690 # command check, runs here. A read of origin that fails ends the approval
1691 # rather than reading as no evidence. When every check is covered,
1692 # nothing runs and no key is needed, as when nothing is required.
1693 local -a missing=() reused=()
1694 local -A stored=() covered=()
1695 if [ "${#required[@]}" -gt 0 ]; then
1696 command -v attest > /dev/null 2>&1 || {
1697 refuse "this choice needs the attest helper; nix run .#valley bundles it. Nothing published"
1698 return 1
1699 }
1700 local -a asked=()
1701 for check in "${required[@]}"; do
1702 [ "${CHECK_RUNNER[$check]:-}" != nix ] || asked+=(--check "$check=${CHECK_ATTRIBUTE[$check]}")
1703 done
1704 local coverage kind field value by
1705 if ! coverage="$(valley-go coverage --head "$head" ${asked[@]+"${asked[@]}"})"; then
1706 refuse "could not read the evidence origin holds for $what; nothing run, nothing published"
1707 return 1
1708 fi
1709 while read -r kind field value by; do
1710 case "$kind" in
1711 digest) digest="$field" ;;
1712 stored) stored["$field"]="$value" ;;
1713 covered) covered["$field"]="$value $by" ;;
1714 esac
1715 done <<< "$coverage"
1716 [ -n "$digest" ] || {
1717 refuse "valley-go coverage named no tree for $what; nothing run, nothing published"
1718 return 1
1719 }
1720 for check in "${required[@]}"; do
1721 if [ -n "${covered[$check]:-}" ]; then reused+=("$check"); else missing+=("$check"); fi
1722 done
1723 if [ "${#reused[@]}" -gt 0 ]; then
1724 printf '\nreusing the evidence origin holds for %s at %s:\n' "$what" "$(git rev-parse --short "$head")"
1725 for check in "${reused[@]}"; do
1726 printf ' %-24s signed by %s\n' "$check" "${covered[$check]#* }"
1727 done
1728 fi
1729 fi
1730
1731 if [ "${#missing[@]}" -gt 0 ]; then
1732 key="${VALLEY_ATTEST_KEY:-}"
1733 [ -n "$key" ] || {
1734 refuse "no signing key: set VALLEY_ATTEST_KEY to the ed25519 key this host attests with. The host signs; nothing published"
1735 return 1
1736 }
1737 [ -f "$key" ] || {
1738 refuse "no signing key at $key; nothing published"
1739 return 1
1740 }
1741 signer=(--key "$key")
1742 [ -z "${VALLEY_ATTEST_NAME:-}" ] || signer+=(--name "$VALLEY_ATTEST_NAME")
1743
1744 # The ref this run's evidence goes to is keyed by the tree and this
1745 # signer's key hash, and the namespace admits creations only. When
1746 # origin already holds it, evidence for the checks still missing has
1747 # nowhere to go, so that is said before anything is built rather than
1748 # after (bd-7b7d58f).
1749 local verifier keyhash own
1750 verifier="$(attest key "${signer[@]}")" || {
1751 refuse "could not read the signing key at $key; nothing published"
1752 return 1
1753 }
1754 keyhash="${verifier#*+}"
1755 own="refs/the-valley/attestations/$digest/${keyhash%%+*}"
1756 if [ -n "${stored[$own]:-}" ]; then
1757 refuse "origin already holds $own, this signer's evidence for this tree, and it does not cover $(printf '%s\n' "${missing[@]}" | join_lines). That namespace admits creations only, so evidence for the rest has nowhere to go: that is bd-7b7d58f, which approving again will not clear. Nothing run, nothing published"
1758 return 1
1759 fi
1760
1761 # attest logs how long each check took, on this machine and outside
1762 # the evidence. What it cannot know itself is passed in: the change,
1763 # and each check's declared cost.
1764 timing=(--timings)
1765 [ -z "$CHANGE_ID" ] || timing+=(--change "$CHANGE_ID")
1766 [ -z "$APPROVE_VERSION" ] || timing+=(--change-version "$APPROVE_VERSION")
1767 for check in "${missing[@]}"; do
1768 case "${CHECK_RUNNER[$check]:-}" in
1769 nix) run+=(--check "$check=${CHECK_ATTRIBUTE[$check]}") ;;
1770 command) run+=(--command "$check=${CHECK_COMMAND[$check]}") ;;
1771 *)
1772 refuse "the policy requires $check but does not say how to run it; nothing published"
1773 return 1
1774 ;;
1775 esac
1776 [ -z "${CHECK_COST[$check]:-}" ] || timing+=(--cost "$check=${CHECK_COST[$check]}")
1777 done
1778
1779 cleanup_approve_wt
1780 APPROVE_WT="$(mktemp -d)" || {
1781 refuse "no scratch directory to check $what in; nothing published"
1782 return 1
1783 }
1784 git worktree add --quiet --detach "$APPROVE_WT" "$head" || {
1785 cleanup_approve_wt
1786 refuse "could not check $what out to run its checks; nothing published"
1787 return 1
1788 }
1789
1790 printf '\nchecking %s at %s: %s\n' "$what" "$(git rev-parse --short "$head")" \
1791 "$(printf '%s\n' "${missing[@]}" | join_lines)"
1792 if ! attest run --repo "$APPROVE_WT" "${signer[@]}" "${timing[@]}" "${run[@]}"; then
1793 cleanup_approve_wt
1794 CHECKS_FAILED_AT="$head"
1795 refuse "the checks did not pass; nothing published, main untouched"
1796 return 1
1797 fi
1798 cleanup_approve_wt
1799
1800 # Every attestation stored here for this tree, whoever signed it: the
1801 # evidence for this change is what the subject digest is keyed by, not
1802 # what this run happened to add to it.
1803 mapfile -t evidence < <(git for-each-ref --format='%(refname)' \
1804 "refs/the-valley/attestations/$digest")
1805 [ "${#evidence[@]}" -gt 0 ] || {
1806 refuse "no attestation is stored for $digest; nothing published"
1807 return 1
1808 }
1809 elif [ "${#required[@]}" -eq 0 ]; then
1810 printf '\n%s requires no check under %s + %s; filing the request with no evidence\n' \
1811 "$what" "$POLICY_INSTANCE_LABEL" "$POLICY_PROJECT_LABEL"
1812 fi
1813
1814 # What origin already holds for this request, read once and remembered.
1815 # Approving the same change twice is ordinary: evidence expires, and a
1816 # change whose input closure moved under it is told to re-attest. So the
1817 # request ref may already exist, and what to do about it depends on
1818 # where it points. A read that does not happen is not a read that found
1819 # nothing, so it ends the verb here.
1820 local pending
1821 if ! pending="$(remote_ref "$ref")"; then
1822 refuse "could not read $ref from origin; nothing published"
1823 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1824 return 1
1825 fi
1826
1827 # The one push: every evidence ref as it stands, and the request ref
1828 # wherever it has to go. --atomic, so a hook that refuses any of them
1829 # leaves origin exactly as it was.
1830 #
1831 # Every write of the request ref is leased against exactly what the read
1832 # above saw, including when it saw nothing: git spells that expectation
1833 # `--force-with-lease=<ref>:` with an empty value, and it refuses if the
1834 # ref exists at all. So filing a change for the first time is a
1835 # compare-and-swap too. Without it, two operators filing one change at
1836 # once would have the second silently fast-forward the first away.
1837 #
1838 # A pending request at this same head is a re-attestation of the tree
1839 # already approved. The evidence is new and the ref does not move, so
1840 # the ref is left out of the refspec entirely — a push cannot carry a
1841 # compare-and-swap on a ref it is not changing, because git leaves an
1842 # up-to-date ref out of what it sends. Nothing this run does establishes
1843 # where that ref stands afterwards, so it is read again below.
1844 #
1845 # A pending request at a different head is a replacement. This is the
1846 # shape a change takes when main moved through its checks' input
1847 # closures: no attestation over the old tree can transfer again, so the
1848 # cure is a new head rebased onto the moved main — and that head is not
1849 # a descendant of the old one, which makes replacing the ref a
1850 # non-fast-forward update that git refuses unless told.
1851 #
1852 # The lease is the whole of the force, and the refspec carries no `+`.
1853 # A leading `+` sets git's per-ref force flag, and that flag defeats
1854 # every rejection the push rules produce — the lease's stale-info among
1855 # them. The two together are a plain force wearing a lease's name.
1856 local -a push=() lease=()
1857 for spec in ${evidence[@]+"${evidence[@]}"}; do push+=("$spec:$spec"); done
1858 if [ "$pending" != "$head" ]; then
1859 lease+=("--force-with-lease=$ref:$pending")
1860 push+=("$head:$ref")
1861 fi
1862
1863 # The checks can take minutes, and the record may have moved meanwhile.
1864 # So it is read once more, just before anything is filed, and a name that
1865 # read as a plain branch is read again in case it names a change now.
1866 #
1867 # This is the last check, and a window remains between it and the push
1868 # below. A change unreadied or withdrawn in that window is filed all the
1869 # same. git compares only the refs a push changes, and the record ref is
1870 # not one of them, so no client can make the filing conditional on the
1871 # record. The integrator narrows the window: it lands no request that
1872 # would bring a version of a change that is not ready, whatever the
1873 # request is named, so a request filed in the window stays until the
1874 # change is ready again. It reads the records last just before it moves
1875 # the target, so only a record written in that moment is missed.
1876 if ! check_record "nothing published" "$head" "$APPROVE_HEAD"; then
1877 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1878 return 1
1879 fi
1880 # A plain branch is filed at the head review showed only while the
1881 # branch on origin is still there. The operator reviewed a branch, and a
1882 # branch that moved holds commits nobody has read. A change with a
1883 # record is filed at its head wherever its branch is.
1884 if [ -z "$CHANGE_ID" ] && [ -n "$APPROVE_HEAD" ] && ! branch_at_shown "$branch"; then
1885 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1886 return 1
1887 fi
1888
1889 # With no new evidence, because nothing was required or origin already
1890 # held all of it, and the request already standing at this head, there
1891 # is nothing to push. A push assembled with an empty refspec would fall
1892 # back to origin's default one, so none is made.
1893 local made_push=no
1894 if [ "${#push[@]}" -gt 0 ]; then
1895 made_push=yes
1896 if ! git push --atomic --quiet ${lease[@]+"${lease[@]}"} origin "${push[@]}"; then
1897 if [ "${#lease[@]}" -eq 0 ] \
1898 && attestation_stands_elsewhere "$digest" ${evidence[@]+"${evidence[@]}"}; then
1899 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"
1900 else
1901 diagnose_request_push "$ref" "$pending"
1902 fi
1903 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1904 return 1
1905 fi
1906 fi
1907
1908 # The lines under the request line, which differ by what was found and
1909 # what was done about it.
1910 local -a standing=()
1911
1912 if [ "$pending" = "$head" ]; then
1913 # The request ref was not in that push, so where it stands now is not
1914 # something this run established. Read it again rather than repeat
1915 # what was read before it: in between, the integrator may have landed
1916 # the change and consumed the ref, or another approval may have
1917 # replaced it.
1918 #
1919 # Nothing here writes it back. Re-creating a consumed request would
1920 # file a change already in the stream, which the commit rule calls out
1921 # as the state it consumes the ref to avoid; replacing a request
1922 # another approval has just filed would clobber the winner; and
1923 # either would be a second push behind the one this verb promises. So
1924 # what this does is say what is true and stop. Approving again is the
1925 # repair, and by then it takes the create or the replace path against
1926 # what is actually there.
1927 local after
1928 if ! after="$(remote_ref "$ref")"; then
1929 refuse "$ref could not be read again, so whether the request still stands at this head is not known here"
1930 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1931 return 1
1932 fi
1933 if [ -z "$after" ]; then
1934 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 $what again, and approve it once more if it has not landed"
1935 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1936 return 1
1937 fi
1938 if [ "$after" != "$head" ]; then
1939 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"
1940 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1941 return 1
1942 fi
1943 if [ "$made_push" = yes ]; then
1944 standing+=("the request already stood at this head; the evidence is what was published")
1945 elif [ "${#required[@]}" -gt 0 ]; then
1946 standing+=("the request already stood at this head and origin already held the evidence, so nothing needed publishing")
1947 else
1948 standing+=("the request already stood at this head and nothing was required, so nothing needed publishing")
1949 fi
1950 elif [ -n "$pending" ]; then
1951 standing+=("replaced the pending request, which stood at $(git rev-parse --short "$pending") ($(subject_of "$pending"))")
1952 fi
1953
1954 printf '\nApproved %s (%s): its integration request for origin/%s is filed.\n' \
1955 "$what" "$(git rev-parse --short "$head")" "$target"
1956 printf 'The integrator will decide whether this change can land.\n'
1957 printf 'Your local checkout has not changed.\n\n'
1958 printf 'Check the result: valley status %q\n\n' "$named"
1959 printf ' request %s -> %s\n' "$ref" "$(git rev-parse --short "$head")"
1960 [ "${#standing[@]}" -eq 0 ] || printf ' %s\n' "${standing[@]}"
1961 if [ "${#required[@]}" -eq 0 ]; then
1962 printf ' evidence none — nothing was required, so nothing was signed\n'
1963 printf ' checks none — the policy requires no check of this change\n'
1964 else
1965 [ "${#evidence[@]}" -eq 0 ] || printf ' evidence %s\n' "${evidence[@]}"
1966 # The refs on origin whose evidence was reused, each once.
1967 local -A shown=()
1968 for check in ${reused[@]+"${reused[@]}"}; do
1969 spec="${covered[$check]%% *}"
1970 [ -z "${shown[$spec]:-}" ] || continue
1971 shown["$spec"]=1
1972 printf ' reused %s\n' "$spec"
1973 done
1974 printf ' checks %s\n' "$(printf '%s\n' "${required[@]}" | join_lines)"
1975 fi
1976}
1977
1978# status, ready, unready and withdraw are a Go program, valley-go
1979# (status/). status reads a change's request and outcome from origin,
1980# because what front ends read from it is a JSON contract, and because the
1981# read is subtle enough to want a real parser: an outcome record it does
1982# not recognise must read as unknown, never as success. It writes nothing
1983# and moves no local branch. ready, unready and withdraw write a change's
1984# record, in the one format the push hook reads it in (change/). knot
1985# reads and writes the plan graph at refs/the-valley/knots, in the one
1986# form the push hook validates (knot/), and plan shows that graph as a
1987# view.
1988cmd_go() {
1989 command -v valley-go > /dev/null 2>&1 \
1990 || die "$1 needs the valley-go helper; nix run .#valley bundles it"
1991 exec valley-go "$@"
1992}
1993
1994# A change is named by its full change ID, its handle, or its branch.
1995# resolve_change reads the name with the helper and sets CHANGE_BRANCH, the
1996# branch to act on. When the name is a change's, it also sets the change's
1997# ID, handle, active version, state and owner, and CHANGE_HEAD, the head
1998# that version records. A branch name is a change's when exactly one record's
1999# active version is on that branch, and is refused when more than one's is.
2000# So whether a change's record is read never depends on how it is named,
2001# and review, approve and rebase cannot run without the helper.
2002#
2003# A change with a record is acted on at a head its record names, and never
2004# at the branch's tip: review at CHANGE_HEAD, and approve at the head bound
2005# to it (bind_head). rebase reads the record itself (status/rebase.go).
2006# The branch a record names is only where its head is expected to be, and
2007# anyone who can push the branch can move it, in the same push as the
2008# record if they like.
2009CHANGE_NAME="" CHANGE_ID="" CHANGE_HANDLE="" CHANGE_VERSION="" CHANGE_HEAD="" CHANGE_BRANCH="" CHANGE_STATE=""
2010CHANGE_OWNER=""
2011
2012# read_resolved <line> <name…>: read a line of valley-go resolve into the
2013# variables named, one field each. A version's branch may be empty, and
2014# read runs consecutive tabs together, since a tab is whitespace to it: an
2015# empty branch would shift the state into the branch. So each tab is made
2016# a unit separator first, which read keeps apart.
2017read_resolved() {
2018 local resolved="$1"
2019 shift
2020 IFS=$'\x1f' read -r "$@" <<< "${resolved//$'\t'/$'\x1f'}"
2021}
2022
2023# ready_hint <change ID> <branch>: the valley ready line that readies the
2024# change again, naming the branch unless its version records none.
2025ready_hint() {
2026 printf 'valley ready --change %s' "$1"
2027 [ -z "$2" ] || printf ' %q' "$2"
2028}
2029
2030resolve_change() {
2031 local line kind
2032 CHANGE_NAME="$1"
2033 command -v valley-go > /dev/null 2>&1 \
2034 || die "review, approve and rebase read the change's record with the valley-go helper; nix run .#valley bundles it"
2035 line="$(valley-go resolve "$1")" || return 1
2036 read_resolved "$line" kind CHANGE_ID CHANGE_HANDLE CHANGE_VERSION CHANGE_HEAD CHANGE_BRANCH CHANGE_STATE CHANGE_OWNER
2037 case "$kind" in
2038 branch)
2039 CHANGE_BRANCH="$CHANGE_ID"
2040 CHANGE_ID=""
2041 ;;
2042 change)
2043 [[ "$CHANGE_HEAD" =~ ^[0-9a-f]{40}$ ]] \
2044 || die "valley-go resolve named the head $CHANGE_HEAD, which is no object ID"
2045 case "$CHANGE_STATE" in
2046 ready | draft | withdrawn) ;;
2047 *) die "valley-go resolve named the state $CHANGE_STATE, which this script does not read" ;;
2048 esac
2049 ;;
2050 *) die "valley-go resolve answered $line, which this script does not read" ;;
2051 esac
2052}
2053
2054# need_branch <verb>: refuse a change whose active version records no
2055# branch. review acts on the change's branch: it files its notes under it
2056# and its [r]eject deletes it. rebase, which pushes it, refuses such a
2057# change in valley-go. approve files the head alone, so it approves such a
2058# change.
2059need_branch() {
2060 if [ -n "$CHANGE_ID" ] && [ -z "$CHANGE_BRANCH" ]; then
2061 die "change $CHANGE_HANDLE v$CHANGE_VERSION records no branch, and $1 acts on a change's branch. Approve its head alone: valley approve --head $CHANGE_HEAD $CHANGE_HANDLE"
2062 fi
2063}
2064
2065# The commit review and approve act on: the recorded head for a change
2066# with a record, and otherwise the branch's head on origin.
2067change_head() {
2068 if [ -n "$CHANGE_HEAD" ]; then
2069 printf '%s\n' "$CHANGE_HEAD"
2070 else
2071 git rev-parse "refs/remotes/origin/$1"
2072 fi
2073}
2074
2075# For a change with a record, refuse unless the branch's tip on origin is
2076# the recorded head, and name both. review's [r]eject acts on the branch
2077# itself: deleting it while it is elsewhere would delete a commit no
2078# version records. rebase asks the same in valley-go. approve does not ask
2079# this, since the request it files names the head it approves and not the
2080# branch. The second argument is what the refusal leaves undone.
2081check_recorded_tip() {
2082 local branch="$1" undone="$2" tip
2083 [ -n "$CHANGE_HEAD" ] || return 0
2084 tip="$(git rev-parse "refs/remotes/origin/$branch")" || {
2085 refuse "no such branch on origin: $branch; $undone"
2086 return 1
2087 }
2088 [ "$tip" = "$CHANGE_HEAD" ] && return 0
2089 refuse "change $CHANGE_HANDLE v$CHANGE_VERSION records the head $CHANGE_HEAD, and origin/$branch is at $tip; $undone. Ready the branch's head as a new version of $CHANGE_HANDLE to act on it"
2090}
2091
2092# For a change with a record, read the record again from origin, and
2093# refuse unless the change is still ready at the head this run began with.
2094# A draft is paused and a withdrawn change given up, and neither is
2095# approved until it is readied again. The record was read when review or
2096# approve began, and another principal may unready, withdraw or ready a
2097# new version of the change while a review is open or the checks run. So
2098# approve reads it again before it runs the checks and before it files.
2099# These checks save a run that would come to nothing: the integrator makes
2100# the same one on origin, and lands no request for a change that is not
2101# ready. rebase makes its own checks in valley-go (status/rebase.go).
2102#
2103# A name that read as a plain branch can come to name a change meanwhile:
2104# someone readies the branch, and perhaps unreadies it, while the review
2105# is open. So the last check before approve files reads the original name
2106# again too. approve passes the head it is about to file as the second
2107# argument. When the name now names a change, the same rules hold: the
2108# change must be ready, and its recorded head must be that head. The first
2109# argument is what the refusal leaves undone.
2110#
2111# approve binds the head it approves (APPROVE_HEAD), and passes it as the
2112# third argument. For approve the change must be ready, and that head must
2113# be one of its version heads, whichever version is active by then: a
2114# record that moves after review cannot change what lands, since the
2115# request names the head approved.
2116check_record() {
2117 local undone="$1" acting="${2:-}" bound="${3:-}" line kind id handle version head branch state owner
2118 if [ -z "$CHANGE_ID" ]; then
2119 [ -n "$acting" ] || return 0
2120 if ! line="$(valley-go resolve "$CHANGE_NAME")"; then
2121 refuse "could not read $CHANGE_NAME again against origin's records; $undone"
2122 return 1
2123 fi
2124 read_resolved "$line" kind id handle version head branch state owner
2125 [ "$kind" = change ] || return 0
2126 if [ "$state" != ready ]; then
2127 refuse "$CHANGE_NAME is now change $handle v$version, which is $state, not ready; $undone. Ready it first: $(ready_hint "$id" "$branch")"
2128 return 1
2129 fi
2130 if [ "$head" != "$acting" ]; then
2131 refuse "$CHANGE_NAME is now change $handle v$version, which records the head $head, and this run began at $acting; $undone. Review it again by its handle"
2132 return 1
2133 fi
2134 return 0
2135 fi
2136 if ! line="$(valley-go resolve "$CHANGE_ID")"; then
2137 refuse "could not read the record of change $CHANGE_HANDLE again; $undone"
2138 return 1
2139 fi
2140 read_resolved "$line" kind id handle version head branch state owner
2141 if [ "$kind" != change ] || [ "$id" != "$CHANGE_ID" ]; then
2142 refuse "origin no longer holds a record of change $CHANGE_HANDLE; $undone"
2143 return 1
2144 fi
2145 if [ "$state" != ready ]; then
2146 refuse "change $CHANGE_HANDLE v$version is $state, not ready; $undone. Ready it first: $(ready_hint "$CHANGE_ID" "$branch")"
2147 return 1
2148 fi
2149 if [ -n "$bound" ]; then
2150 check_version "$undone" "$bound"
2151 return
2152 fi
2153 if [ "$head" != "$CHANGE_HEAD" ]; then
2154 refuse "change $CHANGE_HANDLE is at v$version, $head, and this run began at v$CHANGE_VERSION, $CHANGE_HEAD; $undone. Review it again at its new head"
2155 return 1
2156 fi
2157}
2158
2159# For a change with a record, read its versions from origin again, and
2160# refuse unless the change is ready and the head given is one of its
2161# versions' heads. Sets APPROVE_VERSION and APPROVE_TITLE to that
2162# version's number and title. The first argument is what the refusal
2163# leaves undone.
2164APPROVE_VERSION="" APPROVE_TITLE=""
2165check_version() {
2166 local undone="$1" head="$2" out n vhead vstate title state=""
2167 local -a known=()
2168 APPROVE_VERSION="" APPROVE_TITLE=""
2169 if ! out="$(valley-go versions "$CHANGE_ID")"; then
2170 refuse "could not read the versions of change $CHANGE_HANDLE; $undone"
2171 return 1
2172 fi
2173 # read empties its variables at the end of its input, so the state is
2174 # kept apart from them.
2175 while IFS=$'\t' read -r n vhead vstate title; do
2176 state="$vstate"
2177 known+=("v$n at $vhead")
2178 if [ "$vhead" = "$head" ]; then
2179 APPROVE_VERSION="$n"
2180 APPROVE_TITLE="$title"
2181 fi
2182 done <<< "$out"
2183 if [ "$state" != ready ]; then
2184 refuse "change $CHANGE_HANDLE is $state, not ready; $undone. Ready it first: $(ready_hint "$CHANGE_ID" "$CHANGE_BRANCH")"
2185 return 1
2186 fi
2187 if [ -z "$APPROVE_VERSION" ]; then
2188 refuse "$head is no version of change $CHANGE_HANDLE, whose versions are $(printf '%s\n' "${known[@]}" | join_lines); $undone"
2189 return 1
2190 fi
2191}
2192
2193# The head approve approves for a change with a record, in APPROVE_HEAD.
2194# With --head, it is exactly that head, which must be one of the record's
2195# version heads. A front end that shows the change its own way passes the
2196# head it showed, so what is approved is what was seen, whichever version
2197# the record makes active by then. Without --head, the operator is shown
2198# the active version's head and title and asked to confirm them, which
2199# needs a terminal; off one, approve refuses. The first argument is
2200# --head's value, or empty.
2201APPROVE_HEAD=""
2202bind_head() {
2203 local want="$1" sha answer
2204 APPROVE_HEAD=""
2205 if [ "$CHANGE_STATE" != ready ]; then
2206 refuse "change $CHANGE_HANDLE v$CHANGE_VERSION is $CHANGE_STATE, not ready; nothing published. Ready it first: $(ready_hint "$CHANGE_ID" "$CHANGE_BRANCH")"
2207 return 1
2208 fi
2209 if [ -n "$want" ]; then
2210 if ! [[ "$want" =~ ^[0-9a-f]{4,64}$ ]] \
2211 || ! sha="$(git rev-parse --verify --quiet "$want^{commit}")"; then
2212 refuse "--head takes the object ID of one of change $CHANGE_HANDLE's version heads, and $want is none here; nothing published"
2213 return 1
2214 fi
2215 check_version "nothing published" "$sha" || return 1
2216 APPROVE_HEAD="$sha"
2217 return 0
2218 fi
2219 check_version "nothing published" "$CHANGE_HEAD" || return 1
2220 if [ ! -t 0 ]; then
2221 refuse "approving change $CHANGE_HANDLE names the head it approves: off a terminal, pass it with --head. Its active version is v$APPROVE_VERSION at $CHANGE_HEAD, $APPROVE_TITLE: valley approve --head $CHANGE_HEAD $CHANGE_HANDLE. Nothing published"
2222 return 1
2223 fi
2224 printf 'approve change %s v%s at %s, %s? [y/N] ' \
2225 "$CHANGE_HANDLE" "$APPROVE_VERSION" "$CHANGE_HEAD" "$APPROVE_TITLE"
2226 read -r answer || answer=""
2227 case "$answer" in
2228 y | Y | yes) APPROVE_HEAD="$CHANGE_HEAD" ;;
2229 *)
2230 refuse "not approved; nothing published"
2231 return 1
2232 ;;
2233 esac
2234}
2235
2236# review shows a change with a record at its active version's head, and
2237# its [a]pprove approves exactly that head. A plain branch is bound to the
2238# head review pages, when it pages it (show_review, use_layer), and approve
2239# files that head. approve with no review binds nothing, and files the
2240# branch's tip on origin as the fetch left it.
2241bind_review() {
2242 APPROVE_HEAD="" APPROVE_VERSION=""
2243 if [ -n "$CHANGE_ID" ]; then
2244 APPROVE_HEAD="$CHANGE_HEAD"
2245 APPROVE_VERSION="$CHANGE_VERSION"
2246 fi
2247}
2248
2249# branch_at_shown <branch>: refuse unless the branch on origin is still at
2250# the head bound to this approval, and name both. origin itself is read,
2251# not the tracking ref: a push from another checkout moves the branch
2252# without moving this clone's ref. ls-remote matches a pattern against the
2253# tail of a ref name, so each ref it lists is compared whole.
2254branch_at_shown() {
2255 local out now
2256 out="$(git ls-remote origin "refs/heads/$1")" || {
2257 refuse "could not read $1 on origin to check that it is still at $APPROVE_HEAD, the head shown; nothing published"
2258 return 1
2259 }
2260 now="$(printf '%s\n' "$out" | awk -v r="refs/heads/$1" '$2 == r { print $1 }')"
2261 if [ -z "$now" ]; then
2262 refuse "origin/$1 is gone, and is no longer at $APPROVE_HEAD, the head shown; nothing published"
2263 return 1
2264 fi
2265 [ "$now" = "$APPROVE_HEAD" ] && return 0
2266 refuse "origin/$1 is at $now, and is no longer at $APPROVE_HEAD, the head shown; nothing published"
2267}
2268
2269# The head the checks failed at in this review, short, while the change is
2270# still at it. Approving that head again would run the same checks over
2271# the same tree and fail the same way, so the prompt stops offering
2272# [a]pprove until the change has a new head. Fails when the checks have
2273# not failed at the head the change is at.
2274approve_failed_at() {
2275 if [ -z "$CHECKS_FAILED_AT" ] || [ "$CHECKS_FAILED_AT" != "$(change_head "$1")" ]; then
2276 return 1
2277 fi
2278 git rev-parse --short "$CHECKS_FAILED_AT"
2279}
2280
2281# not_ready <handle> <version> <state> <owner>: the line review shows for a
2282# change whose record is not ready, above its diff and in its prompt.
2283# Prints nothing, and fails, for a ready change, and for a plain branch,
2284# which has no record. A draft is often a change an agent is still working
2285# on, so the prompt then offers only [v]iew full diff and [s]kip.
2286# [a]pprove would be refused. [b]ase is not offered either: rebase refuses
2287# such a change, since adding its rebased head as a version would ready it
2288# behind its owner's back. Nor is [r]eject, which records nothing on the
2289# change: it deletes the branch its owner may still be working on, and the
2290# record says what it said before. approve still reads the record again
2291# when it acts, since the state can change while the review is open.
2292not_ready() {
2293 case "$3" in
2294 draft) printf "%s v%s is a draft: its owner (%s) hasn't marked it ready, so it can't be approved yet." "$1" "$2" "$4" ;;
2295 withdrawn) printf '%s is withdrawn: there is nothing to approve.' "$1" ;;
2296 *) return 1 ;;
2297 esac
2298}
2299
2300# shown_not_ready: not_ready for the change review is showing.
2301shown_not_ready() {
2302 not_ready "$CHANGE_HANDLE" "$CHANGE_VERSION" "$CHANGE_STATE" "$CHANGE_OWNER"
2303}
2304
2305# Show the branch and take the verdict. Split out of cmd_review so that
2306# every way out of it — approve, reject, skip — is followed by the notes.
2307# A change that is not ready is asked as decide asks it: it can be neither
2308# approved nor rebased, so whether it fast-forwards from main changes
2309# nothing.
2310read_and_decide() {
2311 local branch="$1" choice failed answers
2312 show_review "$branch"
2313 # A stale branch's pre-rebase diff is not what would land; offer to rebase it
2314 # mechanically, then re-review what actually would. [a]pprove is offered
2315 # here as well, because the integrator applies a delta to the tip rather
2316 # than fast-forwarding: a stale branch is a request it can judge, and
2317 # rebasing first is a convenience rather than a precondition.
2318 while ! shown_not_ready > /dev/null \
2319 && ! git merge-base --is-ancestor refs/remotes/origin/main "$(change_head "$branch")"; do
2320 if failed="$(approve_failed_at "$branch")"; then
2321 printf '%s does not fast-forward from main. Its checks failed at %s, so approving needs a new head: [v]iew full diff, [b]ase onto main, [r]eject, [s]kip? ' \
2322 "$branch" "$failed"
2323 answers="v, b, r, or s"
2324 else
2325 printf '%s does not fast-forward from main: [a]pprove, [v]iew full diff, [b]ase onto main, [r]eject, [s]kip? ' \
2326 "$branch"
2327 answers="a, v, b, r, or s"
2328 fi
2329 read -r choice || die "stdin closed before an answer; nothing done"
2330 case "$choice" in
2331 a)
2332 if [ -n "$failed" ]; then
2333 echo "answer $answers"
2334 elif approve "$branch"; then
2335 return
2336 fi
2337 ;;
2338 v) view_full "$branch" ;;
2339 b)
2340 # A change with a record gains the rebased head as a new version,
2341 # so the review goes on at that version, as it does at the rebased
2342 # tip of a plain branch. A refused rebase has said why, and the
2343 # prompt comes back.
2344 if rebase_shown "$(change_head "$branch")"; then
2345 if [ -n "$CHANGE_ID" ]; then
2346 resolve_change "$CHANGE_ID" || die "could not read change $CHANGE_HANDLE again after the rebase"
2347 bind_review
2348 fi
2349 fetch_origin
2350 show_review "$branch"
2351 fi
2352 ;;
2353 r) reject "$branch" && return ;;
2354 s)
2355 echo "skipped $branch; nothing done"
2356 return
2357 ;;
2358 *) echo "answer $answers" ;;
2359 esac
2360 done
2361 decide "$branch"
2362}
2363
2364# decide <branch> [<name> <n>]: the verdict on a change that fast-forwards
2365# from main, and on the top of a stack, which is never offered [b]ase. A
2366# change alone is asked about by its branch. The top of a stack of <n> is
2367# asked about by its <name>, as the stack lists it, and its prompt says
2368# that approving it lands all <n> layers. [v]iew full diff pages the
2369# change's whole diff, or the top layer's.
2370#
2371# A change that is not ready is asked about by the line not_ready gives,
2372# in place of the label, and is offered only [v]iew full diff and
2373# [s]kip, or [s]top. The top of a stack with a layer under it that is not
2374# ready says why it can't be approved (layer_held), and is offered the
2375# rest.
2376decide() {
2377 local branch="$1" name="${2:-}" n="${3:-}" choice failed answers own held=""
2378 local label="$1" approve="[a]pprove" reject="[r]eject" stop="[s]kip"
2379 local stopped="skipped $1; nothing done"
2380 own="$(shown_not_ready)" || own=""
2381 if [ -n "$n" ]; then
2382 label="$name, $n of $n" approve="[a]pprove all $n" reject="[r]eject $name" stop="[s]top"
2383 stopped="stopped reviewing $name at change $n of $n; nothing done"
2384 held="$(layer_held $((n - 1)))" || held=""
2385 fi
2386 while true; do
2387 failed=""
2388 if [ -n "$own" ]; then
2389 if [ -n "$n" ]; then
2390 printf '%s: %s [v]iew full diff, %s? ' "$label" "$own" "$stop"
2391 else
2392 printf '%s [v]iew full diff, %s? ' "$own" "$stop"
2393 fi
2394 answers="v or s"
2395 elif [ -n "$held" ]; then
2396 printf '%s: %s [v]iew full diff, %s, %s? ' "$label" "$held" "$reject" "$stop"
2397 answers="v, r, or s"
2398 elif failed="$(approve_failed_at "$branch")"; then
2399 printf '%s: its checks failed at %s, so approving needs a new head: [v]iew full diff, %s, %s? ' \
2400 "$label" "$failed" "$reject" "$stop"
2401 answers="v, r, or s"
2402 else
2403 printf '%s: %s, [v]iew full diff, %s, %s? ' "$label" "$approve" "$reject" "$stop"
2404 answers="a, v, r, or s"
2405 fi
2406 read -r choice || die "stdin closed before an answer; nothing done"
2407 case "$choice" in
2408 # A refusal from approve is not a verdict: it says what it did not do
2409 # and the prompt comes back, so the branch can still be rejected or
2410 # skipped. When the checks failed, approving the same head again is
2411 # no longer offered, nor is approving a change that is not ready.
2412 a)
2413 if [ -n "$failed" ] || [ -n "$own" ] || [ -n "$held" ]; then
2414 echo "answer $answers"
2415 elif approve "$branch"; then
2416 return
2417 fi
2418 ;;
2419 v)
2420 if [ -n "$n" ]; then
2421 view_layer $((n - 1))
2422 else
2423 view_full "$branch"
2424 fi
2425 ;;
2426 r)
2427 if [ -n "$own" ]; then
2428 echo "answer $answers"
2429 else
2430 reject "$branch" && return
2431 fi
2432 ;;
2433 s)
2434 echo "$stopped"
2435 return
2436 ;;
2437 *) echo "answer $answers" ;;
2438 esac
2439 done
2440}
2441
2442# ----------------------------------------------------------------------
2443# A stack — a change with layers under it that have not landed — is
2444# reviewed one layer at a time, bottom first, each against the layer below
2445# it, the way it was built. Approving the top lands every layer under it,
2446# so reading the top against main alone would ask the operator to judge
2447# the whole stack as one diff.
2448#
2449# The layers are valley-go stack's (status/stack.go): one line each, bottom
2450# first, the change itself last, read here into one array per field.
2451# L_BRANCH is the branch a layer's notes are kept under: a branch's own
2452# name, or the branch a change's active version names. L_OWNER is a
2453# change's owner, as its record names it. L_NOTES holds the notes taken on
2454# each layer, for the print after the verdict.
2455L_KIND=() L_NAME=() L_BASE=() L_HEAD=() L_STATE=() L_TITLE=()
2456L_ID=() L_VERSION=() L_BRANCH=() L_OWNER=() L_NOTES=()
2457# The name review was given, which the top is read again by.
2458TOP_NAME=""
2459
2460# read_stack: read the stack under the change review resolved. Each change
2461# under the top is read again with resolve, for its ID, version, branch
2462# and owner, and must still be at the head the stack names. The top must be
2463# what review resolved. Fails, having said why, when either does not hold
2464# or the helper cannot read the stack. Called in a condition, so each step
2465# is checked by hand.
2466read_stack() {
2467 local out line kind name base head state title k last
2468 local rkind id handle version rhead branch rstate owner
2469 L_KIND=() L_NAME=() L_BASE=() L_HEAD=() L_STATE=() L_TITLE=()
2470 L_ID=() L_VERSION=() L_BRANCH=() L_OWNER=() L_NOTES=()
2471 out="$(valley-go stack "${CHANGE_ID:-origin/$CHANGE_BRANCH}")" || return 1
2472 while IFS= read -r line; do
2473 read_resolved "$line" kind name base head state title
2474 if ! [[ "$kind" =~ ^(change|branch)$ && "$base" =~ ^[0-9a-f]{40}$ && "$head" =~ ^[0-9a-f]{40}$ ]]; then
2475 refuse "valley-go stack answered $line, which this script does not read"
2476 return 1
2477 fi
2478 L_KIND+=("$kind") L_NAME+=("$name") L_BASE+=("$base") L_HEAD+=("$head")
2479 L_STATE+=("$state") L_TITLE+=("$title") L_NOTES+=("")
2480 L_ID+=("") L_VERSION+=("") L_BRANCH+=("$name") L_OWNER+=("")
2481 done <<< "$out"
2482 last=$((${#L_NAME[@]} - 1))
2483 if [ "${L_HEAD[last]}" != "$(change_head "$CHANGE_BRANCH")" ] \
2484 || [ "${L_KIND[last]}" != "$([ -n "$CHANGE_ID" ] && echo change || echo branch)" ]; then
2485 refuse "$TOP_NAME moved while its stack was read"
2486 return 1
2487 fi
2488 L_ID[last]="$CHANGE_ID" L_VERSION[last]="$CHANGE_VERSION" L_BRANCH[last]="$CHANGE_BRANCH"
2489 L_OWNER[last]="$CHANGE_OWNER"
2490 for ((k = 0; k < last; k++)); do
2491 [ "${L_KIND[k]}" = change ] || continue
2492 line="$(valley-go resolve "${L_NAME[k]}")" || return 1
2493 read_resolved "$line" rkind id handle version rhead branch rstate owner
2494 if [ "$rkind" != change ] || [ "$rhead" != "${L_HEAD[k]}" ]; then
2495 refuse "change ${L_NAME[k]}, under $TOP_NAME, moved while the stack was read"
2496 return 1
2497 fi
2498 L_ID[k]="$id" L_VERSION[k]="$version" L_BRANCH[k]="$branch" L_STATE[k]="$rstate"
2499 L_OWNER[k]="$owner"
2500 done
2501}
2502
2503# use_layer <k>: act on layer k as review acts on a change it was given,
2504# binding [a]pprove to the head the stack shows. A branch under the top is
2505# read again as origin/<branch>, which no handle can shadow.
2506use_layer() {
2507 local k="$1"
2508 CHANGE_ID="${L_ID[k]}" CHANGE_VERSION="${L_VERSION[k]}" CHANGE_BRANCH="${L_BRANCH[k]}"
2509 CHANGE_STATE="${L_STATE[k]}" CHANGE_OWNER="${L_OWNER[k]}" CHANGE_HANDLE="" CHANGE_HEAD=""
2510 CHANGE_NAME="origin/${L_NAME[k]}"
2511 [ "$k" -lt $((${#L_NAME[@]} - 1)) ] || CHANGE_NAME="$TOP_NAME"
2512 if [ -n "$CHANGE_ID" ]; then
2513 CHANGE_NAME="${L_NAME[k]}" CHANGE_HANDLE="${L_NAME[k]}" CHANGE_HEAD="${L_HEAD[k]}"
2514 fi
2515 bind_review
2516 [ -n "$CHANGE_ID" ] || APPROVE_HEAD="${L_HEAD[k]}"
2517}
2518
2519# notes_key <k>: the branch layer k's notes are kept under. A change whose
2520# active version names no branch keeps them under its handle.
2521notes_key() {
2522 printf '%s' "${L_BRANCH[$1]:-${L_NAME[$1]}}"
2523}
2524
2525# layer_label <k>: how a layer is named in the list: its name, then
2526# branch, or the change's state.
2527layer_label() {
2528 local k="$1"
2529 if [ "${L_KIND[k]}" = branch ]; then
2530 printf '%s (branch)' "${L_NAME[k]}"
2531 else
2532 printf '%s (%s)' "${L_NAME[k]}" "${L_STATE[k]}"
2533 fi
2534}
2535
2536# What is coming: the layers bottom first, the lower layers the integrator
2537# would refuse, and what each answer lands.
2538summarize_stack() {
2539 local n="${#L_NAME[@]}" k
2540 printf '%s is a stack of %d changes; reviewing from the bottom, each against the one below it:\n' \
2541 "${L_NAME[n - 1]}" "$n"
2542 for ((k = 0; k < n; k++)); do
2543 printf ' %d. %s: %s\n' "$((k + 1))" "$(layer_label "$k")" "${L_TITLE[k]}"
2544 done
2545 for ((k = 0; k < n - 1; k++)); do
2546 case "${L_STATE[k]}" in
2547 draft | withdrawn)
2548 printf 'warning: %s, change %d of %d, is %s. The integrator refuses to land it or anything above it (refused-not-ready).\n' \
2549 "${L_NAME[k]}" "$((k + 1))" "$n" "$([ "${L_STATE[k]}" = draft ] && echo 'a draft' || echo withdrawn)"
2550 ;;
2551 esac
2552 done
2553 printf 'read each layer and go on with [n]; approving %s at the top lands all %d. [a] on a lower layer lands it and the layers under it, and ends the review.\n' \
2554 "${L_NAME[n - 1]}" "$n"
2555}
2556
2557# base_stack: before any layer is paged, a stack whose bottom does not
2558# fast-forward from main is offered [b]ase, which rebases every layer as
2559# the rebase verb does (status/rebase.go), or [s]top. After a rebase the
2560# stack is read again and listed again, so the heads paged are the heads
2561# approved. A rebase refused or left unfinished has said what happened,
2562# and only [s]top is offered then. Fails when the review stops here.
2563base_stack() {
2564 local n choice offered="[b]ase" stopped="; nothing done"
2565 while ! git merge-base --is-ancestor refs/remotes/origin/main "${L_HEAD[0]}"; do
2566 n="${#L_NAME[@]}"
2567 if [ -n "$offered" ]; then
2568 printf '%s, at the bottom, does not fast-forward from main: [b]ase all %d onto main, [s]top? ' \
2569 "${L_NAME[0]}" "$n"
2570 else
2571 printf 'the stack under %s is not rebased: [s]top? ' "${L_NAME[n - 1]}"
2572 fi
2573 read -r choice || die "stdin closed before an answer; nothing done"
2574 case "$choice" in
2575 b)
2576 if [ -z "$offered" ]; then
2577 echo "answer s"
2578 elif rebase_shown "${L_HEAD[n - 1]}"; then
2579 fetch_origin
2580 if [ -n "$CHANGE_ID" ]; then
2581 resolve_change "$CHANGE_ID" || die "could not read change $CHANGE_HANDLE again after the rebase"
2582 fi
2583 bind_review
2584 read_stack || die "could not read the stack under $TOP_NAME again after the rebase"
2585 summarize_stack
2586 else
2587 offered="" stopped=""
2588 fi
2589 ;;
2590 s)
2591 echo "stopped reviewing ${L_NAME[n - 1]} before its first layer$stopped"
2592 return 1
2593 ;;
2594 *) echo "answer ${offered:+b or }s" ;;
2595 esac
2596 done
2597}
2598
2599# layer_heading <k>: the line that heads layer k wherever it is shown.
2600layer_heading() {
2601 local k="$1" below=main
2602 [ "$k" -eq 0 ] || below="${L_NAME[k - 1]}"
2603 printf 'change %d of %d: %s on %s' "$((k + 1))" "${#L_NAME[@]}" "${L_NAME[k]}" "$below"
2604}
2605
2606# layer_held <k>: why layer k can't be approved, when it or a layer under
2607# it is not ready. A layer that is not ready says so as a change alone
2608# does (not_ready). A layer above one says which: approving it would land
2609# that layer too, and the integrator lands nothing that would bring a
2610# version of a change that is not ready. Prints nothing, and fails, when
2611# every layer up to k is ready or a plain branch.
2612layer_held() {
2613 local k="$1" j
2614 not_ready "${L_NAME[k]}" "${L_VERSION[k]}" "${L_STATE[k]}" "${L_OWNER[k]}" && return
2615 for ((j = k - 1; j >= 0; j--)); do
2616 case "${L_STATE[j]}" in
2617 draft | withdrawn)
2618 printf "it would bring %s, change %d of %d, which is %s, so it can't be approved yet." \
2619 "${L_NAME[j]}" "$((j + 1))" "${#L_NAME[@]}" "$([ "${L_STATE[j]}" = draft ] && echo 'a draft' || echo withdrawn)"
2620 return
2621 ;;
2622 esac
2623 done
2624 return 1
2625}
2626
2627# page_layer <k>: show layer k, as show_review shows a change alone. The
2628# layer shown is compared with its own change's approved version, so a
2629# lower layer is set against its own approval, not the top's. Its whole
2630# diff is against the layer below it. The notes taken in it are kept
2631# under its own branch. When it can't be approved, layer_held's line
2632# follows its heading, before the layer's knots.
2633page_layer() {
2634 local k="$1" heading held
2635 NOTES=()
2636 heading="$(layer_heading "$k")"
2637 if held="$(layer_held "$k")"; then heading+=$'\n'"$held"; fi
2638 REVIEW_TMP="$(mktemp -d)"
2639 compare_shown "${L_ID[k]}" "${L_VERSION[k]}" "${L_HEAD[k]}"
2640 show_compared "$(notes_key "$k")" "${L_HEAD[k]}" "$heading" "$(does_of "${L_ID[k]}")" layer_diff "$k"
2641 keep_layer_notes "$k"
2642}
2643
2644# view_layer <k>: [v]iew full diff for layer k: its whole diff against
2645# the layer below it.
2646view_layer() {
2647 local k="$1"
2648 NOTES=()
2649 REVIEW_TMP="$(mktemp -d)"
2650 {
2651 layer_heading "$k"
2652 printf '\n'
2653 layer_diff "$k"
2654 } > "$REVIEW_TMP/review.diff"
2655 page_buffer "$(notes_key "$k")" "$(git rev-parse --short "${L_HEAD[k]}")"
2656 keep_layer_notes "$k"
2657}
2658
2659# keep_layer_notes <k>: add the notes just taken to layer k's.
2660keep_layer_notes() {
2661 [ "${#NOTES[@]}" -gt 0 ] || return 0
2662 L_NOTES[$1]="${L_NOTES[$1]:+${L_NOTES[$1]}$'\n'}$(printf '%s\n' "${NOTES[@]}")"
2663}
2664
2665# layer_diff <k>: layer k's whole diff: its log and its diff against the
2666# layer below it.
2667layer_diff() {
2668 local k="$1" below=main head base sha on
2669 [ "$k" -eq 0 ] || below="${L_NAME[k - 1]}"
2670 head="${L_HEAD[k]}" base="${L_BASE[k]}"
2671 sha="$(git rev-parse --short "$head")"
2672 on="$below at $(git rev-parse --short "$base")"
2673 if [ "${L_KIND[k]}" = branch ]; then
2674 printf 'branch %s, log against %s:\n\n' "${L_NAME[k]}" "$on"
2675 elif [ -n "${L_BRANCH[k]}" ]; then
2676 printf 'change %s v%s at %s, on branch %s, log against %s:\n\n' \
2677 "${L_NAME[k]}" "${L_VERSION[k]}" "$sha" "${L_BRANCH[k]}" "$on"
2678 else
2679 printf 'change %s v%s at %s, log against %s:\n\n' "${L_NAME[k]}" "${L_VERSION[k]}" "$sha" "$on"
2680 fi
2681 git --no-pager log --oneline "$base..$head"
2682 printf '\n'
2683 git --no-pager diff "$base...$head"
2684}
2685
2686# Show each layer under the top and ask after each, naming the layer and
2687# its place: [n]ext layer goes on to the layer above, [a]pprove approves
2688# that layer at the head shown, which lands it and every layer under it,
2689# as the prompt names them, [v]iew full diff pages the layer's whole diff,
2690# and [s]top ends the review. [r]eject is not offered under the top:
2691# deleting a lower layer's branch would leave the layers above still
2692# holding it. [a]pprove is not offered at or above a layer that is not
2693# ready, and the prompt says why in its place (layer_held). After the
2694# top, its verdict is taken as for any change, with a prompt that names
2695# the top and says approving it lands all n.
2696review_stack() {
2697 local n top k choice answers failed lands held
2698 summarize_stack
2699 base_stack || return 0
2700 printf '\n'
2701 n="${#L_NAME[@]}" top=$((${#L_NAME[@]} - 1))
2702 for ((k = 0; k < top; k++)); do
2703 page_layer "$k"
2704 case "$k" in
2705 0) lands="${L_NAME[0]} alone" ;;
2706 1) lands="${L_NAME[0]} and ${L_NAME[1]}" ;;
2707 *) lands="the $((k + 1)) up to ${L_NAME[k]}" ;;
2708 esac
2709 held="$(layer_held "$k")" || held=""
2710 while true; do
2711 failed=""
2712 [ "$CHECKS_FAILED_AT" != "${L_HEAD[k]}" ] || failed="$(git rev-parse --short "${L_HEAD[k]}")"
2713 if [ -n "$held" ]; then
2714 printf '%s, %d of %d: %s [n]ext layer, [v]iew full diff, [s]top? ' \
2715 "${L_NAME[k]}" "$((k + 1))" "$n" "$held"
2716 answers="n, v, or s"
2717 elif [ -n "$failed" ]; then
2718 printf '%s, %d of %d: its checks failed at %s, so approving needs a new head: [n]ext layer, [v]iew full diff, [s]top? ' \
2719 "${L_NAME[k]}" "$((k + 1))" "$n" "$failed"
2720 answers="n, v, or s"
2721 else
2722 printf '%s, %d of %d: [n]ext layer, [a]pprove %s, [v]iew full diff, [s]top? ' \
2723 "${L_NAME[k]}" "$((k + 1))" "$n" "$lands"
2724 answers="n, a, v, or s"
2725 fi
2726 read -r choice || die "stdin closed before an answer; nothing done"
2727 case "$choice" in
2728 n) break ;;
2729 a)
2730 if [ -n "$failed" ] || [ -n "$held" ]; then
2731 echo "answer $answers"
2732 continue
2733 fi
2734 use_layer "$k"
2735 if approve "$CHANGE_BRANCH"; then
2736 return
2737 fi
2738 use_layer "$top"
2739 ;;
2740 v) view_layer "$k" ;;
2741 s)
2742 echo "stopped reviewing ${L_NAME[top]} at change $((k + 1)) of $n, ${L_NAME[k]}; nothing done"
2743 return
2744 ;;
2745 *) echo "answer $answers" ;;
2746 esac
2747 done
2748 done
2749 page_layer "$top"
2750 use_layer "$top"
2751 decide "${L_BRANCH[top]}" "${L_NAME[top]}" "$n"
2752}
2753
2754# The notes taken on every layer, each under its own branch.
2755print_stack_notes() {
2756 local k
2757 for ((k = 0; k < ${#L_NAME[@]}; k++)); do
2758 [ -n "${L_NOTES[k]}" ] || continue
2759 mapfile -t NOTES <<< "${L_NOTES[k]}"
2760 print_notes "$(notes_key "$k")"
2761 done
2762}
2763
2764cmd_review() {
2765 local name="" verbose=() arg
2766 for arg in "$@"; do
2767 case "$arg" in
2768 -v) verbose=(-v) ;;
2769 -*) die "usage: valley review [-v] <change>" ;;
2770 *)
2771 [ -z "$name" ] || die "usage: valley review [-v] <change>"
2772 name="$arg"
2773 ;;
2774 esac
2775 done
2776 [ -n "$name" ] || die "usage: valley review [-v] <change>"
2777 set -- "$name"
2778 resolve_change "$1" || exit 1
2779 need_branch review
2780 local branch="$CHANGE_BRANCH"
2781 TOP_NAME="$1"
2782 fetch_origin
2783 git rev-parse --verify --quiet "refs/remotes/origin/$branch" >/dev/null \
2784 || die "no such branch on origin: $branch"
2785 bind_review
2786 trap cleanup_scratch EXIT
2787 trap 'exit 130' INT TERM
2788 # The verdict disposes of the change; the notes are what the human made
2789 # of it, so they are printed whatever the verdict was. A stack that
2790 # cannot be read is reviewed whole against main, as a change with
2791 # nothing under it is.
2792 if ! read_stack; then
2793 printf 'valley: warning: the stack under %s could not be read; reviewing it whole, against main\n' "$1" >&2
2794 L_NAME=()
2795 fi
2796 read_does "${verbose[@]}"
2797 if [ "${#L_NAME[@]}" -gt 1 ]; then
2798 review_stack
2799 print_stack_notes
2800 else
2801 read_and_decide "$branch"
2802 print_notes "$branch"
2803 fi
2804}
2805
2806# approve and rebase are review's [a]pprove and [b]ase without the pager,
2807# for a front end that has shown the change its own way. Each runs the
2808# code its key runs, approve and valley-go rebase, so the verb and the key
2809# cannot drift apart. A change is named as resolve_change reads it, and
2810# rebase reads its name the same way, in valley-go.
2811#
2812# approve of a change with a record approves exactly one head (bind_head):
2813# --head's, or the active version's once the operator confirms it on a
2814# terminal. A plain branch is approved at its tip on origin, as the fetch
2815# left it, and --head, when given, must be that tip.
2816cmd_approve() {
2817 local name="" want=""
2818 local usage="usage: valley approve [--head <sha>] <change>"
2819 while [ $# -gt 0 ]; do
2820 case "$1" in
2821 --head)
2822 [ $# -ge 2 ] || die "$usage"
2823 want="$2"
2824 shift 2
2825 ;;
2826 --head=*)
2827 want="${1#--head=}"
2828 shift
2829 ;;
2830 -*) die "$usage" ;;
2831 *)
2832 [ -z "$name" ] || die "$usage"
2833 name="$1"
2834 shift
2835 ;;
2836 esac
2837 done
2838 [ -n "$name" ] || die "$usage"
2839 resolve_change "$name" || exit 1
2840 local branch="$CHANGE_BRANCH" tip
2841 fetch_origin
2842 trap cleanup_scratch EXIT
2843 trap 'exit 130' INT TERM
2844 if [ -n "$CHANGE_ID" ]; then
2845 bind_head "$want" || exit 1
2846 else
2847 tip="$(git rev-parse --verify --quiet "refs/remotes/origin/$branch")" \
2848 || die "no such branch on origin: $branch"
2849 if [ -n "$want" ] && [ "$(git rev-parse --verify --quiet "$want^{commit}" || true)" != "$tip" ]; then
2850 die "origin/$branch is at $tip, not $want; nothing published"
2851 fi
2852 fi
2853 # In a condition, as the review prompt calls it: approve checks each of
2854 # its own steps, and has already said why when it refuses.
2855 approve "$branch" || exit 1
2856}
2857
2858# The two flags that say what a transfer statement is verified with are
2859# valley-go's, and pass through to it untouched.
2860cmd_rebase() {
2861 local usage="usage: valley rebase [--known-signers <file>] [--integrator-name <name>] <change>"
2862 local name="" verify=()
2863 while [ $# -gt 0 ]; do
2864 case "$1" in
2865 --known-signers | --integrator-name)
2866 [ $# -ge 2 ] || die "$usage"
2867 verify+=("$1" "$2")
2868 shift 2
2869 ;;
2870 --known-signers=* | --integrator-name=*)
2871 verify+=("$1")
2872 shift
2873 ;;
2874 -*) die "$usage" ;;
2875 *)
2876 [ -z "$name" ] || die "$usage"
2877 name="$1"
2878 shift
2879 ;;
2880 esac
2881 done
2882 [ -n "$name" ] || die "$usage"
2883 command -v valley-go > /dev/null 2>&1 \
2884 || die "review, approve and rebase read the change's record with the valley-go helper; nix run .#valley bundles it"
2885 fetch_origin
2886 exec valley-go rebase "${verify[@]}" "$name"
2887}
2888
2889# tail and replay are thin wrappers over the nats CLI — anything they do,
2890# plain nats and git can do. They are the only verbs needing more than git
2891# and coreutils.
2892need_nats() {
2893 command -v nats >/dev/null 2>&1 \
2894 || die "this verb needs the nats CLI (natscli); nix run .#valley bundles it"
2895}
2896
2897cmd_tail() {
2898 [ $# -le 1 ] || die "usage: valley tail [subject]"
2899 need_nats
2900 exec nats sub "${1:-valley.>}"
2901}
2902
2903# One ref-updated event per existing ref, from git for-each-ref alone. A
2904# ref's prior value is not derivable from the repository, so `old` is the
2905# all-zero id — the same payload a push creating the ref would produce.
2906# The payload construction mirrors the host module's publisher hook
2907# (nix/valley-host.nix); change one only with the other.
2908cmd_replay() {
2909 [ $# -le 1 ] || die "usage: valley replay [repo-dir]"
2910 need_nats
2911 local dir="${1:-.}" repo sha ref event count=0
2912 git -C "$dir" rev-parse --git-dir >/dev/null 2>&1 \
2913 || die "not a git repository: $dir"
2914 if [ "$(git -C "$dir" rev-parse --is-bare-repository)" = true ]; then
2915 repo="$(basename "$(git -C "$dir" rev-parse --absolute-git-dir)" .git)"
2916 else
2917 repo="$(basename "$(git -C "$dir" rev-parse --show-toplevel)")"
2918 fi
2919 while read -r sha ref; do
2920 # " is the only JSON-significant character a refname can contain (git
2921 # forbids \ and control characters); names and object ids are safe.
2922 event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \
2923 "$repo" "${ref//\"/\\\"}" "${sha//?/0}" "$sha")"
2924 nats pub "valley.git.$repo.ref-updated" "$event" >/dev/null
2925 count=$((count + 1))
2926 done < <(git -C "$dir" for-each-ref --format='%(objectname) %(refname)')
2927 echo "replayed $count refs of $repo onto the bus"
2928}
2929
2930# ----------------------------------------------------------------------
2931# checks — the verification-policy deriver (dcr-f41f718). It composes the
2932# instance layer with the project layer, matches every side of a diff
2933# against the composed classes, and prints the check names the policy
2934# requires of the change, with the class or classes that made each one
2935# required. It reports: no check is run, nothing is gated, nothing is
2936# written.
2937#
2938# Composition is CUE's, never this script's. The whole of the mandatory-
2939# versus-overridable distinction is unification, so reimplementing it here
2940# would be reimplementing the decision. What this script does that CUE
2941# cannot is glob matching and reading a diff.
2942
2943need_cue() {
2944 command -v cue >/dev/null 2>&1 \
2945 || die "this verb needs the cue CLI; nix run .#valley bundles it"
2946}
2947
2948# One glob segment as an ERE fragment: `*` and `?` are wildcards that never
2949# cross a `/`, and every ERE metacharacter is escaped.
2950segment_ere() {
2951 local seg="$1" out="" i c
2952 for ((i = 0; i < ${#seg}; i++)); do
2953 c="${seg:i:1}"
2954 case "$c" in
2955 '*') out+='[^/]*' ;;
2956 '?') out+='[^/]' ;;
2957 '.' | '^' | '$' | '+' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | \\) out+="\\$c" ;;
2958 *) out+="$c" ;;
2959 esac
2960 done
2961 printf '%s' "$out"
2962}
2963
2964# A path glob as an anchored ERE, segment by segment. A `**` segment matches
2965# any number of segments including none, so it swallows the separator that
2966# would otherwise follow it and `a/**/b` matches `a/b`; every other segment
2967# matches exactly one.
2968glob_ere() {
2969 local ere='^' i last
2970 local -a segs=()
2971 IFS=/ read -r -a segs <<<"$1"
2972 last=$((${#segs[@]} - 1))
2973 for ((i = 0; i <= last; i++)); do
2974 if [ "${segs[i]}" = '**' ]; then
2975 if [ "$i" -eq "$last" ]; then ere+='.*'; else ere+='(.*/)?'; fi
2976 else
2977 ere+="$(segment_ere "${segs[i]}")"
2978 [ "$i" -eq "$last" ] || ere+='/'
2979 fi
2980 done
2981 printf '%s$' "$ere"
2982}
2983
2984# The composed policy as one tab-separated line per covered pattern, per
2985# required check, per class's carry mode, and per field of the check
2986# catalogue, so the shell never parses CUE. Every line is three fields — a
2987# kind, a name, and a value — whatever the kind, so one reader takes them
2988# all. The field is hidden because the schema's sentinel rejects unknown
2989# top-level fields, and `unclassified` is rendered as a class of that name:
2990# it is one more source a check can come from. A class's carry mode is the
2991# one the schema resolves (`_mode`), so the shell only picks the strictest.
2992#
2993# Each line is held to its shape (`line`): three fields, two tabs, and no
2994# other control character. A newline in a field would end its line and
2995# start one of the policy's choosing, and a tab would add a field. The
2996# schema already refuses control characters in every string rendered here,
2997# so this is a second wall: a line out of shape fails the render, and the
2998# deriver refuses a render that fails. The whole line is checked because a
2999# bound on a value inside an interpolation does not fail the string.
3000#
3001# The catalogue is rendered because a caller that runs a check needs what
3002# the policy says a check IS — its runner, and the attribute or command
3003# line that runner takes — and a tool that groups the required checks
3004# needs their cost. `checks` reads only the cost, to group the required
3005# checks by it; approve turns the rest into the arguments attest is given.
3006render_cue() {
3007 cat <<'EOF'
3008package verification
3009
3010import (
3011 "list"
3012 "strings"
3013)
3014
3015let line = =~"^[^\\x00-\\x1f\\x7f]+\t[^\\x00-\\x1f\\x7f]+\t[^\\x00-\\x1f\\x7f]+$"
3016
3017_render: strings.Join(list.Concat([[
3018 for cn, c in policy.classes
3019 for p, on in c.paths if on {"path\t\(cn)\t\(p)" & line}
3020], [
3021 for cn, c in policy.classes
3022 for k, on in c.requires if on {"requires\t\(cn)\t\(k)" & line}
3023], [
3024 for k, on in policy.unclassified if on {"requires\tunclassified\t\(k)" & line}
3025], [
3026 for cn, m in _mode {"carry\t\(cn)\t\(m)" & line}
3027], [
3028 for n, c in policy.checks {"runner\t\(n)\t\(c.runner)" & line}
3029], [
3030 for n, c in policy.checks if c.runner == "nix" {"attribute\t\(n)\t\(c.attribute)" & line}
3031], [
3032 for n, c in policy.checks if c.runner == "command" {"command\t\(n)\t\(c.command)" & line}
3033], [
3034 for n, c in policy.checks {"cost\t\(n)\t\(c.cost)" & line}
3035]]), "\n")
3036EOF
3037}
3038
3039# The composed layer, and a scratch directory for the documents the
3040# derivation writes into the composition. Globals so the probe below can
3041# see them.
3042POLICY_LAYER=()
3043POLICY_TMP=""
3044
3045cleanup_policy_tmp() {
3046 [ -n "$POLICY_TMP" ] || return 0
3047 rm -rf "$POLICY_TMP"
3048 POLICY_TMP=""
3049}
3050
3051# Where the schema and the two policy layers come from in a project
3052# following the convention (dcr-f41f718).
3053#
3054# The client derives from exactly the sources the integrator uses
3055# (integrator/policy.go), and the working tree is not among them. The
3056# project's own layer is read from the TARGET's tip, the pointer naming the
3057# owning valley is read from the target's tip, and the floor is read from
3058# that valley's integrated tip. A change never supplies the policy that
3059# gates it, and neither does whoever happens to be reviewing it: the
3060# reviewer's checkout may be any branch, however stale, and derivation
3061# gives the same answer from all of them.
3062#
3063# The schema is not a policy layer. It is the shape a policy is written in,
3064# and it ships with this tool: the package sets VALLEY_VERIFICATION_SCHEMA
3065# to the copy it was built with, as the integrator's package does. Only
3066# the-valley's own tree carries schema/, so this script reads the schema
3067# there only when it runs straight from such a checkout with the variable
3068# unset.
3069#
3070# Neither layer is ever the worked example under examples/policy/ — a gate
3071# derived from an example is a gate nobody wrote. `checks` takes an option
3072# for each, so a reader can point it at the example or anywhere else on
3073# purpose; approve takes no such option, because a request is filed
3074# against the policy that governs the project and nowhere else.
3075#
3076# Neither layer is a path in this tree, so policy_defaults leaves both
3077# empty and the two resolvers answer for them. That split is also what
3078# keeps `checks --instance DIR` from fetching a repository whose layer it
3079# was told to ignore, and `checks --project DIR` from reading a tip whose
3080# layer it was told to ignore.
3081POLICY_SCHEMA=""
3082POLICY_INSTANCE=""
3083POLICY_INSTANCE_LABEL=""
3084POLICY_PROJECT=""
3085POLICY_PROJECT_LABEL=""
3086policy_defaults() {
3087 POLICY_SCHEMA="${VALLEY_VERIFICATION_SCHEMA:-$1/schema/verification.cue}"
3088 POLICY_INSTANCE=""
3089 POLICY_INSTANCE_LABEL=""
3090 POLICY_PROJECT=""
3091 POLICY_PROJECT_LABEL=""
3092}
3093
3094# The floor, copied out of a fetch of the owning valley's repository, and
3095# the project's own layer, copied out of the target's tip. Globals, so the
3096# traps clean them up whatever happens.
3097INSTANCE_TMP=""
3098cleanup_instance_tmp() {
3099 [ -n "$INSTANCE_TMP" ] || return 0
3100 rm -rf "$INSTANCE_TMP"
3101 INSTANCE_TMP=""
3102}
3103
3104PROJECT_TMP=""
3105cleanup_project_tmp() {
3106 [ -n "$PROJECT_TMP" ] || return 0
3107 rm -rf "$PROJECT_TMP"
3108 PROJECT_TMP=""
3109}
3110
3111# The directory each layer lives in, the file naming this project's owning
3112# valley, and the ref of that valley whose tip carries the floor. The floor
3113# resolves at the integrated tip, because a floor a project could pin is
3114# not a floor (dcr-f41f718).
3115INSTANCE_DIR=policy/instance
3116PROJECT_DIR=policy/project
3117VALLEY_POINTER=policy/valley
3118VALLEY_POINTER_REF=refs/heads/main
3119
3120# The *.cue documents of one directory at one tree-ish, copied out of a
3121# repository into a directory on disk. Reading a tip with ls-tree and
3122# cat-file rather than checking it out is what lets the layers come from
3123# the target while the checkout stays on whatever branch the reviewer is
3124# on. 0 copied something, 1 the directory holds no *.cue, 2 the read
3125# failed.
3126#
3127# -z because a path may hold anything but NUL, and *.cue because the layer
3128# is the directory's documents — the same reading the composer takes.
3129#
3130# The listing is written out and its status checked before it is read. A
3131# listing read straight from a process substitution that failed reads as a
3132# directory holding nothing, and for the project layer that is the floor
3133# alone: fewer checks required, from a read that never happened. The listing's
3134# name is not a *.cue name, so the composer never reads it.
3135copy_layer() {
3136 local gitdir="$1" treeish="$2" dir="$3" dest="$4" path name copied=0
3137 local listing="$dest/.listing"
3138 git -C "$gitdir" ls-tree --name-only -z "$treeish" "$dir/" > "$listing" \
3139 || return 2
3140 while IFS= read -r -d '' path; do
3141 case "$path" in *.cue) ;; *) continue ;; esac
3142 name="${path##*/}"
3143 git -C "$gitdir" cat-file blob "$treeish:$path" > "$dest/$name" || return 2
3144 copied=1
3145 done < "$listing"
3146 rm -f "$listing"
3147 [ "$copied" -eq 1 ]
3148}
3149
3150# The ref whose tip supplies the policy, printed the way a person names it,
3151# with the commit it stood at. Staleness in a remote-tracking ref is a real
3152# thing to see, so the report says which commit the layers came out of
3153# rather than only which ref. A ref that cannot be read fails, so that no
3154# report names a tip nobody read.
3155target_label() {
3156 local ref="$1" short
3157 short="$(git rev-parse --short "$ref")" || return 1
3158 ref="${ref#refs/remotes/}"
3159 ref="${ref#refs/heads/}"
3160 printf '%s %s' "$ref" "$short"
3161}
3162
3163# Resolve the project's own layer, out of the target's tip, into
3164# POLICY_PROJECT, and set POLICY_PROJECT_LABEL to where it came from.
3165#
3166# A target carrying no layer of its own is derived under the floor alone.
3167# The project layer only ever adds (dcr-f41f718), so the identity of "adds"
3168# is "adds nothing"; refusing instead would make a repository underivable
3169# until its first policy commit, and that commit could not derive either.
3170# This is the integrator's own reading (integrator/policy.go), and the two
3171# have to agree about an absent layer as much as about a present one.
3172#
3173# Absence is answered with a document that adds nothing rather than with an
3174# argument left off, because the composer is handed a directory of *.cue
3175# and has no spelling for "no layer".
3176#
3177# It reports and returns rather than dying, for the reason derive_required
3178# does: a refusal inside the review loop is not the end of the session.
3179resolve_project_layer() {
3180 local root="$1" target="$2" rc at
3181
3182 at="$(target_label "$target")" || {
3183 refuse "could not read $target; nothing derived"
3184 return 1
3185 }
3186 cleanup_project_tmp
3187 PROJECT_TMP="$(mktemp -d)" || {
3188 refuse "no scratch directory to read the project layer into; nothing derived"
3189 return 1
3190 }
3191 copy_layer "$root" "$target" "$PROJECT_DIR" "$PROJECT_TMP" && rc=0 || rc=$?
3192 case "$rc" in
3193 0)
3194 POLICY_PROJECT="$PROJECT_TMP"
3195 POLICY_PROJECT_LABEL="$PROJECT_DIR@$at"
3196 ;;
3197 1)
3198 printf 'package verification\n' > "$PROJECT_TMP/adds-nothing.cue" || {
3199 cleanup_project_tmp
3200 refuse "could not compose an empty project layer; nothing derived"
3201 return 1
3202 }
3203 POLICY_PROJECT="$PROJECT_TMP"
3204 POLICY_PROJECT_LABEL="no $PROJECT_DIR@$at — the floor alone"
3205 ;;
3206 *)
3207 cleanup_project_tmp
3208 refuse "could not read $PROJECT_DIR/ at $at; nothing derived"
3209 return 1
3210 ;;
3211 esac
3212}
3213
3214# The first line of the pointer that is neither blank nor a comment. Read
3215# in the shell so that naming an owning valley needs nothing beyond what
3216# the rest of this script needs.
3217pointer_url() {
3218 local line url=""
3219 while IFS= read -r line || [ -n "$line" ]; do
3220 line="${line%%#*}"
3221 line="${line#"${line%%[![:space:]]*}"}"
3222 line="${line%"${line##*[![:space:]]}"}"
3223 [ -n "$line" ] || continue
3224 url="$line"
3225 break
3226 done < "$1"
3227 printf '%s' "$url"
3228}
3229
3230# Resolve the floor to a directory on disk, into POLICY_INSTANCE, and set
3231# POLICY_INSTANCE_LABEL to where it came from — a temporary directory is
3232# not an answer a reader can check.
3233#
3234# Every project has exactly one owning valley, and the floor is that
3235# valley's (dcr-9b5da04). It is read from the valley's own repository and
3236# never from the project's tree, which is the tree under judgment. Two
3237# shapes, and the first is a special case of the second:
3238#
3239# - a valley's config repository carries policy/instance itself, and is
3240# governed by that floor like every other project. It uses its own,
3241# and fetches nothing.
3242# - every other project names its owning valley at policy/valley. That
3243# repository is fetched into scratch and its policy/instance is read
3244# at the integrated tip. Fetching is all this needs, and anyone the
3245# valley governs necessarily holds fetch on it.
3246#
3247# Both the pointer and a valley's own floor are read from the TARGET's tip
3248# and never from the working tree. The pointer is a file a branch can edit,
3249# so reading it from the branch would let a change name the valley that
3250# gates it; reading it from the checkout would let whoever is reviewing
3251# decide the same thing by accident, which is the failure this fixes. An
3252# absent floor is refused — that is the direction absence defaults in for
3253# this layer, because the floor is the minimum (dcr-f41f718).
3254#
3255# It reports and returns rather than dying, for the reason derive_required
3256# does: a refusal inside the review loop is not the end of the session.
3257resolve_instance_layer() {
3258 local root="$1" target="$2" url bare dest rc at
3259 at="$(target_label "$target")" || {
3260 refuse "could not read $target; nothing derived"
3261 return 1
3262 }
3263 cleanup_instance_tmp
3264 INSTANCE_TMP="$(mktemp -d)" || {
3265 refuse "no scratch directory to read the floor into; nothing derived"
3266 return 1
3267 }
3268 dest="$INSTANCE_TMP/instance"
3269 mkdir -p "$dest"
3270
3271 copy_layer "$root" "$target" "$INSTANCE_DIR" "$dest" && rc=0 || rc=$?
3272 case "$rc" in
3273 0)
3274 POLICY_INSTANCE="$dest"
3275 POLICY_INSTANCE_LABEL="$INSTANCE_DIR@$at (this repository is its own valley)"
3276 return 0
3277 ;;
3278 1) ;; # no floor of its own: the pointer names the valley that has one
3279 *)
3280 cleanup_instance_tmp
3281 refuse "could not read $INSTANCE_DIR/ at $at; nothing derived"
3282 return 1
3283 ;;
3284 esac
3285
3286 git -C "$root" cat-file blob "$target:$VALLEY_POINTER" > "$INSTANCE_TMP/pointer" 2> /dev/null || {
3287 cleanup_instance_tmp
3288 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"
3289 return 1
3290 }
3291 url="$(pointer_url "$INSTANCE_TMP/pointer")"
3292 [ -n "$url" ] || {
3293 cleanup_instance_tmp
3294 refuse "$VALLEY_POINTER at $at names no repository — it wants one line, the owning valley as git fetch takes it; nothing derived"
3295 return 1
3296 }
3297
3298 bare="$INSTANCE_TMP/valley.git"
3299 git init --quiet --bare "$bare" || {
3300 cleanup_instance_tmp
3301 refuse "no scratch repository to fetch the floor into; nothing derived"
3302 return 1
3303 }
3304 git -C "$bare" fetch --quiet --depth 1 "$url" "$VALLEY_POINTER_REF" || {
3305 cleanup_instance_tmp
3306 refuse "could not fetch the owning valley $url at $VALLEY_POINTER_REF (named by $VALLEY_POINTER at $at); nothing derived"
3307 return 1
3308 }
3309
3310 copy_layer "$bare" FETCH_HEAD "$INSTANCE_DIR" "$dest" && rc=0 || rc=$?
3311 case "$rc" in
3312 0) ;;
3313 1)
3314 cleanup_instance_tmp
3315 refuse "the owning valley $url holds no *.cue in $INSTANCE_DIR/ at $VALLEY_POINTER_REF; nothing derived"
3316 return 1
3317 ;;
3318 *)
3319 cleanup_instance_tmp
3320 refuse "could not read $INSTANCE_DIR/ from $url; nothing derived"
3321 return 1
3322 ;;
3323 esac
3324
3325 POLICY_INSTANCE="$dest"
3326 POLICY_INSTANCE_LABEL="$url $INSTANCE_DIR@$VALLEY_POINTER_REF"
3327}
3328
3329# Is this check mandatory in this class, or a default the project left
3330# alone? The bit is the form of the composed value, so the test is CUE's
3331# own: a project supplying `false` either conflicts or unifies cleanly.
3332# Answering by unifying rather than by inspecting syntax means the script
3333# cannot disagree with `cue vet`.
3334#
3335# This is the one producer whose failure does not end the derivation. A
3336# probe that fails for any other reason, or that cannot be written, reads as
3337# mandatory, which is the strict answer, and the bit never changes which
3338# checks are required.
3339check_is_mandatory() {
3340 local class="$1" check="$2" field
3341 if [ "$class" = unclassified ]; then
3342 field="policy: unclassified: \"$check\": false"
3343 else
3344 field="policy: classes: \"$class\": requires: \"$check\": false"
3345 fi
3346 # A probe that could not be written may leave the last one in its place,
3347 # and that one answers for another check. Mandatory is the strict answer.
3348 printf 'package verification\n%s\n' "$field" > "$POLICY_TMP/probe.cue" \
3349 || return 0
3350 ! cue vet "${POLICY_LAYER[@]}" "$POLICY_TMP/probe.cue" > /dev/null 2>&1
3351}
3352
3353# Every side of the diff: an added, modified or deleted path, and both the
3354# old and the new path of a rename or copy. It reads `git diff -z
3355# --name-status` on stdin, because a path may contain anything but NUL, and
3356# fails on a record cut short — including one cut inside its status, which
3357# a plain `while read` would end on quietly, dropping the record. It also
3358# fails when a write fails: the caller runs without `errexit`, so a lost
3359# path would otherwise end in a normal EOF and a status of 0.
3360diff_paths() {
3361 local status path
3362 while IFS= read -r -d '' status || { [ -z "$status" ] || return 1; false; }; do
3363 IFS= read -r -d '' path || return 1
3364 printf '%s\n' "$path" || return 1
3365 case "$status" in
3366 R* | C*)
3367 IFS= read -r -d '' path || return 1
3368 printf '%s\n' "$path" || return 1
3369 ;;
3370 esac
3371 done
3372}
3373
3374# Lines in, one comma-separated line out.
3375join_lines() {
3376 local out="" line
3377 while IFS= read -r line; do out="${out:+$out, }$line"; done
3378 printf '%s' "$out"
3379}
3380
3381# Arguments in, one comma-separated line out, or `none` when there are none.
3382join_or_none() {
3383 if [ $# -eq 0 ]; then echo none; else printf '%s\n' "$@" | join_lines; fi
3384}
3385
3386# The remaining arguments, sorted bytewise, into the array the first one
3387# names. The order is the C locale's whatever the caller's is, as it is
3388# throughout the derivation (derive_required). The sort is captured and its
3389# status returned: a sort read through a process substitution that fails
3390# reads as a sort of nothing, and for a list of required checks that is a
3391# change that requires none.
3392#
3393# The destination is a nameref, so what is assigned is the caller's array,
3394# and the linter cannot see that array being read.
3395# shellcheck disable=SC2034
3396sort_into() {
3397 local -n sort_into_dest="$1"
3398 local sorted
3399 shift
3400 sort_into_dest=()
3401 [ $# -gt 0 ] || return 0
3402 sorted="$(printf '%s\n' "$@" | LC_ALL=C sort)" || return 1
3403 mapfile -t sort_into_dest <<<"$sorted"
3404}
3405
3406# The target: the ref a change is derived against, and the tip both policy
3407# layers are read out of. origin's answer is preferred, because the target
3408# is the branch as the integrator holds it and not as this checkout last
3409# built it.
3410#
3411# Only a ref that is not there falls through to the next. show-ref says
3412# "not there" with 1 and fails any other way with another status, so a
3413# read of origin's ref that failed ends here: falling through would read
3414# the policy out of the local main, which may be older. 1 no main at all,
3415# 2 a read failed.
3416target_ref() {
3417 local ref rc
3418 for ref in refs/remotes/origin/main refs/heads/main; do
3419 git show-ref --verify --quiet "$ref" && rc=0 || rc=$?
3420 case "$rc" in
3421 0) echo "$ref"; return 0 ;;
3422 1) ;;
3423 *) return 2 ;;
3424 esac
3425 done
3426 return 1
3427}
3428
3429# ----------------------------------------------------------------------
3430# The derivation itself, and the globals it answers with. Everything a
3431# caller could want from the policy comes out of one pass, because every
3432# part of it is a function of the same composition: `checks` prints the
3433# answer, approve runs what it names.
3434#
3435# It reports and returns rather than dying, so that a caller inside the
3436# review loop is refused rather than ended. Its callers are all in a
3437# condition, which suspends `set -e` for the whole call, so every step is
3438# checked by hand.
3439#
3440# The derivation runs in the C locale, whatever locale its caller runs in,
3441# so a glob matches bytes and every list sorts bytewise. Under a UTF-8
3442# locale bash's regular expressions read characters instead: `?` matches é,
3443# and a path holding a byte that is not UTF-8 matches no pattern at all,
3444# not even `**`, so it would fall to `unclassified`. sort -u under
3445# en_US.UTF-8 also merges distinct paths that collate equally. Which checks
3446# a change requires would then depend on the locale of whoever derives it:
3447# an operator's shell for approve, the integrator's unit for the integrator.
3448# The Go deriver (derive/) matches bytes too, and its tests hold the two to
3449# the same answer under UTF-8 locales.
3450#
3451# Every producer — git, cue, sort — writes a file or a variable, and its
3452# status is checked before anything reads what it wrote. A producer read
3453# through a process substitution loses its status, and a failed one then
3454# reads as an empty list: no changed paths, no catalogue, no classes. Each
3455# of those derives a change that requires nothing, which is the one answer a
3456# failure must never give.
3457DERIVED_PATHS=() # every side of the diff, sorted
3458DERIVED_MATCHED=() # the class names at least one path matched, sorted
3459DERIVED_UNCOVERED=() # the paths no class covered
3460DERIVED_UNCLASSIFIED=0 # whether `unclassified` requires something
3461DERIVED_CARRY="" # the strictest carry mode among the matched classes
3462declare -A DERIVED_REQUIRED=() # check -> the classes that required it
3463declare -A DERIVED_PINNED=() # check -> mandatory | default
3464declare -A CHECK_RUNNER=() # check -> nix | command
3465declare -A CHECK_ATTRIBUTE=() # check -> the flake check attribute
3466declare -A CHECK_COMMAND=() # check -> the command line
3467declare -A CHECK_COST=() # check -> quick | slow
3468
3469derive_required() {
3470 local schema="$1" instance="$2" project="$3" base="$4" head="$5"
3471 # Exported, so sort and every other program the derivation runs reads
3472 # bytes too; bash restores the caller's locale when this returns.
3473 local -x LC_ALL=C
3474
3475 need_cue
3476 [ -f "$schema" ] || {
3477 refuse "no policy schema at $schema; nothing derived"
3478 return 1
3479 }
3480 # An unmatched glob stays literal, so the first entry is a real file
3481 # exactly when the directory holds a document.
3482 local -a instance_docs=("$instance"/*.cue) project_docs=("$project"/*.cue)
3483 [ -f "${instance_docs[0]}" ] || {
3484 refuse "no instance policy layer at $instance; nothing derived"
3485 return 1
3486 }
3487 [ -f "${project_docs[0]}" ] || {
3488 refuse "no project policy layer at $project: a project's own layer is the *.cue documents under $PROJECT_DIR/ (dcr-f41f718). Nothing derived"
3489 return 1
3490 }
3491
3492 cleanup_policy_tmp
3493 POLICY_LAYER=("$schema" "${instance_docs[@]}" "${project_docs[@]}")
3494 POLICY_TMP="$(mktemp -d)" || {
3495 refuse "no scratch directory to compose the policy in; nothing derived"
3496 return 1
3497 }
3498
3499 git diff --no-relative --name-status -M -z "$base" "$head" > "$POLICY_TMP/diff" || {
3500 refuse "could not diff $base..$head; nothing derived"
3501 return 1
3502 }
3503 diff_paths < "$POLICY_TMP/diff" > "$POLICY_TMP/paths" || {
3504 refuse "truncated diff output; nothing derived"
3505 return 1
3506 }
3507 sort -u "$POLICY_TMP/paths" > "$POLICY_TMP/paths.sorted" || {
3508 refuse "could not sort the changed paths; nothing derived"
3509 return 1
3510 }
3511 DERIVED_PATHS=()
3512 mapfile -t DERIVED_PATHS < "$POLICY_TMP/paths.sorted"
3513
3514 render_cue > "$POLICY_TMP/render.cue" || {
3515 refuse "could not write the policy render; nothing derived"
3516 return 1
3517 }
3518 cue vet -c "${POLICY_LAYER[@]}" || {
3519 refuse "the policy layers do not compose; nothing derived"
3520 return 1
3521 }
3522
3523 # The render is checked before it is read. A render that fails prints
3524 # nothing, and an empty render reads as a policy that requires nothing. A
3525 # schema older than this script fails it, by lacking a field it reads. So
3526 # does a policy string holding a control character, which a schema that
3527 # admits one lets through.
3528 cue eval --out text -e _render "${POLICY_LAYER[@]}" "$POLICY_TMP/render.cue" \
3529 > "$POLICY_TMP/rendered" || {
3530 refuse "the composed policy does not render (a schema older than this script, and a policy string holding a control character, are two causes); nothing derived"
3531 return 1
3532 }
3533 # Sorted once here, so every list below comes out in a stable order.
3534 sort "$POLICY_TMP/rendered" > "$POLICY_TMP/rendered.sorted" || {
3535 refuse "could not sort the composed policy; nothing derived"
3536 return 1
3537 }
3538 local -a rendered=()
3539 mapfile -t rendered < "$POLICY_TMP/rendered.sorted"
3540
3541 unset CHECK_RUNNER CHECK_ATTRIBUTE CHECK_COMMAND CHECK_COST DERIVED_REQUIRED \
3542 DERIVED_PINNED
3543 declare -gA CHECK_RUNNER=() CHECK_ATTRIBUTE=() CHECK_COMMAND=() \
3544 CHECK_COST=() DERIVED_REQUIRED=() DERIVED_PINNED=()
3545
3546 # The middle field is a class name for a coverage or requirement line and
3547 # a check name for a catalogue one; `key` is what both are.
3548 #
3549 # The render states each thing once: a class has one carry mode, a check
3550 # one runner, and a class requires a check once. A second line for the
3551 # same thing is forged, and a reader that took the last one would let the
3552 # forgery win, so it is refused. A coverage or requirement line is one
3553 # member of a set, so it is identified by its value too.
3554 local -a pat_class=() pat_ere=() req_class=() req_check=()
3555 local -A class_carry=() seen=()
3556 local line kind key value id
3557 for line in "${rendered[@]}"; do
3558 kind="${line%%$'\t'*}"
3559 key="${line#*$'\t'}"
3560 value="${key#*$'\t'}"
3561 key="${key%%$'\t'*}"
3562 case "$kind" in
3563 path | requires) id="$kind $key $value" ;;
3564 *) id="$kind $key" ;;
3565 esac
3566 [ -z "${seen[$id]:-}" ] || {
3567 refuse "the composed policy rendered '$id' twice, and states each thing once; nothing derived"
3568 return 1
3569 }
3570 seen["$id"]=1
3571 case "$kind" in
3572 path)
3573 pat_class+=("$key")
3574 pat_ere+=("$(glob_ere "$value")")
3575 ;;
3576 requires)
3577 req_class+=("$key")
3578 req_check+=("$value")
3579 ;;
3580 carry) class_carry["$key"]="$value" ;;
3581 runner) CHECK_RUNNER["$key"]="$value" ;;
3582 attribute) CHECK_ATTRIBUTE["$key"]="$value" ;;
3583 command) CHECK_COMMAND["$key"]="$value" ;;
3584 cost) CHECK_COST["$key"]="$value" ;;
3585 esac
3586 done
3587
3588 # A pattern bash cannot compile answers 2, not 1. Read as "no match", it
3589 # would drop the pattern's class from every change it covers.
3590 local -A matched=()
3591 local path i hit rc
3592 DERIVED_UNCOVERED=()
3593 for path in "${DERIVED_PATHS[@]}"; do
3594 hit=0
3595 for ((i = 0; i < ${#pat_ere[@]}; i++)); do
3596 [[ "$path" =~ ${pat_ere[i]} ]] && rc=0 || rc=$?
3597 case "$rc" in
3598 0)
3599 matched["${pat_class[i]}"]=1
3600 hit=1
3601 ;;
3602 1) ;;
3603 *)
3604 refuse "class ${pat_class[i]} has a path pattern that does not compile (${pat_ere[i]}); nothing derived"
3605 return 1
3606 ;;
3607 esac
3608 done
3609 [ "$hit" -eq 1 ] || DERIVED_UNCOVERED+=("$path")
3610 done
3611
3612 # The change's carry mode: the strictest among the classes its paths
3613 # matched, each as the schema resolved it. It is taken before
3614 # `unclassified` joins the matched classes, because an unclassified path
3615 # is same-paths and can make no change stricter. A matched class with no
3616 # mode this script knows is refused rather than read as the loosest.
3617 local class
3618 DERIVED_CARRY=same-paths
3619 for class in "${!matched[@]}"; do
3620 case "${class_carry[$class]:-}" in
3621 exact) DERIVED_CARRY=exact ;;
3622 same-class) [ "$DERIVED_CARRY" = exact ] || DERIVED_CARRY=same-class ;;
3623 same-paths) ;;
3624 *)
3625 refuse "class $class has no carry mode this script knows ('${class_carry[$class]:-}'); nothing derived"
3626 return 1
3627 ;;
3628 esac
3629 done
3630
3631 # A path no class covers is answered by the policy's `unclassified` set,
3632 # which is why it is treated as one more matched class rather than as an
3633 # absence.
3634 [ "${#DERIVED_UNCOVERED[@]}" -eq 0 ] || matched[unclassified]=1
3635
3636 local check
3637 DERIVED_UNCLASSIFIED=0
3638 for ((i = 0; i < ${#req_check[@]}; i++)); do
3639 key="${req_class[i]}"
3640 check="${req_check[i]}"
3641 [ -n "${matched[$key]:-}" ] || continue
3642 [ "$key" != unclassified ] || DERIVED_UNCLASSIFIED=1
3643 DERIVED_REQUIRED["$check"]="${DERIVED_REQUIRED[$check]:+${DERIVED_REQUIRED[$check]}, }$key"
3644 if check_is_mandatory "$key" "$check"; then
3645 DERIVED_PINNED["$check"]=mandatory
3646 else
3647 DERIVED_PINNED["$check"]="${DERIVED_PINNED[$check]:-default}"
3648 fi
3649 done
3650
3651 sort_into DERIVED_MATCHED "${!matched[@]}" || {
3652 refuse "could not sort the matched classes; nothing derived"
3653 return 1
3654 }
3655}
3656
3657cmd_checks() {
3658 local root schema instance="" label project="" plabel base head target=""
3659 local names=0 cost="" costed=0 short_base short_head
3660 root="$(git rev-parse --show-toplevel 2> /dev/null)" \
3661 || die "not a git repository"
3662 policy_defaults "$root"
3663 schema="$POLICY_SCHEMA"
3664 while [ $# -gt 0 ]; do
3665 case "$1" in
3666 --schema) [ $# -ge 2 ] || die "--schema needs a file"; schema="$2"; shift 2 ;;
3667 --instance) [ $# -ge 2 ] || die "--instance needs a directory"; instance="$2"; shift 2 ;;
3668 --project) [ $# -ge 2 ] || die "--project needs a directory"; project="$2"; shift 2 ;;
3669 --names) names=1; shift ;;
3670 --cost) [ $# -ge 2 ] || die "--cost needs quick or slow"; cost="$2"; costed=1; shift 2 ;;
3671 --) shift; break ;;
3672 -*) die "unknown option: $1" ;;
3673 *) break ;;
3674 esac
3675 done
3676 [ $# -le 2 ] || die "usage: valley checks [options] [<base> [<head>]]"
3677 if [ "$costed" -eq 1 ]; then
3678 case "$cost" in
3679 quick | slow) ;;
3680 *) die "--cost takes quick or slow, not '$cost'" ;;
3681 esac
3682 [ "$names" -eq 1 ] || die "--cost filters the --names list; pass --names too"
3683 fi
3684
3685 head="$(git rev-parse --verify --quiet "${2:-HEAD}^{commit}")" \
3686 || die "no such commit: ${2:-HEAD}"
3687 # The target is what the layers are read out of, so it is needed whenever
3688 # either layer is left to its default — and it is what an unnamed base
3689 # is the merge base with.
3690 if [ -z "$instance" ] || [ -z "$project" ] || [ $# -lt 1 ]; then
3691 target="$(target_ref)" || {
3692 [ $? -eq 1 ] || die "could not read the main branch; nothing derived"
3693 die "no main branch: the target's tip is where the policy layers are read from, and there is none here"
3694 }
3695 fi
3696 if [ $# -ge 1 ]; then
3697 base="$(git rev-parse --verify --quiet "$1^{commit}")" \
3698 || die "no such commit: $1"
3699 else
3700 base="$(git merge-base "$target" "$head")" \
3701 || die "$head and ${target#refs/} do not share history — name a base"
3702 fi
3703
3704 trap 'cleanup_policy_tmp; cleanup_instance_tmp; cleanup_project_tmp' EXIT
3705 # Each layer is resolved only when nobody named one. --instance and
3706 # --project are a reader pointing this at a layer on purpose, and
3707 # honouring that means not fetching the repository, and not reading the
3708 # tip, that the named layer replaced.
3709 if [ -n "$instance" ]; then
3710 label="${instance#"$root"/}"
3711 else
3712 resolve_instance_layer "$root" "$target" || exit 1
3713 instance="$POLICY_INSTANCE"
3714 label="$POLICY_INSTANCE_LABEL"
3715 fi
3716 if [ -n "$project" ]; then
3717 plabel="${project#"$root"/}"
3718 else
3719 resolve_project_layer "$root" "$target" || exit 1
3720 project="$POLICY_PROJECT"
3721 plabel="$POLICY_PROJECT_LABEL"
3722 fi
3723 derive_required "$schema" "$instance" "$project" "$base" "$head" || exit 1
3724
3725 # The required checks, sorted, and grouped by the cost the policy
3726 # declares. The grouping changes nothing required: approve runs every
3727 # required check, and the integrator requires evidence for every one,
3728 # whatever it costs.
3729 local check width=0
3730 local -a required=() quick=() slow=() listed=()
3731 sort_into required "${!DERIVED_REQUIRED[@]}" \
3732 || die "could not sort the required checks; nothing derived"
3733 for check in "${required[@]}"; do
3734 [ "${#check}" -le "$width" ] || width="${#check}"
3735 if [ "${CHECK_COST[$check]}" = slow ]; then
3736 slow+=("$check")
3737 else
3738 quick+=("$check")
3739 fi
3740 done
3741
3742 # The form for agents and scripts: the names alone, one per line.
3743 if [ "$names" -eq 1 ]; then
3744 case "$cost" in
3745 quick) listed=("${quick[@]}") ;;
3746 slow) listed=("${slow[@]}") ;;
3747 *) listed=("${required[@]}") ;;
3748 esac
3749 [ "${#listed[@]}" -eq 0 ] || printf '%s\n' "${listed[@]}"
3750 return
3751 fi
3752
3753 # Read before the first line is printed, so a read that fails leaves no
3754 # partial report behind.
3755 short_base="$(git rev-parse --short "$base")" \
3756 || die "could not read $base; nothing derived"
3757 short_head="$(git rev-parse --short "$head")" \
3758 || die "could not read $head; nothing derived"
3759
3760 printf '%s..%s: %d changed path(s)\n' "$short_base" "$short_head" \
3761 "${#DERIVED_PATHS[@]}"
3762 printf 'policy: %s + %s\n' "$label" "$plabel"
3763 if [ "${#DERIVED_MATCHED[@]}" -eq 0 ]; then
3764 printf 'classes matched: none\n'
3765 else
3766 printf 'classes matched: %s\n' \
3767 "$(printf '%s\n' "${DERIVED_MATCHED[@]}" | join_lines)"
3768 fi
3769 # How far an approval of this change carries across a rebase. Nothing
3770 # here acts on it.
3771 printf 'carry mode: %s\n\n' "$DERIVED_CARRY"
3772
3773 if [ "${#DERIVED_REQUIRED[@]}" -eq 0 ]; then
3774 echo "required checks: none"
3775 else
3776 echo "required checks:"
3777 for check in "${required[@]}"; do
3778 printf ' %-*s %-9s %s\n' \
3779 "$width" "$check" "${DERIVED_PINNED[$check]}" "${DERIVED_REQUIRED[$check]}"
3780 done
3781 fi
3782
3783 if [ "${#DERIVED_UNCOVERED[@]}" -gt 0 ]; then
3784 printf '\nunclassified: %d path(s) matched no class\n' "${#DERIVED_UNCOVERED[@]}"
3785 printf ' %s\n' "${DERIVED_UNCOVERED[@]}"
3786 # The failure the `unclassified` field exists to prevent: paths outside
3787 # every class that the policy then asks nothing of.
3788 [ "$DERIVED_UNCLASSIFIED" -eq 1 ] \
3789 || echo " the policy requires nothing of them — it is behind the tree"
3790 fi
3791
3792 # Below every line the integrator reads (integrator/policy.go), and
3793 # unindented, so neither line can read as a required check.
3794 if [ "${#required[@]}" -gt 0 ]; then
3795 printf '\nquick: %s\n' "$(join_or_none "${quick[@]}")"
3796 printf 'slow: %s\n' "$(join_or_none "${slow[@]}")"
3797 fi
3798}
3799
3800# self-update installs the tip of a branch of the-valley into the user's
3801# nix profile (status/selfupdate.go). It is told this valley's stamp, which
3802# says what is installed until it has installed something itself.
3803cmd_self_update() {
3804 export VALLEY_VERSION="$VALLEY_STAMP"
3805 cmd_go self-update "$@"
3806}
3807
3808cmd_version() {
3809 printf 'valley %s\n' "${VALLEY_STAMP:-unstamped (run from a checkout, not built by nix)}"
3810}
3811
3812cmd_help() {
3813 [ $# -le 1 ] || die "usage: valley help [<verb>]"
3814 local out
3815 case "${1:-}" in
3816 '' | help | -h | --help) out="$(usage)" ;;
3817 pending) out="$(help_pending)" ;;
3818 changes) out="$(help_changes)" ;;
3819 review) out="$(help_review)" ;;
3820 approve) out="$(help_approve)" ;;
3821 rebase) out="$(help_rebase)" ;;
3822 status) out="$(help_status)" ;;
3823 ready) out="$(help_ready)" ;;
3824 unready) out="$(help_unready)" ;;
3825 withdraw) out="$(help_withdraw)" ;;
3826 knot) out="$(help_knot)" ;;
3827 plan) out="$(help_plan)" ;;
3828 checks) out="$(help_checks)" ;;
3829 tail) out="$(help_tail)" ;;
3830 replay) out="$(help_replay)" ;;
3831 self-update) out="$(help_self_update)" ;;
3832 *) die "unknown help topic: $1 (try 'valley help')" ;;
3833 esac
3834 printf '%s\n' "$out" 2> /dev/null || true
3835}
3836
3837main() {
3838 local verb="${1:-help}"
3839 if [ $# -gt 0 ]; then shift; fi
3840 # The verb set is mirrored in completions/ (valley.bash, _valley) —
3841 # update both when it changes.
3842 case "$verb" in
3843 pending | changes | review | approve | rebase | status | ready | unready | withdraw | knot | plan | checks | tail | replay | self-update)
3844 if [ $# -eq 1 ] && { [ "$1" = -h ] || [ "$1" = --help ]; }; then
3845 cmd_help "$verb"
3846 return
3847 fi
3848 ;;
3849 esac
3850 case "$verb" in
3851 pending) cmd_pending "$@" ;;
3852 review) cmd_review "$@" ;;
3853 approve) cmd_approve "$@" ;;
3854 rebase) cmd_rebase "$@" ;;
3855 status | ready | unready | withdraw | changes | knot | plan) cmd_go "$verb" "$@" ;;
3856 checks) cmd_checks "$@" ;;
3857 tail) cmd_tail "$@" ;;
3858 replay) cmd_replay "$@" ;;
3859 self-update) cmd_self_update "$@" ;;
3860 --version) cmd_version ;;
3861 help | -h | --help) cmd_help "$@" ;;
3862 *)
3863 printf 'valley: unknown verb: %s\n\n' "$verb" >&2
3864 usage >&2
3865 exit 1
3866 ;;
3867 esac
3868}
3869
3870main "$@"