Branchwell

Glimmer / app · glimmertoday.ai / native / Glimmer / JournalStore.swift

1import Foundation
2import Observation
3
4@MainActor
5@Observable
6final class JournalStore {
7 private let bundledCatalog: Catalog?
8 let editorialLibrary: EditorialLibrary?
9 var catalog: Catalog? { editorialLibrary?.edition?.content ?? bundledCatalog }
10 var maintenanceChores: [MaintenanceChore] {
11 catalog?.cleaning.maintenance ?? bundledCatalog?.cleaning.maintenance ?? []
12 }
13 var seasonalEditions: [SeasonalEdition] { catalog?.seasonal ?? bundledCatalog?.seasonal ?? [] }
14 var dailyQuote: DailyQuote? {
15 DailyQuote.quote(on: day, from: catalog?.quotes ?? bundledCatalog?.quotes ?? [])
16 }
17 private(set) var journal = Journal()
18 private(set) var loadError: String?
19 var notice: String?
20 private(set) var earnedCoins: EarnedCoins?
21 var showingOnboardingReplay = false
22 var day = Date()
23 private let url: URL
24 private let cloud: JournalCloud?
25 private var cloudState: JournalCloudState?
26 private var syncing = false
27 private var cloudGeneration = UUID()
28 private(set) var cloudStatus = "Journal stays on this device."
29 private(set) var accountStatus = "Not checked"
30 private(set) var lastCheck: Date?
31 private(set) var lastCloudContact: Date?
32 private(set) var syncErrorCode: String?
33 var cloudSyncing: Bool { syncing }
34
35 var cloudEnabled: Bool { cloudState?.enabled == true }
36 var canUseCloud: Bool { cloud != nil && loadError == nil }
37
38 init(url: URL? = nil, catalogURL: URL? = AppResources.url("Catalog", extension: "json")) {
39 self.url = url ?? Self.storageURL
40 // An explicitly isolated journal must never join the signed-in user's iCloud account.
41 cloud = url == nil && Self.testJournalID == nil ? JournalCloud() : nil
42 let baseline = catalogURL.flatMap { try? Catalog.load(from: $0) }
43 bundledCatalog = baseline
44 editorialLibrary = url == nil && Self.testJournalID == nil
45 ? baseline.map { EditorialLibrary(bundled: $0) } : nil
46 reload()
47 #if os(macOS)
48 if url == nil { watchForAgentChanges() }
49 #endif
50 }
51
52 private nonisolated static var testJournalID: UUID? {
53 #if DEBUG
54 ProcessInfo.processInfo.environment["GLIMMER_TEST_JOURNAL"].flatMap(UUID.init(uuidString:))
55 #else
56 nil
57 #endif
58 }
59
60 var usesDeviceReminders: Bool {
61 Self.testJournalID == nil || ProcessInfo.processInfo.environment["GLIMMER_TEST_REMINDERS"] == "1"
62 }
63
64 nonisolated static var storageURL: URL {
65 let folder = testJournalID.map { "Glimmer-Test-\($0.uuidString)" } ?? "Glimmer"
66 let root = URL.applicationSupportDirectory.appending(path: folder, directoryHint: .isDirectory)
67 return root.appending(path: "Journal.json")
68 }
69
70 #if os(macOS)
71 private(set) var agentLevel = AgentAccess.Level.off
72 private(set) var agentActivity: AgentActivity?
73 private var diskStamp: Date?
74 private var watcher: DispatchSourceFileSystemObject?
75
76 private var folder: URL { url.deletingLastPathComponent() }
77
78 /// Off removes both permissions. Changes also turns on summaries, because it includes them.
79 func setAgentLevel(_ level: AgentAccess.Level) throws {
80 let manager = FileManager.default
81 try manager.createDirectory(at: folder, withIntermediateDirectories: true)
82 for (name, wanted) in [(AgentAccess.marker, level != .off), (AgentAccess.changesMarker, level == .changes)] {
83 let file = folder.appending(path: name)
84 if wanted && !manager.fileExists(atPath: file.path) {
85 try Data().write(to: file, options: .atomic)
86 } else if !wanted && manager.fileExists(atPath: file.path) {
87 try manager.removeItem(at: file)
88 }
89 }
90 refreshAgentState()
91 }
92
93 func refreshAgentState() {
94 agentLevel = AgentAccess.level(in: folder)
95 let activity = AgentActivity.read(in: folder)
96 if activity != agentActivity { agentActivity = activity }
97 }
98
99 private var currentStamp: Date? {
100 try? FileManager.default.attributesOfItem(atPath: url.path)[.modificationDate] as? Date
101 }
102
103 /// An agent connected with `--mcp` may have saved the journal. Pick its change up before saving over it.
104 func reloadIfChangedOnDisk() {
105 guard currentStamp != diskStamp else { return }
106 reload()
107 }
108
109 private func watchForAgentChanges() {
110 refreshAgentState()
111 try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
112 let descriptor = open(folder.path, O_EVTONLY)
113 guard descriptor >= 0 else { return }
114 let source = DispatchSource.makeFileSystemObjectSource(fileDescriptor: descriptor, eventMask: .write, queue: .main)
115 source.setEventHandler { [weak self] in
116 MainActor.assumeIsolated {
117 self?.reloadIfChangedOnDisk()
118 self?.refreshAgentState()
119 }
120 }
121 source.setCancelHandler { close(descriptor) }
122 source.resume()
123 watcher = source
124 }
125 #endif
126
127 func reload() {
128 do {
129 #if os(macOS)
130 let stamp = currentStamp
131 #endif
132 if FileManager.default.fileExists(atPath: url.path) {
133 let data = try Data(contentsOf: url)
134 let saved = try JSONDecoder().decode(SavedJournal.self, from: data)
135 journal = try Self.validate(saved.journal)
136 cloudState = saved.cloud
137 }
138 #if os(macOS)
139 diskStamp = stamp
140 #endif
141 loadError = nil
142 } catch {
143 loadError = "Glimmer couldn’t open the journal. The original file is still on this device."
144 }
145 }
146
147 @discardableResult
148 func change(_ mutate: (inout Journal) -> Void) -> Bool {
149 do {
150 try withWriteLock {
151 #if os(macOS)
152 // Another MCP client or the app may have committed while this client was waiting.
153 reloadIfChangedOnDisk()
154 #endif
155 guard loadError == nil else { throw CocoaError(.fileReadCorruptFile) }
156 var next = journal
157 let now = Date()
158 // Capture verified dates from pre-ledger journals before an edit replaces the last checklist date.
159 if next.readerDays == nil { next.preserveReaderDays(asOf: now) }
160 mutate(&next)
161 next.preserveReaderDays(asOf: now)
162 var nextCloud = cloudState
163 if var state = nextCloud {
164 try state.replica.observe(from: journal, to: next, device: state.device)
165 nextCloud = state
166 }
167 let amount = next.coins - journal.coins
168 try persist(next, cloud: nextCloud)
169 if amount > 0 {
170 notice = nil
171 earnedCoins = EarnedCoins(amount: amount)
172 }
173 }
174 return true
175 } catch {
176 notice = "Glimmer couldn’t save this change. Please try again."
177 return false
178 }
179 }
180
181 private func withWriteLock(_ action: () throws -> Void) throws {
182 #if os(macOS)
183 // The journal file itself is atomically replaced, so coordinate on a stable sibling.
184 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
185 let descriptor = open(folder.appending(path: ".journal-write.lock").path, O_CREAT | O_RDWR | O_CLOEXEC, 0o600)
186 guard descriptor >= 0 else { throw POSIXError(.EACCES) }
187 defer { close(descriptor) }
188 while flock(descriptor, LOCK_EX) != 0 {
189 if errno != EINTR { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
190 }
191 #endif
192 try action()
193 }
194
195 private func save(_ next: Journal, cloud state: JournalCloudState?) throws {
196 try withWriteLock {
197 #if os(macOS)
198 guard currentStamp == diskStamp else {
199 reload()
200 throw CocoaError(.fileWriteFileExists)
201 }
202 #endif
203 try persist(next, cloud: state)
204 }
205 }
206
207 private func persist(_ next: Journal, cloud state: JournalCloudState?) throws {
208 let data = try JSONEncoder().encode(SavedJournal(journal: next, cloud: state))
209 let directory = url.deletingLastPathComponent()
210 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
211 #if os(iOS)
212 var values = URLResourceValues()
213 values.isExcludedFromBackup = true
214 var backupExcludedDirectory = directory
215 try backupExcludedDirectory.setResourceValues(values)
216 try data.write(to: url, options: [.atomic, .completeFileProtection])
217 #else
218 try data.write(to: url, options: .atomic)
219 diskStamp = currentStamp
220 #endif
221 journal = next
222 cloudState = state
223 }
224
225 func setCloudEnabled(_ enabled: Bool) {
226 guard canUseCloud else { return }
227 do {
228 var state: JournalCloudState
229 if let cloudState {
230 state = cloudState
231 } else {
232 let device = UUID()
233 state = JournalCloudState(device: device, replica: try JournalReplica(seed: journal, device: device))
234 }
235 state.enabled = enabled
236 state.acceptAccountChange = enabled
237 try save(journal, cloud: state)
238 cloudGeneration = UUID()
239 cloud?.stop()
240 cloudStatus = enabled ? "Connecting to iCloud Drive…" : "Sync is off on this device."
241 } catch {
242 cloudStatus = "Couldn’t change iCloud sync. Try again."
243 }
244 }
245
246 func syncWhileActive() async {
247 while cloudEnabled && !Task.isCancelled {
248 await syncNow()
249 do { try await Task.sleep(for: .seconds(8)) } catch { return }
250 }
251 }
252
253 func cloudAccountChanged() {
254 cloudGeneration = UUID()
255 cloud?.stop()
256 if cloudEnabled { cloudStatus = "Checking your Apple Account…" }
257 }
258
259 func syncNow() async {
260 guard let cloud, cloudEnabled, !syncing, loadError == nil else { return }
261 syncing = true
262 defer { syncing = false }
263 let generation = cloudGeneration
264 lastCheck = .now
265 syncErrorCode = nil
266 do {
267 let connection = try await Task.detached { try JournalCloud.connect() }.value
268 guard cloudGeneration == generation, cloudEnabled, !Task.isCancelled, var state = cloudState else { return }
269 guard let connection else {
270 cloud.stop()
271 accountStatus = FileManager.default.ubiquityIdentityToken == nil ? "Not signed in" : "iCloud Drive unavailable"
272 cloudStatus = "iCloud Drive is unavailable. Your changes are saved here."
273 return
274 }
275 accountStatus = "Connected"
276 if state.account != connection.account {
277 if state.account != nil && !state.acceptAccountChange {
278 setCloudEnabled(false)
279 cloudStatus = "Apple Account changed. Turn on sync to use the current account."
280 return
281 }
282 if state.account != nil {
283 state.device = UUID()
284 state.replica = try JournalReplica(seed: journal, device: state.device)
285 }
286 state.account = connection.account
287 }
288 if state.acceptAccountChange || state.account != cloudState?.account {
289 state.acceptAccountChange = false
290 try save(journal, cloud: state)
291 }
292 guard let files = try cloud.files(in: connection) else {
293 cloudStatus = "Looking for your journal in iCloud Drive…"
294 return
295 }
296 let device = state.device
297 let exchange = try await Task.detached {
298 try JournalCloud.pull(files, device: device, in: connection)
299 }.value
300 lastCloudContact = .now
301 // Read local state again after the download so an edit made while it ran is never lost.
302 guard cloudGeneration == generation, cloudEnabled, !Task.isCancelled, var current = cloudState else { return }
303 current.replica.merge(exchange.remote)
304 if current.replica != cloudState?.replica {
305 let updated = try current.replica.materialize(keepingEngagement: journal.engagement)
306 try save(updated, cloud: current)
307 }
308 guard !exchange.downloading else {
309 cloudStatus = "Downloading changes from iCloud Drive…"
310 return
311 }
312 let replica = current.replica
313 let uploaded = try await Task.detached {
314 if exchange.own != replica {
315 return try JournalCloud.push(replica, device: device, in: connection)
316 }
317 return try JournalCloud.uploaded(device: device, in: connection)
318 }.value
319 guard cloudGeneration == generation, cloudEnabled else { return }
320 cloudStatus = uploaded && replica == cloudState?.replica ? "Journal synced with iCloud Drive." : "Waiting for iCloud Drive to upload changes…"
321 } catch {
322 let failure = error as NSError
323 syncErrorCode = "\(failure.domain) (\(failure.code))"
324 if cloudGeneration == generation && cloudEnabled {
325 cloudStatus = "iCloud sync will retry. Your changes are saved here."
326 }
327 }
328 }
329
330 func export() throws -> Data { try JSONEncoder().encode(journal) }
331
332 func readBackup(_ url: URL) throws -> Journal {
333 let scoped = url.startAccessingSecurityScopedResource()
334 defer { if scoped { url.stopAccessingSecurityScopedResource() } }
335 return try Self.decode(Data(contentsOf: url))
336 }
337
338 nonisolated static func decode(_ data: Data) throws -> Journal {
339 try validate(JSONDecoder().decode(Journal.self, from: data))
340 }
341
342 private nonisolated static func validate(_ journal: Journal) throws -> Journal {
343 let todos = journal.personalTodos ?? []
344 let steps = journal.todoSteps ?? []
345 let estimates = journal.todoEstimates ?? []
346 guard journal.version == 1,
347 Set(steps.map(\.id)).count == steps.count, steps.allSatisfy(\.isValid),
348 Set(estimates.map(\.id)).count == estimates.count, estimates.allSatisfy(\.isValid),
349 Set(journal.tasks.map(\.id)).count == journal.tasks.count,
350 Set(todos.map(\.id)).count == todos.count, todos.allSatisfy(\.isValid),
351 Set(journal.moments.map(\.id)).count == journal.moments.count,
352 journal.rewards.values.allSatisfy({ (0...60).contains($0) }) else {
353 throw CocoaError(.fileReadCorruptFile)
354 }
355 return journal.droppingBuiltInEmoji()
356 }
357
358 func start(name: String) {
359 guard let catalog, !journal.onboardingComplete else { return }
360 let now = Date()
361 change {
362 $0.started = now
363 $0.name = name.trimmingCharacters(in: .whitespacesAndNewlines)
364 $0.tasks = catalog.initialTasks.map { PlanTask(template: $0, date: now) }
365 $0.award(40, key: "welcome")
366 let selected = $0.answers["first_experiment"]?.first
367 if let suggestion = catalog.startingSuggestions($0.answers).first(where: { $0.id == selected }) {
368 $0.queued.append(suggestion)
369 }
370 }
371 }
372
373 func startOrQueue(_ suggestion: Suggestion) {
374 if change({
375 if $0.experiment == nil {
376 $0.experiment = Experiment(suggestion: suggestion, start: Date())
377 $0.queued.removeAll { $0.id == suggestion.id }
378 } else if $0.experiment?.suggestion != suggestion && !$0.queued.contains(suggestion) {
379 $0.queued.append(suggestion)
380 }
381 }) {
382 notice = journal.experiment?.suggestion == suggestion ? "Experiment started." : "Saved for your next experiment."
383 }
384 }
385
386 var todayKey: String { CalendarDay.key(day) }
387 var todaysTasks: [PlanTask] { journal.tasks.filter { $0.occurs(on: day) } }
388 var duePersonalTodos: [PersonalTodo] {
389 let today = PracticeDate.key(day)
390 return PersonalTodo.ordered((journal.personalTodos ?? []).filter { $0.isDue(by: today) })
391 }
392
393 @discardableResult
394 func setPersonalTodoDone(_ id: UUID, done: Bool) -> Bool {
395 var found = false
396 return change { journal in
397 found = journal.setPersonalTodo(id, done: done)
398 } && found
399 }
400 var todayLogs: [Moment] { journal.moments.filter { $0.day == todayKey } }
401 var todayCompletion: Set<String> { journal.completions[todayKey] ?? [] }
402}