← All repositories

reportage

A life-logging app for iPhone

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


commit 753c3befa3255582b09fff9a88d2e30c1c8c3cb9
parent 8681f56d21c95c441544e0d42a01795538463a52
Author: Michael Camilleri <[email protected]>
Date:   Fri, 16 Oct 2026 15:19:19 +0900

Add JSON export of the store

The design calls for an on-demand export in a documented, versioned
format, so the life log is never locked inside the app. Until now there
was a way to bring the Reporter archive in but no way to get anything
out.

This commit adds an exporter that writes the questions, tokens and
reports in the store to a Reportage JSON file, and types that read the
file back into the model. Tokens are part of the export because
responses refer to them by ID; without them, activity, people and place
answers could not be read. Every date inside a report, including those
in its context, is written with the report's own offset, so the local
time can be read straight off the file; other dates are in UTC.

Records are written one per line as they are read, in batches, so the
decade-long archive is never held in memory as a whole and the file can
be processed line by line. The original Reporter snapshots are left out
by default and, when included, keep their bytes exactly as a string.
Reading rejects other formats and newer versions.

The format is documented in Notes/ExportFormat.md, and the design
document now lists tokens and exportedAt at the top level. There is no
UI for the export yet.

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

Diffstat

MNotes/Design.md | 12++++++++----
ANotes/ExportFormat.md | 144+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MReportage.xcodeproj/project.pbxproj | 20++++++++++++++++++++
AReportage/Services/Export/ReportageExport.swift | 255+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AReportage/Services/Export/ReportageExporter.swift | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ATests/Unit/ReportageExportTests.swift | 174+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

6 files changed, 726 insertions(+), 4 deletions(-)

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

