gunk-dev/the-valley

run.go

source30e24c82839bmain's published tip history
14.3 KiB
1package run
2
3import (
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.
14type 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}
74
75// HouseRules is the house rules file a run's prompt carried.
76type HouseRules struct {
77 Source string `json:"source"`
78 Digest string `json:"digest,omitempty"`
79 Missing bool `json:"missing,omitempty"`
80}
81
82// SharedGit records the files of a run's clone that every worktree of the
83// clone shares and that decide what git does there (git.SharedSnapshot).
84type SharedGit struct {
85 Dir string `json:"dir"` // the clone's common git dir
86 Files map[string]string `json:"files"` // launch's digest of each, by path relative to Dir
87 Changed []string `json:"changed,omitempty"` // the files finalize found changed since launch
88}
89
90// SharedGitChanged reports whether finalize found the run's clone's shared
91// git files changed. Such a run needs attention whatever became of its work,
92// and no other run takes that on.
93func (s *State) SharedGitChanged() bool {
94 return s.SharedGit != nil && len(s.SharedGit.Changed) > 0
95}
96
97// How a run delivers its work, as launch decides it from the run's repo.
98const (
99 DeliveryPR = "pr" // the agent opens a GitHub PR, or continues one (--pr)
100 DeliveryPush = "push" // the agent pushes its branch; the repo takes no PRs
101)
102
103// Unready is what launch's `valley unready` did to the change a follow-up
104// run continues, before its agent started.
105type Unready struct {
106 // ChangeID is the change launch returned to draft. Empty in state that
107 // predates it, where it is the run's change; finalize fills it in when
108 // the run pushed another change.
109 ChangeID string `json:"change_id,omitempty"`
110 Repo string `json:"repo,omitempty"` // the valley's name for the repo, when the change became a draft
111 Handle string `json:"handle,omitempty"` // the change's handle, when it became a draft
112 Note string `json:"note,omitempty"` // what the valley said when the change wasn't ready
113 Error string `json:"error,omitempty"` // why valley unready failed
114}
115
116// UnreadyHandle is the handle launch's `valley unready` reported for the
117// run's change, or "" when it reported none, or reported it for a change the
118// run then left for another.
119func (s *State) UnreadyHandle() string {
120 if s.Unready == nil || s.Unready.ChangeID != "" && s.Unready.ChangeID != s.ChangeID {
121 return ""
122 }
123 return s.Unready.Handle
124}
125
126// Valley is what finalize's `valley ready` recorded for a pushed run: the
127// version of its change that the pushed head became, or why it couldn't
128// mark it ready. klaus ready updates it when it marks the version ready.
129type Valley struct {
130 Repo string `json:"repo,omitempty"` // the valley's name for the repo
131 Handle string `json:"handle,omitempty"` // the change's handle when it was marked ready
132 Version int `json:"version,omitempty"` // the version the pushed head became
133 Title string `json:"title,omitempty"` // the pushed head's subject
134 Error string `json:"error,omitempty"` // why valley ready (or, for a draft, valley unready) failed; empty when it succeeded
135 // Draft is set when finalize left the version a draft awaiting review
136 // (ready_at_finalize off), until klaus ready marks it ready.
137 Draft bool `json:"draft,omitempty"`
138}
139
140// Knot is the knot in a valley project's plan graph that a run was launched
141// to work (--issue <knot>), and what klaus did to it: launch claims it,
142// finalize links the run's change to it, or comments when the run failed or
143// paused, and clears the claim; once the dashboard sees the change landed it
144// comments with the landed commit and may close the knot.
145type Knot struct {
146 ID string `json:"id"` // e.g. oc-897917f
147 Project string `json:"project"` // the valley project whose plan graph holds it
148 Type string `json:"type"` // outcome or bug
149 Title string `json:"title,omitempty"` // its title at launch
150 Dir string `json:"dir,omitempty"` // the checkout launch ran valley in, where klaus asks about the knot after the run
151 Claimed bool `json:"claimed,omitempty"` // launch claimed it for the run
152 Released bool `json:"released,omitempty"` // finalize cleared the run's claim
153 Linked string `json:"linked,omitempty"` // the change finalize linked to it: valley:<repo>/<change ID>
154 Note string `json:"note,omitempty"` // why finalize commented instead of linking a change
155 Landed string `json:"landed,omitempty"` // the commit the change landed as, once klaus commented with it
156 Closed string `json:"closed,omitempty"` // the status klaus set after the landing: done or closed
157 Error string `json:"error,omitempty"` // the last knot write that failed
158}
159
160// TmuxDeps abstracts tmux pane operations so callers can inject test doubles.
161type TmuxDeps struct {
162 PaneExists func(string) bool
163 PaneIsIdle func(string) bool
164 PaneIsDead func(string) bool
165}
166
167// DefaultTmuxDeps returns TmuxDeps wired to the real tmux package.
168// Uses a background context for the underlying tmux calls.
169func DefaultTmuxDeps() TmuxDeps {
170 return TmuxDeps{
171 PaneExists: func(paneID string) bool { return tmux.PaneExists(context.Background(), paneID) },
172 PaneIsIdle: func(paneID string) bool { return tmux.PaneIsIdle(context.Background(), paneID) },
173 PaneIsDead: func(paneID string) bool { return tmux.PaneIsDead(context.Background(), paneID) },
174 }
175}
176
177// TmuxDepsFor returns TmuxDeps that ask tc, under ctx.
178func TmuxDepsFor(ctx context.Context, tc tmux.Client) TmuxDeps {
179 return TmuxDeps{
180 PaneExists: func(paneID string) bool { return tc.PaneExists(ctx, paneID) },
181 PaneIsIdle: func(paneID string) bool { return tc.PaneIsIdle(ctx, paneID) },
182 PaneIsDead: func(paneID string) bool { return tc.PaneIsDead(ctx, paneID) },
183 }
184}
185
186// IsAgentRunning checks if the agent's tmux pane is still active and
187// executing its command pipeline.
188func (s *State) IsAgentRunning() bool {
189 return s.IsAgentRunningWith(DefaultTmuxDeps())
190}
191
192// IsAgentRunningWith is like IsAgentRunning but uses the provided TmuxDeps.
193func (s *State) IsAgentRunningWith(td TmuxDeps) bool {
194 if s.TmuxPane == nil || !td.PaneExists(*s.TmuxPane) {
195 return false
196 }
197
198 // Finalized runs (cost/duration set) are running only if their pane
199 // is not idle (e.g. still showing output before the user closes it).
200 if s.CostUSD != nil || s.DurationMS != nil {
201 return !td.PaneIsIdle(*s.TmuxPane)
202 }
203
204 // Active (unfinalized) runs are running unless the pane is explicitly dead.
205 return !td.PaneIsDead(*s.TmuxPane)
206}
207
208// StaleGracePeriod is how long after creation before a run can be considered stale.
209// This allows time for the agent pipeline to start up.
210var StaleGracePeriod = 2 * time.Minute
211
212// IsStale returns true if the run appears to have been orphaned — its pipeline
213// never ran _finalize. A run is stale when it has no finalization data (CostUSD
214// and DurationMS are both nil), its tmux pane no longer exists, and enough time
215// has passed since creation to rule out normal startup delays.
216func (s *State) IsStale() bool {
217 return s.IsStaleWith(DefaultTmuxDeps())
218}
219
220// IsStaleWith is like IsStale but uses the provided TmuxDeps.
221func (s *State) IsStaleWith(td TmuxDeps) bool {
222 // Already finalized — not stale.
223 if s.CostUSD != nil || s.DurationMS != nil {
224 return false
225 }
226
227 // Sessions are not agent runs.
228 if s.Type == "session" {
229 return false
230 }
231
232 // If the pane reference is nil or the pane still exists, not stale.
233 if s.TmuxPane == nil {
234 // No pane reference at all — could be stale if old enough, but we
235 // require the pane to have existed and then disappeared.
236 return false
237 }
238 if td.PaneExists(*s.TmuxPane) {
239 return false
240 }
241
242 // Grace period: don't mark very recent runs as stale.
243 created, err := time.Parse(time.RFC3339, s.CreatedAt)
244 if err != nil {
245 return false
246 }
247 return time.Since(created) > StaleGracePeriod
248}
249
250// GenChangeID generates a change ID in jj's form: 16 random bytes in jj's
251// "reverse hex", where the hex digits 0-9a-f are written z-k. The result is 32
252// characters drawn from k to z, comparable as-is with a jj change-id header.
253func GenChangeID() (string, error) {
254 b := make([]byte, 16)
255 if _, err := rand.Read(b); err != nil {
256 return "", fmt.Errorf("generating random bytes: %w", err)
257 }
258 id := make([]byte, 0, 2*len(b))
259 for _, c := range b {
260 id = append(id, 'z'-c>>4, 'z'-c&0x0f)
261 }
262 return string(id), nil
263}
264
265// ValidChangeID reports whether id has the form GenChangeID produces.
266func ValidChangeID(id string) bool {
267 if len(id) != 32 {
268 return false
269 }
270 for _, c := range []byte(id) {
271 if c < 'k' || c > 'z' {
272 return false
273 }
274 }
275 return true
276}
277
278// GenID generates a run ID in the format YYYYMMDD-HHMM-XXXXXXXX where the suffix is 8 hex chars.
279func GenID() (string, error) {
280 ts := time.Now().Format("20060102-1504")
281 b := make([]byte, 4)
282 if _, err := rand.Read(b); err != nil {
283 return "", fmt.Errorf("generating random bytes: %w", err)
284 }
285 return fmt.Sprintf("%s-%s", ts, hex.EncodeToString(b)), nil
286}