Branchwell

Glimmer / app / native / Checks / CoreChecks.swift

1import Foundation
2import ImageIO
3
4@main
5struct CoreChecks {
6 @MainActor
7 static func main() async throws {
8 let directory = URL(fileURLWithPath: CommandLine.arguments[1]).appending(path: "LibraryContent/Gallery/Gallery.json")
9 try await galleryRefreshChecks(GalleryCatalog.load(directory), posterDirectory: directory.deletingLastPathComponent())
10 try await editorialRefreshChecks(resources: directory.deletingLastPathComponent().deletingLastPathComponent())
11 try core()
12 try glyphChecks(resources: directory.deletingLastPathComponent().deletingLastPathComponent())
13 engagementChecks()
14 supportReminderChecks()
15 inkspringLinkChecks()
16 try agentSkillChecks(native: URL(fileURLWithPath: CommandLine.arguments[1]))
17 if CommandLine.arguments.contains("--verify-live-editorial") {
18 let resources = directory.deletingLastPathComponent().deletingLastPathComponent()
19 let catalog = try Catalog.load(from: resources.appending(path: "Catalog.json"))
20 let gallery = try GalleryCatalog.load(directory)
21 let cache = URL.temporaryDirectory.appending(path: UUID().uuidString)
22 defer { try? FileManager.default.removeItem(at: cache) }
23 let library = EditorialLibrary(bundled: catalog, bundledGallery: gallery, directory: cache)
24 await library.refreshIfNeeded()
25 check(library.edition?.content.lessons.map(\.id) == catalog.lessons.map(\.id),
26 "Production R2 returns the published curriculum to the native reader")
27 let reopened = EditorialLibrary(bundled: catalog, bundledGallery: gallery, directory: cache)
28 check(reopened.edition?.content.lessons.count == catalog.lessons.count,
29 "Production edition reopens from the native cache")
30 check(reopened.edition?.content.seasonal?.map(\.id) == catalog.seasonal?.map(\.id),
31 "Production seasonal content reopens from the native cache")
32 let quoteIDs = catalog.quotes?.map(\.id) ?? []
33 check(reopened.edition?.content.quotes?.prefix(quoteIDs.count).map(\.id) == quoteIDs,
34 "Production quotes reopen from the native cache in the published order")
35 print("PASS: production R2 edition downloaded, validated, and reopened from cache.")
36 }
37 }
38
39 /// Every row gets a single-colour symbol, built-in names carry no emoji, and old journals migrate.
40 @MainActor
41 static func glyphChecks(resources: URL) throws {
42 let catalog = try Catalog.load(from: resources.appending(path: "Catalog.json"))
43 let isEmoji: (String) -> Bool = { $0.contains(where: Glyph.isEmoji) }
44 check(!catalog.activities.contains(where: isEmoji) && !catalog.people.contains(where: isEmoji),
45 "Built-in activities and people have no emoji")
46 check(catalog.activities.contains("Deep work"), "Deep work reads without its emoji")
47 check(Glyph.plainName("💻 Deep work") == "Deep work" && Glyph.plainName("Walk 🚶") == "Walk",
48 "Emoji are stripped from either end of a name")
49 check(Glyph.plainName("🎉") == "🎉", "A name that is only an emoji is kept")
50 check(Glyph.plainName("C++ and Swift") == "C++ and Swift", "Ordinary text is untouched")
51 var symbols: [String] = []
52 symbols += catalog.sources.map { Glyph.symbol(name: $0, category: "app") }
53 symbols += catalog.activities.map { Glyph.symbol(name: $0, category: "activity") }
54 symbols += catalog.people.map { Glyph.symbol(name: $0, category: "person") }
55 symbols += catalog.library.flatMap { category in
56 category.tasks.map { Glyph.symbol(icon: $0.icon, name: $0.name, category: category.id) } }
57 symbols += catalog.habits.map { Glyph.symbol(icon: $0.icon, name: $0.name, category: "habit") }
58 symbols += catalog.challenges.map { Glyph.symbol(icon: $0.icon, name: $0.title, category: "challenge") }
59 symbols += catalog.lessons.flatMap { $0.pages.map { Glyph.symbol(icon: $0.emoji, name: $0.title) } }
60 symbols += catalog.challenges.flatMap { $0.opts.map { Glyph.symbol(icon: $0.e, name: $0.l) } }
61 let missing = Set(symbols.filter { !Glyph.exists($0) })
62 check(missing.isEmpty, "Every built-in row resolves to a real SF Symbol (missing: \(missing.sorted()))")
63 check(!symbols.contains(where: isEmoji), "No built-in row resolves to an emoji")
64 let lessonPages = catalog.lessons.flatMap(\.pages)
65 let unmapped = lessonPages.filter { Glyph.symbol(icon: $0.emoji, name: $0.title) == GlyphMap.fallback }
66 check(unmapped.count <= lessonPages.count / 20, "Lesson illustrations map to meaningful symbols (\(unmapped.count) fall back)")
67 for source in ["TikTok", "YouTube", "Reddit", "Slack", "Claude", "News"] {
68 check(Glyph.symbol(name: source, category: "app") == GlyphMap.names[source.lowercased()], "\(source) has its own glyph")
69 }
70 check(Glyph.symbol(name: "Practice violin", category: "activity") != GlyphMap.fallback,
71 "A typed activity finds a glyph from its words")
72 check(Glyph.exists(Glyph.symbol(name: "Zxqv", category: "activity")), "Unknown names fall back to a real symbol")
73 check(Glyph.symbol(icon: "drop.fill", name: "Anything") == "drop.fill", "A stored symbol name is kept")
74 check(Glyph.symbol(icon: "💧", name: "Anything") == Glyph.symbol(icon: "💧", name: "Other"),
75 "A stored emoji icon maps to a fixed symbol")
76
77 var journal = Journal()
78 let day = CalendarDay.key(.now)
79 journal.moments = [
80 Moment(source: "💻 Deep work", kind: "Activity", tags: [], value: 0.8, decision: .same, date: .now, day: day),
81 Moment(source: "🦄 My own thing", kind: "Feed", tags: [], value: 0.5, decision: .same, date: .now, day: day),
82 ]
83 journal.favoriteSources = ["💻 Deep work", "Deep work", "🦄 My own thing"]
84 let migrated = journal.droppingBuiltInEmoji()
85 check(migrated.moments.map(\.source) == ["Deep work", "🦄 My own thing"],
86 "Old built-in moments lose their emoji; names people typed stay as written")
87 check(migrated.favoriteSources == ["Deep work", "🦄 My own thing"], "Favourites migrate without duplicates")
88 }
89
90 /// The App Store prompt waits for five logged moments and is asked for once.
91 static func engagementChecks() {
92 var engagement = Engagement()
93 engagement.count = 4
94 check(!engagement.shouldRequestReview, "No rating prompt before five moments")
95 engagement.count = 5
96 check(engagement.shouldRequestReview, "Rating prompt is due after five moments")
97 engagement.requestedReview = true
98 check(!engagement.shouldRequestReview, "Rating prompt is never asked twice")
99 var rated = Engagement()
100 rated.count = 9
101 rated.actions.insert("review")
102 check(!rated.shouldRequestReview, "No rating prompt after someone rated from Settings")
103 }
104
105 /// Send to Inkspring builds a well-formed inkspring://new-idea link within Inkspring's limits.
106 static func inkspringLinkChecks() {
107 func query(_ url: URL?) -> [String: String] {
108 guard let url, let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems else { return [:] }
109 return Dictionary(items.map { ($0.name, $0.value ?? "") }, uniquingKeysWith: { first, _ in first })
110 }
111 let url = InkspringLink.newIdea(quote: "Small steps & big leaps = 1+1 #today?", author: "Maya Angelou")
112 check(url?.scheme == "inkspring" && url?.host == "new-idea", "Inkspring link uses inkspring://new-idea")
113 let raw = url?.absoluteString ?? ""
114 check(raw.contains("%2B") && raw.contains("%26") && raw.contains("%3D") && raw.contains("%23")
115 && !raw.contains("+") && !raw.contains(" "),
116 "Inkspring link percent-encodes plus, ampersand, equals, hash and spaces")
117 let fields = query(url)
118 check(fields["source"] == "glimmer", "Inkspring link names Glimmer as the source")
119 check(fields["text"] == "“Small steps & big leaps = 1+1 #today?”\n— Maya Angelou",
120 "Inkspring idea text is the quote and its attribution on its own line")
121 check(fields["title"] == "Small steps & big leaps = 1+1 #today?", "A short quote is its own idea title")
122 check(raw.contains("%0A"), "The line break before the attribution is kept as %0A")
123
124 let long = String(repeating: "Notice what nourishes you today. ", count: 120)
125 let longFields = query(InkspringLink.newIdea(quote: long, author: "Glimmer"))
126 check((longFields["text"]?.utf16.count ?? .max) <= InkspringLink.textLimit && longFields["text"]?.hasSuffix("…") == true,
127 "Inkspring idea text stays within 2,000 UTF-16 units and ends in an ellipsis")
128 let title = longFields["title"] ?? ""
129 check(title.utf16.count <= InkspringLink.shortTitleLimit && title.hasSuffix("…") && title.hasPrefix("Notice what nourishes"),
130 "A long quote's title is its opening words, cut at a word boundary")
131 check(!title.contains("\n"), "The idea title stays on one line")
132
133 let emoji = String(repeating: "🌱", count: 1_500)
134 let clipped = InkspringLink.clip(emoji, to: InkspringLink.textLimit)
135 check(clipped.utf16.count <= InkspringLink.textLimit && clipped.unicodeScalars.allSatisfy { $0 == "🌱" || $0 == "…" },
136 "Clipping never splits an emoji's surrogate pair")
137 check(InkspringLink.clip(String(repeating: "a", count: 500), to: InkspringLink.titleLimit).utf16.count <= InkspringLink.titleLimit,
138 "Titles stay within 140 UTF-16 units")
139 check(InkspringLink.newIdea(title: "Empty", text: " \n ") == nil, "Blank text builds no link")
140 check(query(InkspringLink.newIdea(quote: "Rest is part of the work.", author: "")).keys.sorted() == ["source", "text", "title"],
141 "A quote with no author still sends title, text and source")
142 print("PASS: Send to Inkspring link building, percent-encoding, attribution and length limits.")
143 }
144
145 /// The Mac support card returns weekly until every action is opened or the person picks Don't show again.
146 @MainActor
147 static func supportReminderChecks() {
148 #if os(macOS)
149 let suite = "glimmer.checks.\(UUID().uuidString)"
150 guard let defaults = UserDefaults(suiteName: suite) else { return check(false, "Support reminder defaults") }
151 defer { defaults.removePersistentDomain(forName: suite) }
152 let start = Date(timeIntervalSince1970: 1_800_000_000)
153 check(!GlimmerSupportReminder.claim(activity: 4, now: start, in: defaults), "Support card waits for five moments")
154 check(GlimmerSupportReminder.claim(activity: 5, now: start, in: defaults), "Support card shows after five moments")
155 check(!GlimmerSupportReminder.claim(activity: 9, now: start.addingTimeInterval(6 * 86_400), in: defaults),
156 "Support card waits a week before returning")
157 let nextWeek = start.addingTimeInterval(7 * 86_400)
158 for action in GlimmerSupportReminder.Action.allCases.dropLast() {
159 check(!GlimmerSupportReminder.record(action, in: defaults), "Opening \(action.rawValue) leaves others unticked")
160 }
161 check(GlimmerSupportReminder.claim(activity: 9, now: nextWeek, in: defaults),
162 "Support card returns while any checkbox is still empty")
163 check(GlimmerSupportReminder.record(.apps, in: defaults), "Opening the last action ticks every box")
164 check(!GlimmerSupportReminder.claim(activity: 9, now: nextWeek.addingTimeInterval(30 * 86_400), in: defaults),
165 "Support card stops once every action has been opened")
166 defaults.removeObject(forKey: GlimmerSupportReminder.actionsKey)
167 defaults.removeObject(forKey: GlimmerSupportReminder.presentedKey)
168 check(GlimmerSupportReminder.claim(activity: 9, now: start, in: defaults), "Later brings the card back")
169 GlimmerSupportReminder.dismissForever(in: defaults)
170 check(!GlimmerSupportReminder.claim(activity: 9, now: start.addingTimeInterval(60 * 86_400), in: defaults),
171 "Don't show again stops the card for good")
172 #endif
173 }
174
175 static func agentSkillChecks(native: URL) throws {
176 let home = URL.temporaryDirectory.appending(path: "skill-home-\(UUID().uuidString)")
177 defer { try? FileManager.default.removeItem(at: home) }
178 func text(_ version: String, name: String = "glimmer-mcp") -> String {
179 "---\nname: \(name)\nmetadata:\n version: \"\(version)\"\n---\nbody \(version)"
180 }
181 func skill(_ version: String = "1.2.0") -> AgentSkillInstaller {
182 AgentSkillInstaller(app: "Glimmer", skillID: "glimmer-mcp", instructions: Data(text(version).utf8), home: home)
183 }
184 try skill("1.1.0").install(.claudeCode)
185 check(skill().status(.claudeCode).state == .updateAvailable, "Agent skill offers an update for an older version")
186 try skill().install(.claudeCode)
187 check(skill().status(.claudeCode).state == .installed, "Agent skill updates to the bundled version")
188 try skill("1.10.0").install(.codex, replacing: true)
189 check(skill().status(.codex).state == .installed, "Agent skill treats a newer version as installed")
190 let gemini = skill().status(.gemini)
191 check(gemini.shared, "Codex and Gemini CLI share one agent skill copy")
192 let other = AgentSkillInstaller(app: "Other", skillID: "glimmer-mcp", instructions: Data(text("9.0.0", name: "other").utf8), home: home)
193 try other.install(.claudeCode, replacing: true)
194 check(skill().status(.claudeCode).state == .differentVersion, "Agent skill keeps a different skill unless replacing")
195 let bundled = try String(contentsOf: native.appending(path: "Glimmer/AgentSkill.md"), encoding: .utf8)
196 check(bundled.hasPrefix("---\nname: glimmer-mcp\n"), "Bundled agent skill is glimmer-mcp")
197 check(AgentSkillInstaller.frontMatter(Data(bundled.utf8)).version != nil, "Bundled agent skill has a version")
198 }
199
200 @MainActor
201 static func editorialRefreshChecks(resources: URL) async throws {
202 let folder = URL.temporaryDirectory.appending(path: UUID().uuidString)
203 defer { try? FileManager.default.removeItem(at: folder) }
204 let catalogURL = resources.appending(path: "Catalog.json")
205 let baseline = try Catalog.load(from: catalogURL)
206 let media = try GalleryCatalog.load(resources.appending(path: "Gallery/Gallery.json"))
207 let library = EditorialLibrary(bundled: baseline, bundledGallery: media, directory: folder)
208 var content = try JSONSerialization.jsonObject(with: Data(contentsOf: catalogURL)) as! [String: Any]
209 var lessons = content["lessons"] as! [[String: Any]]
210 lessons[0]["title"] = "Remote title without a new binary"
211 content["lessons"] = lessons
212 let gallery = try JSONSerialization.jsonObject(with: JSONEncoder().encode(media))
213 let document: [String: Any] = ["schemaVersion": 1, "content": content, "gallery": gallery]
214 let bytes = try JSONSerialization.data(withJSONObject: document)
215 let now = Date()
216 let url = EditorialLibrary.endpoint
217 let ok = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil,
218 headerFields: ["Content-Type": "application/json", "ETag": "\"edition-a\""])!
219 check(library.edition == nil, "No network is needed to open the bundled catalog")
220 await library.refreshIfNeeded(now: now) { request, _ in
221 check(request.url == url, "The app reads only the public editorial catalog")
222 return (bytes, ok)
223 }
224 check(library.edition?.content.lessons.first?.title == lessons[0]["title"] as? String,
225 "New editorial text is available in the same app session")
226 check(library.edition?.gallery == media, "Gallery references ship with the editorial edition")
227 let reopened = EditorialLibrary(bundled: baseline, bundledGallery: media, directory: folder)
228 check(reopened.edition?.content.lessons.first?.title == lessons[0]["title"] as? String,
229 "The offline app opens the last accepted edition")
230 let unchanged = HTTPURLResponse(url: url, statusCode: 304, httpVersion: nil, headerFields: nil)!
231 await reopened.refreshIfNeeded(now: now) { request, _ in
232 check(request.value(forHTTPHeaderField: "If-None-Match") == "\"edition-a\"", "Cache revalidation uses the saved ETag")
233 return (Data(), unchanged)
234 }
235 var bad = document
236 lessons[0]["slug"] = "new-id-would-break-progress"
237 content["lessons"] = lessons
238 bad["content"] = content
239 let invalid = try JSONSerialization.data(withJSONObject: bad)
240 await reopened.refreshIfNeeded(now: now.addingTimeInterval(1_000)) { _, _ in (invalid, ok) }
241 await reopened.refreshIfNeeded(now: now.addingTimeInterval(2_000)) { _, _ in throw URLError(.notConnectedToInternet) }
242 check(reopened.edition?.content.lessons.first?.id == baseline.lessons[0].id,
243 "Edits that break journal identities and outages preserve the last valid edition")
244 print("PASS: remote content updates, media references, ETag, offline relaunch, and stable journal identities.")
245 }
246
247 @MainActor
248 static func galleryRefreshChecks(_ bundled: GalleryCatalog, posterDirectory: URL) async throws {
249 let folder = URL.temporaryDirectory.appending(path: UUID().uuidString)
250 defer { try? FileManager.default.removeItem(at: folder) }
251 let remote = GalleryPlate(id: "new-summer-scene", description: "Sunlit reeds beside the river.", aspectRatio: 2.4, wholeSubject: false,
252 video: "summer/reeds-abc123.mp4", poster: "summer/reeds-ef4321.jpg")
253 let expanded = GalleryCatalog(schemaVersion: 1, plates: [remote] + bundled.plates)
254 let library = GalleryLibrary(bundled: bundled, directory: folder)
255 let now = Date()
256 let bytes = try JSONEncoder().encode(expanded)
257 let ok = HTTPURLResponse(url: GalleryCatalog.endpoint, statusCode: 200, httpVersion: nil, headerFields: ["ETag":"\"revision-1\""])!
258 check(library.catalog == bundled, "First launch works from bundled posters")
259 await library.refreshIfNeeded(now: now) { request, _ in
260 check(request.url == GalleryCatalog.endpoint && request.value(forHTTPHeaderField: "If-None-Match") == nil, "First gallery request goes to canonical index")
261 return (bytes, ok)
262 }
263 check(library.catalog.plates.first?.id == remote.id && library.catalog.plates.count == bundled.plates.count + 1, "New remote media appears without an app build")
264 let restarted = GalleryLibrary(bundled: bundled, directory: folder)
265 check(restarted.catalog == expanded, "Offline restart uses the last validated snapshot")
266 await restarted.refreshIfNeeded(now: now.addingTimeInterval(60)) { _,_ in preconditionFailure("Fresh catalog was re-requested") }
267 let later = now.addingTimeInterval(7 * 3600)
268 await restarted.refreshIfNeeded(now: later) { request, _ in
269 check(request.value(forHTTPHeaderField: "If-None-Match") == "\"revision-1\"", "Refresh validates the stored ETag")
270 return (Data(), HTTPURLResponse(url: GalleryCatalog.endpoint, statusCode: 304, httpVersion: nil, headerFields: nil)!)
271 }
272 let after304 = GalleryLibrary(bundled: bundled, directory: folder)
273 check(after304.catalog == expanded, "304 preserves the complete cached catalog")
274 await after304.refreshIfNeeded(now: later.addingTimeInterval(7 * 3600)) { _,_ in (Data("{}".utf8), ok) }
275 check(after304.catalog == expanded, "Invalid responses preserve the working catalog")
276 await after304.refreshIfNeeded(now: later.addingTimeInterval(8 * 3600)) { _,_ in throw URLError(.notConnectedToInternet) }
277 check(after304.catalog == expanded, "Disconnected devices retain their remote collection")
278 let animal = GalleryPlate(id: "full-subject", description: "A rabbit in a meadow.", aspectRatio: 1.0,
279 wholeSubject: true, video: "new/rabbit.mp4", poster: "new/rabbit.jpg")
280 let wildlife = GalleryCatalog(schemaVersion: 1, plates: [animal])
281 check(wildlife.pick(slot: 0, date: now, aspect: 8, featured: true)?.id == animal.id, "A new themed collection still presents a full subject in a wide slot")
282 let ids = Set(bundled.plates.map(\.id))
283 let missing = GalleryPlate(id: "unseen", description: "New image", aspectRatio: 1, wholeSubject: nil, video: nil, poster: nil)
284 check((try? GalleryCatalog(schemaVersion: 1, plates: [missing]).validate(bundledIDs: ids)) == nil, "New IDs require an available poster")
285 check((try? GalleryCatalog(schemaVersion: 1, plates: [remote, remote]).validate(bundledIDs: ids)) == nil, "Duplicate IDs rejected")
286 for bad in ["https://invalid.example/clip.mp4", "//invalid.example/clip.mp4", "../clip.mp4", "v1/../clip.mp4",
287 "v1/%2e%2e/x.mp4", "v1/%2Ffilm.mp4", "v1/file.mp4?secret", "C:\\file.mp4", "/root.mp4", "v1/file.mov"] {
288 check(GalleryCatalog.asset(bad, extensions: ["mp4"]) == nil, "Invalid remote path rejected: \(bad)")
289 }
290 let address = GalleryCatalog.endpoint.deletingLastPathComponent().appending(path: "summer/reeds-abc123.mp4")
291 check(remote.filmURL == address, "New subdirectories resolve under the canonical base")
292 let posterFolder = folder.appending(path: "posters")
293 let original = try Data(contentsOf: posterDirectory.appending(path: bundled.plates[0].id + ".jpg"))
294 let posterURL = remote.posterURL!
295 let onlineCache = GalleryPosters(directory: posterFolder) { request, limit in
296 check(request.url == posterURL && limit >= original.count, "Only the remote plate's JPEG is requested")
297 return (original, HTTPURLResponse(url: posterURL, statusCode: 200, httpVersion: nil, headerFields: nil)!)
298 }
299 let fetched = await onlineCache.image(for: posterURL)
300 check(fetched != nil, "A previously unknown remote poster decodes as a JPEG")
301 let offlineCache = GalleryPosters(directory: posterFolder) { _,_ in throw URLError(.notConnectedToInternet) }
302 let cached = await offlineCache.image(for: posterURL)
303 check(cached?.width == fetched?.width, "New remote posters remain available across an offline relaunch")
304 print("PASS: gallery discovery, conditional refresh, atomic cache, offline fallback, new remote posters and path validation.")
305 }
306
307 static func checkJourneyStages(_ catalog: Catalog) {
308 check(JourneyStage.level(days: 0) == 1 && JourneyStage.level(days: 13) == 1 && JourneyStage.level(days: 14) == 2
309 && JourneyStage.level(days: 30) == 3 && JourneyStage.level(days: 60) == 4 && JourneyStage.level(days: 500) == 5,
310 "Journey stages follow the reader rank thresholds")
311 let challengeStages = catalog.challenges.map(\.stage)
312 let practiceStages = catalog.practiceTopics.flatMap(\.exercises).map(\.stage)
313 check(Set(challengeStages) == Set(1...5) && Set(practiceStages) == Set(1...5), "Every stage has challenges and practices")
314 check(challengeStages == challengeStages.sorted(), "Challenges are listed from first stage to last")
315 let coins = (1...5).map { stage in catalog.challenges.filter { $0.stage == stage }.map(\.coins).max() ?? 0 }
316 check(coins == coins.sorted() && coins[4] <= 40, "Challenge rewards stay modest so small wins never look second-class")
317 for topic in catalog.practiceTopics {
318 check(topic.exercises.first?.stage == 1, "Topic \(topic.id) starts with an opening practice")
319 }
320 let start = PracticeDate.parse("2026-11-23")!
321 for level in 1...5 {
322 let days = (0..<120).compactMap { PracticeDate.calendar.date(byAdding: .day, value: $0, to: start) }
323 let picks = days.compactMap { catalog.dailyPractice(on: $0, level: level)?.practice }
324 check(picks.count == days.count && picks.allSatisfy { $0.stage <= level }, "Daily practice stays open at stage \(level)")
325 if level > 1 {
326 check(picks.filter { $0.stage >= level - 1 }.count * 2 > picks.count, "Daily practice favors stage \(level) content")
327 }
328 let reflections = days.compactMap { catalog.dailyReflection(on: $0, level: level) }
329 check(reflections.allSatisfy { $0.stage <= level }, "Daily reflection stays open at stage \(level)")
330 }
331 var fresh = Journal()
332 check(catalog.nextChallenge(for: fresh, level: 1)?.id == "pad", "A new journal starts with the first tiny win")
333 for challenge in catalog.challenges where challenge.stage == 1 { fresh.challenges[challenge.id] = ChallengeRecord(choice: "Done", date: start) }
334 check(catalog.nextChallenge(for: fresh, level: 1) == nil && catalog.nextChallenge(for: fresh, level: 2)?.stage == 2, "Finished stages hand off to the next open stage")
335 check(catalog.nextChallenge(for: Journal(), level: 3)?.stage == 3, "The next challenge meets the person at their stage")
336 var tired = Journal()
337 for offset in 0..<70 { tired.readerDays = (tired.readerDays ?? []).union([PracticeDate.key(PracticeDate.calendar.date(byAdding: .day, value: -offset, to: start)!)]) }
338 check(tired.journeyLevel(asOf: start) == 4 && tired.guidanceLevel(asOf: start) == 4, "Seventy active days reach the fourth stage")
339 tired.energy[CalendarDay.key(start)] = EnergyCheck(level: "low", value: 0.25)
340 check(tired.guidanceLevel(asOf: start) == 2 && tired.journeyLevel(asOf: start) == 4, "A low-energy day brings suggestions back to gentle ground without losing progress")
341 check(catalog.suggestions(level: 4, goals: ["rest"]).contains { suggestion in
342 catalog.practiceTopics.flatMap(\.exercises).contains { $0.suggestion == suggestion && $0.stage >= 3 } }, "Coach suggestions include practices from the person's stage")
343 }
344
345 static func checkReaderRanks(catalog: Catalog) throws {
346 let day = PracticeDate.parse("2025-01-01")!
347 func date(_ offset: Int) -> Date { PracticeDate.calendar.date(byAdding: .day, value: offset, to: day)! }
348 let cutoff = date(200)
349 var reader = Journal()
350 reader.started = date(-1_000)
351 reader.award(40, key: "welcome")
352 reader.lessons["retired-lesson"] = LessonRecord(completed: true)
353 for lesson in catalog.lessons { reader.lessons[lesson.id] = LessonRecord(completed: true) }
354 func progress(_ journal: Journal) -> ReaderProgress { ReaderProgress(journal: journal, catalog: catalog, asOf: cutoff) }
355 let legacy = try JSONDecoder().decode(Journal.self, from: JSONEncoder().encode(reader))
356 check(progress(legacy).completed == 90 && progress(legacy).days == 0 && progress(legacy).rank == .fledgling,
357 "Undated legacy lessons count as lessons only; rewards and account age earn no practice days")
358 let boundaries: [Int: ReaderRank] = [0:.fledgling, 13:.fledgling, 14:.seeker, 29:.seeker, 30:.scholar,
359 59:.scholar, 60:.sage, 89:.sage, 90:.guru]
360 for count in 0...90 {
361 if let expected = boundaries[count] { check(progress(reader).rank == expected, "Rank after \(count) distinct days, including days apart") }
362 if count < 90 { reader.moods[PracticeDate.key(date(2 * count))] = 3 }
363 }
364 // Guru stays tied to the first 90 lessons, so the Deep Path never moves the goal.
365 let deepPath = catalog.lessons.last!
366 reader.lessons[deepPath.id] = nil
367 check(progress(reader).rank == .guru, "Unread Deep Path lessons don't hold back Guru")
368 let last = catalog.lessons.first { $0.number == ReaderProgress.curriculumLength }!
369 reader.lessons[last.id] = nil
370 check(progress(reader).rank == .sage && progress(reader).remaining(until: .guru) == "1 more lesson to unlock Guru.", "Guru checks both requirements")
371 reader.completeLesson(last, on: date(178))
372 check(progress(reader).days == 90 && progress(reader).rank == .guru && reader.readerDays == [PracticeDate.key(date(178))], "Completing the final lesson on an existing practice day unlocks Guru")
373 var mixed = Journal()
374 let key = PracticeDate.key(day)
375 mixed.completions[key] = ["task"]
376 mixed.completions[PracticeDate.key(date(5))] = []
377 mixed.moments = [Moment(source: "Walking", kind: "Activity", tags: [], value: 0.5, decision: .same, date: day, day: key)]
378 mixed.energy[key] = EnergyCheck(level: "Good", value: 0.6)
379 mixed.habits["read"] = [key, PracticeDate.key(date(2))]
380 mixed.challenges["one"] = ChallengeRecord(choice: "Try", date: day)
381 mixed.cleaningLast["desk"] = key
382 mixed.experiment = Experiment(suggestion: Suggestion(type: "Try", title: "read", sub: ""), start: day)
383 mixed.experiment?.checkins[key] = .held
384 mixed.moods["2025-02-31"] = 2
385 mixed.moods[PracticeDate.key(date(201))] = 2
386 mixed.preserveReaderDays(asOf: cutoff)
387 check(mixed.readerDays == [key, PracticeDate.key(date(2))], "Practice sources deduplicate across days and discard impossible or future keys")
388 mixed.habits.removeAll()
389 check(progress(mixed).days == 2, "Earned practice dates survive housekeeping of detail records")
390 let first = UUID(), second = UUID()
391 var a = try JournalReplica(seed: mixed, device: first)
392 var b = a
393 var phone = mixed
394 phone.readerDays?.insert(PracticeDate.key(date(3)))
395 try a.observe(from: mixed, to: phone, device: first)
396 var mac = mixed
397 mac.readerDays?.insert(PracticeDate.key(date(4)))
398 try b.observe(from: mixed, to: mac, device: second)
399 a.merge(b)
400 let data = try JSONEncoder().encode(a)
401 let replica = try JSONDecoder().decode(JournalReplica.self, from: data)
402 let merged = try replica.materialize(keepingEngagement: .init())
403 check(progress(merged).days == 4, "Independent practice dates survive replica merging and snapshot persistence")
404 struct LegacyWire: Decodable { let entries: [JournalReplica.Key: JournalReplica.Entry] }
405 let wire = try JSONDecoder().decode(LegacyWire.self, from: data)
406 check(wire.entries.keys.allSatisfy { $0.path.first != "readerDays" }, "Older replicas can decode all familiar journal fields")
407 print("PASS: Fledgling through Guru, dated and undated journal migration, missed days, deduplication, and offline date merging.")
408 }
409
410 @MainActor
411 static func core() throws {
412 try checkPersonalTodos()
413 try checkToolkit()
414 checkCoachPrompts()
415 checkCheckOffRewards()
416 let root = URL(fileURLWithPath: CommandLine.arguments[1], isDirectory: true)
417 let resources = root.appending(path: "LibraryContent")
418 let catalogURL = resources.appending(path: "Catalog.json")
419 let catalog = try Catalog.load(from: catalogURL)
420 try checkSeasonal(catalog)
421 checkQuotes(catalog)
422 check(catalog.onboarding.count == 14, "Original onboarding")
423 check(catalog.lessons.count >= 120 && catalog.lessons.map(\.number) == Array(1...catalog.lessons.count)
424 && catalog.lessons.allSatisfy { !$0.pages.isEmpty && $0.pages.last?.kind == "takeaway" && $0.pages.last?.tryToday != nil }, "Complete lesson catalog with the Deep Path")
425 check(Array(catalog.challenges.prefix(4).map(\.id)) == ["pad", "patch", "sweep", "coffee"] && catalog.challenges.allSatisfy { !$0.teach.isEmpty && $0.opts.count >= 2 }, "Original challenges first, every challenge complete")
426 checkJourneyStages(catalog)
427 let practices = catalog.practiceTopics.flatMap(\.exercises)
428 check(practices.count == Set(practices.map(\.id)).count && practices.count >= 8, "Distinct life coaching exercises")
429 let referenceDay = PracticeDate.parse("2026-11-23")!
430 let reflectionIDs = Set((0..<(12 * (catalog.reflectionTopic?.exercises.count ?? 0))).compactMap { offset in
431 PracticeDate.calendar.date(byAdding: .day, value: offset, to: referenceDay)
432 .flatMap { catalog.dailyReflection(on: $0)?.id }
433 })
434 check(reflectionIDs == Set(catalog.reflectionTopic?.exercises.map(\.id) ?? []) && reflectionIDs.contains("would-you-do-it-offline"), "Daily reflections cover every practice, including the online fads reflection")
435 try checkReaderRanks(catalog: catalog)
436 let goalStep = catalog.onboarding.first { $0.key == "primary_goal" }!
437 let goalIDs = goalStep.options!.map(\.v)
438 let allGoals = goalIDs.reduce([String]()) { goalStep.toggling($1, in: $0) }
439 check(allGoals == goalIDs && goalStep.toggling(goalIDs[0], in: allGoals) == Array(goalIDs.dropFirst()), "Any number of goals can be selected and deselected")
440 let mixed = catalog.startingSuggestions(["primary_goal": allGoals])
441 for topic in catalog.practiceTopics where goalIDs.contains(topic.id) {
442 check(mixed.contains(topic.exercises[0].suggestion), "Personalization includes selected topics")
443 }
444 for goal in ["work_growth", "learn_build"] {
445 let suggestions = catalog.startingSuggestions(["primary_goal": [goal]])
446 check(suggestions.first == catalog.practiceTopics.first(where: { $0.id == goal })?.exercises.first?.suggestion, "Goal selects its practice exercises")
447 }
448 let directory = resources.appending(path: "Gallery")
449 let gallery = try GalleryCatalog.load(directory.appending(path: "Gallery.json"))
450 let plates = gallery.plates
451 let files = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)
452 check(files.allSatisfy { ["json","jpg"].contains($0.pathExtension.lowercased()) }, "Only posters and their manifest ship in the gallery")
453 let videos = plates.compactMap(\.video)
454 check(!videos.isEmpty && Set(videos).count == videos.count, "Different remote films are available for the daily feature")
455 try gallery.validate(bundledIDs: Set(plates.map(\.id)))
456 check(!plates.isEmpty && Set(plates.map(\.id)).count == plates.count, "Gallery covers the full rotation")
457 check(plates.allSatisfy { !$0.description.isEmpty && $0.aspectRatio > 0 }, "Gallery includes descriptions and proportions")
458 for plate in plates {
459 let url = directory.appending(path: plate.id + ".jpg")
460 guard let image = CGImageSourceCreateWithURL(url as CFURL, nil),
461 let poster = CGImageSourceCreateImageAtIndex(image, 0, nil)
462 else { fatalError("Missing gallery poster: \(plate.id)") }
463 check(abs(Double(poster.width) / Double(poster.height) - plate.aspectRatio) < 0.001, "Catalog uses actual image dimensions")
464 if let video = plate.video {
465 check(plate.filmURL == GalleryCatalog.endpoint.deletingLastPathComponent().appending(path: video), "Film URL uses the configured location")
466 } else {
467 check(plate.filmURL == nil, "Still photographs never request video")
468 }
469 }
470 let veryWide = (0..<plates.count).compactMap { gallery.pick(slot: $0, date: referenceDay, aspect: 8) }
471 check(!veryWide.isEmpty && veryWide.allSatisfy { $0.wholeSubject != true }, "Narrow strips avoid cropping people and animals")
472 let followingDay = Calendar.current.date(byAdding: .day, value: 1, to: referenceDay)!
473 for aspect in [1.0, 1.5, 2.5, 6.0] {
474 let first = gallery.pick(slot: 1, date: referenceDay, aspect: aspect)
475 let second = gallery.pick(slot: 1, date: followingDay, aspect: aspect)
476 check(first != nil && first?.id != second?.id, "Artwork rotates across days")
477 check(second?.id == gallery.pick(slot: 2, date: referenceDay, aspect: aspect)?.id,
478 "Adjacent cards show distinct stable choices")
479 }
480
481 for aspect in [1.0, 1.5, 2.5, 6.0] {
482 let weekly = (0..<7).compactMap { index -> GalleryPlate? in
483 let date = Calendar.current.date(byAdding: .day, value: index, to: referenceDay)!
484 return gallery.pick(slot: 0, date: date, aspect: aspect, featured: true)
485 }
486 check(weekly.count == 7 && weekly.allSatisfy { $0.video != nil }, "Today offers a real motion scene on every day")
487 check(Set(weekly.map(\.id)).count > 1, "Featured motion rotates between distinct scenes")
488 let regular = (0..<plates.count).compactMap { gallery.pick(slot: $0, date: referenceDay, aspect: aspect) }
489 check(regular.filter { $0.video == nil }.count > regular.count / 2, "Regular gallery slots are primarily still photographs")
490 }
491
492 let now = Date()
493 let calendar = Calendar.current
494 let tomorrow = calendar.date(byAdding: .day, value: 1, to: now)!
495 let yesterday = calendar.date(byAdding: .day, value: -1, to: now)!
496 let today = CalendarDay.key(now)
497 let testDirectory = URL.temporaryDirectory.appending(path: "glimmer-core-" + UUID().uuidString)
498 let journalURL = testDirectory.appending(path: "journal.json")
499 defer { try? FileManager.default.removeItem(at: testDirectory) }
500 let store = JournalStore(url: journalURL, catalogURL: catalogURL)
501 store.start(name: " Sample ")
502 check(store.journal.name == "Sample" && store.journal.coins == 40, "Onboarding persisted")
503 let task = store.journal.tasks[0]
504 check(task.occurs(on: now) && task.occurs(on: tomorrow) && !task.occurs(on: yesterday), "Daily task recurrence")
505 var alternate = task
506 alternate.every = 2
507 check(!alternate.occurs(on: tomorrow), "Repeat interval")
508 alternate.repeats = false
509 check(!alternate.occurs(on: tomorrow), "One-time task recurrence")
510 var weekly = task
511 weekly.cadence = .weekly
512 weekly.weekdays = [calendar.component(.weekday, from: tomorrow)]
513 check(!weekly.occurs(on: now) && weekly.occurs(on: tomorrow), "Selected weekdays")
514
515 store.change { $0.toggleTask(task, on: now) }
516 check(store.journal.coins == 45 && store.todayCompletion.contains(task.id), "Task reward")
517 store.change { $0.toggleTask(task, on: now) }
518 check(store.journal.coins == 40 && !store.todayCompletion.contains(task.id), "Undo removes reward")
519 let log = Moment(source: "Sample", kind: "Feed", tags: ["Learning"], value: 0.8,
520 decision: .more, date: now, day: today)
521 let drain = Moment(source: "Other", kind: "Feed", tags: [], value: 0,
522 decision: .less, date: now, day: today)
523 store.change {
524 $0.record(log)
525 $0.record(log)
526 $0.record(drain)
527 $0.recordEnergy(.init(level: "mid", value: 0.5), on: now)
528 $0.recordEnergy(.init(level: "high", value: 0.8), on: now)
529 }
530 check(store.journal.coins == 55 && store.journal.moments.count == 2, "Reward only once per day")
531 check(store.journal.engagement.count == 2 && !store.journal.engagement.shouldRequestReview, "Successful saves count once")
532 let summary = ReflectionSummary(store.journal.moments, day: now, days: 14)
533 check(summary.alignment == 50 && summary.best.first?.name == "Sample" && summary.rough.first?.name == "Other",
534 "Grounded insight scores and groups")
535 check(ReflectionSummary([], day: now, days: 7).alignment == nil, "No demo values in an empty journal")
536
537 let flat = (0..<5).map { offset in
538 var item = log
539 item.date = calendar.date(byAdding: .day, value: -offset, to: now)!
540 item.day = CalendarDay.key(item.date)
541 return item
542 }
543 let steady = ReflectionSummary(flat, day: now, days: 14)
544 check(!summary.hasHistory, "One day's entries cannot form a history")
545 check(steady.hasHistory, "Enough logs form a history even when every rating is the same")
546
547 let lesson = catalog.lessons[0]
548 check(!store.journal.lessonIsOpen(2, on: now) && store.journal.lessonIsOpen(2, on: tomorrow), "Daily unlock")
549 store.change {
550 $0.completeLesson(lesson, on: now)
551 $0.completeLesson(lesson, on: now)
552 $0.completeChallenge(catalog.challenges[0], choice: "Sample", on: now)
553 $0.completeChallenge(catalog.challenges[0], choice: "Sample", on: now)
554 }
555 check(store.journal.coins == 90 && store.journal.coffeeUnlocked, "One-time lesson and challenge rewards")
556 let suggestion = catalog.startingSuggestions(["distraction": ["short_video"]])[0]
557 store.startOrQueue(suggestion)
558 store.change { $0.checkIn(.held, on: now); $0.checkIn(.slip, on: now) }
559 check(store.journal.experiment?.checkins.count == 1, "One experiment check-in per calendar day")
560 for offset in 1...6 {
561 let date = calendar.date(byAdding: .day, value: offset, to: now)!
562 store.change { $0.checkIn(.held, on: date) }
563 }
564 check(store.journal.experiment?.readyToReview == true, "Experiment review gate")
565 store.change { $0.reviewExperiment(.keep, on: now); $0.reviewExperiment(.keep, on: now) }
566 check(store.journal.experiment == nil && store.journal.history.count == 1 && store.journal.coins == 150, "Experiment reward")
567 var engagement = Engagement(count: 5)
568 check(engagement.shouldRequestReview, "Review becomes eligible at milestone")
569 engagement.actions.insert("review")
570 check(!engagement.shouldRequestReview, "Manual review link suppresses automatic request")
571 engagement.actions.removeAll()
572 engagement.requestedReview = true
573 check(!engagement.shouldRequestReview, "Automatic review only once")
574
575 let relaunched = JournalStore(url: journalURL, catalogURL: catalogURL)
576 check(relaunched.journal.moments.count == 2 && relaunched.journal.coins == 150, "Relaunch persistence")
577 let exportURL = testDirectory.appending(path: "export.json")
578 try store.export().write(to: exportURL)
579 let restored = try relaunched.readBackup(exportURL)
580 check(restored.moments == relaunched.journal.moments && restored.lessons[lesson.id]?.completed == true, "Backup round trip")
581 try Data("broken".utf8).write(to: journalURL)
582 let broken = JournalStore(url: journalURL, catalogURL: catalogURL)
583 check(broken.loadError != nil && !broken.change { $0.name = "Overwrite" }, "Corrupt file is preserved")
584 try checkSync(in: testDirectory, catalog: catalog, now: now, tomorrow: tomorrow)
585 try checkAgentAccess(in: testDirectory, catalog: catalog, catalogURL: catalogURL)
586 print("PASS: catalog, recurring tasks, rewards, insight math, unlocks, experiment review, review eligibility, persistence, backup, sync and agent access.")
587 }
588
589 @MainActor
590 private static func checkSeasonal(_ catalog: Catalog) throws {
591 let season = catalog.seasonal!.first!
592 let list = season.checklists[0]
593 let november = PracticeDate.parse("2026-11-15")!
594 let january = PracticeDate.parse("2027-01-07")!
595 let later = PracticeDate.parse("2027-01-08")!
596 let nextSeason = PracticeDate.parse("2027-11-15")!
597 let key = season.progressKey(for: list, on: november)
598 check(season.isFeatured(on: november) && season.isFeatured(on: january) && !season.isFeatured(on: later),
599 "Seasonal promotion starts and ends on the local calendar dates across New Year")
600 let nextDay = PracticeDate.parse("2026-11-16")!
601 check(season.recommendation(on: november)?.item.id == list.items.first?.id
602 && season.recommendation(on: nextDay)?.item.id == list.items.dropFirst().first?.id
603 && season.recommendation(on: january) != nil
604 && season.recommendation(on: later) == nil,
605 "Today offers a single rotating checklist action inside the seasonal window")
606 check(season.progressKey(for: list, on: january) == key && season.progressKey(for: list, on: later) == key
607 && season.progressKey(for: list, on: nextSeason) != key, "A holiday checklist persists through New Year")
608 check(Set(season.maintenance).isSubset(of: Set((catalog.cleaning.maintenance ?? []).map(\.id))),
609 "Seasonal upkeep references the same chores as Cleaning & maintenance")
610 let phone = UUID(), mac = UUID()
611 let empty = Journal()
612 var phoneJournal = empty
613 phoneJournal.toggleSeasonalCheck(list.items[0].id, in: key)
614 var macJournal = empty
615 macJournal.toggleSeasonalCheck(list.items[1].id, in: key)
616 let saved = try JournalStore.decode(JSONEncoder().encode(phoneJournal))
617 check(saved.seasonalChecks == phoneJournal.seasonalChecks, "Checklist progress survives reopening a saved journal")
618 var phoneCopy = try JournalReplica(seed: phoneJournal, device: phone)
619 let macCopy = try JournalReplica(seed: macJournal, device: mac)
620 phoneCopy.merge(macCopy)
621 let wire = try JSONEncoder().encode(phoneCopy)
622 let merged = try JSONDecoder().decode(JournalReplica.self, from: wire).materialize(keepingEngagement: .init())
623 check(merged.seasonalChecks?[key] == Set(list.items.prefix(2).map(\.id)),
624 "Independent devices preserve both checked items")
625 var previousWire = try JSONSerialization.jsonObject(with: wire) as! [String: Any]
626 previousWire.removeValue(forKey: "seasonalEntries")
627 let oldReader = try JSONDecoder().decode(JournalReplica.self, from: JSONSerialization.data(withJSONObject: previousWire))
628 let oldJournal = try oldReader.materialize(keepingEngagement: .init())
629 check(oldJournal.seasonalChecks == nil, "Older replicas can read the original journal fields")
630 }
631
632 private static func checkQuotes(_ catalog: Catalog) {
633 let quotes = catalog.quotes ?? []
634 let start = PracticeDate.parse("2026-11-23")!
635 check(quotes.count >= 180 && Set(quotes.map(\.id)).count == quotes.count
636 && Set(quotes.map(\.text)).count == quotes.count, "The launch rotation contains 180 distinct quotes")
637 check(quotes.allSatisfy { !$0.text.contains("://") && !$0.author.contains("://") },
638 "Display quotes contain text and attribution without URLs")
639 let calendar = PracticeDate.calendar
640 let scheduled = (0..<quotes.count).compactMap {
641 calendar.date(byAdding: .day, value: $0, to: start).flatMap { DailyQuote.quote(on: $0, from: quotes)?.id }
642 }
643 check(scheduled == quotes.map(\.id), "One quote advances per local calendar day in catalog order")
644 let cycleEnd = calendar.date(byAdding: .day, value: quotes.count, to: start)!
645 check(DailyQuote.quote(on: cycleEnd, from: quotes)?.id == quotes.first?.id,
646 "Quote rotation starts over only after every entry")
647 }
648
649 private static func checkCoachPrompts() {
650 let texts = CoachPrompts.pool.map(\.text)
651 check(Set(texts).count == texts.count && texts.count >= 40, "Coach has at least 40 unique suggested prompts")
652 // Spelled out so the banned label never appears in source or copy.
653 let banned = [["a", "d", "h", "d"].joined(), "attention journal"]
654 check(!texts.contains { text in banned.contains { text.lowercased().contains($0) } }, "Coach prompts avoid banned wording")
655 check(CoachPrompts.fixed.allSatisfy { CoachPrompts.pool.contains($0) }, "The fixed test prompts are in the pool")
656 check(CoachPrompts.pool.allSatisfy { CoachPrompts.category(for: $0.text) == $0.category },
657 "Every pooled prompt routes to its own category in the practice guide")
658 let typed: [(String, CoachPrompt.Category)] = [
659 ("I'm so tired today", .rest), ("Can you suggest a lesson?", .read), ("I feel stuck at work", .kindness),
660 ("I want some quiet", .stillness), ("Help me plan my morning", .focus), ("Any pattern in my moments?", .reflect),
661 ]
662 check(typed.allSatisfy { CoachPrompts.category(for: $0.0) == $0.1 }, "Typed questions route to a sensible guide category")
663 var previous = Set<String>()
664 var overlaps = 0, mixed = true
665 for _ in 0..<500 {
666 let set = CoachPrompts.draw(excluding: previous)
667 if set.count != 3 || Set(set.map(\.category)).count != 3 { mixed = false }
668 if !previous.isDisjoint(with: set.map(\.text)) { overlaps += 1 }
669 previous = Set(set.map(\.text))
670 }
671 check(mixed && overlaps == 0, "Coach shows three prompts from three categories with no repeat from the last set")
672 }
673
674 private static func checkCheckOffRewards() {
675 var journal = Journal()
676 let day = Date(timeIntervalSince1970: 1_790_000_000)
677 let before = journal.coins
678 journal.toggleHabit("water", on: day)
679 let afterHabit = journal.coins
680 journal.toggleHabit("water", on: day)
681 check(afterHabit > before && journal.coins == before && journal.habits["water"]?.isEmpty != false,
682 "Checking off a habit earns coins once; unchecking takes them back")
683 let todo = PersonalTodo(title: "Call the bank")
684 journal.personalTodos = [todo]
685 let found = journal.setPersonalTodo(todo.id, done: true)
686 let afterTodo = journal.coins
687 _ = journal.setPersonalTodo(todo.id, done: true)
688 let again = journal.coins
689 _ = journal.setPersonalTodo(todo.id, done: false)
690 check(found && afterTodo > before && again == afterTodo && journal.coins == before && !journal.setPersonalTodo(UUID(), done: true),
691 "Finishing a personal to-do earns coins once; reopening takes them back")
692 }
693
694 private static func checkToolkit() throws {
695 // Steps and estimates: model, validation, sync and old-peer safety.
696 let todo = PersonalTodo(title: "Write the quarterly report", dueDay: PracticeDate.key(.now))
697 var journal = Journal()
698 journal.personalTodos = [todo]
699 journal.replaceSteps(for: todo.id, with: ["Open a blank page", "List three points", " ", "Write it"])
700 let first = journal.steps(for: todo.id)
701 check(first.map(\.title) == ["Open a blank page", "List three points", "Write it"], "Breakdowns drop blank steps and keep order")
702 journal.setStepDone(first[0].id, done: true)
703 journal.replaceSteps(for: todo.id, parent: first[1].id, with: ["Point one", "Point two"])
704 check(journal.flatSteps(for: todo.id).map(\.title) == ["Open a blank page", "List three points", "Point one", "Point two", "Write it"],
705 "Smaller steps sit under their parent step")
706 check(journal.nextStep(for: todo.id)?.title == "Point one", "One thing starts with the first unfinished smaller step")
707 let points = journal.steps(for: todo.id, parent: first[1].id)
708 journal.setStepDone(points[0].id, done: true)
709 journal.setStepDone(points[1].id, done: true)
710 check(journal.steps(for: todo.id)[1].done && journal.nextStep(for: todo.id)?.title == "Write it",
711 "Finishing the last smaller step finishes its step")
712 check(journal.nextStep(for: todo.id, skipping: [first[2].id]) == nil, "Skipped steps are passed over")
713 journal.setStepDone(first[1].id, done: false)
714 journal.replaceSteps(for: todo.id, with: ["Open a blank page", "Write it", "Share it"])
715 check(journal.steps(for: todo.id).first?.done == true && journal.steps(for: todo.id).count == 3,
716 "Rebreaking keeps finished steps with unchanged text")
717 check(!(journal.todoSteps ?? []).contains { $0.title == "Point one" }, "Removing a step removes its smaller steps")
718 journal.setEstimate(25, source: ToolkitSource.device.rawValue, for: todo.id)
719 journal.setEstimate(30, source: ToolkitSource.person.rawValue, for: todo.id)
720 check(journal.todoEstimates?.count == 1 && journal.estimate(for: todo.id)?.minutes == 30, "One estimate per to-do")
721 let restored = try JournalStore.decode(JSONEncoder().encode(journal))
722 check(restored.todoSteps == journal.todoSteps && restored.todoEstimates == journal.todoEstimates, "Steps and estimates survive backup and restore")
723 var oldBackup = try JSONSerialization.jsonObject(with: JSONEncoder().encode(journal)) as! [String: Any]
724 oldBackup.removeValue(forKey: "todoSteps")
725 oldBackup.removeValue(forKey: "todoEstimates")
726 let old = try JournalStore.decode(JSONSerialization.data(withJSONObject: oldBackup))
727 check(old.todoSteps == nil && old.personalTodos?.count == 1, "Backups from before the Toolkit still restore")
728 var invalid = journal
729 invalid.todoEstimates = [TodoEstimate(id: todo.id, minutes: 0, source: "device")]
730 check((try? JournalStore.decode(JSONEncoder().encode(invalid))) == nil, "Invalid estimates are rejected on restore")
731
732 // Two devices edit different steps of the same to-do offline; both edits survive.
733 let phone = UUID(), mac = UUID()
734 var phoneReplica = try JournalReplica(seed: journal, device: phone)
735 var macReplica = phoneReplica
736 let steps = journal.steps(for: todo.id)
737 var onPhone = journal
738 onPhone.setStepDone(steps[1].id, done: true)
739 try phoneReplica.observe(from: journal, to: onPhone, device: phone)
740 var onMac = journal
741 onMac.replaceSteps(for: todo.id, parent: steps[2].id, with: ["Find the shared folder"])
742 onMac.setEstimate(45, source: "agent", for: todo.id)
743 try macReplica.observe(from: journal, to: onMac, device: mac)
744 phoneReplica.merge(macReplica)
745 let merged = try phoneReplica.materialize(keepingEngagement: Engagement())
746 check(merged.steps(for: todo.id)[1].done && merged.steps(for: todo.id, parent: steps[2].id).count == 1
747 && merged.estimate(for: todo.id)?.minutes == 45, "Concurrent step edits on two devices merge")
748 let wire = try JSONSerialization.jsonObject(with: JSONEncoder().encode(phoneReplica)) as! [String: Any]
749 check(wire["toolkitEntries"] != nil && !((wire["entries"] as? [Any])?.description.contains("todoSteps") ?? false),
750 "Toolkit records live in their own replica extension for older peers")
751 var legacy = wire
752 legacy.removeValue(forKey: "toolkitEntries")
753 let legacyReplica = try JSONDecoder().decode(JournalReplica.self, from: JSONSerialization.data(withJSONObject: legacy))
754 phoneReplica.merge(legacyReplica)
755 let afterLegacy = try phoneReplica.materialize(keepingEngagement: Engagement())
756 check(afterLegacy.todoSteps?.count == merged.todoSteps?.count,
757 "Older peers that omit the extension cannot erase steps")
758 var removed = merged
759 removed.removePersonalTodo(todo.id)
760 check(removed.todoSteps?.isEmpty == true && removed.todoEstimates?.isEmpty == true, "Deleting a to-do deletes its steps and estimate")
761
762 // Offline guide.
763 for size in StepSize.allCases {
764 let plan = OfflineToolkit.breakDown("Reply to Sam's email", size: size)
765 check(plan.count >= 3 && plan.count <= 10 && Set(plan).count == plan.count, "Offline breakdown at \(size.title) has 3 to 10 steps")
766 }
767 check(OfflineToolkit.breakDown("Pay the water bill", size: .tinySteps).count > OfflineToolkit.breakDown("Pay the water bill", size: .bigStrides).count,
768 "Tiny steps give more steps than big strides")
769 check(OfflineToolkit.breakDown("Sort the garage", size: .balanced).first?.contains("Sort the garage") == true,
770 "Generic breakdowns name the task")
771 var calendar = Calendar(identifier: .gregorian)
772 calendar.timeZone = TimeZone(identifier: "UTC")!
773 let monday = calendar.date(from: DateComponents(year: 2026, month: 11, day: 23, hour: 12))!
774 let dump = """
775 ugh so much to do
776 - email Priya about the venue tomorrow
777 I need to buy cat food, pay the electric bill by Friday and then call the dentist
778 also tidy the desk; email Priya about the venue tomorrow
779 """
780 let items = OfflineToolkit.unload(dump, today: monday, calendar: calendar)
781 check(items.map(\.title) == ["Email Priya about the venue", "Buy cat food", "Pay the electric bill", "Call the dentist", "Tidy the desk"],
782 "Unload splits a brain dump into to-dos, drops filler and duplicates")
783 let messy = OfflineToolkit.unload("ugh need to email Sam about friday\nalso dentist?? and coffee filters\nand start that report",
784 today: monday, calendar: calendar)
785 check(messy.map(\.title) == ["Email Sam about friday", "Dentist", "Coffee filters", "Start that report"] && messy[0].dueDay == nil,
786 "Unload keeps actions after a sigh and splits at question marks")
787 check(items[0].dueDay == "2026-11-24" && items[2].dueDay == "2026-11-27" && items[1].dueDay == nil, "Unload finds due days")
788 check(OfflineToolkit.estimate("Reply to an email", focus: .clear) == 10
789 && OfflineToolkit.estimate("Reply to an email", focus: .scattered) == 15
790 && OfflineToolkit.estimate("Something new", steps: 8, focus: .clear) == 50, "Time check adjusts for focus and steps")
791 check(ToolkitClean.lines(["1. Open the laptop", "- Open the laptop", "", "• Start"]) == ["Open the laptop", "Start"],
792 "Model and agent lists are cleaned before saving")
793 check(OfflineToolkit.reword("I just wanted to say I really think it's done.", tone: .shorter) == "I wanted to say it's done."
794 && OfflineToolkit.reword("One. Two.", tone: .bullets) == "• One\n• Two"
795 && OfflineToolkit.reword("Hi", tone: .kinder) == nil, "Offline Reword offers only Shorter and Bullet points")
796 let urgent = OfflineToolkit.readTone("I need this ASAP. Thanks!", received: true)?.tones.map(\.tone) ?? []
797 let curt = OfflineToolkit.readTone("ok.", received: true)?.tones.map(\.tone) ?? []
798 let plain = OfflineToolkit.readTone("The meeting moved to 3pm", received: false)?.tones.map(\.tone) ?? []
799 check(urgent.contains("Emphatic") && urgent.contains("Urgent") && urgent.contains("Warm")
800 && curt == ["Brief"] && plain == ["Neutral"]
801 && OfflineToolkit.readTone(" ", received: true) == nil, "Offline Read the room names tones and the words behind them")
802 let frustrated = OfflineToolkit.readTone("Per my last email, still waiting.", received: true)?.tones ?? []
803 check(frustrated.first { $0.tone == "Frustrated" }?.why.contains("“Per my last”") == true,
804 "Offline Read the room quotes the longest phrase as written")
805 check(OfflineToolkit.weighing("Should I take the pottery class?").experiment
806 == "Pick one small, reversible step toward “take the pottery class” and try it for 7 days. Note how it feels each evening."
807 && OfflineToolkit.weighing("Move house").pros.isEmpty, "Offline Weigh it suggests a plain experiment")
808 let quick = PersonalTodo(title: "Text Mum", dueDay: "2026-11-25")
809 let overdue = PersonalTodo(title: "Return the form", dueDay: "2026-11-20")
810 let big = PersonalTodo(title: "Write the essay")
811 let picks = OneThingPicker.choices([big, quick, overdue], estimates: [TodoEstimate(id: quick.id, minutes: 5, source: "guide"),
812 TodoEstimate(id: big.id, minutes: 120, source: "guide")],
813 focus: .scattered, today: "2026-11-24", hour: 19)
814 check(picks.count == 2 && picks[0].id == overdue.id && picks[1].id == quick.id, "One thing offers two choices, overdue and small first")
815 let reply = try ToolkitReply.decode(ToolkitReply.Items.self, from: ["items": [["title": "Buy milk", "due_day": "2026-11-25"]]])
816 check(reply.items.first?.dueDay == "2026-11-25", "Agent replies decode snake_case fields")
817 print("PASS: Toolkit steps, estimates, sync, backup, offline guide and agent replies.")
818 }
819
820 private static func checkPersonalTodos() throws {
821 let now = Date()
822 let day = PracticeDate.key(now)
823 let tomorrow = PracticeDate.key(Calendar.current.date(byAdding: .day, value: 1, to: now)!)
824 let open = PersonalTodo(title: "Return the library book", dueDay: day, reminderAt: now + 600)
825 let later = PersonalTodo(title: "Check the mail", dueDay: tomorrow, reminderAt: now + 1200)
826 let undated = PersonalTodo(title: "Look up pottery lessons")
827 var done = PersonalTodo(title: "Buy stamps", dueDay: day, reminderAt: now + 300)
828 done.completed = true
829 let past = PersonalTodo(title: "Pick up a parcel", dueDay: day, reminderAt: now - 600)
830 check(open.isDue(by: day) && open.isDue(by: tomorrow), "Due tasks remain visible after their due day")
831 check(!later.isDue(by: day) && !undated.isDue(by: day) && !done.isDue(by: day), "Future, undated and completed tasks stay out of Today")
832 check(PersonalReminders.upcoming([done, later, undated, past, open], now: now, limit: 1) == [open],
833 "Schedule only the soonest unfinished future reminders up to capacity")
834
835 let oldJournal = try JournalStore.decode(JSONEncoder().encode(Journal()))
836 check(oldJournal.personalTodos == nil, "Old journals load without personal to-dos")
837 let firstDevice = UUID()
838 let secondDevice = UUID()
839 var first = oldJournal
840 first.personalTodos = [open]
841 var second = oldJournal
842 second.personalTodos = [later]
843 var firstReplica = try JournalReplica(seed: first, device: firstDevice)
844 let secondReplica = try JournalReplica(seed: second, device: secondDevice)
845 firstReplica.merge(secondReplica)
846 let restored = try firstReplica.materialize(keepingEngagement: Engagement())
847 check(Set(restored.personalTodos?.map(\.id) ?? []) == [open.id, later.id] && restored.tasks.isEmpty && restored.coins == 0,
848 "Personal tasks merge independently of the coaching plan and rewards")
849
850 let bytes = try JSONEncoder().encode(firstReplica)
851 var legacy = try JSONSerialization.jsonObject(with: bytes) as! [String: Any]
852 check(legacy.removeValue(forKey: "personalTodoEntries") != nil, "New records occupy their own replica extension")
853 let legacyReplica = try JSONDecoder().decode(JournalReplica.self, from: JSONSerialization.data(withJSONObject: legacy))
854 firstReplica.merge(legacyReplica)
855 let afterLegacy = try firstReplica.materialize(keepingEngagement: Engagement())
856 check(afterLegacy.personalTodos?.count == 2, "Old peers that omit the extension cannot erase personal tasks")
857 var afterDelete = restored
858 afterDelete.personalTodos?.removeAll { $0.id == later.id }
859 try firstReplica.observe(from: restored, to: afterDelete, device: firstDevice)
860 firstReplica.merge(secondReplica)
861 let remaining = try firstReplica.materialize(keepingEngagement: Engagement())
862 check(remaining.personalTodos == [open], "Deleted personal tasks stay deleted after merging a stale peer")
863 }
864
865 private static func checkSync(in directory: URL, catalog: Catalog, now: Date, tomorrow: Date) throws {
866 let day = CalendarDay.key(now)
867 let nextDay = CalendarDay.key(tomorrow)
868 let phone = UUID()
869 let pad = UUID()
870 let mac = UUID()
871 let first = PlanTask()
872 let second = PlanTask()
873 let lesson = catalog.lessons[0]
874 let challenge = catalog.challenges[0]
875 let suggestion = catalog.startingSuggestions([:])[0]
876 var base = Journal()
877 base.started = now
878 base.name = "Alex"
879 base.tasks = [first, second]
880 base.favoriteSources = ["Claude", "YouTube"]
881 base.experiment = Experiment(suggestion: suggestion, start: now)
882 let seed = try JournalReplica(seed: base, device: phone)
883 var phoneState = seed
884 var padState = seed
885 var macState = seed
886
887 var phoneJournal = base
888 let moment = Moment(source: "Claude", kind: "AI", tags: ["Coding help"], value: 0.8,
889 decision: .more, date: now, day: day)
890 phoneJournal.record(moment)
891 phoneJournal.recordEnergy(.init(level: "high", value: 0.8), on: now)
892 phoneJournal.toggleTask(first, on: now)
893 phoneJournal.completeLesson(lesson, on: now)
894 phoneJournal.checkIn(.held, on: now)
895 try phoneState.observe(from: base, to: phoneJournal, device: phone)
896
897 var padJournal = base
898 padJournal.toggleTask(second, on: now)
899 padJournal.habits[day] = ["read"]
900 padJournal.moods[day] = 3
901 padJournal.lessons[lesson.id, default: LessonRecord()].choices["2"] = "A reply"
902 padJournal.checkIn(.slip, on: tomorrow)
903 padJournal.toggleFavoriteChore("maintenance:hvac-filter")
904 padJournal.toggleMaintenanceChore("maintenance:hvac-filter", on: tomorrow)
905 try padState.observe(from: base, to: padJournal, device: pad)
906
907 var macJournal = base
908 macJournal.name = "Alex R"
909 macJournal.tracker = .ring
910 macJournal.favoriteSources?.removeAll { $0 == "YouTube" }
911 macJournal.customSources = ["My book"]
912 macJournal.cleaningChecks["daily"] = [0, 1]
913 macJournal.cleaningLast["daily"] = day
914 let daily = catalog.cleaning.daily
915 let choreID = daily.choreID(at: 2)
916 macJournal.toggleFavoriteChore(choreID)
917 macJournal.toggleCleaningChore(daily, at: 2, on: now)
918 macJournal.toggleCleaningChore(daily, at: 2, on: now)
919 macJournal.completeChallenge(challenge, choice: "Keys", on: now)
920 try macState.observe(from: base, to: macJournal, device: mac)
921
922 let file = directory.appending(path: "phone-snapshot.glimmerjournal")
923 try JournalCloud.write(phoneState, to: file)
924 let readback = try JournalCloud.read(file)
925 check(readback == phoneState, "Coordinated replica transfer round trip")
926 var all = readback
927 all.merge(padState)
928 all.merge(macState)
929 var reverse = macState
930 reverse.merge(padState)
931 reverse.merge(readback)
932 check(all == reverse, "Three independently edited devices converge")
933
934 let merged = try all.materialize(keepingEngagement: phoneJournal.engagement)
935 check(merged.tasks == base.tasks && merged.completions[day] == [first.id, second.id], "Same-day task completions merge")
936 check(merged.moments == [moment] && merged.energy[day]?.value == 0.8, "Moment and energy merge")
937 check(merged.lessons[lesson.id]?.completed == true && merged.lessons[lesson.id]?.choices["2"] == "A reply", "Independent lesson changes merge")
938 check(merged.experiment?.checkins == [day: .held, nextDay: .slip], "Experiment check-ins merge by day")
939 check(merged.name == "Alex R" && merged.tracker == .ring && merged.favoriteSources == ["Claude"], "Preferences and deletions merge")
940 check(merged.customSources == ["My book"] && merged.habits[day] == ["read"] && merged.moods[day] == 3, "Sources, habits and moods merge")
941 check(merged.cleaningChecks["daily"] == [0, 1] && merged.cleaningLast["daily"] == day
942 && merged.challenges[challenge.id]?.choice == "Keys", "Cleaning and Tiny wins merge")
943 check(merged.favoriteChores == [choreID, "maintenance:hvac-filter"]
944 && merged.recentChores?["maintenance:hvac-filter"] == [CalendarDay.key(tomorrow)]
945 && merged.recentChores?[choreID]?.contains(day) != true,
946 "Chore favorites and completion dates merge, and an undone check stays out of Recent")
947 let wire = try JSONSerialization.jsonObject(with: JSONEncoder().encode(all)) as? [String: Any]
948 if var oldWire = wire {
949 oldWire.removeValue(forKey: "choreEntries")
950 let oldReplica = try JSONDecoder().decode(JournalReplica.self, from: JSONSerialization.data(withJSONObject: oldWire))
951 let oldJournal = try oldReplica.materialize(keepingEngagement: .init())
952 check(oldJournal.favoriteChores == nil && oldJournal.cleaningLast["daily"] == day,
953 "Older releases can read existing cleaning state independently of new chore fields")
954 }
955 check(merged.engagement.count == phoneJournal.engagement.count && merged.rewards["log:\(day)"] == 10, "Review milestones stay local and rewards deduplicate")
956
957 var undone = merged
958 undone.toggleTask(first, on: now)
959 undone.tasks.removeAll { $0.id == first.id }
960 try all.observe(from: merged, to: undone, device: phone)
961 all.merge(seed)
962 all.merge(macState)
963 let afterUndo = try all.materialize(keepingEngagement: .init())
964 check(afterUndo.tasks.map(\.id) == [second.id] && afterUndo.completions[day] == [second.id]
965 && afterUndo.rewards["task:\(day):\(first.id)"] == nil, "A stale replica cannot resurrect a deleted task or undone check")
966
967 let saved = SavedJournal(journal: afterUndo, cloud: JournalCloudState(device: phone, replica: all))
968 let data = try JSONEncoder().encode(saved)
969 let oldReader = try JSONDecoder().decode(Journal.self, from: data)
970 let newReader = try JSONDecoder().decode(SavedJournal.self, from: data)
971 check(oldReader.tasks == afterUndo.tasks && newReader.cloud?.replica == all, "Local sync metadata preserves the existing journal format")
972 print("PASS: three independent journal replicas, coordinated file exchange, conflicting offline edits, deletions and relaunch compatibility.")
973 }
974
975 @MainActor
976 private static func checkAgentAccess(in directory: URL, catalog: Catalog, catalogURL: URL) throws {
977 let folder = directory.appending(path: "agent", directoryHint: .isDirectory)
978 let journalURL = folder.appending(path: "Journal.json")
979 let app = JournalStore(url: journalURL, catalogURL: catalogURL)
980 app.start(name: "Agent")
981 let session = AgentAccess.Session(journal: journalURL, catalog: catalog)
982 var next = 1
983 func send(_ method: String, _ params: [String: Any] = [:]) -> [String: Any] {
984 next += 1
985 let request: [String: Any] = ["jsonrpc": "2.0", "id": next, "method": method, "params": params]
986 let line = String(decoding: try! JSONSerialization.data(withJSONObject: request), as: UTF8.self)
987 return session.handle(line) ?? [:]
988 }
989 func call(_ name: String, _ arguments: [String: Any] = [:]) -> (error: Bool, body: [String: Any], text: String) {
990 let result = send("tools/call", ["name": name, "arguments": arguments])["result"] as? [String: Any] ?? [:]
991 let text = ((result["content"] as? [[String: Any]])?.first?["text"] as? String) ?? ""
992 let body = (try? JSONSerialization.jsonObject(with: Data(text.utf8))) as? [String: Any] ?? [:]
993 return (result["isError"] as? Bool == true, body, text)
994 }
995 check(send("tools/list")["error"] != nil, "Tools wait for initialize")
996 let initialized = send("initialize", ["protocolVersion": "2025-06-18", "clientInfo": ["name": "Checks"]])["result"] as? [String: Any]
997 check(initialized?["instructions"] is String, "Server sends agent instructions")
998 check(session.handle(#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#) == nil, "Notifications get no reply")
999 let advertised = (send("tools/list")["result"] as? [String: Any])?["tools"] as? [[String: Any]] ?? []
1000 check(Set(advertised.compactMap { $0["name"] as? String }).isSuperset(of:
1001 ["list_personal_todos", "add_personal_todo", "set_personal_todo_done", "set_todo_steps"]), "Personal task tools are advertised")
1002 check(call("get_plan_summary").error, "Access off blocks summaries")
1003
1004 try app.setAgentLevel(.summaries)
1005 check(!call("get_plan_summary").error && call("get_attention_summary", ["days": 7]).body["days"] as? Int == 7, "Summaries allowed")
1006 check(call("get_attention_summary", ["days": 31]).error && call("get_attention_summary", ["days": true]).error, "Day range validated")
1007 check(call("get_today").error && call("log_moment", ["source": "Walk", "aftertaste": 2]).error, "Summaries mode cannot read titles or write")
1008 check(call("list_personal_todos").error && call("add_personal_todo", ["title": "Books"]).error,
1009 "Summaries mode keeps personal task titles private")
1010
1011 let daily = call("get_daily_glimmer")
1012 let attribution = daily.body["source"] as? [String: String]
1013 check(attribution?["credit"] == "the owner, author and life coach" && attribution?["note"] == CoachingSource.note, "Daily guidance credits its author and explains its scope")
1014 let dayKey = PracticeDate.key(.now)
1015 let reflection = daily.body["reflection"] as? [String: Any]
1016 check(reflection?["topic_id"] as? String == Catalog.reflectionTopicID && reflection?["saved"] as? Bool == false && reflection?["done"] as? Bool == false, "Read-only dashboard includes today’s public reflection")
1017 let featured = daily.body["practice"] as! [String: Any]
1018 let practiceID = featured["practice_id"] as! String
1019 let practiceTaskID = featured["task_id"] as! String
1020 let saveArguments = ["practice_id": practiceID, "day": dayKey]
1021 let listed = call("list_practices").body["practices"] as! [[String: Any]]
1022 check(!daily.error && daily.body["day_id"] as? String == "glimmer:daily:\(dayKey)" && daily.text == call("get_daily_glimmer").text, "Repeatable daily content")
1023 check(listed.count == catalog.practiceTopics.flatMap(\.exercises).count && listed.contains { $0["practice_id"] as? String == practiceID }, "Complete public coaching catalog")
1024 check(call("list_practices", ["topic_id": "missing"]).error && call("save_practice", saveArguments).error, "Read-only boundaries")
1025 check(!daily.text.contains(app.journal.tasks[0].name) && !daily.text.contains("favoriteSources"), "Personal task titles and journal records excluded")
1026 try app.setAgentLevel(.changes)
1027 let reminder = ISO8601DateFormatter().string(from: .now + 3600)
1028 let todoID = UUID().uuidString
1029 let todoArguments: [String: Any] = ["title": "Return a library book", "due_day": dayKey,
1030 "reminder_at": reminder, "request_id": todoID]
1031 let todo = call("add_personal_todo", todoArguments)
1032 let retry = call("add_personal_todo", todoArguments)
1033 check(todo.body["task_id"] as? String == todoID && todo.body["added"] as? Bool == true
1034 && retry.body["added"] as? Bool == false && retry.body["reminder_at"] as? String == reminder,
1035 "An agent can save a dated, timed personal task and safely retry")
1036 check(call("add_personal_todo", ["title": "Impossible date", "due_day": "2026-02-30"]).error &&
1037 call("add_personal_todo", ["title": "Elapsed reminder", "reminder_at": "2025-11-25T12:00:00Z"]).error,
1038 "The agent rejects invalid dates and elapsed reminders")
1039 check((call("list_personal_todos", ["filter": "due"]).body["todos"] as? [[String: Any]])?.count == 1,
1040 "The agent can read today's personal tasks")
1041 check(call("set_personal_todo_done", ["task_id": todoID, "done": true]).body["done"] as? Bool == true
1042 && (call("list_personal_todos", ["filter": "due"]).body["todos"] as? [[String: Any]])?.isEmpty == true,
1043 "Checking off a personal task removes it from the due list")
1044 check(call("set_personal_todo_done", ["task_id": todoID, "done": false]).body["done"] as? Bool == false,
1045 "Personal tasks can be reopened")
1046 let stepped = call("add_personal_todo", ["title": "Plan the party", "steps": ["Pick a date", "Write the guest list"],
1047 "estimate_minutes": 45])
1048 let steppedID = stepped.body["task_id"] as? String ?? ""
1049 let firstSteps = stepped.body["steps"] as? [[String: Any]] ?? []
1050 check(firstSteps.map { $0["title"] as? String } == ["Pick a date", "Write the guest list"]
1051 && stepped.body["estimate_minutes"] as? Int == 45 && stepped.body["estimate_source"] as? String == "agent",
1052 "An agent can add a to-do with steps and an estimate")
1053 check(call("add_personal_todo", ["title": "Bad", "steps": [""]]).error
1054 && call("add_personal_todo", ["title": "Bad", "estimate_minutes": 0]).error
1055 && call("add_personal_todo", ["title": "Bad", "steps": "Pick a date"]).error, "Step and estimate input is validated")
1056 let pickID = firstSteps.first?["step_id"] as? String ?? ""
1057 let smaller = call("set_todo_steps", ["task_id": steppedID, "parent_step_id": pickID, "steps": ["Check the calendar", "Ask Sam"]])
1058 let nested = (smaller.body["steps"] as? [[String: Any]])?.first?["steps"] as? [[String: Any]] ?? []
1059 check(nested.count == 2 && (smaller.body["steps"] as? [[String: Any]])?.first?["step_id"] as? String == pickID,
1060 "set_todo_steps adds smaller steps and keeps the parent")
1061 let replaced = call("set_todo_steps", ["task_id": steppedID, "steps": ["Pick a date", "Book the room"]])
1062 check((replaced.body["steps"] as? [[String: Any]])?.first?["step_id"] as? String == pickID
1063 && (replaced.body["steps"] as? [[String: Any]])?.last?["title"] as? String == "Book the room",
1064 "Replacing steps keeps unchanged steps")
1065 let grandchild = nested.first?["step_id"] as? String ?? ""
1066 check(call("set_todo_steps", ["task_id": steppedID, "parent_step_id": grandchild, "steps": ["Too deep"]]).error
1067 && call("set_todo_steps", ["task_id": UUID().uuidString, "steps": []]).error, "Steps stay two levels deep on real to-dos")
1068 check(call("set_todo_steps", ["task_id": steppedID, "steps": []]).body["steps"] == nil
1069 && JournalStore(url: journalURL, catalogURL: catalogURL).journal.todoSteps?.isEmpty == true,
1070 "An agent can clear steps")
1071 _ = call("set_personal_todo_done", ["task_id": steppedID, "done": true])
1072 let reopenedApp = JournalStore(url: journalURL, catalogURL: catalogURL)
1073 check(reopenedApp.journal.personalTodos?.count == 2 && reopenedApp.journal.tasks.count == catalog.initialTasks.count,
1074 "Agent writes persist in the same journal and leave the coaching plan intact")
1075 let today = call("get_today")
1076 let tasks = today.body["tasks"] as? [[String: Any]] ?? []
1077 check(!today.error && !tasks.isEmpty && tasks.allSatisfy { $0["name"] is String }, "Today lists tasks with names")
1078 let logged = call("log_moment", ["source": "walk", "aftertaste": 2, "decision": "more", "tags": ["Outside"]])
1079 check(!logged.error && logged.body["logged"] as? String == "Walk" && logged.body["category"] as? String == "Activity", "Moment matches a catalog source")
1080 check(call("log_moment", ["source": "Instagram", "aftertaste": 3]).error, "Aftertaste range validated")
1081 let historicalDay = PracticeDate.key(Calendar.current.date(byAdding: .day, value: -2, to: .now)!)
1082 check(call("log_moment", ["day": historicalDay, "source": "Walk", "aftertaste": 1]).body["day"] as? String == historicalDay, "Backdated moments retain their local day")
1083 check(call("log_moment", ["day": "2099-11-29", "source": "Walk", "aftertaste": 1]).error, "Future logs rejected")
1084 let id = tasks[0]["id"] as! String
1085 check(!call("set_task_done", ["task_id": id]).error && !call("set_task_done", ["task_id": id, "done": true]).error, "Check off is idempotent")
1086 check(call("set_task_done", ["task_id": "missing"]).error, "Unknown task rejected")
1087 let added = call("add_plan_task", ["name": "Call the bank", "day": "tomorrow", "icon": "📞"])
1088 check(!added.error && added.body["added"] as? Bool == true, "Task added to tomorrow")
1089 check(call("add_plan_task", ["name": "call the bank", "day": "tomorrow"]).body["added"] as? Bool == false, "Same task not added twice")
1090 check(!(call("get_today").body["tasks"] as? [[String: Any]] ?? []).contains { $0["name"] as? String == "Call the bank" }, "Tomorrow's task stays off today")
1091 let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: .now)!
1092 check(JournalStore(url: journalURL, catalogURL: nil).journal.tasks.contains { $0.name == "Call the bank" && !$0.repeats && $0.occurs(on: tomorrow) }, "Tomorrow's task is saved once")
1093 check(call("add_plan_task", ["name": "", "day": "today"]).error && call("add_plan_task", ["name": "X", "day": "monday"]).error, "Task input validated")
1094 check(!call("record_energy", ["level": "high"]).error && call("record_energy", ["level": "loud"]).error, "Energy levels validated")
1095 check(call("check_in_experiment", ["outcome": "held"]).error, "No experiment means no check-in")
1096
1097 let saved = call("save_practice", saveArguments)
1098 check(saved.body["added"] as? Bool == true && saved.body["task_id"] as? String == practiceTaskID && call("save_practice", saveArguments).body["added"] as? Bool == false, "Practice save and retry")
1099 let complete = call("set_task_done", ["task_id": practiceTaskID, "day": dayKey, "done": true])
1100 check(!complete.error && complete.body["coins"] as? Int == call("set_task_done", ["task_id": practiceTaskID, "day": dayKey, "done": true]).body["coins"] as? Int, "Dated completion is idempotent")
1101 let prior = PracticeDate.key(Calendar.current.date(byAdding: .day, value: -1, to: .now)!)
1102 check(call("set_task_done", ["task_id": practiceTaskID, "day": prior]).error && call("save_practice", ["practice_id": practiceID, "day": "2026-02-30"]).error, "Stale day mismatch and invalid date rejected")
1103 check((call("get_daily_glimmer").body["practice"] as? [String: Any])?["done"] as? Bool == true, "Dashboard reads completed state")
1104 _ = call("record_energy", ["level": "high"])
1105 // The running app sees the agent's changes before it saves its own.
1106 check(app.journal.moments.isEmpty, "App holds its earlier copy")
1107 Thread.sleep(forTimeInterval: 0.01)
1108 check(app.change { $0.name = "Agent R" }, "App saves after an agent change")
1109 let reread = JournalStore(url: journalURL, catalogURL: nil)
1110 let day = CalendarDay.key(Date())
1111 check(reread.journal.moments.count == 2 && reread.journal.moments.contains(where: { $0.day == historicalDay }) && reread.journal.completions[day]?.contains(id) == true
1112 && reread.journal.energy[day]?.level == "high" && reread.journal.name == "Agent R", "Agent and app changes both kept")
1113 check(AgentActivity.read(in: folder)?.client == "Checks" && AgentActivity.read(in: folder)?.tool == "record_energy", "Activity recorded")
1114
1115 try app.setAgentLevel(.off)
1116 check(AgentAccess.level(in: folder) == .off && call("get_plan_summary").error, "Turning access off revokes it")
1117
1118 let merged = try AgentSetup.mergedProjectConfiguration(existing: Data(#"{"mcpServers":{"other":{"command":"x"}},"keep":1}"#.utf8), command: "/Applications/Glimmer.app/Contents/MacOS/Glimmer")
1119 let root = try JSONSerialization.jsonObject(with: merged.data) as? [String: Any]
1120 let servers = root?["mcpServers"] as? [String: Any]
1121 check(servers?["other"] != nil && root?["keep"] as? Int == 1 && (servers?["glimmer"] as? [String: Any])?["args"] as? [String] == ["--mcp"] && !merged.replaces,
1122 "Project connection keeps other servers")
1123 check((try? AgentSetup.mergedProjectConfiguration(existing: Data("[1]".utf8), command: "x")) == nil, "Invalid project configuration left alone")
1124 let manifest = try JSONSerialization.jsonObject(with: AgentSetup.extensionManifest(command: "/Applications/Glimmer.app/Contents/MacOS/Glimmer")) as? [String: Any]
1125 check(manifest?["name"] as? String == "glimmer" && (manifest?["tools"] as? [Any])?.count == advertised.count,
1126 "Claude extension manifest advertises the same tools")
1127 }
1128
1129 private static func check(_ condition: @autoclosure () -> Bool, _ message: String) {
1130 precondition(condition(), message)
1131 }
1132}