gunk-dev/the-valley

valley

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