gunk-dev/the-valley

valley

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