diff --git a/README.md b/README.md index ac9bbff..4136a14 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ Open `http://localhost:8420`, click `⋯` → set server URL + token → Save. | `Ctrl/Cmd+Shift+P` | toggle markdown preview (`[[wiki-links]]` open/create notes) | | `Ctrl/Cmd+K` | cycle tag filter | | `Ctrl/Cmd+J` / `+Shift` | next / previous note while editing | +| `Ctrl/Cmd+I` | note info (created / last synced) & version history | ## CLI @@ -96,6 +97,12 @@ edits of the same note never silently overwrite: the loser comes back as a new n tagged `conflict` with “(conflicted copy …)” in its title. Delete-vs-edit: the edit wins. Every client keeps a full offline copy in IndexedDB; a crash mid-sync loses nothing. +**Version history:** every time an accepted sync overwrites a note, the server keeps the +previous state (last 50 revisions per note). `Ctrl/Cmd+I` (or the “History” button under +the editor) shows a note’s revisions; restoring one applies the old text as a new edit, +so the replaced text itself stays in history — rollback is never destructive. +`tefterd compact` drops history along with the purged notes. + ## Development ```sh diff --git a/SPEC.md b/SPEC.md index 8cf4ffc..8fbd892 100644 --- a/SPEC.md +++ b/SPEC.md @@ -92,17 +92,29 @@ CREATE TABLE notes ( CREATE INDEX idx_notes_version ON notes(version); CREATE TABLE meta (k TEXT PRIMARY KEY, v TEXT); -- schema_version, next_version counter + +CREATE TABLE note_history ( -- schema v2: version history + note_id TEXT NOT NULL, + version INTEGER NOT NULL, -- version of the superseded revision + content TEXT NOT NULL DEFAULT '', + tags TEXT NOT NULL DEFAULT '[]', + modified_at INTEGER NOT NULL, + replaced_at INTEGER NOT NULL, -- unix ms when it was overwritten + PRIMARY KEY (note_id, version) +); ``` - **Title is derived**, never stored: first non-empty line of `content`, markdown heading markers stripped for display. - `version` is a single global monotonically increasing counter (like a Lamport clock per server). Every accepted write bumps the global counter and stamps the note. This makes "give me everything changed since cursor X" trivial. - Tombstones are kept forever (personal scale; millions of notes are not expected). A `tefterd compact` subcommand may purge tombstones older than N days. +- **Version history:** whenever an accepted push overwrites an existing note (fast-forward or edit-over-tombstone), the superseded state is copied into `note_history`, capped at the newest 50 revisions per note. Conflict pushes touch nothing, so they record nothing. `compact` purges history rows of notes that no longer exist. Rollback is client-side: fetch a revision, apply its content as a normal edit. ### Client store (IndexedDB) Object store `notes`: same fields as server, plus: - `dirty: boolean` — locally modified, not yet pushed. - `baseVersion: number` — server version this local copy was derived from (0 for never-synced). +- `synced_at?: number` — unix ms of the last confirmed exchange with the server for this note (accepted push or applied pull); absent = never synced. Object store `meta`: `cursor` (last server version pulled), `serverUrl`, `token`. @@ -116,6 +128,7 @@ Design: **pull-then-push, last-write-wins with conflict copies** (Simplenote-sty |---|---|---| | GET | `/changes?since=&limit=500` | Pull notes with `version > cursor`, ordered by version. Returns `{notes: [...], cursor: , more: bool}` | | POST | `/notes/batch` | Push local changes. Body: `{notes: [{id, content, tags, created_at, modified_at, deleted, baseVersion}]}` | +| GET | `/notes/{id}/history` | Superseded revisions of a note, newest first: `{revisions: [{note_id, version, content, tags, modified_at, replaced_at}]}` (empty list for unknown ids) | | GET | `/health` | Liveness + schema version | | POST | `/import/simplenote` | Multipart upload of Simplenote export zip (also available as CLI) | @@ -187,6 +200,7 @@ This section is the heart of the product. The NV model must be reproduced exactl | Cmd/Ctrl+Shift+P | Toggle markdown preview for current note | | Cmd/Ctrl+K | Cycle tag filter (simple tag dropdown) | | Cmd/Ctrl+J / Cmd/Ctrl+Shift+J | Next / previous note in list while in editor | +| Cmd/Ctrl+I | Note info (created / modified / last synced) + version history panel; a revision can be previewed and restored (restore = normal edit, non-destructive) | ### Editor - CodeMirror 6, markdown mode, light syntax styling only (bold headings, dim syntax marks). Monospace or user-set font. No WYSIWYG. diff --git a/frontend/src/db/store.ts b/frontend/src/db/store.ts index 53d7f93..08c9c60 100644 --- a/frontend/src/db/store.ts +++ b/frontend/src/db/store.ts @@ -102,10 +102,11 @@ export async function applyServerNote(sn: ServerNote): Promise { export async function applyServerNotes(sns: ServerNote[]): Promise { const m = get(notes); const updates: Note[] = []; + const now = Date.now(); for (const sn of sns) { const local = m.get(sn.id); if (local && local.dirty) continue; // push will resolve - updates.push({ ...sn, baseVersion: sn.version, dirty: false }); + updates.push({ ...sn, baseVersion: sn.version, dirty: false, synced_at: now }); } if (!updates.length) return; notes.update((map) => { @@ -120,14 +121,14 @@ export async function markPushed(id: string, sentModifiedAt: number, version: nu const n = get(notes).get(id); if (!n) return; const stillSame = n.modified_at === sentModifiedAt; - const upd: Note = { ...n, version, baseVersion: version, dirty: stillSame ? false : n.dirty }; + const upd: Note = { ...n, version, baseVersion: version, dirty: stillSame ? false : n.dirty, synced_at: Date.now() }; mutate(upd); await idbPutNote(upd); } /** After a conflict: server truth replaces local; conflict copy arrives via next pull. */ export async function replaceWithServer(sn: ServerNote): Promise { - const upd: Note = { ...sn, baseVersion: sn.version, dirty: false }; + const upd: Note = { ...sn, baseVersion: sn.version, dirty: false, synced_at: Date.now() }; mutate(upd); await idbPutNote(upd); } diff --git a/frontend/src/sync/engine.ts b/frontend/src/sync/engine.ts index 2b49f82..e20e576 100644 --- a/frontend/src/sync/engine.ts +++ b/frontend/src/sync/engine.ts @@ -1,5 +1,5 @@ import { writable, get } from 'svelte/store'; -import type { PushResult, ServerNote, SyncState } from '../types'; +import type { PushResult, Revision, ServerNote, SyncState } from '../types'; import { notes, settings, cursor, setCursor, applyServerNotes, markPushed, replaceWithServer } from '../db/store'; export const syncState = writable('local'); @@ -66,6 +66,15 @@ async function push(): Promise { } } +/** Fetch a note's server-side revision history (newest first). */ +export async function fetchHistory(id: string): Promise { + if (!configured()) throw new Error('no server configured'); + const res = await api(`/api/v1/notes/${encodeURIComponent(id)}/history`); + if (!res.ok) throw new Error(`history: HTTP ${res.status}`); + const body: { revisions: Revision[] } = await res.json(); + return body.revisions; +} + /** Pull-then-push; safe to interrupt at any point (SPEC §4). */ export async function syncNow(): Promise { if (!configured()) { diff --git a/frontend/src/time.ts b/frontend/src/time.ts new file mode 100644 index 0000000..1885d97 --- /dev/null +++ b/frontend/src/time.ts @@ -0,0 +1,13 @@ +/** Absolute timestamp for metadata display, e.g. "Jul 25, 2026, 14:03". */ +export function fmtDateTime(ms: number): string { + return new Date(ms).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }); +} + +/** Coarse relative timestamp: "just now", "5 min ago", "3 h ago", else absolute. */ +export function fmtAgo(ms: number, now: number = Date.now()): string { + const d = now - ms; + if (d < 60_000) return 'just now'; + if (d < 3_600_000) return `${Math.floor(d / 60_000)} min ago`; + if (d < 86_400_000) return `${Math.floor(d / 3_600_000)} h ago`; + return fmtDateTime(ms); +} diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 7d4e6d6..e564640 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -8,6 +8,17 @@ export interface Note { version: number; // server-assigned version of the copy we derived from (0 = never synced) baseVersion: number; // server version this local copy was derived from dirty: boolean; // locally modified, not yet pushed + synced_at?: number; // unix ms of last confirmed server exchange (absent = never synced) +} + +/** A superseded note state kept server-side (GET /notes/{id}/history). */ +export interface Revision { + note_id: string; + version: number; + content: string; + tags: string[]; + modified_at: number; + replaced_at: number; } export interface ServerNote { diff --git a/frontend/src/ui/App.svelte b/frontend/src/ui/App.svelte index f073aa1..07ab9f4 100644 --- a/frontend/src/ui/App.svelte +++ b/frontend/src/ui/App.svelte @@ -10,13 +10,17 @@ import Preview from './Preview.svelte'; import StatusDot from './StatusDot.svelte'; import SettingsMenu from './SettingsMenu.svelte'; + import NoteInfo from './NoteInfo.svelte'; import Toast from './Toast.svelte'; + import { fmtDateTime, fmtAgo } from '../time'; let query = ''; let selectedId: string | null = null; let tagFilter: string | null = null; let preview = false; let menuOpen = false; + let infoOpen = false; + let now = Date.now(); // periodic tick so "synced X ago" stays fresh let narrow = false; let mobileView: 'list' | 'editor' = 'list'; let toast: { message: string; onAction: () => void } | null = null; @@ -142,6 +146,9 @@ } else if (mod && e.shiftKey && e.key.toLowerCase() === 'p') { e.preventDefault(); if (selected) preview = !preview; + } else if (mod && !e.shiftKey && e.key.toLowerCase() === 'i') { + e.preventDefault(); + if (selected) infoOpen = !infoOpen; } else if (mod && !e.shiftKey && e.key.toLowerCase() === 'k') { e.preventDefault(); cycleTag(); @@ -161,13 +168,17 @@ narrow = mq.matches; const onMq = () => (narrow = mq.matches); mq.addEventListener('change', onMq); + const tick = setInterval(() => (now = Date.now()), 30_000); omnibar?.focus(); // First run: offer server config; Cancel = work locally only (SPEC §7). if (!localStorage.getItem('tefter-first-run-done')) { localStorage.setItem('tefter-first-run-done', '1'); if (!notesArr.length && !$settings.serverUrl) menuOpen = true; } - return () => mq.removeEventListener('change', onMq); + return () => { + mq.removeEventListener('change', onMq); + clearInterval(tick); + }; }); @@ -219,6 +230,24 @@

