gunk-dev/the-valley

valley

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