gunk-dev/the-valley

valley

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