gunk-dev/the-valley

session.go

sourcec14b0e68e9c3main's published tip history
18.5 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/flowenv"
19 "the-valley/flow/internal/git"
20 "the-valley/flow/internal/nix"
21 "the-valley/flow/internal/project"
22 "the-valley/flow/internal/projectsync"
23 "the-valley/flow/internal/run"
24 "the-valley/flow/internal/tmux"
25 "github.com/spf13/cobra"
26)
27
28var sessionCmd = &cobra.Command{
29 Use: "session",
30 Short: "Start or resume an interactive coordinator session",
31 Long: `Resumes the most recent coordinator session, or creates a new one if none exists.
32The coordinator runs in an isolated worktree, keeping the base repo clean on
33the default branch. Must be run inside a tmux session.
34
35Use 'valley flow new' to explicitly start a fresh session.
36
37If run outside a git repository, creates a scratch workspace and uses
38~/.klaus/config.json for configuration. Use 'valley flow launch --repo owner/repo'
39from inside the session to target specific repositories.`,
40 RunE: func(cmd *cobra.Command, args []string) error {
41 return runSession(cmd, false)
42 },
43}
44
45var newSessionCmd = &cobra.Command{
46 Use: "new",
47 Short: "Start a fresh coordinator session",
48 Long: `Creates a new isolated worktree and starts a fresh interactive coordinator session
49with no prior conversation context.
50
51Use this when you want to start clean instead of resuming the most recent session.`,
52 RunE: func(cmd *cobra.Command, args []string) error {
53 return runSession(cmd, true)
54 },
55}
56
57func runSession(cmd *cobra.Command, forceNew bool) error {
58 ctx := cmd.Context()
59 tmuxClient := tmux.NewExecClient()
60
61 if !tmux.InSession() {
62 return fmt.Errorf("valley flow session must be run inside a tmux session")
63 }
64
65 continueFlag, _ := cmd.Flags().GetBool("continue")
66 resumeFlag, _ := cmd.Flags().GetString("resume")
67
68 // Git repo is optional — session can run without one
69 root, _ := git.RepoRoot()
70 inRepo := root != ""
71 gitClient := git.NewExecClient()
72
73 cfg, err := config.Load(root)
74 if err != nil {
75 return err
76 }
77
78 backendFlag, _ := cmd.Flags().GetString("backend")
79 backendName := backendFlag
80 if backendName == "" {
81 backendName = cfg.DefaultCoordinatorBackend
82 }
83 kind, err := backend.Parse(backendName)
84 if err != nil {
85 return err
86 }
87 workerFlag, _ := cmd.Flags().GetString("agent-backend")
88 workerName := workerFlag
89 if workerName == "" {
90 workerName = cfg.DefaultAgentBackend
91 }
92 workerKind, err := backend.Parse(workerName)
93 if err != nil {
94 return err
95 }
96 sessionsDir, err := run.SessionsDir()
97 if err != nil {
98 return err
99 }
100
101 var id string
102 var resuming bool
103
104 switch {
105 case forceNew:
106 // Explicit fresh session via 'klaus new'
107 baseID, err := run.GenID()
108 if err != nil {
109 return err
110 }
111 id = "session-" + baseID
112 case continueFlag:
113 found, err := run.FindMostRecentSession(sessionsDir)
114 if err != nil {
115 return fmt.Errorf("finding most recent session: %w", err)
116 }
117 id = found
118 resuming = true
119 case resumeFlag != "":
120 id = resumeFlag
121 dir := filepath.Join(sessionsDir, id)
122 if _, err := os.Stat(dir); os.IsNotExist(err) {
123 return fmt.Errorf("session directory does not exist: %s", id)
124 }
125 resuming = true
126 default:
127 // Default: resume most recent session if one exists
128 found, findErr := run.FindMostRecentSession(sessionsDir)
129 if findErr == nil {
130 id = found
131 resuming = true
132 } else {
133 // No existing session — create a new one
134 baseID, err := run.GenID()
135 if err != nil {
136 return err
137 }
138 id = "session-" + baseID
139 }
140 }
141
142 store, err := run.NewHomeDirStore(id)
143 if err != nil {
144 return err
145 }
146 if err := store.EnsureDirs(); err != nil {
147 return err
148 }
149 // A coordinator may follow klaus watch from the start, before anything
150 // has emitted an event: the file has to be there for it to follow.
151 if err := event.NewLog(store.BaseDir()).Create(); err != nil {
152 return err
153 }
154
155 // Keep registered project clones up-to-date with their upstreams in the
156 // background so the coordinator sees current code. Never blocks startup;
157 // results are appended to ~/.klaus/sync.log. The current repo is excluded
158 // to avoid racing with the foreground git operations below.
159 kickoffBackgroundSync("session", root)
160
161 var branch, repoName, worktree string
162 var state *run.State
163
164 if resuming {
165 // Load existing state — carry forward backend conversation IDs,
166 // worktree path, and repo root. All ephemeral state (pane IDs,
167 // etc.) starts clean to avoid stale references after tmux restarts.
168 prevState, err := store.Load(id)
169 if err != nil {
170 return fmt.Errorf("loading session state: %w", err)
171 }
172 previousKind, parseErr := backend.Parse(prevState.Backend)
173 if parseErr != nil {
174 return parseErr
175 }
176 if backendFlag != "" && kind != previousKind {
177 return fmt.Errorf("session %s uses %s; use valley flow new --backend %s for a new conversation", id, previousKind, kind)
178 }
179 kind = previousKind
180 if workerFlag == "" && prevState.AgentBackend != "" {
181 workerKind, err = backend.Parse(prevState.AgentBackend)
182 if err != nil {
183 return err
184 }
185 }
186 worktree = prevState.Worktree
187 branch = prevState.Branch
188 if branch != "" {
189 repoName = filepath.Base(filepath.Dir(worktree))
190 } else if inRepo {
191 repoName = filepath.Base(root)
192 }
193
194 // Verify worktree still exists; recreate if cleaned up
195 if _, statErr := os.Stat(worktree); os.IsNotExist(statErr) {
196 if branch == "" {
197 if err := os.MkdirAll(worktree, 0o755); err != nil {
198 return fmt.Errorf("recreating scratch workspace: %w", err)
199 }
200 } else {
201 baseRepo := root
202 if prevState.RepoRoot != nil && *prevState.RepoRoot != "" {
203 baseRepo = *prevState.RepoRoot
204 }
205 if baseRepo == "" {
206 return fmt.Errorf("session worktree no longer exists and no repo root available: %s", worktree)
207 }
208 defaultBranch := cfg.DefaultBranch
209 if err := gitClient.FetchBranch(ctx, baseRepo, defaultBranch); err != nil {
210 return fmt.Errorf("fetching %s: %w", defaultBranch, err)
211 }
212 startPoint := "origin/" + defaultBranch
213 if err := gitClient.WorktreeAdd(ctx, baseRepo, worktree, branch, startPoint); err != nil {
214 return fmt.Errorf("recreating worktree: %w", err)
215 }
216 if err := gitClient.InstallHooks(ctx, worktree, git.Provenance{}, formatCommand(ctx, cfg, worktree)); err != nil {
217 fmt.Fprintf(os.Stderr, "warning: could not install git hooks: %v\n", err)
218 }
219 }
220 fmt.Printf("Recreated worktree at %s\n", worktree)
221 } else if branch != "" {
222 // Worktree already exists (resuming an existing session). Reinstall
223 // the hooks so sessions created before them (or where they were
224 // removed) still strip attribution trailers and format commits,
225 // and ones whose hooks were enabled in the shared config get them
226 // scoped to this worktree. InstallHooks is idempotent, so this is
227 // safe to rerun. The coordinator gets no provenance trailers: it is
228 // not a run that produces a change.
229 if err := gitClient.InstallHooks(ctx, worktree, git.Provenance{}, formatCommand(ctx, cfg, worktree)); err != nil {
230 fmt.Fprintf(os.Stderr, "warning: could not install git hooks: %v\n", err)
231 }
232 }
233
234 // Re-link the shared coordinator memory: the project dir for this
235 // worktree may have been recreated (or predate memory sharing).
236 if err := linkBackendMemory(kind, worktree); err != nil {
237 fmt.Fprintf(os.Stderr, "warning: could not link shared memory: %v\n", err)
238 }
239
240 // Clear stale tmux pane references from all agent runs in this session.
241 // After a tmux restart, pane IDs recycle and point to unrelated panes.
242 agentStates, _ := store.List()
243 for _, as := range agentStates {
244 if as.Type == "session" || as.TmuxPane == nil {
245 continue
246 }
247 as.TmuxPane = nil
248 if err := store.Save(as); err != nil {
249 slog.Warn("failed to clear stale pane from agent", "id", as.ID, "err", err)
250 }
251 }
252
253 // Build clean state, carrying forward only what matters
254 state = &run.State{
255 Backend: string(kind),
256 AgentBackend: string(workerKind),
257 ID: id,
258 Type: "session",
259 Prompt: "(interactive session)",
260 Branch: branch,
261 Worktree: worktree,
262 CreatedAt: prevState.CreatedAt,
263 RepoRoot: prevState.RepoRoot,
264 ClaudeSessionID: prevState.ClaudeSessionID,
265 BackendSessionID: prevState.BackendSessionID,
266 }
267 if err := store.Save(state); err != nil {
268 return fmt.Errorf("saving refreshed session state: %w", err)
269 }
270
271 fmt.Printf("Resuming coordinator session %s...\n", id)
272 fmt.Printf(" worktree: %s\n", worktree)
273 if branch != "" {
274 fmt.Printf(" branch: %s\n", branch)
275 }
276 } else {
277 if inRepo {
278 branch = "session/" + id
279 repoName = filepath.Base(root)
280 worktree = filepath.Join(cfg.WorktreeBase, repoName, id)
281 defaultBranch := cfg.DefaultBranch
282
283 fmt.Printf("Creating coordinator session %s...\n", id)
284
285 if err := gitClient.FetchBranch(ctx, root, defaultBranch); err != nil {
286 return fmt.Errorf("fetching %s: %w", defaultBranch, err)
287 }
288
289 startPoint := "origin/" + defaultBranch
290 if err := gitClient.WorktreeAdd(ctx, root, worktree, branch, startPoint); err != nil {
291 return fmt.Errorf("creating worktree: %w", err)
292 }
293 fmt.Printf(" worktree: %s\n", worktree)
294 fmt.Printf(" branch: %s\n", branch)
295
296 if err := gitClient.InstallHooks(ctx, worktree, git.Provenance{}, formatCommand(ctx, cfg, worktree)); err != nil {
297 fmt.Fprintf(os.Stderr, "warning: could not install git hooks: %v\n", err)
298 }
299
300 // Set up Nix dev environment if flake.nix exists
301 nix.SetupDevEnvironment(worktree)
302 } else {
303 // No repo — use a scratch workspace
304 worktree = filepath.Join(store.BaseDir(), "workspace")
305 if err := os.MkdirAll(worktree, 0o755); err != nil {
306 return fmt.Errorf("creating scratch workspace: %w", err)
307 }
308
309 fmt.Printf("Creating coordinator session %s (no repo)...\n", id)
310 fmt.Printf(" workspace: %s\n", worktree)
311 }
312
313 if err := trustBackendWorktree(kind, worktree); err != nil {
314 fmt.Fprintf(os.Stderr, "warning: could not pre-trust worktree: %v\n", err)
315 }
316
317 if err := linkBackendMemory(kind, worktree); err != nil {
318 fmt.Fprintf(os.Stderr, "warning: could not link shared memory: %v\n", err)
319 }
320
321 // Write state
322 createdAt := time.Now().Format(time.RFC3339)
323 var repoRoot *string
324 if inRepo {
325 repoRoot = &root
326 }
327 state = &run.State{
328 Backend: string(kind),
329 AgentBackend: string(workerKind),
330 ID: id,
331 Type: "session",
332 Prompt: "(interactive session)",
333 Branch: branch,
334 Worktree: worktree,
335 CreatedAt: createdAt,
336 RepoRoot: repoRoot,
337 }
338 if err := store.Save(state); err != nil {
339 return fmt.Errorf("saving state: %w", err)
340 }
341 }
342
343 // Load project list for session prompt
344 var projectList string
345 if reg, loadErr := project.Load(); loadErr == nil {
346 projectList = config.FormatProjectList(reg.List(), reg.Descriptions)
347 }
348
349 // Render session system prompt
350 sessionPrompt, err := config.RenderSessionPrompt(root, config.PromptVars{
351 RunID: id,
352 Branch: branch,
353 RepoName: repoName,
354 Projects: projectList,
355 Coordinator: string(kind),
356 })
357 if err != nil {
358 return fmt.Errorf("rendering session prompt: %w", err)
359 }
360
361 if kind != backend.Claude {
362 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."
363 }
364 // Configure tmux window for better situational awareness
365 currentPane := os.Getenv("TMUX_PANE")
366 if currentPane != "" {
367 windowTitle := repoName
368 if windowTitle == "" {
369 windowTitle = "klaus"
370 }
371 tmuxClient.SetWindowOption(ctx, currentPane, "automatic-rename", "off")
372 tmuxClient.RenameWindow(ctx, currentPane, windowTitle)
373 tmuxClient.SetWindowOption(ctx, currentPane, "pane-border-status", "top")
374 tmuxClient.SetWindowOption(ctx, currentPane, "pane-border-format", "#{pane_title}")
375
376 // Persist the coordinator pane so the dashboard can route "discuss"
377 // requests (the 'd' keybinding) to this coordinator session.
378 state.CoordinatorPane = &currentPane
379 if err := store.Save(state); err != nil {
380 slog.Warn("failed to persist coordinator pane", "id", state.ID, "err", err)
381 }
382 }
383
384 fmt.Println()
385 fmt.Printf("Starting interactive %s session...\n", kind)
386 fmt.Println(" Use 'valley flow launch' from inside to spawn workers.")
387 fmt.Println()
388
389 // Launch dashboard in a bottom pane before starting the coordinator.
390 var dashPane string
391 if currentPane != "" {
392 paneID, err := tmuxClient.SplitWindowSized(ctx, currentPane, worktree, dashboardPaneCommand(id), "-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 = coordinatorEnv(os.Environ(), id, kind, 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}
563
564// dashboardPaneCommand runs the dashboard of session id in a pane.
565func dashboardPaneCommand(id string) string {
566 return flowenv.SessionID.EnvPrefix(id) + "klaus dashboard"
567}
568
569// coordinatorEnv is the environment a session's coordinator starts with:
570// environ, with the session's ID, the coordinator's backend and the
571// session's default worker backend.
572func coordinatorEnv(environ []string, id string, kind, workerKind backend.Kind) []string {
573 env := flowenv.SessionID.Set(environ, id)
574 env = flowenv.Backend.Set(env, string(kind))
575 return flowenv.AgentBackend.Set(env, string(workerKind))
576}