Commit ae747ac63e

ae747ac63efddb0f800b211d6f9997e0231b62aa

parent: 6fb74210e7

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-14 04:43 UTC

Snapshots of ordinary edits in Recovery Versions

Recovery versions were kept only when a save displaced another writer's
version, so ordinary writing had no history beyond undo. The save path now
offers the version it is about to replace to RecoveryStore.keepSnapshot when
the save changes the file; FileRecoveryStore keeps it, labelled snapshot,
when the file's last snapshot is more than an hour old. Snapshots have their
own limit of 10, so they never push out the 20 replaced versions. A snapshot
that can't be kept doesn't fail the save. Recovery Versions shows them as
"Snapshot, before a save" on the Mac and iOS.

Closes #81

Layout: unified · split

Sources/OrgDocument/FileStorage.swift +23 −3
@@ -53,16 +53,35 @@ public struct CoordinatedFileSystem: FileSystem {
5353 }
5454}
5555
56/// Keeps the last `limit` displaced versions per file in `directory/<hash of path>/`.
56/// Keeps the last `limit` displaced versions per file in `directory/<hash of path>/`, and
57/// apart from them up to `snapshotLimit` snapshots, the version before a save at most once
58/// every `snapshotInterval`.
5759public struct FileRecoveryStore: RecoveryStore {
5860 public let directory: URL
5961 public let limit: Int
62 public static let snapshotLimit = 10
63 public static let snapshotInterval: TimeInterval = 3600
64 static let snapshotLabel = "snapshot"
65 /// The clock, for tests.
66 public var now: @Sendable () -> Date = { Date() }
6067
6168 public init(directory: URL, limit: Int = 20) {
6269 self.directory = directory
6370 self.limit = limit
6471 }
6572
73 /// Whether the version file named `name` is a snapshot: after the 20-digit time and `-`.
74 static func isSnapshot(_ name: String) -> Bool {
75 name.dropFirst(21).hasPrefix(snapshotLabel + "-")
76 }
77
78 public func keepSnapshot(_ bytes: [UInt8], for url: URL) throws {
79 let last = try versions(for: url).map(\.lastPathComponent).last(where: Self.isSnapshot)
80 if let last, let nanoseconds = UInt64(last.prefix(20)),
81 now().timeIntervalSince1970 - Double(nanoseconds) / 1_000_000_000 < Self.snapshotInterval { return }
82 try keep(bytes, for: url, label: Self.snapshotLabel)
83 }
84
6685 public func folder(for url: URL) -> URL {
6786 let digest = SHA256.hash(data: Data(url.standardizedFileURL.path.utf8))
6887 let name = digest.prefix(8).map { String(format: "%02x", $0) }.joined()
@@ -74,11 +93,12 @@ public struct FileRecoveryStore: RecoveryStore {
7493 let manager = FileManager.default
7594 try manager.createDirectory(at: folder, withIntermediateDirectories: true)
7695 // Zero-padded wall-clock nanoseconds sort by time; the UUID keeps same-instant names apart.
77 let stamp = String(format: "%020llu", UInt64(Date().timeIntervalSince1970 * 1_000_000_000))
96 let stamp = String(format: "%020llu", UInt64(now().timeIntervalSince1970 * 1_000_000_000))
7897 let name = "\(stamp)-\(label)-\(UUID().uuidString.prefix(8))-\(url.lastPathComponent)"
7998 try Data(bytes).write(to: folder.appendingPathComponent(name))
8099 let kept = try manager.contentsOfDirectory(atPath: folder.path).sorted()
81 for old in kept.dropLast(limit) {
100 let snapshots = kept.filter(Self.isSnapshot)
101 for old in kept.filter({ !Self.isSnapshot($0) }).dropLast(limit) + snapshots.dropLast(Self.snapshotLimit) {
82102 try manager.removeItem(at: folder.appendingPathComponent(old))
83103 }
84104 }
Sources/OrgDocument/Saving.swift +8
@@ -11,6 +11,12 @@ public protocol FileSystem: Sendable {
1111
1212public protocol RecoveryStore: Sendable {
1313 func keep(_ bytes: [UInt8], for url: URL, label: String) throws
14 /// Offered the version a save is about to replace, to keep now and then as a snapshot.
15 func keepSnapshot(_ bytes: [UInt8], for url: URL) throws
16}
17
18extension RecoveryStore {
19 public func keepSnapshot(_ bytes: [UInt8], for url: URL) throws {}
1420}
1521
1622public enum SaveOutcome: Sendable, Equatable {
@@ -62,6 +68,8 @@ public struct Saver: Sendable {
6268 }
6369 let bytes = try state.encodedText()
6470 guard try fileSystem.read(url) == disk else { continue }
71 // A snapshot is a convenience: one that can't be kept doesn't stop the save.
72 if let disk, disk != bytes { try? recovery.keepSnapshot(disk, for: url) }
6573
6674 let replaced = try fileSystem.replace(url, with: bytes)
6775 state.didWrite(bytes)
Sources/Orgstar/VersionViews.swift +1
@@ -204,6 +204,7 @@ struct RecoverySheet: View {
204204 case "local": "Your version, replaced"
205205 case "external": "Disk version, replaced"
206206 case "sync-conflict": "Sync conflict copy"
207 case "snapshot": "Snapshot, before a save"
207208 default: label
208209 }
209210 }
Sources/OrgstarMobile/VersionScreens.swift +1
@@ -214,6 +214,7 @@ struct RecoverySheet: View {
214214 case "local": "Your version, replaced"
215215 case "external": "Disk version, replaced"
216216 case "sync-conflict": "Sync conflict copy"
217 case "snapshot": "Snapshot, before a save"
217218 default: label
218219 }
219220 }
Tests/OrgDocumentTests/SaveTests.swift +47
@@ -202,3 +202,50 @@ struct FileStorageTests {
202202 #expect(try versions.map { try String(contentsOf: $0, encoding: .utf8) } == ["v2", "v3", "v4"])
203203 }
204204}
205
206final class SnapshotRecovery: RecoveryStore, @unchecked Sendable {
207 var snapshots: [String] = []
208 func keep(_ bytes: [UInt8], for url: URL, label: String) throws {}
209 func keepSnapshot(_ bytes: [UInt8], for url: URL) throws {
210 snapshots.append(String(decoding: bytes, as: UTF8.self))
211 }
212}
213
214struct SnapshotTests {
215 /// A save that changes the file offers the version it replaces as a snapshot.
216 @Test func savesOfferTheReplacedVersion() throws {
217 let files = FaultyFileSystem("a\nb\nc\n")
218 let recovery = SnapshotRecovery()
219 var doc = try editedState()
220 #expect(try Saver(fileSystem: files, recovery: recovery).save(&doc, to: url) == .saved)
221 #expect(recovery.snapshots == ["a\nb\nc\n"])
222 // Saving the same text again changes nothing, so nothing is offered.
223 _ = try Saver(fileSystem: files, recovery: recovery).save(&doc, to: url)
224 #expect(recovery.snapshots.count == 1)
225 }
226
227 @Test func keptHourlyWithTheirOwnLimit() throws {
228 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-snap-\(UUID().uuidString)")
229 defer { try? FileManager.default.removeItem(at: folder) }
230 nonisolated(unsafe) var clock = Date(timeIntervalSince1970: 1_800_000_000)
231 var store = FileRecoveryStore(directory: folder)
232 store.now = { clock }
233 func labels() throws -> [String] { try store.versions(for: url).map { $0.lastPathComponent.split(separator: "-")[1].description } }
234 try store.keepSnapshot(Array("one".utf8), for: url)
235 clock += 1800
236 try store.keepSnapshot(Array("two".utf8), for: url)
237 #expect(try labels() == ["snapshot"])
238 clock += 1801
239 try store.keepSnapshot(Array("three".utf8), for: url)
240 #expect(try labels() == ["snapshot", "snapshot"])
241 // Displaced versions don't count towards the hour, and snapshots don't push them out.
242 try store.keep(Array("theirs".utf8), for: url, label: "external")
243 for _ in 0..<15 {
244 clock += 3601
245 try store.keepSnapshot(Array("later".utf8), for: url)
246 }
247 let kept = try labels()
248 #expect(kept.filter { $0 == "snapshot" }.count == FileRecoveryStore.snapshotLimit)
249 #expect(kept.contains("external"))
250 }
251}
docs/manual/guide/01-files-and-folders.org +1 −1
@@ -282,7 +282,7 @@ Each choice moves the copy to recovery and deletes it from the folder. The buffe
282282
283283** Recovery versions
284284
285Whenever orgstar replaces a version of a file, it keeps a copy: your buffer when you take the disk version, the disk version when you keep yours, a version another program wrote while orgstar saved, and resolved Syncthing copies. orgstar keeps the last 20 versions per file in =~/Library/Application Support/Orgstar/Recovery=.
285Whenever orgstar replaces a version of a file, it keeps a copy: your buffer when you take the disk version, the disk version when you keep yours, a version another program wrote while orgstar saved, and resolved Syncthing copies. It also keeps a snapshot of the file as it was before a save, at most once an hour, so there is a version of your own writing to go back to. orgstar keeps the last 20 replaced versions and the last 10 snapshots per file in =~/Library/Application Support/Orgstar/Recovery=.
286286
287287Choose File ▸ Recovery Versions… to see the open file's versions, newest first, each with its date and why it was kept:
288288
docs/manual/guide/15-alongside-emacs.org +3 −2
@@ -94,18 +94,19 @@ When scanning folders, orgstar skips Emacs lock files (=.#name=), backups (=name
9494
9595* Recovery versions
9696
97Every version a save, a merge or a conflict resolution displaces is kept in the recovery folder:
97Every version a save, a merge or a conflict resolution displaces is kept in the recovery folder, and so is a snapshot of the file before a save, at most once an hour:
9898
9999- on the Mac, =~/Library/Application Support/Orgstar/Recovery= (or =$ORGSTAR_DATA_DIR/Recovery=),
100100- on iOS, the app's own Application Support folder.
101101
102Each file has a subfolder named from a hash of its path, holding its last 20 kept versions. A version's file name has a timestamp, a label and the file's name. The labels are:
102Each file has a subfolder named from a hash of its path, holding its last 20 replaced versions and, apart from them, its last 10 snapshots. A version's file name has a timestamp, a label and the file's name. The labels are:
103103
104104| Label | Kept when |
105105|-----------------+-------------------------------------------------------------------------------|
106106| =external= | A version written by another program was replaced or merged |
107107| =local= | orgstar's version was replaced, or set aside by Use Disk Version, Merge with Markers or Restore |
108108| =sync-conflict= | A Syncthing conflict copy was resolved |
109| =snapshot= | A save changed the file and the last snapshot was more than an hour before |
109110
110111File ▸ Recovery Versions… (More ▸ Recovered Versions on iOS) lists the open file's kept versions, newest first, each compared with the buffer (lines marked - in the buffer, + in the kept version). Restore puts a version's text in the buffer as an edit you can undo; the buffer as it was goes to the recovery folder first. On the Mac, Show in Finder selects the version's file.
111112