gunk-dev/the-valley

replay.go

source672eff5ffaecmain's published tip history
12.0 KiB
1package cmd
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "encoding/json"
8 "fmt"
9 "os"
10 "path/filepath"
11 "strings"
12
13 "the-valley/flow/internal/backend"
14 "the-valley/flow/internal/draft"
15 "the-valley/flow/internal/git"
16 "the-valley/flow/internal/run"
17)
18
19// Trajectory replay continues the prior Claude conversation on a budget-paused
20// PR, or on a change continued with --change, instead of dispatching a fresh
21// agent that must re-explore the repo.
22//
23// Mechanism: klaus stores the resume-able conversation JSONL (the file
24// claude itself writes under ~/.claude/projects/<encoded-cwd>/<uuid>.jsonl)
25// on the local clone's refs/klaus/data at sessions/<run-id>.jsonl. On 'klaus
26// launch --pr' against a paused PR, or 'klaus launch --change', we read that
27// blob and restore it into the *new* worktree's project dir, then invoke
28// 'claude --resume <uuid>'. claude
29// re-anchors to the new cwd; the conversation picks up where it paused. The
30// ref reaches origin only when push_data_ref is set, so by default replay
31// works only on the machine whose clone ran the paused agent.
32//
33// IMPORTANT: this is NOT the stream-json log at logs/<run-id>.jsonl —
34// claude --resume rejects that format ("No conversation found"). The two
35// are different schemas; see findResumeConversation.
36//
37// Only Claude conversations are stored there. A Codex run continues a Codex
38// run by forking its session, which lives in that machine's Codex state
39// ('codex exec fork <thread>'); agy workers can't resume a conversation.
40
41// encodeProjectPath converts an absolute working directory into the directory
42// segment Claude Code uses under ~/.claude/projects. Claude replaces both '/'
43// and '.' with '-'. Verified empirically against Claude Code 2.1.x.
44func encodeProjectPath(cwd string) string {
45 if abs, err := filepath.Abs(cwd); err == nil {
46 cwd = abs
47 }
48 return strings.NewReplacer("/", "-", ".", "-").Replace(cwd)
49}
50
51// claudeProjectsDir returns ~/.claude/projects, or "" if the home dir is
52// unknown.
53func claudeProjectsDir() string {
54 home, err := os.UserHomeDir()
55 if err != nil {
56 return ""
57 }
58 return filepath.Join(home, ".claude", "projects")
59}
60
61// claudeConversationPath returns the path claude --resume reads for a session
62// whose conversation runs in worktree cwd.
63func claudeConversationPath(cwd, sessionUUID string) string {
64 base := claudeProjectsDir()
65 if base == "" {
66 return ""
67 }
68 return filepath.Join(base, encodeProjectPath(cwd), sessionUUID+".jsonl")
69}
70
71// validSessionUUID reports whether s is safe to interpolate into a filepath
72// glob/join (UUID-shaped: alphanumerics and hyphens only).
73func validSessionUUID(s string) bool {
74 if s == "" {
75 return false
76 }
77 for _, r := range s {
78 if !((r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-') {
79 return false
80 }
81 }
82 return true
83}
84
85// findClaudeConversationFile globs every project dir for a session UUID's
86// conversation file, returning the first match or "".
87func findClaudeConversationFile(sessionUUID string) string {
88 if !validSessionUUID(sessionUUID) {
89 return ""
90 }
91 base := claudeProjectsDir()
92 if base == "" {
93 return ""
94 }
95 matches, err := filepath.Glob(filepath.Join(base, "*", sessionUUID+".jsonl"))
96 if err != nil || len(matches) == 0 {
97 return ""
98 }
99 return matches[0]
100}
101
102// findResumeConversation locates the resume-able Claude conversation file for
103// a finalized run. It prefers the run's own worktree project dir, then falls
104// back to globbing all project dirs. Returns "" if the UUID is unknown or no
105// file exists.
106func findResumeConversation(state *run.State) string {
107 if state == nil || !isClaudeRun(state) {
108 return ""
109 }
110 uuid := ""
111 if state.ClaudeSessionID != nil {
112 uuid = *state.ClaudeSessionID
113 }
114 if uuid == "" && state.LogFile != nil {
115 uuid = ExtractClaudeSessionID(*state.LogFile)
116 }
117 if !validSessionUUID(uuid) {
118 return ""
119 }
120 if state.Worktree != "" {
121 if p := claudeConversationPath(state.Worktree, uuid); p != "" {
122 if fi, err := os.Stat(p); err == nil && !fi.IsDir() {
123 return p
124 }
125 }
126 }
127 return findClaudeConversationFile(uuid)
128}
129
130// stageResumeTranscript copies a prior run's Claude conversation transcript
131// into newWorktree's project dir so 'claude --resume <sessionUUID>' launched
132// there can find it. Claude scopes transcripts by working directory, so a
133// resume in a different worktree would otherwise fail with 0 turns.
134//
135// It is best-effort and self-healing: it returns true only when the transcript
136// is present at the destination and ready to resume. On any miss (the source
137// transcript is gone, the project dir can't be resolved, or the copy fails) it
138// returns false so the caller starts a fresh session — a launched agent must
139// never crash because a conversation is missing.
140func stageResumeTranscript(prevState *run.State, sessionUUID, newWorktree string) bool {
141 if !validSessionUUID(sessionUUID) {
142 return false
143 }
144 src := findResumeConversation(prevState)
145 if src == "" {
146 return false
147 }
148 dest := claudeConversationPath(newWorktree, sessionUUID)
149 if dest == "" {
150 return false
151 }
152 if src == dest {
153 // Already in the right place (e.g. same worktree) — nothing to copy.
154 return true
155 }
156 data, err := os.ReadFile(src)
157 if err != nil {
158 return false
159 }
160 if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
161 return false
162 }
163 if err := os.WriteFile(dest, data, 0o600); err != nil {
164 return false
165 }
166 return true
167}
168
169// extractConversationSessionID reads the sessionId (camelCase) from a
170// conversation-format JSONL blob. Returns "" if none is found.
171func extractConversationSessionID(data []byte) string {
172 // bufio.Reader.ReadBytes avoids the fixed buffer cap of bufio.Scanner,
173 // which would silently stop (bufio.ErrTooLong) on a single line larger
174 // than the cap — tool outputs and system prompts can exceed many MB.
175 r := bufio.NewReader(bytes.NewReader(data))
176 var ev struct {
177 SessionID string `json:"sessionId"`
178 }
179 for {
180 line, err := r.ReadBytes('\n')
181 if len(line) > 0 {
182 if uerr := json.Unmarshal(line, &ev); uerr == nil && ev.SessionID != "" {
183 return ev.SessionID
184 }
185 }
186 if err != nil {
187 break
188 }
189 }
190 return ""
191}
192
193// replayParams carries everything resolveReplay needs.
194type replayParams struct {
195 Kind backend.Kind // the new run's worker backend; "" means Claude
196 GitClient git.Client
197 Store run.StateStore
198 RepoRoot string // repo dir holding refs/klaus/data (clone dir or host repo)
199 DataRef string
200 Worktree string // the fresh worktree the resumed agent will run in
201 // The work the run continues: a PR, or, when Change is set, a change.
202 PRBranch string
203 PRNumber string
204 GHRepo string // owner/repo for gh calls (may be "")
205 Change *changeTarget // --change: the change, with its runs
206 ForceReplay bool // --replay: skip the size threshold and the paused gate
207 ThresholdKB int // max trajectory size in KB (0 disables the size check)
208}
209
210// replayDecision is the outcome of attempting trajectory replay.
211type replayDecision struct {
212 // SessionUUID is non-empty when the caller should resume it: a Claude
213 // session for claude --resume, or a Codex thread for codex exec fork.
214 // Empty means fall back to the fresh-agent flow.
215 SessionUUID string
216 // SourceRunID is the run whose conversation is continued (for logging).
217 SourceRunID string
218 // Reason explains the decision (always set, for user-facing logging).
219 Reason string
220}
221
222// resolveReplay decides whether a run that continues a PR or a change
223// resumes the conversation of the most recent run on it, and how. A PR's
224// runs are those on its branch in this session, and only a budget-paused PR
225// replays unless the user forces it; a change's are its runs in every
226// session, and replay needs no label. Only the newest run counts: an older
227// conversation never saw the work that came after it, so when the newest
228// run's can't be resumed the run starts fresh.
229//
230// A Claude run resumes a Claude run's conversation stored on the data ref,
231// restored into the new worktree's project dir; a Codex run forks a Codex
232// run's local session; agy can't resume. Any other case returns an empty
233// SessionUUID with a Reason naming the run, signalling the caller to fall
234// back to the fresh-agent flow.
235func resolveReplay(ctx context.Context, p replayParams) replayDecision {
236 kind := p.Kind
237 if kind == "" {
238 kind = backend.Claude
239 }
240 if kind == backend.Agy {
241 return replayDecision{Reason: "agy workers can't resume a conversation"}
242 }
243 candidates, reason := replayCandidates(ctx, p)
244 if len(candidates) == 0 {
245 return replayDecision{Reason: reason}
246 }
247 s := candidates[0]
248 from := s.Backend
249 if from == "" {
250 from = string(backend.Claude)
251 }
252 latest := fmt.Sprintf("the latest run, %s (%s),", s.ID, from)
253 if from != string(kind) {
254 return replayDecision{Reason: fmt.Sprintf("%s ran on another backend; a %s worker can't resume its conversation", latest, kind)}
255 }
256
257 if kind == backend.Codex {
258 thread := resolveResumeID(s, kind, p.Worktree)
259 if thread == "" {
260 return replayDecision{Reason: latest + " has no local Codex session to fork (it ran on a sandbox host, or recorded none)"}
261 }
262 return replayDecision{SessionUUID: thread, SourceRunID: s.ID, Reason: fmt.Sprintf("forking Codex session %s from run %s", thread, s.ID)}
263 }
264
265 // Best-effort: pull the data ref so a blob another machine pushed (with
266 // push_data_ref) is present. Errors are expected: no remote, ref absent
267 // from origin (the default), or a local ref ahead of origin's, which the
268 // non-forced fetch refuses to rewind. The read below uses the local ref.
269 _ = p.GitClient.FetchDataRef(ctx, p.RepoRoot, p.DataRef)
270
271 blob, err := p.GitClient.ReadDataRefFile(ctx, p.RepoRoot, p.DataRef, "sessions/"+s.ID+".jsonl")
272 if err != nil {
273 return replayDecision{Reason: latest + " has no stored conversation: it was kept off the data ref as potentially sensitive, or is on another machine"}
274 }
275 if !p.ForceReplay && p.ThresholdKB > 0 && len(blob) > p.ThresholdKB*1024 {
276 return replayDecision{Reason: fmt.Sprintf("%s has a %dKB conversation, over the %dKB threshold (use --replay to force)", latest, len(blob)/1024, p.ThresholdKB)}
277 }
278
279 uuid := extractConversationSessionID(blob)
280 if !validSessionUUID(uuid) {
281 return replayDecision{Reason: latest + " has a stored conversation with no usable session UUID"}
282 }
283
284 dest := claudeConversationPath(p.Worktree, uuid)
285 if dest == "" {
286 return replayDecision{Reason: "could not resolve Claude projects dir"}
287 }
288 if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
289 return replayDecision{Reason: fmt.Sprintf("creating project dir: %v", err)}
290 }
291 if err := os.WriteFile(dest, blob, 0o600); err != nil {
292 return replayDecision{Reason: fmt.Sprintf("restoring trajectory: %v", err)}
293 }
294 return replayDecision{
295 SessionUUID: uuid,
296 SourceRunID: s.ID,
297 Reason: fmt.Sprintf("resuming conversation from run %s (%dKB)", s.ID, len(blob)/1024),
298 }
299}
300
301// replayCandidates returns the runs whose trajectory a continuing run may
302// replay, newest first, or why there are none.
303func replayCandidates(ctx context.Context, p replayParams) ([]*run.State, string) {
304 if p.Change != nil {
305 // A track record (`klaus track`) is no run: it holds no conversation.
306 var runs []*run.State
307 for _, s := range p.Change.Runs {
308 if s.Type != "track" {
309 runs = append(runs, s)
310 }
311 }
312 if len(runs) == 0 {
313 return nil, "no prior run recorded for this change"
314 }
315 return runs, ""
316 }
317
318 // Replay only targets budget-paused PRs unless the user forces it.
319 if !p.ForceReplay {
320 paused, err := draft.HasBudgetPausedLabel(ctx, budgetPauseRunner, p.Worktree, p.GHRepo, p.PRNumber)
321 if err != nil {
322 return nil, fmt.Sprintf("could not check budget-paused label: %v", err)
323 }
324 if !paused {
325 return nil, "PR is not budget-paused"
326 }
327 }
328
329 // Find candidate runs on this branch, newest first (List() is sorted by
330 // CreatedAt descending).
331 states, err := p.Store.List()
332 if err != nil {
333 return nil, fmt.Sprintf("listing runs: %v", err)
334 }
335 var candidates []*run.State
336 for _, s := range states {
337 if s.Branch == p.PRBranch {
338 candidates = append(candidates, s)
339 }
340 }
341 if len(candidates) == 0 {
342 return nil, "no prior run recorded for this branch"
343 }
344 return candidates, ""
345}