xonecas.io
62159
Sy

symb / files

symb / internal / delta / delta.go

4.1 KB
1// Package delta tracks filesystem changes made by tool calls so they can be
2// reversed on undo. Deltas are persisted to SQLite and keyed by (session, turn).
3package delta
4
5import (
6	"database/sql"
7	"os"
8	"sync"
9
10	"github.com/rs/zerolog/log"
11)
12
13// Tracker records and replays filesystem deltas.
14type Tracker struct {
15	mu        sync.Mutex
16	db        *sql.DB
17	sessionID string
18	turnID    int64 // current turn; 0 = no active turn
19}
20
21// New creates a Tracker that writes to the given database.
22func New(db *sql.DB) *Tracker {
23	return &Tracker{db: db}
24}
25
26// SetSession sets the active session ID.
27func (t *Tracker) SetSession(id string) {
28	t.mu.Lock()
29	defer t.mu.Unlock()
30	t.sessionID = id
31}
32
33// BeginTurn sets the current turn ID. All subsequent Record* calls
34// are associated with this turn until the next BeginTurn.
35func (t *Tracker) BeginTurn(turnID int64) {
36	t.mu.Lock()
37	defer t.mu.Unlock()
38	t.turnID = turnID
39}
40
41// TurnID returns the current turn ID.
42func (t *Tracker) TurnID() int64 {
43	t.mu.Lock()
44	defer t.mu.Unlock()
45	return t.turnID
46}
47
48// RecordModify stores the original content of a file before it is modified.
49// Only the first snapshot per file per turn is kept (subsequent edits to the
50// same file in the same turn are no-ops — we already have the original).
51func (t *Tracker) RecordModify(filePath string, oldContent []byte) {
52	t.mu.Lock()
53	defer t.mu.Unlock()
54	if t.turnID == 0 || t.sessionID == "" {
55		return
56	}
57	// Check if we already have a delta for this file in this turn.
58	var exists bool
59	err := t.db.QueryRow(
60		`SELECT 1 FROM file_deltas WHERE session_id = ? AND turn_id = ? AND file_path = ? LIMIT 1`,
61		t.sessionID, t.turnID, filePath,
62	).Scan(&exists)
63	if err == nil && exists {
64		return // already recorded
65	}
66	_, err = t.db.Exec(
67		`INSERT INTO file_deltas (session_id, turn_id, file_path, op, old_content, created)
68		 VALUES (?, ?, ?, 'modify', ?, strftime('%s','now'))`,
69		t.sessionID, t.turnID, filePath, oldContent,
70	)
71	if err != nil {
72		log.Warn().Err(err).Str("file", filePath).Msg("failed to record modify delta")
73	}
74}
75
76// RecordCreate records that a file was created (old_content is NULL).
77func (t *Tracker) RecordCreate(filePath string) {
78	t.mu.Lock()
79	defer t.mu.Unlock()
80	if t.turnID == 0 || t.sessionID == "" {
81		return
82	}
83	_, err := t.db.Exec(
84		`INSERT INTO file_deltas (session_id, turn_id, file_path, op, old_content, created)
85		 VALUES (?, ?, ?, 'create', NULL, strftime('%s','now'))`,
86		t.sessionID, t.turnID, filePath,
87	)
88	if err != nil {
89		log.Warn().Err(err).Str("file", filePath).Msg("failed to record create delta")
90	}
91}
92
93// Undo reverses all file changes for the given turn, in reverse order.
94// Modify ops restore old content; create ops delete the file.
95// Returns the list of affected absolute file paths and any error.
96func (t *Tracker) Undo(sessionID string, turnID int64) ([]string, error) {
97	t.mu.Lock()
98	defer t.mu.Unlock()
99
100	rows, err := t.db.Query(
101		`SELECT file_path, op, old_content FROM file_deltas
102		 WHERE session_id = ? AND turn_id = ?
103		 ORDER BY id DESC`,
104		sessionID, turnID,
105	)
106	if err != nil {
107		return nil, err
108	}
109	defer rows.Close()
110
111	var affected []string
112	for rows.Next() {
113		var filePath, op string
114		var oldContent []byte
115		if err := rows.Scan(&filePath, &op, &oldContent); err != nil {
116			log.Warn().Err(err).Msg("failed to scan delta row")
117			continue
118		}
119		affected = append(affected, filePath)
120		switch op {
121		case "modify":
122			if err := os.WriteFile(filePath, oldContent, 0600); err != nil {
123				log.Warn().Err(err).Str("file", filePath).Msg("undo: failed to restore file")
124			}
125		case "create":
126			if err := os.Remove(filePath); err != nil && !os.IsNotExist(err) {
127				log.Warn().Err(err).Str("file", filePath).Msg("undo: failed to remove created file")
128			}
129		}
130	}
131	return affected, rows.Err()
132}
133
134// DeleteTurn removes all delta records for a turn.
135func (t *Tracker) DeleteTurn(sessionID string, turnID int64) {
136	t.mu.Lock()
137	defer t.mu.Unlock()
138	_, err := t.db.Exec(
139		`DELETE FROM file_deltas WHERE session_id = ? AND turn_id = ?`,
140		sessionID, turnID,
141	)
142	if err != nil {
143		log.Warn().Err(err).Int64("turn", turnID).Msg("failed to delete turn deltas")
144	}
145}