gunk-dev/the-valley

valley

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