gunk-dev/the-valley

session.go

sourcecaaa5bee5e11main's published tip history
18.0 KiB
1package cmd
2
3import (
4 "context"
5 "crypto/rand"
6 "fmt"
7 "log/slog"
8 "os"
9 "os/exec"
10 "os/signal"
11 "path/filepath"
12 "syscall"
13 "time"
14
15 "the-valley/flow/internal/backend"
16 "the-valley/flow/internal/config"
17 "the-valley/flow/internal/event"
18 "the-valley/flow/internal/git"
19 "the-valley/flow/internal/nix"
20 "the-valley/flow/internal/project"
21 "the-valley/flow/internal/projectsync"
22 "the-valley/flow/internal/run"
23 "the-valley/flow/internal/tmux"
24 "github.com/spf13/cobra"
25)
26
27var sessionCmd = &cobra.Command{
28 Use: "session",
29 Short: "Start or resume an interactive coordinator session",
30 Long: `Resumes the most recent coordinator session, or creates a new one if none exists.
31The coordinator runs in an isolated worktree, keeping the base repo clean on
32the default branch. Must be run inside a tmux session.
33
34Use 'valley flow new' to explicitly start a fresh session.
35
36If run outside a git repository, creates a scratch workspace and uses
37~/.klaus/config.json for configuration. Use 'valley flow launch --repo owner/repo'
38from inside the session to target specific repositories.`,
39 RunE: func(cmd *cobra.Command, args []string) error {
40 return runSession(cmd, false)
41 },
42}
43
44var newSessionCmd = &cobra.Command{
45 Use: "new",
46 Short: "Start a fresh coordinator session",
47 Long: `Creates a new isolated worktree and starts a fresh interactive coordinator session
48with no prior conversation context.
49
50Use this when you want to start clean instead of resuming the most recent session.`,
51 RunE: func(cmd *cobra.Command, args []string) error {
52 return runSession(cmd, true)
53 },
54}
55
56func runSession(cmd *cobra.Command, forceNew bool) error {
57 ctx := cmd.Context()
58 tmuxClient := tmux.NewExecClient()
59
60 if !tmux.InSession() {
61 return fmt.Errorf("valley flow session must be run inside a tmux session")
62 }
63
64 continueFlag, _ := cmd.Flags().GetBool("continue")
65 resumeFlag, _ := cmd.Flags().GetString("resume")
66
67 // Git repo is optional — session can run without one
68 root, _ := git.RepoRoot()
69 inRepo := root != ""
70 gitClient := git.NewExecClient()
71
72 cfg, err := config.Load(root)
73 if err != nil {
74 return err
75 }
76
77 backendFlag, _ := cmd.Flags().GetString("backend")
78 backendName := backendFlag
79 if backendName == "" {
80 backendName = cfg.DefaultCoordinatorBackend
81 }
82 kind, err := backend.Parse(backendName)
83 if err != nil {
84 return err
85 }
86 workerFlag, _ := cmd.Flags().GetString("agent-backend")
87 workerName := workerFlag
88 if workerName == "" {
89 workerName = cfg.DefaultAgentBackend
90 }
91 workerKind, err := backend.Parse(workerName)
92 if err != nil {
93 return err
94 }
95 sessionsDir, err := run.SessionsDir()
96 if err != nil {
97 return err
98 }
99
100 var id string
101 var resuming bool
102
103 switch {
104 case forceNew:
105 // Explicit fresh session via 'klaus new'
106 baseID, err := run.GenID()
107 if err != nil {
108 return err
109 }
110 id = "session-" + baseID
111 case continueFlag:
112 found, err := run.FindMostRecentSession(sessionsDir)
113 if err != nil {
114 return fmt.Errorf("finding most recent session: %w", err)
115 }
116 id = found
117 resuming = true
118 case resumeFlag != "":
119 id = resumeFlag
120 dir := filepath.Join(sessionsDir, id)
121 if _, err := os.Stat(dir); os.IsNotExist(err) {
122 return fmt.Errorf("session directory does not exist: %s", id)
123 }
124 resuming = true
125 default:
126 // Default: resume most recent session if one exists
127 found, findErr := run.FindMostRecentSession(sessionsDir)
128 if findErr == nil {
129 id = found
130 resuming = true
131 } else {
132 // No existing session — create a new one
133 baseID, err := run.GenID()
134 if err != nil {
135 return err
136 }
137 id = "session-" + baseID
138 }
139 }
140
141 store, err := run.NewHomeDirStore(id)
142 if err != nil {
143 return err
144 }
145 if err := store.EnsureDirs(); err != nil {
146 return err
147 }
148 // A coordinator may follow klaus watch from the start, before anything
149 // has emitted an event: the file has to be there for it to follow.
150 if err := event.NewLog(store.BaseDir()).Create(); err != nil {
151 return err
152 }
153
154 // Keep registered project clones up-to-date with their upstreams in the
155 // background so the coordinator sees current code. Never blocks startup;
156 // results are appended to ~/.klaus/sync.log. The current repo is excluded
157 // to avoid racing with the foreground git operations below.
158 kickoffBackgroundSync("session", root)
159
160 var branch, repoName, worktree string
161 var state *run.State
162
163 if resuming {
164 // Load existing state — carry forward backend conversation IDs,
165 // worktree path, and repo root. All ephemeral state (pane IDs,
166 // etc.) starts clean to avoid stale references after tmux restarts.
167 prevState, err := store.Load(id)
168 if err != nil {
169 return fmt.Errorf("loading session state: %w", err)
170 }
171 previousKind, parseErr := backend.Parse(prevState.Backend)
172 if parseErr != nil {
173 return parseErr
174 }
175 if backendFlag != "" && kind != previousKind {
176 return fmt.Errorf("session %s uses %s; use valley flow new --backend %s for a new conversation", id, previousKind, kind)
177 }
178 kind = previousKind
179 if workerFlag == "" && prevState.AgentBackend != "" {
180 workerKind, err = backend.Parse(prevState.AgentBackend)
181 if err != nil {
182 return err
183 }
184 }
185 worktree = prevState.Worktree
186 branch = prevState.Branch
187 if branch != "" {
188 repoName = filepath.Base(filepath.Dir(worktree))
189 } else if inRepo {
190 repoName = filepath.Base(root)
191 }
192
193 // Verify worktree still exists; recreate if cleaned up
194 if _, statErr := os.Stat(worktree); os.IsNotExist(statErr) {
195 if branch == "" {
196 if err := os.MkdirAll(worktree, 0o755); err != nil {
197 return fmt.Errorf("recreating scratch workspace: %w", err)
198 }
199 } else {
200 baseRepo := root
201 if prevState.RepoRoot != nil && *prevState.RepoRoot != "" {
202 baseRepo = *prevState.RepoRoot
203 }
204 if baseRepo == "" {
205 return fmt.Errorf("session worktree no longer exists and no repo root available: %s", worktree)
206 }
207 defaultBranch := cfg.DefaultBranch
208 if err := gitClient.FetchBranch(ctx, baseRepo, defaultBranch); err != nil {
209 return fmt.Errorf("fetching %s: %w", defaultBranch, err)
210 }
211 startPoint := "origin/" + defaultBranch
212 if err := gitClient.WorktreeAdd(ctx, baseRepo, worktree, branch, startPoint); err != nil {
213 return fmt.Errorf("recreating worktree: %w", err)
214 }
215 if err := gitClient.InstallHooks(ctx, worktree, git.Provenance{}, formatCommand(ctx, cfg, worktree)); err != nil {
216 fmt.Fprintf(os.Stderr, "warning: could not install git hooks: %v\n", err)
217 }
218 }
219 fmt.Printf("Recreated worktree at %s\n", worktree)
220 } else if branch != "" {
221 // Worktree already exists (resuming an existing session). Reinstall
222 // the hooks so sessions created before them (or where they were
223 // removed) still strip attribution trailers and format commits,
224 // and ones whose hooks were enabled in the shared config get them
225 // scoped to this worktree. InstallHooks is idempotent, so this is
226 // safe to rerun. The coordinator gets no provenance trailers: it is
227 // not a run that produces a change.
228 if err := gitClient.InstallHooks(ctx, worktree, git.Provenance{}, formatCommand(ctx, cfg, worktree)); err != nil {
229 fmt.Fprintf(os.Stderr, "warning: could not install git hooks: %v\n", err)
230 }
231 }
232
233 // Re-link the shared coordinator memory: the project dir for this
234 // worktree may have been recreated (or predate memory sharing).
235 if err := linkBackendMemory(kind, worktree); err != nil {
236 fmt.Fprintf(os.Stderr, "warning: could not link shared memory: %v\n", err)
237 }
238
239 // Clear stale tmux pane references from all agent runs in this session.
240 // After a tmux restart, pane IDs recycle and point to unrelated panes.
241 agentStates, _ := store.List()
242 for _, as := range agentStates {
243 if as.Type == "session" || as.TmuxPane == nil {
244 continue
245 }
246 as.TmuxPane = nil
247 if err := store.Save(as); err != nil {
248 slog.Warn("failed to clear stale pane from agent", "id", as.ID, "err", err)
249 }
250 }
251
252 // Build clean state, carrying forward only what matters
253 state = &run.State{
254 Backend: string(kind),
255 AgentBackend: string(workerKind),
256 ID: id,
257 Type: "session",
258 Prompt: "(interactive session)",
259 Branch: branch,
260 Worktree: worktree,
261 CreatedAt: prevState.CreatedAt,
262 RepoRoot: prevState.RepoRoot,
263 ClaudeSessionID: prevState.ClaudeSessionID,
264 BackendSessionID: prevState.BackendSessionID,
265 }
266 if err := store.Save(state); err != nil {
267 return fmt.Errorf("saving refreshed session state: %w", err)
268 }
269
270 fmt.Printf("Resuming coordinator session %s...\n", id)
271 fmt.Printf(" worktree: %s\n", worktree)
272 if branch != "" {
273 fmt.Printf(" branch: %s\n", branch)
274 }
275 } else {
276 if inRepo {
277 branch = "session/" + id
278 repoName = filepath.Base(root)
279 worktree = filepath.Join(cfg.WorktreeBase, repoName, id)
280 defaultBranch := cfg.DefaultBranch
281
282 fmt.Printf("Creating coordinator session %s...\n", id)
283
284 if err := gitClient.FetchBranch(ctx, root, defaultBranch); err != nil {
285 return fmt.Errorf("fetching %s: %w", defaultBranch, err)
286 }
287
288 startPoint := "origin/" + defaultBranch
289 if err := gitClient.WorktreeAdd(ctx, root, worktree, branch, startPoint); err != nil {
290 return fmt.Errorf("creating worktree: %w", err)
291 }
292 fmt.Printf(" worktree: %s\n", worktree)
293 fmt.Printf(" branch: %s\n", branch)
294
295 if err := gitClient.InstallHooks(ctx, worktree, git.Provenance{}, formatCommand(ctx, cfg, worktree)); err != nil {
296 fmt.Fprintf(os.Stderr, "warning: could not install git hooks: %v\n", err)
297 }
298
299 // Set up Nix dev environment if flake.nix exists
300 nix.SetupDevEnvironment(worktree)
301 } else {
302 // No repo — use a scratch workspace
303 worktree = filepath.Join(store.BaseDir(), "workspace")
304 if err := os.MkdirAll(worktree, 0o755); err != nil {
305 return fmt.Errorf("creating scratch workspace: %w", err)
306 }
307
308 fmt.Printf("Creating coordinator session %s (no repo)...\n", id)
309 fmt.Printf(" workspace: %s\n", worktree)
310 }
311
312 if err := trustBackendWorktree(kind, worktree); err != nil {
313 fmt.Fprintf(os.Stderr, "warning: could not pre-trust worktree: %v\n", err)
314 }
315
316 if err := linkBackendMemory(kind, worktree); err != nil {
317 fmt.Fprintf(os.Stderr, "warning: could not link shared memory: %v\n", err)
318 }
319
320 // Write state
321 createdAt := time.Now().Format(time.RFC3339)
322 var repoRoot *string
323 if inRepo {
324 repoRoot = &root
325 }
326 state = &run.State{
327 Backend: string(kind),
328 AgentBackend: string(workerKind),
329 ID: id,
330 Type: "session",
331 Prompt: "(interactive session)",
332 Branch: branch,
333 Worktree: worktree,
334 CreatedAt: createdAt,
335 RepoRoot: repoRoot,
336 }
337 if err := store.Save(state); err != nil {
338 return fmt.Errorf("saving state: %w", err)
339 }
340 }
341
342 // Load project list for session prompt
343 var projectList string
344 if reg, loadErr := project.Load(); loadErr == nil {
345 projectList = config.FormatProjectList(reg.List(), reg.Descriptions)
346 }
347
348 // Render session system prompt
349 sessionPrompt, err := config.RenderSessionPrompt(root, config.PromptVars{
350 RunID: id,
351 Branch: branch,
352 RepoName: repoName,
353 Projects: projectList,
354 Coordinator: string(kind),
355 })
356 if err != nil {
357 return fmt.Errorf("rendering session prompt: %w", err)
358 }
359
360 if kind != backend.Claude {
361 sessionPrompt += "\n\nBackend note: You are running " + string(kind) + ". Use valley flow status and valley flow logs to inspect workers. Do not assume Claude-specific memory or conversation replay."
362 }
363 // Configure tmux window for better situational awareness
364 currentPane := os.Getenv("TMUX_PANE")
365 if currentPane != "" {
366 windowTitle := repoName
367 if windowTitle == "" {
368 windowTitle = "klaus"
369 }
370 tmuxClient.SetWindowOption(ctx, currentPane, "automatic-rename", "off")
371 tmuxClient.RenameWindow(ctx, currentPane, windowTitle)
372 tmuxClient.SetWindowOption(ctx, currentPane, "pane-border-status", "top")
373 tmuxClient.SetWindowOption(ctx, currentPane, "pane-border-format", "#{pane_title}")
374
375 // Persist the coordinator pane so the dashboard can route "discuss"
376 // requests (the 'd' keybinding) to this coordinator session.
377 state.CoordinatorPane = &currentPane
378 if err := store.Save(state); err != nil {
379 slog.Warn("failed to persist coordinator pane", "id", state.ID, "err", err)
380 }
381 }
382
383 fmt.Println()
384 fmt.Printf("Starting interactive %s session...\n", kind)
385 fmt.Println(" Use 'valley flow launch' from inside to spawn workers.")
386 fmt.Println()
387
388 // Launch dashboard in a bottom pane before starting the coordinator.
389 var dashPane string
390 if currentPane != "" {
391 dashCmd := fmt.Sprintf("KLAUS_SESSION_ID=%s klaus dashboard", id)
392 paneID, err := tmuxClient.SplitWindowSized(ctx, currentPane, worktree, dashCmd, "-v", "30%")
393 if err != nil {
394 fmt.Fprintf(os.Stderr, "warning: could not open dashboard pane: %v\n", err)
395 } else {
396 dashPane = paneID
397 state.DashboardPane = &dashPane
398 if err := store.Save(state); err != nil {
399 fmt.Fprintf(os.Stderr, "warning: could not persist dashboard pane: %v\n", err)
400 }
401 }
402 }
403
404 opts := backend.Options{SystemPrompt: sessionPrompt, RunID: id, Continue: resuming}
405 // A coordinator with a worktree gets a status line naming its repo, from
406 // a file in the session's state, rewritten on every start or resume.
407 if kind == backend.Claude && branch != "" {
408 path := claudeSettingsPath(store, id)
409 if err := writeClaudeSettings(path, repoName); err != nil {
410 fmt.Fprintf(os.Stderr, "warning: could not write the coordinator's status line settings: %v\n", err)
411 } else {
412 opts.SettingsFile = path
413 }
414 }
415 if kind == backend.Claude {
416 if state.ClaudeSessionID != nil {
417 opts.ResumeID = *state.ClaudeSessionID
418 }
419 if !resuming {
420 opts.ResumeID = genUUIDv4()
421 state.ClaudeSessionID = stringPtr(opts.ResumeID)
422 if err := store.Save(state); err != nil {
423 return err
424 }
425 }
426 }
427 if kind == backend.Agy && resuming {
428 if state.BackendSessionID != nil {
429 opts.ResumeID = *state.BackendSessionID
430 }
431 if opts.ResumeID == "" {
432 opts.ResumeID = backend.AgyConversationID(worktree)
433 }
434 if opts.ResumeID == "" {
435 fmt.Fprintln(os.Stderr, "warning: no agy conversation recorded for this workspace; starting fresh")
436 }
437 }
438 fmt.Printf("Coordinator: %s; default workers: %s\n", kind, workerKind)
439 argv := kind.Coordinator(opts)
440 coordinator := exec.Command(argv[0], argv[1:]...)
441 coordinator.Dir = worktree
442 coordinator.Stdin = os.Stdin
443 coordinator.Stdout = os.Stdout
444 coordinator.Stderr = os.Stderr
445 coordinator.Env = append(os.Environ(), sessionIDEnv+"="+id, "KLAUS_BACKEND="+string(kind), "KLAUS_AGENT_BACKEND="+string(workerKind))
446 coordinatorErr := coordinator.Run()
447 if kind == backend.Agy {
448 if sid := backend.AgyConversationID(worktree); sid != "" {
449 state.BackendSessionID = &sid
450 if err := store.Save(state); err != nil {
451 return err
452 }
453 }
454 }
455
456 fmt.Println()
457 fmt.Printf("Session %s ended.\n", id)
458
459 // Install signal handler so Ctrl+C during post-exit work exits promptly.
460 sigCtx, sigStop := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM)
461 defer sigStop()
462
463 // Check for running agents and print a summary instead of blocking.
464 running := checkRunningAgents(sigCtx, store, tmuxClient)
465
466 if dashPane != "" {
467 if len(running) > 0 {
468 fmt.Println("Dashboard pane left open to monitor running agents.")
469 } else {
470 if err := tmuxClient.KillPane(sigCtx, dashPane); err != nil {
471 fmt.Fprintf(os.Stderr, "warning: could not kill dashboard pane %s: %v\n", dashPane, err)
472 }
473 }
474 }
475
476 if inRepo {
477 fmt.Printf(" Worktree preserved at: %s\n", worktree)
478 }
479 fmt.Printf(" To clean up: valley flow cleanup %s\n", id)
480 if coordinatorErr != nil {
481 return fmt.Errorf("%s coordinator exited: %w", kind, coordinatorErr)
482 }
483 return nil
484}
485
486// kickoffBackgroundSync fires projectsync.Sync in a goroutine and writes its
487// results to ~/.klaus/sync.log. The foreground caller is not blocked. The
488// goroutine uses a detached context so it survives past the foreground
489// command's lifetime (bounded by projectsync.PerRepoTimeout per repo).
490//
491// excludePath is the absolute path of any repo the foreground caller is about
492// to operate on; it's skipped to avoid racing with concurrent git operations
493// (e.g., FETCH_HEAD.lock contention).
494func kickoffBackgroundSync(source, excludePath string) {
495 reg, err := project.Load()
496 if err != nil || reg == nil || len(reg.Projects) == 0 {
497 return
498 }
499 go func() {
500 results := projectsync.Sync(context.Background(), reg, git.NewExecClient(), excludePath)
501 projectsync.WriteLog(source, results)
502 }()
503}
504
505// checkRunningAgents inspects agent states and returns those still running
506// in tmux panes. It prints a summary so the user knows what's still active.
507// It does not block — agents continue in their tmux panes independently.
508func checkRunningAgents(ctx context.Context, store run.StateStore, tc tmux.Client) []*run.State {
509 states, err := store.List()
510 if err != nil {
511 slog.Warn("failed to list agent states", "err", err)
512 return nil
513 }
514
515 td := run.TmuxDepsFor(ctx, tc)
516
517 var running []*run.State
518 for _, s := range states {
519 if ctx.Err() != nil {
520 break
521 }
522 if s.Type == "session" {
523 continue
524 }
525 if s.IsAgentRunningWith(td) {
526 running = append(running, s)
527 }
528 }
529
530 if len(running) == 0 {
531 fmt.Println("No agents running.")
532 return nil
533 }
534
535 fmt.Printf("%d agent(s) still running:\n", len(running))
536 for _, s := range running {
537 fmt.Printf(" - %s (pane %s)\n", s.ID, *s.TmuxPane)
538 }
539 return running
540}
541
542// genUUIDv4 returns a random UUID v4 string, or "" on error.
543func genUUIDv4() string {
544 var b [16]byte
545 if _, err := rand.Read(b[:]); err != nil {
546 return ""
547 }
548 b[6] = (b[6] & 0x0f) | 0x40 // version 4
549 b[8] = (b[8] & 0x3f) | 0x80 // variant 1
550 return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
551}
552
553func init() {
554 for _, c := range []*cobra.Command{rootCmd, sessionCmd, newSessionCmd} {
555 c.Flags().String("backend", "", "Coordinator backend: claude, codex, or agy (default from config; saved on session)")
556 c.Flags().String("agent-backend", "", "Default worker backend: claude, codex, or agy (independent of coordinator)")
557 }
558 sessionCmd.Flags().Bool("continue", false, "Resume the most recent coordinator session")
559 sessionCmd.Flags().String("resume", "", "Resume a specific session by ID")
560 rootCmd.AddCommand(sessionCmd)
561 rootCmd.AddCommand(newSessionCmd)
562}