docs(health-profile): 添加防编造加固修订记录到导出健康档案设计文档 补充了关于导出摘要出现虚构病例问题的详细分析和修复方案, 包括检索策略优化、空数据兜底处理和prompt重写等三层防护措施。 ```
77 lines
3.3 KiB
Swift
77 lines
3.3 KiB
Swift
import SwiftUI
|
||
import SwiftData
|
||
|
||
@main
|
||
struct KangkangApp: App {
|
||
@State private var lang = LanguageManager.shared
|
||
|
||
var sharedModelContainer: ModelContainer = {
|
||
let schema = Schema([
|
||
Indicator.self,
|
||
Report.self,
|
||
DiaryEntry.self,
|
||
Asset.self,
|
||
ChatTurn.self,
|
||
Symptom.self,
|
||
UserProfile.self,
|
||
MetricReminder.self,
|
||
CustomMonitorMetric.self,
|
||
HealthExport.self,
|
||
CustomReminder.self,
|
||
])
|
||
let config = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
|
||
do {
|
||
return try ModelContainer(for: schema, configurations: [config])
|
||
} catch {
|
||
// Demo 阶段 schema 仍在演进:某次改动若超出 SwiftData 自动轻量迁移能力
|
||
// (最常见:给已存在的 @Model 新增「非可选且无内联默认值」的属性),自动迁移会抛错。
|
||
// 这里不再静默删库,而是把旧 store 连同 -wal/-shm 整体挪到带时间戳的备份目录后重建——
|
||
// 既保证 App 能启动,又让旧数据可手动恢复(挪不动才降级为删除)。
|
||
// ⚠️ 正式发布前仍应改为 VersionedSchema + SchemaMigrationPlan 的正式迁移。
|
||
// 注:新增 @Model 属性请一律给「可选」或「内联默认值」,即可走轻量迁移、不触发本兜底。
|
||
print("⚠️ ModelContainer 创建失败,备份旧 store 后重建: \(error)")
|
||
KangkangApp.backupIncompatibleStore(at: config.url)
|
||
do {
|
||
return try ModelContainer(for: schema, configurations: [config])
|
||
} catch {
|
||
fatalError("Could not create ModelContainer even after store reset: \(error)")
|
||
}
|
||
}
|
||
}()
|
||
|
||
/// 把与新 schema 不兼容的旧 store(含 `-wal` / `-shm`)挪到
|
||
/// `Application Support/StoreBackups/<时间戳>/`,而不是直接删除。
|
||
/// 既清出路径让新库能建起来,又把旧数据留作可手动恢复的备份;挪不动时才降级为删除。
|
||
private static func backupIncompatibleStore(at storeURL: URL) {
|
||
let fm = FileManager.default
|
||
let fmt = DateFormatter()
|
||
fmt.locale = Locale(identifier: "en_US_POSIX")
|
||
fmt.dateFormat = "yyyyMMdd-HHmmss"
|
||
let stamp = fmt.string(from: Date())
|
||
let backupDir = storeURL.deletingLastPathComponent()
|
||
.appendingPathComponent("StoreBackups/\(stamp)", isDirectory: true)
|
||
try? fm.createDirectory(at: backupDir, withIntermediateDirectories: true)
|
||
for suffix in ["", "-wal", "-shm"] {
|
||
let src = URL(fileURLWithPath: storeURL.path + suffix)
|
||
guard fm.fileExists(atPath: src.path) else { continue }
|
||
let dst = backupDir.appendingPathComponent(src.lastPathComponent)
|
||
do {
|
||
try fm.moveItem(at: src, to: dst)
|
||
} catch {
|
||
try? fm.removeItem(at: src) // 挪不动就删,至少保证能启动
|
||
}
|
||
}
|
||
}
|
||
|
||
var body: some Scene {
|
||
WindowGroup {
|
||
AppLockContainer {
|
||
RootView()
|
||
.environment(\.locale, lang.locale)
|
||
.id(lang.current) // 语言切换 → 整树重建,即时生效
|
||
}
|
||
}
|
||
.modelContainer(sharedModelContainer)
|
||
}
|
||
}
|