gunk-dev/the-valley

valley

sourcedbe26c5ba15amain's published tip history
137.1 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
51# When this invocation started, in microseconds, for its command record
52# (valley help telemetry). Reading the clock starts no process.
53TEL_T0="${EPOCHREALTIME/[.,]/}"
54
55die() {
56 printf 'valley: %s\n' "$*" >&2
57 exit 1
58}
59
60usage() {
61 cat <<'EOF'
62usage: valley <verb> [args]
63
64valley — S1 integrator verbs for a valley project: author, review, approve, and
65track changes and the plan graph.
66
67Authoring and updating changes:
68 ready mark a branch head ready as a new version of its change
69 unready pause a ready change by marking it a draft
70 withdraw mark a ready or draft change withdrawn
71 rebase rebase a change and its stack onto origin/main
72 checks print the checks the composed policy requires of a diff
73
74Reviewing, approving, and inspecting changes:
75 pending list what needs an approval, in landing order, and what moves
76 review page through a change or stack to approve, rebase, or reject
77 approve run required checks and file an integration request
78 status read a change's integration request and last outcome
79 changes print every recorded change as valley-changes/v1 JSON
80
81Planning work:
82 plan show the project's plan graph as a milestone tree
83 knot read and write knots in the plan graph at refs/the-valley/knots
84
85Bus and client maintenance:
86 tail watch NATS bus events scroll by
87 replay publish ref-updated events for the current refs of a repo
88 self-update build, test, and install the tip of a branch of the-valley
89 telemetry read a valley host's diagnostics over ssh (observe grant)
90
91A change is named by its 32-letter change id, its handle (shortest unique
92prefix, at least 4 letters, or <repo>:<handle>), or its branch name.
93Runs from any checkout; nix run .#valley bundles git, valley-go, attest, cue,
94less, and natscli (self-update also needs nix). Judgment stays with the human:
95nothing here writes main.
96
97`valley --version` prints the package's version and commit (e.g. 0.1.0-97db597,
98with -dirty for uncommitted changes, -unknown when nix knew no commit, or
99unstamped when run straight from a checkout).
100Run `valley help <verb>` (or `valley <verb> --help`) for a verb's flags and
101rules. See docs/reference.md for the full CLI, ref, and schema reference.
102EOF
103}
104
105help_naming() {
106 cat <<'EOF'
107
108A change is named by its full change id, by its handle — the shortest
109prefix of the id, four letters at least, that no other change recorded on
110origin shares, written <repo>:<handle> too, with this repository's name —
111or by its branch. A name written origin/<branch> is always
112a branch. A handle that is also a branch on origin is refused unless the
113change is on that branch. review, approve and rebase read a branch name,
114written either way, against every record on origin: when exactly one
115record's active version is on the branch, the name is that change, as if
116its id were given, and when more than one's is, the verb refuses and lists
117their ids. A change that has landed as any version — its head is on
118main's first-parent history with no merge above it, or the integrator's
119outcome record and verified transfer statement record that exact head
120landing — is skipped, unless its active version was made on that landing, so a branch can be used again once its change has
121landed. unready, withdraw and status read a branch the same way. A
122branch no record's active version is on is acted on as a branch. A
123change with a record is reviewed, approved and rebased at the
124head its active version records, never at its branch's tip: review shows
125that head and its [a]pprove approves it, and rebase and review's
126[r]eject refuse, naming both, when the branch's tip on origin is another
127commit. approve approves the head bound to it, wherever the branch is.
128[r]eject deletes the branch under a lease on the recorded head. approve,
129and rebase refuse a change whose record is not ready, naming its state,
130and review offers neither [a]pprove nor [r]eject for a change that is not
131ready when it shows it. approve and rebase read the record again just
132before they act, and again before approve files or rebase pushes, and
133refuse when the change is not ready. review reads the change again before
134its [a]pprove or [r]eject acts. When the change has moved since review
135showed it, returned to draft, withdrawn, given a new version or landed,
136review says so in one line and moves on, without asking again. rebase also refuses when the change's
137record has changed at all since it began, and approve when the head it
138approves is not a version's. A name that read as a plain branch is
139read again before approve files or rebase pushes. If it names a change by
140then, rebase refuses, and approve files only while the change is ready at
141the head it began with. An approval already past that last check can
142still file if the change is unreadied or withdrawn in the moment before
143its push; the integrator refuses to land it, since it lands no request
144that would bring a version of a change that is not ready, whatever the
145request is named.
146The integrator reads the records last just before it moves main, so a
147change paused in that moment can still land at the head the operator
148approved, and never at any other.
149EOF
150}
151
152help_runtime() {
153 cat <<'EOF'
154
155Runs from any checkout of the project; needs only git and coreutils,
156except tail and replay, which also need the nats CLI (natscli), checks,
157which also needs the cue CLI, review's notes, which need less, approve
158and review's [a]pprove, which need both the cue CLI and the attest
159helper, and status, ready, unready, withdraw, review, approve and rebase,
160which need the valley-go helper, as pending, changes, knot, plan and
161self-update do. nix run .#valley bundles all of them. self-update also
162needs nix. Deriving a policy fetches the owning valley's repository, so
163checks and approving also need whatever reaching it takes.
164No config but valley.principal, which ready, rebase, knot and plan read,
165and valley.selfUpdate.repo and .branch, which self-update reads; no batch
166mode; and no state but the notes file, the handle cache pending and
167changes write for completion, and self-update's record of what it
168installed — the judgment stays with the human.
169EOF
170}
171
172help_unready_withdraw_requests() {
173 cat <<'EOF'
174 the integrator lands no request that would bring a
175 version of a change that is not ready, so unready and
176 withdraw both stop a
177 pending integration request, under c-<change id> or a
178 branch's request name. each says so when origin holds
179 one. a draft's request stands and lands once the change
180 is ready again. withdrawing voids the request: the
181 integrator deletes it on its next pass while the change
182 is still withdrawn. withdraw warns, since a ready before
183 then leaves the request standing: only a holder of the
184 approve grant (also accepted as request) may touch a
185 request ref, so the operator must drop it then.
186EOF
187}
188
189help_pending() {
190 cat <<'EOF'
191usage: valley pending [--all] [--repo <name>] [--checks] [--drafts] [--branches] [--json] [-v] [--known-signers <file>] [--integrator-name <name>]
192
193 pending [--all] [--repo <name>] [--checks] [--drafts] [--branches]
194 [--json] [-v] [--known-signers <file>] [--integrator-name <name>]
195 list what waits on you and what is moving. one line
196 on main's state comes first for each project whose
197 policy declares follow checks: clear, clearing or
198 muddy. needs you holds the ready changes that wait on
199 an approval, one numbered row each in landing order:
200 oldest ready first, as the check worker builds them,
201 then by project and change id. a row gives the
202 handle and active version, its checks as passed out of
203 required (or how many are pending), and how long it
204 has been ready, with its title under it. a stack of
205 such changes is one row, its top's, saying `stack of
206 N`: approving the top lands every layer. moving holds
207 the ready changes that need no approval now, one line
208 each: ◐ approved, waiting on checks and the
209 integrator; ✗ a check failed, named; ✗ or ◇ a restack
210 holds it. older versions are never listed. a last line
211 counts the drafts and the branches no change is on.
212 lines fit the terminal, or 80 columns off one; titles
213 are cut short with …, names never. names are bold and
214 glyphs coloured on a terminal unless NO_COLOR is set.
215 --all every project the serving host
216 publishes, as one listing: each line
217 names its project, and the rows of
218 every project share one landing order
219 (see valley help changes)
220 --repo NAME that one project
221 --checks add to each row the checks the policy
222 requires of it, by cost, as checks
223 derives them, and its full check state,
224 naming the checks that failed and what
225 they cost the host's check worker to
226 build. with --json, give each pending
227 change its checks object
228 --drafts list the drafts in full, in place of
229 their count
230 --branches list the branches no change is on in
231 full, in place of their count. each
232 draft and branch is a block: its name
233 with its head's age and author, its
234 title, then the commits and the diff
235 it adds to the nearest listed entry
236 its head contains, or to main. a stack
237 is its top, then every entry the top
238 contains, at one indentation; an entry
239 not on the one listed after it says
240 `on <base>`
241 --json print valley-pending/v1: the
242 valley-changes/v1 shape, with the
243 pending changes in changes, each
244 marked approved or not, and the
245 drafts in drafts
246 -v follow each row with its block, its
247 stack drawn in full, with what its
248 head includes, `uncertain` when it may
249 have landed without its evidence
250 stored, and its full check state; and
251 warn on stderr when a plan graph is
252 missing or unreadable
253 --known-signers FILE, --integrator-name NAME
254 what a transfer statement is verified
255 with (see changes below)
256 reading the checks costs seconds for each project
257 with a ready change. needs the valley-go helper.
258EOF
259 help_runtime
260}
261
262help_changes() {
263 cat <<'EOF'
264usage: valley changes --json [--all] [--repo <name>] [--checks] [-v] [--known-signers <file>] [--integrator-name <name>]
265
266 changes --json [--all] [--repo <name>] [--checks] [-v]
267 [--known-signers <file>] [--integrator-name <name>]
268 print every change origin holds a record of, in every
269 state, as one JSON object, valley-changes/v1, for front
270 ends to read (docs/architecture.md): each version's
271 head, title and branch, how far it has landed
272 (landed, landed-recorded, uncertain or not-landed),
273 its pending request and its last outcome, the knots in
274 refs/the-valley/knots that link it
275 (valley:<project>/<change id>, active first), and
276 the branches no change is on. -v warns on stderr when a
277 plan graph is missing or unreadable. --checks adds
278 checks to the active version of each ready change that
279 has not landed: each check the policy requires of it,
280 passed, failed or pending by the note the integrator
281 would judge it by on origin, and other for a check the
282 host's worker does not run (docs/reference.md). each nix
283 check also gives its build time for this version, and
284 the median of its recent builds, from the host's
285 worker telemetry; when that cannot be read, those
286 fields are left out and stderr says why. it costs a
287 few seconds for each project with such a change.
288 handles are unique across
289 everything listed: a change id recorded in more than
290 one repository listed has the handle <repo>:<prefix>
291 in each. without --all it covers this
292 repository. --all covers every project the serving
293 host lists at refs/the-valley/projects in its instance
294 repository, which policy/valley names at main's tip on
295 origin; each project's URL is the instance's with its
296 last path segment replaced, and is read through a clone
297 kept under $XDG_CACHE_HOME/valley/repos. a url that
298 opens with a dash, names a <transport>:: helper such
299 as ext::, or has a scheme other than ssh, git, https or
300 file is refused. a repository that cannot be read is
301 listed with its error. --repo limits it to one
302 project. landed means on main's first-parent history
303 with no merge above it. landed-recorded needs a landed
304 commit with one parent and the integrator's transfer
305 statement for the version's request name, verified;
306 the integrator's outcome record for that name saying
307 land at the version's head; and the integrator's merge
308 of the head onto the landed commit's parent giving the
309 landed tree. attest verifies the statement with the
310 registry's known-signers file and the integrator's
311 signing name. each is taken from the first of these
312 that gives it: --known-signers FILE or
313 --integrator-name NAME; VALLEY_KNOWN_SIGNERS or
314 VALLEY_INTEGRATOR_SIGNER; what the serving host
315 publishes at refs/the-valley/signers in its instance
316 repository, read only when a statement needs
317 verifying. a file that does not read, or holds no key
318 under the name, is reported on stderr, and then no
319 statement is verified.
320 needs the valley-go helper.
321EOF
322 help_runtime
323}
324
325help_review() {
326 cat <<'EOF'
327usage: valley review [-v] [--build-here] <change>
328 valley review [-v] [--build-here] [--repo <name>]
329
330 review [-v] [--build-here] [--repo <name>]
331 with no change, review each change that needs you, as
332 valley pending --all lists them, in landing order, or
333 those of the project --repo names. each step opens
334 with `[1/3] <project> · <handle> v<N> · <checks>` and
335 is the review below, run where the project is read:
336 this checkout, or the clone valley keeps of another
337 project, lent this checkout's valley.principal,
338 user.name and user.email. a change that landed, is
339 not ready or has no branch since is not reviewed; one
340 at a new version is reviewed at it. the walk ends with
341 each change's outcome and what still needs you. a
342 project that did not read is said first and last.
343 ctrl-c ends the walk with what it walked, exit 130.
344
345 review [-v] [--build-here] <change>
346 page through the change's branch: its log, with each
347 commit's whole message, and diff vs origin/main, or a
348 stack layer by layer (below). above
349 each change's diff, review shows every knot in the plan
350 graph that links the change, as `does oc-6335749 (open):
351 <title>` (valley-go does). a missing or unreadable graph
352 shows no knots; -v warns on stderr. before the prompt, a
353 ready change shows the state of its checks and what
354 they cost the host's check worker to build, as pending
355 --checks shows it: `checks: 21 passed in 9m10s (eval
356 24s); worker-e2e 431s, +100s against its recent 331s`.
357 review reads them while it shows the diff and never
358 waits for them: a line not read by the prompt is not
359 shown, unless VALLEY_REVIEW_CHECKS_WAIT=<seconds> says
360 how long to wait for it. checks that cannot be read show no line; -v
361 warns on stderr. the prompt is one header line, the
362 change and its state, `nqyw v3 · checks: 4 passed ·
363 behind main (integrator merges)`, then the keys it
364 takes; a change that can't be approved says why in the
365 header and is not offered [a]pprove. -v also passes -v
366 to approve. then choose:
367 [a]pprove file an integration request for the
368 head shown, as approve does (valley
369 help approve). it reuses the evidence
370 origin holds for the checks the
371 composed policy requires of this
372 change. when a required nix check has
373 none, it files the request at once
374 all the same, builds nothing, and
375 names the check. when evidence is
376 published, the integrator considers
377 the request again; it may never be
378 published. given
379 --build-here, review's [a]pprove builds
380 those nix checks here instead. it runs
381 the command checks, and any nix check
382 it builds, over a throwaway worktree of
383 that head, signs each result as an
384 attestation, and publishes the evidence
385 and the request ref to origin in ONE
386 atomic push. this files the request;
387 it does not wait for integration or
388 update your local checkout. use status
389 to read the result. the policy comes
390 from the target's tip and the owning
391 valley's, as checks describes (valley
392 help checks), so your checkout
393 can be on any branch. a change the policy
394 requires no check of is filed too, as a
395 request with no evidence, and says so.
396 approving a change already requested is
397 how it is filed again. at a head rebased
398 onto a moved main it replaces the request
399 ref under a lease and names the head it
400 replaced; at the same head it leaves the
401 ref alone and publishes only the new
402 evidence, which origin refuses when
403 this signer has already attested that
404 tree: approve publishes a signer's
405 evidence for a tree once (bd-7b7d58f). every write of the request
406 ref is leased, filing included, so an
407 approval that lost a race is refused
408 rather than clobbering the one that won.
409 needs the attest helper whenever a
410 check is required, and
411 VALLEY_ATTEST_KEY, the ed25519 key this
412 host signs with, whenever a check runs
413 here; VALLEY_ATTEST_NAME is the name it
414 signs under, defaulting to this host's.
415 [v]iew full diff
416 page the change's whole diff, with
417 notes taken as below, and ask again
418 [r]eject delete the remote branch (confirmed first)
419 [s]kip do nothing
420 a change with a record is first set against its
421 approved version: the greatest version below the one
422 shown whose exact head an integration request or a
423 land, stale or reject outcome on origin names, under
424 c-<change id> or a branch name of the change that
425 nothing else maps to (valley-go compare). with none,
426 or an ambiguous one, review pages the whole diff. its
427 first line says what changed since you approved v<m>:
428 `<change> v<n> at <head>: rebased since you approved
429 v<m> at <old head>, with the same file changes.`
430 each version's diff from its merge base with main
431 changes the same files the same way (valley-delta-v1).
432 review prints the commits main landed between the
433 bases, and pages nothing.
434 `... rebased since you approved v<m> at <old head>.`
435 the commits are the same patches, messages and
436 authors, but main also edited files the change edits.
437 review pages each file whose change differs, with the
438 landings that edited it, then the shown version's diff
439 of those files.
440 `... edited since you approved v<m> at <old head>.`
441 a commit's patch, message or author differs. review
442 pages how many commits changed, the files whose change
443 differs with the landings that edited them, git
444 range-diff of the two versions, and the shown
445 version's diff of those files, or prints a changed
446 message or author when the files are the same. -v adds
447 each file's mode and SHA-256 in each version. on a
448 terminal, unless NO_COLOR is set, the title, the
449 section headings and the hashes are styled; the buffer
450 the editor opens is plain. this is information only:
451 it files nothing and skips no check.
452 when [a]pprove's checks fail, the prompt says approving
453 needs a new head and stops offering [a]pprove until the
454 change has one. any other refusal keeps the prompt as
455 it was.
456 [a]pprove files the head shown, for a branch no record
457 is on too: it refuses, naming both heads, when the
458 branch on origin has moved off that head since.
459 [a]pprove is the only way a change reaches main from
460 here, and approve (valley help approve) is the same act
461 without the pager.
462 Nothing in this script writes the protected ref: the
463 integrator does, having judged the request.
464 a change behind main (one that does not fast-forward
465 from it) is asked the same prompt, under one line:
466 `<branch> is behind main; the integrator lands it
467 onto main as main stands (no rebase needed).`
468 the integrator applies the change's delta onto main as
469 it stands, and the host's restacker rebases ready
470 changes itself, so review asks nothing more of it.
471 while the restacker reports a conflict for the change,
472 the line says `<branch> conflicts with main; its owner
473 is resolving it.` instead. [a]pprove is still offered,
474 and the integrator decides whether the change applies.
475 to rebase a change of your own, use valley rebase.
476 a change whose record is not ready says so above its
477 diff, and again in place of the prompt, which then
478 offers only [v]iew full diff and [s]kip:
479 `<change> v<n> is a draft: its owner (<owner>) hasn't
480 marked it ready, so it can't be approved yet.`
481 `<change> is withdrawn: there is nothing to approve.`
482 a draft is often a change an agent is still working on.
483 [a]pprove would be refused. [r]eject records nothing
484 on the change: it would only delete a branch its owner
485 may still be working on.
486 before [a]pprove or [r]eject acts, review reads the
487 change again. when it moved while you read it, review
488 says what changed in one line, and acts on nothing
489 unless you approve a new version it offers:
490 `<change> changed while you were reviewing: it was
491 returned to draft (since <time>), so there is
492 nothing to approve now. It comes back when it is
493 ready again.`
494 `<change> changed while you were reviewing: it was
495 withdrawn (since <time>), so there is nothing to
496 approve.`
497 `<change> moved to v<n> while you were reviewing
498 (<why>) · [a]pprove v<n>, [v]iew what changed
499 since v<m>, [s]kip?`
500 `<change> landed as v<n> while you were reviewing;
501 there is nothing left to approve.`
502 <time> is when the record last changed, in UTC.
503 a new version with the same changes and commits, such
504 as a restack the carry mode allows, keeps the answer:
505 `<change> moved to v<n> while you were reviewing
506 (a restack of v<m>; same changes) · your answer
507 about v<m> stands`
508 and [a]pprove files v<m>, the head shown. otherwise
509 <why> says whether the change's commits changed or
510 only main moved under them, and why the answer does
511 not carry. with its commits unchanged, [a]pprove v<n>
512 is offered at once; with a commit changed, only after
513 [v]iew. [a] files v<n>'s head, and is refused if the
514 change moves again first.
515 a branch no record is on has no state, and is offered
516 the usual prompt.
517 while paging, press v: less opens the diff in $EDITOR.
518 every line you insert there is a note. it is anchored to
519 the file and new-side line it sits on — to the file alone
520 when it sits above the first hunk. range-diff gives no
521 line numbers, so set against an approved version a
522 note keeps its file and line only in the section
523 headed `── v<n>'s diff of these files against main`. each note is then appended to
524 $XDG_STATE_HOME/valley/notes/<branch>.md (default
525 ~/.local/state) and printed after the verdict. notes
526 survive a stack's [b]ase onto main. lines you change
527 or delete instead of inserting are ignored, with a
528 warning.
529 a change whose active version names no branch is
530 refused, since notes and [r]eject act on a branch;
531 approve files its head without one.
532 a stack is reviewed one layer at a time, bottom first.
533 a layer below the top that is approved, as pending
534 lists it, is named in the list and not paged: it asks
535 nothing of you. the top is always paged.
536 its layers are what pending lists under the change: the
537 changes not landed and the branches no record is on
538 that its head contains (valley-go stack). review first
539 lists them, warns of a lower layer that is a draft or
540 withdrawn, since the integrator lands nothing above it,
541 and says how the review goes: [n] through the layers,
542 and approving the top lands them all. a stack whose
543 bottom does not fast-forward from main is then asked,
544 before any layer is paged, under `<top> · stack of <n>
545 · behind main`:
546 [b]ase onto main
547 rebase the whole stack onto origin/main,
548 as rebase does (valley help rebase), then
549 list it again and page the rebased layers,
550 so the heads paged are the heads approved
551 [v]iew diff page the top's whole diff against main
552 [s]kip end the review; nothing done
553 a rebase that is refused or left unfinished says what
554 happened, and then only [v]iew diff and [s]kip are
555 offered.
556 it then shows each layer, headed `change <k> of <n>:
557 <name> on <below>`, as a change alone is shown: set
558 against its own change's approved version, or its log
559 and diff against the layer below it paged, with notes
560 kept under that layer's branch.
561 after each lower layer it asks, naming the layer and
562 its place, as in `two, 2 of 3:`:
563 [n]ext layer go on to the layer above; the usual
564 answer
565 [a]pprove approve that layer at the head shown,
566 as review of it would. this lands it
567 and every layer under it, which the
568 prompt names (`one alone`, `one and
569 two`, `the <k> up to <name>`), and
570 ends the review
571 [v]iew full diff
572 page that layer's log and diff against
573 the layer below it, and ask again
574 [s]top end the review; nothing done
575 after the top it asks, as in `three, 3 of 3:`:
576 [a]pprove all <n>
577 approve the top at the head shown,
578 which lands every layer
579 [v]iew full diff
580 page the top's log and diff against
581 the layer below it, and ask again
582 [r]eject <name>
583 delete the top's branch (confirmed
584 first)
585 [s]top end the review; nothing done
586 only the top is offered [r]eject. when a layer's checks
587 fail, its prompt says approving needs a new head and
588 stops offering [a]pprove, as for any change. a layer
589 that is not ready says so as a change alone does, under
590 its heading and in its prompt. neither it nor any layer
591 above it is offered [a]pprove, since approving one would
592 land it: each prompt above it says `it would bring
593 <name>, change <k> of <n>, which is a draft` (or
594 withdrawn) in its place. a top that is not ready is not
595 offered [r]eject either. every layer's notes are printed
596 at the end.
597EOF
598 help_naming
599 help_runtime
600}
601
602help_approve() {
603 cat <<'EOF'
604usage: valley approve [-v] [--head <sha>] [--build-here] <change>
605
606 approve [-v] [--head <sha>] [--build-here] <change>
607 do what review's [a]pprove does for the change, without
608 paging it: the same checks, the same refusals, the same
609 leased request write and the same output. exits non-zero
610 when it refuses. a change with a record is approved at
611 exactly one head, and its request is filed as
612 refs/the-valley/integration-requests/main/c-<change id>,
613 at that head:
614 --head SHA approve exactly this head, which must be
615 one of the record's version heads,
616 active or not. a front end passes the
617 head it showed, so a record that moves
618 after review cannot change what lands.
619 without --head, approve shows the active version's head
620 and title and asks to confirm them, on a terminal; off
621 one it refuses. a branch no record is on is approved at
622 its tip on origin, which --head must name if it is
623 given (review's [a]pprove files the head it showed, and
624 refuses once the branch on origin has moved off it), under
625 the branch's request name: the branch with
626 each / replaced by -. a branch whose request name would
627 be c-<change id> is refused, since that name is the
628 change's.
629 approve first reads the evidence origin holds for that
630 head's tree, refs/the-valley/attestations/<tree>/*, byte
631 for byte. it judges each required nix check by the note
632 the integrator judges it by: the first, in ref order,
633 that attest verify accepts under the known-signers file
634 the host publishes. it reuses that note when it is pure
635 evidence for the check's name and flake attribute and
636 says it passed. VALLEY_KNOWN_SIGNERS, when set, must
637 accept it too: it can narrow what is reused, never widen
638 it. a required nix check whose judged note records a
639 failure refuses the approval, since the integrator
640 judges the check by that note. a command check is never
641 reused. a listing or a fetch of
642 origin's evidence that fails is refused, and nothing is
643 run.
644 a required nix check that origin holds no evidence for
645 does not stop the approval. approve files the request at
646 once, with the evidence origin holds, builds nothing,
647 and publishes no evidence for that check. required
648 command checks still run first, and a missing signing
649 key, a failed check, or a refused push still fails the
650 approval. approve says the approval is recorded and
651 how many checks it waits for. the integrator keeps the
652 request and considers it again when evidence is
653 published. landing still requires a clean apply and
654 acceptable evidence for every required check. an
655 enabled worker that serves the project attempts the nix
656 checks of a ready change's active version, but cannot
657 add checks to its own existing evidence ref for the
658 same tree, and a failed build publishes nothing. waiting
659 does not ensure the evidence will be published. no
660 worker builds a branch no record is on, or a version
661 that is not the active one, and approve says so and
662 offers --build-here. the
663 evidence of an approval that ran a command check
664 occupies this signer's ref for the tree, so use
665 --build-here on the initial approval.
666 --build-here build those nix checks on this
667 machine instead, and publish their
668 evidence with the request.
669 approve runs every command check, and every nix check
670 it builds, over a throwaway worktree of that head, signs
671 each result as an attestation, and publishes the new
672 evidence and the request ref to origin in ONE atomic
673 push. when every required check is reused, nothing
674 runs, no signing key is needed, and the push carries
675 the request alone.
676 this files the request; it does not wait for
677 integration or update your local checkout. use status to
678 read the result. the policy comes from the target's tip
679 and the owning valley's, as checks describes (valley help
680 checks), so your checkout can be on any branch. a change
681 the policy requires no check of is filed too, as a
682 request with no evidence, and says so. approving a
683 change already requested is how it is filed again: at a
684 head rebased onto a moved main it replaces the request
685 ref under a lease and names the head it replaced; at the
686 same head it leaves the ref alone and publishes only the
687 new evidence. origin already holding this signer's
688 evidence for that tree, without a check that still has
689 to run, is refused before anything runs: approve
690 publishes a signer's evidence for a tree once, as a
691 ref of the new notes alone, and origin keeps every
692 note the ref holds (bd-7b7d58f). every
693 write of the request ref
694 is leased, filing included, so an approval that lost a
695 race is refused rather than clobbering the one that won.
696 needs the attest helper whenever a check is required,
697 and VALLEY_ATTEST_KEY, the ed25519 key this host signs
698 with, whenever a check has to run here;
699 VALLEY_ATTEST_NAME is the name it signs under,
700 defaulting to this host's. approve never writes the
701 protected ref: the integrator does, having judged the
702 request.
703 approve refuses, before any check runs, a head that does
704 not fast-forward from main and would bring a version of
705 another change that has not landed: a layer above the
706 bottom of a stale stack. the refusal names the command
707 that rebases the stack, valley rebase <change>. this is
708 the project's choice, not a rule the integrator needs:
709 approved as it is, the stack would land as one commit
710 recorded against this request alone, so the changes
711 under it would have no landing record of their own, and
712 the checks would run over a head that has to be rebased
713 anyway. a stale head with no change under it, such as
714 the bottom layer of a stack or a change alone, is
715 approved as it is, and the integrator merges it onto
716 main.
717 approve ends in one verdict line: the change, whether
718 it was approved, and what happens next, with one
719 indented line under it only when you must act:
720 ✓ nqyw v3 approved · checks passed · landing on main
721 ◐ nqyw v3 approved · lands when 3 checks pass (1/4 passed)
722 ◇ nqyw v3 approved · waiting for 2 checks (no worker building)
723 run: valley approve --build-here nqyw
724 ⊘ nqyw v3 not approved · change is a draft
725 run: valley ready --change <id> <branch>
726 a refusal goes to stderr. checks built here show one
727 line of progress, and a failed check's log. the glyphs
728 are in colour on a terminal unless NO_COLOR is set.
729 -v, --verbose also print what approve read and
730 published: the checks it reuses and who
731 signed them, the tree's digest, the
732 evidence and request refs, and the
733 checks' own output and timings.
734 approve times each required check it runs, and
735 appends one JSON line per check to the timing log,
736 $XDG_STATE_HOME/valley/timings.jsonl (default
737 ~/.local/state/valley/timings.jsonl). the log stays on
738 this machine and is not evidence; a log that cannot be
739 written is a warning, and approving goes on.
740EOF
741 help_naming
742 help_runtime
743}
744
745help_rebase() {
746 cat <<'EOF'
747usage: valley rebase [--known-signers <file>] [--integrator-name <name>] <change>
748
749 rebase [--known-signers <file>] [--integrator-name <name>] <change>
750 rebase the change's whole stack onto origin/main, as
751 review's [b]ase onto main does: the layers valley-go stack
752 lists under the change, and the change itself. in a
753 throwaway worktree, bottom first, each layer's own commits
754 go onto the rebased layer below it, and the bottom's onto
755 origin/main, so each layer keeps its own diff. commits
756 under the bottom that a lower change landed through the
757 integrator drop out, since main holds them; that landing
758 is read as changes reads it, with the signers its two
759 flags, VALLEY_KNOWN_SIGNERS and VALLEY_INTEGRATOR_SIGNER,
760 or the host's publication give. one atomic
761 push then moves every layer's branch, each leased on the
762 tip read: every branch moves, or none does. last, bottom
763 first, each change gains its rebased head as a new
764 version, as valley.principal names, the way ready
765 --if-active does: only while the change is still ready
766 at the head the rebase began with.
767 it refuses, with nothing changed, a stack holding a
768 change that is not ready, records no branch, or whose
769 branch is missing on origin or is not at its recorded
770 head; a plain branch that is the branch of a change not
771 in the stack; two layers on one branch; a merge among the
772 commits to be rebased, or a version head of a change
773 that is not ready or not in the stack, since a rebase
774 gives each commit a new id; and a stack holding a change
775 while git config valley.principal names no one. a
776 conflict in any layer pushes nothing, records nothing
777 and names the layer.
778 a change alone prints its new head. a
779 stack prints a manifest: one line for each layer, with
780 its old and new head, whether its branch was pushed, and
781 whether a version was added. then, for each change left
782 unfinished, the valley ready command that finishes it,
783 and the exit status is non-zero. rebasing again refuses
784 a change whose branch holds a head no version records,
785 and prints the same command. last, it names each ready
786 change or branch outside the stack that is left on an
787 old head of a layer, such as a second stack on a lower
788 layer, with the rebase that moves it; it does not move
789 it. rebase does not re-review the result. a stack that
790 already fast-forwards from main is left as it is.
791EOF
792 help_naming
793 help_runtime
794}
795
796help_status() {
797 cat <<'EOF'
798usage: valley status [--json] [-v] [--known-signers <file>] [--integrator-name <name>] <change>
799
800 status [--json] [-v] [--known-signers <file>] [--integrator-name <name>]
801 <change>
802 read the request and the integrator's last decision from
803 origin. distinguish waiting, a decision that needs
804 attention, and a change integrated into origin/main.
805 a change with a record is read at its active version's
806 head, under c-<change id>, and the status says the
807 version, its title, the owner, and how far the version
808 has landed, as changes reads it. a change that landed
809 as an older version is read at that version's head. a refusal for a record
810 that is not ready, or for a merge in the change's
811 commits, is a state of its own.
812 after integration, show how to update the local checkout.
813 fetches objects without moving local branches or files;
814 no checks run and no request is filed.
815 --json print the status as one JSON object,
816 valley-status/v1, for front ends to read
817 (docs/architecture.md), with the knots
818 in the plan graph that link the change.
819 an error prints no object: it goes to
820 stderr and the exit status is non-zero.
821 -v with --json, warn on stderr when the plan
822 graph is missing or unreadable
823 --known-signers FILE, --integrator-name NAME
824 what a transfer statement is verified
825 with, as changes reads them
826 needs the valley-go helper.
827EOF
828 help_naming
829 help_runtime
830}
831
832help_ready() {
833 cat <<'EOF'
834usage: valley ready [--head <sha>] [--change <id>] [--if-active <sha>] [--stamp] [<branch>]
835
836 ready [--head <sha>] [--change <id>] [--if-active <sha>] [--stamp] [<branch>]
837 mark a head of the branch ready, as a new version of its
838 change, in the change's record on origin:
839 refs/the-valley/changes/main/<change id>. the branch
840 defaults to the current one. the head is --head, or else
841 origin/<branch>, and it must be on origin already. the
842 first ready of a change makes v1; each later one adds
843 the next version, at a head other than the active
844 version's. a draft or a withdrawn change comes back this
845 way: at the active version's head, it is ready again at
846 that version, and at another head it gains the next
847 version. prints the handle and version, e.g.
848 `app nxvp v2 ready`.
849 the change id is --change, else the head commit's jj
850 change-id header, else a Change-Id: trailer in its
851 message, else a new one, which is printed. a header and
852 a trailer that disagree are refused. so is a change
853 whose commits from its merge base with origin/main hold
854 a merge, or that has more than one merge base.
855 --if-active SHA
856 add the version only while the change
857 is ready at an active version whose head
858 is SHA. the record ref is leased on the
859 record read, so nothing comes between
860 that check and the write. rebase readies
861 the head it rebased this way.
862 --stamp amend the head of your local branch to
863 carry the id as a Change-Id: trailer and
864 push the branch, leased, before marking it
865 ready. it only starts a new change: it
866 is refused for a change that has a
867 record on origin already, and for a head
868 already on origin.
869 the record names the principal your key pushes as, read
870 from git config valley.principal; the host refuses one
871 naming anyone else. the record ref is pushed leased on
872 the value read. a new change is owned by the principal
873 that readies it, and a later version may come from its
874 owner, the operator, or a restack holder while the
875 change is ready.
876 a record never makes anything land, and approve is
877 still the only way to main. the integrator reads
878 records only to refuse: it lands no request that would
879 bring a version of a change that is not ready.
880 needs the valley-go helper.
881EOF
882 help_naming
883 help_runtime
884}
885
886help_unready() {
887 cat <<'EOF'
888usage: valley unready <change>
889
890 unready <change>
891 make a ready change a draft in its record on origin, as
892 its owner or the operator. a draft is a pause: it voids
893 nothing, and approvals of its active version stand when
894 it is readied again. ready brings it back. prints e.g.
895 `app nxvp v2 draft`. needs the valley-go helper.
896EOF
897 help_unready_withdraw_requests
898 help_naming
899 help_runtime
900}
901
902help_withdraw() {
903 cat <<'EOF'
904usage: valley withdraw <change>
905
906 withdraw <change>
907 mark a ready change or a draft withdrawn in its record
908 on origin, as its owner or the operator. withdrawing
909 voids everything outstanding on the change: its
910 integration requests, and the approvals and reviews of
911 every version, so a change brought back needs fresh
912 approvals. ready brings it back, at the same version
913 or a new one. prints e.g. `app nxvp v2 withdrawn`.
914 needs the valley-go helper.
915EOF
916 help_unready_withdraw_requests
917 help_naming
918 help_runtime
919}
920
921help_knot() {
922 cat <<'EOF'
923usage: valley knot <verb> [args]
924
925 knot <verb> [args]
926 read and write the project's plan graph: knots, at
927 refs/the-valley/knots on origin. a knot is an outcome,
928 a bug, an idea or a question; `knot schema` prints the
929 types, their statuses, active and terminal, the fields
930 and the edges. a write is one commit on the ref, made
931 without a checkout and pushed with a lease on the tip
932 it was made on; no review is involved. a write that
933 loses the lease is made again on the new tip, up to 5
934 tries. every verb takes --project NAME, another
935 project on the same host, and --json. exit status 3
936 is a conflict. needs the valley-go helper, and
937 git config valley.principal for every write.
938 new <type> <title> [--parent ID] [--blocked-by ID]...
939 [--owner P] [--target PROJECT] [--body -]
940 make a knot. its id is the type's prefix
941 and 7 hex digits of the sha-256 of the
942 title's slug.
943 show <id> [--at COMMIT] [--json]
944 its fields, body and comments, each
945 comment with its id, and the edges both
946 ways. --at shows the knot at a commit of
947 the graph; claim age uses the current
948 clock, and other projects' knots use
949 their current tips.
950 log <id> [--json]
951 every commit of the graph that touched
952 the knot or its comments, newest first:
953 time, committer, operation, and the
954 files it added, changed or deleted
955 list [--type T] [--status S] [--owner P] [--ready]
956 every knot. --status takes a status,
957 active or terminal. --ready lists the
958 active, unclaimed knots whose blockers
959 are all terminal.
960 set <id> <field>=<value>... [--if <field>=<value>]...
961 [--force]
962 change status, title, source, owner,
963 target or graduated_into. a field that
964 another write changed meanwhile is a
965 conflict unless --force. --if requires
966 a field to hold a value first.
967 link <id> (--blocked-by ID | --parent ID | --change X)...
968 unlink <id> (--blocked-by ID | --parent ID | --change X)...
969 add or drop an edge. a change is
970 valley:<project>/<change id> or a github
971 pull request url. outcomes and bugs link
972 the changes that do the work, and a
973 question links the change that records
974 its answer in the source.
975 edit <id> --body -
976 replace the body with stdin
977 comment <id> (-m TEXT | --body -) [--edit COMMENT-ID]
978 add a comment. --edit replaces the body
979 of the comment with that id; its author
980 and file stay, and it records who edited
981 it and when. only the comment's author
982 or a holder of the approve grant may
983 edit it. a comment that another edit
984 changed meanwhile is a conflict.
985 comments are never deleted; log and
986 show --at read every earlier text.
987 claim <id> --run RUN
988 claim an active outcome or bug for a
989 run; an open outcome becomes
990 in-progress. a knot claimed already is
991 a conflict.
992 unclaim <id>
993 release the claim. a claim that
994 changes before the release lands is
995 a conflict.
996 schema [--json]
997 print the model
998EOF
999 help_runtime
1000}
1001
1002help_plan() {
1003 cat <<'EOF'
1004usage: valley plan [--project NAME | --all] [--owner P] [--json] [--known-signers <file>] [--integrator-name <name>]
1005
1006 plan [--project NAME | --all] [--owner P] [--json]
1007 [--known-signers <file>] [--integrator-name <name>]
1008 show the project's plan graph as a tree, to see where
1009 things stand. the roots are the outcomes with no
1010 parent, the milestones, each with its progress: its
1011 descendants that are terminal and not abandoned, out
1012 of those not abandoned, as a count and a bar. under
1013 each come its children, indented, in the order they
1014 were created, then by title. each knot has a glyph for
1015 its state (○ ready, ◐ in progress, ⊘ blocked, ◇
1016 active, ✓ done, ✗ abandoned), its id and title, and,
1017 while active, its claim and the claim's age (marked
1018 stale past a day), its owner, and what blocks it. a
1019 blocker that ended abandoned, discarded, superseded or
1020 dropped clears the knot, and is marked with how it
1021 ended. a reference to another project's knot,
1022 <project>:<id>, is marked dangling when that
1023 project's graph cannot be read or holds no such knot.
1024 a root whose descendants are all terminal is one
1025 line. three sections follow. waiting on you: the
1026 active outcomes and bugs and the open questions the
1027 operator owns, then the changes ready for
1028 approval, as pending lists them. in flight: the
1029 claimed knots, oldest claim first. open residuals:
1030 the open bugs, under their parent. the operator is
1031 git config valley.principal, or --owner. lines fit
1032 the terminal as pending's do; glyphs are coloured on
1033 a terminal unless NO_COLOR is set.
1034 --project NAME another project on the same host
1035 --all every project the serving host
1036 publishes, each under its name, as
1037 pending --all reads them. a project
1038 that cannot be read is reported in
1039 its own section
1040 --owner P read P as the operator
1041 --json print valley-plan/v1: every knot with
1042 what the graph derives of it, and the
1043 three sections (docs/architecture.md)
1044 --known-signers FILE, --integrator-name NAME
1045 what a transfer statement is verified
1046 with, for the changes ready for
1047 approval, as changes reads them
1048 needs the valley-go helper.
1049EOF
1050 help_runtime
1051}
1052
1053help_checks() {
1054 cat <<'EOF'
1055usage: valley checks [--schema FILE] [--instance DIR] [--project DIR] [--names [--cost COST] | --json] [<base> [<head>]]
1056
1057 checks [<base> [<head>]]
1058 print the check names the composed verification policy
1059 (dcr-f41f718) requires of the change between two
1060 commits, which class made each one required, and the
1061 change's carry mode: how far an approval of it carries
1062 across a rebase, the strictest of exact, same-class and
1063 same-paths among the classes it matched. It prints: no
1064 check is run, nothing is gated, nothing is written.
1065 base defaults to the merge base with main, head to HEAD.
1066 by default both layers come from the target's tip
1067 (origin/main), never from your checkout: the project's
1068 own layer is policy/project there, and the owning valley
1069 is named one line at policy/valley there, fetched and
1070 read at policy/instance in that repository's integrated
1071 tip. a valley's own config repository carries
1072 policy/instance and uses it. a target carrying no
1073 policy/project is derived under the floor alone; a floor
1074 that is not there is refused. this is what the
1075 integrator reads, so the answer is the same from any
1076 branch, however stale. an option overrides each layer,
1077 which is the only way to derive against a layer that
1078 does not govern — the worked example under
1079 examples/policy/, say:
1080 --schema FILE default $VALLEY_VERIFICATION_SCHEMA
1081 --instance DIR default the owning valley's floor
1082 --project DIR default policy/project at the target
1083 naming a layer stops this reading the source it
1084 replaced. the schema is the shape a policy is written
1085 in rather than a layer, so it ships with this tool: the
1086 package sets VALLEY_VERIFICATION_SCHEMA to its own copy.
1087 with that unset, as when this script runs straight from
1088 a the-valley checkout, it is schema/verification.cue in
1089 the checkout.
1090 a class's globs match bytes, whatever your locale
1091 is: `?` is one byte, so `?.md` does not match
1092 é.md, whose é is two.
1093 after the report, two lines group the required checks
1094 by the cost the policy declares, `quick` or `slow`. a
1095 slow check takes minutes or needs special hardware. the
1096 cost changes nothing required: approving runs every
1097 required check whatever its cost, and the integrator
1098 requires evidence for every one.
1099 --names print only the required check names,
1100 one per line
1101 --cost COST with --names, only the quick or
1102 the slow ones, e.g.
1103 `valley checks --names --cost slow`
1104 --json print the valley-checks/v1 document
1105 instead of the report
1106EOF
1107 help_runtime
1108}
1109
1110help_tail() {
1111 cat <<'EOF'
1112usage: valley tail [subject]
1113
1114 tail [subject] watch bus events scroll by (default subject: valley.>);
1115 the server comes from the nats CLI's own config
1116 (NATS_URL or a nats context; default localhost)
1117EOF
1118 help_runtime
1119}
1120
1121help_replay() {
1122 cat <<'EOF'
1123usage: valley replay [dir]
1124
1125 replay [dir] publish one ref-updated event per current ref of the
1126 repo at dir (default: .) — rebuilds the stream's
1127 projection, e.g. after nats stream purge valley
1128EOF
1129 help_runtime
1130}
1131
1132help_telemetry() {
1133 cat <<'EOF'
1134usage: valley telemetry [--remote <remote>] [--json] <operation> [flags]
1135
1136 sources every source the host declares, and its state:
1137 disabled, unavailable, failed, stale, active or
1138 idle, with its units, its records and how far its
1139 journal reaches
1140 snapshot sources, with each producer's exported state and
1141 its open and latest runs
1142 read [--source <name>] [--since <cursor>] [--limit <n>] [--logs]
1143 records after the cursor (default: the newest
1144 --limit, 200, at most 1000); a source's systemd
1145 lifecycle from the journal; with --logs, its own
1146 output and the tail of its build logs, marked
1147 untrusted
1148 follow [--source <name>] [--since <cursor>] [--seconds <n>] [--logs]
1149 records as they are stored, and with --logs build
1150 output as it is written, for --seconds (default
1151 60, at most 300); ends with a cursor to resume from
1152 flush send this workstation's spooled records now
1153
1154Reading needs a key whose principal holds the host's observe grant. The
1155remote is the checkout's valley.telemetry.remote, else origin, or the one
1156--remote names (a remote, an ssh URL, or user@host:path); its URL is read
1157and never run. --json prints the valley-telemetry/v1 answer lines as they
1158come. A gap, a cut-short answer or an error is said; an answer that does
1159not end exits 1.
1160
1161With `git config valley.telemetry true`, every valley command records a
1162command record: its verb (and knot's or telemetry's subverb), the names of
1163the flags it was given, its project, its exit status and its wall time,
1164and for pending and status the milliseconds and processes each phase took.
1165It never records an argument's value, a path, a title or a body. Every
1166approval attempt, from approve or from review, also records its steps and
1167its checks' progress. Records go to an owner-only spool for the
1168destination the checkout's telemetry remote names, under
1169$XDG_STATE_HOME/valley/telemetry/spools. A background flusher sends each
1170spool to its own destination, with the report grant; flush does the same
1171now, and --remote limits it to that remote's spool. Telemetry never fails
1172or holds up a command, and changes nothing it prints.
1173EOF
1174}
1175
1176help_self_update() {
1177 if command -v valley-go > /dev/null 2>&1; then
1178 valley-go self-update --help
1179 printf '\n'
1180 else
1181 cat <<'EOF'
1182usage: valley self-update [-v] [--retry | --rollback | --pin | --unpin]
1183 [--repo <url>] [--branch <name>]
1184
1185EOF
1186 fi
1187 cat <<'EOF'
1188 self-update [-v] [--retry | --rollback | --pin | --unpin]
1189 [--repo <url>] [--branch <name>]
1190 install the tip of a branch of the-valley into your
1191 default nix profile, in place of its valley element,
1192 once that exact commit builds and passes a smoke test.
1193 a commit that fails is skipped until the branch moves,
1194 or until --retry. it is off until --repo or
1195 git config valley.selfUpdate.repo names the
1196 repository; the branch is valley.selfUpdate.branch,
1197 or main. --rollback reinstalls the previous build, and
1198 --pin and --unpin freeze and release the install.
1199 `valley-go self-update --help` gives every step. needs
1200 the valley-go helper and nix.
1201
1202 --version print this valley's version: the package's version and
1203 the commit it was built from, e.g. 0.1.0-97db597, with
1204 -dirty after it for a tree with uncommitted changes and
1205 -unknown in its place when nix knew no commit. run
1206 straight from a checkout, it says it is unstamped.
1207EOF
1208 help_runtime
1209}
1210
1211fetch_origin() {
1212 git fetch --prune --quiet origin
1213}
1214
1215# ref_oid <ref>: the object ID that ref, a full ref name, holds here, read
1216# by that exact name with show-ref. 1 no such ref, 2 a read that failed.
1217#
1218# git rev-parse, and every git command given a ref name, does not stop at
1219# the name it is given. For a missing refs/remotes/origin/main it goes on
1220# to try other names, refs/tags/refs/remotes/origin/main and
1221# refs/heads/refs/remotes/origin/main among them, and a fetch can bring the
1222# first from origin. So a ref is read here once, and what it held is read
1223# through the object ID from then on.
1224ref_oid() {
1225 local rc
1226 git show-ref --exists --end-of-options "$1" 2> /dev/null && rc=0 || rc=$?
1227 case "$rc" in
1228 0) git show-ref --verify --hash --end-of-options "$1" || return 2 ;;
1229 2) return 1 ;;
1230 *) return 2 ;;
1231 esac
1232}
1233
1234# Resolve the pager as git would for a diff: pager.diff first (per-command
1235# pager configs — e.g. home-manager's delta module — set pager.diff and leave
1236# core.pager alone), then git var GIT_PAGER (core.pager, GIT_PAGER, PAGER,
1237# less). pager.<cmd> may legally be a boolean; treat true/false — and an
1238# empty or missing value — as unset and fall back. The value is
1239# shell-interpreted, hence sh -c.
1240diff_pager() {
1241 local pager
1242 pager="$(git config --get pager.diff || true)"
1243 case "$pager" in '' | true | false) pager="$(git var GIT_PAGER)" ;; esac
1244 printf '%s' "$pager"
1245}
1246
1247# Page a file rather than a pipe, so less's v key has something to hand
1248# $EDITOR. That file is the review buffer, and editing it is how notes get
1249# written (see collect_notes). A pipe has no name, so less refuses to edit
1250# one.
1251#
1252# The configured diff pager stays the renderer, run once as a filter into a
1253# sibling file that less pages. v runs LESSEDIT, which opens the editor on
1254# the raw buffer, not the rendering, and renders it again when the editor
1255# exits, so the view less reopens shows the notes in place. The editor is
1256# the one less's %E names: VISUAL, then EDITOR, then vi, each a shell
1257# command line. Paths reach LESSEDIT through the environment, since it is a
1258# prompt string in which % ? . : and \ are special.
1259#
1260# What this costs is the line number. v opens the editor at +%lm, a line
1261# of the rendered view, so a filter that restructures the diff — delta's
1262# default rendering does — opens it near the cursor rather than on it. A
1263# structure-preserving filter (pager.diff = `delta --color-only`) makes it
1264# exact. No anchor depends on it: a note is anchored by where it was
1265# inserted, not by where the editor opened.
1266#
1267# valley-go style (status/style.go) is the rendering's last step, after
1268# the pager, so the pager never reads its escapes and the raw buffer has
1269# none. It keeps every line in its place.
1270page_file() {
1271 local file="$1" shown="${1%.diff}.shown" pager view=less
1272 [ -t 1 ] || { cat -- "$file"; return; } # a non-tty just cats
1273 pager="$(diff_pager)"
1274 case "${pager%%[[:space:]]*}" in
1275 less | */less)
1276 # Already less, with its options: the rendering is style's alone, and
1277 # without it there is no filter to run, so less is given the file.
1278 command -v valley-go > /dev/null 2>&1 || { sh -c "$pager \"\$1\"" sh "$file"; return; }
1279 view="$pager" pager='cat'
1280 ;;
1281 esac
1282 # Without less there is no editor key; fall back to filtering into a pipe.
1283 command -v less > /dev/null 2>&1 || {
1284 sh -c "$pager" < "$file"
1285 return
1286 }
1287 ! command -v valley-go > /dev/null 2>&1 || pager="$pager | valley-go style --paged"
1288 sh -c "$pager" < "$file" > "$shown"
1289 # -R because the filter's color is the whole point of running it. No
1290 # LESSOPEN, since the filter has run and less answers v on a file read
1291 # through one with a warning, then runs the editor on whatever key comes
1292 # next, q included; and so no LESSCLOSE.
1293 # shellcheck disable=SC2016 # expanded by the shells LESSEDIT starts
1294 VALLEY_PAGE_RAW="$file" VALLEY_PAGE_SHOWN="$shown" VALLEY_PAGE_RENDER="$pager" \
1295 VALLEY_PAGE_EDIT='eval "${VISUAL:-${EDITOR:-vi}} \"\$@\" \"\$VALLEY_PAGE_RAW\""
1296 sh -c "$VALLEY_PAGE_RENDER" < "$VALLEY_PAGE_RAW" > "$VALLEY_PAGE_SHOWN"' \
1297 LESSEDIT='sh -c "$VALLEY_PAGE_EDIT" sh ?lm+%lm.' \
1298 env -u LESSOPEN -u LESSCLOSE sh -c "$view -R -- \"\$1\"" sh "$shown"
1299}
1300
1301# pending is valley-go's (status/pending.go). The fetch first keeps this
1302# checkout's remote-tracking branches current, as pending always has.
1303cmd_pending() {
1304 command -v valley-go > /dev/null 2>&1 \
1305 || die "pending needs the valley-go helper; nix run .#valley bundles it"
1306 fetch_origin
1307 VALLEY_TELEMETRY_SINCE="$TEL_T0" VALLEY_TELEMETRY_VERSION="$VALLEY_STAMP" \
1308 exec valley-go pending "$@"
1309}
1310
1311# For a change with a record, what is rejected is the head its record
1312# names. So the branch is deleted only while its tip is that head, and the
1313# delete is leased on it. When the tip is another commit, reject refuses
1314# and names both, and deletes nothing. A branch no record names is deleted
1315# as before.
1316#
1317# reject runs inside a condition, where bash suspends `set -e`, so the push
1318# is checked by hand.
1319reject() {
1320 local branch="$1" answer
1321 local -a lease=()
1322 if [ -n "$CHANGE_HEAD" ]; then
1323 check_recorded_tip "$branch" "nothing deleted" || {
1324 WALK_REFUSED=yes
1325 return 1
1326 }
1327 lease=("--force-with-lease=refs/heads/$branch:$CHANGE_HEAD")
1328 fi
1329 printf 'really delete origin/%s? [y/N] ' "$branch"
1330 read -r answer || answer=""
1331 case "$answer" in
1332 y | Y | yes)
1333 # The change may have moved while the confirmation waited: say so,
1334 # and delete nothing.
1335 ! moved || return 0
1336 if ! git push --quiet "${lease[@]}" origin --delete "$branch"; then
1337 refuse "origin did not delete $branch, which may have moved since the fetch; nothing deleted"
1338 WALK_REFUSED=yes
1339 return 1
1340 fi
1341 echo "rejected $branch: deleted from origin"
1342 walk_outcome rejected "$branch"
1343 ;;
1344 *)
1345 echo "kept $branch"
1346 walk_outcome kept "$branch"
1347 ;;
1348 esac
1349}
1350
1351# ----------------------------------------------------------------------
1352# review notes — the lines the reviewer inserts into the paged diff.
1353#
1354# The buffer the reviewer pages is a file, so the pager's editor key can open
1355# it (page_file). Whatever comes back with lines inserted is read as notes:
1356# no marker, no syntax, no mode — an inserted line is a note because it was
1357# not there before. What a note is *about* is where it sits, so each one is
1358# anchored to the file and the new-side line number of the diff line above
1359# it, which is the pair a reviewer would otherwise have to copy out by hand.
1360
1361# The scratch directory holding the buffer and its pristine copy, and the
1362# notes taken so far in this review — a global because [b]ase onto main
1363# pages a second time and the notes from the first pass are not thereby
1364# withdrawn.
1365REVIEW_TMP=""
1366NOTES=()
1367
1368cleanup_review_tmp() {
1369 [ -n "$REVIEW_TMP" ] || return 0
1370 rm -rf "$REVIEW_TMP"
1371 REVIEW_TMP=""
1372}
1373
1374# Where a branch's notes live. XDG_STATE_HOME is the right home for them:
1375# they are neither config nor cache, and losing them loses judgment.
1376notes_file() {
1377 printf '%s/valley/notes/%s.md\n' "${XDG_STATE_HOME:-$HOME/.local/state}" "$1"
1378}
1379
1380# The anchor of every line of the buffer, by line: the file that line belongs
1381# to, and the new-side line number it sits on. Built in one pass so that
1382# anchoring a note is a lookup. An empty path means the line is above every
1383# file (the log); line 0 means the line is a file header, above every hunk.
1384ANCHOR_PATH=()
1385ANCHOR_LINE=()
1386
1387anchor_buffer() {
1388 local file="$1" line path="" at=0 next=0 inhunk=0 rest
1389 ANCHOR_PATH=()
1390 ANCHOR_LINE=()
1391 while IFS= read -r line; do
1392 # Header lines are only headers outside a hunk: inside one, every line
1393 # carries a +/-/space prefix, so a diff of a diff cannot be misread.
1394 if [ "$inhunk" -eq 1 ]; then
1395 case "$line" in
1396 ' '* | '+'* | '')
1397 at="$next" # this line's own new-side number
1398 next=$((next + 1))
1399 ;;
1400 '-'* | \\*) ;; # a removal or the no-newline marker: no new-side line
1401 *) inhunk=0 ;;
1402 esac
1403 fi
1404 if [ "$inhunk" -eq 0 ]; then
1405 case "$line" in
1406 'diff --git '*)
1407 path=""
1408 # The b/ side, so a rename anchors to the name it will have.
1409 if [[ "$line" =~ ^diff\ --git\ a/(.*)\ b/(.*)$ ]]; then
1410 path="${BASH_REMATCH[2]}"
1411 fi
1412 at=0
1413 ;;
1414 '@@ '*)
1415 rest="${line#*+}" # -12,7 +34,9 @@ -> 34,9 @@
1416 at="${rest%%[!0-9]*}"
1417 [ -n "$at" ] || at=0
1418 next="$at"
1419 inhunk=1
1420 ;;
1421 esac
1422 fi
1423 ANCHOR_PATH+=("$path")
1424 ANCHOR_LINE+=("$at")
1425 done < "$file"
1426}
1427
1428# The anchor for a note inserted after buffer line n, as it is written down.
1429anchor_of() {
1430 local n="$1" path line
1431 [ "$n" -ge 1 ] || { printf '(unanchored)'; return; }
1432 path="${ANCHOR_PATH[n - 1]:-}"
1433 line="${ANCHOR_LINE[n - 1]:-0}"
1434 if [ -z "$path" ]; then
1435 printf '(unanchored)'
1436 elif [ "$line" -eq 0 ]; then
1437 printf '%s' "$path"
1438 else
1439 printf '%s:%s' "$path" "$line"
1440 fi
1441}
1442
1443# The notes in an edited buffer, one `anchor: text` line each. git says where
1444# the reviewer's lines landed; a hunk that removes nothing is an insertion,
1445# and the line it was inserted after is the anchor. A hunk that removes
1446# something is an edit of the diff itself — it anchors to nothing, since the
1447# line it would name is the line it changed — so it is dropped with a count.
1448notes_in() {
1449 local orig="$1" edited="$2" line rest at old insert=0 touched=0 text
1450 anchor_buffer "$orig"
1451 while IFS= read -r line; do
1452 case "$line" in
1453 '@@ '*)
1454 rest="${line#@@ -}" # 12,0 +13,2 @@ -> 12,0 +13,2 @@
1455 at="${rest%%[!0-9]*}"
1456 rest="${rest#"$at"}"
1457 old=1
1458 case "$rest" in
1459 ,*)
1460 rest="${rest#,}"
1461 old="${rest%%[!0-9]*}"
1462 ;;
1463 esac
1464 if [ "$old" -eq 0 ]; then
1465 insert=1
1466 else
1467 insert=0
1468 touched=$((touched + old))
1469 fi
1470 ;;
1471 '+'*)
1472 # Only inside an insertion hunk: the +++ of git's own header is not
1473 # a note, and neither is the new side of an edit.
1474 [ "$insert" -eq 1 ] || continue
1475 text="${line#+}"
1476 text="${text#"${text%%[![:space:]]*}"}"
1477 [ -n "$text" ] || continue # a blank line says nothing
1478 printf '%s: %s\n' "$(anchor_of "$at")" "$text"
1479 ;;
1480 esac
1481 done < <(git --no-pager diff --no-ext-diff --no-index -U0 -- "$orig" "$edited")
1482 [ "$touched" -eq 0 ] || printf \
1483 'valley: warning: %d changed or deleted diff line(s) ignored — a note is a line you insert\n' \
1484 "$touched" >&2
1485}
1486
1487# Read the notes out of the paged buffer and keep them: appended to the
1488# branch's notes file under the commit they were taken against, and held for
1489# the print that follows the verdict. A notes file that cannot be written is
1490# a warning, never a failure — the notes are still printed, and a review is
1491# not undone by a missing directory.
1492collect_notes() {
1493 local branch="$1" sha="$2" file dir
1494 local -a found=()
1495 mapfile -t found < <(notes_in "$REVIEW_TMP/review.orig" "$REVIEW_TMP/review.diff")
1496 [ "${#found[@]}" -gt 0 ] || return 0
1497 NOTES+=("${found[@]}")
1498 file="$(notes_file "$branch")"
1499 dir="${file%/*}"
1500 mkdir -p "$dir" 2> /dev/null && {
1501 printf '## %s at %s\n\n' "$branch" "$sha"
1502 printf '%s\n' "${found[@]}"
1503 printf '\n'
1504 } >> "$file" 2> /dev/null && return 0
1505 printf 'valley: warning: could not write %s — the notes are printed only\n' \
1506 "$file" >&2
1507}
1508
1509print_notes() {
1510 local branch="$1"
1511 [ "${#NOTES[@]}" -gt 0 ] || return 0
1512 printf '\n%d note(s) on %s, appended to %s:\n' \
1513 "${#NOTES[@]}" "$branch" "$(notes_file "$branch")"
1514 printf ' %s\n' "${NOTES[@]}"
1515}
1516
1517# ----------------------------------------------------------------------
1518# review sets the version it shows of a change against the change's
1519# approved version: the greatest version below it whose head a request or
1520# an outcome on origin names (valley-go compare, status/compare.go). The
1521# logic is valley-go's, and this script prints what it says:
1522#
1523# - none: there is no approved version to compare with, so review pages
1524# the whole diff, as for any change. Any note valley-go gives, such as
1525# an approved version it could not compare, heads the page.
1526# - clean: the file delta is the approved version's. review prints that
1527# in a few lines, with the landings between the two bases, and pages
1528# nothing.
1529# - changed: review pages the files whose change differs, with the
1530# landings that edited them, the range-diff when a commit was edited,
1531# and the shown version's diff of those files. range-diff's hunks
1532# carry no line numbers, so a note taken beside them is unanchored.
1533# That last diff is in git's ordinary form, so a note taken there
1534# keeps its file and line (anchor_buffer).
1535#
1536# A changed commit message or author is in valley-go's text either way.
1537# [v]iew full diff pages the whole diff at every prompt. The comparison
1538# files no request and skips no check: [a]pprove is the same act whatever
1539# it says.
1540#
1541# compare_shown <change ID> <version> <head>: compare the version shown,
1542# against main's tip as the fetch left it. Leaves none, clean or changed
1543# in COMPARE_KIND, and the text to show in $REVIEW_TMP/compare. A plain
1544# branch is none, and so is a comparison valley-go could not make, with a
1545# warning.
1546COMPARE_KIND=none
1547compare_shown() {
1548 local out="$REVIEW_TMP/compare.out" tip
1549 COMPARE_KIND=none
1550 : > "$REVIEW_TMP/compare"
1551 [ -n "$1" ] || return 0
1552 if ! tip="$(ref_oid refs/remotes/origin/main)" \
1553 || ! valley-go compare ${VERBOSE:+-v} --tip "$tip" "$1" "$2" "$3" > "$out"; then
1554 printf 'valley: warning: could not compare v%s of change %s with its approved version; reviewing it in full\n' \
1555 "$2" "$1" >&2
1556 return 0
1557 fi
1558 IFS= read -r COMPARE_KIND < "$out" || COMPARE_KIND=""
1559 case "$COMPARE_KIND" in
1560 none | clean | changed) tail -n +2 "$out" > "$REVIEW_TMP/compare" ;;
1561 *)
1562 printf 'valley: warning: valley-go compare answered %s, which this script does not read; reviewing it in full\n' \
1563 "$COMPARE_KIND" >&2
1564 COMPARE_KIND=none
1565 ;;
1566 esac
1567}
1568
1569# show_compared <notes key> <head> <heading> <knots> <writer> [<arg>…]:
1570# show what compare_shown found, under the heading when there is one. A
1571# clean restack is printed, and nothing is paged. A changed version pages
1572# the comparison. Otherwise the writer writes the whole diff, and it is
1573# paged. Notes taken in a page are kept under the notes key, against the
1574# head.
1575#
1576# Knots follow the heading when there is one. Otherwise they follow the
1577# first line of the comparison or full diff, which names the change.
1578show_compared() {
1579 local key="$1" sha heading="$3" knots="$4"
1580 sha="$(git rev-parse --short "$2")"
1581 shift 4
1582 {
1583 if [ -n "$heading" ]; then
1584 printf '%s\n' "$heading"
1585 [ -z "$knots" ] || printf '%s\n' "$knots"
1586 cat "$REVIEW_TMP/compare"
1587 [ "$COMPARE_KIND" != none ] || "$@"
1588 else
1589 {
1590 cat "$REVIEW_TMP/compare"
1591 [ "$COMPARE_KIND" != none ] || "$@"
1592 } | under_first "$knots"
1593 fi
1594 } > "$REVIEW_TMP/review.diff"
1595 if [ "$COMPARE_KIND" = clean ]; then
1596 valley-go style < "$REVIEW_TMP/review.diff"
1597 cleanup_review_tmp
1598 else
1599 page_buffer "$key" "$sha"
1600 fi
1601}
1602
1603# under_first <lines>: copy stdin, inserting <lines> after the first line.
1604under_first() {
1605 local first
1606 IFS= read -r first || [ -n "$first" ] || return 0
1607 printf '%s\n' "$first"
1608 [ -z "$1" ] || printf '%s\n' "$1"
1609 cat
1610}
1611
1612# DOES caches the output of `valley-go does` for the review (status/does.go):
1613# one `<change ID>\tdoes <knot ID> (<status>): <title>` line per knot.
1614# The checks line takes seconds to read: it reads the policy and the host's
1615# telemetry. So read_does starts `valley-go checkline`
1616# (status/versionchecks.go) in the background, and it writes one
1617# `<change ID>\tchecks: …` line for each ready change into REVIEW_CHECKS_TMP: the
1618# state of its checks and what they cost the host's check worker to build,
1619# as pending --checks shows it. The diff is shown without waiting for it.
1620# checks_line prints a change's line when the read has finished, just
1621# before the prompt, and prints nothing when it has not (it waits at most
1622# VALLEY_REVIEW_CHECKS_WAIT seconds, 0 unless set). REVIEW_CHECKS_PID is the
1623# background read, REVIEW_CHECKS_SHOWN the change IDs whose line is not shown
1624# again, REVIEW_CHECKS_IDS the changes it reads, and
1625# REVIEW_CHECKS_VERBOSE whether to pass on what the read said on stderr.
1626DOES=""
1627REVIEW_CHECKS_TMP=""
1628REVIEW_CHECKS_PID=""
1629REVIEW_CHECKS_SHOWN=" "
1630REVIEW_CHECKS_VERBOSE=""
1631REVIEW_CHECKS_IDS=()
1632
1633# read_does [-v]: read the plan graph once for every change in the review,
1634# and start reading their checks. A missing or unreadable graph leaves DOES
1635# empty; -v warns on stderr.
1636read_does() {
1637 local ids=() k
1638 DOES=""
1639 if [ "${#L_NAME[@]}" -gt 1 ]; then
1640 for ((k = 0; k < ${#L_ID[@]}; k++)); do
1641 [ -z "${L_ID[k]}" ] || ids+=("${L_ID[k]}")
1642 done
1643 elif [ -n "$CHANGE_ID" ]; then
1644 ids=("$CHANGE_ID")
1645 fi
1646 [ "${#ids[@]}" -gt 0 ] || return 0
1647 DOES="$(valley-go does "$@" "${ids[@]}")" || DOES=""
1648 REVIEW_CHECKS_IDS=("${ids[@]}")
1649 REVIEW_CHECKS_VERBOSE="${1:-}"
1650 start_checks_read
1651}
1652
1653# start_checks_read: read the checks of REVIEW_CHECKS_IDS in the background,
1654# in place of any read already started.
1655start_checks_read() {
1656 cleanup_checks_tmp
1657 REVIEW_CHECKS_TMP="$(mktemp -d)"
1658 REVIEW_CHECKS_SHOWN=" "
1659 valley-go checkline "${REVIEW_CHECKS_IDS[@]}" > "$REVIEW_CHECKS_TMP/out" 2> "$REVIEW_CHECKS_TMP/err" &
1660 REVIEW_CHECKS_PID=$!
1661}
1662
1663# checks_line <change ID>: print the `checks: …` line of one change, once,
1664# if the background read has finished and gave it one. It never waits.
1665checks_line() {
1666 local line
1667 [ -n "$REVIEW_CHECKS_PID" ] && [ -n "$1" ] || return 0
1668 case "$REVIEW_CHECKS_SHOWN" in *" $1 "*) return 0 ;; esac
1669 # Normally the read has had the whole time the diff was read in. A host
1670 # that wants the line at the prompt can have review wait for it.
1671 local waited=0 limit="${VALLEY_REVIEW_CHECKS_WAIT:-0}"
1672 case "$limit" in '' | *[!0-9]*) limit=0 ;; esac
1673 while kill -0 "$REVIEW_CHECKS_PID" 2> /dev/null; do
1674 [ "$waited" -lt "$((limit * 10))" ] || return 0
1675 sleep 0.1
1676 waited=$((waited + 1))
1677 done
1678 if [ -n "$REVIEW_CHECKS_VERBOSE" ] && [ -s "$REVIEW_CHECKS_TMP/err" ]; then
1679 cat "$REVIEW_CHECKS_TMP/err" >&2
1680 : > "$REVIEW_CHECKS_TMP/err"
1681 fi
1682 while IFS= read -r line; do
1683 if [ "${line%%$'\t'*}" = "$1" ]; then
1684 printf '%s\n' "${line#*$'\t'}"
1685 REVIEW_CHECKS_SHOWN+="$1 "
1686 fi
1687 done < "$REVIEW_CHECKS_TMP/out"
1688}
1689
1690# cleanup_checks_tmp: stop the background read of the checks, if it still
1691# runs, and remove what it wrote.
1692cleanup_checks_tmp() {
1693 if [ -n "$REVIEW_CHECKS_PID" ]; then
1694 kill "$REVIEW_CHECKS_PID" 2> /dev/null || true
1695 REVIEW_CHECKS_PID=""
1696 fi
1697 [ -z "$REVIEW_CHECKS_TMP" ] || rm -rf "$REVIEW_CHECKS_TMP"
1698 REVIEW_CHECKS_TMP=""
1699}
1700
1701# does_of <change ID>: print the `does ...` lines for one change from DOES.
1702does_of() {
1703 local line
1704 [ -n "$1" ] || return 0
1705 while IFS= read -r line; do
1706 [ "${line%%$'\t'*}" != "$1" ] || printf '%s\n' "${line#*$'\t'}"
1707 done <<< "$DOES"
1708}
1709
1710# full_diff <branch> <head>: the whole diff of a change alone: its log
1711# and its diff against origin/main. main is read by its exact name, since
1712# git would take a tag named origin/main for it.
1713full_diff() {
1714 local sha tip
1715 sha="$(git rev-parse --short "$2")"
1716 tip="$(ref_oid refs/remotes/origin/main)" || return 1
1717 if [ -n "$CHANGE_HEAD" ]; then
1718 printf 'change %s v%s at %s, on branch %s, log against origin/main:\n\n' \
1719 "$CHANGE_HANDLE" "$CHANGE_VERSION" "$sha" "$1"
1720 else
1721 printf 'branch %s, log against origin/main:\n\n' "$1"
1722 fi
1723 commit_log "$tip..$2"
1724 git --no-pager diff "$tip...$2"
1725}
1726
1727# commit_log <range>: each commit in <range>, newest first: its short hash
1728# and subject, its body indented four spaces, and a blank line. The whole
1729# message is shown because a change lands with its head commit's. The
1730# indent keeps a body line from reading as a diff header, to the notes'
1731# anchors and to the diff pager alike.
1732commit_log() {
1733 git --no-pager log --format='%h %s%n%w(0,4,4)%b' "$1"
1734}
1735
1736# show_review <branch>: show a change alone. A change that is not ready
1737# says so first, before anything else shown of it (shown_not_ready). That
1738# notice becomes the heading, so the change's knots follow it.
1739show_review() {
1740 local branch="$1" head held
1741 head="$(change_head "$branch")"
1742 # [a]pprove approves exactly the head shown here (bind_review).
1743 [ -n "$CHANGE_ID" ] || APPROVE_HEAD="$head"
1744 held="$(shown_not_ready)" || held=""
1745 REVIEW_TMP="$(mktemp -d)"
1746 compare_shown "$CHANGE_ID" "$CHANGE_VERSION" "$head"
1747 show_compared "$branch" "$head" "$held" "$(does_of "$CHANGE_ID")" full_diff "$branch" "$head"
1748 REVIEW_CHECKS="$(checks_line "$CHANGE_ID")"
1749}
1750
1751# view_full <branch>: [v]iew full diff for a change alone. It pages the
1752# change's whole diff, and keeps the notes taken in it.
1753view_full() {
1754 local head
1755 head="$(change_head "$1")"
1756 REVIEW_TMP="$(mktemp -d)"
1757 full_diff "$1" "$head" > "$REVIEW_TMP/review.diff"
1758 page_buffer "$1" "$(git rev-parse --short "$head")"
1759}
1760
1761# page_buffer <branch> <sha>: page the buffer written to REVIEW_TMP, and
1762# keep the notes taken in it under the branch, against the commit shown.
1763page_buffer() {
1764 cp "$REVIEW_TMP/review.diff" "$REVIEW_TMP/review.orig"
1765 page_file "$REVIEW_TMP/review.diff" || true # quitting the pager early is not an error
1766 collect_notes "$1" "$2"
1767 cleanup_review_tmp
1768}
1769
1770# Everything review leaves outside the repository: the paged buffer and
1771# the checks' scratch. One handler, installed once, so that no path
1772# through review, and no ctrl-C in the pager, leaves any of them behind.
1773# The worktrees of a rebase and of an approval's checks are valley-go's,
1774# which removes them itself.
1775cleanup_scratch() {
1776 local status=$?
1777 # A walk's step with no outcome yet was cut short: by a signal, or by a
1778 # step that ended the session.
1779 if [ -z "$WALK_WRITTEN" ]; then
1780 if [ "$status" -eq 130 ]; then walk_outcome interrupted; else walk_outcome error; fi
1781 fi
1782 cleanup_review_tmp
1783 cleanup_checks_tmp
1784 tel_command "$status"
1785}
1786
1787# A stack's [b]ase onto main and the rebase verb are one piece of code,
1788# valley-go rebase (status/rebase.go). It rebases the change's whole
1789# stack in a throwaway worktree of its own — the user's checkout is never
1790# touched — pushes
1791# every layer's branch in one atomic push, leased on the tips it read, and
1792# adds each change's rebased head to its record as a new version. A
1793# change alone prints what rebase always has; a stack prints a manifest
1794# of what became of each layer. The judgment on the rebased diff stays
1795# with the human, back at the review prompt or in whatever front end ran
1796# the rebase verb.
1797#
1798# rebase_shown <head>: [b]ase onto main for the stack under review, while
1799# its top is still at <head>, the head review showed of it.
1800rebase_shown() {
1801 valley-go rebase --head "$1" "${CHANGE_ID:-$CHANGE_NAME}" || return
1802 # What the checks read was for the heads before the rebase.
1803 [ -z "$REVIEW_CHECKS_PID" ] || start_checks_read
1804}
1805
1806# ----------------------------------------------------------------------
1807# approve — file an integration request for the change under review,
1808# which valley-go approve does (status/approve.go). Nothing in this script
1809# writes the protected ref.
1810
1811# Report and fail, without leaving the review. A refusal here is not a
1812# reason to end the session: the branch is still under review and the
1813# operator can still answer. die() is for the verbs that have nothing left
1814# to offer.
1815refuse() {
1816 printf 'valley: %s\n' "$*" >&2
1817 return 1
1818}
1819
1820# The head approve last ran the checks over and saw them fail, for the
1821# review prompt: see approve_failed_at.
1822CHECKS_FAILED_AT=""
1823# The checks line review read for the change it shows (checks_line), for
1824# the header of its prompt.
1825REVIEW_CHECKS=""
1826
1827# Set by --build-here and -v on review, and passed to its [a]pprove
1828# (approve): --build-here builds the required nix checks origin holds no
1829# evidence for on this machine, and -v prints what approve read and
1830# published.
1831BUILD_HERE=""
1832VERBOSE=""
1833
1834# approve <branch>: review's [a]pprove, one approval attempt of its own
1835# for each answer, a stack's layers included. valley-go approve
1836# (status/approve.go) runs it on review's own terminal, told the change
1837# and head review bound, and the name as typed, which it reads again
1838# before filing. It writes how the attempt ended to a file: approved, with
1839# what it filed; checks-failed, with the head the checks failed at, which
1840# the prompt stops offering [a]pprove for (approve_failed_at); refused or
1841# unknown; or interrupted, which ends the review as a ctrl-C does. Fails
1842# unless it filed.
1843approve() {
1844 local outcome line="" kind id handle version head
1845 local -a bound=(--branch "$1")
1846 [ -z "$APPROVE_HEAD" ] || bound+=(--shown "$APPROVE_HEAD")
1847 if [ -n "$CHANGE_ID" ]; then
1848 bound=(--change "$CHANGE_ID" --handle "$CHANGE_HANDLE" --version "$APPROVE_VERSION" --head "$APPROVE_HEAD")
1849 fi
1850 if outcome="$(mktemp)"; then
1851 VALLEY_TELEMETRY_VERSION="$VALLEY_STAMP" valley-go approve --reviewing --name "$CHANGE_NAME" \
1852 --outcome "$outcome" "${bound[@]}" ${BUILD_HERE:+--build-here} ${VERBOSE:+-v} \
1853 ${CARRIED:+--carried} || true
1854 line="$(cat -- "$outcome" 2> /dev/null)" || line=""
1855 rm -f -- "$outcome"
1856 fi
1857 read_resolved "$line" kind id handle version head
1858 case "$kind" in
1859 approved)
1860 walk_outcome approved "$id" "$handle" "$version" "$head"
1861 return 0
1862 ;;
1863 checks-failed) CHECKS_FAILED_AT="$id" ;;
1864 interrupted) exit 130 ;;
1865 refused | unknown) ;;
1866 *) printf 'valley: warning: the approval left no outcome; taking it as refused\n' >&2 ;;
1867 esac
1868 WALK_REFUSED=yes
1869 return 1
1870}
1871
1872# tel_command <status>: the command record of a verb this script runs
1873# itself, handed to valley-go as the script exits, once. valley-go decides
1874# whether telemetry is on; the verbs this script execs it for it records
1875# itself.
1876TEL_ARGS=()
1877tel_command() {
1878 [ ${#TEL_ARGS[@]} -gt 0 ] || return 0
1879 local -a args=("${TEL_ARGS[@]}")
1880 TEL_ARGS=()
1881 valley-go telemetry command --since "$TEL_T0" --version "$VALLEY_STAMP" --status "$1" \
1882 -- "${args[@]}" < /dev/null > /dev/null 2>&1 || true
1883}
1884
1885# status, ready, unready and withdraw are a Go program, valley-go
1886# (status/). status reads a change's request and outcome from origin,
1887# because what front ends read from it is a JSON contract, and because the
1888# read is subtle enough to want a real parser: an outcome record it does
1889# not recognise must read as unknown, never as success. It writes nothing
1890# and moves no local branch. ready, unready and withdraw write a change's
1891# record, in the one format the push hook reads it in (change/). knot
1892# reads and writes the plan graph at refs/the-valley/knots, in the one
1893# form the push hook validates (knot/), and plan shows that graph as a
1894# view.
1895cmd_go() {
1896 command -v valley-go > /dev/null 2>&1 \
1897 || die "$1 needs the valley-go helper; nix run .#valley bundles it"
1898 VALLEY_TELEMETRY_SINCE="$TEL_T0" VALLEY_TELEMETRY_VERSION="$VALLEY_STAMP" exec valley-go "$@"
1899}
1900
1901# A change is named by its full change ID, its handle, or its branch.
1902# resolve_change reads the name with the helper and sets CHANGE_BRANCH, the
1903# branch to act on. When the name is a change's, it also sets the change's
1904# ID, handle, active version, state and owner, and CHANGE_HEAD, the head
1905# that version records. A branch name is a change's when exactly one record's
1906# active version is on that branch, and is refused when more than one's is.
1907# So whether a change's record is read never depends on how it is named,
1908# and review, approve and rebase cannot run without the helper.
1909#
1910# A change with a record is acted on at a head its record names, and never
1911# at the branch's tip: review at CHANGE_HEAD, and approve at the head bound
1912# to it (status/approve.go). rebase reads the record itself
1913# (status/rebase.go).
1914# The branch a record names is only where its head is expected to be, and
1915# anyone who can push the branch can move it, in the same push as the
1916# record if they like.
1917CHANGE_NAME="" CHANGE_ID="" CHANGE_HANDLE="" CHANGE_VERSION="" CHANGE_HEAD="" CHANGE_BRANCH="" CHANGE_STATE=""
1918CHANGE_OWNER=""
1919
1920# read_resolved <line> <name…>: read a line of valley-go resolve into the
1921# variables named, one field each. A version's branch may be empty, and
1922# read runs consecutive tabs together, since a tab is whitespace to it: an
1923# empty branch would shift the state into the branch. So each tab is made
1924# a unit separator first, which read keeps apart.
1925read_resolved() {
1926 local resolved="$1"
1927 shift
1928 IFS=$'\x1f' read -r "$@" <<< "${resolved//$'\t'/$'\x1f'}"
1929}
1930
1931resolve_change() {
1932 local line kind
1933 CHANGE_NAME="$1"
1934 command -v valley-go > /dev/null 2>&1 \
1935 || die "review, approve and rebase read the change's record with the valley-go helper; nix run .#valley bundles it"
1936 line="$(valley-go resolve "$1")" || return 1
1937 read_resolved "$line" kind CHANGE_ID CHANGE_HANDLE CHANGE_VERSION CHANGE_HEAD CHANGE_BRANCH CHANGE_STATE CHANGE_OWNER
1938 case "$kind" in
1939 branch)
1940 CHANGE_BRANCH="$CHANGE_ID"
1941 CHANGE_ID=""
1942 ;;
1943 change)
1944 [[ "$CHANGE_HEAD" =~ ^[0-9a-f]{40}$ ]] \
1945 || die "valley-go resolve named the head $CHANGE_HEAD, which is no object ID"
1946 case "$CHANGE_STATE" in
1947 ready | draft | withdrawn) ;;
1948 *) die "valley-go resolve named the state $CHANGE_STATE, which this script does not read" ;;
1949 esac
1950 ;;
1951 *) die "valley-go resolve answered $line, which this script does not read" ;;
1952 esac
1953}
1954
1955# need_branch <verb>: refuse a change whose active version records no
1956# branch. review acts on the change's branch: it files its notes under it
1957# and its [r]eject deletes it. rebase, which pushes it, refuses such a
1958# change in valley-go. approve files the head alone, so it approves such a
1959# change.
1960need_branch() {
1961 if [ -n "$CHANGE_ID" ] && [ -z "$CHANGE_BRANCH" ]; then
1962 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"
1963 fi
1964}
1965
1966# The commit review and approve act on: the recorded head for a change
1967# with a record, and otherwise the branch's head on origin.
1968change_head() {
1969 if [ -n "$CHANGE_HEAD" ]; then
1970 printf '%s\n' "$CHANGE_HEAD"
1971 else
1972 ref_oid "refs/remotes/origin/$1"
1973 fi
1974}
1975
1976# fast_forwards <commit>: whether the commit fast-forwards from main's tip
1977# as the fetch left it. A main that cannot be read is not one it
1978# fast-forwards from.
1979fast_forwards() {
1980 local tip
1981 tip="$(ref_oid refs/remotes/origin/main)" && git merge-base --is-ancestor "$tip" "$1"
1982}
1983
1984# For a change with a record, refuse unless the branch's tip on origin is
1985# the recorded head, and name both. review's [r]eject acts on the branch
1986# itself: deleting it while it is elsewhere would delete a commit no
1987# version records. rebase asks the same in valley-go. approve does not ask
1988# this, since the request it files names the head it approves and not the
1989# branch. The second argument is what the refusal leaves undone.
1990check_recorded_tip() {
1991 local branch="$1" undone="$2" tip
1992 [ -n "$CHANGE_HEAD" ] || return 0
1993 tip="$(ref_oid "refs/remotes/origin/$branch")" || {
1994 refuse "no such branch on origin: $branch; $undone"
1995 return 1
1996 }
1997 [ "$tip" = "$CHANGE_HEAD" ] && return 0
1998 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"
1999}
2000
2001# The head review's [a]pprove files, and its version: the active version's
2002# head for a change with a record, or the head review shows of a plain
2003# branch (bind_review).
2004APPROVE_HEAD="" APPROVE_VERSION=""
2005
2006# review shows a change with a record at its active version's head, and
2007# its [a]pprove approves exactly that head. A plain branch is bound to the
2008# head review pages, when it pages it (show_review, use_layer), and approve
2009# files that head.
2010bind_review() {
2011 APPROVE_HEAD="" APPROVE_VERSION=""
2012 if [ -n "$CHANGE_ID" ]; then
2013 APPROVE_HEAD="$CHANGE_HEAD"
2014 APPROVE_VERSION="$CHANGE_VERSION"
2015 fi
2016}
2017
2018# The head the checks failed at in this review, short, while the change is
2019# still at it. Approving that head again would run the same checks over
2020# the same tree and fail the same way, so the prompt stops offering
2021# [a]pprove until the change has a new head. Fails when the checks have
2022# not failed at the head the change is at.
2023approve_failed_at() {
2024 if [ -z "$CHECKS_FAILED_AT" ] || [ "$CHECKS_FAILED_AT" != "$(change_head "$1")" ]; then
2025 return 1
2026 fi
2027 git rev-parse --short "$CHECKS_FAILED_AT"
2028}
2029
2030# not_ready <handle> <version> <state> <owner>: the line review shows for a
2031# change whose record is not ready, above its diff and in its prompt.
2032# Prints nothing, and fails, for a ready change, and for a plain branch,
2033# which has no record. A draft is often a change an agent is still working
2034# on, so the prompt then offers only [v]iew full diff and [s]kip.
2035# [a]pprove would be refused. Nor is [r]eject offered, which records
2036# nothing on the change: it deletes the branch its owner may still be
2037# working on, and the record says what it said before. review still reads
2038# the record again before it acts, since the state can change while the
2039# review is open (moved).
2040not_ready() {
2041 case "$3" in
2042 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" ;;
2043 withdrawn) printf '%s is withdrawn: there is nothing to approve.' "$1" ;;
2044 *) return 1 ;;
2045 esac
2046}
2047
2048# shown_not_ready: not_ready for the change review is showing.
2049shown_not_ready() {
2050 not_ready "$CHANGE_HANDLE" "$CHANGE_VERSION" "$CHANGE_STATE" "$CHANGE_OWNER"
2051}
2052
2053# Where the change under review stands now, as valley-go standing reads
2054# it from origin (status/standing.go), set by read_standing. The state,
2055# the active version and its head; when the record last changed; the
2056# version the change landed as, v<n>, once any has; and STANDING_CONFLICT, which is "conflict"
2057# while the host's restacker reports that rebasing the change onto main
2058# conflicted.
2059STANDING_STATE="" STANDING_VERSION="" STANDING_HEAD="" STANDING_SINCE=""
2060STANDING_LANDED="" STANDING_CONFLICT=""
2061
2062# read_standing: read where the change under review stands now. A plain
2063# branch has no record, and reads as nothing. Fails when origin cannot be
2064# read.
2065read_standing() {
2066 local line
2067 STANDING_STATE="" STANDING_VERSION="" STANDING_HEAD="" STANDING_SINCE=""
2068 STANDING_LANDED="" STANDING_CONFLICT=""
2069 [ -n "$CHANGE_ID" ] || return 0
2070 line="$(valley-go standing "$CHANGE_ID")" || return 1
2071 read_resolved "$line" STANDING_STATE STANDING_VERSION STANDING_HEAD STANDING_SINCE \
2072 STANDING_LANDED STANDING_CONFLICT
2073}
2074
2075# moved [approve]: before review acts on an answer about a change with a
2076# record, it reads the change again. Another principal may return it to
2077# draft, ready a new version, or withdraw it while the operator reads, and
2078# it may land.
2079# When it is no longer what review showed, moved says in one line what
2080# changed and what happens next, and the review of that change ends: the
2081# prompt's answers were about what was shown, so it is not asked again.
2082# A new version the answer carries to, such as a restack with the same
2083# changes, does not end it (carried), nor does approving the new version
2084# in place, which moved approve offers. Fails when the change is still as
2085# shown, the answer carries or the new version is to be approved, and for
2086# a plain branch, which approve and reject check themselves.
2087moved() {
2088 local h="$CHANGE_HANDLE"
2089 CARRIED=""
2090 [ -n "$CHANGE_ID" ] || return 1
2091 if ! read_standing; then
2092 echo "could not read $h again from origin; nothing done"
2093 walk_outcome error
2094 return 0
2095 fi
2096 case "$STANDING_STATE" in
2097 withdrawn)
2098 echo "$h changed while you were reviewing: it was withdrawn (since $STANDING_SINCE), so there is nothing to approve."
2099 walk_outcome moved
2100 return 0
2101 ;;
2102 draft)
2103 echo "$h changed while you were reviewing: it was returned to draft (since $STANDING_SINCE), so there is nothing to approve now. It comes back when it is ready again."
2104 walk_outcome moved
2105 return 0
2106 ;;
2107 esac
2108 if [ -n "$STANDING_LANDED" ]; then
2109 echo "$h landed as $STANDING_LANDED while you were reviewing; there is nothing left to approve."
2110 walk_outcome moved
2111 return 0
2112 fi
2113 if [ "$STANDING_VERSION" != "$CHANGE_VERSION" ] || [ "$STANDING_HEAD" != "$CHANGE_HEAD" ]; then
2114 carried "${1:-}" || {
2115 walk_outcome moved
2116 return 0
2117 }
2118 fi
2119 return 1
2120}
2121
2122# Set by carried when the answer carries, and cleared by moved: off a
2123# terminal, carried's line ended the line review's prompt left open, so
2124# approve's verdict needs no newline of its own.
2125CARRIED=""
2126
2127# carried [approve]: whether the answer about the version review showed
2128# carries to the version the change moved to, as valley-go carry decides
2129# (status/carry.go). When it does, carried says so in one line, and the
2130# answer stays bound to the head shown: an approval names what the
2131# reviewer read, and the integrator applies its delta onto main as main
2132# stands. When it does not, carried says why in one line and offers to
2133# page only what changed since the version shown. Answering an approval,
2134# it also offers to approve the version the change moved to, when
2135# valley-go carry says: at once, or after the page. [a] binds the approval
2136# to that version's head, and Go reads the record again before it files.
2137# Fails unless the answer carries or [a] is taken.
2138carried() {
2139 local h="$CHANGE_HANDLE" verdict="" reason="" offer="" choice keys
2140 bind_review
2141 REVIEW_TMP="$(mktemp -d)"
2142 valley-go carry "$CHANGE_ID" "$CHANGE_VERSION" "$STANDING_VERSION" > "$REVIEW_TMP/carry" \
2143 && IFS=$'\t' read -r verdict reason offer < "$REVIEW_TMP/carry"
2144 [ "${1:-}" = approve ] || offer=none
2145 case "$verdict" in
2146 carries)
2147 echo "$h moved to v$STANDING_VERSION while you were reviewing ($reason) · your answer about v$CHANGE_VERSION stands"
2148 CARRIED=yes
2149 cleanup_review_tmp
2150 return 0
2151 ;;
2152 review)
2153 keys="[v]iew what changed since v$CHANGE_VERSION, [s]kip?"
2154 case "$offer" in
2155 approve) keys="[a]pprove v$STANDING_VERSION, $keys" ;;
2156 view) ;;
2157 *) offer="" keys="review it again to approve it · $keys" ;;
2158 esac
2159 printf '%s moved to v%s while you were reviewing (%s) · %s ' "$h" "$STANDING_VERSION" "$reason" "$keys"
2160 read -r choice || choice=""
2161 if [ "$choice" = v ]; then
2162 tail -n +2 "$REVIEW_TMP/carry" > "$REVIEW_TMP/changed"
2163 page_file "$REVIEW_TMP/changed" || true # quitting the pager early is not an error
2164 if [ -n "$offer" ]; then
2165 offer=approve
2166 printf '[a]pprove v%s, [s]kip? ' "$STANDING_VERSION"
2167 read -r choice || choice=""
2168 fi
2169 fi
2170 if [ "$choice" = a ] && [ "$offer" = approve ]; then
2171 APPROVE_VERSION="$STANDING_VERSION" APPROVE_HEAD="$STANDING_HEAD"
2172 cleanup_review_tmp
2173 return 0
2174 fi
2175 ;;
2176 *) echo "$h moved to v$STANDING_VERSION while you were reviewing; review it again to approve what would land." ;;
2177 esac
2178 cleanup_review_tmp
2179 return 1
2180}
2181
2182# behind_main <branch>: the clause review's prompt shows for a change that
2183# does not fast-forward from main. Being behind main is normal and asks
2184# nothing of the operator: the integrator applies the change's delta onto
2185# main as main stands, with the evidence for the head approved, and the
2186# host's restacker rebases ready changes itself. When the restacker
2187# reports that rebasing the change conflicted, the clause says so instead,
2188# and [a]pprove stays offered: the integrator decides whether the change
2189# applies. Prints nothing, and fails, for a change that fast-forwards from
2190# main.
2191behind_main() {
2192 fast_forwards "$(change_head "$1")" && return 1
2193 read_standing || STANDING_CONFLICT=""
2194 if [ "$STANDING_CONFLICT" = conflict ]; then
2195 printf 'conflicts with main (owner resolving)'
2196 else
2197 printf 'behind main (integrator merges)'
2198 fi
2199}
2200
2201# Show the branch and take the verdict. Split out of cmd_review so that
2202# every way out of it — approve, reject, skip — is followed by the notes.
2203read_and_decide() {
2204 show_review "$1"
2205 decide "$1"
2206}
2207
2208# decide <branch> [<name> <n>]: the verdict on a change alone, and on the
2209# top of a stack. Its prompt is one header line, the change and what
2210# stands in its way as clauses, and the keys it takes (valley-go verdict
2211# prompt, status/verdict.go). A change is named by its handle and version,
2212# a plain branch by its name, and a change alone carries the checks line
2213# review read for it. The top of a stack of <n> is named by its <name>, as
2214# the stack lists it, and its [a]pprove says that approving it lands all
2215# <n> layers. [v]iew diff pages the change's whole diff, or the top
2216# layer's.
2217#
2218# A change that is not ready says so in its header, and is offered only
2219# [v]iew diff and [s]kip, or [s]top. The top of a stack with a layer under
2220# it that is not ready says why it can't be approved (layer_held), as
2221# does a change whose checks failed at the head shown, and neither is
2222# offered [a]pprove. A change that can be approved and does not
2223# fast-forward from main says so (behind_main). Before [a]pprove and
2224# [r]eject act, moved reads the change again, and ends its review when it
2225# moved.
2226decide() {
2227 local branch="$1" name="${2:-}" n="${3:-}" choice failed answers own="" held="" behind="" clause
2228 local approve="[a]pprove" reject="[r]eject" stop="[s]kip"
2229 local stopped="skipped $1; nothing done"
2230 local -a header=("$1") keys=()
2231 if [ -n "$CHANGE_ID" ]; then
2232 header=("$CHANGE_HANDLE v$CHANGE_VERSION")
2233 case "$CHANGE_STATE" in
2234 draft) own="draft (its owner, $CHANGE_OWNER, has not readied it)" ;;
2235 withdrawn) own="withdrawn" ;;
2236 esac
2237 fi
2238 if [ -n "$n" ]; then
2239 header+=("stack of $n")
2240 approve="[a]pprove all $n" reject="[r]eject $name" stop="[s]top"
2241 stopped="stopped reviewing $name at change $n of $n; nothing done"
2242 held="$(layer_held $((n - 1)))" || held=""
2243 elif [ -n "${REVIEW_CHECKS:-}" ]; then
2244 header+=("$REVIEW_CHECKS")
2245 fi
2246 if [ -z "$own" ] && [ -z "$held" ]; then
2247 behind="$(behind_main "$branch")" || behind=""
2248 fi
2249 while true; do
2250 failed=""
2251 if [ -n "$own" ]; then
2252 clause="$own" keys=("[v]iew diff" "$stop") answers="v or s"
2253 elif [ -n "$held" ]; then
2254 clause="$held" keys=("[v]iew diff" "$reject" "$stop") answers="v, r, or s"
2255 elif failed="$(approve_failed_at "$branch")"; then
2256 clause="checks failed at $failed" keys=("[v]iew diff" "$reject" "$stop") answers="v, r, or s"
2257 else
2258 clause="$behind" keys=("$approve" "[v]iew diff" "$reject" "$stop") answers="a, v, r, or s"
2259 fi
2260 valley-go verdict prompt "${header[@]}" ${clause:+"$clause"} -- "${keys[@]}"
2261 read -r choice || die "stdin closed before an answer; nothing done"
2262 case "$choice" in
2263 # A refusal from approve is not a verdict: it says what it did not do
2264 # and the prompt comes back, so the branch can still be rejected or
2265 # skipped. When the checks failed, approving the same head again is
2266 # no longer offered, nor is approving a change that is not ready. A
2267 # change that moved since it was shown is not acted on, and its
2268 # review ends.
2269 a)
2270 if [ -n "$failed" ] || [ -n "$own" ] || [ -n "$held" ]; then
2271 echo "answer $answers"
2272 elif moved approve || approve "$branch"; then
2273 return
2274 fi
2275 ;;
2276 v)
2277 if [ -n "$n" ]; then
2278 view_layer $((n - 1))
2279 else
2280 view_full "$branch"
2281 fi
2282 ;;
2283 r)
2284 if [ -n "$own" ]; then
2285 echo "answer $answers"
2286 elif moved; then
2287 return
2288 else
2289 reject "$branch" && return
2290 fi
2291 ;;
2292 s)
2293 echo "$stopped"
2294 walk_skipped
2295 return
2296 ;;
2297 *) echo "answer $answers" ;;
2298 esac
2299 done
2300}
2301
2302# ----------------------------------------------------------------------
2303# A stack — a change with layers under it that have not landed — is
2304# reviewed one layer at a time, bottom first, each against the layer below
2305# it, the way it was built. Approving the top lands every layer under it,
2306# so reading the top against main alone would ask the operator to judge
2307# the whole stack as one diff.
2308#
2309# The layers are valley-go stack's (status/stack.go): one line each, bottom
2310# first, the change itself last, read here into one array per field.
2311# L_BRANCH is the branch a layer's notes are kept under: a branch's own
2312# name, or the branch a change's active version names. L_OWNER is a
2313# change's owner, as its record names it. L_NOTES holds the notes taken on
2314# each layer, for the print after the verdict.
2315L_KIND=() L_NAME=() L_BASE=() L_HEAD=() L_STATE=() L_APPROVED=() L_TITLE=()
2316L_ID=() L_VERSION=() L_BRANCH=() L_OWNER=() L_NOTES=()
2317# The name review was given, which the top is read again by.
2318TOP_NAME=""
2319
2320# read_stack: read the stack under the change review resolved. Each change
2321# under the top is read again with resolve, for its ID, version, branch
2322# and owner, and must still be at the head the stack names. The top must be
2323# what review resolved. Fails, having said why, when either does not hold
2324# or the helper cannot read the stack. Called in a condition, so each step
2325# is checked by hand.
2326read_stack() {
2327 local out line kind name base head state approved title k last
2328 local rkind id handle version rhead branch rstate owner
2329 L_KIND=() L_NAME=() L_BASE=() L_HEAD=() L_STATE=() L_APPROVED=() L_TITLE=()
2330 L_ID=() L_VERSION=() L_BRANCH=() L_OWNER=() L_NOTES=()
2331 out="$(valley-go stack "${CHANGE_ID:-origin/$CHANGE_BRANCH}")" || return 1
2332 while IFS= read -r line; do
2333 read_resolved "$line" kind name base head state approved title
2334 if ! [[ "$kind" =~ ^(change|branch)$ && "$base" =~ ^[0-9a-f]{40}$ && "$head" =~ ^[0-9a-f]{40}$ ]]; then
2335 refuse "valley-go stack answered $line, which this script does not read"
2336 return 1
2337 fi
2338 L_KIND+=("$kind") L_NAME+=("$name") L_BASE+=("$base") L_HEAD+=("$head")
2339 L_STATE+=("$state") L_APPROVED+=("$approved") L_TITLE+=("$title") L_NOTES+=("")
2340 L_ID+=("") L_VERSION+=("") L_BRANCH+=("$name") L_OWNER+=("")
2341 done <<< "$out"
2342 last=$((${#L_NAME[@]} - 1))
2343 if [ "${L_HEAD[last]}" != "$(change_head "$CHANGE_BRANCH")" ] \
2344 || [ "${L_KIND[last]}" != "$([ -n "$CHANGE_ID" ] && echo change || echo branch)" ]; then
2345 refuse "$TOP_NAME moved while its stack was read"
2346 return 1
2347 fi
2348 L_ID[last]="$CHANGE_ID" L_VERSION[last]="$CHANGE_VERSION" L_BRANCH[last]="$CHANGE_BRANCH"
2349 L_OWNER[last]="$CHANGE_OWNER"
2350 for ((k = 0; k < last; k++)); do
2351 [ "${L_KIND[k]}" = change ] || continue
2352 line="$(valley-go resolve "${L_NAME[k]}")" || return 1
2353 read_resolved "$line" rkind id handle version rhead branch rstate owner
2354 if [ "$rkind" != change ] || [ "$rhead" != "${L_HEAD[k]}" ]; then
2355 refuse "change ${L_NAME[k]}, under $TOP_NAME, moved while the stack was read"
2356 return 1
2357 fi
2358 L_ID[k]="$id" L_VERSION[k]="$version" L_BRANCH[k]="$branch" L_STATE[k]="$rstate"
2359 L_OWNER[k]="$owner"
2360 done
2361}
2362
2363# use_layer <k>: act on layer k as review acts on a change it was given,
2364# binding [a]pprove to the head the stack shows. A branch under the top is
2365# read again as origin/<branch>, which no handle can shadow.
2366use_layer() {
2367 local k="$1"
2368 CHANGE_ID="${L_ID[k]}" CHANGE_VERSION="${L_VERSION[k]}" CHANGE_BRANCH="${L_BRANCH[k]}"
2369 CHANGE_STATE="${L_STATE[k]}" CHANGE_OWNER="${L_OWNER[k]}" CHANGE_HANDLE="" CHANGE_HEAD=""
2370 CHANGE_NAME="origin/${L_NAME[k]}"
2371 [ "$k" -lt $((${#L_NAME[@]} - 1)) ] || CHANGE_NAME="$TOP_NAME"
2372 if [ -n "$CHANGE_ID" ]; then
2373 CHANGE_NAME="${L_NAME[k]}" CHANGE_HANDLE="${L_NAME[k]}" CHANGE_HEAD="${L_HEAD[k]}"
2374 fi
2375 bind_review
2376 [ -n "$CHANGE_ID" ] || APPROVE_HEAD="${L_HEAD[k]}"
2377}
2378
2379# notes_key <k>: the branch layer k's notes are kept under. A change whose
2380# active version names no branch keeps them under its handle.
2381notes_key() {
2382 printf '%s' "${L_BRANCH[$1]:-${L_NAME[$1]}}"
2383}
2384
2385# layer_skipped <k>: succeeds for a layer below the top that is approved,
2386# which asks nothing of the reviewer: the valley carries it to landing once
2387# its checks pass. The walk does not page it. The top is the change review
2388# was named, so it is always paged.
2389layer_skipped() {
2390 [ "$1" -lt $((${#L_NAME[@]} - 1)) ] && [ "${L_APPROVED[$1]}" = approved ]
2391}
2392
2393# layer_label <k>: how a layer is named in the list: its name, then
2394# branch, or the change's state.
2395layer_label() {
2396 local k="$1"
2397 if [ "${L_KIND[k]}" = branch ]; then
2398 printf '%s (branch)' "${L_NAME[k]}"
2399 elif layer_skipped "$k"; then
2400 printf '%s (approved, not paged)' "${L_NAME[k]}"
2401 else
2402 printf '%s (%s)' "${L_NAME[k]}" "${L_STATE[k]}"
2403 fi
2404}
2405
2406# What is coming: the layers bottom first, the lower layers the integrator
2407# would refuse, and what each answer lands.
2408summarize_stack() {
2409 local n="${#L_NAME[@]}" k
2410 printf '%s is a stack of %d changes; reviewing from the bottom, each against the one below it:\n' \
2411 "${L_NAME[n - 1]}" "$n"
2412 for ((k = 0; k < n; k++)); do
2413 printf ' %d. %s: %s\n' "$((k + 1))" "$(layer_label "$k")" "${L_TITLE[k]}"
2414 done
2415 for ((k = 0; k < n - 1; k++)); do
2416 case "${L_STATE[k]}" in
2417 draft | withdrawn)
2418 printf 'warning: %s, change %d of %d, is %s. The integrator refuses to land it or anything above it (refused-not-ready).\n' \
2419 "${L_NAME[k]}" "$((k + 1))" "$n" "$([ "${L_STATE[k]}" = draft ] && echo 'a draft' || echo withdrawn)"
2420 ;;
2421 esac
2422 done
2423 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' \
2424 "${L_NAME[n - 1]}" "$n"
2425}
2426
2427# base_stack: before any layer is paged, a stack whose bottom does not
2428# fast-forward from main is offered [b]ase, which rebases every layer as
2429# the rebase verb does (status/rebase.go), [v]iew diff, which pages the
2430# top's whole diff, or [s]kip. After a rebase the stack is read again and
2431# listed again, so the heads paged are the heads approved. A rebase
2432# refused or left unfinished has said what happened, and only [v]iew diff
2433# and [s]kip are offered then. Fails when the review stops here.
2434base_stack() {
2435 local n choice answers clause="behind main" stopped="; nothing done"
2436 local -a keys=()
2437 while ! fast_forwards "${L_HEAD[0]}"; do
2438 n="${#L_NAME[@]}"
2439 if [ "$clause" = "behind main" ]; then
2440 keys=("[b]ase onto main" "[v]iew diff" "[s]kip") answers="b, v, or s"
2441 else
2442 keys=("[v]iew diff" "[s]kip") answers="v or s"
2443 fi
2444 valley-go verdict prompt "${L_NAME[n - 1]}" "stack of $n" "$clause" -- "${keys[@]}"
2445 read -r choice || die "stdin closed before an answer; nothing done"
2446 case "$choice" in
2447 b)
2448 if [ "$clause" != "behind main" ]; then
2449 echo "answer $answers"
2450 elif rebase_shown "${L_HEAD[n - 1]}"; then
2451 fetch_origin
2452 if [ -n "$CHANGE_ID" ]; then
2453 resolve_change "$CHANGE_ID" || die "could not read change $CHANGE_HANDLE again after the rebase"
2454 fi
2455 bind_review
2456 read_stack || die "could not read the stack under $TOP_NAME again after the rebase"
2457 summarize_stack
2458 else
2459 clause="not rebased" stopped="" WALK_REFUSED=yes
2460 fi
2461 ;;
2462 v) view_full "$CHANGE_BRANCH" ;;
2463 s)
2464 echo "stopped reviewing ${L_NAME[n - 1]} before its first layer$stopped"
2465 walk_skipped
2466 return 1
2467 ;;
2468 *) echo "answer $answers" ;;
2469 esac
2470 done
2471}
2472
2473# layer_heading <k>: the line that heads layer k wherever it is shown.
2474layer_heading() {
2475 local k="$1" below=main
2476 [ "$k" -eq 0 ] || below="${L_NAME[k - 1]}"
2477 printf 'change %d of %d: %s on %s' "$((k + 1))" "${#L_NAME[@]}" "${L_NAME[k]}" "$below"
2478}
2479
2480# layer_held <k>: why layer k can't be approved, when it or a layer under
2481# it is not ready. A layer that is not ready says so as a change alone
2482# does (not_ready). A layer above one says which: approving it would land
2483# that layer too, and the integrator lands nothing that would bring a
2484# version of a change that is not ready. Prints nothing, and fails, when
2485# every layer up to k is ready or a plain branch.
2486layer_held() {
2487 local k="$1" j
2488 not_ready "${L_NAME[k]}" "${L_VERSION[k]}" "${L_STATE[k]}" "${L_OWNER[k]}" && return
2489 for ((j = k - 1; j >= 0; j--)); do
2490 case "${L_STATE[j]}" in
2491 draft | withdrawn)
2492 printf "it would bring %s, change %d of %d, which is %s, so it can't be approved yet." \
2493 "${L_NAME[j]}" "$((j + 1))" "${#L_NAME[@]}" "$([ "${L_STATE[j]}" = draft ] && echo 'a draft' || echo withdrawn)"
2494 return
2495 ;;
2496 esac
2497 done
2498 return 1
2499}
2500
2501# page_layer <k>: show layer k, as show_review shows a change alone. The
2502# layer shown is compared with its own change's approved version, so a
2503# lower layer is set against its own approval, not the top's. Its whole
2504# diff is against the layer below it. The notes taken in it are kept
2505# under its own branch. When it can't be approved, layer_held's line
2506# follows its heading, before the layer's knots.
2507page_layer() {
2508 local k="$1" heading held
2509 NOTES=()
2510 heading="$(layer_heading "$k")"
2511 if held="$(layer_held "$k")"; then heading+=$'\n'"$held"; fi
2512 REVIEW_TMP="$(mktemp -d)"
2513 compare_shown "${L_ID[k]}" "${L_VERSION[k]}" "${L_HEAD[k]}"
2514 show_compared "$(notes_key "$k")" "${L_HEAD[k]}" "$heading" "$(does_of "${L_ID[k]}")" layer_diff "$k"
2515 checks_line "${L_ID[k]}"
2516 keep_layer_notes "$k"
2517}
2518
2519# view_layer <k>: [v]iew full diff for layer k: its whole diff against
2520# the layer below it.
2521view_layer() {
2522 local k="$1"
2523 NOTES=()
2524 REVIEW_TMP="$(mktemp -d)"
2525 {
2526 layer_heading "$k"
2527 printf '\n'
2528 layer_diff "$k"
2529 } > "$REVIEW_TMP/review.diff"
2530 page_buffer "$(notes_key "$k")" "$(git rev-parse --short "${L_HEAD[k]}")"
2531 keep_layer_notes "$k"
2532}
2533
2534# keep_layer_notes <k>: add the notes just taken to layer k's.
2535keep_layer_notes() {
2536 [ "${#NOTES[@]}" -gt 0 ] || return 0
2537 L_NOTES[$1]="${L_NOTES[$1]:+${L_NOTES[$1]}$'\n'}$(printf '%s\n' "${NOTES[@]}")"
2538}
2539
2540# layer_diff <k>: layer k's whole diff: its log and its diff against the
2541# layer below it.
2542layer_diff() {
2543 local k="$1" below=main head base sha on
2544 [ "$k" -eq 0 ] || below="${L_NAME[k - 1]}"
2545 head="${L_HEAD[k]}" base="${L_BASE[k]}"
2546 sha="$(git rev-parse --short "$head")"
2547 on="$below at $(git rev-parse --short "$base")"
2548 if [ "${L_KIND[k]}" = branch ]; then
2549 printf 'branch %s, log against %s:\n\n' "${L_NAME[k]}" "$on"
2550 elif [ -n "${L_BRANCH[k]}" ]; then
2551 printf 'change %s v%s at %s, on branch %s, log against %s:\n\n' \
2552 "${L_NAME[k]}" "${L_VERSION[k]}" "$sha" "${L_BRANCH[k]}" "$on"
2553 else
2554 printf 'change %s v%s at %s, log against %s:\n\n' "${L_NAME[k]}" "${L_VERSION[k]}" "$sha" "$on"
2555 fi
2556 commit_log "$base..$head"
2557 git --no-pager diff "$base...$head"
2558}
2559
2560# Show each layer under the top and ask after each, naming the layer and
2561# its place: [n]ext layer goes on to the layer above, [a]pprove approves
2562# that layer at the head shown, which lands it and every layer under it,
2563# as the prompt names them, [v]iew full diff pages the layer's whole diff,
2564# and [s]top ends the review. [r]eject is not offered under the top:
2565# deleting a lower layer's branch would leave the layers above still
2566# holding it. [a]pprove is not offered at or above a layer that is not
2567# ready, and the prompt says why in its place (layer_held). After the
2568# top, its verdict is taken as for any change, with a prompt that names
2569# the top and says approving it lands all n.
2570review_stack() {
2571 local n top k choice answers failed lands held
2572 summarize_stack
2573 base_stack || return 0
2574 printf '\n'
2575 n="${#L_NAME[@]}" top=$((${#L_NAME[@]} - 1))
2576 for ((k = 0; k < top; k++)); do
2577 layer_skipped "$k" && continue
2578 page_layer "$k"
2579 case "$k" in
2580 0) lands="${L_NAME[0]} alone" ;;
2581 1) lands="${L_NAME[0]} and ${L_NAME[1]}" ;;
2582 *) lands="the $((k + 1)) up to ${L_NAME[k]}" ;;
2583 esac
2584 held="$(layer_held "$k")" || held=""
2585 while true; do
2586 failed=""
2587 [ "$CHECKS_FAILED_AT" != "${L_HEAD[k]}" ] || failed="$(git rev-parse --short "${L_HEAD[k]}")"
2588 if [ -n "$held" ]; then
2589 printf '%s, %d of %d: %s [n]ext layer, [v]iew full diff, [s]top? ' \
2590 "${L_NAME[k]}" "$((k + 1))" "$n" "$held"
2591 answers="n, v, or s"
2592 elif [ -n "$failed" ]; then
2593 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? ' \
2594 "${L_NAME[k]}" "$((k + 1))" "$n" "$failed"
2595 answers="n, v, or s"
2596 else
2597 printf '%s, %d of %d: [n]ext layer, [a]pprove %s, [v]iew full diff, [s]top? ' \
2598 "${L_NAME[k]}" "$((k + 1))" "$n" "$lands"
2599 answers="n, a, v, or s"
2600 fi
2601 read -r choice || die "stdin closed before an answer; nothing done"
2602 case "$choice" in
2603 n) break ;;
2604 a)
2605 if [ -n "$failed" ] || [ -n "$held" ]; then
2606 echo "answer $answers"
2607 continue
2608 fi
2609 use_layer "$k"
2610 if moved approve || approve "$CHANGE_BRANCH"; then
2611 return
2612 fi
2613 use_layer "$top"
2614 ;;
2615 v) view_layer "$k" ;;
2616 s)
2617 echo "stopped reviewing ${L_NAME[top]} at change $((k + 1)) of $n, ${L_NAME[k]}; nothing done"
2618 walk_skipped
2619 return
2620 ;;
2621 *) echo "answer $answers" ;;
2622 esac
2623 done
2624 done
2625 page_layer "$top"
2626 use_layer "$top"
2627 decide "${L_BRANCH[top]}" "${L_NAME[top]}" "$n"
2628}
2629
2630# The notes taken on every layer, each under its own branch.
2631print_stack_notes() {
2632 local k
2633 for ((k = 0; k < ${#L_NAME[@]}; k++)); do
2634 [ -n "${L_NOTES[k]}" ] || continue
2635 mapfile -t NOTES <<< "${L_NOTES[k]}"
2636 print_notes "$(notes_key "$k")"
2637 done
2638}
2639
2640# A review run as a step of a walk (valley-go walk, status/walk.go) is
2641# told what the walker's queue held of the change, as "<change ID>
2642# <version> <head>", and the file its outcome goes to. Both are empty for
2643# any other review. WALK_REFUSED is set when an answer is refused, so a
2644# skip after it is said as one.
2645WALK_QUEUED="" WALK_FILE="" WALK_WRITTEN="" WALK_REFUSED=""
2646
2647# walk_outcome <outcome> [<field>...]: how the step ended, as one line of
2648# tab-separated fields for the walker. The last one written stands.
2649walk_outcome() {
2650 [ -n "$WALK_FILE" ] || return 0
2651 (IFS=$'\t' && printf '%s\n' "$*") > "$WALK_FILE" && WALK_WRITTEN=yes
2652}
2653
2654# walk_skipped: the outcome of a step whose review was skipped or stopped.
2655walk_skipped() {
2656 if [ -n "$WALK_REFUSED" ]; then walk_outcome refused; else walk_outcome skipped; fi
2657}
2658
2659# walk_queued: in a walk, compare the change with what the queue held. A
2660# change that landed, is no longer ready or has no branch on origin is not
2661# reviewed, and the step ends; one ready at another version is reviewed at
2662# it, saying so first. Fails when the step ends here.
2663walk_queued() {
2664 local id version head why=""
2665 [ -n "$WALK_QUEUED" ] || return 0
2666 read -r id version head <<< "$WALK_QUEUED"
2667 read_standing || STANDING_LANDED=""
2668 if [ -n "$STANDING_LANDED" ]; then
2669 why="it landed as $STANDING_LANDED"
2670 elif [ "$CHANGE_STATE" != ready ]; then
2671 why="it is ${CHANGE_STATE/draft/a draft}"
2672 elif [ -z "$CHANGE_BRANCH" ] || ! ref_oid "refs/remotes/origin/$CHANGE_BRANCH" > /dev/null; then
2673 why="its branch is gone from origin"
2674 fi
2675 if [ -n "$why" ]; then
2676 echo "$CHANGE_HANDLE is not reviewed: $why"
2677 walk_outcome not-reviewed "$why"
2678 return 1
2679 fi
2680 [ "$CHANGE_ID $CHANGE_VERSION $CHANGE_HEAD" = "$id $version $head" ] \
2681 || echo "$CHANGE_HANDLE moved to v$CHANGE_VERSION since the queue was read"
2682}
2683
2684cmd_review() {
2685 local name="" verbose=() repo=()
2686 local usage="usage: valley review [-v] [--build-here] [<change> | --repo <name>]"
2687 while [ $# -gt 0 ]; do
2688 case "$1" in
2689 -v) verbose=(-v) VERBOSE=yes ;;
2690 --build-here) BUILD_HERE=yes ;;
2691 --repo)
2692 [ $# -gt 1 ] || die "$usage"
2693 repo=(--repo "$2")
2694 shift
2695 ;;
2696 -*) die "$usage" ;;
2697 *)
2698 [ -z "$name" ] || die "$usage"
2699 name="$1"
2700 ;;
2701 esac
2702 shift
2703 done
2704 # With no change, review walks what needs the operator (status/walk.go),
2705 # running this verb once for each change.
2706 if [ -z "$name" ]; then
2707 command -v valley-go > /dev/null 2>&1 \
2708 || die "review with no change needs the valley-go helper; nix run .#valley bundles it"
2709 fetch_origin
2710 VALLEY_COMMAND="$0" VALLEY_TELEMETRY_SINCE="$TEL_T0" VALLEY_TELEMETRY_VERSION="$VALLEY_STAMP" \
2711 exec valley-go walk "${verbose[@]}" ${BUILD_HERE:+--build-here} "${repo[@]}"
2712 fi
2713 [ "${#repo[@]}" -eq 0 ] || die "$usage"
2714 set -- "$name"
2715 WALK_QUEUED="${VALLEY_WALK_QUEUED:-}" WALK_FILE="${VALLEY_WALK_OUTCOME:-}"
2716 unset VALLEY_WALK_QUEUED VALLEY_WALK_OUTCOME
2717 resolve_change "$1" || exit 1
2718 fetch_origin
2719 walk_queued || exit 0
2720 need_branch review
2721 local branch="$CHANGE_BRANCH"
2722 TOP_NAME="$1"
2723 ref_oid "refs/remotes/origin/$branch" >/dev/null \
2724 || die "no such branch on origin: $branch"
2725 bind_review
2726 trap cleanup_scratch EXIT
2727 trap 'exit 130' INT TERM
2728 # The verdict disposes of the change; the notes are what the human made
2729 # of it, so they are printed whatever the verdict was. A stack that
2730 # cannot be read is reviewed whole against main, as a change with
2731 # nothing under it is.
2732 if ! read_stack; then
2733 printf 'valley: warning: the stack under %s could not be read; reviewing it whole, against main\n' "$1" >&2
2734 L_NAME=()
2735 fi
2736 read_does "${verbose[@]}"
2737 if [ "${#L_NAME[@]}" -gt 1 ]; then
2738 review_stack
2739 print_stack_notes
2740 else
2741 read_and_decide "$branch"
2742 print_notes "$branch"
2743 fi
2744}
2745
2746# approve is review's [a]pprove without the pager, for a front end that
2747# has shown the change its own way: valley-go approve (status/approve.go),
2748# the code the key runs, so the verb and the key cannot drift apart. It
2749# resolves the change before the fetch, as review does.
2750cmd_approve() {
2751 command -v valley-go > /dev/null 2>&1 \
2752 || die "approve needs the valley-go helper; nix run .#valley bundles it"
2753 VALLEY_TELEMETRY_SINCE="$TEL_T0" VALLEY_TELEMETRY_VERSION="$VALLEY_STAMP" \
2754 exec valley-go approve "$@"
2755}
2756
2757# rebase is review's [b]ase onto main without the pager. It runs the code
2758# its key runs, valley-go rebase, and reads a change's name as
2759# resolve_change reads it. The two flags that say what a transfer
2760# statement is verified with are valley-go's, and pass through to it
2761# untouched.
2762cmd_rebase() {
2763 local usage="usage: valley rebase [--known-signers <file>] [--integrator-name <name>] <change>"
2764 local name="" verify=()
2765 while [ $# -gt 0 ]; do
2766 case "$1" in
2767 --known-signers | --integrator-name)
2768 [ $# -ge 2 ] || die "$usage"
2769 verify+=("$1" "$2")
2770 shift 2
2771 ;;
2772 --known-signers=* | --integrator-name=*)
2773 verify+=("$1")
2774 shift
2775 ;;
2776 -*) die "$usage" ;;
2777 *)
2778 [ -z "$name" ] || die "$usage"
2779 name="$1"
2780 shift
2781 ;;
2782 esac
2783 done
2784 [ -n "$name" ] || die "$usage"
2785 command -v valley-go > /dev/null 2>&1 \
2786 || die "review, approve and rebase read the change's record with the valley-go helper; nix run .#valley bundles it"
2787 fetch_origin
2788 VALLEY_TELEMETRY_SINCE="$TEL_T0" VALLEY_TELEMETRY_VERSION="$VALLEY_STAMP" \
2789 exec valley-go rebase "${verify[@]}" "$name"
2790}
2791
2792# tail and replay are thin wrappers over the nats CLI — anything they do,
2793# plain nats and git can do. They are the only verbs needing more than git
2794# and coreutils.
2795need_nats() {
2796 command -v nats >/dev/null 2>&1 \
2797 || die "this verb needs the nats CLI (natscli); nix run .#valley bundles it"
2798}
2799
2800cmd_tail() {
2801 [ $# -le 1 ] || die "usage: valley tail [subject]"
2802 need_nats
2803 exec nats sub "${1:-valley.>}"
2804}
2805
2806# One ref-updated event per existing ref, from git for-each-ref alone. A
2807# ref's prior value is not derivable from the repository, so `old` is the
2808# all-zero id — the same payload a push creating the ref would produce.
2809# The payload construction mirrors the host module's publisher hook
2810# (nix/valley-host.nix); change one only with the other.
2811cmd_replay() {
2812 [ $# -le 1 ] || die "usage: valley replay [repo-dir]"
2813 need_nats
2814 local dir="${1:-.}" repo sha ref event count=0
2815 git -C "$dir" rev-parse --git-dir >/dev/null 2>&1 \
2816 || die "not a git repository: $dir"
2817 if [ "$(git -C "$dir" rev-parse --is-bare-repository)" = true ]; then
2818 repo="$(basename "$(git -C "$dir" rev-parse --absolute-git-dir)" .git)"
2819 else
2820 repo="$(basename "$(git -C "$dir" rev-parse --show-toplevel)")"
2821 fi
2822 while read -r sha ref; do
2823 # " is the only JSON-significant character a refname can contain (git
2824 # forbids \ and control characters); names and object ids are safe.
2825 event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \
2826 "$repo" "${ref//\"/\\\"}" "${sha//?/0}" "$sha")"
2827 nats pub "valley.git.$repo.ref-updated" "$event" >/dev/null
2828 count=$((count + 1))
2829 done < <(git -C "$dir" for-each-ref --format='%(objectname) %(refname)')
2830 echo "replayed $count refs of $repo onto the bus"
2831}
2832
2833# ----------------------------------------------------------------------
2834# checks — the checks the verification policy requires of a change, and
2835# the classes requiring each. The verb is valley-go's (status/checks.go):
2836# it reads the policy's layers and derives with the Go deriver (derive/).
2837cmd_checks() {
2838 command -v valley-go > /dev/null 2>&1 \
2839 || die "checks needs the valley-go helper; nix run .#valley bundles it"
2840 VALLEY_TELEMETRY_SINCE="$TEL_T0" VALLEY_TELEMETRY_VERSION="$VALLEY_STAMP" \
2841 exec valley-go checks "$@"
2842}
2843
2844# self-update installs the tip of a branch of the-valley into the user's
2845# nix profile (status/selfupdate.go). It is told this valley's stamp, which
2846# says what is installed until it has installed something itself.
2847cmd_self_update() {
2848 export VALLEY_VERSION="$VALLEY_STAMP"
2849 cmd_go self-update "$@"
2850}
2851
2852cmd_version() {
2853 printf 'valley %s\n' "${VALLEY_STAMP:-unstamped (run from a checkout, not built by nix)}"
2854}
2855
2856cmd_help() {
2857 [ $# -le 1 ] || die "usage: valley help [<verb>]"
2858 local out
2859 case "${1:-}" in
2860 '' | help | -h | --help) out="$(usage)" ;;
2861 pending) out="$(help_pending)" ;;
2862 changes) out="$(help_changes)" ;;
2863 review) out="$(help_review)" ;;
2864 approve) out="$(help_approve)" ;;
2865 rebase) out="$(help_rebase)" ;;
2866 status) out="$(help_status)" ;;
2867 ready) out="$(help_ready)" ;;
2868 unready) out="$(help_unready)" ;;
2869 withdraw) out="$(help_withdraw)" ;;
2870 knot) out="$(help_knot)" ;;
2871 plan) out="$(help_plan)" ;;
2872 checks) out="$(help_checks)" ;;
2873 tail) out="$(help_tail)" ;;
2874 replay) out="$(help_replay)" ;;
2875 self-update) out="$(help_self_update)" ;;
2876 telemetry) out="$(help_telemetry)" ;;
2877 *) die "unknown help topic: $1 (try 'valley help')" ;;
2878 esac
2879 printf '%s\n' "$out" 2> /dev/null || true
2880}
2881
2882main() {
2883 local verb="${1:-help}"
2884 if [ $# -gt 0 ]; then shift; fi
2885 # The verb set is mirrored in completions/ (valley.bash, _valley) —
2886 # update both when it changes.
2887 case "$verb" in
2888 pending | changes | review | approve | rebase | status | ready | unready | withdraw | knot | plan | checks | tail | replay | self-update | telemetry)
2889 if [ $# -eq 1 ] && { [ "$1" = -h ] || [ "$1" = --help ]; }; then
2890 cmd_help "$verb"
2891 return
2892 fi
2893 ;;
2894 esac
2895 case "$verb" in
2896 review | checks | tail | replay)
2897 TEL_ARGS=("$verb" "$@")
2898 trap 'tel_command $?' EXIT
2899 ;;
2900 esac
2901 case "$verb" in
2902 pending) cmd_pending "$@" ;;
2903 review) cmd_review "$@" ;;
2904 approve) cmd_approve "$@" ;;
2905 rebase) cmd_rebase "$@" ;;
2906 status | ready | unready | withdraw | changes | knot | plan) cmd_go "$verb" "$@" ;;
2907 checks) cmd_checks "$@" ;;
2908 tail) cmd_tail "$@" ;;
2909 replay) cmd_replay "$@" ;;
2910 self-update) cmd_self_update "$@" ;;
2911 telemetry) cmd_go telemetry "$@" ;;
2912 --version) cmd_version ;;
2913 help | -h | --help) cmd_help "$@" ;;
2914 *)
2915 printf 'valley: unknown verb: %s\n\n' "$verb" >&2
2916 usage >&2
2917 exit 1
2918 ;;
2919 esac
2920}
2921
2922main "$@"