@@ -502,10 +502,14 @@ 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
-`{"format": "reportage", "version": 1, "questions": [...], "reports": [...]}`.
-Dates are ISO 8601 with the report's own offset, plus an explicit `timeZone`
-field. The schema is documented in `Notes/ExportFormat.md` and covered by
-round-trip tests. Including the `legacy` blobs is optional (off by default).
+`{"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
+offset, plus an explicit `timeZone` field; other dates are UTC. Records are
+written one per line, in batches, so the archive is never held in memory as a
+whole. The schema is documented in `Notes/ExportFormat.md` and covered by
+round-trip tests. Including the `legacy` snapshots is optional (off by
+default); when included, each is the original JSON text as a string.
 
 ## Phases
 

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

@@ -0,0 +1,144 @@
+# Reportage Export Format
+
+Version 1. Written by `ReportageExporter` and read by `ReportageExport.decode`.
+
+## File
+
+A UTF-8 JSON object:
+
+```json
+{"format":"reportage","version":1,"exportedAt":"2026-10-16T06:00:00Z",
+"questions":[
+{...},
+{...}
+],
+"tokens":[
+...
+],
+"reports":[
+...
+]}
+```
+
+- `format` is always `"reportage"`.
+- `version` is the format version. A reader should reject versions newer than
+  it knows. Fields may be added within a version; a reader should ignore keys
+  it doesn't recognise.
+- Each record is on its own line, so the file can be processed line by line or
+  with `jq`. Keys within a record are sorted.
+- Questions are ordered by `order` then `id`, tokens by `questionID` then `id`,
+  and reports by `date` then `id`.
+- Optional fields are left out when they have no value, rather than written as
+  `null`.
+
+### Dates
+
+Dates are ISO 8601 strings with a numeric offset (RFC 3339). Every date inside
+a report, including those in its context, is written in the report's own time
+zone, so the local time can be read directly from the string:
+`2025-01-15T09:30:00+11:00`. All other dates are in UTC: `...Z`.
+
+Fractional seconds appear only when a date has them, to millisecond precision:
+`2025-01-15T09:31:00.250+11:00`.
+
+## Question
+
+| Key           | Type      | Notes                                              |
+|---------------|-----------|----------------------------------------------------|
+| `id`          | string    | Questions imported from Reporter keep Reporter's IDs. |
+| `prompt`      | string    | The current wording.                               |
+| `kind`        | string    | `yesNo`, `choice`, `tokens`, `people`, `location`, `number` or `note`. |
+| `options`     | [string]? | The fixed answer list of a `choice` question.      |
+| `placeholder` | string?   |                                                    |
+| `askOn`       | [string]  | Surveys the question appears in: `random`, `wake`, `bedtime`. Manual reports use the `random` survey. |
+| `order`       | integer   | Sort order within a survey.                        |
+| `archivedAt`  | date?     | Questions are archived, never deleted.             |
+| `modifiedAt`  | date      |                                                    |
+
+## Token
+
+A reusable answer to a `tokens`, `people` or `location` question. Responses
+refer to tokens by ID, so a token's `text` is the name of every answer using it.
+
+| Key           | Type      | Notes                                              |
+|---------------|-----------|----------------------------------------------------|
+| `id`          | string    |                                                    |
+| `questionID`  | string    | The question the token belongs to.                 |
+| `text`        | string    | The name shown.                                    |
+| `place`       | object?   | Location tokens only. See below.                   |
+| `mergedInto`  | string?   | Set when the token was merged into another. Read answers referring to this token as referring to that one, following the chain if it has several steps. |
+| `archivedAt`  | date?     |                                                    |
+| `modifiedAt`  | date      |                                                    |
+
+`place`:
+
+| Key           | Type      | Notes                                              |
+|---------------|-----------|----------------------------------------------------|
+| `coordinate`  | object?   | `{"latitude": number, "longitude": number}`, a representative point. |
+| `names`       | [object]  | Directory names by language: `{"language": "ja", "text": "..."}` (BCP 47 tags). |
+| `externalID`  | object?   | `{"source": "foursquare" | "mapKit", "value": string}`. |
+
+## Report
+
+| Key           | Type      | Notes                                              |
+|---------------|-----------|----------------------------------------------------|
+| `id`          | string    | Uppercase UUID. Imported reports keep Reporter's IDs. |
+| `date`        | date      | The moment described: when the prompt fired or the passive log was made. |
+| `timeZone`    | string    | IANA identifier, for example `Asia/Tokyo`.         |
+| `kind`        | string    | `random`, `wake`, `bedtime` or `manual`.           |
+| `trigger`     | string    | `notification`, `app`, `watch`, `intent` or `imported`. |
+| `state`       | string    | `passive` (logged, awaiting answers) or `complete`. |
+| `promptedAt`  | date?     | When the notification that prompted it fired.      |
+| `completedAt` | date?     | When the survey was submitted.                     |
+| `context`     | object    | See [Context](#context). `{}` when nothing was captured. |
+| `responses`   | [object]  | In survey order. See below.                        |
+| `legacy`      | string?   | Imported reports only, and only if the export was made with legacy data included (off by default): the original Reporter snapshot JSON, byte for byte, as a string. |
+| `modifiedAt`  | date      |                                                    |
+
+### Response
+
+| Key           | Type      | Notes                                              |
+|---------------|-----------|----------------------------------------------------|
+| `questionID`  | string    |                                                    |
+| `prompt`      | string    | The wording when the question was answered.        |
+| `value`       | object?   | Absent when the question was shown but skipped.    |
+
+`value` has exactly one key, which gives its shape:
+
+| Key       | Value                       | Used by                          |
+|-----------|-----------------------------|----------------------------------|
+| `options` | [string]                    | `yesNo`, `choice`                |
+| `tokens`  | [string], token IDs         | `tokens`, `people`               |
+| `number`  | number                      | `number`                         |
+| `text`    | string                      | `note`                           |
+| `place`   | object                      | `location`                       |
+
+A `place` value is `{"tokenID": string, "coordinate": {...}?, "accuracy":
+number?}`: the place token chosen, and where the answer was given (accuracy in
+metres).
+
+### Context
+
+Every section is optional and absent when it wasn't captured. Units are
+metric.
+
+- `location`: `coordinate`; `altitude` (m); `horizontalAccuracy` and
+  `verticalAccuracy` (m); `speed` (m/s); `course` (degrees from true north);
+  `timestamp` (date of the fix); `placemark` with `name`, `subThoroughfare`,
+  `thoroughfare`, `subLocality`, `locality`, `subAdministrativeArea`,
+  `administrativeArea`, `postalCode`, `country`, `inlandWater` and `ocean`.
+- `weather`: `source` (`wunderground`, `darkSky` or `weatherKit`);
+  `backfilled` (true when fetched after the fact); `condition`; `temperature`,
+  `feelsLike` and `dewPoint` (°C); `humidity` (0–1); `pressure` (hPa);
+  `windSpeed` and `windGust` (km/h); `windDirection` (degrees, the direction
+  the wind comes from); `visibility` (km); `uvIndex`; `cloudCover` (0–1);
+  `precipitationChance` (0–1); `precipitationToday` (mm since local midnight).
+- `audio`: `source` (`microphone` or `healthEnvironmental`); `average` and
+  `peak` (dB: dBFS from the microphone, dBA SPL from Health).
+- `motion`: `steps` (so far today); `floorsAscended`; `floorsDescended`;
+  `pressure` (kPa); `relativeAltitude` (m).
+- `device`: `batteryLevel` (0–1); `batteryState` (`unplugged`, `charging` or
+  `full`); `connectivity` (`wifi`, `cellular` or `none`).
+- `photos`: `count` (photos taken since the previous report) and `photos`, a
+  list of `{date, coordinate, pixelWidth, pixelHeight, make, model}`, each
+  optional.

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

@@ -7,6 +7,7 @@
 	objects = {
 
 /* Begin PBXBuildFile section */
+		047D3797389624E8B4AF44B4 /* ReportageExporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD433A98973E8B13E42230A1 /* ReportageExporter.swift */; };
 		06415D2A2EDA6E92ECAC96FA /* Report.swift in Sources */ = {isa = PBXBuildFile; fileRef = B03734F91822E7F161432075 /* Report.swift */; };
 		25BC9F95DC40E31B1E4C6FBA /* Token.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3BE62142CCC4A791F05163A /* Token.swift */; };
 		28D2CDAAB0777233D4465A83 /* ReporterArchiveTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 487F88C880B5DE69964C6A37 /* ReporterArchiveTests.swift */; };
@@ -25,9 +26,11 @@
 		964408E4D25713F627048C77 /* ModelCodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C606A9B0EF8D84950B9681B /* ModelCodingTests.swift */; };
 		9EF3CB3707CD6B5AFFD3B767 /* ReporterArchive.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1C5F0F722477CDA949F018 /* ReporterArchive.swift */; };
 		AD22705E9154633961006403 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A5B8284AB637F8542721C8A /* ContentView.swift */; };
+		B510BB2C1C11D72DFE15E3C7 /* ReportageExportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DB6FF151DCEBC3913131834 /* ReportageExportTests.swift */; };
 		C5D94FEC4507054E6497E85B /* PersistenceController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61C0B5BB02ECDBE84F5F73FA /* PersistenceController.swift */; };
 		C8E02DEA2119E61D31667FFE /* ReporterImportPlanTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FD562C0C92C1D59881C771E /* ReporterImportPlanTests.swift */; };
 		DF632654B427EE32C44C6F78 /* Context.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F200EBD30BC12D2313E6C6F /* Context.swift */; };
+		E0137FEEBF13F5D14C07656F /* ReportageExport.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7F1ECC4B803EFFD88FFF52B /* ReportageExport.swift */; };
 		E68EF6274FD2F6D54D49F5BD /* ReporterImporterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 917C4579342FAC42F6C616FC /* ReporterImporterTests.swift */; };
 		E8CC84072697836F87D8A00D /* TestHelpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20C574BC234EDBD4056E2B7 /* TestHelpers.swift */; };
 		EFF44121C9ECBFBCAC1D7730 /* ReportageModel.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = A49FBFD55992A79B9A6492C4 /* ReportageModel.xcdatamodeld */; };
@@ -63,6 +66,7 @@
 		7196D553D769071DB876B606 /* ReporterTimeZones.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterTimeZones.swift; sourceTree = "<group>"; };
 		798E1DE82BD53EC5BEBA76B7 /* ReporterImportPlan.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImportPlan.swift; sourceTree = "<group>"; };
 		7ABE75DB46245AFDE8A44A48 /* Config.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Config.xcconfig; sourceTree = "<group>"; };
+		7DB6FF151DCEBC3913131834 /* ReportageExportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageExportTests.swift; sourceTree = "<group>"; };
 		7FD562C0C92C1D59881C771E /* ReporterImportPlanTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImportPlanTests.swift; sourceTree = "<group>"; };
 		917C4579342FAC42F6C616FC /* ReporterImporterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImporterTests.swift; sourceTree = "<group>"; };
 		9A5B8284AB637F8542721C8A /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = "<group>"; };
@@ -71,9 +75,11 @@
 		B007E6BACAA214C7332EF77C /* Question.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Question.swift; sourceTree = "<group>"; };
 		B03734F91822E7F161432075 /* Report.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Report.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>"; };
 		D4AFF3D49ED9E8AC69390925 /* JSONSlicerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONSlicerTests.swift; sourceTree = "<group>"; };
 		E21F898FF60FC3A6AFCA06E9 /* Reportage Unit Tests.xctest */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.cfbundle; path = "Reportage Unit Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
+		E7F1ECC4B803EFFD88FFF52B /* ReportageExport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageExport.swift; sourceTree = "<group>"; };
 /* End PBXFileReference section */
 
 /* Begin PBXGroup section */
@@ -113,6 +119,7 @@
 		60B58F5030E4A690025C51F5 /* Services */ = {
 			isa = PBXGroup;
 			children = (
+				AD85758A0521ED681067B90F /* Export */,
 				F7B8E02FFC282DCD163E25FE /* ReporterImport */,
 			);
 			path = Services;
@@ -133,6 +140,7 @@
 				D4AFF3D49ED9E8AC69390925 /* JSONSlicerTests.swift */,
 				5C606A9B0EF8D84950B9681B /* ModelCodingTests.swift */,
 				3DF3B490F336FCE1E1E3DDBA /* RealExportVerificationTests.swift */,
+				7DB6FF151DCEBC3913131834 /* ReportageExportTests.swift */,
 				487F88C880B5DE69964C6A37 /* ReporterArchiveTests.swift */,
 				917C4579342FAC42F6C616FC /* ReporterImporterTests.swift */,
 				7FD562C0C92C1D59881C771E /* ReporterImportPlanTests.swift */,
@@ -153,6 +161,15 @@
 			);
 			sourceTree = "<group>";
 		};
+		AD85758A0521ED681067B90F /* Export */ = {
+			isa = PBXGroup;
+			children = (
+				E7F1ECC4B803EFFD88FFF52B /* ReportageExport.swift */,
+				CD433A98973E8B13E42230A1 /* ReportageExporter.swift */,
+			);
+			path = Export;
+			sourceTree = "<group>";
+		};
 		B5824AFC6F20AC08247A4DC5 /* Products */ = {
 			isa = PBXGroup;
 			children = (
@@ -299,6 +316,7 @@
 				8ADBA81D5D9ECCDCD5BDA742 /* JSONSlicerTests.swift in Sources */,
 				964408E4D25713F627048C77 /* ModelCodingTests.swift in Sources */,
 				4A0DEFB7E69A9FC5EAAD99D4 /* RealExportVerificationTests.swift in Sources */,
+				B510BB2C1C11D72DFE15E3C7 /* ReportageExportTests.swift in Sources */,
 				28D2CDAAB0777233D4465A83 /* ReporterArchiveTests.swift in Sources */,
 				C8E02DEA2119E61D31667FFE /* ReporterImportPlanTests.swift in Sources */,
 				E68EF6274FD2F6D54D49F5BD /* ReporterImporterTests.swift in Sources */,
@@ -319,6 +337,8 @@
 				F38A1CCFAF016AB982EAB791 /* Question.swift in Sources */,
 				06415D2A2EDA6E92ECAC96FA /* Report.swift in Sources */,
 				961848A8D899BC67FA43F475 /* ReportageApp.swift in Sources */,
+				E0137FEEBF13F5D14C07656F /* ReportageExport.swift in Sources */,
+				047D3797389624E8B4AF44B4 /* ReportageExporter.swift in Sources */,
 				EFF44121C9ECBFBCAC1D7730 /* ReportageModel.xcdatamodeld in Sources */,
 				9EF3CB3707CD6B5AFFD3B767 /* ReporterArchive.swift in Sources */,
 				68DDAB8BB2E679EB7EC1E9C1 /* ReporterImportPlan.swift in Sources */,

diff --git a/Reportage/Services/Export/ReportageExport.swift b/Reportage/Services/Export/ReportageExport.swift

@@ -0,0 +1,255 @@
+import Foundation
+
+/// A Reportage JSON export, as documented in `Notes/ExportFormat.md`.
+///
+/// The export has its own record types rather than encoding the model types
+/// directly, so the documented format only changes when `version` does.
+/// `Context`, `Response` and `PlaceDetails` are the exception: their JSON is
+/// already the stored form and is part of the format as is.
+struct ReportageExport: Decodable, Sendable {
+    static let format = "reportage"
+    static let version = 1
+
+    var format: String
+    var version: Int
+    var exportedAt: Date
+    var questions: [ExportedQuestion]
+    var tokens: [ExportedToken]
+    var reports: [ExportedReport]
+
+    /// Decodes an export, rejecting other formats and newer versions.
+    static func decode(_ data: Data) throws -> ReportageExport {
+        let header = try ExportDates.decoder.decode(Header.self, from: data)
+        guard header.format == format else {
+            throw ReportageExportError.unknownFormat(header.format)
+        }
+        guard header.version <= version else {
+            throw ReportageExportError.unsupportedVersion(header.version)
+        }
+        return try ExportDates.decoder.decode(ReportageExport.self, from: data)
+    }
+
+    private struct Header: Decodable {
+        var format: String
+        var version: Int
+    }
+}
+
+enum ReportageExportError: Error, Equatable {
+    case unknownFormat(String)
+    case unsupportedVersion(Int)
+    case legacyNotUTF8(UUID)
+    case unknownSurvey(String)
+}
+
+/// Dates are ISO 8601 with a numeric offset. Dates inside a report use the
+/// report's own time zone, so the local time can be read straight off the
+/// file; everything else is in UTC. Fractional seconds appear only when a
+/// date has them, to millisecond precision.
+enum ExportDates {
+    /// The zone dates are written in. A report sets it while encoding itself.
+    @TaskLocal static var timeZone: TimeZone = .gmt
+
+    static func string(from date: Date, in timeZone: TimeZone) -> String {
+        let whole = date.timeIntervalSinceReferenceDate.rounded(.down)
+        let style = Date.ISO8601FormatStyle(
+            timeZoneSeparator: .colon,
+            includingFractionalSeconds: whole != date.timeIntervalSinceReferenceDate,
+            timeZone: timeZone
+        )
+        return date.formatted(style)
+    }
+
+    static func date(from string: String) -> Date? {
+        let fractional = Date.ISO8601FormatStyle(
+            timeZoneSeparator: .colon, includingFractionalSeconds: true)
+        let whole = Date.ISO8601FormatStyle(timeZoneSeparator: .colon)
+        return (try? fractional.parse(string)) ?? (try? whole.parse(string))
+    }
+
+    static var encoder: JSONEncoder {
+        let encoder = JSONEncoder()
+        encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
+        encoder.dateEncodingStrategy = .custom { date, encoder in
+            var container = encoder.singleValueContainer()
+            try container.encode(string(from: date, in: timeZone))
+        }
+        return encoder
+    }
+
+    static var decoder: JSONDecoder {
+        let decoder = JSONDecoder()
+        decoder.dateDecodingStrategy = .custom { decoder in
+            let container = try decoder.singleValueContainer()
+            let string = try container.decode(String.self)
+            guard let date = date(from: string) else {
+                throw DecodingError.dataCorruptedError(
+                    in: container, debugDescription: "Expected an ISO 8601 date: \(string)")
+            }
+            return date
+        }
+        return decoder
+    }
+}
+
+struct ExportedQuestion: Codable, Hashable, Sendable {
+    var id: String
+    var prompt: String
+    var kind: QuestionKind
+    var options: [String]?
+    var placeholder: String?
+    /// Survey names: `random`, `wake` and `bedtime`.
+    var askOn: [String]
+    var order: Int
+    var archivedAt: Date?
+    var modifiedAt: Date
+
+    private static let surveys: [(name: String, kind: SurveyKinds)] = [
+        ("random", .random), ("wake", .wake), ("bedtime", .bedtime),
+    ]
+
+    init(_ question: Question) {
+        id = question.id
+        prompt = question.prompt
+        kind = question.kind
+        options = question.options.isEmpty ? nil : question.options
+        placeholder = question.placeholder
+        askOn = Self.surveys.filter { question.askOn.contains($0.kind) }.map(\.name)
+        order = question.order
+        archivedAt = question.archivedAt
+        modifiedAt = question.modifiedAt
+    }
+
+    func question() throws -> Question {
+        var surveys: SurveyKinds = []
+        for name in askOn {
+            guard let survey = Self.surveys.first(where: { $0.name == name }) else {
+                throw ReportageExportError.unknownSurvey(name)
+            }
+            surveys.insert(survey.kind)
+        }
+        return Question(
+            id: id,
+            prompt: prompt,
+            kind: kind,
+            options: options ?? [],
+            placeholder: placeholder,
+            askOn: surveys,
+            order: order,
+            archivedAt: archivedAt,
+            modifiedAt: modifiedAt
+        )
+    }
+}
+
+struct ExportedToken: Codable, Hashable, Sendable {
+    var id: String
+    var questionID: String
+    var text: String
+    var place: PlaceDetails?
+    var mergedInto: String?
+    var archivedAt: Date?
+    var modifiedAt: Date
+
+    init(_ token: Token) {
+        id = token.id
+        questionID = token.questionID
+        text = token.text
+        place = token.place
+        mergedInto = token.mergedInto
+        archivedAt = token.archivedAt
+        modifiedAt = token.modifiedAt
+    }
+
+    func token() -> Token {
+        Token(
+            id: id,
+            questionID: questionID,
+            text: text,
+            place: place,
+            mergedInto: mergedInto,
+            archivedAt: archivedAt,
+            modifiedAt: modifiedAt
+        )
+    }
+}
+
+struct ExportedReport: Codable, Hashable, Sendable {
+    var id: UUID
+    var date: Date
+    var timeZone: String
+    var kind: ReportKind
+    var trigger: ReportTrigger
+    var state: ReportState
+    var promptedAt: Date?
+    var completedAt: Date?
+    var context: Context
+    var responses: [Response]
+    /// The original Reporter snapshot JSON, byte for byte, as a string. Only
+    /// present when the export includes legacy data.
+    var legacy: String?
+    var modifiedAt: Date
+
+    private enum CodingKeys: String, CodingKey {
+        case id, date, timeZone, kind, trigger, state, promptedAt, completedAt
+        case context, responses, legacy, modifiedAt
+    }
+
+    init(_ report: Report, includingLegacy: Bool) throws {
+        id = report.id
+        date = report.date
+        timeZone = report.timeZone
+        kind = report.kind
+        trigger = report.trigger
+        state = report.state
+        promptedAt = report.promptedAt
+        completedAt = report.completedAt
+        context = report.context
+        responses = report.responses
+        if includingLegacy, let blob = report.legacy {
+            guard let text = String(data: try LegacyBlob.decompress(blob), encoding: .utf8) else {
+                throw ReportageExportError.legacyNotUTF8(report.id)
+            }
+            legacy = text
+        }
+        modifiedAt = report.modifiedAt
+    }
+
+    func report() throws -> Report {
+        Report(
+            id: id,
+            date: date,
+            timeZone: timeZone,
+            kind: kind,
+            trigger: trigger,
+            state: state,
+            promptedAt: promptedAt,
+            completedAt: completedAt,
+            context: context,
+            responses: responses,
+            legacy: try legacy.map { try LegacyBlob.compress(Data($0.utf8)) },
+            modifiedAt: modifiedAt
+        )
+    }
+
+    func encode(to encoder: Encoder) throws {
+        // Every date in the report, including those inside its context, is
+        // written in the report's own zone.
+        let zone = TimeZone(identifier: timeZone) ?? .gmt
+        try ExportDates.$timeZone.withValue(zone) {
+            var container = encoder.container(keyedBy: CodingKeys.self)
+            try container.encode(id, forKey: .id)
+            try container.encode(date, forKey: .date)
+            try container.encode(timeZone, forKey: .timeZone)
+            try container.encode(kind, forKey: .kind)
+            try container.encode(trigger, forKey: .trigger)
+            try container.encode(state, forKey: .state)
+            try container.encodeIfPresent(promptedAt, forKey: .promptedAt)
+            try container.encodeIfPresent(completedAt, forKey: .completedAt)
+            try container.encode(context, forKey: .context)
+            try container.encode(responses, forKey: .responses)
+            try container.encodeIfPresent(legacy, forKey: .legacy)
+            try container.encode(modifiedAt, forKey: .modifiedAt)
+        }
+    }
+}

diff --git a/Reportage/Services/Export/ReportageExporter.swift b/Reportage/Services/Export/ReportageExporter.swift

@@ -0,0 +1,125 @@
+import CoreData
+import Foundation
+
+struct ReportageExportOptions: Sendable {
+    /// Include each imported report's original Reporter snapshot. Off by
+    /// default: the snapshots are large and only matter for imported reports.
+    var includeLegacy = false
+}
+
+struct ReportageExportSummary: Equatable, Sendable {
+    var questions = 0
+    var tokens = 0
+    var reports = 0
+}
+
+/// Writes the store out as a Reportage JSON export (`Notes/ExportFormat.md`).
+///
+/// Records are written one per line as they're read, in batches, so the
+/// archive is never held in memory as a whole.
+struct ReportageExporter: Sendable {
+    static let batchSize = 500
+
+    let persistence: PersistenceController
+
+    @concurrent
+    func export(
+        to url: URL,
+        options: ReportageExportOptions = ReportageExportOptions(),
+        now: Date = Date()
+    ) async throws -> ReportageExportSummary {
+        let context = persistence.newBackgroundContext()
+        return try await context.perform {
+            guard FileManager.default.createFile(atPath: url.path, contents: nil) else {
+                throw CocoaError(.fileWriteUnknown, userInfo: [NSFilePathErrorKey: url.path])
+            }
+            do {
+                let handle = try FileHandle(forWritingTo: url)
+                defer { try? handle.close() }
+                return try Self.write(to: handle, from: context, options: options, now: now)
+            } catch {
+                try? FileManager.default.removeItem(at: url)
+                throw error
+            }
+        }
+    }
+
+    private static func write(
+        to handle: FileHandle,
+        from context: NSManagedObjectContext,
+        options: ReportageExportOptions,
+        now: Date
+    ) throws -> ReportageExportSummary {
+        let encoder = ExportDates.encoder
+        var summary = ReportageExportSummary()
+
+        func write(_ string: String) throws {
+            try handle.write(contentsOf: Data(string.utf8))
+        }
+
+        let exportedAt = ExportDates.string(from: now, in: .gmt)
+        try write(
+            #"{"format":"\#(ReportageExport.format)","version":\#(ReportageExport.version),"#
+                + #""exportedAt":"\#(exportedAt)","#)
+
+        // Each array opens on its own line, with one record per line after it.
+        var separator = ""
+        func beginArray(_ name: String) throws {
+            try write("\n\"\(name)\":[")
+            separator = "\n"
+        }
+        func writeRecord<T: Encodable>(_ record: T) throws {
+            try write(separator)
+            try handle.write(contentsOf: try encoder.encode(record))
+            separator = ",\n"
+        }
+
+        let questionRequest = QuestionEntity.fetchRequest()
+        questionRequest.sortDescriptors = [
+            NSSortDescriptor(key: "order", ascending: true),
+            NSSortDescriptor(key: "id", ascending: true),
+        ]
+        try beginArray("questions")
+        for entity in try context.fetch(questionRequest) {
+            try writeRecord(ExportedQuestion(try entity.question()))
+            summary.questions += 1
+        }
+        try write("\n],")
+        context.reset()
+
+        let tokenRequest = TokenEntity.fetchRequest()
+        tokenRequest.sortDescriptors = [
+            NSSortDescriptor(key: "questionID", ascending: true),
+            NSSortDescriptor(key: "id", ascending: true),
+        ]
+        try beginArray("tokens")
+        for entity in try context.fetch(tokenRequest) {
+            try writeRecord(ExportedToken(try entity.token()))
+            summary.tokens += 1
+        }
+        try write("\n],")
+        context.reset()
+
+        let reportRequest = ReportEntity.fetchRequest()
+        reportRequest.sortDescriptors = [
+            NSSortDescriptor(key: "date", ascending: true),
+            NSSortDescriptor(key: "id", ascending: true),
+        ]
+        reportRequest.relationshipKeyPathsForPrefetching = ["responses"]
+        reportRequest.fetchLimit = batchSize
+        try beginArray("reports")
+        while true {
+            reportRequest.fetchOffset = summary.reports
+            let batch = try context.fetch(reportRequest)
+            for entity in batch {
+                let report = try entity.report()
+                try writeRecord(ExportedReport(report, includingLegacy: options.includeLegacy))
+                summary.reports += 1
+            }
+            context.reset()
+            if batch.count < batchSize { break }
+        }
+        try write("\n]}\n")
+        return summary
+    }
+}

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

@@ -0,0 +1,174 @@
+import CoreData
+import Foundation
+import Testing
+
+@testable import Reportage
+
+@Suite("ReportageExport")
+struct ReportageExportTests {
+
+    private let persistence = makeTestPersistence()
+
+    private var exporter: ReportageExporter { ReportageExporter(persistence: persistence) }
+
+    private func exportData(
+        options: ReportageExportOptions = ReportageExportOptions(),
+        now: Date = Date(timeIntervalSince1970: 0)
+    ) async throws -> (summary: ReportageExportSummary, data: Data) {
+        let url = FileManager.default.temporaryDirectory
+            .appendingPathComponent("reportage-export-\(UUID().uuidString).json")
+        defer { try? FileManager.default.removeItem(at: url) }
+        let summary = try await exporter.export(to: url, options: options, now: now)
+        return (summary, try Data(contentsOf: url))
+    }
+
+    private func stored() async throws -> (questions: [Question], tokens: [Token], reports: [Report]) {
+        let context = persistence.newBackgroundContext()
+        return try await context.perform {
+            let reports = ReportEntity.fetchRequest()
+            reports.sortDescriptors = [
+                NSSortDescriptor(key: "date", ascending: true),
+                NSSortDescriptor(key: "id", ascending: true),
+            ]
+            return (
+                try context.fetch(QuestionEntity.fetchRequest()).map { try $0.question() },
+                try context.fetch(TokenEntity.fetchRequest()).map { try $0.token() },
+                try context.fetch(reports).map { try $0.report() }
+            )
+        }
+    }
+
+    private func insert(_ report: Report) async throws {
+        let context = persistence.newBackgroundContext()
+        try await context.perform {
+            try ReportEntity(context: context).update(from: report)
+            try context.save()
+        }
+    }
+
+    private func importFixture() async throws {
+        _ = try await ReporterImporter(persistence: persistence)
+            .importArchive(try Fixtures.reporterExport(), now: Date(timeIntervalSince1970: 0))
+    }
+
+    private static let sydneyReport = Report(
+        id: UUID(uuidString: "E0000001-0000-4000-8000-000000000000")!,
+        // 2025-01-15 09:30:00 in Sydney, which is +11:00 in January.
+        date: Date(timeIntervalSince1970: 1_736_893_800),
+        timeZone: "Australia/Sydney",
+        kind: .manual,
+        trigger: .app,
+        state: .complete,
+        completedAt: Date(timeIntervalSince1970: 1_736_893_860.25),
+        context: Context(
+            location: LocationContext(
+                coordinate: Coordinate(latitude: -33.87, longitude: 151.21),
+                timestamp: Date(timeIntervalSince1970: 1_736_893_790)
+            )
+        ),
+        responses: [
+            Response(questionID: "Q1", prompt: "How many?", value: .number(Decimal(string: "2.5")!)),
+            Response(questionID: "Q2", prompt: "Skipped?", value: nil),
+        ],
+        modifiedAt: Date(timeIntervalSince1970: 1_736_893_860)
+    )
+
+    @Test("An export of the imported fixture decodes to what the store holds")
+    func roundTrip() async throws {
+        try await importFixture()
+        let (summary, data) = try await exportData()
+        let export = try ReportageExport.decode(data)
+        var expected = try await stored()
+        for index in expected.reports.indices { expected.reports[index].legacy = nil }
+
+        #expect(summary == ReportageExportSummary(questions: 9, tokens: 11, reports: 14))
+        #expect(export.format == "reportage")
+        #expect(export.version == 1)
+        #expect(export.exportedAt == Date(timeIntervalSince1970: 0))
+        #expect(Set(try export.questions.map { try $0.question() }) == Set(expected.questions))
+        #expect(Set(export.tokens.map { $0.token() }) == Set(expected.tokens))
+        #expect(try export.reports.map { try $0.report() } == expected.reports)
+    }
+
+    @Test("The export is valid JSON with one record per line")
+    func layout() async throws {
+        try await importFixture()
+        let (_, data) = try await exportData()
+        let object = try JSONSerialization.jsonObject(with: data) as? [String: Any]
+        #expect((object?["reports"] as? [Any])?.count == 14)
+
+        let lines = String(decoding: data, as: UTF8.self).split(separator: "\n")
+        // The header, three array openings, three closings and one record per line.
+        let records = 9 + 11 + 14
+        #expect(lines.count == 7 + records)
+    }
+
+    @Test("Dates in a report use its time zone and others use UTC")
+    func dates() async throws {
+        try await insert(Self.sydneyReport)
+        let (_, data) = try await exportData(now: Date(timeIntervalSince1970: 1_800_000_000.5))
+        let text = String(decoding: data, as: UTF8.self)
+
+        #expect(text.contains(#""exportedAt":"2027-01-15T08:00:00.500Z""#))
+        #expect(text.contains(#""date":"2025-01-15T09:30:00+11:00""#))
+        #expect(text.contains(#""completedAt":"2025-01-15T09:31:00.250+11:00""#))
+        #expect(text.contains(#""timestamp":"2025-01-15T09:29:50+11:00""#))
+        #expect(text.contains(#""timeZone":"Australia/Sydney""#))
+        #expect(try ReportageExport.decode(data).reports.map { try $0.report() } == [Self.sydneyReport])
+    }
+
+    @Test("Response values keep their shape and skipped answers have no value")
+    func responses() async throws {
+        try await insert(Self.sydneyReport)
+        let text = String(decoding: try await exportData().data, as: UTF8.self)
+        #expect(text.contains(#"{"prompt":"How many?","questionID":"Q1","value":{"number":2.5}}"#))
+        #expect(text.contains(#"{"prompt":"Skipped?","questionID":"Q2"}"#))
+    }
+
+    @Test("Legacy snapshots are left out unless asked for, and are byte-exact")
+    func legacy() async throws {
+        try await importFixture()
+        let without = try ReportageExport.decode(try await exportData().data)
+        #expect(without.reports.allSatisfy { $0.legacy == nil })
+
+        let with = try ReportageExport.decode(
+            try await exportData(options: ReportageExportOptions(includeLegacy: true)).data)
+        let reports = try await stored().reports
+        #expect(with.reports.count == reports.count)
+        for (exported, report) in zip(with.reports, reports) {
+            let original = try LegacyBlob.decompress(try #require(report.legacy))
+            #expect(Data(try #require(exported.legacy).utf8) == original)
+        }
+    }
+
+    @Test("Question surveys are written as names")
+    func askOn() throws {
+        let question = Question(
+            id: "Q", prompt: "P", kind: .yesNo, askOn: [.random, .bedtime], order: 0,
+            modifiedAt: Date(timeIntervalSince1970: 0))
+        let exported = ExportedQuestion(question)
+        #expect(exported.askOn == ["random", "bedtime"])
+        #expect(exported.options == nil)
+        #expect(try exported.question() == question)
+    }
+
+    @Test("An empty store exports empty arrays")
+    func empty() async throws {
+        let (summary, data) = try await exportData()
+        let export = try ReportageExport.decode(data)
+        #expect(summary == ReportageExportSummary())
+        #expect(export.questions.isEmpty && export.tokens.isEmpty && export.reports.isEmpty)
+    }
+
+    @Test("Other formats and newer versions are rejected")
+    func rejects() {
+        let other = Data(#"{"format":"reporter","version":1}"#.utf8)
+        #expect(throws: ReportageExportError.unknownFormat("reporter")) {
+            try ReportageExport.decode(other)
+        }
+        let newer = Data(#"{"format":"reportage","version":2}"#.utf8)
+        #expect(throws: ReportageExportError.unsupportedVersion(2)) {
+            try ReportageExport.decode(newer)
+        }
+    }
+}