Type to search — Enter creates a note when nothing matches.

{/if} + {#if selected} +
+ Created {fmtDateTime(selected.created_at)} + · + + {#if selected.dirty} + Sync pending + {:else if selected.synced_at} + Synced {fmtAgo(selected.synced_at, now)} + {:else} + Not synced + {/if} + + +
+ {/if} {/if} @@ -227,6 +256,10 @@ (menuOpen = false)} /> {/if} + {#if infoOpen && selected} + (infoOpen = false)} /> + {/if} + {#if toast} (toast = null)} /> {/if} @@ -319,6 +352,30 @@ text-overflow: ellipsis; white-space: nowrap; } + .note-meta { + display: flex; + align-items: center; + gap: 6px; + padding: 3px 10px; + border-top: 1px solid var(--sep); + font-size: 11.5px; + color: var(--fg-dim); + white-space: nowrap; + overflow: hidden; + } + .meta-sep { + opacity: 0.6; + } + .meta-btn { + margin-left: auto; + color: var(--accent); + font-size: 11.5px; + padding: 2px 6px; + border-radius: 5px; + } + .meta-btn:hover { + background: var(--sel-bg); + } .empty { flex: 1; display: flex; diff --git a/frontend/src/ui/NoteInfo.svelte b/frontend/src/ui/NoteInfo.svelte new file mode 100644 index 0000000..43dbff4 --- /dev/null +++ b/frontend/src/ui/NoteInfo.svelte @@ -0,0 +1,220 @@ + + + +
dispatch('close')}> +
+

{noteTitle(note.content)}

+ +
+

Info

+
+
Created
+
{fmtDateTime(note.created_at)}
+
Modified
+
{fmtDateTime(note.modified_at)}
+
Last synced
+
{syncLabel}
+ {#if note.version > 0} +
Server version
+
{note.version}
+ {/if} +
+
+ +
+

History

+ {#if !hasServer} +
Versions are recorded on the server — configure sync in Settings to get history.
+ {:else if loading} +
Loading…
+ {:else if error} +
Couldn’t load history: {error}
+ {:else if !revisions.length} +
No older versions yet. A version is saved every time a synced note is overwritten.
+ {:else} +
    + {#each revisions as rev (rev.version)} +
  • + + {#if selected?.version === rev.version} +
    {rev.content}
    + + {/if} +
  • + {/each} +
+
Restoring applies the old text as a new edit — nothing is lost, the current text stays in history.
+ {/if} +
+ +
+ +
+
+
+ + diff --git a/server/api/api.go b/server/api/api.go index 8fc8727..bc720c0 100644 --- a/server/api/api.go +++ b/server/api/api.go @@ -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()) diff --git a/server/api/api_test.go b/server/api/api_test.go index 726a3bc..5dd9b5c 100644 --- a/server/api/api_test.go +++ b/server/api/api_test.go @@ -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) diff --git a/server/store/store.go b/server/store/store.go index bd789b4..6e76954 100644 --- a/server/store/store.go +++ b/server/store/store.go @@ -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() } diff --git a/server/store/store_test.go b/server/store/store_test.go index a71974c..332bb3f 100644 --- a/server/store/store_test.go +++ b/server/store/store_test.go @@ -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()