gunk-dev/the-valley

valley

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