gunk-dev/the-valley

session.go

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