| 1 | package run |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "encoding/hex" |
| 7 | "fmt" |
| 8 | "time" |
| 9 | |
| 10 | "the-valley/flow/internal/tmux" |
| 11 | ) |
| 12 | |
| 13 | // State represents the persistent state of a single agent run. |
| 14 | type State struct { |
| 15 | Backend string `json:"backend,omitempty"` // Empty in old state means Claude. |
| 16 | AgentBackend string `json:"agent_backend,omitempty"` // Session worker default. |
| 17 | BackendSessionID *string `json:"backend_session_id,omitempty"` |
| 18 | ID string `json:"id"` |
| 19 | Prompt string `json:"prompt"` |
| 20 | Issue *string `json:"issue"` |
| 21 | PR *string `json:"pr,omitempty"` |
| 22 | Branch string `json:"branch"` // the run's branch: launch's, until finalize finds the run pushed another, as an agent that makes a new change does |
| 23 | Worktree string `json:"worktree"` |
| 24 | TmuxPane *string `json:"tmux_pane"` |
| 25 | Budget *string `json:"budget"` |
| 26 | LogFile *string `json:"log_file"` |
| 27 | CreatedAt string `json:"created_at"` |
| 28 | CostUSD *float64 `json:"cost_usd"` |
| 29 | DurationMS *int64 `json:"duration_ms"` |
| 30 | PRURL *string `json:"pr_url"` |
| 31 | Type string `json:"type,omitempty"` |
| 32 | TargetRepo *string `json:"target_repo,omitempty"` |
| 33 | CloneDir *string `json:"clone_dir,omitempty"` |
| 34 | Host *string `json:"host,omitempty"` |
| 35 | MergedAt *string `json:"merged_at,omitempty"` |
| 36 | DashboardPane *string `json:"dashboard_pane,omitempty"` |
| 37 | CoordinatorPane *string `json:"coordinator_pane,omitempty"` // tmux pane running the coordinator/claude session |
| 38 | Approved *bool `json:"approved,omitempty"` |
| 39 | ApprovedAt *string `json:"approved_at,omitempty"` |
| 40 | SessionName *string `json:"session_name,omitempty"` // claude -n name, same as run ID |
| 41 | OriginalRunID *string `json:"original_run_id,omitempty"` // run ID this was forked from |
| 42 | ClaudeSessionID *string `json:"claude_session_id,omitempty"` // Claude conversation UUID for --resume |
| 43 | RepoRoot *string `json:"repo_root,omitempty"` // absolute path to base repo for worktree recreation |
| 44 | FailureReason *string `json:"failure_reason,omitempty"` // set when the agent crashed (e.g. error_during_execution) or, without a PR, left background work running; suppresses success events and blocks resume chaining |
| 45 | NeedsAttention *string `json:"needs_attention,omitempty"` // set when finalize salvaged unfinished work (no PR, or crash); names the preserved branch |
| 46 | PushedBranch *string `json:"pushed_branch,omitempty"` // set when finalize found a PR-less run's branch on origin (e.g. direct-push repos) |
| 47 | PushedSHA *string `json:"pushed_sha,omitempty"` // origin's tip of PushedBranch at finalize |
| 48 | PushedSubject string `json:"pushed_subject,omitempty"` // the subject of the commit at PushedSHA, when finalize had it |
| 49 | Model *string `json:"model,omitempty"` // claude --model the agent ran with (unset → claude's default) |
| 50 | ResolvedModel string `json:"resolved_model,omitempty"` // the model the worker reported using (claude's stream-json init event), set at finalize; preferred over Model |
| 51 | Effort *string `json:"effort,omitempty"` // claude --effort the agent ran with (unset → claude's default) |
| 52 | ChangeID string `json:"change_id,omitempty"` // the change the run's commits belong to (their Change-Id trailer): launch's, until finalize finds the run pushed another (see Branch); empty in state that predates change IDs |
| 53 | Valley *Valley `json:"valley,omitempty"` // set when finalize found the pushed branch's repo delivers to a valley |
| 54 | Unready *Unready `json:"unready,omitempty"` // set when launch returned the change this run continues to draft on a valley, or tried to |
| 55 | ChangeRepo string `json:"change_repo,omitempty"` // the repo of the change this run continues, as the run it continues named it (integration.RepoName); set at launch when the change ID is inherited from a run |
| 56 | Delivery string `json:"delivery,omitempty"` // how launch told the agent to deliver: DeliveryPR or DeliveryPush; empty in state that predates it |
| 57 | Knot *Knot `json:"knot,omitempty"` // set when the run was launched to work a valley knot (--issue <knot>) |
| 58 | DispatchReason string `json:"dispatch_reason,omitempty"` // why the run was launched (event.Dispatch*, or launch --reason); empty in state that predates it |
| 59 | RepoKey string `json:"repo_key,omitempty"` // the repo as launch named it for events: owner/repo, valley:<name>, or the repo's short name |
| 60 | HeadSHA string `json:"head_sha,omitempty"` // the worktree's HEAD when the agent started, then when it finished; for a tracked valley change, its active version's head when klaus track added it |
| 61 | // TookOver names the runs of this run's change, each needing attention, |
| 62 | // whose pushed work this run took on: recorded at launch when it |
| 63 | // continued a branch (--pr, --change, or --resume-from on its run's |
| 64 | // branch) holding their pushed heads, and at finalize when the head it |
| 65 | // left on origin contains theirs. Their attention is then this run's. |
| 66 | TookOver []string `json:"took_over,omitempty"` |
| 67 | // HouseRules records the house rules the worker was given: where they were |
| 68 | // read from and their digest, or that they were configured but missing. |
| 69 | HouseRules *HouseRules `json:"house_rules,omitempty"` |
| 70 | // SharedGit is launch's snapshot of the files the run's clone shares |
| 71 | // across its worktrees, and what finalize found changed. |
| 72 | SharedGit *SharedGit `json:"shared_git,omitempty"` |
| 73 | // DataRefPush is what happened at finalize when it published the run's |
| 74 | // data ref to origin. Nothing changes it afterwards. |
| 75 | DataRefPush *DataRefPush `json:"data_ref_push,omitempty"` |
| 76 | // CreatedBy is the flow build (its version) that created a session, and |
| 77 | // NamingGeneration the location.Generation whose names it was given. |
| 78 | // Both are empty in a session a build before them created: a legacy |
| 79 | // one. A resumed session keeps both. |
| 80 | CreatedBy string `json:"created_by,omitempty"` |
| 81 | NamingGeneration string `json:"naming_generation,omitempty"` |
| 82 | // TmuxSession is the detached tmux session launch put a run's pane in. |
| 83 | // Empty in a run launched before it was recorded, or into the |
| 84 | // coordinator's window: cleanup then computes the legacy name, as it |
| 85 | // does for a name location doesn't give the run's session. |
| 86 | TmuxSession string `json:"tmux_session,omitempty"` |
| 87 | } |
| 88 | |
| 89 | // DataRefPush statuses. |
| 90 | const ( |
| 91 | DataRefPublished = "published" |
| 92 | DataRefNotAttempted = "not_attempted" // push_data_ref is off |
| 93 | DataRefFailed = "failed" |
| 94 | ) |
| 95 | |
| 96 | // DataRefPush records finalize's publication of the run's data ref. |
| 97 | type DataRefPush struct { |
| 98 | Ref string `json:"ref"` |
| 99 | Commit string `json:"commit"` // the data-ref commit finalize wrote for the run |
| 100 | Status string `json:"status"` |
| 101 | Class string `json:"class,omitempty"` // a failure's git.Push* class |
| 102 | Message string `json:"message,omitempty"` // a failure's git.PushError Message, or finalize's when the pushed history lacks Commit |
| 103 | } |
| 104 | |
| 105 | // HouseRules is the house rules file a run's prompt carried. |
| 106 | type HouseRules struct { |
| 107 | Source string `json:"source"` |
| 108 | Digest string `json:"digest,omitempty"` |
| 109 | Missing bool `json:"missing,omitempty"` |
| 110 | } |
| 111 | |
| 112 | // SharedGit records the files of a run's clone that every worktree of the |
| 113 | // clone shares and that decide what git does there (git.SharedSnapshot). |
| 114 | type SharedGit struct { |
| 115 | Dir string `json:"dir"` // the clone's common git dir |
| 116 | Files map[string]string `json:"files"` // launch's digest of each, by path relative to Dir |
| 117 | Changed []string `json:"changed,omitempty"` // the files finalize found changed since launch |
| 118 | } |
| 119 | |
| 120 | // SharedGitChanged reports whether finalize found the run's clone's shared |
| 121 | // git files changed. Such a run needs attention whatever became of its work, |
| 122 | // and no other run takes that on. |
| 123 | func (s *State) SharedGitChanged() bool { |
| 124 | return s.SharedGit != nil && len(s.SharedGit.Changed) > 0 |
| 125 | } |
| 126 | |
| 127 | // How a run delivers its work, as launch decides it from the run's repo. |
| 128 | const ( |
| 129 | DeliveryPR = "pr" // the agent opens a GitHub PR, or continues one (--pr) |
| 130 | DeliveryPush = "push" // the agent pushes its branch; the repo takes no PRs |
| 131 | ) |
| 132 | |
| 133 | // Unready is what launch's `valley unready` did to the change a follow-up |
| 134 | // run continues, before its agent started. |
| 135 | type Unready struct { |
| 136 | // ChangeID is the change launch returned to draft. Empty in state that |
| 137 | // predates it, where it is the run's change; finalize fills it in when |
| 138 | // the run pushed another change. |
| 139 | ChangeID string `json:"change_id,omitempty"` |
| 140 | Repo string `json:"repo,omitempty"` // the valley's name for the repo, when the change became a draft |
| 141 | Handle string `json:"handle,omitempty"` // the change's handle, when it became a draft |
| 142 | Note string `json:"note,omitempty"` // what the valley said when the change wasn't ready |
| 143 | Error string `json:"error,omitempty"` // why valley unready failed |
| 144 | } |
| 145 | |
| 146 | // UnreadyHandle is the handle launch's `valley unready` reported for the |
| 147 | // run's change, or "" when it reported none, or reported it for a change the |
| 148 | // run then left for another. |
| 149 | func (s *State) UnreadyHandle() string { |
| 150 | if s.Unready == nil || s.Unready.ChangeID != "" && s.Unready.ChangeID != s.ChangeID { |
| 151 | return "" |
| 152 | } |
| 153 | return s.Unready.Handle |
| 154 | } |
| 155 | |
| 156 | // Valley is what finalize's `valley ready` recorded for a pushed run: the |
| 157 | // version of its change that the pushed head became, or why it couldn't |
| 158 | // mark it ready. klaus ready updates it when it marks the version ready. |
| 159 | type Valley struct { |
| 160 | Repo string `json:"repo,omitempty"` // the valley's name for the repo |
| 161 | Handle string `json:"handle,omitempty"` // the change's handle when it was marked ready |
| 162 | Version int `json:"version,omitempty"` // the version the pushed head became |
| 163 | Title string `json:"title,omitempty"` // the pushed head's subject |
| 164 | Error string `json:"error,omitempty"` // why valley ready (or, for a draft, valley unready) failed; empty when it succeeded |
| 165 | // Draft is set when finalize left the version a draft awaiting review |
| 166 | // (ready_at_finalize off), until klaus ready marks it ready. |
| 167 | Draft bool `json:"draft,omitempty"` |
| 168 | } |
| 169 | |
| 170 | // Knot is the knot in a valley project's plan graph that a run was launched |
| 171 | // to work (--issue <knot>), and what klaus did to it: launch claims it, |
| 172 | // finalize links the run's change to it, or comments when the run failed or |
| 173 | // paused, and clears the claim; once the dashboard sees the change landed it |
| 174 | // comments with the landed commit and may close the knot. |
| 175 | type Knot struct { |
| 176 | ID string `json:"id"` // e.g. oc-897917f |
| 177 | Project string `json:"project"` // the valley project whose plan graph holds it |
| 178 | Type string `json:"type"` // outcome or bug |
| 179 | Title string `json:"title,omitempty"` // its title at launch |
| 180 | Dir string `json:"dir,omitempty"` // the checkout launch ran valley in, where klaus asks about the knot after the run |
| 181 | Claimed bool `json:"claimed,omitempty"` // launch claimed it for the run |
| 182 | Released bool `json:"released,omitempty"` // finalize cleared the run's claim |
| 183 | Linked string `json:"linked,omitempty"` // the change finalize linked to it: valley:<repo>/<change ID> |
| 184 | Note string `json:"note,omitempty"` // why finalize commented instead of linking a change |
| 185 | Landed string `json:"landed,omitempty"` // the commit the change landed as, once klaus commented with it |
| 186 | Closed string `json:"closed,omitempty"` // the status klaus set after the landing: done or closed |
| 187 | Error string `json:"error,omitempty"` // the last knot write that failed |
| 188 | } |
| 189 | |
| 190 | // TmuxDeps abstracts tmux pane operations so callers can inject test doubles. |
| 191 | type TmuxDeps struct { |
| 192 | PaneExists func(string) bool |
| 193 | PaneIsIdle func(string) bool |
| 194 | PaneIsDead func(string) bool |
| 195 | } |
| 196 | |
| 197 | // DefaultTmuxDeps returns TmuxDeps wired to the real tmux package. |
| 198 | // Uses a background context for the underlying tmux calls. |
| 199 | func DefaultTmuxDeps() TmuxDeps { |
| 200 | return TmuxDeps{ |
| 201 | PaneExists: func(paneID string) bool { return tmux.PaneExists(context.Background(), paneID) }, |
| 202 | PaneIsIdle: func(paneID string) bool { return tmux.PaneIsIdle(context.Background(), paneID) }, |
| 203 | PaneIsDead: func(paneID string) bool { return tmux.PaneIsDead(context.Background(), paneID) }, |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | // TmuxDepsFor returns TmuxDeps that ask tc, under ctx. |
| 208 | func TmuxDepsFor(ctx context.Context, tc tmux.Client) TmuxDeps { |
| 209 | return TmuxDeps{ |
| 210 | PaneExists: func(paneID string) bool { return tc.PaneExists(ctx, paneID) }, |
| 211 | PaneIsIdle: func(paneID string) bool { return tc.PaneIsIdle(ctx, paneID) }, |
| 212 | PaneIsDead: func(paneID string) bool { return tc.PaneIsDead(ctx, paneID) }, |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | // IsAgentRunning checks if the agent's tmux pane is still active and |
| 217 | // executing its command pipeline. |
| 218 | func (s *State) IsAgentRunning() bool { |
| 219 | return s.IsAgentRunningWith(DefaultTmuxDeps()) |
| 220 | } |
| 221 | |
| 222 | // IsAgentRunningWith is like IsAgentRunning but uses the provided TmuxDeps. |
| 223 | func (s *State) IsAgentRunningWith(td TmuxDeps) bool { |
| 224 | if s.TmuxPane == nil || !td.PaneExists(*s.TmuxPane) { |
| 225 | return false |
| 226 | } |
| 227 | |
| 228 | // Finalized runs (cost/duration set) are running only if their pane |
| 229 | // is not idle (e.g. still showing output before the user closes it). |
| 230 | if s.CostUSD != nil || s.DurationMS != nil { |
| 231 | return !td.PaneIsIdle(*s.TmuxPane) |
| 232 | } |
| 233 | |
| 234 | // Active (unfinalized) runs are running unless the pane is explicitly dead. |
| 235 | return !td.PaneIsDead(*s.TmuxPane) |
| 236 | } |
| 237 | |
| 238 | // StaleGracePeriod is how long after creation before a run can be considered stale. |
| 239 | // This allows time for the agent pipeline to start up. |
| 240 | var StaleGracePeriod = 2 * time.Minute |
| 241 | |
| 242 | // IsStale returns true if the run appears to have been orphaned — its pipeline |
| 243 | // never ran _finalize. A run is stale when it has no finalization data (CostUSD |
| 244 | // and DurationMS are both nil), its tmux pane no longer exists, and enough time |
| 245 | // has passed since creation to rule out normal startup delays. |
| 246 | func (s *State) IsStale() bool { |
| 247 | return s.IsStaleWith(DefaultTmuxDeps()) |
| 248 | } |
| 249 | |
| 250 | // IsStaleWith is like IsStale but uses the provided TmuxDeps. |
| 251 | func (s *State) IsStaleWith(td TmuxDeps) bool { |
| 252 | // Already finalized — not stale. |
| 253 | if s.CostUSD != nil || s.DurationMS != nil { |
| 254 | return false |
| 255 | } |
| 256 | |
| 257 | // Sessions are not agent runs. |
| 258 | if s.Type == "session" { |
| 259 | return false |
| 260 | } |
| 261 | |
| 262 | // If the pane reference is nil or the pane still exists, not stale. |
| 263 | if s.TmuxPane == nil { |
| 264 | // No pane reference at all — could be stale if old enough, but we |
| 265 | // require the pane to have existed and then disappeared. |
| 266 | return false |
| 267 | } |
| 268 | if td.PaneExists(*s.TmuxPane) { |
| 269 | return false |
| 270 | } |
| 271 | |
| 272 | // Grace period: don't mark very recent runs as stale. |
| 273 | created, err := time.Parse(time.RFC3339, s.CreatedAt) |
| 274 | if err != nil { |
| 275 | return false |
| 276 | } |
| 277 | return time.Since(created) > StaleGracePeriod |
| 278 | } |
| 279 | |
| 280 | // GenChangeID generates a change ID in jj's form: 16 random bytes in jj's |
| 281 | // "reverse hex", where the hex digits 0-9a-f are written z-k. The result is 32 |
| 282 | // characters drawn from k to z, comparable as-is with a jj change-id header. |
| 283 | func GenChangeID() (string, error) { |
| 284 | b := make([]byte, 16) |
| 285 | if _, err := rand.Read(b); err != nil { |
| 286 | return "", fmt.Errorf("generating random bytes: %w", err) |
| 287 | } |
| 288 | id := make([]byte, 0, 2*len(b)) |
| 289 | for _, c := range b { |
| 290 | id = append(id, 'z'-c>>4, 'z'-c&0x0f) |
| 291 | } |
| 292 | return string(id), nil |
| 293 | } |
| 294 | |
| 295 | // ValidChangeID reports whether id has the form GenChangeID produces. |
| 296 | func ValidChangeID(id string) bool { |
| 297 | if len(id) != 32 { |
| 298 | return false |
| 299 | } |
| 300 | for _, c := range []byte(id) { |
| 301 | if c < 'k' || c > 'z' { |
| 302 | return false |
| 303 | } |
| 304 | } |
| 305 | return true |
| 306 | } |
| 307 | |
| 308 | // GenID generates a run ID in the format YYYYMMDD-HHMM-XXXXXXXX where the suffix is 8 hex chars. |
| 309 | func GenID() (string, error) { |
| 310 | ts := time.Now().Format("20060102-1504") |
| 311 | b := make([]byte, 4) |
| 312 | if _, err := rand.Read(b); err != nil { |
| 313 | return "", fmt.Errorf("generating random bytes: %w", err) |
| 314 | } |
| 315 | return fmt.Sprintf("%s-%s", ts, hex.EncodeToString(b)), nil |
| 316 | } |