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