gunk-dev/the-valley

valley

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