gunk-dev/the-valley

valley

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