| 1 | // Package location says where each kind of flow state is. It is the only |
| 2 | // code that spells the directories flow keeps state in, and the tmux |
| 3 | // sessions its agents run in. |
| 4 | // |
| 5 | // Flow's state has two sets of names: the legacy ones (~/.klaus, |
| 6 | // <project>/.klaus, $XDG_STATE_HOME/klaus, <git-common-dir>/klaus) and the |
| 7 | // flow ones (~/.valley/flow, <project>/.valley/flow, |
| 8 | // <git-common-dir>/valley/flow). Flow finds and operates state under |
| 9 | // either, by the rule each kind needs: |
| 10 | // |
| 11 | // - a declaration (host config, project config, each prompt template, |
| 12 | // principles) is the file under the flow names when one is there, else |
| 13 | // the legacy file; |
| 14 | // - a single-valued mutable file or directory (project registry, |
| 15 | // self-update state, memory) is the one that exists, and having both is |
| 16 | // an error; |
| 17 | // - sessions are enumerated under both roots, and a session ID names one |
| 18 | // directory; |
| 19 | // - a lock that moves is held at both paths; |
| 20 | // - new state goes where the host's naming_generation says. |
| 21 | // |
| 22 | // Nothing is moved, and every generation gives new state the legacy names: |
| 23 | // sessions outlive updates, records hold absolute paths, and an older build |
| 24 | // may still be running. |
| 25 | package location |
| 26 | |
| 27 | import ( |
| 28 | "encoding/json" |
| 29 | "errors" |
| 30 | "fmt" |
| 31 | "io/fs" |
| 32 | "os" |
| 33 | "path/filepath" |
| 34 | "sort" |
| 35 | "strings" |
| 36 | ) |
| 37 | |
| 38 | // Generation is a value of the host-only naming_generation setting: which |
| 39 | // names new state gets. |
| 40 | type Generation string |
| 41 | |
| 42 | const ( |
| 43 | // Legacy gives every new object the legacy names. |
| 44 | Legacy Generation = "legacy" |
| 45 | // Bridge is to give new home and project state the flow names |
| 46 | // (~/.valley/flow, <project>/.valley/flow), keeping the legacy names |
| 47 | // for the plumbing older builds share. |
| 48 | Bridge Generation = "bridge" |
| 49 | // Flow is to give every new object the flow names, the plumbing too. |
| 50 | Flow Generation = "flow" |
| 51 | ) |
| 52 | |
| 53 | // Generations are the generations in the order a host advances through |
| 54 | // them. |
| 55 | var Generations = []Generation{Legacy, Bridge, Flow} |
| 56 | |
| 57 | // ParseGeneration reads a naming_generation value; unset is Legacy. |
| 58 | func ParseGeneration(s string) (Generation, error) { |
| 59 | switch g := Generation(s); g { |
| 60 | case "": |
| 61 | return Legacy, nil |
| 62 | case Legacy, Bridge, Flow: |
| 63 | return g, nil |
| 64 | } |
| 65 | return "", fmt.Errorf("naming_generation %q is none of legacy, bridge and flow", s) |
| 66 | } |
| 67 | |
| 68 | // Next is the generation a host advances to from g, or "" from Flow. |
| 69 | func (g Generation) Next() Generation { |
| 70 | for i, x := range Generations { |
| 71 | if x == g && i+1 < len(Generations) { |
| 72 | return Generations[i+1] |
| 73 | } |
| 74 | } |
| 75 | return "" |
| 76 | } |
| 77 | |
| 78 | // Allocates is the generation whose names this build gives new state when |
| 79 | // the host selects g: Legacy for every g. The writers that give new state |
| 80 | // the flow names are not built. |
| 81 | func Allocates(Generation) Generation { return Legacy } |
| 82 | |
| 83 | // Operates lists the generations whose stores this build finds, reads and |
| 84 | // writes: all of them, whichever is selected. |
| 85 | func Operates() []Generation { return Generations } |
| 86 | |
| 87 | // The names, legacy and flow, of each root. |
| 88 | var ( |
| 89 | legacyHome = ".klaus" // under the home directory and a project |
| 90 | flowHome = filepath.Join(".valley", "flow") // under the home directory and a project |
| 91 | legacyState = "klaus" // under $XDG_STATE_HOME |
| 92 | legacyGitDir = "klaus" // under a clone's git common directory |
| 93 | flowGitDir = filepath.Join("valley", "flow") // under a clone's git common directory |
| 94 | legacyAgents = "klaus-agents" // a detached tmux session of agent panes |
| 95 | ) |
| 96 | |
| 97 | // Layout is one user's state: where their home directory and state |
| 98 | // directory are, and which generation new state takes. |
| 99 | type Layout struct { |
| 100 | Home string // the user's home directory |
| 101 | StateHome string // $XDG_STATE_HOME when it is absolute, else Home/.local/state |
| 102 | // Gen is the generation new state takes. Empty reads naming_generation |
| 103 | // from the host config when an allocation needs it. |
| 104 | Gen Generation |
| 105 | } |
| 106 | |
| 107 | // Host is the running user's layout. |
| 108 | func Host() (Layout, error) { |
| 109 | home, err := os.UserHomeDir() |
| 110 | if err != nil { |
| 111 | return Layout{}, fmt.Errorf("resolving home dir: %w", err) |
| 112 | } |
| 113 | l := Layout{Home: home, StateHome: os.Getenv("XDG_STATE_HOME")} |
| 114 | if !filepath.IsAbs(l.StateHome) { |
| 115 | l.StateHome = filepath.Join(home, ".local", "state") |
| 116 | } |
| 117 | return l, nil |
| 118 | } |
| 119 | |
| 120 | func (l Layout) legacy(name ...string) string { |
| 121 | return filepath.Join(append([]string{l.Home, legacyHome}, name...)...) |
| 122 | } |
| 123 | |
| 124 | func (l Layout) flow(name ...string) string { |
| 125 | return filepath.Join(append([]string{l.Home, flowHome}, name...)...) |
| 126 | } |
| 127 | |
| 128 | // Generation is the generation new state takes: l.Gen, else the host |
| 129 | // config's naming_generation, Legacy when it sets none. A host config |
| 130 | // under the legacy name that can't be read or parsed sets none, so |
| 131 | // allocating never fails on it; config.Load reports one that doesn't parse. |
| 132 | func (l Layout) Generation() (Generation, error) { |
| 133 | if l.Gen != "" { |
| 134 | return ParseGeneration(string(l.Gen)) |
| 135 | } |
| 136 | path, err := l.HostConfig() |
| 137 | if err != nil { |
| 138 | return "", err |
| 139 | } |
| 140 | data, err := os.ReadFile(path) |
| 141 | if errors.Is(err, fs.ErrNotExist) { |
| 142 | return Legacy, nil |
| 143 | } |
| 144 | if err != nil { |
| 145 | if !FlowNamed(path) { |
| 146 | return Legacy, nil |
| 147 | } |
| 148 | return "", fmt.Errorf("reading host config: %w", err) |
| 149 | } |
| 150 | var c struct { |
| 151 | NamingGeneration string `json:"naming_generation"` |
| 152 | } |
| 153 | if err := json.Unmarshal(data, &c); err != nil { |
| 154 | if !FlowNamed(path) { |
| 155 | return Legacy, nil |
| 156 | } |
| 157 | return "", fmt.Errorf("parsing host config %s: %w", path, err) |
| 158 | } |
| 159 | g, err := ParseGeneration(c.NamingGeneration) |
| 160 | if err != nil { |
| 161 | return "", fmt.Errorf("host config %s: %w", path, err) |
| 162 | } |
| 163 | return g, nil |
| 164 | } |
| 165 | |
| 166 | // allocate is where new state of a kind goes, legacy being its legacy |
| 167 | // path: the legacy path under every generation, once the generation is |
| 168 | // known to be one. |
| 169 | func (l Layout) allocate(legacy string) (string, error) { |
| 170 | if _, err := l.Generation(); err != nil { |
| 171 | return "", err |
| 172 | } |
| 173 | return legacy, nil |
| 174 | } |
| 175 | |
| 176 | // declaration is the path of one declaration file: flow when a file is |
| 177 | // there, else legacy. A file there is the one even when it can't be read: |
| 178 | // reading it is the caller's, and never falls back. A symlink there to |
| 179 | // nothing is an error, since its reader would take it for no file. |
| 180 | func declaration(legacy, flow string) (string, error) { |
| 181 | _, err := os.Lstat(flow) |
| 182 | switch { |
| 183 | case err == nil: |
| 184 | if _, err := os.Stat(flow); errors.Is(err, fs.ErrNotExist) { |
| 185 | return "", fmt.Errorf("%s is a symlink to nothing", flow) |
| 186 | } |
| 187 | return flow, nil |
| 188 | case errors.Is(err, fs.ErrNotExist): |
| 189 | return legacy, nil |
| 190 | } |
| 191 | return "", fmt.Errorf("checking %s: %w", flow, err) |
| 192 | } |
| 193 | |
| 194 | // FlowNamed reports whether path, as HostConfig or ProjectFile returned |
| 195 | // it, is the file under the flow names, which its reader holds to the |
| 196 | // strict rule: one there that can't be read or parsed is an error. A |
| 197 | // legacy file is read by its reader's own rule. |
| 198 | func FlowNamed(path string) bool { |
| 199 | dir := filepath.Dir(path) |
| 200 | return filepath.Base(dir) == filepath.Base(flowHome) && filepath.Base(filepath.Dir(dir)) == filepath.Dir(flowHome) |
| 201 | } |
| 202 | |
| 203 | // HostConfig is the host config file. |
| 204 | func (l Layout) HostConfig() (string, error) { |
| 205 | return declaration(l.legacy("config.json"), l.flow("config.json")) |
| 206 | } |
| 207 | |
| 208 | // Project declaration files. |
| 209 | const ( |
| 210 | ProjectConfig = "config.json" |
| 211 | WorkerPrompt = "prompt.md" |
| 212 | FixPrompt = "pr-fix-prompt.md" |
| 213 | SessionPrompt = "session-prompt.md" |
| 214 | Principles = "principles.md" |
| 215 | ) |
| 216 | |
| 217 | // ProjectFiles are the declaration files a project can hold. |
| 218 | var ProjectFiles = []string{ProjectConfig, WorkerPrompt, FixPrompt, SessionPrompt, Principles} |
| 219 | |
| 220 | // ProjectFile is the declaration file name (ProjectConfig, WorkerPrompt, |
| 221 | // ...) of the project checked out at root. |
| 222 | func ProjectFile(root, name string) (string, error) { |
| 223 | return declaration(filepath.Join(root, legacyHome, name), filepath.Join(root, flowHome, name)) |
| 224 | } |
| 225 | |
| 226 | // ScaffoldProjectFile is where scaffolding writes the declaration file |
| 227 | // name of the project checked out at root: the file there is, else where |
| 228 | // a new one goes. |
| 229 | func (l Layout) ScaffoldProjectFile(root, name string) (string, error) { |
| 230 | return l.scaffold(filepath.Join(root, legacyHome, name), filepath.Join(root, flowHome, name)) |
| 231 | } |
| 232 | |
| 233 | // ScaffoldHostConfig is where scaffolding writes the host config: the |
| 234 | // file there is, else where a new one goes. |
| 235 | func (l Layout) ScaffoldHostConfig() (string, error) { |
| 236 | return l.scaffold(l.legacy("config.json"), l.flow("config.json")) |
| 237 | } |
| 238 | |
| 239 | func (l Layout) scaffold(legacy, flow string) (string, error) { |
| 240 | path, err := declaration(legacy, flow) |
| 241 | if err != nil || path == flow { |
| 242 | return path, err |
| 243 | } |
| 244 | if _, err := os.Lstat(legacy); err == nil { |
| 245 | return legacy, nil |
| 246 | } |
| 247 | return l.allocate(legacy) |
| 248 | } |
| 249 | |
| 250 | // ConflictError is state flow keeps in one place found in two. |
| 251 | type ConflictError struct { |
| 252 | What string // the kind of state, e.g. "the project registry" |
| 253 | Paths []string // where it is |
| 254 | } |
| 255 | |
| 256 | func (e *ConflictError) Error() string { |
| 257 | return fmt.Sprintf("%s is at both %s; flow keeps it in one place, so remove or merge one by hand", |
| 258 | e.What, strings.Join(e.Paths, " and ")) |
| 259 | } |
| 260 | |
| 261 | // one is the place of single-valued state: whichever of legacy and flow |
| 262 | // exists, and when neither does, where new state of its kind goes. Both |
| 263 | // existing is a ConflictError, unless symlinks make them one file, which |
| 264 | // is then named by its own path: a save renames a new file over the name |
| 265 | // it is given, which would replace a symlink, and parts a hard link's |
| 266 | // names. |
| 267 | func (l Layout) one(what, legacy, flow string) (string, error) { |
| 268 | _, lerr := os.Stat(legacy) |
| 269 | _, ferr := os.Stat(flow) |
| 270 | for _, e := range []struct { |
| 271 | path string |
| 272 | err error |
| 273 | }{{legacy, lerr}, {flow, ferr}} { |
| 274 | if e.err != nil && !errors.Is(e.err, fs.ErrNotExist) { |
| 275 | return "", fmt.Errorf("checking %s: %w", e.path, e.err) |
| 276 | } |
| 277 | } |
| 278 | switch { |
| 279 | case lerr == nil && ferr == nil: |
| 280 | lr, lerr := filepath.EvalSymlinks(legacy) |
| 281 | fr, ferr := filepath.EvalSymlinks(flow) |
| 282 | if lerr == nil && ferr == nil && lr == fr { |
| 283 | return lr, nil |
| 284 | } |
| 285 | return "", &ConflictError{What: what, Paths: []string{legacy, flow}} |
| 286 | case lerr == nil: |
| 287 | return legacy, nil |
| 288 | case ferr == nil: |
| 289 | return flow, nil |
| 290 | } |
| 291 | return l.allocate(legacy) |
| 292 | } |
| 293 | |
| 294 | // Registry is the project registry file. |
| 295 | func (l Layout) Registry() (string, error) { |
| 296 | return l.one("the project registry", l.legacy("projects.json"), l.flow("projects.json")) |
| 297 | } |
| 298 | |
| 299 | // Memory is the shared coordinator memory directory. |
| 300 | func (l Layout) Memory() (string, error) { |
| 301 | return l.one("the shared coordinator memory", l.legacy("memory"), l.flow("memory")) |
| 302 | } |
| 303 | |
| 304 | // SelfUpdateState is self-update's state file. Read it holding |
| 305 | // SelfUpdateLocks, so no update moves it in between. |
| 306 | func (l Layout) SelfUpdateState() (string, error) { |
| 307 | return l.one("the self-update state", filepath.Join(l.StateHome, legacyState, "self-update.json"), l.flow("self-update.json")) |
| 308 | } |
| 309 | |
| 310 | // SelfUpdateLocks are the lock files every self-update holds, in order. |
| 311 | func (l Layout) SelfUpdateLocks() []string { |
| 312 | return []string{filepath.Join(l.StateHome, legacyState, "self-update.lock"), l.flow("self-update.lock")} |
| 313 | } |
| 314 | |
| 315 | // ReviewLockDirs are the directories of the global review locks, used |
| 316 | // when no session holds a review's lock: each lock is a file of one name |
| 317 | // in both, held in order. |
| 318 | func (l Layout) ReviewLockDirs() []string { |
| 319 | return []string{l.legacy("locks"), l.flow("locks")} |
| 320 | } |
| 321 | |
| 322 | // ContinuationLocks are the files of the continuation lock of the clone |
| 323 | // whose git common directory is gitCommonDir, in order. |
| 324 | func ContinuationLocks(gitCommonDir string) []string { |
| 325 | return []string{ |
| 326 | filepath.Join(gitCommonDir, "klaus-continue.lock"), |
| 327 | filepath.Join(gitCommonDir, flowGitDir, "continuation.lock"), |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | // AgentsSession is the detached tmux session the agents of the flow |
| 332 | // session id run in, id being empty outside a session. Every generation |
| 333 | // gives it the legacy name. |
| 334 | func AgentsSession(id string) string { |
| 335 | if id == "" { |
| 336 | return legacyAgents |
| 337 | } |
| 338 | // tmux treats "." and ":" as target separators. |
| 339 | return legacyAgents + "-" + strings.NewReplacer(".", "-", ":", "-").Replace(id) |
| 340 | } |
| 341 | |
| 342 | // AgentsSessions are the names flow gives the agents session of the flow |
| 343 | // session id under some generation: AgentsSession's alone, since every |
| 344 | // generation allocates the legacy names. A tmux session a run of that |
| 345 | // session records outside them is not one flow made for it. |
| 346 | func AgentsSessions(id string) []string { |
| 347 | return []string{AgentsSession(id)} |
| 348 | } |
| 349 | |
| 350 | // ConsultSnapshots is the directory one-shot consult snapshots go in. |
| 351 | // Each consult removes its own, at the path it was given. |
| 352 | func (l Layout) ConsultSnapshots() (string, error) { |
| 353 | return l.allocate(l.legacy("consult-snapshots")) |
| 354 | } |
| 355 | |
| 356 | // SyncLog is the file background project syncs append to. |
| 357 | func (l Layout) SyncLog() (string, error) { |
| 358 | return l.allocate(l.legacy("sync.log")) |
| 359 | } |
| 360 | |
| 361 | // SyncLogs are the sync log files that exist, legacy first: an older build |
| 362 | // may append to one while this one appends to another. |
| 363 | func (l Layout) SyncLogs() []string { |
| 364 | return existing(l.legacy("sync.log"), l.flow("sync.log")) |
| 365 | } |
| 366 | |
| 367 | // StandaloneStore is the directory a run started outside a session keeps |
| 368 | // its runs/ and logs/ in, in the clone whose git common directory is |
| 369 | // gitCommonDir. |
| 370 | func (l Layout) StandaloneStore(gitCommonDir string) (string, error) { |
| 371 | return l.allocate(filepath.Join(gitCommonDir, legacyGitDir)) |
| 372 | } |
| 373 | |
| 374 | func existing(paths ...string) []string { |
| 375 | var out []string |
| 376 | for _, p := range paths { |
| 377 | if _, err := os.Stat(p); err == nil { |
| 378 | out = append(out, p) |
| 379 | } |
| 380 | } |
| 381 | return out |
| 382 | } |
| 383 | |
| 384 | // SessionRoots are the directories sessions are found under, legacy first. |
| 385 | func (l Layout) SessionRoots() []string { |
| 386 | return []string{l.legacy("sessions"), l.flow("sessions")} |
| 387 | } |
| 388 | |
| 389 | // Session is one session's directory. |
| 390 | type Session struct { |
| 391 | ID string |
| 392 | Dir string |
| 393 | } |
| 394 | |
| 395 | // ErrUnknownSession is a session ID no directory has. |
| 396 | var ErrUnknownSession = errors.New("unknown session") |
| 397 | |
| 398 | // validSessionID rejects what would name a directory other than one entry |
| 399 | // of a sessions root. |
| 400 | func validSessionID(id string) error { |
| 401 | if id == "" || id == "." || id == ".." || strings.ContainsAny(id, `/\`) { |
| 402 | return fmt.Errorf("%q is not a session ID", id) |
| 403 | } |
| 404 | return nil |
| 405 | } |
| 406 | |
| 407 | // Sessions lists the session directories under both roots, by ID. A |
| 408 | // session ID under both roots, unless both are one directory, is left out |
| 409 | // and reported in a ConflictError, which comes back with the rest. |
| 410 | func (l Layout) Sessions() ([]Session, error) { |
| 411 | byID := map[string][]string{} |
| 412 | for _, root := range l.SessionRoots() { |
| 413 | entries, err := os.ReadDir(root) |
| 414 | if errors.Is(err, fs.ErrNotExist) { |
| 415 | continue |
| 416 | } |
| 417 | if err != nil { |
| 418 | return nil, fmt.Errorf("reading sessions dir: %w", err) |
| 419 | } |
| 420 | for _, e := range entries { |
| 421 | dir := filepath.Join(root, e.Name()) |
| 422 | if e.Type()&fs.ModeSymlink != 0 { |
| 423 | // Session looks a symlinked session up: so does the listing. |
| 424 | if fi, err := os.Stat(dir); err != nil || !fi.IsDir() { |
| 425 | continue |
| 426 | } |
| 427 | } else if !e.IsDir() { |
| 428 | continue |
| 429 | } |
| 430 | byID[e.Name()] = append(byID[e.Name()], dir) |
| 431 | } |
| 432 | } |
| 433 | var out []Session |
| 434 | var conflicts []error |
| 435 | for id, dirs := range byID { |
| 436 | dir, err := oneDir("session "+id, dirs) |
| 437 | if err != nil { |
| 438 | conflicts = append(conflicts, err) |
| 439 | continue |
| 440 | } |
| 441 | out = append(out, Session{ID: id, Dir: dir}) |
| 442 | } |
| 443 | sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID }) |
| 444 | sort.Slice(conflicts, func(i, j int) bool { return conflicts[i].Error() < conflicts[j].Error() }) |
| 445 | return out, errors.Join(conflicts...) |
| 446 | } |
| 447 | |
| 448 | // oneDir is the one directory dirs name, or a ConflictError. |
| 449 | func oneDir(what string, dirs []string) (string, error) { |
| 450 | if len(dirs) == 2 { |
| 451 | a, aerr := os.Stat(dirs[0]) |
| 452 | b, berr := os.Stat(dirs[1]) |
| 453 | if aerr == nil && berr == nil && os.SameFile(a, b) { |
| 454 | return dirs[0], nil |
| 455 | } |
| 456 | } |
| 457 | if len(dirs) != 1 { |
| 458 | return "", &ConflictError{What: what, Paths: dirs} |
| 459 | } |
| 460 | return dirs[0], nil |
| 461 | } |
| 462 | |
| 463 | // Session is the directory of the session id: the one root that has it. |
| 464 | // An ID no root has is ErrUnknownSession; one both have is a |
| 465 | // ConflictError. |
| 466 | func (l Layout) Session(id string) (string, error) { |
| 467 | if err := validSessionID(id); err != nil { |
| 468 | return "", err |
| 469 | } |
| 470 | var dirs []string |
| 471 | for _, root := range l.SessionRoots() { |
| 472 | dir := filepath.Join(root, id) |
| 473 | fi, err := os.Stat(dir) |
| 474 | if errors.Is(err, fs.ErrNotExist) { |
| 475 | continue |
| 476 | } |
| 477 | if err != nil { |
| 478 | return "", fmt.Errorf("checking session dir: %w", err) |
| 479 | } |
| 480 | if fi.IsDir() { |
| 481 | dirs = append(dirs, dir) |
| 482 | } |
| 483 | } |
| 484 | if len(dirs) == 0 { |
| 485 | return "", fmt.Errorf("%w %s: no %s", ErrUnknownSession, id, strings.Join(l.sessionPaths(id), " or ")) |
| 486 | } |
| 487 | return oneDir("session "+id, dirs) |
| 488 | } |
| 489 | |
| 490 | func (l Layout) sessionPaths(id string) []string { |
| 491 | var out []string |
| 492 | for _, root := range l.SessionRoots() { |
| 493 | out = append(out, filepath.Join(root, id)) |
| 494 | } |
| 495 | return out |
| 496 | } |
| 497 | |
| 498 | // NewSession is the directory a new session id goes in. It does not |
| 499 | // create it; an id a root already has is an error. |
| 500 | func (l Layout) NewSession(id string) (string, error) { |
| 501 | if err := validSessionID(id); err != nil { |
| 502 | return "", err |
| 503 | } |
| 504 | if dir, err := l.Session(id); err == nil { |
| 505 | return "", fmt.Errorf("session %s already exists at %s", id, dir) |
| 506 | } else if !errors.Is(err, ErrUnknownSession) { |
| 507 | return "", err |
| 508 | } |
| 509 | root, err := l.NewSessionsRoot() |
| 510 | if err != nil { |
| 511 | return "", err |
| 512 | } |
| 513 | return filepath.Join(root, id), nil |
| 514 | } |
| 515 | |
| 516 | // NewSessionsRoot is the sessions root new sessions go under. |
| 517 | func (l Layout) NewSessionsRoot() (string, error) { |
| 518 | return l.allocate(l.SessionRoots()[0]) |
| 519 | } |