gunk-dev/the-valley

valley

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