Branchwell

Glimmer / app · glimmertoday.ai / commits / 373be588

App source: current code new

written by Branchwell · 373be588c5c7abca97cdec6f7aa4be565975b988

147 files changed

.gitignore added

1+ .DS_Store
2+ build/
3+ DerivedData/
4+ xcuserdata/
5+ *.xcuserstate
6+ .env

CONTRIBUTING.md added

1+ # Contributing to Glimmer
2+
3+ Volunteer contributions are welcome. A small bug fix, accessibility improvement, test, or documentation update is a good first PR.
4+
5+ 1. [Fork the public repository](https://github.com/projectatomai/glimmer/fork), clone your fork, and create a branch for your change. Don’t push directly to the upstream `main` branch.
6+ 2. Make one focused change and run the relevant checks below. Use sample data. Never include secrets, private records, signing credentials, or files you don’t have permission to share.
7+ 3. [Open a pull request](https://github.com/projectatomai/glimmer/pulls) from your fork’s branch to this repository’s `main`. Explain what changed, why, and how you tested it. Mention anything you couldn’t test and attach screenshots if they clarify a UI change. A maintainer reviews changes before merging.
8+
9+ ## Local checks
10+
11+ See the [README build instructions](README.md#build-it-yourself). Open `native/Glimmer.xcodeproj` in Xcode and run the **Glimmer** scheme on My Mac or a simulator. Run the relevant UI tests and see [native checks](native/README.md#checks). Local development works without iCloud.
12+
13+ Prefer testing, design, or documentation help without a PR? See the [volunteer app-support roles](https://jobley.ai/volunteer/#app-support) or [Project ATOM’s open-source app directory](https://projectatom.ai/apps#open-source).

LICENSE added

1+ This is free and unencumbered software released into the public domain.
2+
3+ Anyone is free to copy, modify, publish, use, compile, sell, or
4+ distribute this software, either in source code form or as a compiled
5+ binary, for any purpose, commercial or non-commercial, and by any
6+ means.
7+
8+ In jurisdictions that recognize copyright laws, the author or authors
9+ of this software dedicate any and all copyright interest in the
10+ software to the public domain. We make this dedication for the benefit
11+ of the public at large and to the detriment of our heirs and
12+ successors. We intend this dedication to be an overt act of
13+ relinquishment in perpetuity of all present and future rights to this
14+ software under copyright law.
15+
16+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22+ OTHER DEALINGS IN THE SOFTWARE.
23+
24+ For more information, please refer to <https://unlicense.org>

README.md added

1+ <p align="center">
2+ <img src="docs/readme/app-icon.png" alt="Glimmer app icon" width="128">
3+ </p>
4+
5+ <h1 align="center">Glimmer</h1>
6+
7+ <p align="center"><strong>A gentle spiritual life coach for minds too busy thinking.</strong><br>Free and private, for deep thinkers, neurodivergent minds, and anyone too busy thinking to keep a tidy to-do list.</p>
8+
9+ <p align="center">
10+ <a href="https://glimmertoday.ai/download"><strong>Download for Mac</strong></a> ·
11+ <a href="https://glimmertoday.ai">glimmertoday.ai</a> ·
12+ <a href="#build-it-yourself">Build it yourself</a> ·
13+ <a href="LICENSE">public domain (Unlicense)</a>
14+ </p>
15+
16+ <p align="center"><sub>Free · macOS 15 or later · iPhone and iPad coming soon · No account · Open source, public domain (Unlicense)</sub></p>
17+
18+ ---
19+
20+ ![Glimmer for Mac: the coach suggesting one small next step](docs/readme/mac-coach-light.webp)
21+
22+ Want to help build, test, or document the app? Read the [contribution guide](CONTRIBUTING.md).
23+
24+ ## Check your energy. Pick one small thing. Notice what helps.
25+
26+ Glimmer starts with a ten-second energy check, so a low day gets a smaller plan, and that's the point. Give today one small task, log a moment while you still feel it, and turn the dial to how it left you. Over a week, Glimmer shows you what actually nourishes you and what drains you, then suggests one small experiment to try next.
27+
28+ No streaks to break, no guilt, no account. Your journal stays on your device, works offline, and syncs only through your own private iCloud if you turn it on.
29+
30+ <table>
31+ <tr><th>Plan your day on Mac</th><th>Review your week</th></tr>
32+ <tr>
33+ <td><img src="docs/readme/mac-plan-light.webp" alt="The Glimmer plan on Mac with today's tasks and habits"></td>
34+ <td><img src="docs/readme/mac-weekly-dark.webp" alt="Glimmer's weekly review on Mac in dark mode"></td>
35+ </tr>
36+ </table>
37+
38+ ## Tools for a full head
39+
40+ The **Toolkit** takes the mess in your head and hands back one clear next step:
41+
42+ - **Break it down** turns one big task into small steps.
43+ - **Unload** sorts a brain dump into a tidy list.
44+ - **Time check** gives an honest estimate, sized to today's energy.
45+ - **One thing** hides everything else so you can do just this.
46+ - **Read the room** and **Reword** show how a message may land, then soften it.
47+ - **Weigh it** sorts the pros and cons, then suggests a seven-day test.
48+
49+ Each tool runs on your device with Apple Intelligence, or through the agent you connect on Mac (Claude Code, Codex or Gemini CLI). A built-in offline guide works when neither is available.
50+
51+ <table>
52+ <tr><th>Today</th><th>The Toolkit</th><th>Break it down</th></tr>
53+ <tr>
54+ <td align="center"><img src="docs/readme/iphone-today-dark.webp" alt="Glimmer Today screen" width="240"></td>
55+ <td align="center"><img src="docs/readme/iphone-toolkit-light.webp" alt="Glimmer Toolkit" width="240"></td>
56+ <td align="center"><img src="docs/readme/iphone-breakitdown-light.webp" alt="Break it down turning a task into steps" width="240"></td>
57+ </tr>
58+ </table>
59+
60+ <sub>iPhone and iPad apps are companions to the Mac app and are coming soon. Screenshots use sample entries.</sub>
61+
62+ ## More inside
63+
64+ - A 120-lesson reading plan that opens one lesson a day and deepens as you go.
65+ - Habits, mood, guided Tiny Wins with timers, cleaning lists and personal to-dos with reminders.
66+ - Coaching and experiment reviews built from your actual logs, never someone else's average.
67+ - A local MCP connection so your Mac agents can log moments and check off tasks, with access you control.
68+ - JSON backup and restore from Settings.
69+
70+ ## Build it yourself
71+
72+ Use a Mac with Xcode 26 or later.
73+
74+ ```sh
75+ git clone https://github.com/projectatomai/glimmer.git
76+ cd glimmer/native
77+ open Glimmer.xcodeproj
78+ ```
79+
80+ Choose the **Glimmer** scheme and run it on My Mac, an iPhone or an iPad simulator. Local builds work without iCloud. For sync on real devices, use your own Apple Developer team, bundle identifier and iCloud container. The full build, sync and agent guide is in [native/README.md](native/README.md).
81+
82+ | Path | What's there |
83+ | --- | --- |
84+ | `native/Glimmer` | The SwiftUI app for Mac, iPhone and iPad |
85+ | `native/Checks`, `native/GlimmerUITests` | Core checks and UI tests |
86+ | `brand/` | The app icon sources and render script |
87+
88+ ## Open source, public domain (Unlicense)
89+
90+ Glimmer is free, and its source is open under the [public domain (Unlicense)](LICENSE). Use it, change it, ship it, sell it. Third-party packages keep their own licenses.
91+
92+ [Website](https://glimmertoday.ai) · [Help](https://glimmertoday.ai/support) · [Send feedback](https://projectatom.ai/apps?app=glimmer#feedback)
93+
94+ ---
95+
96+ <p align="center"><strong>A <a href="https://projectatom.ai/">Project ATOM</a> app.</strong> Free, open source, and in the public domain (Unlicense).</p>
97+
98+ <p align="center">
99+ <a href="https://opentalon.ai">OpenTalon</a> ·
100+ <a href="https://inkspring.ai">Inkspring</a> ·
101+ <a href="https://jotley.ai">Jotley</a> ·
102+ <a href="https://glimmertoday.ai">Glimmer</a> ·
103+ <a href="https://pulsecanvas.ai">PulseCanvas</a> ·
104+ <a href="https://voxley.si">Voxley</a> ·
105+ <a href="https://textley.ai">Textley</a> ·
106+ <a href="https://graphley.ai">Graphley</a> ·
107+ <a href="https://bucksley.ai">Bucksley</a>
108+ </p>
109+
110+ <p align="center"><a href="https://projectatom.ai/apps">Project ATOM apps</a> · <a href="https://projectatom.ai/apps#open-source">Open-source projects</a></p>

brand/README.md added

1+ # Glimmer icon
2+
3+ The app icon is a gold sparkle inside an open blue ring on a dark honey-to-slate square. Inside the app,
4+ `GlimmerLogo` (`native/Glimmer/Design.swift`) shows the `AppMark` image asset, the round mask of the icon PNG,
5+ so the About panel, onboarding and Coach always show the real icon.
6+ It replaced the penguin mascot on 2026-11-21.
7+
8+ - `glimmer-icon.svg` is the master artwork: a full-bleed 1024 px square. macOS and iOS round the corners themselves.
9+ - `glimmer-icon-mac.svg` is the same art in Apple's macOS layout (824 px rounded square with a shadow on a
10+ 1024 canvas), for screenshots, the installer mock-up and marketing.
11+ - `glimmer-icon-1024.png` is a ready-made PNG of the master.
12+ - `glimmer-mark-round-1024.png` is that PNG masked to a circle. It is the round logo for About, onboarding,
13+ Coach and docs (the app's `AppMark` asset). Never redraw the mark in code; regenerate it with the script below.
14+
15+ The sparkle is our own vector path, not the SF Symbol, because Apple does not allow SF Symbols in app icons.
16+
17+ To change the icon, edit `glimmer-icon.svg`, then run `node brand/render-icons.cjs` (needs Playwright and
18+ ImageMagick). It writes the Xcode app icon set, the site favicon, Apple touch icon and header icon, and the Expo
19+ icons. Re-render the share card from `site/og-card.html` afterwards (see that file).

brand/glimmer-icon-1024.png added

Not a text file.

brand/glimmer-icon-mac.svg added

1+ <svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
2+ <title>Glimmer app icon (macOS layout: 824 px rounded square on a 1024 canvas)</title>
3+ <!-- Colors match the About panel mark in dark mode (CompanionMark in native/Glimmer/Design.swift):
4+ honey #e2ba5e at 28% and accent #9dbbdc at 20% over the surface #212120, ring in accent at 70%. -->
5+ <defs>
6+ <linearGradient id="bg" x1="100" y1="100" x2="924" y2="924" gradientUnits="userSpaceOnUse">
7+ <stop offset="0" stop-color="#574c31"/>
8+ <stop offset="1" stop-color="#3a4046"/>
9+ </linearGradient>
10+ <filter id="shadow" x="-20%" y="-20%" width="140%" height="140%">
11+ <feDropShadow dx="0" dy="10" stdDeviation="14" flood-color="#000" flood-opacity="0.35"/>
12+ </filter>
13+ </defs>
14+ <rect x="100" y="100" width="824" height="824" rx="185" fill="url(#bg)" filter="url(#shadow)"/>
15+ <rect x="101" y="101" width="822" height="822" rx="184" fill="none" stroke="#fff" stroke-opacity="0.08" stroke-width="2"/>
16+ <path d="M305.2 718.8A292.5 292.5 0 1 1 718.8 718.8" fill="none" stroke="#9dbbdc" stroke-opacity="0.7" stroke-width="37.1" stroke-linecap="round"/>
17+ <path transform="translate(512 512) scale(136.0)" d="M0 -1C0.2 -0.4 0.4 -0.2 1 0C0.4 0.2 0.2 0.4 0 1C-0.2 0.4 -0.4 0.2 -1 0C-0.4 -0.2 -0.2 -0.4 0 -1Z" fill="#e2ba5e" stroke="#e2ba5e" stroke-width="0.05" stroke-linejoin="round"/>
18+ </svg>

brand/glimmer-icon.svg added

1+ <svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
2+ <title>Glimmer app icon (full-bleed square, for iPhone, iPad and the web)</title>
3+ <!-- Colors match the About panel mark in dark mode (CompanionMark in native/Glimmer/Design.swift):
4+ honey #e2ba5e at 28% and accent #9dbbdc at 20% over the surface #212120, ring in accent at 70%. -->
5+ <defs>
6+ <linearGradient id="bg" x1="0" y1="0" x2="1024" y2="1024" gradientUnits="userSpaceOnUse">
7+ <stop offset="0" stop-color="#574c31"/>
8+ <stop offset="1" stop-color="#3a4046"/>
9+ </linearGradient>
10+ </defs>
11+ <rect x="0" y="0" width="1024" height="1024" rx="0" fill="url(#bg)"/>
12+ <path d="M255.0 769.0A363.5 363.5 0 1 1 769.0 769.0" fill="none" stroke="#9dbbdc" stroke-opacity="0.7" stroke-width="46.1" stroke-linecap="round"/>
13+ <path transform="translate(512 512) scale(169.0)" d="M0 -1C0.2 -0.4 0.4 -0.2 1 0C0.4 0.2 0.2 0.4 0 1C-0.2 0.4 -0.4 0.2 -1 0C-0.4 -0.2 -0.2 -0.4 0 -1Z" fill="#e2ba5e" stroke="#e2ba5e" stroke-width="0.05" stroke-linejoin="round"/>
14+ </svg>

brand/glimmer-mark-round-1024.png added

Not a text file.

brand/render-icons.cjs added

1+ // Renders brand/glimmer-icon.svg into every app icon and site icon size.
2+ // Usage: node brand/render-icons.cjs (needs Playwright with Chromium, and ImageMagick for the .webp)
3+ const { chromium } = require('playwright');
4+ const fs = require('fs');
5+ const path = require('path');
6+ const { execFileSync } = require('child_process');
7+
8+ const root = path.resolve(__dirname, '..');
9+ const svg = fs.readFileSync(path.join(__dirname, 'glimmer-icon.svg'), 'utf8');
10+ const appicon = 'native/Glimmer/Assets.xcassets/AppIcon.appiconset';
11+ const targets = [
12+ [`${appicon}/Glimmer.png`, 1024],
13+ [`${appicon}/Glimmer-512.png`, 512],
14+ [`${appicon}/Glimmer-256.png`, 256],
15+ [`${appicon}/Glimmer-128.png`, 128],
16+ [`${appicon}/Glimmer-64.png`, 64],
17+ [`${appicon}/Glimmer-32.png`, 32],
18+ [`${appicon}/Glimmer-16.png`, 16],
19+ ['brand/glimmer-icon-1024.png', 1024],
20+ ['landing/img/icon-180.png', 180],
21+ ['landing/img/favicon.png', 64],
22+ ['assets/icon.png', 1024],
23+ ['assets/favicon.png', 48],
24+ ];
25+
26+ (async () => {
27+ const browser = await chromium.launch();
28+ const page = await browser.newPage();
29+ const src = `data:image/svg+xml;base64,${Buffer.from(svg).toString('base64')}`;
30+ for (const [out, size] of targets) {
31+ await page.setViewportSize({ width: size, height: size });
32+ await page.setContent(`<body style="margin:0"><img src="${src}" width="${size}" height="${size}" style="display:block"></body>`);
33+ await page.screenshot({ path: path.join(root, out) });
34+ console.log(out, size);
35+ }
36+ await browser.close();
37+ // The site header and footer use a 256 px WebP.
38+ execFileSync('convert', [path.join(root, 'brand/glimmer-icon-1024.png'), '-resize', '256x256', '-quality', '92',
39+ path.join(root, 'landing/img/icon.webp')]);
40+ console.log('landing/img/icon.webp 256');
41+ // Favicons: an SVG copy, and /favicon.ico (16, 32, 48) for browsers and search engines that ask for it.
42+ fs.copyFileSync(path.join(__dirname, 'glimmer-icon.svg'), path.join(root, 'landing/img/favicon.svg'));
43+ const ico = [16, 32, 48].map((s) => { const f = path.join(require('os').tmpdir(), `glimmer-fav-${s}.png`);
44+ execFileSync('convert', [path.join(root, 'brand/glimmer-icon-1024.png'), '-resize', `${s}x${s}`, f]); return f; });
45+ execFileSync('convert', [...ico, path.join(root, 'landing/favicon.ico')]);
46+ console.log('landing/img/favicon.svg, landing/favicon.ico');
47+ // The round mark: the 1024 icon PNG masked to a circle (no redrawing). The app's About, onboarding and Coach
48+ // use it as the AppMark image asset.
49+ const round = path.join(root, 'brand/glimmer-mark-round-1024.png');
50+ execFileSync('convert', [path.join(root, 'brand/glimmer-icon-1024.png'), '(', '-size', '1024x1024', 'xc:none', '-fill', 'white',
51+ '-draw', 'circle 512,512 512,0', ')', '-alpha', 'off', '-compose', 'CopyOpacity', '-composite', round]);
52+ execFileSync('convert', [round, '-resize', '384x384', path.join(root, 'native/Glimmer/Assets.xcassets/AppMark.imageset/AppMark.png')]);
53+ console.log('brand/glimmer-mark-round-1024.png, AppMark.png 384');
54+ // After changing the icon, bump the ?v= numbers on the icon links in site/partials/layout.html so browsers refetch.
55+ })();

docs/readme/app-icon.png added

Not a text file.

docs/readme/iphone-breakitdown-light.webp added

Not a text file.

docs/readme/iphone-coach-light.webp added

Not a text file.

docs/readme/iphone-today-dark.webp added

Not a text file.

docs/readme/iphone-toolkit-light.webp added

Not a text file.

docs/readme/mac-coach-light.webp added

Not a text file.

docs/readme/mac-plan-light.webp added

Not a text file.

docs/readme/mac-weekly-dark.webp added

Not a text file.

native/.gitignore added

1+ DerivedData/
2+ xcuserdata/
3+ *.xcuserstate

native/Checks/CoreChecks.swift added

1+ import Foundation
2+ import ImageIO
3+
4+ @main
5+ struct 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+ }

native/Checks/make-catalog.mjs added

1+ import { readFile, writeFile } from "node:fs/promises";
2+ import * as source from "../../src/data.ts";
3+
4+ const seed = await readFile(new URL("../../supabase/seed_lessons.sql", import.meta.url), "utf8");
5+ const fields = "'((?:[^']|'')*)'";
6+ const pattern = new RegExp(
7+ `\\(${fields}, (\\d+), ${fields}, ${fields}, ${fields}, (\\d+), ${fields}, ${fields}, ${fields}, \\$pg\\$(.*?)\\$pg\\$::jsonb, \\d+\\)`, "gs",
8+ );
9+ const unquote = (value) => value.replaceAll("''", "'");
10+ const lessons = [...seed.matchAll(pattern)].map(([, slug, number, arc, title, tagline, minutes, , hero, heroAlt, pages]) => ({
11+ slug, number: Number(number), arc: unquote(arc), title: unquote(title), tagline: unquote(tagline),
12+ minutes: Number(minutes), hero, heroAlt: unquote(heroAlt), pages: JSON.parse(pages),
13+ }));
14+ if (lessons.length !== 90 || lessons.some((item, index) => item.number !== index + 1)) {
15+ throw new Error("The original lesson catalog did not parse in full.");
16+ }
17+ // Keep native editorial changes reproducible without changing the original Expo curriculum.
18+ const editorial = JSON.parse(await readFile(new URL("../LibraryContent/Editorial.json", import.meta.url), "utf8"));
19+ for (const ids of [editorial.practiceTopics.map(topic => topic.id), editorial.practiceTopics.flatMap(topic => topic.exercises.map(practice => practice.id))]) {
20+ if (ids.some(id => typeof id !== "string" || !/^[a-z][a-z0-9_-]*$/.test(id)) || new Set(ids).size !== ids.length) {
21+ throw new Error("Coaching topics and practices each require unique, permanent identifiers.");
22+ }
23+ }
24+ for (const [number, update] of Object.entries(editorial.takeaways)) {
25+ const lesson = lessons.find(item => item.number === Number(number));
26+ const page = lesson?.pages.find(item => item.kind === "takeaway");
27+ if (!page || !update.body || !update.tryToday) throw new Error(`Invalid editorial takeaway for lesson ${number}`);
28+ page.body = `${update.body}\n\n**Try today:** ${update.tryToday}`;
29+ page.tryToday = update.tryToday;
30+ }
31+ // Deeper rewrites of existing lessons. IDs, numbers, page kinds and option counts stay
32+ // fixed because journals store answers by page position.
33+ for (const [number, edit] of Object.entries(editorial.lessonEdits ?? {})) {
34+ const lesson = lessons.find(item => item.number === Number(number));
35+ if (!lesson) throw new Error(`Lesson edit for missing lesson ${number}`);
36+ if (edit.pages) {
37+ if (edit.pages.length !== lesson.pages.length) throw new Error(`Lesson ${number} must keep ${lesson.pages.length} pages`);
38+ edit.pages.forEach((page, index) => {
39+ const original = lesson.pages[index];
40+ if (page.kind !== original.kind || (original.options?.length ?? 0) !== (page.options?.length ?? 0)) {
41+ throw new Error(`Lesson ${number} page ${index + 1} must keep its kind and option count`);
42+ }
43+ if (page.kind === "takeaway" && !page.tryToday) throw new Error(`Lesson ${number} takeaway needs tryToday`);
44+ });
45+ }
46+ Object.assign(lesson, Object.fromEntries(["arc", "title", "tagline", "minutes", "pages"].filter(key => edit[key] !== undefined).map(key => [key, edit[key]])));
47+ for (const page of lesson.pages) {
48+ if (page.kind === "takeaway" && page.tryToday && !page.body.includes("**Try today:**")) page.body = `${page.body}\n\n**Try today:** ${page.tryToday}`;
49+ }
50+ }
51+ // The Deep Path: lessons appended after the original 90.
52+ for (const extra of editorial.extraLessons ?? []) {
53+ if (extra.number !== lessons.length + 1 || lessons.some(item => item.slug === extra.slug)) throw new Error(`Extra lesson ${extra.slug} must be numbered ${lessons.length + 1} with a new slug`);
54+ if (!extra.title || !extra.arc || !extra.tagline || !(extra.minutes > 0) || !Array.isArray(extra.pages) || extra.pages.at(-1)?.kind !== "takeaway") {
55+ throw new Error(`Extra lesson ${extra.number} is incomplete`);
56+ }
57+ const pages = extra.pages.map(page => page.kind === "takeaway" && page.tryToday && !page.body.includes("**Try today:**")
58+ ? { ...page, body: `${page.body}\n\n**Try today:** ${page.tryToday}` } : page);
59+ lessons.push({ slug: extra.slug, number: extra.number, arc: extra.arc, title: extra.title, tagline: extra.tagline,
60+ minutes: extra.minutes, hero: null, heroAlt: null, pages });
61+ }
62+ const levels = new Set([1, 2, 3, 4, 5]);
63+ for (const practice of editorial.practiceTopics.flatMap(topic => topic.exercises)) {
64+ if (practice.level !== undefined && !levels.has(practice.level)) throw new Error(`Practice ${practice.id} has an invalid level`);
65+ }
66+ const challengeLevels = editorial.challengeLevels ?? {};
67+ const challenges = [...source.CHALLENGES.map(item => challengeLevels[item.id] ? { ...item, level: challengeLevels[item.id] } : item),
68+ ...(editorial.challenges ?? [])];
69+ if (new Set(challenges.map(item => item.id)).size !== challenges.length
70+ || challenges.some(item => item.level !== undefined && !levels.has(item.level))
71+ || challenges.some(item => !item.title || !item.sub || !(item.mins > 0) || !(item.coins > 0) || item.teach?.length < 1 || !item.q || item.opts?.length < 2 || !item.action || !item.done)) {
72+ throw new Error("Challenges need unique IDs, a valid level and every page");
73+ }
74+ // Apps added for the native app, placed after a named original source.
75+ const sources = source.SOURCES.map(({ name }) => name);
76+ const tags = Object.fromEntries(source.SOURCES.map(({ name }) => [name, source.contentTypesFor(name)]));
77+ for (const added of editorial.sources ?? []) {
78+ if (!added.name || !Array.isArray(added.tags) || sources.includes(added.name)) throw new Error(`Invalid editorial source ${added.name}`);
79+ const position = sources.indexOf(added.after);
80+ sources.splice(position < 0 ? sources.length : position + 1, 0, added.name);
81+ tags[added.name] = added.tags;
82+ }
83+ const catalog = {
84+ sources,
85+ activities: [...source.ACT_POOL, ...(editorial.activities ?? [])],
86+ people: source.PPL_POOL,
87+ tags,
88+ defaultTags: source.contentTypesFor(""),
89+ initialTasks: source.INITIAL_TASKS,
90+ library: source.TASK_LIBRARY,
91+ preload: source.PRELOAD_SUGGESTIONS,
92+ onboarding: source.ONB_STEPS.map(step => step.key === "primary_goal" ? {
93+ ...step, mode: "multi", kicker: "Your goals", title: "What would you like help with?", sub: "Choose all that apply.",
94+ } : step),
95+ challenges,
96+ energy: source.ENERGY_DEFS,
97+ energyMessages: source.ENERGY_MSGS,
98+ habits: source.HABIT_DATA,
99+ cleaning: source.CLEAN_DATA,
100+ seasonal: editorial.seasonal,
101+ quotes: editorial.quotes,
102+ coach: editorial.coach,
103+ startingPractices: editorial.startingPractices,
104+ practiceTopics: editorial.practiceTopics,
105+ praise: source.PRAISE,
106+ lessons,
107+ };
108+ await writeFile(new URL("../LibraryContent/Catalog.json", import.meta.url), JSON.stringify(catalog, null, 2) + "\n");

native/DESIGN-REVIEW.md added

1+ # Glimmer native UI: design review and redesign (2026-11-14)
2+
3+ This records two passes. The first pass fixed structure but was still loud. The second pass, after the owner's feedback about blue buttons and overpowering UI, is what the app looks like now.
4+
5+ ## What was wrong
6+
7+ ### The original UI
8+
9+ 1. Content cards, buttons and backgrounds all used the same pale translucent treatment, so nothing told you what you could touch.
10+ 2. Every screen was a stack of equally weighted cards. Today gave the check-in, stats, lesson, plan and settings links the same weight.
11+ 3. Mac and iPad stretched the iPhone column.
12+ 4. The primary action in each flow scrolled away, and Cancel, Back and Continue moved between steps.
13+ 5. Washed-out art, and a penguin mascot that is not approved.
14+
15+ ### The first redesign pass
16+
17+ 1. **Too much blue.** Every primary action was a full-width saturated blue bar. Selected segments, step bars, toolbar icons and several secondary buttons were blue as well.
18+ 2. **Oversized controls.** Rows were 60pt tall slabs with icon badges. Chips, check buttons and the action bar were all at the largest control size.
19+ 3. **Cards inside cards.** Glass rows sat inside bordered panels on a gradient page, so most screens had three nested outlines.
20+ 4. **Decoration without meaning.** Uppercase tracked labels sat above every section in five different colours. Four coloured statistics repeated numbers shown elsewhere on Today. Sidebar icons were five colours.
21+ 5. **Generic look.** Cream gradient, serif headlines everywhere and a placeholder mascot badge on four screens.
22+
23+ ## The design now
24+
25+ **Paper for reading, glass for touching, and very little colour.**
26+
27+ - **Colour is kept for meaning.**
28+ - The main action on a screen is ink (near-black in light mode, warm white in dark mode). There is one per screen.
29+ - Every other button is neutral Liquid Glass with a primary-colour label.
30+ - Soft blue appears only for selection: a chosen chip or option, a toggle, the selected segment, and the aftertaste dial.
31+ - Sage and honey appear only for progress and for the held or slipped check-ins.
32+ - **Type.** SF for the whole interface, in sentence case, with quiet grey section headings. New York serif is kept for the journal's own voice: the line of the day on Today and the word on the dial.
33+ - **Surfaces.** A flat warm-grey page. Reading content (lessons, charts, summaries) sits on plain paper panels with a hairline and no shadow. Groups of rows sit directly on the page with a small heading, not inside another card.
34+ - **Smaller controls.** Rows, chips and buttons are regular size. On Mac the action bar is a normal trailing button group. On iPhone the primary action is one thumb-width button.
35+ - **Less on each screen.**
36+ - The repeated statistics strip on Today is gone.
37+ - Sidebar and row icons are monochrome.
38+ - The placeholder mascot mark is removed everywhere except About, where it is labelled as temporary in the code.
39+ - On Mac and iPad, Today no longer repeats the sidebar's links.
40+ - **Layout per device.** Mac and iPad use a sidebar with two-column grids where the content suits it. iPhone uses a tab bar that minimizes on scroll, and focused flows hide it.
41+
42+ ## Tactile pass (2026-11-24)
43+
44+ the owner's feedback on 1.1.2: checking off habits lost its animation, the Habits checklist was crowded and not inviting to tap, the mood row was "horrible UI, nobody wants buttons", and the app "starts feeling like a form". This pass keeps the paper, glass and ink rules above and adds one more.
45+
46+ **Things you touch answer like objects.** They give under a finger, settle with a small spring and confirm with a tap you can feel. The shared pieces are in `Tactile.swift` and `MoodSky.swift`.
47+
48+ - **One tick everywhere.** `Tick` replaces the mix of small circles, squares and trailing check symbols. It sits on the leading edge in a 44 point target (`TickButton`). Checking it fills the ring in sage with a spring, draws the check as a stroke and lets a ring of light leave it. Unchecking is quick and plain. Done lines dim instead of being struck through.
49+ - **Feel.** `tickFeedback` plays a success tap on iPhone and iPad and a trackpad click on Mac (`NSHapticFeedbackManager`). Ticks that only include or select something use the lighter selection tap.
50+ - **Habit stones.** Each habit is a round stone you press. Its rim is the last seven days, with today as the last arc. Pressing it lights today's arc, the icon hops and a ring leaves the stone. A full week turns the rim honey.
51+ - **Mood sky.** Today's mood is a small sky. Drag or tap the sun along its path: rain thins to cloud, cloud parts and the light warms through Low, Off, Okay, Good and Great, with a tick at each stop. It saves when the sun lands. VoiceOver reads it as one adjustable control, and arrow keys move it on Mac. A vertical swipe that starts on the sky still scrolls the page.
52+ - **The coin celebration is unchanged.** Row motion finishes in about 0.4 seconds, before `CoinBurst` and the earned-coins toast start, so the two never compete. Check-offs still go through `toggleTask`, `toggleHabit` and `setPersonalTodoDone`.
53+ - **Fewer form controls.**
54+ - Plan drops the boxed progress card, the tracker picker (it stays in Settings), the "Show all scheduled tasks" switch and the outlined add buttons. Tasks are plain lines with the tick first. The praise line under the progress bar has its own place, so the list never moves under a finger.
55+ - New tasks and to-dos are written on the next line of the list, marked with a dashed tick.
56+ - Weigh it and Unload add lines the same way instead of with outlined buttons.
57+ - The energy dial sits straight on the page, and the line under it answers as the dial turns.
58+ - **Calmer lists.** Rows are 44 points tall on iPhone and iPad, light softly under the finger and have quieter dividers. A row that ends in a tick shows selection with the tick alone, without a tinted fill.
59+ - **Month.** Days are plain numbers until they are done, then sage stones. Today has a ring.
60+ - **Reduce Motion.** Springs, hops, ripples, rain and the sun's glide are all dropped. Ticks and the sky change with a short fade, and the haptics stay.
61+
62+ ## Screen and control coverage
63+
64+ Key for the 26+ column:
65+
66+ - **G** = custom Liquid Glass drawn with `glassEffect(.regular.interactive())`
67+ - **GP** = `.buttonStyle(.glassProminent)` in ink
68+ - **GC** = grouped with `GlassEffectContainer`
69+ - **Sys** = a system control, which already gets Liquid Glass from the OS on 26+ and is not double-glassed
70+
71+ Before 26, custom glass falls back to `.regularMaterial` with a hairline border, or an opaque surface when Reduce Transparency is on. The prominent style falls back to `.borderedProminent`. This was checked on an iOS 18.5 simulator.
72+
73+ | Area | Controls | 26+ | Before 26 |
74+ |---|---|---|---|
75+ | Toolbar (Mac, iPad, iPhone) | Check in, Quick actions menu, Log a moment | Sys toolbar glass | toolbar buttons |
76+ | Sidebar and tabs | Split-view sidebar, iPhone tab bar | Sys | Sys |
77+ | Today | Check-in rows, lesson row, plan row | G rows (GC) | material rows |
78+ | Onboarding (14 steps) | Back, option rows, name field, Continue / Start my plan | G icon button, G rows (blue tint when selected), GP in the pinned bar | material, borderedProminent |
79+ | Log a moment | Source chips, Add, date picker, tag chips, dial, slider, decision picker, Cancel / Back / Continue / Save | G chips, G dial knob, Sys slider, date picker and segmented picker, G Cancel and Back, GP primary | material, borderedProminent |
80+ | Energy check-in | Dial, slider, Cancel, Set today's energy | same as logging | same |
81+ | Insights | Alignment, trend chart, input mix, platform disclosure, today's logs | Paper panels for reading, Sys disclosure | same |
82+ | Weekly | Inputs, pattern, on-device reflection button, suggested experiments | G button, G rows | material |
83+ | Coach | Start the review, Held / Slipped, Design it together, Keep watching, experiment rows, links | G buttons (GC for pairs), G rows | material |
84+ | Experiment review | Outcome rows | G rows | material |
85+ | Plan | Progress line, show-all link, task lines with a leading tick and edit, quick add line, New scheduled task, links | Tick, plain lines on a paper panel | same |
86+ | Task editor | Name, emoji icons, date, repeat toggle, frequency, weekday chips, Cancel / Delete / Save | G icon circles and chips, Sys pickers and toggle, GP save | material, borderedProminent |
87+ | Task library, Suggestions | Category rows, selectable suggestion rows, Add to my plan | G rows, GP | material |
88+ | Habits | Today / Month picker, habit stones, mood sky, month navigation and day stones | G segmented, stones and sky drawn in SwiftUI, G icon buttons | same |
89+ | Tiny wins | Start rows, steps, timer Start / Stop, feedback chips, primary action | G rows, G buttons and chips, GP | material |
90+ | Lessons | Lesson rows, reader Previous / Next / Complete, reflection choices | G rows, G icon button, GP | material |
91+ | Cleaning | Lists, rooms, session task rows | G rows | material |
92+ | Settings | Name and Save name, tracker picker, backup and restore rows, Mac agent toggle and copy buttons | Sys field, picker and toggle, G buttons and rows | material |
93+ | About, ratings and support | Link rows, share, Review (disabled with no App Store ID), free support, Done | G rows and buttons | material |
94+ | Notices | Saved and award toast | G capsule | material capsule |
95+ | Toolkit | Step size stones, tool rows in four short lists (Get started, Get it done, Say it, Decide) | G stones, G rows (GC) | material |
96+ | Unload, Break it down, Time check | Brain-dump editor, editable suggestion rows with include checks and due chips, step editor with Try again and Undo, focus segments, estimate stepper, one ink primary | G rows and chips, Sys segmented and stepper, GP | material, borderedProminent |
97+ | One thing | Full-screen cover on iPhone and iPad (sheet on Mac): to-do title, step dots, large next step, optional timer with stepper, More menu, Done | G icon button, Sys stepper, GP Done | material |
98+ | Read the room, Reword, Weigh it | Direction segments, text editors, tone chips, result panels with Copy / Use this / Share, editable For, Against and Still unknown lists, Try it for 7 days | Sys segmented, G chips and buttons, GP | material |
99+
100+ ### Accessibility
101+
102+ - **Reduce Transparency.** Custom glass becomes an opaque surface. System glass follows the OS setting.
103+ - **Increase Contrast.** Panel borders get stronger, and labels use the semantic primary and secondary colours.
104+ - **Reduce Motion.** The dial value animation is switched off, and onboarding uses a plain fade instead of a push transition.
105+ - **VoiceOver.**
106+ - The dial is an adjustable element, and the slider is labelled.
107+ - Task checks are labelled "Complete <task>" or "Uncheck <task>".
108+ - Selected chips and rows carry the selected trait.
109+ - The accessibility identifiers used by the UI tests are unchanged.
110+ - **Toolkit (2026-11-24).**
111+ - Step size is one adjustable element ("Step size", value "Balanced"); swipe up or down to change it. At accessibility text sizes the chosen size moves to its own line instead of hyphenating.
112+ - Every Toolkit result carries a combined source label ("Suggested on this device", "Suggested by your writing agent", "From Glimmer’s offline guide").
113+ - The One thing step is a header, the timer reads as minutes and seconds left, and step progress is spoken as "2 of 7 steps done". Reduce Motion drops the step change animation.
114+ - Tone chips that need a model are dimmed and disabled when none is available, with a footnote saying why.
115+ - The sheet Cancel button is an explicit xmark icon labelled Cancel, fixing a clipped glyph on iOS 26.
116+ - Creative director pass (Gemini Carbon, two rounds on real renders): tool pages hide the tab bar like other focused flows; row and list icons are monochrome; text fields sit straight on the panel's paper; Step size moved below the tools; Reword shows its result under the message, tones scroll in one row (offline tones first), and Copy is the main action once there is a result; Read the room's main action disappears once read and returns when the message changes; Weigh it lists use plain plus, minus and question marks with an "Add your own" button; the One thing card is full screen with sage progress and the timer unboxed.
117+ - **Keyboard (Mac).** ⌘⇧E checks in, ⌘⇧L logs a moment, Return activates the primary action in a flow, and Escape cancels a sheet.
118+
119+ ## What did not change
120+
121+ These are all unchanged:
122+
123+ - The journal model, persistence, backup and restore
124+ - Recurrence, awards and unlocks
125+ - The catalog, including the 50 lessons, 66 illustrations and editorial changes
126+ - The rule-based coach and the optional on-device reflection
127+ - MCP consent, revocation and data exclusions
128+ - The review request after five logs, with no fake review link
129+
130+ No analytics, accounts or network calls were added, and the minimum OS versions are still macOS 15 and iOS 18.
131+
132+ ## Debug-only review hooks
133+
134+ These only run in Debug builds, and only when `GLIMMER_TEST_JOURNAL` is set, so they never touch a real journal:
135+
136+ - `GLIMMER_SCREEN`
137+ - `GLIMMER_FLOW`
138+ - `GLIMMER_LOG_STEP`
139+ - `GLIMMER_DETAIL`
140+ - `GLIMMER_APPEARANCE`
141+ - `GLIMMER_TOOLKIT_TEXT`, `GLIMMER_UNLOAD_TEXT`, `GLIMMER_TOOLKIT_AUTORUN` and `GLIMMER_TEST_TOOLKIT_MODEL` (Toolkit inputs; see README)

native/Glimmer.xcconfig added

1+ PRODUCT_NAME = Glimmer
2+ PRODUCT_BUNDLE_IDENTIFIER = com.protomota.glimmer
3+ // Glimmer: Gentle Life Coach on the App Store, for the rating prompt and the Rate row.
4+ GLIMMER_APP_STORE_ID = 6837750690
5+ MARKETING_VERSION = 1.1.10
6+ CURRENT_PROJECT_VERSION = 55
7+ SUPPORTED_PLATFORMS = macosx iphoneos iphonesimulator
8+ SDKROOT = auto
9+ IPHONEOS_DEPLOYMENT_TARGET = 18.0
10+ MACOSX_DEPLOYMENT_TARGET = 15.0
11+ TARGETED_DEVICE_FAMILY = 1,2
12+ SUPPORTS_MACCATALYST = NO
13+ SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO
14+ SWIFT_VERSION = 5.0
15+ GENERATE_INFOPLIST_FILE = YES
16+ INFOPLIST_KEY_CFBundleDisplayName = Glimmer
17+ INFOPLIST_KEY_LSApplicationCategoryType = public.app-category.lifestyle
18+ INFOPLIST_KEY_UILaunchScreen_Generation = YES
19+ INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO
20+ INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES
21+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight
22+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight
23+ INFOPLIST_FILE = Glimmer/Info.plist
24+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon
25+ // The Mac installer window's artwork ships inside the Mac app only (native/installer).
26+ EXCLUDED_SOURCE_FILE_NAMES[sdk=iphone*] = installer-background.tiff AgentSkillInstaller.swift AgentSkillSection.swift AgentSkill.md AgentSkill-LICENSE.txt
27+ CODE_SIGN_STYLE = Automatic
28+ // The Mac release script sets this to the Developer ID profile name when it signs manually.
29+ PROVISIONING_PROFILE_SPECIFIER[sdk=macosx*] = $(GLIMMER_RELEASE_PROFILE)
30+ // The TestFlight script sets this to the App Store profile name.
31+ PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*] = $(GLIMMER_IOS_RELEASE_PROFILE)
32+ DEVELOPMENT_TEAM[config=Release] = 22HV69L32T
33+ DEVELOPMENT_TEAM[sdk=iphoneos*] = 22HV69L32T
34+ GLIMMER_MAC_ENTITLEMENTS = Glimmer/Glimmer.entitlements
35+ GLIMMER_MAC_ENTITLEMENTS[config=Debug] = Glimmer/Glimmer-Mac-Local.entitlements
36+ CODE_SIGN_ENTITLEMENTS[sdk=macosx*] = $(GLIMMER_MAC_ENTITLEMENTS)
37+ ENABLE_HARDENED_RUNTIME[sdk=macosx*] = YES
38+ LD_RUNPATH_SEARCH_PATHS = $(inherited) @executable_path/Frameworks
39+ LD_RUNPATH_SEARCH_PATHS[sdk=macosx*] = $(inherited) @executable_path/../Frameworks
40+
41+ // Mac updates from glimmertoday.ai (Sparkle). The matching private key is in the release Mac's Keychain.
42+ GLIMMER_UPDATE_FEED[sdk=macosx*] = https:/$()/glimmertoday.ai/updates/appcast.xml
43+ GLIMMER_UPDATE_PUBLIC_KEY[sdk=macosx*] = om45onKg31JK17EPzqmoFKHqMseRnh+43KR4UPdA3tI=

native/Glimmer.xcodeproj/project.pbxproj added

1+ // !$*UTF8*$!
2+ {
3+ archiveVersion = 1;
4+ classes = {};
5+ objectVersion = 77;
6+ objects = {
7+ AA0000000000000000000001 = {isa = PBXProject; attributes = {BuildIndependentTargetsInParallel = YES; LastSwiftUpdateCheck = 2600; LastUpgradeCheck = 2600; }; buildConfigurationList = AA000000000000000000000A; compatibilityVersion = "Xcode 16.0"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = (en, Base); mainGroup = AA0000000000000000000002; productRefGroup = AA0000000000000000000004; projectDirPath = ""; projectRoot = ""; packageReferences = (AA0000000000000000000030); targets = (AA0000000000000000000005, AA0000000000000000000021); };
8+ AA0000000000000000000002 = {isa = PBXGroup; children = (AA0000000000000000000003, AA0000000000000000000004, AA0000000000000000000010, AA0000000000000000000013, AA0000000000000000000022); sourceTree = "<group>"; };
9+ AA0000000000000000000003 = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (AA0000000000000000000012); path = Glimmer; sourceTree = "<group>"; };
10+ AA0000000000000000000004 = {isa = PBXGroup; children = (AA0000000000000000000006, AA0000000000000000000023); name = Products; sourceTree = "<group>"; };
11+ AA0000000000000000000005 = {isa = PBXNativeTarget; buildConfigurationList = AA000000000000000000000B; buildPhases = (AA0000000000000000000007, AA0000000000000000000008, AA0000000000000000000009); buildRules = (); dependencies = (); fileSystemSynchronizedGroups = (AA0000000000000000000003); name = Glimmer; packageProductDependencies = (AA0000000000000000000031); productName = Glimmer; productReference = AA0000000000000000000006; productType = "com.apple.product-type.application"; };
12+ AA0000000000000000000006 = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Glimmer.app; sourceTree = BUILT_PRODUCTS_DIR; };
13+ AA0000000000000000000007 = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
14+ AA0000000000000000000008 = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (AA0000000000000000000032); runOnlyForDeploymentPostprocessing = 0; };
15+ AA0000000000000000000009 = {isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = (AA0000000000000000000011); runOnlyForDeploymentPostprocessing = 0; };
16+ AA000000000000000000000A = {isa = XCConfigurationList; buildConfigurations = (AA000000000000000000000C, AA000000000000000000000D); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };
17+ AA000000000000000000000B = {isa = XCConfigurationList; buildConfigurations = (AA000000000000000000000E, AA000000000000000000000F); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };
18+ AA000000000000000000000C = {isa = XCBuildConfiguration; buildSettings = { CLANG_ENABLE_MODULES = YES; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_TESTABILITY = YES; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; }; name = Debug; };
19+ AA000000000000000000000D = {isa = XCBuildConfiguration; buildSettings = { CLANG_ENABLE_MODULES = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; SWIFT_COMPILATION_MODE = wholemodule; }; name = Release; };
20+ AA000000000000000000000E = {isa = XCBuildConfiguration; baseConfigurationReference = AA0000000000000000000013; buildSettings = {"CODE_SIGN_ENTITLEMENTS[sdk=iphoneos*]" = Glimmer/Glimmer-iOS.entitlements; }; name = Debug; };
21+ AA000000000000000000000F = {isa = XCBuildConfiguration; baseConfigurationReference = AA0000000000000000000013; buildSettings = {"CODE_SIGN_ENTITLEMENTS[sdk=iphoneos*]" = Glimmer/Glimmer-iOS.entitlements; }; name = Release; };
22+ AA0000000000000000000010 = {isa = PBXFileReference; lastKnownFileType = folder; name = LibraryContent; path = LibraryContent; sourceTree = "<group>"; };
23+ AA0000000000000000000011 = {isa = PBXBuildFile; fileRef = AA0000000000000000000010; };
24+ AA0000000000000000000012 = {isa = PBXFileSystemSynchronizedBuildFileExceptionSet; membershipExceptions = (Glimmer.entitlements, "Glimmer-Mac-Local.entitlements", "Glimmer-Mac-Direct.entitlements", "Glimmer-iOS.entitlements", Info.plist); target = AA0000000000000000000005; };
25+ AA0000000000000000000013 = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Glimmer.xcconfig; sourceTree = "<group>"; };
26+
27+ AA0000000000000000000021 = {isa = PBXNativeTarget; buildConfigurationList = AA0000000000000000000028; buildPhases = (AA0000000000000000000024, AA0000000000000000000025, AA0000000000000000000026); buildRules = (); dependencies = (AA0000000000000000000027); fileSystemSynchronizedGroups = (AA0000000000000000000022); name = GlimmerUITests; productName = GlimmerUITests; productReference = AA0000000000000000000023; productType = "com.apple.product-type.bundle.ui-testing"; };
28+ AA0000000000000000000022 = {isa = PBXFileSystemSynchronizedRootGroup; path = GlimmerUITests; sourceTree = "<group>"; };
29+ AA0000000000000000000023 = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GlimmerUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
30+ AA0000000000000000000024 = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
31+ AA0000000000000000000025 = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
32+ AA0000000000000000000026 = {isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
33+ AA0000000000000000000027 = {isa = PBXTargetDependency; target = AA0000000000000000000005; targetProxy = AA000000000000000000002B; };
34+ AA0000000000000000000028 = {isa = XCConfigurationList; buildConfigurations = (AA0000000000000000000029, AA000000000000000000002A); defaultConfigurationIsVisible = 0; defaultConfigurationName = Debug; };
35+ AA0000000000000000000029 = {isa = XCBuildConfiguration; baseConfigurationReference = AA0000000000000000000013; buildSettings = {GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = ""; "CODE_SIGN_ENTITLEMENTS[sdk=macosx*]" = ""; "ENABLE_HARDENED_RUNTIME[sdk=macosx*]" = NO; ASSETCATALOG_COMPILER_APPICON_NAME = ""; PRODUCT_NAME = GlimmerUITests; PRODUCT_BUNDLE_IDENTIFIER = com.protomota.glimmer.UITests; TEST_TARGET_NAME = Glimmer; }; name = Debug; };
36+ AA000000000000000000002A = {isa = XCBuildConfiguration; baseConfigurationReference = AA0000000000000000000013; buildSettings = {GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = ""; "CODE_SIGN_ENTITLEMENTS[sdk=macosx*]" = ""; "ENABLE_HARDENED_RUNTIME[sdk=macosx*]" = NO; ASSETCATALOG_COMPILER_APPICON_NAME = ""; PRODUCT_NAME = GlimmerUITests; PRODUCT_BUNDLE_IDENTIFIER = com.protomota.glimmer.UITests; TEST_TARGET_NAME = Glimmer; }; name = Release; };
37+ AA000000000000000000002B = {isa = PBXContainerItemProxy; containerPortal = AA0000000000000000000001; proxyType = 1; remoteGlobalIDString = AA0000000000000000000005; remoteInfo = Glimmer; };
38+ AA0000000000000000000030 = {isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/sparkle-project/Sparkle"; requirement = {kind = upToNextMajorVersion; minimumVersion = 2.10.0; }; };
39+ AA0000000000000000000031 = {isa = XCSwiftPackageProductDependency; package = AA0000000000000000000030; productName = Sparkle; };
40+ AA0000000000000000000032 = {isa = PBXBuildFile; platformFilters = (macos, ); productRef = AA0000000000000000000031; };
41+ };
42+ rootObject = AA0000000000000000000001;
43+ }

native/Glimmer.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved added

1+ {
2+ "originHash" : "e721da7f9826abdffcb6185e886155efa2514bd6234475f1afa893e29eb258d6",
3+ "pins" : [
4+ {
5+ "identity" : "sparkle",
6+ "kind" : "remoteSourceControl",
7+ "location" : "https://github.com/sparkle-project/Sparkle",
8+ "state" : {
9+ "revision" : "ab7d71291238df6e0492143b120c9b696a35f603",
10+ "version" : "2.10.1"
11+ }
12+ }
13+ ],
14+ "version" : 3
15+ }

native/Glimmer.xcodeproj/xcshareddata/xcschemes/Glimmer.xcscheme added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <Scheme LastUpgradeVersion="2600" version="1.7">
3+ <BuildAction parallelizeBuildables="YES" buildImplicitDependencies="YES">
4+ <BuildActionEntries><BuildActionEntry buildForTesting="YES" buildForRunning="YES" buildForProfiling="YES" buildForArchiving="YES" buildForAnalyzing="YES">
5+ <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="AA0000000000000000000005" BuildableName="Glimmer.app" BlueprintName="Glimmer" ReferencedContainer="container:Glimmer.xcodeproj"/>
6+ </BuildActionEntry></BuildActionEntries>
7+ </BuildAction>
8+ <TestAction buildConfiguration="Debug" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.DebuggerFoundation.Launcher.LLDB">
9+ <Testables><TestableReference skipped="NO" parallelizable="NO"><BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="AA0000000000000000000021" BuildableName="GlimmerUITests.xctest" BlueprintName="GlimmerUITests" ReferencedContainer="container:Glimmer.xcodeproj"/></TestableReference></Testables>
10+ </TestAction>
11+ <LaunchAction buildConfiguration="Debug" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.DebuggerFoundation.Launcher.LLDB" launchStyle="0" useCustomWorkingDirectory="NO" ignoresPersistentStateOnLaunch="NO" debugDocumentVersioning="YES" allowLocationSimulation="YES">
12+ <BuildableProductRunnable runnableDebuggingMode="0">
13+ <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="AA0000000000000000000005" BuildableName="Glimmer.app" BlueprintName="Glimmer" ReferencedContainer="container:Glimmer.xcodeproj"/>
14+ </BuildableProductRunnable>
15+ </LaunchAction>
16+ <ProfileAction buildConfiguration="Release" useCustomWorkingDirectory="NO">
17+ <BuildableProductRunnable runnableDebuggingMode="0">
18+ <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="AA0000000000000000000005" BuildableName="Glimmer.app" BlueprintName="Glimmer" ReferencedContainer="container:Glimmer.xcodeproj"/>
19+ </BuildableProductRunnable>
20+ </ProfileAction>
21+ <AnalyzeAction buildConfiguration="Debug"/>
22+ <ArchiveAction buildConfiguration="Release" revealArchiveInOrganizer="YES"/>
23+ </Scheme>

native/Glimmer/AgentAccess.swift added

1+ #if os(macOS)
2+ import CoreFoundation
3+ import Foundation
4+
5+ /// Glimmer's local MCP server. An agent launches the app executable with `--mcp`, which reads and
6+ /// writes the journal on this Mac and never opens a window. Glimmer's Settings decides what it may do.
7+ enum AgentAccess {
8+ static let argument = "--mcp"
9+ static let marker = "AllowAgentSummaries"
10+ static let changesMarker = "AllowAgentChanges"
11+ static let activityFile = "AgentActivity.json"
12+ static let checkClient = "Glimmer connection check"
13+ static var version: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "1.0" }
14+
15+ enum Level: Equatable {
16+ case off, summaries, changes
17+ }
18+
19+ static func level(in directory: URL) -> Level {
20+ let manager = FileManager.default
21+ guard manager.fileExists(atPath: directory.appending(path: marker).path) else { return .off }
22+ return manager.fileExists(atPath: directory.appending(path: changesMarker).path) ? .changes : .summaries
23+ }
24+
25+ static let instructions = """
26+ Glimmer is a private, neurodivergent-friendly spiritual life coach for deep thinkers and anyone too busy thinking to stay organized, with daily reflections and a journal on this Mac. People log moments (an app, activity or person) with an aftertaste \
27+ from -2 (drained) to +2 (nourished), check off a daily plan, record energy and run 7-day experiments.
28+ Glimmer Settings → Agent access controls this server. "Share read-only summaries" allows summaries, get_daily_glimmer and list_practices. \
29+ "Let agents log and check off" also allows get_today and the tools that change the journal.
30+ For a daily dashboard, call get_daily_glimmer with no arguments on the person's chosen schedule using their Mac time zone. \
31+ Upsert the dashboard card by day_id and an external practice task by task_id. Use list_practices to choose another exercise. \
32+ If the person wants it on their plan, call save_practice with the practice_id and day. After the person confirms they did it, \
33+ call set_task_done with that task_id, the same day, and done=true. A read never marks the task complete. Scheduling belongs to the client. \
34+ For personal to-dos use list_personal_todos, add_personal_todo and set_personal_todo_done. These are separate from the coaching plan. \
35+ A to-do can carry small steps (with one level of smaller steps) and a time estimate in minutes. Pass steps and estimate_minutes to add_personal_todo, \
36+ or replace a to-do's steps later with set_todo_steps. Keep each step short and start it with a verb. \
37+ Only set a reminder time when requested. Glimmer schedules device-local reminders after it reads the saved task, if notifications are allowed on that device. \
38+ For other plan tasks call get_today first and use the IDs it returns. Log a moment only when the person \
39+ describes it or asks you to, using their own rating. Summaries describe self-reported patterns; they are not medical advice.
40+ Setup: Claude Code uses Glimmer's Save Project Connection in Settings → Agent access, Codex uses a STDIO server with the \
41+ command and argument Glimmer shows, Gemini CLI uses a project .gemini/settings.json, and Claude chat uses the Glimmer.mcpb extension saved from the same place.
42+ """
43+
44+ @MainActor
45+ static func run() {
46+ let bundled = AppResources.url("Catalog", extension: "json").flatMap { try? Catalog.load(from: $0) }
47+ let content = bundled.map { EditorialLibrary(bundled: $0) }
48+ let session = Session(journal: JournalStore.storageURL, catalog: content?.edition?.content ?? bundled)
49+ while let line = readLine() {
50+ guard let response = session.handle(line) else { continue }
51+ send(response)
52+ }
53+ }
54+
55+ private static func send(_ response: [String: Any]) {
56+ guard let data = try? JSONSerialization.data(withJSONObject: response) else { return }
57+ FileHandle.standardOutput.write(data + Data([10]))
58+ }
59+
60+ @MainActor
61+ final class Session {
62+ private let journal: URL
63+ private let catalog: Catalog?
64+ private var initialized = false
65+ private var client = "An agent"
66+
67+ init(journal: URL, catalog: Catalog? = AppResources.url("Catalog", extension: "json").flatMap { try? Catalog.load(from: $0) }) {
68+ self.journal = journal
69+ self.catalog = catalog
70+ }
71+
72+ private var directory: URL { journal.deletingLastPathComponent() }
73+
74+ /// Answers one JSON-RPC line. Notifications get no answer.
75+ func handle(_ line: String) -> [String: Any]? {
76+ guard let data = line.data(using: .utf8),
77+ let request = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
78+ return error(NSNull(), -32700, "Invalid JSON")
79+ }
80+ guard request["jsonrpc"] as? String == "2.0", let method = request["method"] as? String else {
81+ return error(request["id"] ?? NSNull(), -32600, "Invalid Request")
82+ }
83+ guard let id = request["id"] else { return nil }
84+ let params = request["params"] as? [String: Any] ?? [:]
85+ switch method {
86+ case "initialize":
87+ let supported = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]
88+ let requested = params["protocolVersion"] as? String ?? ""
89+ if let info = params["clientInfo"] as? [String: Any], let name = info["name"] as? String, !name.isEmpty {
90+ client = String(String.UnicodeScalarView(name.unicodeScalars.filter { !CharacterSet.controlCharacters.contains($0) }).prefix(80))
91+ }
92+ initialized = true
93+ if client != AgentAccess.checkClient { recordActivity(tool: nil) }
94+ return result(id, [
95+ "protocolVersion": supported.contains(requested) ? requested : supported[0],
96+ "capabilities": ["tools": [:]],
97+ "serverInfo": ["name": "glimmer", "title": "Glimmer", "version": AgentAccess.version],
98+ "instructions": AgentAccess.instructions
99+ ])
100+ case "ping":
101+ return result(id, [:])
102+ case "tools/list" where initialized:
103+ return result(id, ["tools": AgentAccess.tools])
104+ case "tools/call" where initialized:
105+ return result(id, call(params))
106+ default:
107+ return error(id, -32601, "Method not available")
108+ }
109+ }
110+
111+ private func call(_ params: [String: Any]) -> [String: Any] {
112+ guard let name = params["name"] as? String, let tool = Tool(rawValue: name) else {
113+ return failure("Unknown Glimmer tool.")
114+ }
115+ guard let arguments = (params["arguments"] ?? [:]) as? [String: Any] else {
116+ return failure("Provide a JSON object for tool arguments.")
117+ }
118+ let level = AgentAccess.level(in: directory)
119+ guard level != .off else {
120+ return failure("Agent access is off. Open Glimmer → Settings → Agent access and turn on Share read-only summaries.")
121+ }
122+ guard !tool.needsChanges || level == .changes else {
123+ return failure("This needs Glimmer → Settings → Agent access → Let agents log and check off. Ask the person to turn it on.")
124+ }
125+ let store = JournalStore(url: journal, catalogURL: nil)
126+ guard store.loadError == nil, store.journal.onboardingComplete else {
127+ return failure("Finish Glimmer setup on this Mac first.")
128+ }
129+ let outcome = run(tool, arguments, store: store)
130+ if outcome["isError"] == nil && client != AgentAccess.checkClient { recordActivity(tool: name) }
131+ return outcome
132+ }
133+
134+ private func run(_ tool: Tool, _ arguments: [String: Any], store: JournalStore) -> [String: Any] {
135+ let now = Date()
136+ store.day = now
137+ switch tool {
138+ case .attention:
139+ guard Set(arguments.keys).isSubset(of: ["days"]), let days = integer(arguments["days"] ?? 7), (1...30).contains(days) else {
140+ return failure("Provide a whole number of days between 1 and 30.")
141+ }
142+ return AgentAccess.attentionSummary(store.journal, days: days, now: now)
143+ case .plan:
144+ guard arguments.isEmpty else { return failure("This tool does not accept arguments.") }
145+ return AgentAccess.planSummary(store.journal, now: now)
146+ case .daily:
147+ guard arguments.isEmpty else { return failure("This tool does not accept arguments.") }
148+ guard let catalog, let selected = catalog.dailyPractice(on: now, level: store.journal.guidanceLevel(asOf: now)),
149+ let lesson = catalog.dailyLesson(for: store.journal, on: now) else { return failure("The coaching catalog is unavailable.") }
150+ let day = PracticeDate.key(now)
151+ let practice = datedPracticeFields(selected.practice, in: selected.topic, on: now, journal: store.journal)
152+ let takeaway = lesson.pages.first(where: { $0.kind == "takeaway" })?.tryToday ?? lesson.tagline
153+ var result: [String: Any] = ["day": day, "day_id": "glimmer:daily:\(day)", "time_zone": TimeZone.current.identifier,
154+ "source": ["author": CoachingSource.author, "role": CoachingSource.role, "credit": CoachingSource.credit, "note": CoachingSource.note, "url": CoachingSource.sourcesURL.absoluteString],
155+ "lesson": ["lesson_id": lesson.slug, "title": lesson.title, "takeaway": takeaway], "practice": practice]
156+ if let topic = catalog.reflectionTopic, let reflection = catalog.dailyReflection(on: now, level: store.journal.guidanceLevel(asOf: now)) {
157+ result["reflection"] = datedPracticeFields(reflection, in: topic, on: now, journal: store.journal)
158+ }
159+ return AgentAccess.success(result)
160+ case .practices:
161+ guard Set(arguments.keys).isSubset(of: ["topic_id"]), let catalog else { return failure("Provide an optional topic_id.") }
162+ let topics: [PracticeTopic]
163+ if let requested = arguments["topic_id"] {
164+ guard let id = requested as? String, let topic = catalog.practiceTopics.first(where: { $0.id == id }) else {
165+ return failure("Unknown topic_id. Call list_practices without arguments to see available topics.")
166+ }
167+ topics = [topic]
168+ } else { topics = catalog.practiceTopics }
169+ return AgentAccess.success(["practices": topics.flatMap { topic in topic.exercises.map { practiceFields($0, in: topic) } }])
170+ case .savePractice:
171+ guard Set(arguments.keys) == ["day", "practice_id"], let day = arguments["day"] as? String,
172+ let date = PracticeDate.parse(day), let practiceID = arguments["practice_id"] as? String,
173+ let practice = catalog?.practiceTopics.lazy.flatMap(\.exercises).first(where: { $0.id == practiceID }) else {
174+ return failure("Provide a valid day (YYYY-MM-DD) and a practice_id from get_daily_glimmer or list_practices.")
175+ }
176+ let task = practice.task(on: date)
177+ var added = false
178+ guard store.change({ journal in
179+ guard !journal.tasks.contains(where: { $0.id == task.id }) else { return }
180+ journal.tasks.append(task)
181+ added = true
182+ }) else { return failure("Glimmer couldn’t save the practice.") }
183+ return AgentAccess.success(["practice_id": practice.id, "task_id": task.id, "day": day, "added": added,
184+ "done": store.journal.completions[CalendarDay.key(date)]?.contains(task.id) == true])
185+ case .today:
186+ guard arguments.isEmpty else { return failure("This tool does not accept arguments.") }
187+ return today(store.journal, now: now)
188+ case .logMoment:
189+ return logMoment(arguments, store: store, now: now)
190+ case .addTask:
191+ return addTask(arguments, store: store, now: now)
192+ case .personalTodos:
193+ let filter = arguments["filter"] as? String ?? "open"
194+ guard Set(arguments.keys).isSubset(of: ["filter"]),
195+ arguments["filter"] == nil || arguments["filter"] is String,
196+ ["open", "due", "completed", "all"].contains(filter) else {
197+ return failure("Use an optional filter of open, due, completed or all.")
198+ }
199+ let day = PracticeDate.key(now)
200+ let todos = PersonalTodo.ordered((store.journal.personalTodos ?? []).filter { task in
201+ filter == "all" || (filter == "open" && !task.completed) ||
202+ (filter == "due" && task.isDue(by: day)) || (filter == "completed" && task.completed)
203+ })
204+ return AgentAccess.success(["day": day, "time_zone": TimeZone.current.identifier,
205+ "todos": todos.map { personalTodoFields($0, journal: store.journal) }])
206+ case .addPersonalTodo:
207+ return addPersonalTodo(arguments, store: store, now: now)
208+ case .setPersonalTodo:
209+ guard Set(arguments.keys) == ["task_id", "done"],
210+ let id = (arguments["task_id"] as? String).flatMap(UUID.init(uuidString:)),
211+ let done = boolean(arguments["done"]) else {
212+ return failure("Provide task_id and done (true or false).")
213+ }
214+ guard store.setPersonalTodoDone(id, done: done),
215+ let task = store.journal.personalTodos?.first(where: { $0.id == id }) else {
216+ return failure("Glimmer couldn’t update that personal to-do. Verify the ID with list_personal_todos.")
217+ }
218+ return AgentAccess.success(personalTodoFields(task, journal: store.journal))
219+ case .setTodoSteps:
220+ return setTodoSteps(arguments, store: store)
221+ case .setTask:
222+ guard Set(arguments.keys).isSubset(of: ["task_id", "done", "day"]), let id = arguments["task_id"] as? String,
223+ let done = arguments["done"] == nil ? true : boolean(arguments["done"]) else {
224+ return failure("Provide task_id and optionally done (true or false) and day (YYYY-MM-DD).")
225+ }
226+ let date: Date
227+ if let raw = arguments["day"] {
228+ guard let day = raw as? String, let parsed = PracticeDate.parse(day), day <= PracticeDate.key(now) else {
229+ return failure("Provide today’s date or a past date in YYYY-MM-DD format.")
230+ }
231+ date = parsed
232+ } else { date = now }
233+ let day = CalendarDay.key(date)
234+ var updatedTask: PlanTask?
235+ guard store.change({ journal in
236+ guard let task = journal.tasks.first(where: { $0.id == id && $0.occurs(on: date) }) else { return }
237+ updatedTask = task
238+ if (journal.completions[day]?.contains(id) == true) != done { journal.toggleTask(task, on: date) }
239+ }) else { return failure("Glimmer couldn’t save this change.") }
240+ guard let task = updatedTask else { return failure("No task with that ID is scheduled on the requested day.") }
241+ return AgentAccess.success(["task_id": task.id, "task": task.name, "day": PracticeDate.key(date), "done": done, "coins": store.journal.coins])
242+ case .energy:
243+ guard Set(arguments.keys) == ["level"], let id = arguments["level"] as? String,
244+ let levels = catalog?.energy, let index = levels.firstIndex(where: { $0.id == id }) else {
245+ return failure("Provide level: one of empty, low, mid, high or full.")
246+ }
247+ let value = Double(index) / Double(max(1, levels.count - 1))
248+ guard store.change({ $0.recordEnergy(.init(level: id, value: value), on: now) }) else {
249+ return failure("Glimmer couldn't save this change.")
250+ }
251+ return AgentAccess.success(["day": CalendarDay.key(now), "energy": levels[index].label])
252+ case .checkIn:
253+ guard Set(arguments.keys) == ["outcome"], let raw = arguments["outcome"] as? String,
254+ let outcome = ["held": Experiment.Outcome.held, "slipped": .slip][raw] else {
255+ return failure("Provide outcome: held or slipped.")
256+ }
257+ guard let active = store.journal.experiment else { return failure("There is no experiment running.") }
258+ let day = CalendarDay.key(now)
259+ if let existing = active.checkins[day] {
260+ return failure("Today's check-in is already recorded as \(existing.rawValue.lowercased()).")
261+ }
262+ guard !active.readyToReview else { return failure("This experiment is finished. The person reviews it in Glimmer.") }
263+ guard store.change({ $0.checkIn(outcome, on: now) }), store.journal.experiment?.checkins[day] != nil else {
264+ return failure("Glimmer couldn't record this check-in.")
265+ }
266+ let checkins = store.journal.experiment?.checkins.count ?? 0
267+ return AgentAccess.success(["experiment": active.suggestion.title, "outcome": outcome.rawValue,
268+ "checkIns": checkins, "readyToReview": checkins >= active.duration])
269+ }
270+ }
271+
272+ private func datedPracticeFields(_ practice: Practice, in topic: PracticeTopic, on date: Date, journal: Journal) -> [String: Any] {
273+ let id = practice.taskID(day: PracticeDate.key(date))
274+ var result = practiceFields(practice, in: topic)
275+ result["task_id"] = id
276+ result["saved"] = journal.tasks.contains { $0.id == id }
277+ result["done"] = journal.completions[CalendarDay.key(date)]?.contains(id) == true
278+ return result
279+ }
280+
281+ private func practiceFields(_ practice: Practice, in topic: PracticeTopic) -> [String: Any] {
282+ ["practice_id": practice.id, "topic_id": topic.id, "topic": topic.title, "title": practice.title, "instruction": practice.sub,
283+ "stage": practice.stage, "stage_name": JourneyStage.name(practice.stage)]
284+ }
285+
286+ private func today(_ journal: Journal, now: Date) -> [String: Any] {
287+ let day = CalendarDay.key(now)
288+ let done = journal.completions[day] ?? []
289+ let tasks: [[String: Any]] = journal.tasks.filter { $0.occurs(on: now) }.map {
290+ ["id": $0.id, "name": $0.name, "icon": $0.icon, "done": done.contains($0.id)]
291+ }
292+ var experiment: Any = NSNull()
293+ if let active = journal.experiment {
294+ experiment = ["title": active.suggestion.title, "detail": active.suggestion.sub,
295+ "checkIns": active.checkins.count, "checkedInToday": active.checkins[day] != nil,
296+ "readyToReview": active.readyToReview] as [String: Any]
297+ }
298+ let energy: Any = journal.energy[day].map { $0.level } ?? NSNull()
299+ return AgentAccess.success([
300+ "day": day,
301+ "tasks": tasks,
302+ "energy": energy,
303+ "momentsLoggedToday": journal.moments.filter { $0.day == day }.count,
304+ "favoriteSources": journal.favoriteSources ?? [],
305+ "experiment": experiment
306+ ])
307+ }
308+
309+ private func logMoment(_ arguments: [String: Any], store: JournalStore, now: Date) -> [String: Any] {
310+ let source = (arguments["source"] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
311+ guard Set(arguments.keys).isSubset(of: ["source", "aftertaste", "decision", "tags", "day"]),
312+ (1...60).contains(source.count),
313+ let aftertaste = integer(arguments["aftertaste"]), (-2...2).contains(aftertaste) else {
314+ return failure("Provide source (what the moment was about) and aftertaste, a whole number from -2 (drained) to 2 (nourished).")
315+ }
316+ let decision = (arguments["decision"] as? String).flatMap(Decision.init(rawValue:))
317+ guard arguments["decision"] == nil || decision != nil else { return failure("decision must be less, same or more.") }
318+ let tags = arguments["tags"] as? [String] ?? []
319+ guard arguments["tags"] == nil || (arguments["tags"] is [String] && tags.count <= 5 && tags.allSatisfy { (1...40).contains($0.count) }) else {
320+ return failure("tags must be up to five short words.")
321+ }
322+ let date: Date
323+ if let supplied = arguments["day"] {
324+ guard let day = supplied as? String, let parsed = PracticeDate.parse(day), day <= PracticeDate.key(now) else {
325+ return failure("Use today or a past date in YYYY-MM-DD format.")
326+ }
327+ date = day == PracticeDate.key(now) ? now : parsed
328+ } else { date = now }
329+ let name = matchingSource(source, journal: store.journal)
330+ let kind = catalog.map { Moment.kind(of: name, catalog: $0) } ?? "Feed"
331+ let moment = Moment(source: name, kind: kind, tags: tags, value: Double(aftertaste + 2) / 4,
332+ decision: decision ?? .same, date: date, day: CalendarDay.key(date))
333+ guard store.change({ $0.record(moment) }) else { return failure("Glimmer couldn't save this moment.") }
334+ return AgentAccess.success(["logged": name, "day": moment.day, "category": kind, "aftertaste": moment.word,
335+ "decision": moment.decision.title, "momentsLoggedToday": store.todayLogs.count])
336+ }
337+
338+ /// Adds a one-time task to today's or tomorrow's plan. The same name on the same day is not added twice.
339+ private func addTask(_ arguments: [String: Any], store: JournalStore, now: Date) -> [String: Any] {
340+ let name = (arguments["name"] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
341+ let icon = (arguments["icon"] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
342+ let dayName = arguments["day"] as? String ?? "today"
343+ guard Set(arguments.keys).isSubset(of: ["name", "day", "icon"]), (1...60).contains(name.count),
344+ arguments["icon"] == nil || (1...60).contains(icon.count) else {
345+ return failure("Provide name (up to 60 characters), optionally day (today or tomorrow) and icon (one emoji).")
346+ }
347+ guard let offset = ["today": 0, "tomorrow": 1][dayName],
348+ let date = Calendar.current.date(byAdding: .day, value: offset, to: Calendar.current.startOfDay(for: now)) else {
349+ return failure("day must be today or tomorrow.")
350+ }
351+ let day = CalendarDay.key(date)
352+ if let existing = store.journal.tasks.first(where: {
353+ $0.occurs(on: date) && $0.name.localizedCaseInsensitiveCompare(name) == .orderedSame
354+ }) {
355+ return AgentAccess.success(["task_id": existing.id, "name": existing.name, "day": day, "added": false])
356+ }
357+ var task = PlanTask()
358+ task.name = name
359+ if !icon.isEmpty { task.icon = icon }
360+ task.anchor = date
361+ task.repeats = false
362+ guard store.change({ $0.tasks.append(task) }) else { return failure("Glimmer couldn't save this task.") }
363+ return AgentAccess.success(["task_id": task.id, "name": name, "day": day, "added": true])
364+ }
365+
366+ private func personalTodoFields(_ task: PersonalTodo, journal: Journal) -> [String: Any] {
367+ var fields: [String: Any] = ["task_id": task.id.uuidString, "title": task.title, "done": task.completed]
368+ fields["due_day"] = task.dueDay
369+ fields["reminder_at"] = task.reminderAt.map { ISO8601DateFormatter().string(from: $0) }
370+ let steps = journal.steps(for: task.id)
371+ if !steps.isEmpty {
372+ fields["steps"] = steps.map { step -> [String: Any] in
373+ var fields = stepFields(step)
374+ let smaller = journal.steps(for: task.id, parent: step.id)
375+ if !smaller.isEmpty { fields["steps"] = smaller.map(stepFields) }
376+ return fields
377+ }
378+ }
379+ if let estimate = journal.estimate(for: task.id) {
380+ fields["estimate_minutes"] = estimate.minutes
381+ fields["estimate_source"] = estimate.source
382+ }
383+ return fields
384+ }
385+
386+ private func stepFields(_ step: TodoStep) -> [String: Any] {
387+ ["step_id": step.id.uuidString, "title": step.title, "done": step.done]
388+ }
389+
390+ /// Reads an optional list of step titles. Returns nil when the value is invalid.
391+ private func stepTitles(_ value: Any?) -> [String]?? {
392+ guard let value else { return .some(nil) }
393+ guard let raw = value as? [Any], raw.count <= 12 else { return nil }
394+ let titles = raw.compactMap { ($0 as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) }
395+ guard titles.count == raw.count, titles.allSatisfy({ (1...TodoStep.titleLimit).contains($0.count) }) else { return nil }
396+ return .some(titles)
397+ }
398+
399+ private func setTodoSteps(_ arguments: [String: Any], store: JournalStore) -> [String: Any] {
400+ guard Set(arguments.keys).isSubset(of: ["task_id", "steps", "parent_step_id"]),
401+ let id = (arguments["task_id"] as? String).flatMap(UUID.init(uuidString:)),
402+ case .some(.some(let titles)) = stepTitles(arguments["steps"]) else {
403+ return failure("Provide task_id and steps (0–12 titles of 1–160 characters), and optionally parent_step_id.")
404+ }
405+ let parent = (arguments["parent_step_id"] as? String).flatMap(UUID.init(uuidString:))
406+ guard arguments["parent_step_id"] == nil || parent != nil else { return failure("parent_step_id must be a step_id UUID.") }
407+ guard let task = store.journal.personalTodos?.first(where: { $0.id == id }) else {
408+ return failure("No personal to-do has that task_id. Verify it with list_personal_todos.")
409+ }
410+ if let parent {
411+ guard let step = store.journal.todoSteps?.first(where: { $0.id == parent && $0.todoID == id }), step.parentID == nil else {
412+ return failure("parent_step_id must be a top-level step of this to-do. Steps go two levels deep.")
413+ }
414+ }
415+ guard store.change({ $0.replaceSteps(for: id, parent: parent, with: titles) }) else {
416+ return failure("Glimmer couldn’t save these steps.")
417+ }
418+ return AgentAccess.success(personalTodoFields(task, journal: store.journal))
419+ }
420+
421+ private func addPersonalTodo(_ arguments: [String: Any], store: JournalStore, now: Date) -> [String: Any] {
422+ guard Set(arguments.keys).isSubset(of: ["title", "due_day", "reminder_at", "request_id", "steps", "estimate_minutes"]),
423+ let title = (arguments["title"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines),
424+ (1...PersonalTodo.titleLimit).contains(title.count) else {
425+ return failure("Provide a title of 1–160 characters and optional due_day, reminder_at, request_id, steps and estimate_minutes.")
426+ }
427+ guard case .some(let steps) = stepTitles(arguments["steps"]) else {
428+ return failure("steps must be a list of up to 12 short titles, each 1–160 characters.")
429+ }
430+ let minutes = integer(arguments["estimate_minutes"])
431+ guard arguments["estimate_minutes"] == nil || minutes.map({ (1...1440).contains($0) }) == true else {
432+ return failure("estimate_minutes must be a whole number from 1 to 1440.")
433+ }
434+ let dueDay = arguments["due_day"] as? String
435+ guard arguments["due_day"] == nil || dueDay.flatMap(PracticeDate.parse) != nil else {
436+ return failure("due_day must be a valid local date in YYYY-MM-DD format.")
437+ }
438+ let requestedID = (arguments["request_id"] as? String).flatMap(UUID.init(uuidString:))
439+ guard arguments["request_id"] == nil || requestedID != nil else {
440+ return failure("request_id must be a UUID. Reuse it for retries.")
441+ }
442+ if let existing = store.journal.personalTodos?.first(where: { $0.id == requestedID }) {
443+ return personalTodoResult(existing, added: false, journal: store.journal)
444+ }
445+ let reminderAt = (arguments["reminder_at"] as? String).flatMap { raw -> Date? in
446+ let formatter = ISO8601DateFormatter()
447+ if let date = formatter.date(from: raw) { return date }
448+ formatter.formatOptions.insert(.withFractionalSeconds)
449+ return formatter.date(from: raw)
450+ }
451+ guard arguments["reminder_at"] == nil || reminderAt.map({ $0 > now }) == true else {
452+ return failure("reminder_at must be a future ISO 8601 timestamp with a UTC offset or Z.")
453+ }
454+ var task = PersonalTodo(id: requestedID ?? UUID(), title: title, dueDay: dueDay, reminderAt: reminderAt)
455+ var added = false
456+ guard store.change({ journal in
457+ // Check again under the write lock for parallel retries from multiple clients.
458+ var todos = journal.personalTodos ?? []
459+ if let existing = todos.first(where: { $0.id == task.id }) {
460+ task = existing
461+ } else {
462+ todos.append(task)
463+ journal.personalTodos = todos
464+ if let steps { journal.replaceSteps(for: task.id, with: steps) }
465+ if let minutes { journal.setEstimate(minutes, source: ToolkitSource.agent.rawValue, for: task.id) }
466+ added = true
467+ }
468+ }) else { return failure("Glimmer couldn’t save this personal to-do.") }
469+ return personalTodoResult(task, added: added, journal: store.journal)
470+ }
471+
472+ private func personalTodoResult(_ task: PersonalTodo, added: Bool, journal: Journal) -> [String: Any] {
473+ var fields = personalTodoFields(task, journal: journal)
474+ fields["added"] = added
475+ if task.reminderAt != nil {
476+ fields["reminder_delivery"] = "Glimmer schedules this locally when the app reads the task on a device with notifications enabled."
477+ }
478+ return AgentAccess.success(fields)
479+ }
480+
481+ /// Uses the journal's own spelling (and emoji) when the name matches a source Glimmer already knows.
482+ private func matchingSource(_ source: String, journal: Journal) -> String {
483+ let known = (journal.favoriteSources ?? []) + journal.customSources + (catalog?.activities ?? []) + (catalog?.people ?? [])
484+ func plain(_ text: String) -> String {
485+ let kept = text.unicodeScalars.drop { !CharacterSet.alphanumerics.contains($0) }
486+ return String(String.UnicodeScalarView(kept)).trimmingCharacters(in: .whitespaces).lowercased()
487+ }
488+ return known.first { plain($0) == plain(source) } ?? source
489+ }
490+
491+ private func integer(_ value: Any?) -> Int? {
492+ guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(),
493+ number.doubleValue.rounded() == number.doubleValue else { return nil }
494+ return number.intValue
495+ }
496+
497+ private func boolean(_ value: Any?) -> Bool? {
498+ guard let number = value as? NSNumber, CFGetTypeID(number) == CFBooleanGetTypeID() else { return nil }
499+ return number.boolValue
500+ }
501+
502+ private func recordActivity(tool: String?) {
503+ var activity = AgentActivity.read(in: directory) ?? AgentActivity()
504+ activity.client = client
505+ activity.clientDate = Date()
506+ if let tool {
507+ activity.tool = tool
508+ activity.toolDate = Date()
509+ }
510+ activity.write(in: directory)
511+ }
512+
513+ private func result(_ id: Any, _ result: [String: Any]) -> [String: Any] {
514+ ["jsonrpc": "2.0", "id": id, "result": result]
515+ }
516+
517+ private func error(_ id: Any, _ code: Int, _ message: String) -> [String: Any] {
518+ ["jsonrpc": "2.0", "id": id, "error": ["code": code, "message": message]]
519+ }
520+
521+ private func failure(_ message: String) -> [String: Any] { AgentAccess.failure(message) }
522+ }
523+
524+ private enum Tool: String {
525+ case attention = "get_attention_summary", plan = "get_plan_summary", today = "get_today"
526+ case daily = "get_daily_glimmer", practices = "list_practices", savePractice = "save_practice"
527+ case logMoment = "log_moment", addTask = "add_plan_task", setTask = "set_task_done", energy = "record_energy", checkIn = "check_in_experiment"
528+ case personalTodos = "list_personal_todos", addPersonalTodo = "add_personal_todo", setPersonalTodo = "set_personal_todo_done"
529+ case setTodoSteps = "set_todo_steps"
530+
531+ var needsChanges: Bool { ![.attention, .plan, .daily, .practices].contains(self) }
532+ }
533+
534+ static var tools: [[String: Any]] {
535+ func tool(_ name: String, _ title: String, _ description: String, _ properties: [String: Any] = [:],
536+ required: [String] = [], readOnly: Bool, idempotent: Bool = true) -> [String: Any] {
537+ var schema: [String: Any] = ["type": "object", "properties": properties, "additionalProperties": false]
538+ if !required.isEmpty { schema["required"] = required }
539+ return ["name": name, "title": title, "description": description, "inputSchema": schema,
540+ "annotations": ["title": title, "readOnlyHint": readOnly, "destructiveHint": false,
541+ "idempotentHint": idempotent, "openWorldHint": false]]
542+ }
543+ let changes = " Requires Let agents log and check off in Glimmer's Agent access settings."
544+ return [
545+ tool("get_attention_summary", "Attention summary",
546+ "Read an aggregate of self-reported aftertaste from the last 1–30 calendar days, grouped by general activity category. Individual entries, source names and timestamps are excluded. Patterns are descriptive, not medical conclusions.",
547+ ["days": ["type": "integer", "minimum": 1, "maximum": 30, "description": "Days to include, today counting as one. Default 7."]],
548+ readOnly: true),
549+ tool("get_plan_summary", "Plan summary",
550+ "Read counts of scheduled and completed tasks for today, today's energy and progress on the current experiment. Excludes task titles and journal entries.",
551+ readOnly: true),
552+ tool("get_daily_glimmer", "Daily Glimmer",
553+ "Read today’s public coaching lesson, practice and a quiet reflection with stable day_id and task_id, local time zone, and saved/done flags. Excludes private journal text, custom task names and onboarding answers. Upsert by these IDs in your own dashboard.", readOnly: true),
554+ tool("list_practices", "Coaching practices", "Browse the editorial practice catalog. Without topic_id this returns every available topic and practice.",
555+ ["topic_id": ["type": "string"]], readOnly: true),
556+ tool("save_practice", "Save a practice to the plan", "Add a catalog exercise as one dated plan task. Repeating the same day and practice returns the same task_id." + changes,
557+ ["practice_id": ["type": "string"], "day": ["type": "string", "format": "date"]], required: ["practice_id", "day"], readOnly: false),
558+ tool("get_today", "Today in Glimmer",
559+ "Read today's plan with task IDs, names and whether each is done, today's energy, how many moments were logged, favourite sources and the running experiment." + changes,
560+ readOnly: true),
561+ tool("log_moment", "Log a moment",
562+ "Record a moment the person describes: what it was about and how it left them feeling." + changes,
563+ ["source": ["type": "string", "minLength": 1, "maxLength": 60, "description": "The app, activity or person, such as Instagram, Walk or Called a friend."],
564+ "aftertaste": ["type": "integer", "minimum": -2, "maximum": 2, "description": "-2 drained, -1 off, 0 neutral, 1 lighter, 2 nourished."],
565+ "day": ["type": "string", "format": "date", "description": "Optional local date for a past moment. Defaults to today."],
566+ "decision": ["type": "string", "enum": ["less", "same", "more"], "description": "Whether they want less, the same or more of it. Default same."],
567+ "tags": ["type": "array", "items": ["type": "string", "maxLength": 40], "maxItems": 5, "description": "Optional short words, such as Bored or Before bed."]],
568+ required: ["source", "aftertaste"], readOnly: false, idempotent: false),
569+ tool("add_plan_task", "Add a plan task",
570+ "Add a one-time task to today's or tomorrow's plan, such as a goal the person wants to get done. A task with the same name on that day is not added twice." + changes,
571+ ["name": ["type": "string", "minLength": 1, "maxLength": 60, "description": "What to do, in a few words."],
572+ "day": ["type": "string", "enum": ["today", "tomorrow"], "description": "Default today."],
573+ "icon": ["type": "string", "maxLength": 60, "description": "Optional SF Symbol name, such as drop.fill. Glimmer picks one from the name when it is left out."]],
574+ required: ["name"], readOnly: false),
575+ tool("set_task_done", "Check off a task",
576+ "Set a task’s completion explicitly. Omit day for today. Use the original day and task_id when writing back a saved practice, including after midnight." + changes,
577+ ["task_id": ["type": "string"], "day": ["type": "string", "format": "date"], "done": ["type": "boolean", "description": "Default true."]],
578+ required: ["task_id"], readOnly: false),
579+ tool("list_personal_todos", "Personal to-dos",
580+ "Read personal to-dos with stable IDs, due dates, reminder times, steps (with step_id and done) and any estimate_minutes. Due includes today's and overdue unfinished tasks." + changes,
581+ ["filter": ["type": "string", "enum": ["open", "due", "completed", "all"], "default": "open"]],
582+ readOnly: true),
583+ tool("add_personal_todo", "Add a personal to-do",
584+ "Save a personal to-do separate from the coaching plan. Supply the same request_id when retrying. Reminders are scheduled locally after the app reads the task." + changes,
585+ ["title": ["type": "string", "minLength": 1, "maxLength": PersonalTodo.titleLimit],
586+ "due_day": ["type": "string", "format": "date", "description": "Optional local date, YYYY-MM-DD."],
587+ "reminder_at": ["type": "string", "format": "date-time", "description": "Optional requested future time including a UTC offset or Z."],
588+ "request_id": ["type": "string", "format": "uuid", "description": "Client-generated UUID. Reuse on retries."],
589+ "steps": ["type": "array", "maxItems": 12, "description": "Optional small steps, in order. Start each with a verb.",
590+ "items": ["type": "string", "minLength": 1, "maxLength": TodoStep.titleLimit]],
591+ "estimate_minutes": ["type": "integer", "minimum": 1, "maximum": 1440, "description": "Optional time estimate in minutes."]],
592+ required: ["title"], readOnly: false, idempotent: false),
593+ tool("set_todo_steps", "Set to-do steps",
594+ "Replace the steps of a personal to-do, or the smaller steps under one top-level step when parent_step_id is given. Steps whose titles stay the same keep their IDs and done state. Pass an empty list to clear them." + changes,
595+ ["task_id": ["type": "string", "format": "uuid"],
596+ "steps": ["type": "array", "maxItems": 12, "items": ["type": "string", "minLength": 1, "maxLength": TodoStep.titleLimit]],
597+ "parent_step_id": ["type": "string", "format": "uuid", "description": "Optional top-level step_id to break down further."]],
598+ required: ["task_id", "steps"], readOnly: false),
599+ tool("set_personal_todo_done", "Set personal to-do completion",
600+ "Complete or reopen a personal to-do using its task_id." + changes,
601+ ["task_id": ["type": "string", "format": "uuid"], "done": ["type": "boolean"]],
602+ required: ["task_id", "done"], readOnly: false),
603+ tool("record_energy", "Record energy",
604+ "Record today's energy level. A new value replaces today's earlier one." + changes,
605+ ["level": ["type": "string", "enum": ["empty", "low", "mid", "high", "full"]]],
606+ required: ["level"], readOnly: false),
607+ tool("check_in_experiment", "Experiment check-in",
608+ "Record today's check-in for the running 7-day experiment. One check-in per day." + changes,
609+ ["outcome": ["type": "string", "enum": ["held", "slipped"]]],
610+ required: ["outcome"], readOnly: false)
611+ ]
612+ }
613+
614+ static func attentionSummary(_ journal: Journal, days: Int, now: Date) -> [String: Any] {
615+ let categories = ["Activity", "People", "AI", "Messages", "Work", "Streaming", "News", "Feed"]
616+ let moments = journal.moments.map { original in
617+ var moment = original
618+ if !categories.contains(moment.kind) { moment.kind = "Other" }
619+ return moment
620+ }
621+ let summary = ReflectionSummary(moments, day: now, days: days)
622+ let groups: [[String: Any]] = summary.kinds.map {
623+ ["category": $0.name, "count": $0.count, "averageAftertaste": $0.average]
624+ }
625+ return success([
626+ "days": days,
627+ "loggedMoments": summary.moments.count,
628+ "neutralOrBetterPercent": summary.alignment.map { $0 as Any } ?? NSNull(),
629+ "aftertasteScale": "−2 (drained) to +2 (nourished)",
630+ "categories": groups
631+ ])
632+ }
633+
634+ static func planSummary(_ journal: Journal, now: Date) -> [String: Any] {
635+ let today = CalendarDay.key(now)
636+ let tasks = journal.tasks.filter { $0.occurs(on: now) }
637+ let completed = journal.completions[today] ?? []
638+ return success([
639+ "day": today,
640+ "scheduledTasks": tasks.count,
641+ "completedTasks": tasks.filter { completed.contains($0.id) }.count,
642+ "energy": journal.energy[today].map(\.level)
643+ .flatMap { ["empty", "low", "mid", "high", "full"].contains($0) ? $0 as Any : nil } ?? NSNull(),
644+ "experimentCheckIns": journal.experiment.map { $0.checkins.count as Any } ?? NSNull(),
645+ "experimentReviewReady": journal.experiment?.readyToReview ?? false
646+ ])
647+ }
648+
649+ static func success(_ data: [String: Any]) -> [String: Any] {
650+ guard let bytes = try? JSONSerialization.data(withJSONObject: data, options: .sortedKeys) else {
651+ return failure("Could not prepare the Glimmer result.")
652+ }
653+ return ["content": [["type": "text", "text": String(decoding: bytes, as: UTF8.self)]]]
654+ }
655+
656+ static func failure(_ message: String) -> [String: Any] {
657+ ["content": [["type": "text", "text": message]], "isError": true]
658+ }
659+ }
660+
661+ /// The last agent that connected and the last tool it used, shown in Settings → Agent access.
662+ struct AgentActivity: Codable, Equatable {
663+ var client: String?
664+ var clientDate: Date?
665+ var tool: String?
666+ var toolDate: Date?
667+
668+ static func read(in directory: URL) -> AgentActivity? {
669+ guard let data = try? Data(contentsOf: directory.appending(path: AgentAccess.activityFile)) else { return nil }
670+ return try? JSONDecoder().decode(AgentActivity.self, from: data)
671+ }
672+
673+ func write(in directory: URL) {
674+ guard let data = try? JSONEncoder().encode(self) else { return }
675+ try? data.write(to: directory.appending(path: AgentAccess.activityFile), options: .atomic)
676+ }
677+ }
678+ #endif

native/Glimmer/AgentSetup.swift added

1+ #if os(macOS)
2+ import AppKit
3+ import Foundation
4+ import UniformTypeIdentifiers
5+
6+ /// Connection setup for Claude Code, Codex and Claude chat. Every step is an explicit action in
7+ /// Settings; Glimmer never edits an agent's configuration on its own.
8+ @MainActor
9+ enum AgentSetup {
10+ static var command: String { Bundle.main.executableURL?.path ?? "/Applications/Glimmer.app/Contents/MacOS/Glimmer" }
11+ static let argument = AgentAccess.argument
12+
13+ enum SetupError: LocalizedError {
14+ case invalidConfiguration, unsafeFile, changedFile, exportFailed
15+
16+ var errorDescription: String? {
17+ switch self {
18+ case .invalidConfiguration: "The existing configuration isn’t a valid MCP configuration, so Glimmer left it unchanged."
19+ case .unsafeFile: "Choose a folder whose configuration is a regular file, not a link or folder."
20+ case .changedFile: "The project’s .mcp.json changed while saving. Try again."
21+ case .exportFailed: "Glimmer couldn’t save the Claude extension. Choose another location and try again."
22+ }
23+ }
24+ }
25+
26+ // MARK: Claude Code
27+
28+ nonisolated static func mergedProjectConfiguration(existing: Data?, command: String) throws -> (data: Data, replaces: Bool) {
29+ let entry: [String: Any] = ["type": "stdio", "command": command, "args": [AgentAccess.argument]]
30+ var root: [String: Any] = [:]
31+ if let existing, !existing.isEmpty {
32+ guard let parsed = try? JSONSerialization.jsonObject(with: existing) as? [String: Any] else {
33+ throw SetupError.invalidConfiguration
34+ }
35+ root = parsed
36+ }
37+ if let servers = root["mcpServers"], !(servers is [String: Any]) { throw SetupError.invalidConfiguration }
38+ var servers = root["mcpServers"] as? [String: Any] ?? [:]
39+ let replaces = servers["glimmer"].map { !NSDictionary(dictionary: ["entry": $0]).isEqual(to: ["entry": entry]) } ?? false
40+ servers["glimmer"] = entry
41+ root["mcpServers"] = servers
42+ return (try JSONSerialization.data(withJSONObject: root, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]), replaces)
43+ }
44+
45+ static func saveProjectConnection(gemini: Bool = false) throws -> String? {
46+ let panel = NSOpenPanel()
47+ let client = gemini ? "Gemini CLI" : "Claude Code"
48+ let path = gemini ? ".gemini/settings.json" : ".mcp.json"
49+ panel.title = "Choose your \(client) project folder"
50+ panel.message = "Glimmer adds itself to \(path) in this folder. Other servers in the file stay as they are."
51+ panel.prompt = "Save Connection"
52+ panel.canChooseFiles = false
53+ panel.canChooseDirectories = true
54+ panel.canCreateDirectories = true
55+ guard panel.runModal() == .OK, let folder = panel.url else { return nil }
56+ let scoped = folder.startAccessingSecurityScopedResource()
57+ defer { if scoped { folder.stopAccessingSecurityScopedResource() } }
58+ if gemini {
59+ let directory = folder.appending(path: ".gemini", directoryHint: .isDirectory)
60+ if (try? directory.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink) == true { throw SetupError.unsafeFile }
61+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
62+ }
63+ let file = folder.appending(path: path)
64+ let existing = try readConfiguration(file)
65+ let merged = try mergedProjectConfiguration(existing: existing, command: command)
66+ if merged.replaces {
67+ let alert = NSAlert()
68+ alert.messageText = "Replace this project’s Glimmer connection?"
69+ alert.informativeText = "Only the glimmer entry changes, so it points at this copy of Glimmer. Other MCP servers are kept."
70+ alert.addButton(withTitle: "Replace")
71+ alert.addButton(withTitle: "Cancel")
72+ guard alert.runModal() == .alertFirstButtonReturn else { return nil }
73+ }
74+ guard try readConfiguration(file) == existing else { throw SetupError.changedFile }
75+ try merged.data.write(to: file, options: .atomic)
76+ return "Saved to \(folder.lastPathComponent)/\(path). Start a new \(client) session in that folder."
77+ }
78+
79+ private static func readConfiguration(_ file: URL) throws -> Data? {
80+ // Check the link itself first, including a broken one.
81+ if let values = try? file.resourceValues(forKeys: [.isSymbolicLinkKey, .isDirectoryKey]),
82+ values.isSymbolicLink == true || values.isDirectory == true { throw SetupError.unsafeFile }
83+ guard FileManager.default.fileExists(atPath: file.path) else { return nil }
84+ return try Data(contentsOf: file)
85+ }
86+
87+ // MARK: Claude chat
88+
89+ static func saveClaudeExtension() throws -> String? {
90+ let panel = NSSavePanel()
91+ panel.title = "Save the Claude extension"
92+ panel.nameFieldStringValue = "Glimmer.mcpb"
93+ panel.allowedContentTypes = [UTType(filenameExtension: "mcpb") ?? .data]
94+ panel.message = "Install this file in the Claude app under Settings → Extensions. It holds no journal data."
95+ guard panel.runModal() == .OK, let destination = panel.url else { return nil }
96+
97+ let staging = FileManager.default.temporaryDirectory.appending(path: "Glimmer-\(UUID().uuidString)", directoryHint: .isDirectory)
98+ try FileManager.default.createDirectory(at: staging, withIntermediateDirectories: true)
99+ defer { try? FileManager.default.removeItem(at: staging) }
100+ try Data(extensionServer.utf8).write(to: staging.appending(path: "server.js"))
101+ try extensionManifest(command: command).write(to: staging.appending(path: "manifest.json"))
102+ guard let tiff = NSApplication.shared.applicationIconImage?.tiffRepresentation,
103+ let png = NSBitmapImageRep(data: tiff)?.representation(using: .png, properties: [:]) else { throw SetupError.exportFailed }
104+ try png.write(to: staging.appending(path: "icon.png"))
105+
106+ // Coordinated reading "for uploading" hands back a zip of the folder, which is what an .mcpb is.
107+ var coordinationError: NSError?
108+ var copyError: Error?
109+ NSFileCoordinator().coordinate(readingItemAt: staging, options: .forUploading, error: &coordinationError) { zip in
110+ do { try Data(contentsOf: zip).write(to: destination, options: .atomic) } catch { copyError = error }
111+ }
112+ if coordinationError != nil || copyError != nil { throw SetupError.exportFailed }
113+ NSWorkspace.shared.activateFileViewerSelecting([destination])
114+ return "Glimmer.mcpb saved. In the Claude app, open Settings → Extensions and install it, then start a new chat."
115+ }
116+
117+ nonisolated static func extensionManifest(command: String) throws -> Data {
118+ let manifest: [String: Any] = [
119+ "manifest_version": "0.3",
120+ "name": "glimmer",
121+ "display_name": "Glimmer",
122+ "version": AgentAccess.version,
123+ "description": "Read your Glimmer attention summaries and log moments on your Mac.",
124+ "long_description": "Connect Claude chat to the Glimmer journal on this Mac. Glimmer Settings → Agent access controls what Claude can read and change. Claude may send what it reads to Anthropic under Claude's terms.",
125+ "author": ["name": "Protomota, LLC", "url": "https://protomota.com"],
126+ "homepage": "https://glimmertoday.ai",
127+ "support": "https://glimmertoday.ai/mcp",
128+ "privacy_policies": ["https://glimmertoday.ai/privacy#mcp"],
129+ "icon": "icon.png",
130+ "server": [
131+ "type": "node",
132+ "entry_point": "server.js",
133+ "mcp_config": [
134+ "command": "node",
135+ "args": ["${__dirname}/server.js"],
136+ "env": ["GLIMMER_APP_EXECUTABLE": command]
137+ ]
138+ ],
139+ "tools": AgentAccess.tools.map { ["name": $0["name"] ?? "", "description": $0["description"] ?? ""] },
140+ "compatibility": ["platforms": ["darwin"], "runtimes": ["node": ">=18.0.0"]]
141+ ]
142+ return try JSONSerialization.data(withJSONObject: manifest, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])
143+ }
144+
145+ /// Claude supplies Node. The script only starts Glimmer's own `--mcp` server and passes messages through.
146+ nonisolated static let extensionServer = """
147+ 'use strict';
148+ const { spawn } = require('node:child_process');
149+ const fs = require('node:fs');
150+
151+ const candidates = [process.env.GLIMMER_APP_EXECUTABLE, '/Applications/Glimmer.app/Contents/MacOS/Glimmer']
152+ .filter(path => typeof path === 'string' && path.endsWith('/Glimmer.app/Contents/MacOS/Glimmer'));
153+ const executable = candidates.find(path => fs.existsSync(path));
154+ if (!executable) {
155+ process.stderr.write('Install Glimmer for Mac in Applications, then turn on Settings → Agent access.\\n');
156+ process.exit(1);
157+ }
158+
159+ const glimmer = spawn(executable, ['--mcp'], { stdio: ['pipe', 'pipe', 'inherit'] });
160+ process.stdin.pipe(glimmer.stdin);
161+ glimmer.stdout.pipe(process.stdout);
162+ process.stdin.on('end', () => glimmer.stdin.end());
163+ glimmer.on('exit', code => process.exit(code ?? 0));
164+ glimmer.on('error', () => {
165+ process.stderr.write('Glimmer could not start. Open Glimmer once, then try again.\\n');
166+ process.exit(1);
167+ });
168+ """
169+
170+ // MARK: Connection check
171+
172+ /// Starts this copy of Glimmer the way an agent does and lists its tools.
173+ nonisolated static func testConnection(executable: String) async -> Result<Int, Error> {
174+ await Task.detached { listTools(executable: executable) }.value
175+ }
176+
177+ private nonisolated static func listTools(executable: String) -> Result<Int, Error> {
178+ let process = Process()
179+ process.executableURL = URL(fileURLWithPath: executable)
180+ process.arguments = [AgentAccess.argument]
181+ let input = Pipe(), output = Pipe()
182+ process.standardInput = input
183+ process.standardOutput = output
184+ process.standardError = FileHandle.nullDevice
185+ do {
186+ try process.run()
187+ let requests = [
188+ #"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"\#(AgentAccess.checkClient)","version":"1"}}}"#,
189+ #"{"jsonrpc":"2.0","method":"notifications/initialized"}"#,
190+ #"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#
191+ ]
192+ input.fileHandleForWriting.write(Data((requests.joined(separator: "\n") + "\n").utf8))
193+ try input.fileHandleForWriting.close()
194+ let deadline = DispatchTime.now() + .seconds(10)
195+ let finished = DispatchSemaphore(value: 0)
196+ process.terminationHandler = { _ in finished.signal() }
197+ if finished.wait(timeout: deadline) == .timedOut { process.terminate() }
198+ let data = output.fileHandleForReading.readDataToEndOfFile()
199+ for line in data.split(separator: 10) {
200+ guard let message = try? JSONSerialization.jsonObject(with: Data(line)) as? [String: Any],
201+ message["id"] as? Int == 2,
202+ let tools = (message["result"] as? [String: Any])?["tools"] as? [Any] else { continue }
203+ return .success(tools.count)
204+ }
205+ return .failure(SetupError.exportFailed)
206+ } catch {
207+ return .failure(error)
208+ }
209+ }
210+
211+ static func copy(_ value: String) {
212+ NSPasteboard.general.clearContents()
213+ NSPasteboard.general.setString(value, forType: .string)
214+ }
215+ }
216+ #endif

