gunk-dev/the-valley

valley

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