gunk-dev/the-valley

approve.go

source499d9e61dfeemain's published tip history
48.6 KiB
1package main
2
3// approve files a change's integration request: the whole of `valley
4// approve`, which bin/valley hands to it, and review's [a]pprove
5// (review.go). Both run one attempt (approval.attempt), so the verb and
6// the key cannot drift apart.
7//
8// An attempt binds the head it files, derives what the policy at main's
9// tip requires of it (../derive), reuses the evidence origin already
10// holds for the head's tree (coverage.go), runs the rest in a throwaway
11// worktree through attest run, and files the request and the evidence in
12// one atomic push. attest run stores each note in this repository and
13// pushes nothing, so no evidence stands published for a change nobody has
14// approved, and the request is never filed without its evidence. Nothing
15// here writes the protected ref: the integrator judges the request and
16// lands it. Every way it ends is said in one verdict line
17// (verdict.go). With valley.telemetry on, each attempt is a telemetry run
18// of its own, recording approve.start, approve.policy, approve.coverage,
19// approve.checks, approve.request and approve.end, and attest records the
20// checks it runs under the linked run <run>-checks. A record is never
21// evidence, nothing reads one to decide anything, and a record that cannot
22// be stored costs that record alone.
23//
24// Review's [a]pprove is told the change review bound (reviewApproval), and
25// runs on review's own terminal. It leaves how the attempt ended in its
26// result, as fields:
27//
28// approved <change ID> <handle> <version> <head>
29// checks-failed <head>
30// refused
31// unknown
32// interrupted
33//
34// The approved result names what was filed, after the attempt's own reads
35// of the record, with empty fields for a plain branch. unknown is a
36// request whose state the attempt could not establish after the push.
37
38import (
39 "context"
40 "errors"
41 "fmt"
42 "io"
43 "os"
44 "os/exec"
45 "os/signal"
46 "regexp"
47 "sort"
48 "strconv"
49 "strings"
50 "sync"
51 "syscall"
52 "time"
53
54 "the-valley/derive"
55 "the-valley/telemetry"
56)
57
58const approveUsage = "usage: valley approve [-v] [--head <sha>] [--build-here] <change>"
59
60// interruptedStatus is the exit status of an approval cut short by a
61// signal, as a shell reports a process SIGINT ended.
62const interruptedStatus = 130
63
64// headArgument is the shape a --head value must have before it is read
65// as a commit: an object ID, or an abbreviation of one.
66var headArgument = regexp.MustCompile(`^[0-9a-f]{4,64}$`)
67
68// changeRequest is the request name of a change with a record, which no
69// branch is filed under.
70var changeRequest = regexp.MustCompile(`^c-[k-z]{32}$`)
71
72// approval is one approval attempt and what it was told.
73type approval struct {
74 g git
75 stdin *os.File // the terminal: the confirmation, and the checks' stdin
76 stdout, stderr io.Writer
77 v verifier // what reading what the head would bring verifies a transfer statement with
78
79 // exit ends the process once a signal has interrupted the attempt: the
80 // approve verb's records the command, and review's ends the review
81 // first (review.go). It does not return.
82 exit func(int)
83
84 verbose, buildHere bool
85 reviewing bool
86 result []string // how the attempt ended, for review
87
88 // carriedVersion is the later version review's answer carried to, and
89 // carriedHead its head: the version that lands, which the verdict
90 // names (carriedVerdict).
91 carriedVersion, carriedHead string
92
93 // name is the change as it was named, read again before filing in case
94 // a plain branch has come to name a change. For a change, id, handle,
95 // version, head, branch, state and owner are what resolving that name
96 // read; head is the active version's head.
97 name string
98 id, handle, version, head, branch string
99 state, owner string
100 bound, boundVersion, title string // the head filed, its version and title
101 failedAt string // the head whose checks failed
102 filedID, filedHandle, filedVersion string // what the approved line names
103 tel *approveTelemetry
104 mu sync.Mutex
105 interrupted, finished bool
106 child *os.Process
107 childDone chan struct{}
108 worktree string
109 signals chan os.Signal
110 unwatched chan struct{}
111}
112
113// errRefused is an attempt that ended without filing, having said why.
114var errRefused = errors.New("refused")
115
116// errUnknown is a request whose state could not be established after the
117// push, having said so.
118var errUnknown = errors.New("unknown")
119
120func runApprove(g git, args []string, stdout, stderr io.Writer, end func(int)) int {
121 a := &approval{g: g, stdin: os.Stdin, stdout: stdout, stderr: stderr, v: newVerifier(),
122 exit: func(status int) {
123 verification.done()
124 end(status)
125 }}
126 want, err := a.verbFlags(args)
127 if err != nil {
128 fmt.Fprintf(stderr, "valley: %s\n", err)
129 return 1
130 }
131 if !g.succeeds(true, "rev-parse", "--git-dir") {
132 fmt.Fprintln(stderr, "valley: not a git repository")
133 return 1
134 }
135 // The name is read before the fetch, as review reads it.
136 r, err := resolveRecorded(g, a.name)
137 if err != nil {
138 fmt.Fprintf(stderr, "valley: %s\n", err)
139 return 1
140 }
141 a.id, a.handle, a.head, a.branch, a.state, a.owner = r.id, r.handle, r.head, r.branch, r.state, r.owner
142 if r.id != "" {
143 a.version = strconv.Itoa(r.version)
144 }
145 fetch := g.command("fetch", "--prune", "--quiet", "origin")
146 fetch.Stdout, fetch.Stderr = stderr, stderr
147 processStarted()
148 if err := fetch.Run(); err != nil {
149 return exitCode(err)
150 }
151 a.watch(os.Interrupt, syscall.SIGTERM)
152 if a.id != "" {
153 if a.bindHead(want) != nil {
154 return 1
155 }
156 } else {
157 tip, ok, err := g.ref("refs/remotes/origin/" + a.branch)
158 if err != nil || !ok {
159 fmt.Fprintf(stderr, "valley: no such branch on origin: %s\n", a.branch)
160 return 1
161 }
162 if want != "" {
163 at, _ := g.output(true, "rev-parse", "--verify", "--quiet", want+"^{commit}")
164 if at != tip {
165 a.declined(fmt.Sprintf("origin/%s is at %s, not %s", a.branch, a.short(tip), want),
166 act{run: "valley approve " + shellQuote(a.branch)})
167 return 1
168 }
169 }
170 }
171 return a.run()
172}
173
174// verbFlags reads the approve verb's arguments, and returns --head's value.
175func (a *approval) verbFlags(args []string) (want string, err error) {
176 for i := 0; i < len(args); i++ {
177 switch arg := args[i]; {
178 case arg == "--build-here":
179 a.buildHere = true
180 case arg == "-v" || arg == "--verbose":
181 a.verbose = true
182 case arg == "--head" && i+1 < len(args):
183 want = args[i+1]
184 i++
185 case strings.HasPrefix(arg, "--head="):
186 want = strings.TrimPrefix(arg, "--head=")
187 case strings.HasPrefix(arg, "-") || a.name != "":
188 return "", failure(approveUsage)
189 default:
190 a.name = arg
191 }
192 }
193 if a.name == "" {
194 return "", failure(approveUsage)
195 }
196 return want, nil
197}
198
199// reviewApproval is review r's [a]pprove of the change it shows, c, bound
200// to the head r bound and, for a change with a record, to its version.
201// c's name is the change as review was given it, read again before
202// filing. A plain branch's attempt is told the branch, and the head review
203// showed when it showed one. r's carried version and head are given when
204// review's answer carried to that later version, whose line ended the one
205// review's prompt left open. The attempt runs in r's repository, on its
206// terminal, and an interrupt ends it through r's exit.
207func reviewApproval(r *review, c shownChange) *approval {
208 head, version := r.approveHead, r.approveVersion
209 a := &approval{g: r.g, stdin: r.stdin, stdout: r.stdout, stderr: r.stderr, v: r.verifier(), exit: r.exit,
210 reviewing: true, carriedVersion: r.carriedVersion, carriedHead: r.carriedHead,
211 verbose: r.verbose, buildHere: r.buildHere, name: c.name, bound: head}
212 if c.id == "" {
213 a.branch = c.branch
214 return a
215 }
216 // Review shows a change at its active version's head, and binds
217 // [a]pprove to it.
218 a.id, a.handle, a.version, a.head, a.boundVersion = c.id, c.handle, version, head, version
219 return a
220}
221
222// run is one attempt, its telemetry run, and its outcome: 0 when it
223// filed, 1 when it did not.
224func (a *approval) run() int {
225 // Off a terminal, the answer to review's prompt ends no line, so the
226 // verdict starts its own, unless the carry line has ended it.
227 if a.reviewing && a.carriedHead == "" {
228 if _, tty := windowColumns(a.stdin); !tty {
229 fmt.Fprintln(a.stdout)
230 }
231 }
232 t := a.beginTelemetry()
233 a.mu.Lock()
234 a.tel = t
235 a.mu.Unlock()
236 return a.ended(a.attempt())
237}
238
239// ended records how the attempt ended, err being what it returned, and
240// keeps that result: 0 when it filed, 1 when it did not.
241func (a *approval) ended(err error) int {
242 if !a.finish() {
243 select {} // the signal handler ends the process
244 }
245 switch {
246 case err == nil:
247 a.tel.end("filed")
248 a.writeOutcome("approved", a.filedID, a.filedHandle, a.filedVersion, a.bound)
249 return 0
250 case a.failedAt != "":
251 a.tel.end("refused")
252 a.writeOutcome("checks-failed", a.failedAt)
253 case errors.Is(err, errUnknown):
254 a.tel.end("refused")
255 a.writeOutcome("unknown")
256 default:
257 a.tel.end("refused")
258 a.writeOutcome("refused")
259 }
260 return 1
261}
262
263// writeOutcome keeps how the attempt ended, for review.
264func (a *approval) writeOutcome(fields ...string) {
265 a.mu.Lock()
266 a.result = fields
267 a.mu.Unlock()
268}
269
270// watch takes over the signals given until unwatch: one interrupts the
271// attempt. The approve verb is interrupted by SIGINT and SIGTERM. Review's
272// [a]pprove is interrupted by SIGINT alone, which a terminal's Ctrl-C sends
273// to the checks as well, and review acts on a SIGTERM once the attempt has
274// ended (review.go).
275func (a *approval) watch(signals ...os.Signal) {
276 a.signals, a.unwatched = make(chan os.Signal, 2), make(chan struct{})
277 signal.Notify(a.signals, signals...)
278 go func() {
279 select {
280 case <-a.signals:
281 a.interrupt()
282 case <-a.unwatched:
283 }
284 }()
285}
286
287// unwatch gives the signals back once the attempt has ended. Review holds
288// every signal while the attempt runs, so one the attempt took and did not
289// act on is review's to act on.
290func (a *approval) unwatch() {
291 signal.Stop(a.signals)
292 close(a.unwatched)
293}
294
295// interrupt ends an attempt a signal cut short: it stops the checks
296// running, if any, waits for them to end, removes their worktree, records
297// the attempt's end as interrupted, keeps that result, and ends with 130
298// through exit. A second signal while the checks are ending kills them. A
299// signal that reaches the checks first ends them, and checking's caller
300// interrupts the attempt itself; whichever comes first ends it.
301func (a *approval) interrupt() {
302 a.mu.Lock()
303 if a.finished {
304 a.mu.Unlock()
305 a.exit(interruptedStatus)
306 }
307 if a.interrupted {
308 a.mu.Unlock()
309 select {} // the first interrupt ends the process
310 }
311 a.interrupted = true
312 child, done, t := a.child, a.childDone, a.tel
313 a.mu.Unlock()
314 if child != nil {
315 _ = child.Signal(os.Interrupt)
316 select {
317 case <-done:
318 case <-a.signals:
319 _ = child.Kill()
320 <-done
321 }
322 }
323 a.removeWorktree()
324 t.end("interrupted")
325 a.writeOutcome("interrupted")
326 a.exit(interruptedStatus)
327}
328
329// finish marks the attempt ended, unless a signal has interrupted it,
330// when it reports false and the signal handler ends the process.
331func (a *approval) finish() bool {
332 a.mu.Lock()
333 defer a.mu.Unlock()
334 a.finished = !a.interrupted
335 return a.finished
336}
337
338func (a *approval) stopped() bool {
339 a.mu.Lock()
340 defer a.mu.Unlock()
341 return a.interrupted
342}
343
344// act is what a refusal tells the person to do next: a command to run,
345// one to read, or what to do when it is no command.
346type act struct{ run, see, then string }
347
348// declined says what stops the approval, as a verdict on stderr, and
349// returns errRefused. A change is named by its handle and the version
350// being approved, a plain branch by its name.
351func (a *approval) declined(why string, next act) error {
352 return a.refused(verdict{why: why, run: next.run, see: next.see, then: next.then, required: -1, passed: -1})
353}
354
355func (a *approval) refused(v verdict) error {
356 if a.stopped() {
357 return errRefused
358 }
359 v.outcome, v.target, v.name = "refused", "main", a.label()
360 if a.id != "" {
361 v.version = a.boundVersion
362 if v.version == "" {
363 v.version = a.version
364 }
365 }
366 fmt.Fprint(a.stderr, v.lines(terminalOf(a.stderr)))
367 return errRefused
368}
369
370// label is the change as the verdict names it: its handle, or a plain
371// branch's name.
372func (a *approval) label() string {
373 if a.handle != "" {
374 return a.handle
375 }
376 return a.branch
377}
378
379// quoted is the change as a command offered names it.
380func (a *approval) quoted() string { return shellQuote(a.label()) }
381
382func (a *approval) short(oid string) string {
383 s, _ := a.g.output(true, "rev-parse", "--short", oid)
384 return s
385}
386
387// subject is one line of a commit, for saying which commit is meant. A
388// request being replaced is usually this operator's own pre-rebase head;
389// one another operator filed may not be in this repository.
390func (a *approval) subject(oid string) string {
391 if s, err := a.g.output(true, "log", "-1", "--format=%s", oid); err == nil && s != "" {
392 return s
393 }
394 return "subject not in this repository"
395}
396
397// notReady refuses a change that is not ready, offering its owner, as
398// git config valley.principal names them, the command that readies it
399// again. A review is the operator's and the change is usually someone
400// else's, so review is offered nothing.
401func (a *approval) notReady(state, id, branch, owner string) error {
402 why := "change is " + state
403 if state == "draft" {
404 why = "change is a draft"
405 }
406 return a.declined(why, a.readyHint(id, branch, owner))
407}
408
409func (a *approval) readyHint(id, branch, owner string) act {
410 if a.reviewing || owner == "" {
411 return act{}
412 }
413 if principal, _ := a.g.output(true, "config", "valley.principal"); principal != owner {
414 return act{}
415 }
416 run := "valley ready --change " + id
417 if branch != "" {
418 run += " " + shellQuote(branch)
419 }
420 return act{run: run}
421}
422
423// bindHead binds the head approve files for a change with a record. With
424// --head it is exactly that head, which must be one of the record's
425// version heads while the change is ready, the active one or not: a front
426// end that shows the change its own way passes the head it showed, so
427// what is approved is what was seen. Without --head the person is shown
428// the active version's head and title and asked to confirm them, which
429// needs a terminal.
430func (a *approval) bindHead(want string) error {
431 if a.state != "ready" {
432 return a.notReady(a.state, a.id, a.branch, a.owner)
433 }
434 if want != "" {
435 var sha string
436 var err error
437 if headArgument.MatchString(want) {
438 sha, err = a.g.output(true, "rev-parse", "--verify", "--quiet", want+"^{commit}")
439 }
440 if sha == "" || err != nil {
441 return a.declined("--head "+want+" names no commit here", act{see: "valley status " + a.handle})
442 }
443 if err := a.checkVersion(sha); err != nil {
444 return err
445 }
446 a.bound = sha
447 return nil
448 }
449 if err := a.checkVersion(a.head); err != nil {
450 return err
451 }
452 if _, tty := windowColumns(a.stdin); !tty {
453 return a.declined("no terminal to confirm the head, "+a.title,
454 act{run: "valley approve --head " + a.head + " " + a.handle})
455 }
456 fmt.Fprintf(a.stdout, "approve change %s v%s at %s, %s? [y/N] ", a.handle, a.boundVersion, a.head, a.title)
457 switch readLine(a.stdin) {
458 case "y", "Y", "yes":
459 a.bound = a.head
460 return nil
461 }
462 return a.declined("not confirmed", act{})
463}
464
465// readLine reads one line, a byte at a time so that nothing after it is
466// taken from whatever reads the input next.
467func readLine(r io.Reader) string {
468 var line []byte
469 b := make([]byte, 1)
470 for {
471 n, err := r.Read(b)
472 if n == 1 {
473 if b[0] == '\n' {
474 break
475 }
476 line = append(line, b[0])
477 }
478 if err != nil {
479 break
480 }
481 }
482 return strings.TrimSuffix(string(line), "\r")
483}
484
485// checkVersion reads the change's versions from origin again, and
486// refuses unless the change is ready and head is one of its versions'
487// heads, whichever version is active by then: a record that moves after
488// review cannot change what lands, since the request names the head
489// approved. It binds that version's number and title.
490func (a *approval) checkVersion(head string) error {
491 a.boundVersion, a.title = "", ""
492 r, err := versionsOf(a.g, a.id)
493 if err != nil {
494 fmt.Fprintf(a.stderr, "valley: %s\n", err)
495 return a.declined("could not read the change's versions", act{})
496 }
497 var known []string
498 for _, v := range r.Versions {
499 known = append(known, fmt.Sprintf("v%d at %s", v.N, headOf(v)))
500 if headOf(v) == head {
501 a.boundVersion, a.title = strconv.Itoa(v.N), v.Title
502 }
503 }
504 if r.State != "ready" {
505 return a.notReady(r.State, a.id, a.branch, a.owner)
506 }
507 if a.boundVersion == "" {
508 return a.declined(fmt.Sprintf("%s is none of its versions (%s)", a.short(head), strings.Join(known, ", ")),
509 act{see: "valley status " + a.handle})
510 }
511 return nil
512}
513
514// checkRecord reads the change's record again from origin, and refuses
515// unless the change is still ready with the bound head among its
516// versions. The record was read when review or approve began, and another
517// principal may unready, withdraw or ready a new version of the change
518// while a review is open or the checks run. These reads save a run that
519// would come to nothing: the integrator makes the same check on origin.
520//
521// A name that read as a plain branch can come to name a change
522// meanwhile, so the last read before filing, given the head about to be
523// filed as acting, reads the name again: when it names a change now, the
524// change must be ready, and its active head must be that head.
525func (a *approval) checkRecord(acting string) error {
526 if a.id == "" {
527 if acting == "" {
528 return nil
529 }
530 r, err := resolveRecorded(a.g, a.name)
531 if err != nil {
532 fmt.Fprintf(a.stderr, "valley: %s\n", err)
533 return a.declined("could not read origin's records again", act{})
534 }
535 if r.id == "" {
536 return nil
537 }
538 if r.state != "ready" {
539 return a.declined(fmt.Sprintf("now change %s v%d, which is %s", r.handle, r.version, r.state),
540 a.readyHint(r.id, r.branch, r.owner))
541 }
542 if r.head != acting {
543 return a.declined(fmt.Sprintf("now change %s v%d, at another head", r.handle, r.version),
544 act{run: "valley review " + r.handle})
545 }
546 return nil
547 }
548 r, err := resolveRecorded(a.g, a.id)
549 if err != nil {
550 fmt.Fprintf(a.stderr, "valley: %s\n", err)
551 return a.declined("could not read the change's record again", act{})
552 }
553 if r.id != a.id {
554 return a.declined("origin no longer holds the change's record", act{})
555 }
556 if r.state != "ready" {
557 return a.notReady(r.state, a.id, r.branch, r.owner)
558 }
559 return a.checkVersion(a.bound)
560}
561
562// branchAtShown refuses unless the plain branch on origin is still at the
563// head bound to this approval. The operator reviewed a branch, and a
564// branch that moved holds commits nobody has read. origin itself is read,
565// not the tracking ref: a push from another checkout moves the branch
566// without moving this clone's ref.
567func (a *approval) branchAtShown() error {
568 now, err := a.remoteRef("refs/heads/" + a.branch)
569 switch {
570 case err != nil:
571 return a.declined("could not read origin/"+a.branch+" again", act{})
572 case now == "":
573 return a.declined("origin/"+a.branch+" is gone", act{})
574 case now != a.bound:
575 return a.declined(fmt.Sprintf("origin/%s moved from %s, the head shown, to %s", a.branch, a.short(a.bound), a.short(now)),
576 act{run: "valley review " + shellQuote(a.branch)})
577 }
578 return nil
579}
580
581// lsRemote lists origin's refs matching the patterns. ls-remote matches a
582// pattern against the tail of a ref name, so a caller compares each ref
583// it lists whole. A listing that fails is an error, never an empty one.
584func (a *approval) lsRemote(patterns ...string) (map[string]string, error) {
585 out, err := a.g.output(true, append([]string{"ls-remote", "origin"}, patterns...)...)
586 if err != nil {
587 return nil, err
588 }
589 refs := map[string]string{}
590 for _, line := range strings.Split(out, "\n") {
591 if oid, ref, ok := strings.Cut(line, "\t"); ok {
592 refs[ref] = oid
593 }
594 }
595 return refs, nil
596}
597
598// remoteRef is the value of a ref on origin, or "" when origin has none.
599func (a *approval) remoteRef(ref string) (string, error) {
600 refs, err := a.lsRemote(ref)
601 return refs[ref], err
602}
603
604// pushLookalike is a ref origin holds whose name ends in one of these,
605// other than the ref itself, or "". git push matches a destination as
606// rev-parse matches a name: with the ref missing on origin, a push to it
607// writes refs/heads/<ref> instead, and with both there it is refused as
608// ambiguous. So nothing is pushed while origin holds such a ref.
609func (a *approval) pushLookalike(refs ...string) (string, error) {
610 var patterns []string
611 exact := map[string]bool{}
612 for _, ref := range refs {
613 patterns = append(patterns, ref, ref+"/HEAD")
614 exact[ref] = true
615 }
616 listed, err := a.lsRemote(patterns...)
617 if err != nil {
618 return "", err
619 }
620 var others []string
621 for ref := range listed {
622 if !exact[ref] {
623 others = append(others, ref)
624 }
625 }
626 sort.Strings(others)
627 if len(others) == 0 {
628 return "", nil
629 }
630 return others[0], nil
631}
632
633// reportEvidence says, with -v, where the checks this run signed are
634// stored, for every failure after they have run.
635func (a *approval) reportEvidence(refs []string) {
636 if len(refs) == 0 || !a.verbose || a.stopped() {
637 return
638 }
639 fmt.Fprintln(a.stderr, "valley: the evidence is stored locally at:")
640 for _, ref := range refs {
641 fmt.Fprintf(a.stderr, " %s\n", ref)
642 }
643}
644
645// attestationStandsElsewhere reports whether origin holds one of these
646// attestation refs at a value other than the one being pushed. approve
647// pushes a ref of its own notes alone, and origin takes an existing one
648// only with every note it holds kept, so that is the one refusal
649// approving again will never clear.
650func (a *approval) attestationStandsElsewhere(digest string, refs []string) bool {
651 remote, err := a.lsRemote(attestationRefs + digest + "/*")
652 if err != nil {
653 return false
654 }
655 for _, ref := range refs {
656 have := remote[ref]
657 if have == "" {
658 continue
659 }
660 if want, err := a.g.output(true, "rev-parse", ref); err == nil && have != want {
661 return true
662 }
663 }
664 return false
665}
666
667// diagnosePush says why a push carrying the request ref failed, as
668// precisely as the state allows. Every such push is leased, and a lease
669// refuses when the ref is not where the read before it saw it: the
670// request was consumed, or another approval filed or moved it. Reading
671// the ref again tells them apart. Anything else is origin's own refusal,
672// which git has already printed.
673func (a *approval) diagnosePush(ref, pending string) error {
674 now, err := a.remoteRef(ref)
675 switch {
676 case err != nil || now == pending:
677 return a.declined("origin refused the push", act{})
678 case now == "":
679 return a.declined("the pending request was consumed meanwhile", act{see: "valley status " + a.quoted()})
680 }
681 return a.declined(fmt.Sprintf("another approval filed %s (%s) meanwhile", a.short(now), a.subject(now)),
682 act{run: "valley approve " + a.quoted()})
683}
684
685// requestName is the change segment of a request ref for a plain branch.
686// The integrator refuses a segment holding a slash (integrator/refs.go),
687// so a slash is written as a dash. The mapping is lossy: topic/x and
688// topic-x are one request, and approve cannot tell a sibling's request
689// from its own, so it prints the subject of any request it replaces.
690func requestName(branch string) string { return strings.ReplaceAll(branch, "/", "-") }
691
692// attempt is one approval attempt, from main's tip to the verdict.
693func (a *approval) attempt() error {
694 g := a.g
695 root, err := g.output(true, "rev-parse", "--show-toplevel")
696 if err != nil {
697 return a.declined("not in a git repository", act{})
698 }
699 // main's tip as the fetch left it, read once by its exact name. The
700 // merge base, the fast-forward and both policy layers are read at
701 // that one commit.
702 tip, ok, err := g.ref("refs/remotes/origin/main")
703 switch {
704 case err != nil:
705 return a.declined("could not read origin/main", act{run: "git fetch origin"})
706 case !ok:
707 return a.declined("origin has no main to approve onto", act{})
708 }
709
710 // A change with a record is filed at exactly the bound head, under its
711 // own request name, c-<change ID>, and only while its record says it
712 // is ready and lists that head as a version's. Where its branch is
713 // does not matter: the request names the head. A plain branch is
714 // filed at the head review showed, or else at its tip on origin.
715 var head, request, what, named string
716 switch {
717 case a.id != "":
718 if a.bound == "" {
719 return a.declined("no head is bound to this approval", act{})
720 }
721 if err := a.checkRecord(""); err != nil {
722 return err
723 }
724 head, request, named = a.bound, "c-"+a.id, a.handle
725 what = a.handle + " v" + a.boundVersion
726 case a.bound != "":
727 head, request, what, named = a.bound, requestName(a.branch), a.branch, a.branch
728 default:
729 oid, ok, err := g.ref("refs/remotes/origin/" + a.branch)
730 if err != nil || !ok {
731 return a.declined("origin has no branch "+a.branch, act{})
732 }
733 head, request, what, named = oid, requestName(a.branch), a.branch, a.branch
734 }
735 if a.id == "" && changeRequest.MatchString(request) {
736 return a.declined("the branch's request name "+request+" is change "+strings.TrimPrefix(request, "c-")+"'s",
737 act{then: "rename the branch, or name the change by its ID"})
738 }
739 base, err := g.output(true, "merge-base", tip, head)
740 if err != nil || !isObjectID(base) {
741 return a.declined("shares no history with main", act{})
742 }
743 ref := "refs/the-valley/integration-requests/main/" + request
744 a.tel.context(a.id, a.boundVersion, head)
745 a.tel.emit("approve.start", map[string]any{"what": what, "request": ref})
746
747 // A head that does not fast-forward from main, and would bring a
748 // version of another change that has not landed, is a layer above the
749 // bottom of a stale stack. The integrator could land it all the same,
750 // as one commit recorded against this request alone, and the changes
751 // under it would have no landing record of their own. So the stack is
752 // rebased first. This is the project's choice, not a rule the
753 // integrator needs: a stale head with no change under it is approved
754 // as it is, and the integrator merges it onto main.
755 if !g.succeeds(true, "merge-base", "--is-ancestor", tip, head) {
756 under, err := bringsOf(g, a.v, a.id, head)
757 if err != nil {
758 fmt.Fprintf(a.stderr, "valley: %s\n", err)
759 return a.declined("could not read which changes it would bring to main", act{})
760 }
761 if len(under) > 0 {
762 return a.declined("stack is behind main (includes "+strings.Join(under, ", ")+")",
763 act{run: "valley rebase " + shellQuote(named)})
764 }
765 }
766
767 // What the policy requires of the change, read out of exactly the
768 // sources the integrator reads: both layers at the target's tip, and
769 // the floor from the owning valley's own tip when the tip names one. A
770 // change never supplies the policy that gates it, and neither does
771 // the checkout this runs from.
772 res, label, plabel, err := a.derive(root, tip, base, head)
773 if err != nil {
774 fmt.Fprintf(a.stderr, "valley: %s\n", err)
775 return a.declined("the policy did not derive", act{})
776 }
777 required := res.Required
778 names := make([]string, len(required))
779 for i, q := range required {
780 names[i] = q.Name
781 }
782 a.tel.emit("approve.policy", map[string]any{"required": names, "instance": label, "project": plabel})
783
784 // A change the policy asks nothing of is still a change, and the
785 // integrator lands a request that requires no check: nothing is
786 // signed, no key is needed, and one request ref is published.
787 //
788 // A required nix check whose evidence origin already holds is reused,
789 // not built again: a check worker, or an earlier approval, may have
790 // published it. A read of origin that fails ends the approval rather
791 // than reading as no evidence.
792 var reused, missing, unbuilt []string
793 var e evidence
794 if len(required) > 0 {
795 if _, err := exec.LookPath("attest"); err != nil {
796 return a.declined("the attest helper is not installed", act{then: "nix run .#valley bundles it"})
797 }
798 var asked []nixCheck
799 for _, q := range required {
800 if q.Runner == "nix" {
801 asked = append(asked, nixCheck{q.Name, q.Attribute})
802 }
803 }
804 // What coverage and the git it runs say is shown only with -v.
805 quiet := g
806 var said io.Writer = io.Discard
807 if a.verbose {
808 said = a.stderr
809 } else {
810 quiet.stderr = io.Discard
811 }
812 if e, err = coverageOf(quiet, head, asked, said); err != nil {
813 if a.verbose {
814 fmt.Fprintf(a.stderr, "valley: %s\n", err)
815 }
816 return a.declined("could not read the evidence origin holds", act{run: "valley approve -v " + a.quoted()})
817 }
818 // A check whose evidence on origin records a failure is judged by
819 // that evidence, so building it again changes nothing for this
820 // tree, and nothing is filed.
821 var failed []string
822 for _, c := range asked {
823 if _, ok := e.failed[c.name]; ok {
824 failed = append(failed, c.name)
825 }
826 }
827 if len(failed) > 0 {
828 a.failedAt = head
829 return a.refused(verdict{required: len(required), passed: -1, failed: failed})
830 }
831 var signedBy []string
832 for _, q := range required {
833 if by, ok := e.covered[q.Name]; ok {
834 reused = append(reused, q.Name)
835 signedBy = append(signedBy, q.Name+"="+signerOf(by))
836 } else {
837 missing = append(missing, q.Name)
838 }
839 }
840 a.tel.emit("approve.coverage", map[string]any{"tree": e.digest, "reused": list(reused),
841 "reused_by": list(signedBy), "missing": list(missing)})
842 if a.verbose && len(reused) > 0 {
843 fmt.Fprintf(a.stdout, "reusing the evidence origin holds for %s at %s, tree %s:\n", what, a.short(head), e.digest)
844 for _, check := range reused {
845 fmt.Fprintf(a.stdout, " %-24s signed by %s\n", check, signerOf(e.covered[check]))
846 }
847 }
848 }
849
850 // A required nix check with no evidence on origin is built here only
851 // with --build-here. The host's check worker builds the same checks
852 // for a ready change and publishes the evidence, so without the flag
853 // approve files the request at once without it, and the integrator
854 // holds the request until the evidence arrives. Whether the worker
855 // publishes at all is not assured. A command check is never reused and
856 // no worker runs one, so it runs here either way. From here on,
857 // missing is what runs here, and unbuilt what nothing here builds.
858 runner := map[string]derive.Required{}
859 for _, q := range required {
860 runner[q.Name] = q
861 }
862 if !a.buildHere {
863 var here []string
864 for _, check := range missing {
865 if runner[check].Runner == "nix" {
866 unbuilt = append(unbuilt, check)
867 } else {
868 here = append(here, check)
869 }
870 }
871 missing = here
872 }
873
874 var evidenceRefs []string
875 took := ""
876 if len(missing) > 0 {
877 if evidenceRefs, took, err = a.check(head, e, required, reused, missing, runner); err != nil {
878 return err
879 }
880 } else if len(required) == 0 && a.verbose {
881 fmt.Fprintf(a.stdout, "%s requires no check under %s + %s; filing the request with no evidence\n", what, label, plabel)
882 }
883
884 // What origin holds for this request, read once. Approving the same
885 // change twice is ordinary: evidence expires, and a change whose input
886 // closure moved under it is told to re-attest. So the request ref may
887 // already exist. A ref whose name ends in the request's, or in an
888 // evidence ref's, would take the push in its place.
889 pending, err := a.remoteRef(ref)
890 lookalike := ""
891 if err == nil {
892 lookalike, err = a.pushLookalike(append([]string{ref}, evidenceRefs...)...)
893 }
894 if err != nil {
895 a.declined("could not read the request ref on origin", act{})
896 a.reportEvidence(evidenceRefs)
897 return errRefused
898 }
899 if lookalike != "" {
900 a.declined("origin holds "+lookalike+", which git would push to in place of a ref approve pushes",
901 act{then: "delete " + lookalike + " on origin"})
902 a.reportEvidence(evidenceRefs)
903 return errRefused
904 }
905
906 // The one push: every evidence ref, and the request ref wherever it
907 // has to go, --atomic, so a hook that refuses any of them leaves
908 // origin as it was.
909 //
910 // Every write of the request ref is leased against what the read above
911 // saw, including nothing: --force-with-lease=<ref>: refuses if the ref
912 // exists at all, so filing for the first time is a compare-and-swap
913 // too, and two operators filing one change at once cannot have the
914 // second silently replace the first. The lease is the whole of the
915 // force and no refspec carries a +, which would defeat the lease.
916 //
917 // A request already at this head is a re-attestation: the ref does not
918 // move, so it is left out of the push, which carries no
919 // compare-and-swap on a ref it does not change. Where it stands
920 // afterwards is read again below. A request at another head is
921 // replaced: a rebased head is no descendant of the old one.
922 var push, lease []string
923 for _, spec := range evidenceRefs {
924 push = append(push, spec+":"+spec)
925 }
926 if pending != head {
927 lease = append(lease, "--force-with-lease="+ref+":"+pending)
928 push = append(push, head+":"+ref)
929 }
930
931 // The checks can take minutes, and the record may have moved
932 // meanwhile, so it is read once more just before anything is filed.
933 //
934 // A window remains between this read and the push. A change unreadied
935 // or withdrawn in it is filed all the same: git compares only the refs
936 // a push changes, and the record ref is not one of them, so no client
937 // can make the filing conditional on the record. The integrator
938 // narrows the window: it lands no request that would bring a version
939 // of a change that is not ready, and reads the records last just
940 // before it moves the target, so only a record written in that moment
941 // is missed.
942 if err := a.checkRecord(head); err != nil {
943 a.reportEvidence(evidenceRefs)
944 return err
945 }
946 if a.id == "" && a.bound != "" {
947 if err := a.branchAtShown(); err != nil {
948 a.reportEvidence(evidenceRefs)
949 return err
950 }
951 }
952
953 // With no new evidence and the request already at this head there is
954 // nothing to push, and a push with no refspec would fall back to
955 // origin's default one, so none is made.
956 pushed := false
957 if len(push) > 0 {
958 pushed = true
959 args := append(append([]string{"push", "--atomic", "--quiet"}, lease...), "origin")
960 cmd := g.command(append(args, push...)...)
961 cmd.Stdout, cmd.Stderr = a.stderr, a.stderr
962 processStarted()
963 if err := cmd.Run(); err != nil {
964 a.tel.emit("approve.request", map[string]any{"ref": ref, "result": "refused"})
965 if len(lease) == 0 && a.attestationStandsElsewhere(e.digest, evidenceRefs) {
966 a.declined("this key's evidence for the tree is on origin already",
967 act{then: "attest with another key: set VALLEY_ATTEST_KEY"})
968 } else {
969 a.diagnosePush(ref, pending)
970 }
971 a.reportEvidence(evidenceRefs)
972 return errRefused
973 }
974 a.tel.emit("approve.request", map[string]any{"ref": ref, "result": "pushed"})
975 }
976
977 // The lines -v adds under the request line.
978 var standing []string
979 if pending == head {
980 // The request ref was not in that push, so where it stands now is
981 // read again: the integrator may have landed the change and
982 // consumed it, or another approval replaced it. Nothing here
983 // writes it back. Re-creating a consumed request would file a
984 // change already in the stream, replacing another approval's
985 // would clobber the winner, and either would be a second push. The
986 // approval stood before this run, so a request that cannot be read
987 // leaves its state unknown rather than unapproved; approving again
988 // takes the create or replace path against what is there.
989 after, err := a.remoteRef(ref)
990 if err != nil || after == "" {
991 v := verdict{outcome: "unknown", name: a.label(), required: -1, passed: -1}
992 if a.id != "" {
993 v.version = a.boundVersion
994 }
995 if err == nil {
996 v.why = "request consumed meanwhile"
997 }
998 if !a.stopped() {
999 fmt.Fprint(a.stdout, v.lines(terminalOf(a.stdout)))
1000 }
1001 a.reportEvidence(evidenceRefs)
1002 return errUnknown
1003 }
1004 if after != head {
1005 a.declined(fmt.Sprintf("another approval filed %s (%s) meanwhile", a.short(after), a.subject(after)),
1006 act{run: "valley approve " + a.quoted()})
1007 a.reportEvidence(evidenceRefs)
1008 return errRefused
1009 }
1010 switch {
1011 case pushed:
1012 standing = append(standing, "the request already stood at this head; the evidence is what was published")
1013 case len(unbuilt) > 0:
1014 standing = append(standing, "the request already stood at this head, and nothing was built or published")
1015 case len(required) > 0:
1016 standing = append(standing, "the request already stood at this head and origin already held the evidence, so nothing needed publishing")
1017 default:
1018 standing = append(standing, "the request already stood at this head and nothing was required, so nothing needed publishing")
1019 }
1020 } else if pending != "" {
1021 standing = append(standing, fmt.Sprintf("replaced the pending request, which stood at %s (%s)", a.short(pending), a.subject(pending)))
1022 }
1023
1024 if a.verbose {
1025 w := a.stdout
1026 fmt.Fprintf(w, " request %s -> %s\n", ref, a.short(head))
1027 for _, s := range standing {
1028 fmt.Fprintf(w, " %s\n", s)
1029 }
1030 if len(required) == 0 {
1031 fmt.Fprintln(w, " evidence none — nothing was required, so nothing was signed")
1032 fmt.Fprintln(w, " checks none — the policy requires no check of this change")
1033 } else {
1034 fmt.Fprintf(w, " tree %s\n", e.digest)
1035 for _, spec := range evidenceRefs {
1036 fmt.Fprintf(w, " evidence %s\n", spec)
1037 }
1038 // The refs on origin whose evidence was reused, each once.
1039 shown := map[string]bool{}
1040 for _, check := range reused {
1041 spec, _, _ := strings.Cut(e.covered[check], " ")
1042 if !shown[spec] {
1043 shown[spec] = true
1044 fmt.Fprintf(w, " reused %s\n", spec)
1045 }
1046 }
1047 if len(unbuilt) > 0 {
1048 fmt.Fprintf(w, " missing %s\n", strings.Join(unbuilt, ", "))
1049 }
1050 fmt.Fprintf(w, " checks %s\n", strings.Join(names, ", "))
1051 }
1052 }
1053
1054 // The verdict. Checks with no evidence yet are built by a check
1055 // worker only for a ready change's active version. Elsewhere approve
1056 // offers to build them here, unless a command check that ran here put
1057 // this signer's evidence for the tree on origin, which approve cannot
1058 // add to, so a plain branch is offered readying instead, which lets a
1059 // worker build it.
1060 v := verdict{outcome: "approved", name: a.label(), target: "main", required: len(required),
1061 passed: len(required) - len(unbuilt), took: took, waiting: unbuilt}
1062 if a.id != "" {
1063 v.version = a.boundVersion
1064 }
1065 if len(unbuilt) > 0 {
1066 switch {
1067 case a.id != "" && head == a.head:
1068 v.worker = true
1069 case len(missing) == 0:
1070 at := ""
1071 if a.id != "" {
1072 at = "--head " + a.short(head) + " "
1073 }
1074 v.run = "valley approve --build-here " + at + a.quoted()
1075 case a.id == "":
1076 v.run = "valley ready " + a.quoted()
1077 default:
1078 v.see = "valley status " + a.quoted()
1079 }
1080 }
1081 if a.carriedHead != "" && !a.stopped() {
1082 v = a.carriedVerdict()
1083 }
1084 if !a.stopped() {
1085 fmt.Fprint(a.stdout, v.lines(terminalOf(a.stdout)))
1086 }
1087 a.filedID, a.filedHandle, a.filedVersion = a.id, a.handle, a.boundVersion
1088 if a.id == "" {
1089 a.filedVersion = ""
1090 }
1091 return nil
1092}
1093
1094// carriedVerdict is the verdict on an approval whose answer carried to a
1095// later version. The request names the head shown, and the integrator
1096// lands its delta once there is evidence for the tree it lands: the later
1097// version's, the change's active one. So the verdict names that version,
1098// and tells its checks as review's checks line reads them for the active
1099// version (activeChecks, versionchecks.go). What that read says goes to
1100// stderr with -v alone.
1101func (a *approval) carriedVerdict() verdict {
1102 said := io.Discard
1103 if a.verbose {
1104 said = a.stderr
1105 }
1106 var checks *jsonVersionChecks
1107 changes, err := activeChecks(a.g, []string{a.id}, nil, said)
1108 if err != nil {
1109 fmt.Fprintf(said, "valley: %s\n", err)
1110 }
1111 for _, c := range changes {
1112 if v := c.Versions[c.Active-1]; c.ChangeID == a.id && v.Head == a.carriedHead {
1113 checks = v.Checks
1114 }
1115 }
1116 return carriedVerdictOf(a.label(), a.carriedVersion, checks)
1117}
1118
1119// carriedVerdictOf is the verdict that names version, the one that lands,
1120// from its check state, or nil when that was not read. The host's worker
1121// builds the version's nix checks, as the change's active version. It runs
1122// no check of another runner, which the checks line does not judge, so
1123// such a check waits with no worker building it, and approving the change
1124// runs it here.
1125func carriedVerdictOf(name, version string, checks *jsonVersionChecks) verdict {
1126 v := verdict{outcome: "approved", name: name, version: version, target: "main", carried: true, worker: true}
1127 if checks == nil {
1128 v.outcome, v.why, v.required, v.passed = "unknown", "checks unknown", -1, -1
1129 return v
1130 }
1131 for _, q := range checks.Required {
1132 switch q.State {
1133 case checkPassed:
1134 v.passed++
1135 case checkFailed:
1136 v.failed = append(v.failed, q.Name)
1137 case checkPending:
1138 v.waiting = append(v.waiting, q.Name)
1139 default:
1140 v.waiting, v.worker = append(v.waiting, q.Name), false
1141 v.run = "valley approve " + shellQuote(name)
1142 }
1143 v.required++
1144 }
1145 return v
1146}
1147
1148// derive is what the policy at main's tip requires of the change from
1149// base to head, and where each layer was read from.
1150func (a *approval) derive(root, tip, base, head string) (res *derive.Result, label, plabel string, err error) {
1151 g := a.g
1152 schema, err := schemaFile(g, "")
1153 if err != nil {
1154 return nil, "", "", err
1155 }
1156 src, done, err := resolveLayers(g, tip, "", "")
1157 defer done()
1158 if err != nil {
1159 return nil, "", "", fmt.Errorf("%v; nothing derived", err)
1160 }
1161 model, err := policyModel(schema, src.instance, src.project, false)
1162 if err != nil {
1163 return nil, "", "", err
1164 }
1165 paths, err := derive.Diff(context.Background(), g.dir, g.env, base, head)
1166 if err != nil {
1167 return nil, "", "", fmt.Errorf("%v; nothing derived", err)
1168 }
1169 if res, err = derive.Derive(model, paths); err != nil {
1170 return nil, "", "", fmt.Errorf("%v; nothing derived", err)
1171 }
1172 label, plabel = src.labels(root, "", "", "origin/main "+a.short(tip))
1173 return res, label, plabel, nil
1174}
1175
1176// check runs the missing checks over head in a throwaway worktree, signed
1177// with this host's key, and returns every attestation ref stored here for
1178// the head's tree and how long the checks took.
1179func (a *approval) check(head string, e evidence, required []derive.Required, reused, missing []string, runner map[string]derive.Required) (refs []string, took string, err error) {
1180 key := os.Getenv("VALLEY_ATTEST_KEY")
1181 if key == "" {
1182 return nil, "", a.declined("no signing key", act{then: "set VALLEY_ATTEST_KEY to the ed25519 key this host attests with"})
1183 }
1184 if st, err := os.Stat(key); err != nil || !st.Mode().IsRegular() {
1185 return nil, "", a.declined("no signing key at "+key, act{})
1186 }
1187 signer := []string{"--key", key}
1188 if name := os.Getenv("VALLEY_ATTEST_NAME"); name != "" {
1189 signer = append(signer, "--name", name)
1190 }
1191
1192 // The ref this run's evidence goes to is keyed by the tree and this
1193 // signer's key hash, and approve pushes it holding this run's notes
1194 // alone, which origin refuses once it holds the ref. So origin
1195 // holding it is refused before anything is built.
1196 keyCmd := a.g.program("attest", append([]string{"key"}, signer...)...)
1197 keyCmd.Stderr = a.stderr
1198 processStarted()
1199 verifier, err := keyCmd.Output()
1200 if err != nil {
1201 return nil, "", a.declined("could not read the signing key at "+key, act{})
1202 }
1203 _, keyhash, _ := strings.Cut(strings.TrimRight(string(verifier), "\n"), "+")
1204 keyhash, _, _ = strings.Cut(keyhash, "+")
1205 if e.listed[attestationRefs+e.digest+"/"+keyhash] != "" {
1206 return nil, "", a.declined("this key's evidence for the tree, on origin, lacks "+strings.Join(missing, ", "),
1207 act{then: "attest with another key: set VALLEY_ATTEST_KEY"})
1208 }
1209
1210 // attest logs how long each check took, on this machine and outside
1211 // the evidence. What it cannot know itself is passed in: the change,
1212 // and each check's declared cost.
1213 timing := []string{"--timings"}
1214 if a.id != "" {
1215 timing = append(timing, "--change", a.id)
1216 }
1217 if a.boundVersion != "" {
1218 timing = append(timing, "--change-version", a.boundVersion)
1219 }
1220 var run []string
1221 for _, check := range missing {
1222 q := runner[check]
1223 switch q.Runner {
1224 case "nix":
1225 run = append(run, "--check", check+"="+q.Attribute)
1226 case "command":
1227 run = append(run, "--command", check+"="+q.Command)
1228 default:
1229 return nil, "", a.declined("the policy requires "+check+" but says no way to run it", act{})
1230 }
1231 if q.Cost != "" {
1232 timing = append(timing, "--cost", check+"="+q.Cost)
1233 }
1234 }
1235
1236 wt, err := os.MkdirTemp("", "valley-approve-")
1237 if err != nil {
1238 return nil, "", a.declined("no scratch directory to check it in", act{})
1239 }
1240 a.mu.Lock()
1241 a.worktree = wt
1242 a.mu.Unlock()
1243 defer a.removeWorktree()
1244 add := a.g.command("worktree", "add", "--quiet", "--detach", wt, head)
1245 add.Stdout, add.Stderr = a.stderr, a.stderr
1246 processStarted()
1247 if add.Run() != nil {
1248 a.removeWorktree()
1249 return nil, "", a.declined("could not check the head out to run its checks", act{})
1250 }
1251
1252 if a.tel != nil {
1253 timing = append(timing, "--telemetry", a.tel.spool, "--telemetry-run", a.tel.run+"-checks", "--project", a.tel.project)
1254 a.tel.emit("approve.checks", map[string]any{"attest_run": a.tel.run + "-checks", "checks": list(missing)})
1255 }
1256 v := verdict{name: a.label(), required: len(required), passed: len(reused)}
1257 if a.id != "" {
1258 v.version = a.boundVersion
1259 }
1260 args := append(append(append([]string{"run", "--repo", wt}, signer...), timing...), run...)
1261 // attest runs the checks in the worktree --repo names; its directory
1262 // and environment are the repository's, as for every program here.
1263 cmd := a.g.program("attest", args...)
1264 cmd.Stdin = a.stdin
1265 began := time.Now()
1266 done := make(chan struct{})
1267 a.mu.Lock()
1268 a.childDone = done
1269 a.mu.Unlock()
1270 status := v.checking(missing, cmd, a.verbose, droppable(a.stdout), droppable(a.stderr), a.started, a.stopped)
1271 a.mu.Lock()
1272 a.child = nil
1273 close(done)
1274 a.mu.Unlock()
1275 if a.stopped() || status == 128+int(syscall.SIGINT) || status == 128+int(syscall.SIGTERM) {
1276 a.interrupt()
1277 }
1278 if status != 0 {
1279 a.failedAt = head
1280 return nil, "", errRefused
1281 }
1282 took = fmt.Sprintf("%ds", int(time.Since(began).Seconds()))
1283 a.removeWorktree()
1284
1285 // Every attestation stored here for the tree, whoever signed it: the
1286 // evidence for this change is what the tree's digest keys, not what
1287 // this run happened to add.
1288 out, err := a.g.output(true, "for-each-ref", "--format=%(refname)", attestationRefs+e.digest)
1289 if err == nil && out != "" {
1290 refs = strings.Split(out, "\n")
1291 }
1292 if len(refs) == 0 {
1293 return nil, "", a.declined("no attestation is stored for the tree", act{})
1294 }
1295 return refs, took, nil
1296}
1297
1298// started is told of the attest run checking starts, so a signal can stop
1299// it.
1300func (a *approval) started(p *os.Process) {
1301 a.mu.Lock()
1302 a.child = p
1303 a.mu.Unlock()
1304}
1305
1306// removeWorktree removes the checks' worktree, if there is one.
1307func (a *approval) removeWorktree() {
1308 a.mu.Lock()
1309 wt := a.worktree
1310 a.worktree = ""
1311 a.mu.Unlock()
1312 if wt == "" {
1313 return
1314 }
1315 remove := a.g.command("worktree", "remove", "--force", wt)
1316 _ = remove.Run()
1317 _ = os.RemoveAll(wt)
1318}
1319
1320// signerOf is the signer of a covered check, as coverage maps it to
1321// "<ref> <signer>".
1322func signerOf(by string) string {
1323 _, signer, _ := strings.Cut(by, " ")
1324 return signer
1325}
1326
1327// list is a list as a telemetry record holds one: empty rather than null.
1328func list(items []string) []string {
1329 if items == nil {
1330 return []string{}
1331 }
1332 return items
1333}
1334
1335// approveTelemetry is an approval attempt's telemetry run, when the
1336// checkout has valley.telemetry on.
1337type approveTelemetry struct {
1338 emitter *telemetry.Emitter
1339 run, spool, project string
1340 began time.Time
1341 mu sync.Mutex
1342 about telemetry.Record
1343 ended bool
1344}
1345
1346// beginTelemetry starts the attempt's run, bound to the spool of the
1347// destination the checkout's telemetry remote names, and a flusher that
1348// sends it. Telemetry off is nil.
1349func (a *approval) beginTelemetry() *approveTelemetry {
1350 if on, _ := a.g.output(true, "config", "--get", "--bool", "valley.telemetry"); on != "true" {
1351 return nil
1352 }
1353 dest, err := telemetryRemote(a.g, "")
1354 if err == nil {
1355 var dir string
1356 if dir, err = bindSpool(dest); err == nil {
1357 version := producerStamp
1358 if version == "" {
1359 version = "unstamped"
1360 }
1361 t := &approveTelemetry{run: telemetry.NewRunID(), spool: dir, project: dest.project(), began: time.Now()}
1362 t.emitter = telemetry.NewEmitter(dir, telemetry.Self("valley", version), t.run)
1363 t.about.Project = t.project
1364 startFlusher()
1365 return t
1366 }
1367 }
1368 fmt.Fprintf(a.stderr, "valley: telemetry: %s\n", err)
1369 return nil
1370}
1371
1372// context is what every record of the attempt from here on is about.
1373func (t *approveTelemetry) context(id, version, head string) {
1374 if t == nil {
1375 return
1376 }
1377 n, _ := strconv.Atoi(version)
1378 t.mu.Lock()
1379 t.about.Change, t.about.Version, t.about.Head = id, n, head
1380 t.mu.Unlock()
1381}
1382
1383// emit records one step of the attempt. elapsed_ms is this machine's wall
1384// clock since the attempt began.
1385func (t *approveTelemetry) emit(typ string, data map[string]any) {
1386 if t == nil {
1387 return
1388 }
1389 t.mu.Lock()
1390 defer t.mu.Unlock()
1391 if t.ended {
1392 return
1393 }
1394 data["elapsed_ms"] = time.Since(t.began).Milliseconds()
1395 t.emitter.Emit(typ, t.about, data)
1396}
1397
1398// end records how the attempt ended: filed, refused or interrupted. Only
1399// the first end is recorded.
1400func (t *approveTelemetry) end(result string) {
1401 if t == nil {
1402 return
1403 }
1404 t.emit("approve.end", map[string]any{"result": result})
1405 t.mu.Lock()
1406 t.ended = true
1407 t.mu.Unlock()
1408}