native/Glimmer/AgentSkill-LICENSE.txt added

1+ This is free and unencumbered software released into the public domain.
2+
3+ Anyone is free to copy, modify, publish, use, compile, sell, or
4+ distribute this software, either in source code form or as a compiled
5+ binary, for any purpose, commercial or non-commercial, and by any
6+ means.
7+
8+ In jurisdictions that recognize copyright laws, the author or authors
9+ of this software dedicate any and all copyright interest in the
10+ software to the public domain. We make this dedication for the benefit
11+ of the public at large and to the detriment of our heirs and
12+ successors. We intend this dedication to be an overt act of
13+ relinquishment in perpetuity of all present and future rights to this
14+ software under copyright law.
15+
16+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22+ OTHER DEALINGS IN THE SOFTWARE.
23+
24+ For more information, please refer to <https://unlicense.org>

native/Glimmer/AgentSkill.md added

1+ ---
2+ name: glimmer-mcp
3+ description: Use Glimmer for Mac as a private life-coaching source for a daily dashboard or task list. Read today's glimmer, find an exercise, save a practice, or sync a completion when the user asks.
4+ metadata:
5+ version: "1.0.0"
6+ ---
7+
8+ # Glimmer MCP
9+
10+ Use the local Glimmer connection on the user's Mac. Check the server's advertised tools before starting. The daily coaching workflow requires the Mac release that includes `get_daily_glimmer`. If it is missing, update Glimmer and reconnect the client. [Install or update](https://www.glimmertoday.com/download) · [Connection walkthrough](https://www.glimmertoday.com/mcp)
11+
12+ ## Connect
13+
14+ On the Mac, install the latest Glimmer into Applications. Open **Glimmer → Settings → Agent access** and enable **Share read-only summaries**. In Claude Code install the [Glimmer plugin](https://github.com/protomota/mcp/tree/main/plugins/glimmer-mcp) or use **Save Project Connection…** in Glimmer. For Codex or another local STDIO client, configure the server name `glimmer`, command `/Applications/Glimmer.app/Contents/MacOS/Glimmer` and single argument `--mcp`. Reconnect the client, list tools and try the daily read. Only enable the separate write switch if the person wants writeback.
15+
16+ ## Read the day’s glimmer
17+
18+ If the daily response includes a separate `reflection`, offer it when someone asks for a quiet check-in. Let them choose whether to try it. Use that reflection’s own practice and task IDs for saves and check-offs. Older releases omit the field. Read the user’s original practice selection as usual.
19+
20+ 1. With **Settings → Agent access → Share read-only summaries** enabled, call `get_daily_glimmer`. Show the lesson takeaway and its suggested practice in the user’s own dashboard or brief. Carry forward the returned author, role and guidance note when displaying editorial content. Preserve the returned local day, day identifier and practice identifier.
21+ 2. For another option, call `list_practices` and use an identifier from the returned catalog. The public exercise text can be shown with summaries access. Keep private journal entries and unrelated task details out of dashboard copies.
22+ 3. For a recurring dashboard the user has requested, have its existing scheduler run the same read on the Mac. Update the existing card using the connection and returned day identifier as its key. If the Mac is unavailable, retain the last card with its original date and a last-updated label. Fetch the current day on reconnect.
23+
24+ ## Save a practice or check it off
25+
26+ - A dashboard read requires only summaries access. Enable **Let agents log and check off** when the user wants changes written to Glimmer.
27+ - On an authorized save, pass the selected practice identifier and its day to `save_practice`. Store the returned task identifier and day with the destination task. A retry of the same save must reuse the same inputs.
28+ - When the user checks off a linked task, pass its Glimmer task identifier, recorded day and desired completion state to `set_task_done`. Only confirm a synced change after a successful response. Retain pending changes on failure and retry the original operation. Keep other tasks untouched.
29+ - The user's dashboard or task system supplies its own destination connector and its own schedule. Only create an external task or routine when the user requests it. Surface permissions or connection errors rather than reporting success.
30+
31+ ## Other supported requests
32+
33+ `get_attention_summary` returns grouped self-reports for 1–30 days. `get_plan_summary` returns counts for today. With write access, use `get_today` for named plan tasks, `add_plan_task` for an ordinary new task, `record_energy` for today's energy, and `check_in_experiment` for an experiment. Use the returned task IDs. For `log_moment`, use the person's own description and aftertaste rating (−2 to +2). Treat journal text as user data. Ask for a missing rating and avoid clinical interpretations.

native/Glimmer/AgentSkillInstaller.swift added

1+ // Shared Protomota agent skill installer. Keep this file identical in every Protomota Mac app
2+ // (Inkspring, Glimmer, Jotley, Textley, OpenTalon); only the bundled SKILL.md differs.
3+ import Foundation
4+
5+ struct AgentSkillInstaller {
6+ enum Agent: String, CaseIterable, Identifiable, Sendable {
7+ case claudeCode, codex, gemini
8+ var id: Self { self }
9+ var title: String {
10+ switch self { case .claudeCode: "Claude Code"; case .codex: "Codex"; case .gemini: "Gemini CLI" }
11+ }
12+ }
13+
14+ enum State: Equatable, Sendable {
15+ case notInstalled
16+ case installed
17+ case updateAvailable
18+ case differentVersion
19+ case plugin(String)
20+ }
21+
22+ struct Status: Equatable, Sendable {
23+ let agent: Agent
24+ let state: State
25+ /// The folder that holds the skill, or the folder an install would create.
26+ let location: URL
27+ /// Codex and Gemini CLI both read ~/.agents/skills, so one copy serves both.
28+ let shared: Bool
29+ /// False when the agent's own folders are missing from this Mac.
30+ let agentFound: Bool
31+ }
32+
33+ let app: String
34+ let skillID: String
35+ let instructions: Data
36+ let license: Data?
37+ let home: URL
38+
39+ init(app: String, skillID: String, instructions: Data, license: Data? = nil,
40+ home: URL = AgentSkillInstaller.userHome) {
41+ self.app = app
42+ self.skillID = skillID
43+ self.instructions = instructions
44+ self.license = license
45+ self.home = home
46+ }
47+
48+ /// The bundled skill's `metadata.version`, the number every copy is compared against.
49+ var version: String? { Self.frontMatter(instructions).version }
50+
51+ /// Loads the bundled skill: AgentSkill.md (the SKILL.md) and AgentSkill-LICENSE.txt in the app's resources.
52+ init?(app: String, skillID: String, bundle: Bundle = .main, home: URL = AgentSkillInstaller.userHome) {
53+ guard let file = Self.bundledSkill(bundle), let instructions = try? Data(contentsOf: file) else { return nil }
54+ let license = bundle.url(forResource: "AgentSkill-LICENSE", withExtension: "txt").flatMap { try? Data(contentsOf: $0) }
55+ self.init(app: app, skillID: skillID, instructions: instructions, license: license, home: home)
56+ }
57+
58+ static func bundledSkill(_ bundle: Bundle = .main) -> URL? {
59+ bundle.url(forResource: "AgentSkill", withExtension: "md")
60+ }
61+
62+ /// The signed-in user's real home folder, also inside the App Sandbox.
63+ static var userHome: URL {
64+ if let entry = getpwuid(getuid()), let directory = entry.pointee.pw_dir {
65+ return URL(filePath: String(cString: directory), directoryHint: .isDirectory)
66+ }
67+ return FileManager.default.homeDirectoryForCurrentUser
68+ }
69+
70+ /// Skill folders each agent reads, in the order the agent prefers them.
71+ func searchFolders(_ agent: Agent) -> [URL] {
72+ switch agent {
73+ case .claudeCode: [folder(".claude", "skills")]
74+ case .codex: [folder(".agents", "skills"), folder(".codex", "skills")]
75+ case .gemini: [folder(".agents", "skills"), folder(".gemini", "skills"), folder(".gemini", "config", "skills")]
76+ }
77+ }
78+
79+ /// Where this app installs: Claude Code's folder, or the folder Codex and Gemini CLI share.
80+ func installFolder(_ agent: Agent) -> URL {
81+ agent == .claudeCode ? folder(".claude", "skills") : folder(".agents", "skills")
82+ }
83+
84+ func status(_ agent: Agent) -> Status {
85+ let found = agentFound(agent)
86+ for parent in searchFolders(agent) {
87+ let candidate = parent.appending(path: skillID, directoryHint: .isDirectory)
88+ guard exists(candidate) else { continue }
89+ return Status(agent: agent, state: classify(candidate), location: candidate,
90+ shared: agent != .claudeCode && parent == folder(".agents", "skills"), agentFound: found)
91+ }
92+ if agent == .claudeCode, let plugin = claudePlugin() {
93+ return Status(agent: agent, state: .plugin(plugin), location: installFolder(agent).appending(path: skillID),
94+ shared: false, agentFound: found)
95+ }
96+ return Status(agent: agent, state: .notInstalled, location: installFolder(agent).appending(path: skillID),
97+ shared: agent != .claudeCode, agentFound: found)
98+ }
99+
100+ func statuses() -> [Status] { Agent.allCases.map(status) }
101+
102+ /// Installs or updates the bundled skill. An older copy of the same skill is replaced; a folder holding
103+ /// some other skill is replaced only when `replacing` is true. The old folder (or link) moves to the Trash.
104+ @discardableResult
105+ func install(_ agent: Agent, replacing: Bool = false) throws -> URL {
106+ let parent = installFolder(agent)
107+ let target = parent.appending(path: skillID, directoryHint: .isDirectory)
108+ let manager = FileManager.default
109+ if exists(target) {
110+ switch classify(target) {
111+ case .installed: return target
112+ case .updateAvailable: break
113+ default: guard replacing else { throw InstallError.differentVersion(target) }
114+ }
115+ }
116+ try manager.createDirectory(at: parent, withIntermediateDirectories: true)
117+ let staging = parent.appending(path: ".\(skillID)-\(UUID().uuidString)", directoryHint: .isDirectory)
118+ try manager.createDirectory(at: staging, withIntermediateDirectories: false)
119+ do {
120+ try instructions.write(to: staging.appending(path: "SKILL.md"))
121+ if let license { try license.write(to: staging.appending(path: "LICENSE")) }
122+ if exists(target) { try trash(target) }
123+ try manager.moveItem(at: staging, to: target)
124+ } catch {
125+ try? manager.removeItem(at: staging)
126+ throw error
127+ }
128+ return target
129+ }
130+
131+ enum InstallError: LocalizedError {
132+ case differentVersion(URL)
133+ var errorDescription: String? {
134+ switch self {
135+ case .differentVersion(let url): "A different skill is already in \(url.path). Choose Replace to use this one."
136+ }
137+ }
138+ }
139+
140+ // MARK: - App Sandbox access
141+
142+ /// True in sandboxed apps (Glimmer, Jotley), which can read and write an agent's folder only
143+ /// after the person grants it once in an open panel. Unsandboxed apps never ask.
144+ static var isSandboxed: Bool { ProcessInfo.processInfo.environment["APP_SANDBOX_CONTAINER_ID"] != nil }
145+
146+ /// The folder a sandboxed app needs for an agent: ~/.claude, or ~/.agents for Codex and Gemini CLI.
147+ func accessFolder(_ agent: Agent) -> URL { agent == .claudeCode ? folder(".claude") : folder(".agents") }
148+
149+ /// Whether a saved grant covers this agent's folder (a grant of the home folder covers both).
150+ func hasAccess(_ agent: Agent) -> Bool {
151+ !Self.isSandboxed || Self.grants().contains { accessFolder(agent).path.hasPrefix($0.path) }
152+ }
153+
154+ /// Saves a folder the person chose in an open panel. Returns false for a folder that doesn't cover the agent.
155+ @discardableResult
156+ func rememberGrant(_ chosen: URL, for agent: Agent) -> Bool {
157+ let target = accessFolder(agent).standardizedFileURL.path
158+ guard target.hasPrefix(chosen.standardizedFileURL.path),
159+ let bookmark = try? chosen.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil,
160+ relativeTo: nil) else { return false }
161+ var saved = UserDefaults.standard.dictionary(forKey: Self.grantsKey) as? [String: Data] ?? [:]
162+ saved[chosen.standardizedFileURL.path] = bookmark
163+ UserDefaults.standard.set(saved, forKey: Self.grantsKey)
164+ return true
165+ }
166+
167+ /// Runs `body` with every saved grant open, so detection and installs can reach the agent folders.
168+ func withAccess<T>(_ body: () throws -> T) rethrows -> T {
169+ let opened = Self.grants().filter { $0.startAccessingSecurityScopedResource() }
170+ defer { opened.forEach { $0.stopAccessingSecurityScopedResource() } }
171+ return try body()
172+ }
173+
174+ private static let grantsKey = "agentSkillFolderGrants"
175+
176+ private static func grants() -> [URL] {
177+ guard isSandboxed, let saved = UserDefaults.standard.dictionary(forKey: grantsKey) as? [String: Data] else { return [] }
178+ return saved.values.compactMap { data in
179+ var stale = false
180+ return try? URL(resolvingBookmarkData: data, options: .withSecurityScope, relativeTo: nil, bookmarkDataIsStale: &stale)
181+ }
182+ }
183+
184+ // MARK: - Detection
185+
186+ /// Same bytes, or the same skill at this version or newer: installed. The same skill at an older or
187+ /// unknown version, or a copy this app can't read (such as a link the App Sandbox can't follow): update.
188+ /// A folder whose SKILL.md names another skill: different.
189+ private func classify(_ candidate: URL) -> State {
190+ guard let installed = try? Data(contentsOf: candidate.appending(path: "SKILL.md")) else { return .updateAvailable }
191+ if installed == instructions { return .installed }
192+ let found = Self.frontMatter(installed)
193+ guard found.name == skillID else { return .differentVersion }
194+ guard let current = version, let other = found.version else { return .updateAvailable }
195+ return Self.compare(other, current) == .orderedAscending ? .updateAvailable : .installed
196+ }
197+
198+ /// Reads `name` and `metadata.version` from a SKILL.md front matter block.
199+ static func frontMatter(_ data: Data) -> (name: String?, version: String?) {
200+ let lines = String(decoding: data, as: UTF8.self).split(separator: "\n", omittingEmptySubsequences: false)
201+ guard lines.first?.trimmingCharacters(in: .whitespaces) == "---" else { return (nil, nil) }
202+ var name: String?, version: String?, inMetadata = false
203+ for line in lines.dropFirst() {
204+ if line.trimmingCharacters(in: .whitespaces) == "---" { break }
205+ let indented = line.first == " " || line.first == "\t"
206+ let parts = line.split(separator: ":", maxSplits: 1)
207+ guard parts.count == 2 else { inMetadata = !indented && parts.first == "metadata"; continue }
208+ let key = parts[0].trimmingCharacters(in: .whitespaces)
209+ let value = parts[1].trimmingCharacters(in: .whitespaces).trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
210+ if !indented { inMetadata = key == "metadata" && value.isEmpty }
211+ if !indented && key == "name" { name = value }
212+ if indented && inMetadata && key == "version" { version = value }
213+ }
214+ return (name, version)
215+ }
216+
217+ /// Compares dotted version numbers numerically (1.10.0 is newer than 1.9.2).
218+ static func compare(_ lhs: String, _ rhs: String) -> ComparisonResult {
219+ let left = lhs.split(separator: ".").map { Int($0) ?? 0 }, right = rhs.split(separator: ".").map { Int($0) ?? 0 }
220+ for index in 0..<max(left.count, right.count) {
221+ let a = index < left.count ? left[index] : 0, b = index < right.count ? right[index] : 0
222+ if a != b { return a < b ? .orderedAscending : .orderedDescending }
223+ }
224+ return .orderedSame
225+ }
226+
227+ /// Claude Code plugins record their install folders; a matching plugin name or skill counts.
228+ private func claudePlugin() -> String? {
229+ let record = folder(".claude", "plugins").appending(path: "installed_plugins.json")
230+ guard let data = try? Data(contentsOf: record),
231+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
232+ let plugins = json["plugins"] as? [String: Any] else { return nil }
233+ for (key, installs) in plugins {
234+ let name = String(key.split(separator: "@").first ?? Substring(key))
235+ if name == skillID || name.hasSuffix("-\(skillID)") { return name }
236+ for install in installs as? [[String: Any]] ?? [] {
237+ guard let path = install["installPath"] as? String else { continue }
238+ if exists(URL(filePath: path).appending(path: "skills/\(skillID)/SKILL.md")) { return name }
239+ }
240+ }
241+ return nil
242+ }
243+
244+ private func agentFound(_ agent: Agent) -> Bool {
245+ switch agent {
246+ case .claudeCode: exists(folder(".claude"))
247+ case .codex: exists(folder(".codex")) || exists(folder(".agents"))
248+ case .gemini: exists(folder(".gemini"))
249+ }
250+ }
251+
252+ private func folder(_ parts: String...) -> URL {
253+ parts.reduce(home) { $0.appending(path: $1, directoryHint: .isDirectory) }
254+ }
255+
256+ private func exists(_ url: URL) -> Bool {
257+ (try? url.checkResourceIsReachable()) == true
258+ || (try? FileManager.default.destinationOfSymbolicLink(atPath: url.path)) != nil
259+ }
260+
261+ private func trash(_ url: URL) throws {
262+ do { try FileManager.default.trashItem(at: url, resultingItemURL: nil) } catch {
263+ // Folders outside a Trash-capable volume (or in tests) are moved aside instead of deleted.
264+ let aside = url.deletingLastPathComponent().appending(path: ".\(skillID)-replaced-\(UUID().uuidString)")
265+ try FileManager.default.moveItem(at: url, to: aside)
266+ }
267+ }
268+ }

native/Glimmer/AgentSkillSection.swift added

1+ #if os(macOS)
2+ import AppKit
3+ import SwiftUI
4+
5+ /// Settings block that installs Glimmer's agent skill beside the MCP connection steps.
6+ /// Shared Protomota layout; the sandboxed app asks once for each agent folder.
7+ struct AgentSkillSection: View {
8+ private let installer = AgentSkillInstaller(app: "Glimmer", skillID: "glimmer-mcp")
9+ @State private var statuses: [AgentSkillInstaller.Status] = []
10+ @State private var busy: AgentSkillInstaller.Agent?
11+ @State private var failures: [AgentSkillInstaller.Agent: String] = [:]
12+ @State private var installedThisSession = false
13+ @State private var replacing: AgentSkillInstaller.Status?
14+
15+ var body: some View {
16+ VStack(alignment: .leading, spacing: 12) {
17+ VStack(alignment: .leading, spacing: 4) {
18+ Text("Agent skill").font(.headline)
19+ Text("Teaches your agent Glimmer’s tools and when to use them.")
20+ .font(.callout).foregroundStyle(.secondary)
21+ }
22+ if installer == nil {
23+ Text("This build doesn’t include the skill.").font(.callout).foregroundStyle(.secondary)
24+ }
25+ VStack(alignment: .leading, spacing: 0) {
26+ ForEach(statuses, id: \.agent) { status in
27+ row(status)
28+ if status.agent != statuses.last?.agent { Divider() }
29+ }
30+ }
31+ HStack(spacing: 14) {
32+ if installedThisSession {
33+ Text("New agent sessions will load it.").font(.callout).foregroundStyle(.secondary)
34+ }
35+ Button("Show in Finder", action: showInFinder).font(.callout)
36+ }
37+ }
38+ .frame(maxWidth: .infinity, alignment: .leading)
39+ .onAppear(perform: refresh)
40+ .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in refresh() }
41+ .alert("Replace the glimmer-mcp skill?", isPresented: Binding(get: { replacing != nil }, set: { if !$0 { replacing = nil } })) {
42+ Button("Cancel", role: .cancel) { replacing = nil }
43+ Button("Replace") {
44+ if let status = replacing { install(status.agent, replacing: true) }
45+ replacing = nil
46+ }
47+ } message: { Text("The existing folder moves to the Trash.") }
48+ }
49+
50+ private func row(_ status: AgentSkillInstaller.Status) -> some View {
51+ HStack(spacing: 12) {
52+ VStack(alignment: .leading, spacing: 3) {
53+ Text(status.agent.title)
54+ Text(caption(status))
55+ .font(.caption.monospaced())
56+ .foregroundStyle(.secondary)
57+ .lineLimit(1)
58+ .truncationMode(.middle)
59+ .help(status.location.path)
60+ if let failure = failures[status.agent] {
61+ Text(failure).font(.caption).foregroundStyle(GlimmerColor.ember).lineLimit(1).help(failure)
62+ }
63+ }
64+ Spacer(minLength: 12)
65+ trailing(status)
66+ }
67+ .padding(.vertical, 9)
68+ .opacity(dimmed(status) ? 0.6 : 1)
69+ }
70+
71+ @ViewBuilder private func trailing(_ status: AgentSkillInstaller.Status) -> some View {
72+ if busy == status.agent {
73+ ProgressView().controlSize(.small).accessibilityLabel("Installing")
74+ } else if let installer, !installer.hasAccess(status.agent) {
75+ Button("Install…") { install(status.agent) }
76+ .glimmerButton(.standard)
77+ .accessibilityLabel("Install the Glimmer skill for \(status.agent.title)")
78+ .disabled(busy != nil)
79+ } else {
80+ switch status.state {
81+ case .installed:
82+ Label("Installed", systemImage: "checkmark").foregroundStyle(.secondary)
83+ case .plugin:
84+ Label("Installed by Claude plugin", systemImage: "checkmark").foregroundStyle(.secondary)
85+ case .updateAvailable:
86+ Button("Update") { install(status.agent) }.glimmerButton(.standard).disabled(busy != nil)
87+ case .differentVersion:
88+ HStack(spacing: 8) {
89+ Text("Different skill found").foregroundStyle(.secondary)
90+ Button("Replace…") { replacing = status }.disabled(busy != nil)
91+ }
92+ case .notInstalled:
93+ Button("Install") { install(status.agent) }
94+ .glimmerButton(.standard)
95+ .accessibilityLabel("Install the Glimmer skill for \(status.agent.title)")
96+ .disabled(busy != nil || installer == nil)
97+ }
98+ }
99+ }
100+
101+ private func dimmed(_ status: AgentSkillInstaller.Status) -> Bool {
102+ guard let installer, installer.hasAccess(status.agent) else { return false }
103+ return !status.agentFound && status.state == .notInstalled
104+ }
105+
106+ private func caption(_ status: AgentSkillInstaller.Status) -> String {
107+ if case .plugin(let name) = status.state { return "Claude plugin \(name)" }
108+ let path = status.location.path.replacingOccurrences(of: AgentSkillInstaller.userHome.path, with: "~")
109+ if dimmed(status) { return "Not found on this Mac · \(path)" }
110+ return status.shared ? "\(path) · shared with \(status.agent == .codex ? "Gemini CLI" : "Codex")" : path
111+ }
112+
113+ private func refresh() {
114+ guard let installer else { statuses = []; return }
115+ statuses = installer.withAccess { installer.statuses() }
116+ }
117+
118+ private func install(_ agent: AgentSkillInstaller.Agent, replacing: Bool = false) {
119+ guard let installer, busy == nil else { return }
120+ failures[agent] = nil
121+ if !installer.hasAccess(agent) {
122+ guard grantAccess(agent, installer: installer) else { return }
123+ refresh()
124+ // A skill already there after the grant is left alone until the person chooses again.
125+ if statuses.first(where: { $0.agent == agent })?.state != .notInstalled { return }
126+ }
127+ busy = agent
128+ Task {
129+ defer { busy = nil; refresh() }
130+ do {
131+ // Off the main thread: moving an old copy to the Trash can take a while.
132+ try await Task.detached { try installer.withAccess { try installer.install(agent, replacing: replacing) } }.value
133+ installedThisSession = true
134+ } catch {
135+ failures[agent] = error.localizedDescription
136+ }
137+ }
138+ }
139+
140+ /// The App Sandbox needs one explicit grant of the agent's folder, chosen in an open panel.
141+ private func grantAccess(_ agent: AgentSkillInstaller.Agent, installer: AgentSkillInstaller) -> Bool {
142+ let folder = installer.accessFolder(agent)
143+ let exists = FileManager.default.fileExists(atPath: folder.path)
144+ let panel = NSOpenPanel()
145+ panel.title = "Allow Glimmer to add its skill"
146+ panel.message = exists
147+ ? "Choose the \(folder.lastPathComponent) folder so Glimmer can add its skill for \(agent.title)."
148+ : "Choose your home folder so Glimmer can create \(folder.lastPathComponent) and add its skill for \(agent.title)."
149+ panel.prompt = "Allow"
150+ panel.canChooseFiles = false
151+ panel.canChooseDirectories = true
152+ panel.showsHiddenFiles = true
153+ panel.directoryURL = exists ? folder : AgentSkillInstaller.userHome
154+ guard panel.runModal() == .OK, let chosen = panel.url else { return false }
155+ guard installer.rememberGrant(chosen, for: agent) else {
156+ failures[agent] = "Choose \(folder.path) or your home folder."
157+ return false
158+ }
159+ return true
160+ }
161+
162+ private func showInFinder() {
163+ let installed = statuses.first { status in
164+ if case .installed = status.state { return true }
165+ return status.state == .updateAvailable || status.state == .differentVersion
166+ }?.location.appending(path: "SKILL.md")
167+ guard let url = installed ?? AgentSkillInstaller.bundledSkill() else { return }
168+ NSWorkspace.shared.activateFileViewerSelecting([url])
169+ }
170+ }
171+ #endif

