gunk-dev/the-valley

valley

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