← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


commit a69db0dd12eb1f829d4d423834b11c18d138d379
parent f3f440a05dc6f794e4655787cd5065dc2fb322cd
Author: Michael Camilleri <[email protected]>
Date:   Sat, 17 Oct 2026 15:18:02 +0900

Add importing from Reporter and exporting to Settings

The Reporter importer and the JSON exporter existed but nothing in the
app ran them, so a Reporter archive couldn't be brought in and the
store couldn't be got out, even as a manual backup.

This commit adds a Data section to Settings. 'Import from Reporter'
picks a Reporter JSON export and imports it, showing the reports and
questions added and any reports already present or unreadable; the
full summary goes to the log as counts and IDs only. 'Export Reports'
writes the store to a temporary file and offers it to save, with
'Include Reporter Snapshots' adding each imported report's original
record.

A fresh install seeds the default questions, so importing on top of
them would have had the surveys ask both sets. An import that adds
questions now archives the defaults, and answers already given to them
keep their meaning.

With the archive imported, the timeline scrolled choppily due to how the
data was sectioned. The timeline now starts with the newest 300 reports,
and reaches back 500 more each time it's scrolled to its end.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Diffstat

MNotes/Design.md | 18++++++++++++++----
MReportage.xcodeproj/project.pbxproj | 4++++
MReportage/Services/ReporterImport/ReporterImportPlan.swift | 2++
MReportage/Services/ReporterImport/ReporterImporter.swift | 19+++++++++++++++++--
MReportage/Views/Home/HomeView.swift | 44+++++++++++++++++++++++++++++++++++++++++++-
AReportage/Views/Settings/DataSection.swift | 221+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MReportage/Views/Settings/SettingsView.swift | 9+++++----
MShared/Models/DefaultQuestions.swift | 5++++-
MShared/Persistence/ReportStore.swift | 18++++++++++++++++++
MTests/Unit/ReportStoreTests.swift | 15+++++++++++++++
MTests/Unit/ReporterImporterTests.swift | 19+++++++++++++++++++

11 files changed, 362 insertions(+), 12 deletions(-)

diff --git a/Notes/Design.md b/Notes/Design.md

@@ -97,7 +97,11 @@ The look is called Almanac: ink on paper, like a printed journal.
   and a line of context (locality and weather). Days are grouped in the
   device's time zone: grouping by each report's own zone would put reports out
   of order around midnight after a change of zone, which a sectioned fetch
-  can't show.
+  can't show. Grouping by a computed day loads every report the fetch
+  covers, and regroups them all whenever one changes (0.6 s and 0.25 s over
+  the imported archive), so the list covers the newest 300 reports to the
+  start of a day, and reaches back 500 more each time it's scrolled to its
+  end.
 - **Report detail:** tapping a report in the timeline pushes its detail view:
   the day, the time in the report's own zone and its kind, a map of where it
   was made (with a circle for the fix's accuracy), every
@@ -157,7 +161,9 @@ importer rebuilds them from the answers given, most common first.
 
 A fresh install starts with a default question set covering every question
 kind (`DefaultQuestions`). The defaults are only added to a store with no
-questions at all, so they never mix with an imported archive. They have fixed
+questions at all, and an import that adds questions archives them, so they
+never mix with an imported archive in the surveys; answers already given to
+them keep their meaning. They have fixed
 IDs (`reportage-default-` plus a name), so seeding is idempotent and two
 devices that both seed them end up with the same questions after syncing.
 Their prompts are written in the user's language at seeding time and are
@@ -798,7 +804,10 @@ Source: Reporter's JSON export, which has two top-level arrays, `questions` and
 
 ### Behaviour
 
-- Runs on the iPhone only, off the main actor, inserting in batches.
+- Runs on the iPhone only, off the main actor, inserting in batches. It's
+  started from **Import from Reporter** in Settings' Data section, which picks
+  the export with `fileImporter` and shows the counts when it's done; the full
+  summary goes to the log, as counts and IDs only.
 - **Idempotent and repeatable.** Reports, questions and tokens keep their
   Reporter IDs, so importing a newer export adds only what's new. The user can
   keep using Reporter while Reportage is under development and re-import at
@@ -821,7 +830,8 @@ Source: Reporter's JSON export, which has two top-level arrays, `questions` and
 
 ## Export
 
-On-demand JSON through `ShareLink` and `fileExporter`. The top level is
+On-demand JSON from **Export Reports** in Settings' Data section, written to
+a temporary file and saved with `fileExporter`. The top level is
 `{"format": "reportage", "version": 1, "exportedAt": ..., "questions": [...],
 "tokens": [...], "reports": [...]}`. Tokens are included because responses
 refer to them by ID. Dates inside a report are ISO 8601 with the report's own

diff --git a/Reportage.xcodeproj/project.pbxproj b/Reportage.xcodeproj/project.pbxproj

@@ -45,6 +45,7 @@
 		964408E4D25713F627048C77 /* ModelCodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C606A9B0EF8D84950B9681B /* ModelCodingTests.swift */; };
 		97BC8348B7F48AF0473691FC /* ReportStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28AD66BC8ED4AEABF6640108 /* ReportStore.swift */; };
 		9EF3CB3707CD6B5AFFD3B767 /* ReporterArchive.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1C5F0F722477CDA949F018 /* ReporterArchive.swift */; };