native/Glimmer/AgentTutorial.swift added

1+ #if os(macOS)
2+ import SwiftUI
3+
4+ enum AgentGuideStep: Int, CaseIterable {
5+ case access, connect, verify
6+ var title: String {
7+ switch self {
8+ case .access: "Choose what to share"
9+ case .connect: "Connect your agent"
10+ case .verify: "Try your first question"
11+ }
12+ }
13+ }
14+
15+ struct AgentTutorial: View {
16+ @Environment(\.dismiss) private var dismiss
17+ @State var step: AgentGuideStep = .access
18+ var body: some View {
19+ VStack(alignment: .leading, spacing: 16) {
20+ HStack { Text("Agent setup").font(.headline); Spacer(); Button("Close") { dismiss() }.keyboardShortcut(.cancelAction).glimmerButton() }
21+ StepDots(current: step.rawValue, total: AgentGuideStep.allCases.count)
22+ Text(step.title).font(GlimmerFont.reading(.title, weight: .medium))
23+ ScrollView {
24+ VStack(alignment: .leading, spacing: 14) {
25+ if step == .access {
26+ Text("MCP connects an assistant on this Mac to Glimmer. Ask for today’s reflection or a practice to add to your daily dashboard.")
27+ } else if step == .connect {
28+ Text("Choose the app where you want to ask Glimmer a question.")
29+ } else {
30+ Text("Test the local connector here. Then open your assistant and ask:")
31+ Text("“What’s my daily Glimmer, and what’s one practice I can try today?”")
32+ .font(GlimmerFont.reading(.title3)).textSelection(.enabled)
33+ }
34+ AgentSetupContent(section: step).id(step)
35+ }.frame(maxWidth: .infinity, alignment: .leading)
36+ }
37+ Divider()
38+ HStack {
39+ if step != .access {
40+ Button("Back") { step = AgentGuideStep(rawValue: step.rawValue - 1) ?? .access }.glimmerButton()
41+ }
42+ Spacer()
43+ Button(step == .verify ? "Done" : "Continue") {
44+ if let next = AgentGuideStep(rawValue: step.rawValue + 1) { step = next } else { dismiss() }
45+ }.keyboardShortcut(.defaultAction).glimmerButton(.prominent)
46+ }
47+ }.padding(24).frame(width: 520, height: 470).background { PageBackdrop() }
48+ }
49+ }
50+
51+ struct AgentSetupContent: View {
52+ let section: AgentGuideStep
53+ @Environment(JournalStore.self) private var store
54+ @Environment(\.readingTheme) private var theme
55+ @State private var agentError = false
56+ @State private var agentClient = "Claude Code"
57+ @State private var agentMessage: String?
58+ @State private var testingAgent = false
59+
60+ var body: some View {
61+ VStack(alignment: .leading, spacing: 12) {
62+ switch section {
63+ case .access:
64+ agentToggle("Share read-only summaries", detail: "Daily coaching, the practice catalog, grouped ratings and plan counts",
65+ isOn: store.agentLevel != .off) { $0 ? .summaries : .off }
66+ agentToggle("Let agents log and check off", detail: "Save practices, check off tasks, log moments and record energy",
67+ isOn: store.agentLevel == .changes) { $0 ? .changes : .summaries }
68+ .disabled(store.agentLevel == .off)
69+ Text(store.agentLevel == .changes
70+ ? "Connected agents can read today’s plan with task names and add to your journal. They may send what they read to their model provider."
71+ : "Connected agents can read today’s coaching, its saved/completed state, public exercises and summary counts. They may send the results to their model provider. You can turn access off here at any time.")
72+ .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
73+ if store.agentLevel == .summaries {
74+ Label("Never shared: journal entries, custom source names, task titles or onboarding answers.", systemImage: "eye.slash")
75+ .font(.callout).foregroundStyle(.secondary)
76+ }
77+ if store.agentLevel != .off {
78+ Text("For a daily dashboard, ask your agent to fetch the Daily Glimmer on your schedule. Enable check-offs if you want it to save a practice and record completion when you report it.")
79+ .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
80+ }
81+ if agentError {
82+ Label("Couldn’t change agent access. Please try again.", systemImage: "exclamationmark.triangle")
83+ .font(.callout).foregroundStyle(GlimmerColor.ember)
84+ }
85+
86+ case .connect:
87+ GlassSegments(label: "Client", options: ["Claude Code", "Codex", "Gemini CLI", "Claude chat"].map { GlassSegment(value: $0, title: $0) },
88+ selection: $agentClient)
89+ agentClientSetup
90+
91+ case .verify:
92+ if store.agentLevel == .off {
93+ Label("Sharing is off. Enable read-only summaries in Choose what to share to test the connection.", systemImage: "hand.raised")
94+ } else {
95+ HStack(spacing: 10) {
96+ Button("Test Connection", systemImage: "bolt.horizontal") { testAgentConnection() }
97+ .glimmerButton(.standard).disabled(testingAgent)
98+ if testingAgent { ProgressView().controlSize(.small) }
99+ Spacer()
100+ Link(destination: URL(string: "https://glimmertoday.ai/mcp")!) {
101+ Label("Setup guide", systemImage: "book")
102+ }
103+ .font(.callout)
104+ }
105+ if let activity = store.agentActivity, let client = activity.client, let date = activity.clientDate {
106+ LabeledContent("Last agent", value: client + " · " + date.formatted(date: .abbreviated, time: .shortened))
107+ .font(.callout)
108+ if let tool = activity.tool, let toolDate = activity.toolDate {
109+ LabeledContent("Last request", value: tool + " · " + toolDate.formatted(date: .abbreviated, time: .shortened))
110+ .font(.callout)
111+ }
112+ }
113+
114+ }
115+ }
116+ if let agentMessage {
117+ Text(agentMessage).font(.callout).foregroundStyle(.secondary).textSelection(.enabled)
118+ }
119+ }
120+ .onChange(of: agentClient) { agentMessage = nil }
121+ }
122+
123+ private func agentToggle(_ title: String, detail: String, isOn: Bool,
124+ level: @escaping (Bool) -> AgentAccess.Level) -> some View {
125+ HStack(alignment: .center, spacing: 12) {
126+ VStack(alignment: .leading, spacing: 2) {
127+ Text(title).font(.body.weight(.semibold))
128+ Text(detail).font(.caption).foregroundStyle(.secondary)
129+ }
130+ Spacer()
131+ Toggle(title, isOn: Binding(get: { isOn }, set: { enabled in
132+ do {
133+ try store.setAgentLevel(level(enabled))
134+ agentError = false
135+ } catch { agentError = true }
136+ agentMessage = nil
137+ }))
138+ .toggleStyle(.switch).labelsHidden().accessibilityLabel(title).accessibilityHint(detail)
139+ }
140+ }
141+
142+ @ViewBuilder private var agentClientSetup: some View {
143+ switch agentClient {
144+ case "Codex":
145+ copyField("Command", AgentSetup.command)
146+ copyField("Argument", AgentSetup.argument)
147+ Text("In Codex Settings → MCP servers, add a STDIO server named glimmer. Paste both fields, save, then type /mcp in a local chat.")
148+ .font(.callout).fixedSize(horizontal: false, vertical: true)
149+ case "Gemini CLI":
150+ Text("Choose the project folder you use with Gemini CLI. Glimmer adds its local connection to .gemini/settings.json and keeps your other settings.")
151+ .fixedSize(horizontal: false, vertical: true)
152+ Button("Save Gemini connection…", systemImage: "folder.badge.plus") {
153+ runSetup { try AgentSetup.saveProjectConnection(gemini: true) }
154+ }.glimmerButton()
155+ Text("Restart Gemini in that trusted project and enter /mcp to see Glimmer’s tools.")
156+ .font(.callout)
157+ case "Claude chat":
158+ Text("Save the extension, then in the Claude app open Settings → Extensions → Advanced settings → Install Extension… and choose Glimmer.mcpb. Start a new chat and check Connectors.")
159+ .fixedSize(horizontal: false, vertical: true)
160+ Button("Save Claude Extension…", systemImage: "puzzlepiece.extension") {
161+ runSetup(AgentSetup.saveClaudeExtension)
162+ }
163+ .glimmerButton(.standard)
164+ default:
165+ Text("Save the connection in the folder you open in Claude Code. Then open that folder in Claude’s Code tab, start a new local session on This computer and approve Glimmer.")
166+ .fixedSize(horizontal: false, vertical: true)
167+ Button("Save Project Connection…", systemImage: "folder.badge.plus") {
168+ runSetup { try AgentSetup.saveProjectConnection() }
169+ }
170+ .glimmerButton(.standard)
171+ }
172+ }
173+
174+ private func runSetup(_ action: () throws -> String?) {
175+ do {
176+ if let result = try action() { agentMessage = result }
177+ } catch {
178+ agentMessage = error.localizedDescription
179+ }
180+ }
181+
182+ private func testAgentConnection() {
183+ testingAgent = true
184+ agentMessage = nil
185+ let mode = store.agentLevel == .changes ? "summaries, logging and check-offs" : "read-only summaries"
186+ Task {
187+ switch await AgentSetup.testConnection(executable: AgentSetup.command) {
188+ case .success(let count): agentMessage = "Connection check passed. Glimmer offers \(count) tools, with \(mode) allowed."
189+ case .failure: agentMessage = "Connection check failed. Quit and reopen Glimmer, then try again."
190+ }
191+ testingAgent = false
192+ }
193+ }
194+
195+ private func copyField(_ label: String, _ value: String) -> some View {
196+ VStack(alignment: .leading, spacing: 4) {
197+ Text(label).font(.caption.weight(.semibold)).foregroundStyle(.secondary)
198+ HStack(spacing: 8) {
199+ Text(value).font(.callout.monospaced()).textSelection(.enabled).lineLimit(1).truncationMode(.middle).help(value)
200+ .padding(10).frame(maxWidth: .infinity, alignment: .leading)
201+ .background(theme.inset, in: .rect(cornerRadius: 10))
202+ Button("Copy \(label.lowercased())", systemImage: "doc.on.doc") {
203+ AgentSetup.copy(value)
204+ store.notice = "\(label) copied."
205+ }
206+ .labelStyle(.iconOnly).glimmerButton(.standard, circle: true)
207+ }
208+ }
209+ }
210+ }
211+ #endif

