gunk-dev/the-valley

location.go

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