gunk-dev/the-valley

valley

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