gunk-dev/the-valley

valley

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