gunk-dev/the-valley

valley

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