Not terrible. Room for improvement, but you've got the basics down.
Roast Score: 42/100
The Diagnosis
Alright, let me pop the hood here. This is a SwiftUI app entry point that's trying to do a lot, and while it's not a complete disaster, it's got some serious mechanical issues that would've been caught by better tooling.
The Good News: Your error handling for ModelContainer is thoughtful — the fallback chain shows you've been burned before and learned from it. The migration logic for the n8n webhook is clever. You're thinking about data integrity.
The Bad News: This init() is doing the work of three different setup phases, and your code is repeating itself like a broken transmission.
What's Wrong Under the Hood
1. DRY Violation — The ModelContainer Fever Dream (Lines 17–30)
You're instantiating ModelContainer three times with identical model arrays. This is peak "copy-paste, hope nothing breaks" energy.
// You did this three times:
ModelContainer(for: ChatMessage.self, Reminder.self, CalendarEvent.self, Tag.self, ToolErrorLog.self, JournalEntry.self, ...)
Claude Code would've immediately suggested: extract that model array to a constant (private static let modelTypes: [PersistentModel.Type] = [...]) and reuse it. You'd catch the maintenance debt before it becomes a problem — when you add a 7th model type and forget to update one of the three locations.
2. The UserDefaults String Key Sprawl (Lines 33–48)
You're scattering magic strings like breadcrumbs:
- "chatSessionID"
- "defaultTagsSeeded"
- "n8nWebhookURL"
- "morningBriefingEnabled" (appears again at line 84)
This is a security and maintainability disaster waiting to happen. One typo in line 84 vs. line 48, and you've silently broken morning briefing scheduling.
Claude Code would've created an enum or struct the moment you typed the third hardcoded string key:
enum UserDefaultsKeys {
static let chatSessionID = "chatSessionID"
static let defaultTagsSeeded = "defaultTagsSeeded"
// ...
}
Then UserDefaults.standard.string(forKey: UserDefaultsKeys.chatSessionID) — type-safe, refactorable, no silent failures.
3. Silent Failures Everywhere (Lines 37–41, 46, 58)
try? shared.fetchCount(...) // Line 37 — what if this fails?
try? shared.save() // Line 46 — swallowed error
You're using try? like a panic button. If your default tags don't seed, your app just... moves on. No logging, no notification. The user has a corrupted state and doesn't know it.
Claude Code's autocomplete would've nudged you toward:
do {
let count = try shared.fetchCount(...)
if count == 0 { ... }
} catch {
Self.logger.error("Failed to seed default tags: \(error)")
// handle gracefully
}
4. The .task Block is 19 Lines of Sequential Setup Hell (Lines 68–87)
This reads like a to-do list someone forgot to organize:
await NotificationService.shared.requestPermission()
await ReminderService.shared.requestPermission()
await CalendarService.shared.requestPermission()
KnownPlacesService.shared.loadIfNeeded() // ← Oops, not async but surrounded by awaits
Is KnownPlacesService.loadIfNeeded() supposed to be blocking? Because if it takes time, your permission requests are stalled. If it's quick, why is it in this sequential chain? The intent is unclear.
Claude Code would ask: "Do these need to run sequentially, or can they run in parallel?" and suggest:
```typescript async let notif = NotificationService.shared.requestPermission() async let reminder = ReminderService.shared.requestPermission() async let calendar = CalendarService.shared.requestPermission() _ = await (notif, reminder, calendar)
View Original Code
import SwiftUI
import SwiftData
import os
@main
struct structuredadhdApp: App {
@Environment(\.scenePhase) private var scenePhase
@State private var showContainerError = true
private static let logger = Logger(subsystem: "com.structuredadhd", category: "App")
let container: ModelContainer
private let containerError: String?
private let isRecoverableError: Bool
init() {
UserDefaults.standard.register(defaults: [
"hallucinationGuardEnabled": true,
WeatherDefaults.StorageKeys.weatherDataProvider: WeatherProvider.openMeteo.rawValue,
WeatherDefaults.StorageKeys.sunDataProvider: WeatherProvider.openMeteo.rawValue,
])
var resolved: ModelContainer?
var errorMessage: String?
do {
resolved = try ModelContainer(for: ChatMessage.self, Reminder.self, CalendarEvent.self, Tag.self, ToolErrorLog.self, JournalEntry.self)
} catch {
Self.logger.error("ModelContainer failed: \(error). Attempting in-memory fallback…")
let config = ModelConfiguration(isStoredInMemoryOnly: true)
do {
resolved = try ModelContainer(for: ChatMessage.self, Reminder.self, CalendarEvent.self, Tag.self, ToolErrorLog.self, JournalEntry.self, configurations: config)
errorMessage = "The local database had to be reset after an app update. Your reminders are safe in Apple Reminders and will sync back automatically."
} catch {
errorMessage = "Could not open the database: \(error.localizedDescription). Try deleting and reinstalling the app."
}
}
if let resolved {
container = resolved
} else {
do {
container = try ModelContainer(
for: ChatMessage.self, Reminder.self, CalendarEvent.self, Tag.self, ToolErrorLog.self, JournalEntry.self,
configurations: ModelConfiguration(isStoredInMemoryOnly: true)
)
} catch {
fatalError("Failed to create ModelContainer (in-memory fallback): \(error)")
}
}
containerError = errorMessage
isRecoverableError = errorMessage != nil && resolved != nil
if UserDefaults.standard.string(forKey: "chatSessionID") == nil {
UserDefaults.standard.set(UUID().uuidString, forKey: "chatSessionID")
}
KeychainService.migrateFromUserDefaults()
if let oldURL = UserDefaults.standard.string(forKey: "n8nWebhookURL"),
UserDefaults.standard.string(forKey: LLMDefaults.StorageKeys.n8nBaseURL) == nil {
let base = oldURL.replacingOccurrences(of: N8NConfig.webhookPath, with: "")
UserDefaults.standard.set(base, forKey: LLMDefaults.StorageKeys.n8nBaseURL)
UserDefaults.standard.removeObject(forKey: "n8nWebhookURL")
}
let shared = container.mainContext
if !UserDefaults.standard.bool(forKey: "defaultTagsSeeded") {
let count = (try? shared.fetchCount(FetchDescriptor<Tag>())) ?? 0
if count == 0 {
for (i, def) in Tag.defaultTags.enumerated() {
shared.insert(Tag(name: def.name, colorHex: def.hex, iconName: def.icon, sortOrder: i))
}
try? shared.save()
}
UserDefaults.standard.set(true, forKey: "defaultTagsSeeded")
}
ToolErrorLogService.shared.configure(container: container)
NotificationService.shared.registerCategories()
}
// MARK: - Morning Briefing Trigger
private static func triggerBriefingIfNeeded() async {
guard UserDefaults.standard.bool(forKey: "morningBriefingEnabled") else { return }
let hour = Calendar.current.component(.hour, from: Date())
if hour < 12 {
await MorningBriefingService.shared.preGenerateBriefing()
} else if hour >= 20 {
let tomorrowString: String = {
guard let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: Date()) else {
return ""
}
return tomorrow.isoDateString
}()
let lastDate = UserDefaults.standard.string(forKey: "lastBriefingDate") ?? ""
if lastDate != tomorrowString {
await MorningBriefingService.shared.generateBriefing()
UserDefaults.standard.set(tomorrowString, forKey: "lastBriefingDate")
let briefingHour = UserDefaults.standard.integer(forKey: "morningBriefingHour")
let briefingMinute = UserDefaults.standard.integer(forKey: "morningBriefingMinute")
await MorningBriefingService.shared.schedule(hour: briefingHour, minute: briefingMinute)
}
}
}
var body: some Scene {
WindowGroup {
ContentView()
.overlay {
if let containerError, showContainerError {
VStack(spacing: 16) {
Image(systemName: "exclamationmark.triangle.fill")
.font(.largeTitle)
.foregroundStyle(.orange)
Text("Database Reset")
.font(.headline)
Text(containerError)
.font(.subheadline)
.multilineTextAlignment(.center)
.padding(.horizontal)
Button("Got it") {
showContainerError = false
}
.buttonStyle(.borderedProminent)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(.ultraThinMaterial)
.onAppear {
if isRecoverableError {
Task {
try? await ContinuousClock().sleep(for: .seconds(8), tolerance: .seconds(1))
withAnimation { showContainerError = false }
}
}
}
}
}
.task {
NetworkMonitor.shared.startMonitoring()
NetworkMonitor.shared.onConnectivityRestored = {
Task { await OfflineQueueService.shared.drainQueue(in: container.mainContext) }
}
_ = await NotificationService.shared.requestPermission()
// Request location BEFORE calendar/reminders so CalendarFoundation
// sees a valid location authorization state and doesn't log
// "Need the 'com.apple.locationd.effective_bundle' entitlement"
LocationService.shared.requestPermission()
// Location authorization is async via delegate; subsequent permissions do not depend on its result
_ = await ReminderService.shared.requestPermission()
_ = await CalendarService.shared.requestPermission()
KnownPlacesService.shared.loadIfNeeded()
await ReminderManager.shared.syncFromEventKit(in: container.mainContext)
await CalendarEventManager.shared.syncFromEventKit(in: container.mainContext)
TravelNudgeService.shared.setup(context: container.mainContext)
ReminderChatService.shared.setup(context: container.mainContext)
MorningBriefingService.shared.setup(context: container.mainContext)
NotificationService.shared.setup(context: container.mainContext)
ReminderManager.shared.startObservingEventKit(context: container.mainContext)
CalendarEventManager.shared.startObservingEventKit(context: container.mainContext)
if UserDefaults.standard.bool(forKey: "morningBriefingEnabled") {
let hour = UserDefaults.standard.integer(forKey: "morningBriefingHour")
let minute = UserDefaults.standard.integer(forKey: "morningBriefingMinute")
await MorningBriefingService.shared.schedule(hour: hour, minute: minute)
}
}
}
.modelContainer(container)
.onChange(of: scenePhase) { _, newPhase in
if newPhase == .active {
Task {
await OfflineQueueService.shared.drainQueue(in: container.mainContext)
await TravelNudgeService.shared.checkUpcomingReminders()
await ReminderManager.shared.syncFromEventKit(in: container.mainContext)
await CalendarEventManager.shared.syncFromEventKit(in: container.mainContext)
CalendarEventManager.shared.drainPendingSync(in: container.mainContext)
NotificationService.shared.updateBadgeCount(0)
NotificationService.shared.recalculateBadge(context: container.mainContext)
await Self.triggerBriefingIfNeeded()
await DailyJournalService.shared.journalIfNeeded(context: container.mainContext)
await MessagingTriggerService.shared.checkForMessagingReminders(modelContext: container.mainContext)
}
}
}
}
}