gunk-dev/the-valley

valley

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