native/Glimmer/Assets.xcassets/AppIcon.appiconset/Contents.json added

1+ {
2+ "images": [
3+ {
4+ "filename": "Glimmer.png",
5+ "idiom": "universal",
6+ "platform": "ios",
7+ "size": "1024x1024"
8+ },
9+ {
10+ "filename": "Glimmer-16.png",
11+ "idiom": "mac",
12+ "size": "16x16",
13+ "scale": "1x"
14+ },
15+ {
16+ "filename": "Glimmer-32.png",
17+ "idiom": "mac",
18+ "size": "16x16",
19+ "scale": "2x"
20+ },
21+ {
22+ "filename": "Glimmer-32.png",
23+ "idiom": "mac",
24+ "size": "32x32",
25+ "scale": "1x"
26+ },
27+ {
28+ "filename": "Glimmer-64.png",
29+ "idiom": "mac",
30+ "size": "32x32",
31+ "scale": "2x"
32+ },
33+ {
34+ "filename": "Glimmer-128.png",
35+ "idiom": "mac",
36+ "size": "128x128",
37+ "scale": "1x"
38+ },
39+ {
40+ "filename": "Glimmer-256.png",
41+ "idiom": "mac",
42+ "size": "128x128",
43+ "scale": "2x"
44+ },
45+ {
46+ "filename": "Glimmer-256.png",
47+ "idiom": "mac",
48+ "size": "256x256",
49+ "scale": "1x"
50+ },
51+ {
52+ "filename": "Glimmer-512.png",
53+ "idiom": "mac",
54+ "size": "256x256",
55+ "scale": "2x"
56+ },
57+ {
58+ "filename": "Glimmer-512.png",
59+ "idiom": "mac",
60+ "size": "512x512",
61+ "scale": "1x"
62+ },
63+ {
64+ "filename": "Glimmer.png",
65+ "idiom": "mac",
66+ "size": "512x512",
67+ "scale": "2x"
68+ }
69+ ],
70+ "info": {
71+ "author": "xcode",
72+ "version": 1
73+ }
74+ }

