gunk-dev/the-valley

runevents.go

source4cbb5ec9c5dbmain's published tip history
10.0 KiB
1package cmd
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "regexp"
10 "strings"
11 "time"
12
13 "the-valley/flow/internal/event"
14 "the-valley/flow/internal/flowenv"
15 "the-valley/flow/internal/git"
16 "the-valley/flow/internal/github"
17 "the-valley/flow/internal/integration"
18 "the-valley/flow/internal/run"
19 "the-valley/flow/internal/valley"
20)
21
22// runEventsOutput, as flowenv.RunEvents, tells the klaus commands in a run
23// that they can't reach its event log, as on a sandbox host, so they report
24// their events in their output (stream.ReportPrefix). The agent's stream
25// carries the output back to the pane's _format-stream, which records them.
26const runEventsOutput = "output"
27
28// runEnvPrefix exports the run's ID (flowenv.RunID) for a pane command, so
29// _format-stream and the klaus commands the agent runs (_pre-review) put
30// their events on the run.
31func runEnvPrefix(id string) string {
32 return flowenv.RunID.Export(id)
33}
34
35// remoteRunEnvPrefix exports the run's ID for a command on a sandbox host,
36// with flowenv.RunEvents set so its klaus commands report in their output.
37func remoteRunEnvPrefix(id string) string {
38 return flowenv.RunID.Export(id) + flowenv.RunEvents.Export(runEventsOutput)
39}
40
41// runFields returns the fields that say what a run worked on and why, which
42// every run event carries:
43//
44// - repo_key: the repo, qualified: owner/repo on GitHub, valley:<name> for
45// a repo that delivers to a valley, else the repo's short name
46// - change_id and, once the run has one, pr_number
47// - key: the change, qualified by repo_key: <repo_key>#<pr_number> once
48// the run has a PR, else <repo_key>@<change_id>
49// - dispatch_reason: why the run was launched (event.Dispatch*)
50// - head_sha: the run's head where known: the branch tip finalize found on
51// origin, else the worktree's HEAD when the agent finished, else when it
52// started
53//
54// A field that isn't known is left out.
55func runFields(s *run.State) map[string]interface{} {
56 f := map[string]interface{}{}
57 repo, pr := runRepoKey(s), runPRNumber(s)
58 put := func(k, v string) {
59 if v != "" {
60 f[k] = v
61 }
62 }
63 put("repo_key", repo)
64 put("change_id", s.ChangeID)
65 put("pr_number", pr)
66 put("key", changeKey(repo, pr, s.ChangeID))
67 put("dispatch_reason", s.DispatchReason)
68 if s.PushedSHA != nil && *s.PushedSHA != "" {
69 put("head_sha", *s.PushedSHA)
70 } else {
71 put("head_sha", s.HeadSHA)
72 }
73 return f
74}
75
76// withRunFields returns data with s's runFields added; data's own fields
77// win.
78func withRunFields(s *run.State, data map[string]interface{}) map[string]interface{} {
79 out := runFields(s)
80 for k, v := range data {
81 out[k] = v
82 }
83 return out
84}
85
86// emitRunEvent emits an event of s's run carrying its runFields.
87func emitRunEvent(baseDir string, s *run.State, eventType string, data map[string]interface{}) {
88 emitEvent(baseDir, s.ID, eventType, withRunFields(s, data))
89}
90
91// changeKey names a change across repos: <repo>#<pr> for a PR, else
92// <repo>@<change id>. It is "" without a repo, or without either.
93func changeKey(repo, pr, changeID string) string {
94 switch {
95 case repo == "":
96 return ""
97 case pr != "":
98 return repo + "#" + pr
99 case changeID != "":
100 return repo + "@" + changeID
101 }
102 return ""
103}
104
105// runPRNumber returns the number of s's PR, or "".
106func runPRNumber(s *run.State) string {
107 if s.PR != nil && *s.PR != "" {
108 return *s.PR
109 }
110 if s.PRURL != nil {
111 return extractPRNumberFromURL(*s.PRURL)
112 }
113 return ""
114}
115
116// runRepoKey names s's repo for its events: the repo of its PR, the valley
117// finalize or launch talked to, else what launch recorded (RepoKey). State
118// from before launch recorded it gets its target's owner/repo or short name.
119func runRepoKey(s *run.State) string {
120 if s.PRURL != nil {
121 if slug := github.OwnerRepoFromPRURL(*s.PRURL); slug != "" {
122 return slug
123 }
124 }
125 switch {
126 case s.Valley != nil && s.Valley.Repo != "":
127 return "valley:" + s.Valley.Repo
128 case s.Unready != nil && s.Unready.Repo != "":
129 return "valley:" + s.Unready.Repo
130 case s.RepoKey != "":
131 return s.RepoKey
132 }
133 if s.TargetRepo != nil {
134 if slug := repoSlug(*s.TargetRepo); slug != "" {
135 return slug
136 }
137 }
138 return integration.RepoName(s)
139}
140
141// launchRepoKey names a new run's repo for its events (State.RepoKey): the
142// GitHub owner/repo of a run that delivers by PR, valley:<name> for a run
143// whose starting head carries a valley's policy, else the repo's short name.
144func launchRepoKey(ctx context.Context, s *run.State, repoRoot string) string {
145 if key := runRepoKey(&run.State{PRURL: s.PRURL, Unready: s.Unready}); key != "" {
146 return key
147 }
148 if s.Delivery != run.DeliveryPush {
149 if slug := repoSlugForDir(repoRoot); slug != "" {
150 return slug
151 }
152 }
153 name := integration.RepoName(s)
154 if name == "" {
155 name = repoShortName(gitRemoteURL(repoRoot))
156 }
157 if name == "" {
158 name = filepath.Base(repoRoot)
159 }
160 if s.Delivery == run.DeliveryPush && s.HeadSHA != "" && valley.HasPolicy(ctx, s.Worktree, s.HeadSHA) {
161 return "valley:" + name
162 }
163 return name
164}
165
166// dirRepoKey names the repo checked out at dir as runFields' repo_key does,
167// from its origin: owner/repo on GitHub, valley:<name> when its HEAD carries
168// a valley's policy, else the origin's short name. It is "" when dir has no
169// origin.
170func dirRepoKey(ctx context.Context, dir string) string {
171 origin := gitRemoteURL(dir)
172 if origin == "" {
173 return ""
174 }
175 if git.IsGitHubRemote(origin) {
176 if slug := repoSlug(origin); slug != "" {
177 return slug
178 }
179 }
180 name := repoShortName(origin)
181 if valley.HasPolicy(ctx, dir, "HEAD") {
182 return "valley:" + name
183 }
184 return name
185}
186
187// repoShortName is the last path component of a remote URL, without .git.
188func repoShortName(remote string) string {
189 name := strings.TrimSuffix(strings.TrimRight(remote, "/"), ".git")
190 if i := strings.LastIndexAny(name, "/:"); i >= 0 {
191 name = name[i+1:]
192 }
193 return name
194}
195
196// gitHead returns the commit HEAD names in dir, or "".
197func gitHead(ctx context.Context, dir string) string {
198 if dir == "" {
199 return ""
200 }
201 if _, err := os.Stat(dir); err != nil {
202 return ""
203 }
204 out, err := exec.CommandContext(ctx, "git", "-C", dir, "rev-parse", "HEAD").Output()
205 if err != nil {
206 return ""
207 }
208 return strings.TrimSpace(string(out))
209}
210
211// dispatchReasonRe is what launch --reason accepts.
212var dispatchReasonRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,63}$`)
213
214// checkDispatchReason rejects a --reason launch doesn't accept; "" is none.
215func checkDispatchReason(flag string) error {
216 if flag != "" && !dispatchReasonRe.MatchString(flag) {
217 return fmt.Errorf("--reason %q: use lowercase letters, digits and hyphens, such as docs-timer", flag)
218 }
219 return nil
220}
221
222// dispatchReason decides why a launch is happening, for its run and its
223// events: --reason when given, else what its flags say.
224func dispatchReason(flag string, isPRFix, budgetPaused, onChange bool, resumeFrom string) string {
225 switch {
226 case flag != "":
227 return flag
228 case isPRFix && budgetPaused:
229 return event.DispatchBudgetResume
230 case isPRFix:
231 return event.DispatchPRFollowUp
232 case onChange:
233 return event.DispatchChangeFollowUp
234 case resumeFrom != "":
235 return event.DispatchResume
236 }
237 return event.DispatchLaunch
238}
239
240// eventTime formats a time for an event field.
241func eventTime(t time.Time) string {
242 return t.UTC().Format(time.RFC3339Nano)
243}
244
245// phaseData is the data of a phase:completed event for phase, which ran
246// from start to end.
247func phaseData(phase string, start, end time.Time) map[string]interface{} {
248 return map[string]interface{}{
249 "phase": phase,
250 "started_at": eventTime(start),
251 "ended_at": eventTime(end),
252 "duration_ms": end.Sub(start).Milliseconds(),
253 }
254}
255
256// emitAgentPhase ends a finalized run's agent phase, which ran from launch
257// starting its pane (CreatedAt) to finalize starting at end, with the
258// agent's cost when known, and starts the finalize phase.
259func emitAgentPhase(baseDir string, s *run.State, end time.Time) {
260 if start, err := time.Parse(time.RFC3339, s.CreatedAt); err == nil {
261 data := phaseData(event.PhaseAgent, start, end)
262 if s.Backend != "" {
263 data["backend"] = s.Backend
264 }
265 if s.CostUSD != nil {
266 data["cost_usd"] = *s.CostUSD
267 }
268 emitRunEvent(baseDir, s, event.PhaseCompleted, data)
269 }
270 emitRunEvent(baseDir, s, event.PhaseStarted, map[string]interface{}{
271 "phase": event.PhaseFinalize,
272 "started_at": eventTime(end),
273 })
274}
275
276// paneRunSaveWait bounds how long a pane's process, finishing with events
277// for its run, waits for launch to save the run's state. Launch saves it just
278// after the pane starts, so a fast agent can finish first.
279const paneRunSaveWait = 2 * time.Second
280
281// paneRun is the run whose pane this process runs in (flowenv.RunID).
282type paneRun struct {
283 baseDir string // the session's directory
284 id string // the run's ID
285 state *run.State // nil until launch has saved it
286}
287
288// currentPaneRun returns the run whose pane this process runs in, with its
289// state if launch has saved it, or nil outside a run's pane.
290func currentPaneRun() *paneRun {
291 id := flowenv.RunID.Get()
292 if id == "" {
293 return nil
294 }
295 store, err := sessionStore()
296 if err != nil {
297 return nil
298 }
299 hds, ok := store.(*run.HomeDirStore)
300 if !ok {
301 return nil
302 }
303 p := &paneRun{baseDir: hds.BaseDir(), id: id}
304 p.load()
305 return p
306}
307
308// load loads p's state if launch has saved it, and reports whether p has it.
309func (p *paneRun) load() bool {
310 if p.state == nil {
311 if s, err := run.NewHomeDirStoreFromPath(p.baseDir).Load(p.id); err == nil {
312 p.state = s
313 }
314 }
315 return p.state != nil
316}
317
318// awaitState waits up to paneRunSaveWait for launch to save p's state.
319func (p *paneRun) awaitState() {
320 deadline := time.Now().Add(paneRunSaveWait)
321 for !p.load() && time.Now().Before(deadline) {
322 time.Sleep(50 * time.Millisecond)
323 }
324}
325
326// emit emits an event of p's run: with its runFields once p has its state,
327// else under its ID alone, so it isn't lost when launch never saves the
328// state in time; the report takes the run's fields from its other events.
329func (p *paneRun) emit(eventType string, data map[string]interface{}) {
330 if p.state != nil {
331 emitRunEvent(p.baseDir, p.state, eventType, data)
332 return
333 }
334 emitEvent(p.baseDir, p.id, eventType, data)
335}