gunk-dev/the-valley

valley

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