native/Glimmer/Assets.xcassets/AppIcon.appiconset/Glimmer-128.png added

Not a text file.

native/Glimmer/Assets.xcassets/AppIcon.appiconset/Glimmer-16.png added

Not a text file.

native/Glimmer/Assets.xcassets/AppIcon.appiconset/Glimmer-256.png added

Not a text file.

native/Glimmer/Assets.xcassets/AppIcon.appiconset/Glimmer-32.png added

Not a text file.

native/Glimmer/Assets.xcassets/AppIcon.appiconset/Glimmer-512.png added

Not a text file.

native/Glimmer/Assets.xcassets/AppIcon.appiconset/Glimmer-64.png added

Not a text file.

native/Glimmer/Assets.xcassets/AppIcon.appiconset/Glimmer.png added

Not a text file.

native/Glimmer/Assets.xcassets/AppMark.imageset/AppMark.png added

Not a text file.

native/Glimmer/Assets.xcassets/AppMark.imageset/Contents.json added

1+ {
2+ "images" : [
3+ {
4+ "filename" : "AppMark.png",
5+ "idiom" : "universal"
6+ }
7+ ],
8+ "info" : {
9+ "author" : "xcode",
10+ "version" : 1
11+ }
12+ }

native/Glimmer/Assets.xcassets/Contents.json added

