gunk-dev/the-valley

session.go

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