gunk-dev/the-valley

valley

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