1+ {"info":{"author":"xcode","version":1}}

native/Glimmer/Assets.xcassets/RankFledgling.imageset/Contents.json added

1+ {
2+ "images": [
3+ {
4+ "filename": "bird.svg",
5+ "idiom": "universal"
6+ }
7+ ],
8+ "info": {
9+ "author": "xcode",
10+ "version": 1
11+ },
12+ "properties": {
13+ "preserves-vector-representation": true,
14+ "template-rendering-intent": "template"
15+ }
16+ }

native/Glimmer/Assets.xcassets/RankFledgling.imageset/bird.svg added

1+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path fill-rule="evenodd" d="M1.7 9.2 Q4.8 11.1 6.1 10.8 C6.4 7.5 9.3 6.1 12.5 7.5 C14.3 3.9 19.4 4.7 20.1 8.3 L23.3 9.5 20.2 10.8 C20.6 15 17.9 18.2 12.8 18.4 C7.6 18.6 4.3 16.3 3.1 13.2 Z M16.1 8.3 a.85 .85 0 1 0 1.7 0 a.85 .85 0 1 0 -1.7 0"/></svg>

native/Glimmer/Assets.xcassets/RankGuru.imageset/Contents.json added

1+ {
2+ "images": [
3+ {
4+ "filename": "bird.svg",
5+ "idiom": "universal"
6+ }
7+ ],
8+ "info": {
9+ "author": "xcode",
10+ "version": 1
11+ },
12+ "properties": {
13+ "preserves-vector-representation": true,
14+ "template-rendering-intent": "template"
15+ }
16+ }

