14 // errNoView tells that a chat has messages but no saved view.
15 var errNoView = errors.New("the chat has messages but no saved view")
17 // Memory is the memory of one chat: the message log, the summary tree, the chat
18 // view, and the compaction view. The compaction view is the chat view merged
19 // further, at the limits of 16 to 32 KB. It takes the same new lines, and it
20 // merges again in one batch when it is too large or when the chat view merges.
21 // So the compactions share its prefix in the prompt cache. It saves the views
22 // to view.json after each change and loads them at start. It never builds the
23 // views again from the log, because a new view differs from the live one and so
24 // loses the prompt cache.
34 // viewFile is the content of view.json.
35 type viewFile struct {
36 Chat viewState `json:"chat"`
37 Compaction viewState `json:"compaction"`
40 // openMemory opens the chat in root. The clock gives the dates of new messages
41 // and the days of new nodes.
42 func openMemory(ctx context.Context, root string, clock func() time.Time) (*Memory, error) {
43 log, err := openLog(ctx, root, clock)
53 m.tree, err = openTree(ctx, root, log.Len(), clock)
55 return nil, errors.Join(err, m.Close())
60 return nil, errors.Join(fmt.Errorf("load view: %w", err), m.Close())
66 // load reads the saved view. A crash can stop an append after the log write and
67 // before the view save, so load continues the view with the messages that it
68 // does not cover yet.
69 func (m *Memory) load() error {
70 data, err := os.ReadFile(m.viewPath())
71 if errors.Is(err, os.ErrNotExist) && m.log.Len() == 0 {
72 m.chat = newView(chatHigh, chatLow)
73 m.cview = newView(compactionHigh, compactionLow)
78 if errors.Is(err, os.ErrNotExist) {
83 return fmt.Errorf("read view: %w", err)
87 err = json.Unmarshal(data, &file)
89 return fmt.Errorf("decode view: %w", err)
92 m.chat, err = restoreView(file.Chat, chatHigh, chatLow, m.tree)
94 return fmt.Errorf("chat view: %w", err)
97 m.cview, err = restoreView(file.Compaction, compactionHigh, compactionLow, m.tree)
99 return fmt.Errorf("compaction view: %w", err)
102 if m.cview.end != m.chat.end {
103 return fmt.Errorf("compaction view covers %d messages, but the chat view %d", m.cview.end, m.chat.end)
106 if m.chat.end > m.log.Len() {
107 return fmt.Errorf("view covers %d messages, but the log has %d", m.chat.end, m.log.Len())
110 if m.chat.end == m.log.Len() {
114 for m.chat.end < m.log.Len() {
115 err = m.addMessage(m.log.Message(m.chat.end))
124 // Close closes the files of the chat and releases its lock.
125 func (m *Memory) Close() error {
127 defer m.mutex.Unlock()
134 return errors.Join(err, m.log.Close())
137 // Append logs a new message and adds it to the tree and the view.
138 func (m *Memory) Append(kind, text string) (Message, error) {
140 defer m.mutex.Unlock()
142 message, err := m.log.Append(kind, text)
144 return Message{}, err
147 err = m.addMessage(message)
149 return Message{}, err
154 return Message{}, err
160 // addMessage builds the leaf of message when it needs no model call and appends
162 func (m *Memory) addMessage(message Message) error {
163 _, built := m.tree.Node(0, message.ID)
164 leaf, free := freeLeaf(message)
172 merged := m.chat.Append(m.tree)
173 m.cview.Append(m.tree)
175 m.cview.Coarsen(m.chat, m.tree)
181 // build adds node to the tree, and then each parent above it that needs no
183 func (m *Memory) build(node Node) error {
185 err := m.tree.Add(node)
190 sibling, built := m.tree.Node(node.Level, node.Index^1)
195 left, right := node, sibling
196 if node.Index%2 != 0 {
197 left, right = sibling, node
200 parent, free := freeMerge(left, right)
209 // save writes the views to view.json.
210 func (m *Memory) save() error {
211 data, err := json.Marshal(viewFile{
212 Chat: m.chat.State(),
213 Compaction: m.cview.State(),
216 return fmt.Errorf("encode view: %w", err)
219 err = writeFileAtomic(m.viewPath(), append(data, '\n'))
221 return fmt.Errorf("save view: %w", err)
227 func (m *Memory) viewPath() string {
228 return filepath.Join(m.root, "view.json")
231 // View returns the chat view as the model reads it.
232 func (m *Memory) View() string {
234 defer m.mutex.Unlock()
236 return m.chat.Render(m.tree)
239 // Context returns the compaction view for the build of node (l, i). It ends
240 // before the message of a leaf, or after the last message of a merge, and it
241 // stops at the first line that is not built.
242 func (m *Memory) Context(level, index int) string {
244 defer m.mutex.Unlock()
246 return m.context(level, index)
249 func (m *Memory) context(level, index int) string {
252 end = nodeEnd(level, index)
255 return m.cview.Context(m.tree, end)
258 // writeFileAtomic replaces the file at path with data. A reader or a crash sees
259 // the old file or the new file, never a part of one.
260 func writeFileAtomic(path string, data []byte) error {
261 dir := filepath.Dir(path)
262 file, err := os.CreateTemp(dir, "."+filepath.Base(path)+".*")
264 return fmt.Errorf("create temporary file: %w", err)
267 _, err = file.Write(data)
272 err = errors.Join(err, file.Close())
274 err = os.Rename(file.Name(), path)
278 return errors.Join(fmt.Errorf("replace file: %w", err), os.Remove(file.Name()))
284 // syncDir flushes the entries of dir to the disk.
285 func syncDir(dir string) (err error) {
286 handle, err := os.Open(dir)
288 return fmt.Errorf("open directory: %w", err)
292 err = errors.Join(err, handle.Close())
297 return fmt.Errorf("flush directory: %w", err)