gunk-dev/the-valley

store.go

source68d12192bbd3main's published tip history
7.6 KiB
1package consult
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "os"
8 "path/filepath"
9 "regexp"
10 "strings"
11 "syscall"
12 "time"
13
14 "the-valley/flow/internal/backend"
15)
16
17type Thread struct {
18 // HouseRules is the operator's house rules text, added to the system
19 // prompt. Each turn sets it afresh; it is never saved.
20 HouseRules string `json:"-"`
21 Backend backend.Kind `json:"backend"`
22 Model string `json:"model"`
23 Effort string `json:"effort,omitempty"`
24 BackendSessionID string `json:"backend_session_id"`
25 Dir string `json:"dir"`
26 // Repo is the registered project a --repo thread reads. Its Dir is then
27 // the thread's snapshot (WorkspaceDir), which every turn moves to
28 // origin's default branch, and Commit is the commit the last turn read.
29 Repo string `json:"repo,omitempty"`
30 Commit string `json:"commit,omitempty"`
31 Role string `json:"role"`
32 CreatedAt time.Time `json:"created_at"`
33 LastUsed time.Time `json:"last_used"`
34 Turns int `json:"turns"`
35}
36
37type Store struct{ Dir string }
38
39func NewStore(sessionDir string) Store { return Store{Dir: filepath.Join(sessionDir, "consults")} }
40
41var threadName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`)
42
43func (s Store) path(name, ext string) (string, error) {
44 if !threadName.MatchString(name) || len(name) > 120 {
45 return "", fmt.Errorf("invalid thread name %q: use up to 120 letters, digits, dots, underscores or hyphens, starting with a letter or digit", name)
46 }
47 return filepath.Join(s.Dir, name+ext), nil
48}
49
50// WorkspaceDir is where a --repo thread's snapshot lives. It doesn't
51// change between turns, so the thread's workspace stays the same.
52func (s Store) WorkspaceDir(name string) (string, error) { return s.path(name, ".workspace") }
53
54func (s Store) Lock(name string) (func(), error) {
55 path, err := s.path(name, ".lock")
56 if err != nil {
57 return nil, err
58 }
59 if err := os.MkdirAll(s.Dir, 0700); err != nil {
60 return nil, err
61 }
62 f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0600)
63 if err != nil {
64 return nil, fmt.Errorf("locking thread %q (another consult may be running): %w", name, err)
65 }
66 if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
67 f.Close()
68 return nil, fmt.Errorf("thread %q is already in use: %w", name, err)
69 }
70 return func() { _ = f.Close() }, nil
71}
72
73func (s Store) Load(name string) (*Thread, error) {
74 path, err := s.path(name, ".json")
75 if err != nil {
76 return nil, err
77 }
78 data, err := os.ReadFile(path)
79 if err != nil {
80 return nil, err
81 }
82 var t Thread
83 if err := json.Unmarshal(data, &t); err != nil {
84 return nil, err
85 }
86 return &t, nil
87}
88
89func (s Store) Save(name string, t *Thread) error {
90 path, err := s.path(name, ".json")
91 if err != nil {
92 return err
93 }
94 data, err := json.MarshalIndent(t, "", " ")
95 if err != nil {
96 return err
97 }
98 return writeAtomic(path, append(data, '\n'))
99}
100
101type Turn struct {
102 Number int `json:"turn"`
103 Status string `json:"status"`
104 StartedAt time.Time `json:"started_at"`
105 FinishedAt *time.Time `json:"finished_at,omitempty"`
106 Backend backend.Kind `json:"backend"`
107 Model string `json:"model"`
108 ResumeID string `json:"resume_id"`
109 RepoRevision string `json:"repo_revision"`
110 SessionIDSource string `json:"session_id_source"`
111 BackendSessionID string `json:"backend_session_id,omitempty"`
112 Prompt string `json:"prompt"`
113 Answer string `json:"answer,omitempty"`
114 RawOutput string `json:"raw_output,omitempty"`
115 prior, pending []byte
116}
117
118// BeginTurn persists intent before execution; callers hold the thread lock.
119func (s Store) BeginTurn(name string, t *Thread, prompt, revision string) (*Turn, error) {
120 path, err := s.path(name, ".log")
121 if err != nil {
122 return nil, err
123 }
124 prior, err := os.ReadFile(path)
125 if err != nil && !os.IsNotExist(err) {
126 return nil, err
127 }
128 if len(prior) > 0 && prior[len(prior)-1] != '\n' {
129 prior = append(prior, '\n')
130 }
131 number := t.Turns + 1
132 for _, line := range bytes.Split(prior, []byte("\n")) {
133 var previous Turn
134 if json.Unmarshal(line, &previous) == nil && previous.Number >= number {
135 number = previous.Number + 1
136 }
137 }
138 turn := &Turn{Number: number, Status: "pending", StartedAt: time.Now().UTC(), Backend: t.Backend, Model: t.Model, ResumeID: t.BackendSessionID, RepoRevision: revision, Prompt: prompt, prior: prior}
139 data, err := json.Marshal(turn)
140 if err != nil {
141 return nil, err
142 }
143 turn.pending = append(data, '\n')
144 if err := writeAtomic(path, append(bytes.Clone(prior), turn.pending...)); err != nil {
145 return nil, err
146 }
147 return turn, nil
148}
149
150func (s Store) FinishTurn(name string, turn *Turn, result Result, turnErr error) error {
151 path, err := s.path(name, ".log")
152 if err != nil {
153 return err
154 }
155 current, err := os.ReadFile(path)
156 if err != nil {
157 return err
158 }
159 if !bytes.Equal(current, append(bytes.Clone(turn.prior), turn.pending...)) {
160 return fmt.Errorf("transcript changed while turn %d was running", turn.Number)
161 }
162 turn.Status = "ok"
163 if turnErr != nil {
164 turn.Status = "error: " + turnErr.Error()
165 }
166 now := time.Now().UTC()
167 turn.FinishedAt = &now
168 turn.Answer = result.Answer
169 turn.SessionIDSource = result.SessionIDSource
170 turn.BackendSessionID = result.SessionID
171 data, err := json.Marshal(turn)
172 if err != nil {
173 return err
174 }
175 return writeAtomic(path, append(bytes.Clone(turn.prior), append(data, '\n')...))
176}
177
178// Turn returns turn number of thread name from its log.
179func (s Store) Turn(name string, number int) (*Turn, error) {
180 path, err := s.path(name, ".log")
181 if err != nil {
182 return nil, err
183 }
184 data, err := os.ReadFile(path)
185 if err != nil {
186 return nil, err
187 }
188 for _, line := range bytes.Split(data, []byte("\n")) {
189 var turn Turn
190 if json.Unmarshal(line, &turn) == nil && turn.Number == number {
191 return &turn, nil
192 }
193 }
194 return nil, fmt.Errorf("thread %q has no turn %d", name, number)
195}
196
197func (s Store) SaveRaw(name string, number int, result Result) (string, error) {
198 path, err := s.path(name, fmt.Sprintf(".%d.raw", number))
199 if err != nil {
200 return "", err
201 }
202 err = writeAtomic(path, []byte(result.Raw()))
203 return path, err
204}
205
206// Raw is everything the backend wrote, as kept for a failed call: stdout,
207// stderr and any diagnostic log, each under a heading.
208func (r Result) Raw() string {
209 raw := "### stdout\n" + r.Answer + "\n### stderr\n" + r.Stderr
210 if r.DiagnosticLog != "" {
211 raw += "\n### diagnostic-log\n" + r.DiagnosticLog
212 }
213 return raw
214}
215
216func writeAtomic(path string, data []byte) error {
217 dir := filepath.Dir(path)
218 if err := os.MkdirAll(dir, 0700); err != nil {
219 return err
220 }
221 f, err := os.CreateTemp(dir, ".consult-*")
222 if err != nil {
223 return err
224 }
225 defer os.Remove(f.Name())
226 if _, err := f.Write(data); err != nil {
227 f.Close()
228 return err
229 }
230 if err := f.Sync(); err != nil {
231 f.Close()
232 return err
233 }
234 if err := f.Close(); err != nil {
235 return err
236 }
237 if err := os.Rename(f.Name(), path); err != nil {
238 return err
239 }
240 d, err := os.Open(dir)
241 if err != nil {
242 return err
243 }
244 defer d.Close()
245 return d.Sync()
246}
247
248func (s Store) List() (map[string]*Thread, error) {
249 entries, err := os.ReadDir(s.Dir)
250 if os.IsNotExist(err) {
251 return map[string]*Thread{}, nil
252 }
253 if err != nil {
254 return nil, err
255 }
256 threads := make(map[string]*Thread)
257 for _, e := range entries {
258 if e.IsDir() || !strings.HasSuffix(e.Name(), ".json") {
259 continue
260 }
261 name := strings.TrimSuffix(e.Name(), ".json")
262 t, err := s.Load(name)
263 if err != nil {
264 return nil, fmt.Errorf("reading thread %s: %w", name, err)
265 }
266 threads[name] = t
267 }
268 return threads, nil
269}