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

@@ -28,6 +28,7 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("GET /api/v1/health", s.handleHealth)
mux.Handle("GET /api/v1/changes", s.auth(s.handleChanges))
mux.Handle("POST /api/v1/notes/batch", s.auth(s.handleBatch))
mux.Handle("GET /api/v1/notes/{id}/history", s.auth(s.handleHistory))
mux.Handle("POST /api/v1/import/simplenote", s.auth(s.handleImport))
mux.HandleFunc("OPTIONS /api/v1/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
@@ -108,6 +109,16 @@ func (s *Server) handleBatch(w http.ResponseWriter, r *http.Request) {
writeJSON(w, map[string]any{"results": results})
}
func (s *Server) handleHistory(w http.ResponseWriter, r *http.Request) {
revs, err := s.Store.History(r.PathValue("id"))
if err != nil {
log.Printf("history: %v", err)
jsonError(w, http.StatusInternalServerError, "internal error")
return
}
writeJSON(w, map[string]any{"revisions": revs})
}
func (s *Server) handleImport(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(64 << 20); err != nil {
jsonError(w, http.StatusBadRequest, "bad multipart form: "+err.Error())

View File

@@ -229,6 +229,45 @@ func TestTwoClientsConverge(t *testing.T) {
}
}
func TestHistoryEndpoint(t *testing.T) {
srv, tok := newTestServer(t)
a := newClient(t, srv.URL, tok)
a.edit("n1", "v1")
a.sync()
a.edit("n1", "v2")
a.notes["n1"].ModifiedAt = 2
a.sync()
var body struct {
Revisions []store.Revision `json:"revisions"`
}
if code := a.req("GET", "/api/v1/notes/n1/history", nil, &body); code != 200 {
t.Fatalf("history HTTP %d", code)
}
if len(body.Revisions) != 1 || body.Revisions[0].Content != "v1" {
t.Fatalf("history: %+v", body.Revisions)
}
// Unknown note → empty list, not an error.
if code := a.req("GET", "/api/v1/notes/nope/history", nil, &body); code != 200 {
t.Fatalf("unknown note HTTP %d", code)
}
if len(body.Revisions) != 0 {
t.Fatalf("want empty history, got %+v", body.Revisions)
}
// Auth required.
res, err := http.Get(srv.URL + "/api/v1/notes/n1/history")
if err != nil {
t.Fatal(err)
}
res.Body.Close()
if res.StatusCode != http.StatusUnauthorized {
t.Fatalf("want 401, got %d", res.StatusCode)
}
}
func TestDeleteEditConflictAcrossClients(t *testing.T) {
srv, tok := newTestServer(t)
a := newClient(t, srv.URL, tok)

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()
}

View File

@@ -1,6 +1,7 @@
package store
import (
"fmt"
"path/filepath"
"strings"
"testing"
@@ -159,6 +160,104 @@ func TestChangesPaging(t *testing.T) {
}
}
func TestHistoryRecordsSupersededRevisions(t *testing.T) {
s := newTestStore(t)
r1 := push(t, s, IncomingNote{ID: "a", Content: "v1", Tags: []string{"t"}, ModifiedAt: 1})
if revs, _ := s.History("a"); len(revs) != 0 {
t.Fatalf("insert must not create history, got %d", len(revs))
}
r2 := push(t, s, IncomingNote{ID: "a", Content: "v2", ModifiedAt: 2, BaseVersion: r1.Version})
r3 := push(t, s, IncomingNote{ID: "a", Content: "v3", ModifiedAt: 3, BaseVersion: r2.Version})
revs, err := s.History("a")
if err != nil {
t.Fatal(err)
}
if len(revs) != 2 {
t.Fatalf("want 2 revisions, got %d", len(revs))
}
// Newest first: the v2 state (superseded by the v3 push), then v1.
if revs[0].Content != "v2" || revs[0].Version != r2.Version {
t.Fatalf("revs[0] = %+v", revs[0])
}
if revs[1].Content != "v1" || revs[1].Version != r1.Version || !containsStr(revs[1].Tags, "t") {
t.Fatalf("revs[1] = %+v", revs[1])
}
if revs[0].ReplacedAt == 0 {
t.Fatal("replaced_at not stamped")
}
_ = r3
}
func TestHistoryRecordedOnDeleteAndResurrect(t *testing.T) {
s := newTestStore(t)
r1 := push(t, s, IncomingNote{ID: "a", Content: "precious", ModifiedAt: 1})
r2 := push(t, s, IncomingNote{ID: "a", Content: "precious", Deleted: true, ModifiedAt: 2, BaseVersion: r1.Version})
// Stale edit overwrites the tombstone (rule 4b) — tombstone state goes to history.
push(t, s, IncomingNote{ID: "a", Content: "resurrected", ModifiedAt: 3, BaseVersion: r1.Version})
revs, err := s.History("a")
if err != nil {
t.Fatal(err)
}
if len(revs) != 2 || revs[0].Version != r2.Version || revs[1].Content != "precious" {
t.Fatalf("history after delete+resurrect: %+v", revs)
}
}
func TestHistoryNotRecordedOnConflict(t *testing.T) {
s := newTestStore(t)
r1 := push(t, s, IncomingNote{ID: "a", Content: "base", ModifiedAt: 1})
push(t, s, IncomingNote{ID: "a", Content: "B's edit", ModifiedAt: 2, BaseVersion: r1.Version})
// Stale edit → conflict copy; server note untouched, so no new history entry.
push(t, s, IncomingNote{ID: "a", Content: "A's edit", ModifiedAt: 3, BaseVersion: r1.Version})
revs, _ := s.History("a")
if len(revs) != 1 || revs[0].Content != "base" {
t.Fatalf("conflict must not record history: %+v", revs)
}
}
func TestHistoryPrunedToCap(t *testing.T) {
s := newTestStore(t)
r := push(t, s, IncomingNote{ID: "a", Content: "v0", ModifiedAt: 0})
for i := 1; i <= historyKeep+10; i++ {
r = push(t, s, IncomingNote{ID: "a", Content: fmt.Sprintf("v%d", i), ModifiedAt: int64(i), BaseVersion: r.Version})
}
revs, err := s.History("a")
if err != nil {
t.Fatal(err)
}
if len(revs) != historyKeep {
t.Fatalf("want %d revisions after prune, got %d", historyKeep, len(revs))
}
if revs[0].Content != fmt.Sprintf("v%d", historyKeep+9) {
t.Fatalf("newest revision wrong: %q", revs[0].Content)
}
}
func TestCompactPurgesOrphanHistory(t *testing.T) {
s := newTestStore(t)
old := time.Now().AddDate(0, 0, -200).UnixMilli()
r1 := push(t, s, IncomingNote{ID: "a", Content: "x", ModifiedAt: old})
push(t, s, IncomingNote{ID: "a", Deleted: true, ModifiedAt: old, BaseVersion: r1.Version})
if _, err := s.Compact(90); err != nil {
t.Fatal(err)
}
revs, err := s.History("a")
if err != nil {
t.Fatal(err)
}
if len(revs) != 0 {
t.Fatalf("history must be purged with the note, got %d", len(revs))
}
}
func TestTokenRoundtrip(t *testing.T) {
s := newTestStore(t)
tok, err := s.EnsureToken()