gunk-dev/the-valley

valley

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