gunk-dev/the-valley

session.go

source28abc5737165main's published tip history
18.3 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 // The coordinator arms klaus watch at start, before anything has emitted
149 // an event: the file has to be there for it to follow. A coordinator
150 // without Monitor starts its first one-shot watch from the file's size
151 // now, so it misses nothing that lands before it arms the watch.
152 events := event.NewLog(store.BaseDir())
153 if err := events.Create(); err != nil {
154 return err
155 }
156 var watchAfter int64
157 if info, err := os.Stat(events.Path()); err == nil {
158 watchAfter = info.Size()
159 }
160
161 // Keep registered project clones up-to-date with their upstreams in the
162 // background so the coordinator sees current code. Never blocks startup;
163 // results are appended to ~/.klaus/sync.log. The current repo is excluded
164 // to avoid racing with the foreground git operations below.
165 kickoffBackgroundSync("session", root)
166
167 var branch, repoName, worktree string
168 var state *run.State
169
170 if resuming {
171 // Load existing state — carry forward backend conversation IDs,
172 // worktree path, and repo root. All ephemeral state (pane IDs,
173 // etc.) starts clean to avoid stale references after tmux restarts.
174 prevState, err := store.Load(id)
175 if err != nil {
176 return fmt.Errorf("loading session state: %w", err)
177 }
178 previousKind, parseErr := backend.Parse(prevState.Backend)
179 if parseErr != nil {
180 return parseErr
181 }
182 if backendFlag != "" && kind != previousKind {
183 return fmt.Errorf("session %s uses %s; use valley flow new --backend %s for a new conversation", id, previousKind, kind)
184 }
185 kind = previousKind
186 if workerFlag == "" && prevState.AgentBackend != "" {
187 workerKind, err = backend.Parse(prevState.AgentBackend)
188 if err != nil {
189 return err
190 }
191 }
192 worktree = prevState.Worktree
193 branch = prevState.Branch
194 if branch != "" {
195 repoName = filepath.Base(filepath.Dir(worktree))
196 } else if inRepo {
197 repoName = filepath.Base(root)
198 }
199
200 // Verify worktree still exists; recreate if cleaned up
201 if _, statErr := os.Stat(worktree); os.IsNotExist(statErr) {
202 if branch == "" {
203 if err := os.MkdirAll(worktree, 0o755); err != nil {
204 return fmt.Errorf("recreating scratch workspace: %w", err)
205 }
206 } else {
207 baseRepo := root
208 if prevState.RepoRoot != nil && *prevState.RepoRoot != "" {
209 baseRepo = *prevState.RepoRoot
210 }
211 if baseRepo == "" {
212 return fmt.Errorf("session worktree no longer exists and no repo root available: %s", worktree)
213 }
214 defaultBranch := cfg.DefaultBranch
215 if err := gitClient.FetchBranch(ctx, baseRepo, defaultBranch); err != nil {
216 return fmt.Errorf("fetching %s: %w", defaultBranch, err)
217 }
218 startPoint := "origin/" + defaultBranch
219 if err := gitClient.WorktreeAdd(ctx, baseRepo, worktree, branch, startPoint); err != nil {
220 return fmt.Errorf("recreating worktree: %w", err)
221 }
222 if err := gitClient.InstallHooks(ctx, worktree, git.Provenance{}, formatCommand(ctx, cfg, worktree)); err != nil {
223 fmt.Fprintf(os.Stderr, "warning: could not install git hooks: %v\n", err)
224 }
225 }
226 fmt.Printf("Recreated worktree at %s\n", worktree)
227 } else if branch != "" {
228 // Worktree already exists (resuming an existing session). Reinstall
229 // the hooks so sessions created before them (or where they were
230 // removed) still strip attribution trailers and format commits,
231 // and ones whose hooks were enabled in the shared config get them
232 // scoped to this worktree. InstallHooks is idempotent, so this is
233 // safe to rerun. The coordinator gets no provenance trailers: it is
234 // not a run that produces a change.
235 if err := gitClient.InstallHooks(ctx, worktree, git.Provenance{}, formatCommand(ctx, cfg, worktree)); err != nil {
236 fmt.Fprintf(os.Stderr, "warning: could not install git hooks: %v\n", err)
237 }
238 }
239
240 // Re-link the shared coordinator memory: the project dir for this
241 // worktree may have been recreated (or predate memory sharing).
242 if err := linkBackendMemory(kind, worktree); err != nil {
243 fmt.Fprintf(os.Stderr, "warning: could not link shared memory: %v\n", err)
244 }
245
246 // Clear stale tmux pane references from all agent runs in this session.
247 // After a tmux restart, pane IDs recycle and point to unrelated panes.
248 agentStates, _ := store.List()
249 for _, as := range agentStates {
250 if as.Type == "session" || as.TmuxPane == nil {
251 continue
252 }
253 as.TmuxPane = nil
254 if err := store.Save(as); err != nil {
255 slog.Warn("failed to clear stale pane from agent", "id", as.ID, "err", err)
256 }
257 }
258
259 // Build clean state, carrying forward only what matters
260 state = &run.State{
261 Backend: string(kind),
262 AgentBackend: string(workerKind),
263 ID: id,
264 Type: "session",
265 Prompt: "(interactive session)",
266 Branch: branch,
267 Worktree: worktree,
268 CreatedAt: prevState.CreatedAt,
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 RepoRoot: repoRoot,
343 }
344 if err := store.Save(state); err != nil {
345 return fmt.Errorf("saving state: %w", err)
346 }
347 }
348
349 // Load project list for session prompt
350 var projectList string
351 if reg, loadErr := project.Load(); loadErr == nil {
352 projectList = config.FormatProjectList(reg.List(), reg.Descriptions)
353 }
354
355 // Render session system prompt
356 sessionPrompt, err := config.RenderSessionPrompt(root, config.PromptVars{
357 RunID: id,
358 Branch: branch,
359 RepoName: repoName,
360 Projects: projectList,
361 Coordinator: string(kind),
362 WatchAfter: watchAfter,
363 })
364 if err != nil {
365 return fmt.Errorf("rendering session prompt: %w", err)
366 }
367
368 if kind != backend.Claude {
369 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."
370 }
371 // Configure tmux window for better situational awareness
372 currentPane := os.Getenv("TMUX_PANE")
373 if currentPane != "" {
374 windowTitle := repoName
375 if windowTitle == "" {
376 windowTitle = "klaus"
377 }
378 tmuxClient.SetWindowOption(ctx, currentPane, "automatic-rename", "off")
379 tmuxClient.RenameWindow(ctx, currentPane, windowTitle)
380 tmuxClient.SetWindowOption(ctx, currentPane, "pane-border-status", "top")
381 tmuxClient.SetWindowOption(ctx, currentPane, "pane-border-format", "#{pane_title}")
382
383 // Persist the coordinator pane so the dashboard can route "discuss"
384 // requests (the 'd' keybinding) to this coordinator session.
385 state.CoordinatorPane = &currentPane
386 if err := store.Save(state); err != nil {
387 slog.Warn("failed to persist coordinator pane", "id", state.ID, "err", err)
388 }
389 }
390
391 fmt.Println()
392 fmt.Printf("Starting interactive %s session...\n", kind)
393 fmt.Println(" Use 'valley flow launch' from inside to spawn workers.")
394 fmt.Println()
395
396 // Launch dashboard in a bottom pane before starting the coordinator.
397 var dashPane string
398 if currentPane != "" {
399 dashCmd := fmt.Sprintf("KLAUS_SESSION_ID=%s klaus dashboard", id)
400 paneID, err := tmuxClient.SplitWindowSized(ctx, currentPane, worktree, dashCmd, "-v", "30%")
401 if err != nil {
402 fmt.Fprintf(os.Stderr, "warning: could not open dashboard pane: %v\n", err)
403 } else {
404 dashPane = paneID
405 state.DashboardPane = &dashPane
406 if err := store.Save(state); err != nil {
407 fmt.Fprintf(os.Stderr, "warning: could not persist dashboard pane: %v\n", err)
408 }
409 }
410 }
411
412 opts := backend.Options{SystemPrompt: sessionPrompt, RunID: id, Continue: resuming}
413 // A coordinator with a worktree gets a status line naming its repo, from
414 // a file in the session's state, rewritten on every start or resume.
415 if kind == backend.Claude && branch != "" {
416 path := claudeSettingsPath(store, id)
417 if err := writeClaudeSettings(path, repoName); err != nil {
418 fmt.Fprintf(os.Stderr, "warning: could not write the coordinator's status line settings: %v\n", err)
419 } else {
420 opts.SettingsFile = path
421 }
422 }
423 if kind == backend.Claude {
424 if state.ClaudeSessionID != nil {
425 opts.ResumeID = *state.ClaudeSessionID
426 }
427 if !resuming {
428 opts.ResumeID = genUUIDv4()
429 state.ClaudeSessionID = stringPtr(opts.ResumeID)
430 if err := store.Save(state); err != nil {
431 return err
432 }
433 }
434 }
435 if kind == backend.Agy && resuming {
436 if state.BackendSessionID != nil {
437 opts.ResumeID = *state.BackendSessionID
438 }
439 if opts.ResumeID == "" {
440 opts.ResumeID = backend.AgyConversationID(worktree)
441 }
442 if opts.ResumeID == "" {
443 fmt.Fprintln(os.Stderr, "warning: no agy conversation recorded for this workspace; starting fresh")
444 }
445 }
446 fmt.Printf("Coordinator: %s; default workers: %s\n", kind, workerKind)
447 argv := kind.Coordinator(opts)
448 coordinator := exec.Command(argv[0], argv[1:]...)
449 coordinator.Dir = worktree
450 coordinator.Stdin = os.Stdin
451 coordinator.Stdout = os.Stdout
452 coordinator.Stderr = os.Stderr
453 coordinator.Env = append(os.Environ(), sessionIDEnv+"="+id, "KLAUS_BACKEND="+string(kind), "KLAUS_AGENT_BACKEND="+string(workerKind))
454 coordinatorErr := coordinator.Run()
455 if kind == backend.Agy {
456 if sid := backend.AgyConversationID(worktree); sid != "" {
457 state.BackendSessionID = &sid
458 if err := store.Save(state); err != nil {
459 return err
460 }
461 }
462 }
463
464 fmt.Println()
465 fmt.Printf("Session %s ended.\n", id)
466
467 // Install signal handler so Ctrl+C during post-exit work exits promptly.
468 sigCtx, sigStop := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM)
469 defer sigStop()
470
471 // Check for running agents and print a summary instead of blocking.
472 running := checkRunningAgents(sigCtx, store, tmuxClient)
473
474 if dashPane != "" {
475 if len(running) > 0 {
476 fmt.Println("Dashboard pane left open to monitor running agents.")
477 } else {
478 if err := tmuxClient.KillPane(sigCtx, dashPane); err != nil {
479 fmt.Fprintf(os.Stderr, "warning: could not kill dashboard pane %s: %v\n", dashPane, err)
480 }
481 }
482 }
483
484 if inRepo {
485 fmt.Printf(" Worktree preserved at: %s\n", worktree)
486 }
487 fmt.Printf(" To clean up: valley flow cleanup %s\n", id)
488 if coordinatorErr != nil {
489 return fmt.Errorf("%s coordinator exited: %w", kind, coordinatorErr)
490 }
491 return nil
492}
493
494// kickoffBackgroundSync fires projectsync.Sync in a goroutine and writes its
495// results to ~/.klaus/sync.log. The foreground caller is not blocked. The
496// goroutine uses a detached context so it survives past the foreground
497// command's lifetime (bounded by projectsync.PerRepoTimeout per repo).
498//
499// excludePath is the absolute path of any repo the foreground caller is about
500// to operate on; it's skipped to avoid racing with concurrent git operations
501// (e.g., FETCH_HEAD.lock contention).
502func kickoffBackgroundSync(source, excludePath string) {
503 reg, err := project.Load()
504 if err != nil || reg == nil || len(reg.Projects) == 0 {
505 return
506 }
507 go func() {
508 results := projectsync.Sync(context.Background(), reg, git.NewExecClient(), excludePath)
509 projectsync.WriteLog(source, results)
510 }()
511}
512
513// checkRunningAgents inspects agent states and returns those still running
514// in tmux panes. It prints a summary so the user knows what's still active.
515// It does not block — agents continue in their tmux panes independently.
516func checkRunningAgents(ctx context.Context, store run.StateStore, tc tmux.Client) []*run.State {
517 states, err := store.List()
518 if err != nil {
519 slog.Warn("failed to list agent states", "err", err)
520 return nil
521 }
522
523 td := run.TmuxDepsFor(ctx, tc)
524
525 var running []*run.State
526 for _, s := range states {
527 if ctx.Err() != nil {
528 break
529 }
530 if s.Type == "session" {
531 continue
532 }
533 if s.IsAgentRunningWith(td) {
534 running = append(running, s)
535 }
536 }
537
538 if len(running) == 0 {
539 fmt.Println("No agents running.")
540 return nil
541 }
542
543 fmt.Printf("%d agent(s) still running:\n", len(running))
544 for _, s := range running {
545 fmt.Printf(" - %s (pane %s)\n", s.ID, *s.TmuxPane)
546 }
547 return running
548}
549
550// genUUIDv4 returns a random UUID v4 string, or "" on error.
551func genUUIDv4() string {
552 var b [16]byte
553 if _, err := rand.Read(b[:]); err != nil {
554 return ""
555 }
556 b[6] = (b[6] & 0x0f) | 0x40 // version 4
557 b[8] = (b[8] & 0x3f) | 0x80 // variant 1
558 return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
559}
560
561func init() {
562 for _, c := range []*cobra.Command{rootCmd, sessionCmd, newSessionCmd} {
563 c.Flags().String("backend", "", "Coordinator backend: claude, codex, or agy (default from config; saved on session)")
564 c.Flags().String("agent-backend", "", "Default worker backend: claude, codex, or agy (independent of coordinator)")
565 }
566 sessionCmd.Flags().Bool("continue", false, "Resume the most recent coordinator session")
567 sessionCmd.Flags().String("resume", "", "Resume a specific session by ID")
568 rootCmd.AddCommand(sessionCmd)
569 rootCmd.AddCommand(newSessionCmd)
570}