gunk-dev/the-valley

valley

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