gunk-dev/the-valley

session.go

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