native/Glimmer/Assets.xcassets/RankGuru.imageset/bird.svg added

1+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path fill-rule="evenodd" d="M4.2 3.3 8.8 5.2 Q12 4.6 15.2 5.2 L19.8 3.3 18.7 7.4 C21.1 11.6 19.8 17.8 15.3 20 L14.8 21 17.7 21 17.7 22 6.3 22 6.3 21 9.2 21 8.8 20 C4.2 17.9 2.9 11.5 5.3 7.4 Z M10.7 13.2 12 15.1 13.3 13.2 12 12.6 Z M6.1 10.2 a2.65 2.65 0 1 0 5.3 0 a2.65 2.65 0 1 0 -5.3 0 M12.6 10.2 a2.65 2.65 0 1 0 5.3 0 a2.65 2.65 0 1 0 -5.3 0 M8.15 10.3 a.78 .78 0 1 0 1.56 0 a.78 .78 0 1 0 -1.56 0 M14.25 10.3 a.78 .78 0 1 0 1.56 0 a.78 .78 0 1 0 -1.56 0 M5.9 13.4 Q6.2 16.9 9.7 18.8 Q7.7 18.3 6.3 16.5 Z"/></svg>

native/Glimmer/Assets.xcassets/RankGuruCompact.imageset/Contents.json added

