Add version history with rollback and per-note created/synced info
All checks were successful
ci / test (push) Successful in 3m8s
ci / release (push) Successful in 11m21s

Server (schema v2, auto-migrates): every accepted overwrite snapshots the
superseded revision into note_history (capped at 50 per note); new
GET /api/v1/notes/{id}/history endpoint; compact purges orphaned history.

Client: notes get a synced_at stamp on every confirmed server exchange;
an info footer under the editor and a Ctrl/Cmd+I panel show created/
modified/last-synced plus the revision list. Restoring a revision applies
it as a normal edit through the sync path, so rollback is non-destructive.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-25 22:20:19 +02:00
parent bd2b8e6241
commit c389bab46e
12 changed files with 563 additions and 9 deletions

View File

@@ -17,7 +17,10 @@ import (
_ "modernc.org/sqlite"
)
const SchemaVersion = 1
const SchemaVersion = 2
// historyKeep caps stored revisions per note; older ones are pruned on write.
const historyKeep = 50
type Note struct {
ID string `json:"id"`
@@ -29,6 +32,16 @@ type Note struct {
Version int64 `json:"version"`
}
// Revision is a superseded note state, recorded when an accepted push overwrites it.
type Revision struct {
NoteID string `json:"note_id"`
Version int64 `json:"version"`
Content string `json:"content"`
Tags []string `json:"tags"`
ModifiedAt int64 `json:"modified_at"`
ReplacedAt int64 `json:"replaced_at"`
}
type IncomingNote struct {
ID string `json:"id"`
Content string `json:"content"`
@@ -83,11 +96,22 @@ CREATE TABLE IF NOT EXISTS notes (
);
CREATE INDEX IF NOT EXISTS idx_notes_version ON notes(version);
CREATE UNIQUE INDEX IF NOT EXISTS idx_notes_source ON notes(source_id) WHERE source_id IS NOT NULL;
CREATE TABLE IF NOT EXISTS note_history (
note_id TEXT NOT NULL,
version INTEGER NOT NULL,
content TEXT NOT NULL DEFAULT '',
tags TEXT NOT NULL DEFAULT '[]',
modified_at INTEGER NOT NULL,
replaced_at INTEGER NOT NULL,
PRIMARY KEY (note_id, version)
);
CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT);
INSERT OR IGNORE INTO meta (k, v) VALUES ('schema_version', '1');
INSERT OR IGNORE INTO meta (k, v) VALUES ('next_version', '1');
`)
return err
if err != nil {
return err
}
return s.setMeta("schema_version", strconv.Itoa(SchemaVersion))
}
// --- meta helpers ---
@@ -228,6 +252,45 @@ func getNoteTx(tx *sql.Tx, id string) (*Note, error) {
return &n, nil
}
// recordHistoryTx snapshots the note state that is about to be overwritten,
// then prunes revisions beyond historyKeep.
func recordHistoryTx(tx *sql.Tx, n *Note, now time.Time) error {
if _, err := tx.Exec(
`INSERT OR REPLACE INTO note_history (note_id, version, content, tags, modified_at, replaced_at) VALUES (?,?,?,?,?,?)`,
n.ID, n.Version, n.Content, tagsJSON(n.Tags), n.ModifiedAt, now.UnixMilli()); err != nil {
return err
}
_, err := tx.Exec(
`DELETE FROM note_history WHERE note_id = ? AND version NOT IN (
SELECT version FROM note_history WHERE note_id = ? ORDER BY version DESC LIMIT ?)`,
n.ID, n.ID, historyKeep)
return err
}
// History returns a note's superseded revisions, newest first.
func (s *Store) History(noteID string) ([]Revision, error) {
rows, err := s.db.Query(
`SELECT note_id, version, content, tags, modified_at, replaced_at
FROM note_history WHERE note_id = ? ORDER BY version DESC`, noteID)
if err != nil {
return nil, err
}
defer rows.Close()
revs := []Revision{}
for rows.Next() {
var r Revision
var tags string
if err := rows.Scan(&r.NoteID, &r.Version, &r.Content, &tags, &r.ModifiedAt, &r.ReplacedAt); err != nil {
return nil, err
}
if err := json.Unmarshal([]byte(tags), &r.Tags); err != nil || r.Tags == nil {
r.Tags = []string{}
}
revs = append(revs, r)
}
return revs, rows.Err()
}
// conflictTitle appends the marker to the first non-empty line of content.
func conflictTitle(content string, at time.Time) string {
marker := at.Format(" (conflicted copy 2006-01-02 15:04)")
@@ -281,6 +344,9 @@ func (s *Store) ApplyBatch(in []IncomingNote, now time.Time) ([]PushResult, erro
case inc.BaseVersion == cur.Version:
// Rule 2: clean fast-forward.
if err := recordHistoryTx(tx, cur, now); err != nil {
return nil, err
}
v, err := nextVersionTx(tx)
if err != nil {
return nil, err
@@ -299,6 +365,9 @@ func (s *Store) ApplyBatch(in []IncomingNote, now time.Time) ([]PushResult, erro
case cur.Deleted:
// Rule 4b: stale edit vs server tombstone → edit wins, overwrites the tombstone.
if err := recordHistoryTx(tx, cur, now); err != nil {
return nil, err
}
v, err := nextVersionTx(tx)
if err != nil {
return nil, err
@@ -370,13 +439,17 @@ func (s *Store) UpsertImported(sourceID string, n Note) (bool, error) {
return true, tx.Commit()
}
// Compact purges tombstones older than the given number of days.
// Compact purges tombstones older than the given number of days, plus the
// history of any note that no longer exists.
func (s *Store) Compact(olderThanDays int) (int64, error) {
cutoff := time.Now().AddDate(0, 0, -olderThanDays).UnixMilli()
res, err := s.db.Exec(`DELETE FROM notes WHERE deleted = 1 AND modified_at < ?`, cutoff)
if err != nil {
return 0, err
}
if _, err := s.db.Exec(`DELETE FROM note_history WHERE note_id NOT IN (SELECT id FROM notes)`); err != nil {
return 0, err
}
return res.RowsAffected()
}