gunk-dev/the-valley

valley

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