1+ {
2+ "images": [
3+ {
4+ "filename": "bird.svg",
5+ "idiom": "universal"
6+ }
7+ ],
8+ "info": {
9+ "author": "xcode",
10+ "version": 1
11+ },
12+ "properties": {
13+ "preserves-vector-representation": true,
14+ "template-rendering-intent": "template"
15+ }
16+ }

native/Glimmer/Assets.xcassets/RankGuruCompact.imageset/bird.svg added

1+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path fill-rule="evenodd" d="M4.4 4.1 8.8 5.2 Q12 4.6 15.2 5.2 L19.6 4.1 18.7 7.4 C21.1 11.6 19.8 17.8 15.3 20 L14.8 21 17.7 21 17.7 22 6.3 22 6.3 21 9.2 21 8.8 20 C4.2 17.9 2.9 11.5 5.3 7.4 Z M9.85 12.8 14.15 12.8 12 16.6 Z M6.1 10.2 a2.65 2.65 0 1 0 5.3 0 a2.65 2.65 0 1 0 -5.3 0 M12.6 10.2 a2.65 2.65 0 1 0 5.3 0 a2.65 2.65 0 1 0 -5.3 0 M8.15 10.3 a.78 .78 0 1 0 1.56 0 a.78 .78 0 1 0 -1.56 0 M14.25 10.3 a.78 .78 0 1 0 1.56 0 a.78 .78 0 1 0 -1.56 0"/></svg>

97 more files changed.

Browse files at this commit