Repository navigation
Expand file tree
/
Copy pathcell.go
More file actions
185 lines (167 loc) · 5.35 KB
/
Copy pathcell.go
File metadata and controls
185 lines (167 loc) · 5.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
// Package cell is the on-disk layout of a cell: one folder per conversation
// under <home>/v3/cells/<ulid>/, holding the cell's own state in .cell/:
//
// .cell/transcript.jsonl the journal
// .cell/env/ environment state
// .cell/meta.json Meta (SCHEMAS.md §4)
//
// Every path this package persists is cell-relative; absolute paths exist
// only transiently, as the answer to Cell.Path.
//
// New chats are cells when a compatible engine is available and while [Available] says the
// platform and engine can carry them. v3MintSession in
// cmd/codeaf/chatv3_layout.go calls [CreateIn] on the project bucket, and
// internal/session's layout.go recognises a folder holding .cell/ and keeps
// the transcript there. Older folders keep their original layout when opened (C24);
// older conversations can move through independent durable copies (C29).
package cell
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/Agent-Field/codeaf/internal/fsreplace"
"os"
"path/filepath"
"strings"
"time"
)
// Cell-relative names.
const (
StateDir = ".cell"
TranscriptPath = StateDir + "/transcript.jsonl"
EnvPath = StateDir + "/env"
MetaPath = StateDir + "/meta.json"
// TreesDir is the folder of a session where its task working copies live,
// and CarriedTreesPath is where a seal carries their uncommitted files.
TreesDir = "trees"
CarriedTreesPath = StateDir + "/" + TreesDir
schemaV = 1
)
// Options describe a new cell. KeyID is generated when empty.
type Options struct {
Class Class
KeyID string
Base *Base
}
// Cell is a handle on one cell folder.
type Cell struct {
ID string
Root string
meta Meta
}
// Dir is the directory that holds every cell under a codeaf home.
func Dir(home string) string { return filepath.Join(home, "v3", "cells") }
// Create makes a new cell folder and writes its meta.json.
func Create(home string, opts Options) (Cell, error) { return CreateIn(Dir(home), opts) }
// CreateIn makes a new cell folder directly under parent. A caller that
// already groups its conversations in a directory (a project bucket) uses it
// so the cell is found where that grouping looks.
func CreateIn(parent string, opts Options) (Cell, error) {
m, err := opts.meta()
if err != nil {
return Cell{}, err
}
id, err := NewID(time.Now())
if err != nil {
return Cell{}, err
}
c := Cell{ID: id, Root: filepath.Join(parent, id), meta: m}
if err := os.MkdirAll(c.Root+"/"+EnvPath, 0o700); err != nil {
return Cell{}, fmt.Errorf("create cell: %w", err)
}
if err := c.WriteMeta(m); err != nil {
return Cell{}, err
}
return c, nil
}
// Open loads an existing cell.
func Open(home, id string) (Cell, error) {
if !ValidID(id) {
return Cell{}, fmt.Errorf("open cell: invalid id %q", id)
}
return OpenAt(filepath.Join(Dir(home), id), id)
}
// OpenAt loads the cell whose folder is root, wherever it lives.
func OpenAt(root, id string) (Cell, error) {
c := Cell{ID: id, Root: root}
raw, err := os.ReadFile(c.abs(MetaPath))
if err != nil {
return Cell{}, fmt.Errorf("open cell %s: %w", id, err)
}
if err := json.Unmarshal(raw, &c.meta); err != nil {
return Cell{}, fmt.Errorf("open cell %s: %w", id, err)
}
if err := c.meta.validate(); err != nil {
return Cell{}, fmt.Errorf("open cell %s: %w", id, err)
}
return c, nil
}
// Meta is the cell's metadata as last written or read.
func (c Cell) Meta() Meta { return c.meta }
// Path resolves a cell-relative path to a location inside the cell. Absolute
// and escaping paths are rejected.
func (c Cell) Path(rel string) (string, error) {
if rel == "" || filepath.IsAbs(rel) || strings.HasPrefix(rel, "/") {
return "", fmt.Errorf("cell path %q: must be relative", rel)
}
clean := filepath.Clean(rel)
if clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) {
return "", fmt.Errorf("cell path %q: escapes the cell", rel)
}
return c.abs(clean), nil
}
func (c Cell) abs(rel string) string { return filepath.Join(c.Root, filepath.FromSlash(rel)) }
// WriteMeta replaces meta.json atomically (temp file, fsync, rename).
func (c *Cell) WriteMeta(m Meta) error {
if err := m.validate(); err != nil {
return err
}
raw, err := encodeMeta(m)
if err != nil {
return err
}
if err := writeAtomic(c.abs(MetaPath), raw); err != nil {
return fmt.Errorf("write cell meta: %w", err)
}
c.meta = m
return nil
}
func encodeMeta(m Meta) ([]byte, error) { return json.MarshalIndent(m, "", " ") }
// RestoreMeta makes meta.json on disk equal the meta this handle holds, and
// writes nothing when it already does. The harness calls it before each seal
// so a tool that edited the file cannot reach a sealed tree (L10).
func (c *Cell) RestoreMeta() error {
raw, err := encodeMeta(c.meta)
if err != nil {
return err
}
if cur, err := os.ReadFile(c.abs(MetaPath)); err == nil && bytes.Equal(cur, raw) {
return nil
}
return c.WriteMeta(c.meta)
}
func writeAtomic(path string, data []byte) (err error) {
tmp, err := os.CreateTemp(filepath.Dir(path), ".meta-*.tmp")
if err != nil {
return err
}
defer func() {
if err != nil {
_ = os.Remove(tmp.Name())
}
}()
if _, err = tmp.Write(data); err != nil {
_ = tmp.Close()
return err
}
if err = tmp.Sync(); err != nil {
_ = tmp.Close()
return err
}
if err = tmp.Close(); err != nil {
return err
}
return fsreplace.Rename(tmp.Name(), path)
}
var errBadMeta = errors.New("invalid cell meta")