+		A1FBFB9809DD3FF52BD7E5A7 /* DataSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA2E66BAB2463FD51EFE9F52 /* DataSection.swift */; };
 		A740B635075EB81AA70ED815 /* ReportDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F498961A14F24AE6CC37453C /* ReportDetailView.swift */; };
 		B00AC94E13BC9C602179953E /* SurveyModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E382405EE9DBEC8EE616C1D /* SurveyModelTests.swift */; };
 		B454D3067CD611AE55E30A1D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 633FE6CD8111A433CA9BE7EC /* AppDelegate.swift */; };
@@ -152,6 +153,7 @@
 		C17F34F71E3E13AF890DA2F3 /* Reportage.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Reportage.entitlements; sourceTree = "<group>"; };
 		C269C1BE83C1A5E08AC087E3 /* ReportDetails.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportDetails.swift; sourceTree = "<group>"; };
 		C3C7B68925A281EF806BB9B8 /* Theme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Theme.swift; sourceTree = "<group>"; };
+		CA2E66BAB2463FD51EFE9F52 /* DataSection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DataSection.swift; sourceTree = "<group>"; };
 		CC1C5F0F722477CDA949F018 /* ReporterArchive.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterArchive.swift; sourceTree = "<group>"; };
 		CD433A98973E8B13E42230A1 /* ReportageExporter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageExporter.swift; sourceTree = "<group>"; };
 		D03D0770BA2E26D7E4A7DECC /* ReportageModel.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = ReportageModel.xcdatamodel; sourceTree = "<group>"; };
@@ -359,6 +361,7 @@
 		B74082E720FBA1EF05FE11E4 /* Settings */ = {
 			isa = PBXGroup;
 			children = (
+				CA2E66BAB2463FD51EFE9F52 /* DataSection.swift */,
 				81BA515BEA1B0B68CE0D1326 /* SettingsView.swift */,
 			);
 			path = Settings;
@@ -535,6 +538,7 @@
 				E8C13757BF3E2C8384F104A1 /* AppleWeather.swift in Sources */,
 				DF632654B427EE32C44C6F78 /* Context.swift in Sources */,
 				D487802C53EA0E96698BE151 /* ContextCapture.swift in Sources */,
+				A1FBFB9809DD3FF52BD7E5A7 /* DataSection.swift in Sources */,
 				BD8D81CBF8C3DE544BB7540C /* DefaultQuestions.swift in Sources */,
 				D0497C9835A2502936591DC1 /* DisplayRule.swift in Sources */,
 				406D536D7764B3FEB140CAA0 /* EntityMapping.swift in Sources */,

diff --git a/Reportage/Services/ReporterImport/ReporterImportPlan.swift b/Reportage/Services/ReporterImport/ReporterImportPlan.swift

@@ -79,6 +79,8 @@ struct ReporterImportSummary: Hashable, Sendable {
 
     var questionsInserted = 0
     var questionsUpdated = 0
+    /// Default questions archived because the import added Reporter's.
+    var defaultQuestionsArchived = 0
     var tokensInserted = 0
     var tokensAlreadyPresent = 0
     var reportsInserted = 0

diff --git a/Reportage/Services/ReporterImport/ReporterImporter.swift b/Reportage/Services/ReporterImport/ReporterImporter.swift

@@ -8,6 +8,10 @@ import Foundation
 /// importing a newer export adds only what's new. Existing questions and
 /// tokens keep any edits made in Reportage, so a renamed token stays renamed;
 /// only choice options grow.
+///
+/// The default questions a fresh install starts with are archived when an
+/// import adds questions, so the surveys ask Reporter's questions rather
+/// than both sets. Answers already given to the defaults keep their meaning.
 struct ReporterImporter: Sendable {
     static let batchSize = 500
 
@@ -23,7 +27,7 @@ struct ReporterImporter: Sendable {
         let plan = ReporterImportPlan(archive: try ReporterArchive(data: data), now: now)
         let context = persistence.newBackgroundContext()
         return try await context.perform {
-            try Self.write(plan, into: context)
+            try Self.write(plan, into: context, now: now)
         }
     }
 
@@ -40,7 +44,8 @@ struct ReporterImporter: Sendable {
 
     private static func write(
         _ plan: ReporterImportPlan,
-        into context: NSManagedObjectContext
+        into context: NSManagedObjectContext,
+        now: Date
     ) throws -> ReporterImportSummary {
         var summary = plan.summary
 
@@ -63,6 +68,16 @@ struct ReporterImporter: Sendable {
                 summary.questionsInserted += 1
             }
         }
+        if summary.questionsInserted > 0 {
+            for entity in existingQuestions where entity.id?.hasPrefix(DefaultQuestions.idPrefix) == true {
+                var question = try entity.question()
+                guard question.archivedAt == nil else { continue }
+                question.archivedAt = now
+                question.modifiedAt = now
+                try entity.update(from: question)
+                summary.defaultQuestionsArchived += 1
+            }
+        }
         try context.save()
         context.reset()
 

diff --git a/Reportage/Views/Home/HomeView.swift b/Reportage/Views/Home/HomeView.swift

@@ -128,11 +128,31 @@ struct ReportList: View {
     /// Opens a report's details.
     let onOpen: (UUID) -> Void
 
+    @Environment(\.reportStore) private var store
     @SectionedFetchRequest(fetchRequest: ReportList.request, sectionIdentifier: \ReportEntity.dayKey)
     private var days: SectionedFetchResults<String, ReportEntity>
+    /// How many of the newest reports the list covers. Grouping into days
+    /// loads every report the fetch covers, and regroups them all whenever
+    /// one changes, so the list starts with the newest and reaches further
+    /// back as it's scrolled to its end.
+    @State private var reach = Self.page
+    @State private var start = ListStart.unknown
+
+    private static let page = 300
+    private static let morePage = 500
+
+    private enum ListStart: Hashable {
+        /// Not worked out yet: the list is empty until it is.
+        case unknown
+        /// Reports from this date on, with older ones beyond.
+        case date(Date)
+        /// Every report.
+        case all
+    }
 
     private static var request: NSFetchRequest<ReportEntity> {
         let request = ReportEntity.fetchRequest()
+        request.predicate = NSPredicate(value: false)
         request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
         request.fetchBatchSize = 40
         request.relationshipKeyPathsForPrefetching = ["responses"]
@@ -146,7 +166,7 @@ struct ReportList: View {
                 .listRowBackground(Theme.paper)
                 .listRowSeparatorTint(Theme.ink)
                 .listRowSeparator(.hidden, edges: .top)
-            if days.isEmpty {
+            if days.isEmpty && start == .all {
                 EmptyReports()
                     .listRowInsets(EdgeInsets(top: 0, leading: Theme.margin, bottom: 0, trailing: Theme.margin))
                     .listRowBackground(Theme.paper)
@@ -164,10 +184,32 @@ struct ReportList: View {
                     DayHeader(date: day.first?.date)
                 }
             }
+            if case .date = start {
+                // Drawn only once the list is scrolled near its end.
+                ProgressView()
+                    .frame(maxWidth: .infinity)
+                    .listRowBackground(Theme.paper)
+                    .listRowSeparator(.hidden)
+                    // A new row each time the list reaches further, so it
+                    // keeps reaching while its end is still in view.
+                    .id(start)
+                    .onAppear { reach += Self.morePage }
+            }
         }
         .listStyle(.plain)
         .scrollContentBackground(.hidden)
         .background(Theme.paper)
+        .task(id: reach) { await widen() }
+    }
+
+    private func widen() async {
+        guard let store, let date = try? await store.listStart(covering: reach) else {
+            start = .all
+            days.nsPredicate = nil
+            return
+        }
+        start = .date(date)
+        days.nsPredicate = NSPredicate(format: "date >= %@", date as NSDate)
     }
 
     /// A report is tapped to see it in full, where it can be edited or

diff --git a/Reportage/Views/Settings/DataSection.swift b/Reportage/Views/Settings/DataSection.swift

@@ -0,0 +1,221 @@
+import CoreTransferable
+import OSLog
+import SwiftUI
+import UniformTypeIdentifiers
+
+/// Importing a Reporter export and exporting the store as JSON.
+struct DataSection: View {
+    @Environment(\.reportStore) private var store
+    @State private var task: DataTask?
+    @State private var isChoosingImport = false
+    @State private var includeLegacy = false
+    @State private var exported: ExportFile?
+    @State private var outcome: Outcome?
+
+    private let logger = Logger(subsystem: "net.inqk.reportage", category: "Data")
+
+    private enum DataTask {
+        case importing
+        case exporting
+    }
+
+    /// What's shown in an alert once a task finishes.
+    private struct Outcome {
+        let title: LocalizedStringKey
+        let message: String
+    }
+
+    var body: some View {
+        Section {
+            Button {
+                isChoosingImport = true
+            } label: {
+                TaskLabel("Import from Reporter", isRunning: task == .importing)
+            }
+            .disabled(task != nil || store == nil)
+            .settingsRow()
+            SettingsNote {
+                Text(
+                    "Adds the reports from a Reporter JSON export. Reports already imported are left alone, so a newer export can be imported again."
+                )
+            }
+            Toggle("Include Reporter Snapshots", isOn: $includeLegacy)
+                .settingsRow()
+            Button {
+                Task { await export() }
+            } label: {
+                TaskLabel("Export Reports", isRunning: task == .exporting)
+            }
+            .disabled(task != nil || store == nil)
+            .settingsRow()
+            SettingsNote {
+                Text(
+                    "Saves every question, answer and report as a JSON file. Reporter snapshots are the original records of imported reports, kept exactly as Reporter exported them."
+                )
+            }
+        } header: {
+            SettingsHeading("Data")
+        }
+        .fileImporter(isPresented: $isChoosingImport, allowedContentTypes: [.json]) { result in
+            switch result {
+            case .success(let url):
+                Task { await importArchive(at: url) }
+            case .failure(let error):
+                outcome = Outcome(title: "Couldn't Import", message: error.localizedDescription)
+            }
+        }
+        .fileExporter(
+            isPresented: isSavingExport,
+            item: exported,
+            contentTypes: [.json],
+            defaultFilename: exported?.url.lastPathComponent
+        ) { result in
+            if case .failure(let error) = result {
+                outcome = Outcome(title: "Couldn't Export", message: error.localizedDescription)
+            }
+            finishExport()
+        } onCancellation: {
+            finishExport()
+        }
+        .alert(outcome?.title ?? "", isPresented: isShowingOutcome, presenting: outcome) { _ in
+            Button("OK") {}
+        } message: { outcome in
+            Text(outcome.message)
+        }
+    }
+
+    private var isShowingOutcome: Binding<Bool> {
+        Binding(
+            get: { outcome != nil },
+            set: { if !$0 { outcome = nil } })
+    }
+
+    private var isSavingExport: Binding<Bool> {
+        Binding(
+            get: { exported != nil },
+            set: { if !$0 { finishExport() } })
+    }
+
+    private func importArchive(at url: URL) async {
+        guard let store else { return }
+        task = .importing
+        defer { task = nil }
+        let isScoped = url.startAccessingSecurityScopedResource()
+        defer { if isScoped { url.stopAccessingSecurityScopedResource() } }
+        do {
+            let summary = try await ReporterImporter(persistence: store.persistence).importArchive(at: url)
+            log(summary)
+            outcome = Outcome(title: "Import Finished", message: Self.message(for: summary))
+        } catch {
+            logger.error("Couldn't import a Reporter export: \(error)")
+            outcome = Outcome(title: "Couldn't Import", message: error.localizedDescription)
+        }
+    }
+
+    private func export() async {
+        guard let store else { return }
+        task = .exporting
+        defer { task = nil }
+        let date = Date().formatted(.iso8601.year().month().day())
+        let url = URL.temporaryDirectory.appending(path: "Reportage \(date).json")
+        do {
+            let options = ReportageExportOptions(includeLegacy: includeLegacy)
+            let summary = try await ReportageExporter(persistence: store.persistence)
+                .export(to: url, options: options)
+            logger.info("Exported \(summary.reports) reports, \(summary.questions) questions, \(summary.tokens) tokens")
+            exported = ExportFile(url: url)
+        } catch {
+            logger.error("Couldn't export: \(error)")
+            outcome = Outcome(title: "Couldn't Export", message: error.localizedDescription)
+        }
+    }
+
+    /// Removes the temporary copy once it's been saved or the save cancelled.
+    private func finishExport() {
+        guard let exported else { return }
+        try? FileManager.default.removeItem(at: exported.url)
+        self.exported = nil
+    }
+
+    /// Counts and fallbacks only: IDs, never the contents of reports.
+    private func log(_ summary: ReporterImportSummary) {
+        logger.info(
+            """
+            Imported \(summary.reportsInserted) reports (\(summary.reportsAlreadyPresent) already present), \
+            \(summary.questionsInserted) questions (\(summary.questionsUpdated) updated, \
+            \(summary.defaultQuestionsArchived) defaults archived), \
+            \(summary.tokensInserted) tokens (\(summary.tokensAlreadyPresent) already present); \
+            \(summary.fallbacks.count) fallbacks, \(summary.failures.count) failures
+            """)
+        for warning in summary.warnings {
+            logger.notice("Import warning: \(warning)")
+        }
+        for failure in summary.failures {
+            logger.error("Snapshot \(failure.index) (\(failure.reportID ?? "no ID")) failed: \(failure.message)")
+        }
+    }
+
+    static func message(for summary: ReporterImportSummary) -> String {
+        var lines: [String] = []
+        if summary.reportsInserted == 0 {
+            lines.append(String(localized: "No new reports. Everything in this export was already imported."))
+        } else {
+            lines.append(
+                String(
+                    localized:
+                        "Added ^[\(summary.reportsInserted) report](inflect: true) and ^[\(summary.questionsInserted) question](inflect: true)."
+                ))
+        }
+        if summary.reportsAlreadyPresent > 0 {
+            lines.append(
+                String(
+                    localized:
+                        "^[\(summary.reportsAlreadyPresent) report](inflect: true) had already been imported."
+                ))
+        }
+        if summary.defaultQuestionsArchived > 0 {
+            lines.append(String(localized: "The surveys now ask Reporter's questions instead of the default ones."))
+        }
+        if !summary.failures.isEmpty {
+            lines.append(
+                String(
+                    localized:
+                        "Skipped ^[\(summary.failures.count) report](inflect: true) that couldn't be read."
+                ))
+        }
+        return lines.joined(separator: "\n\n")
+    }
+}
+
+/// A button's title, with a spinner while its task runs.
+private struct TaskLabel: View {
+    let title: LocalizedStringKey
+    let isRunning: Bool
+
+    init(_ title: LocalizedStringKey, isRunning: Bool) {
+        self.title = title
+        self.isRunning = isRunning
+    }
+
+    var body: some View {
+        HStack {
+            Text(title)
+            Spacer()
+            if isRunning {
+                ProgressView()
+            }
+        }
+        .contentShape(.rect)
+    }
+}
+
+/// A finished export, waiting to be saved.
+private struct ExportFile: Transferable {
+    let url: URL
+
+    static var transferRepresentation: some TransferRepresentation {
+        FileRepresentation(exportedContentType: .json) { file in
+            SentTransferredFile(file.url)
+        }
+    }
+}

diff --git a/Reportage/Views/Settings/SettingsView.swift b/Reportage/Views/Settings/SettingsView.swift

@@ -2,7 +2,7 @@ import CoreLocation
 import SwiftUI
 import UserNotifications
 
-/// Settings: for now, when random prompts come.
+/// Settings: when random prompts come, and importing and exporting.
 struct SettingsView: View {
     @Environment(\.reportStore) private var store
     @Environment(\.scenePhase) private var scenePhase
@@ -76,6 +76,7 @@ struct SettingsView: View {
                         SettingsHeading("Timing")
                     }
                 }
+                DataSection()
                 #if DEBUG
                     ScheduledPrompts(generation: scheduleGeneration)
                 #endif
@@ -203,7 +204,7 @@ private struct SettingsTitle: View {
 }
 
 /// A section heading in small spaced capitals, like a day in the timeline.
-private struct SettingsHeading: View {
+struct SettingsHeading: View {
     let title: LocalizedStringKey
 
     init(_ title: LocalizedStringKey) {
@@ -225,7 +226,7 @@ private struct SettingsHeading: View {
 
 /// An explanation beneath a section's settings, in the muted footnote the
 /// timeline uses for context.
-private struct SettingsNote<Content: View>: View {
+struct SettingsNote<Content: View>: View {
     @ViewBuilder let content: Content
 
     var body: some View {
@@ -241,7 +242,7 @@ private struct SettingsNote<Content: View>: View {
 extension View {
     /// A row of settings on paper, at the screen's margin, ruled like the
     /// timeline.
-    fileprivate func settingsRow() -> some View {
+    func settingsRow() -> some View {
         listRowInsets(EdgeInsets(top: 10, leading: Theme.margin, bottom: 10, trailing: Theme.margin))
             .listRowBackground(Theme.paper)
             .listRowSeparatorTint(Theme.rule)

diff --git a/Shared/Models/DefaultQuestions.swift b/Shared/Models/DefaultQuestions.swift

@@ -7,6 +7,9 @@ import Foundation
 /// they sync. Prompts and options are resolved in the user's language when the
 /// questions are seeded; after that they're ordinary data the user can edit.
 enum DefaultQuestions {
+    /// The start of every default question's ID.
+    static let idPrefix = "reportage-default-"
+
     static func make(now: Date) -> [Question] {
         func question(
             _ id: String,
@@ -16,7 +19,7 @@ enum DefaultQuestions {
             askOn: SurveyKinds
         ) -> Question {
             Question(
-                id: "reportage-default-\(id)",
+                id: idPrefix + id,
                 prompt: prompt,
                 kind: kind,
                 options: options,

diff --git a/Shared/Persistence/ReportStore.swift b/Shared/Persistence/ReportStore.swift

@@ -116,6 +116,24 @@ struct ReportStore: Sendable {
         }
     }
 
+    /// Where a list of the newest `count` reports should start: the start of
+    /// the day, in `calendar`, of the first report beyond them, so the list
+    /// holds at least `count` reports and no day is cut short. `nil` when
+    /// there are no more than `count` reports, so the list holds them all.
+    func listStart(covering count: Int, calendar: Calendar = .current) async throws -> Date? {
+        let context = persistence.newBackgroundContext()
+        return try await context.perform {
+            let request = NSFetchRequest<NSDictionary>(entityName: "ReportEntity")
+            request.resultType = .dictionaryResultType
+            request.propertiesToFetch = ["date"]
+            request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
+            request.fetchOffset = count
+            request.fetchLimit = 1
+            guard let date = try context.fetch(request).first?["date"] as? Date else { return nil }
+            return calendar.startOfDay(for: date)
+        }
+    }
+
     /// Sets the context of a report saved before its capture finished.
     func setContext(_ captured: Context, for id: UUID, now: Date = Date()) async throws {
         let context = persistence.newBackgroundContext()

diff --git a/Tests/Unit/ReportStoreTests.swift b/Tests/Unit/ReportStoreTests.swift

@@ -314,4 +314,19 @@ struct ReportStoreTests {
         #expect(reports == [report])
         #expect(tokens == [token])
     }
+
+    @Test("A list of the newest reports starts at the start of a day, or covers them all")
+    func listStart() async throws {
+        for number in [1, 2, 3, 30, 50] {
+            try await store.insert(Self.report(number, responses: []))
+        }
+        var calendar = Calendar(identifier: .gregorian)
+        calendar.timeZone = .gmt
+        let day = { (number: Int) in Date(timeIntervalSince1970: TimeInterval(number) * 86400) }
+
+        #expect(try await store.listStart(covering: 1, calendar: calendar) == day(1))
+        #expect(try await store.listStart(covering: 2, calendar: calendar) == day(0))
+        #expect(try await store.listStart(covering: 4, calendar: calendar) == day(0))
+        #expect(try await store.listStart(covering: 5, calendar: calendar) == nil)
+    }
 }

diff --git a/Tests/Unit/ReporterImporterTests.swift b/Tests/Unit/ReporterImporterTests.swift

@@ -123,6 +123,25 @@ struct ReporterImporterTests {
         #expect(question.options == ["Poorly", "Well"])
     }
 
+    @Test("Importing archives the default questions, so the surveys ask Reporter's")
+    func defaultsArchived() async throws {
+        let now = Date(timeIntervalSince1970: 0)
+        try await ReportStore(persistence: persistence).seedDefaultQuestionsIfNeeded(now: now)
+        let defaults = DefaultQuestions.make(now: now).count
+
+        let summary = try await importer.importArchive(try Fixtures.reporterExport(), now: now)
+        #expect(summary.defaultQuestionsArchived == defaults)
+        let questions = try await storedQuestions()
+        #expect(questions.count == 9 + defaults)
+        #expect(
+            questions.filter { $0.id.hasPrefix(DefaultQuestions.idPrefix) }.allSatisfy { $0.archivedAt == now })
+        let plan = ReporterImportPlan(archive: try Fixtures.reporterArchive(), now: now)
+        #expect(Set(questions.filter { !$0.id.hasPrefix(DefaultQuestions.idPrefix) }) == Set(plan.questions))
+
+        let again = try await importer.importArchive(try Fixtures.reporterExport(), now: now)
+        #expect(again.defaultQuestionsArchived == 0)
+    }
+
     @Test("The verifier finds no differences after an import")
     func verifierPasses() async throws {
         let data = try Fixtures.reporterExport()