← All repositories

reportage

A life-logging app for iPhone

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


commit 8681f56d21c95c441544e0d42a01795538463a52
parent 6dd422249dca5f44372386b491e5408462ac0d6a
Author: Michael Camilleri <[email protected]>
Date:   Fri, 16 Oct 2026 15:03:04 +0900

Model answers as editable tokens

Reporter let the user rename a token with every past entry showing the
new name once this was done. Previously, Reportage copied each answer's
text into the response, so a rename would have meant rewriting every
report that used it, and two places with the same name could not be told
apart.

This commit makes activities, people and places tokens with their own
identity. Responses now refer to tokens by ID, and a location answer
holds the place's token plus the coordinate where the answer was given.
A place token keeps its names and a representative coordinate as well as
any external ID, so the record keeps its meaning if a directory goes
away. A merge marks one token as merged into another rather than
rewriting the reports that use it.

Reporter already shared one ID between every answer using a token, so
the importer keeps those IDs, just as it keeps report IDs. Re-importing
leaves existing tokens untouched, so a token renamed in Reportage stays
renamed. The fixture shares token IDs between answers in the same way.

The design document records the decisions behind this: MapKit as the
place directory, the rule for showing place names in the user's
languages, and how candidates for a location answer are chosen.

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

Diffstat

MNotes/Design.md | 144++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
MReportage.xcodeproj/project.pbxproj | 4++++
MReportage/Services/ReporterImport/ReporterArchive.swift | 5+++++
MReportage/Services/ReporterImport/ReporterImportPlan.swift | 193+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
MReportage/Services/ReporterImport/ReporterImportVerifier.swift | 36+++++++++++++++++++++++++++---------
MReportage/Services/ReporterImport/ReporterImporter.swift | 37+++++++++++++++++++++++++++++--------
MShared/Models/Response.swift | 30++++++++++--------------------
AShared/Models/Token.swift | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
MShared/Persistence/EntityMapping.swift | 30+++++++++++++++++++++++++++++-
MShared/Persistence/ReportageModel.xcdatamodeld/ReportageModel.xcdatamodel/contents | 17+++++++++++++++++
MTests/Support/reporter-fixture.json | 6+++---
MTests/Unit/ModelCodingTests.swift | 7+++----
MTests/Unit/RealExportVerificationTests.swift | 5+++--
MTests/Unit/ReporterImportPlanTests.swift | 99++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
MTests/Unit/ReporterImporterTests.swift | 31+++++++++++++++++++++++++++++++

15 files changed, 588 insertions(+), 109 deletions(-)

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

@@ -122,19 +122,92 @@ One per question answered in a report.
 |---------------|--------------------------------------------------------------|
 | `questionID`  | Reference to `Question.id`.                                  |
 | `prompt`      | The prompt text at the time of answering. Questions can be reworded later, and Reporter stores it the same way. |
-| `value`       | Tagged union, by question kind: `options: [String]` · `tokens: [String]` · `number: Decimal` · `text: String` · `place: Place`. `nil` when the question was shown but skipped. |
+| `value`       | Tagged union, by question kind: `options: [String]` · `tokens: [Token.ID]` · `number: Decimal` · `text: String` · `place: PlaceAnswer`. `nil` when the question was shown but skipped. |
 
-`Place` holds a name, an optional coordinate and accuracy, and an optional
-external ID. Imported places keep their Foursquare venue IDs (3,362 of them).
-New places use MapKit's `MKMapItem.Identifier`.
+`PlaceAnswer` holds the place's token ID, plus the coordinate and accuracy of
+where the answer was given.
+
+### Token
+
+A reusable answer to a `tokens`, `people` or `location` question: an activity,
+a person or a place. Responses refer to tokens by ID rather than copying their
+text, so editing a token renames it throughout history. Reporter worked the
+same way: it shared one ID between every answer using a token, and renaming
+'Driving' to 'Driving a car', or the old 'Home' after a move, updated every
+past entry.
+
+| Field         | Notes                                                        |
+|---------------|--------------------------------------------------------------|
+| `id`          | String. Imported tokens keep Reporter's `uniqueIdentifier`. New tokens use UUIDs. |
+| `questionID`  | The question whose answers the token belongs to.             |
+| `text`        | The name shown. Editing it is a rename.                      |
+| `place`       | For location tokens: a representative coordinate, names from the directory by language, and an optional external ID. |
+| `mergedInto`  | Set when the token has been merged into another. Answers referring to it read as referring to that token, so a merge rewrites no reports and can be undone. |
+| `archivedAt`  | Tokens are archived, never deleted.                          |
+| `modifiedAt`  | Used for last-writer-wins on sync.                           |
+
+**Places** keep their names and coordinate, not just an external ID, so the
+record keeps its meaning if a directory goes away. Foursquare is the example:
+its venue lookups stopped working in Reporter on 2026-09-01, but each answer
+already held the name and coordinate. Imported places keep their Foursquare
+venue IDs (3,362 answers). New places use MapKit's `MKMapItem.Identifier`.
+
+A place's `text` is what the user chose. Its directory names (`(language,
+text)` pairs) let it be shown in the local language: see
+[Place names and languages](#place-names-and-languages).
 
 ### Vocabulary (local only)
 
-Suggestions for token, people and place answers come from a derived local
-index built from response history: text, use count, last used, and the
+Suggestions for token, people and place answers are ranked from a derived
+local index built from response history: use count, last used, and the
 coordinate centroid for places. It is rebuilt from responses and never synced.
-Place suggestions are ranked by distance from the current location first, then
-by recency.
+Token identity and text are not part of the index: they live in the synced
+`Token` records.
+
+### Place names and languages
+
+The user lists the languages they know in Settings, in order of preference. A
+place is shown with:
+
+1. its name in the local language of the place's country, if the user knows
+   that language;
+2. otherwise, its name in the user's first language;
+3. otherwise, whatever name exists.
+
+The choice is made when a name is shown, not when it's stored, so changing the
+language list re-renders all history. Many places only have one name (small
+businesses in Japan often have only a Japanese name), so the fallback matters.
+A name the user typed or edited is shown as is.
+
+On-device MapKit returns place names in the app's language only, one language
+per process: venue search, nearby search and lookup by ID have no locale
+setting. The ID is the same in every language, though, so a place can be
+stored with the name seen at answer time and gain names in other languages
+later. Reverse geocoding does take a `preferredLocale`.
+
+### Choosing a place
+
+MapKit is the place directory: it needs no key or server and costs nothing.
+Google Places was ruled out because its terms only allow place IDs to be
+stored, so a life log built on it would hold IDs that need a paid lookup to
+read and that lose their meaning if the API changes. Open Places API (hosted
+Overture data) allows storage but has weaker data and an unnamed operator; it
+is a fallback if MapKit's terms turn out to forbid storing names.
+
+Candidates, in order:
+
+1. **The user's own places**, from history: saved places and every venue
+   answered before, ranked by distance from the current location, then by use
+   and recency. This needs no network, and covers most answers: 14 saved names
+   account for 80% of the archive's location answers.
+2. **Nearby places** from `MKLocalPointsOfInterestRequest`, when nothing in
+   history is close.
+3. **Search** across history and MapKit together. MapKit matches queries in
+   either language: 東京タワー finds Tokyo Tower with the app in English.
+4. **A new place**: a name the user types for the current location.
+
+Candidates are merged by external ID, and Foursquare-era places (which have no
+MapKit ID) by name and distance.
 
 ### Context
 
@@ -255,8 +328,11 @@ denied provider leaves its section `nil`. It never blocks saving the report.
 `CLLocationUpdate.liveUpdates()`, taking the first fix within an accuracy
 threshold, then falling back to the best fix within the budget. Reverse
 geocoding uses MapKit's `MKReverseGeocodingRequest` (`CLGeocoder` is deprecated
-in iOS 26). The placemark is stored in a fixed locale. Reporter's archive mixes
-Japanese and English place names depending on the device language at the time.
+in iOS 26), once per language the user knows, using `preferredLocale`, so the
+placemark can be shown by the same rule as place names. Reporter's archive
+mixes Japanese and English placemarks depending on the device language at the
+time. Apple throttles geocoding, so two requests per report is fine but
+re-geocoding the archive would have to run slowly in the background.
 
 ### Weather
 
@@ -315,9 +391,12 @@ Private CloudKit database via `CKSyncEngine`, with two custom zones:
   blob are encoded into the record rather than stored as separate records. A
   report is the unit of editing, so coarse records keep record counts and
   operations low. At about 2–5 KB each, the imported archive is roughly 20,000
-  records and under 100 MB.
+  records and under 100 MB. `Token` records live here too, one per token
+  (about 1,200 in the archive). Keeping tokens separate means renaming 'Home'
+  changes one record instead of the thousands of reports that use it.
 
-Sensitive fields (responses, context, legacy) go in `encryptedValues`.
+Sensitive fields (responses, context, legacy, token text and places) go in
+`encryptedValues`.
 
 Conflicts are resolved last-writer-wins per record using `modifiedAt`. Editing
 the same report on two devices at once is rare enough not to need anything
@@ -387,15 +466,28 @@ Source: Reporter's JSON export, which has two top-level arrays, `questions` and
    hemisphere in `latitudeRef` and `longitudeRef`.
 9. **`connection`** is undocumented. From its distribution (77% 1, 23% 0, 19
    reports with 2), the importer reads it as 1 Wi-Fi, 0 cellular, 2 none.
+10. **Tokens have stable IDs.** Every token, person and place answer carries a
+    `uniqueIdentifier` that Reporter shares between all answers using it (571
+    activity texts with 571 IDs, 105 people with 105 IDs). The importer keeps
+    these as token IDs. Renames in Reporter reached back through history, so
+    the export already carries the current names. Places have 510 IDs for 493
+    names, because some names cover several venues (branches of a chain). One
+    ID appears under two questions, on a stray token attached to a yes/no
+    answer, which the importer ignores.
+11. **Foursquare venue lookup stopped on 2026-09-01.** Answers after that use
+    saved names only, and skipped location answers roughly doubled. Those
+    reports still have their location context, so places could be filled in
+    later.
 
 ### Behaviour
 
 - Runs on the iPhone only, off the main actor, inserting in batches.
-- **Idempotent and repeatable.** Reports and questions 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 the switch.
-  Reports already in the store are left alone. Questions already in the store
-  keep any edits made in Reportage, and only gain new choice options.
+- **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
+  the switch. Reports already in the store are left alone. Questions and
+  tokens already in the store keep any edits made in Reportage, so a renamed
+  token stays renamed; questions only gain new choice options.
 - **`legacy` is byte-exact.** The importer slices each snapshot's bytes out of
   the export instead of re-serialising the decoded value, which would reorder
   keys and reformat numbers.
@@ -439,9 +531,21 @@ round-trip tests. Including the `legacy` blobs is optional (off by default).
 - **"Always" location.** Is "Always" location acceptable, given it's the price
   of location on background passive logs?
 - **Backfills.** Weather from August 2021 onwards and Health from 2014 onwards.
-  Both are optional and can be done at any time.
+  Both are optional and can be done at any time. Location answers skipped
+  since Reporter lost venue lookup (2026-09-01) could be filled in from each
+  report's location context.
+- **Pre-filling places.** If the report's location is inside a saved place's
+  area, should that place be pre-selected? It would save many taps, but a
+  confirmed default may be weaker data than a deliberate choice.
+- **Other-language place names.** Whether to fill in place names in the user's
+  other languages after answering, through the Apple Maps Server API (which
+  takes a language parameter, but needs a key), or accept one name per place.
+  It needs confirming that the Server API uses the same place IDs as MapKit.
+- **MapKit terms.** Check that Apple's terms allow storing place names and
+  coordinates permanently. Also recheck on iOS that lookup by ID ignores the
+  app language (seen on macOS).
 - **Multi-select choice questions.** Reporter stores choice answers as arrays,
   but every answer in the archive has a single value.
-- **Vocabulary editing.** Merging and renaming tokens, people and places
-  (e.g. two spellings of one name) across history.
+- **Vocabulary editing UI.** Renaming and merging are settled in the model
+  (see [Token](#token)); how they're presented in the app isn't.
 - **App lock.** Should there be an optional Face ID lock? The data is personal.

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

@@ -8,6 +8,7 @@
 
 /* Begin PBXBuildFile section */
 		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 */; };
 		3175E324135E1CF5A73683D1 /* ReporterTimeZones.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7196D553D769071DB876B606 /* ReporterTimeZones.swift */; };
 		3244B8439B5E4F79FF84C156 /* JSONSlicer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 643C730A99F0B7BA8C1F8A8E /* JSONSlicer.swift */; };
@@ -66,6 +67,7 @@
 		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>"; };
 		A20C574BC234EDBD4056E2B7 /* TestHelpers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestHelpers.swift; sourceTree = "<group>"; };
+		A3BE62142CCC4A791F05163A /* Token.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Token.swift; sourceTree = "<group>"; };
 		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>"; };
@@ -93,6 +95,7 @@
 				B007E6BACAA214C7332EF77C /* Question.swift */,
 				B03734F91822E7F161432075 /* Report.swift */,
 				6024EA06BE24A189D4F7D0E4 /* Response.swift */,
+				A3BE62142CCC4A791F05163A /* Token.swift */,
 			);
 			path = Models;
 			sourceTree = "<group>";
@@ -323,6 +326,7 @@
 				36A35625365E87B39CB88194 /* ReporterImporter.swift in Sources */,
 				3175E324135E1CF5A73683D1 /* ReporterTimeZones.swift in Sources */,
 				8AF60BB296144ED9D11EA053 /* Response.swift in Sources */,
+				25BC9F95DC40E31B1E4C6FBA /* Token.swift in Sources */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};

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

@@ -88,12 +88,17 @@ struct ReporterResponse: Decodable, Sendable {
     var locationResponse: ReporterLocationResponse?
 }
 
+/// A token or a note. For tokens, Reporter shares one `uniqueIdentifier`
+/// between every answer that uses the token.
 struct ReporterText: Decodable, Sendable {
     var text: String
+    var uniqueIdentifier: String?
 }
 
 struct ReporterLocationResponse: Decodable, Sendable {
     var text: String
+    /// Shared between every answer that uses the place, like a token's.
+    var uniqueIdentifier: String?
     var foursquareVenueId: String?
     var location: ReporterLocation?
 }

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

@@ -1,11 +1,13 @@
 import CryptoKit
 import Foundation
 
-/// The Reportage questions and reports a Reporter archive maps to, plus a
-/// summary of how they were derived. Building a plan is pure; writing it to
-/// the store is `ReporterImporter`'s job.
+/// The Reportage questions, tokens and reports a Reporter archive maps to,
+/// plus a summary of how they were derived. Building a plan is pure; writing
+/// it to the store is `ReporterImporter`'s job.
 struct ReporterImportPlan: Sendable {
     var questions: [Question]
+    /// Sorted by ID.
+    var tokens: [Token]
     /// Sorted by date.
     var reports: [Report]
     var summary: ReporterImportSummary
@@ -21,8 +23,10 @@ struct ReporterImportPlan: Sendable {
         builder.inferAskOn()
         builder.inferChoiceOptions()
         questions = builder.questions
+        tokens = builder.tokens()
         reports = builder.pending.map(\.report)
         summary = builder.summarise()
+        summary.tokenCount = tokens.count
     }
 }
 
@@ -61,6 +65,7 @@ struct ReporterImportSummary: Hashable, Sendable {
     }
 
     var questionCount = 0
+    var tokenCount = 0
     var reportCount = 0
     var reportsByKind: [ReportKind: Int] = [:]
     /// Answered (not skipped) responses per question ID.
@@ -74,6 +79,8 @@ struct ReporterImportSummary: Hashable, Sendable {
 
     var questionsInserted = 0
     var questionsUpdated = 0
+    var tokensInserted = 0
+    var tokensAlreadyPresent = 0
     var reportsInserted = 0
     var reportsAlreadyPresent = 0
 }
@@ -91,6 +98,13 @@ private struct Builder {
         var questionIDs: Set<String>
     }
 
+    struct PendingToken {
+        var token: Token
+        /// The date of the latest answer using the token, whose text wins.
+        var lastUsed: Date
+        var coordinates: [Coordinate] = []
+    }
+
     let now: Date
     var questions: [Question] = []
     var pending: [Pending] = []
@@ -100,6 +114,12 @@ private struct Builder {
     private var questionIndexByPrompt: [String: Int] = [:]
     private var questionIndexByID: [String: Int] = [:]
     private var seenReportIDs: Set<UUID> = []
+    private var pendingTokens: [String: PendingToken] = [:]
+    /// Tokens whose text differs between answers, which Reporter's renaming
+    /// should rule out.
+    private var tokensWithSeveralTexts: Set<String> = []
+    /// Tokens used by more than one question; each keeps its first question.
+    private var tokensInSeveralQuestions: Set<String> = []
 
     init(now: Date) {
         self.now = now
@@ -156,8 +176,7 @@ private struct Builder {
         if let index = questionIndexByPrompt[response.questionPrompt] {
             return index
         }
-        let digest = SHA256.hash(data: Data(response.questionPrompt.utf8))
-        let id = "reporter-prompt-" + digest.prefix(8).map { String(format: "%02x", $0) }.joined()
+        let id = "reporter-prompt-" + Self.hash(response.questionPrompt)
         fallbacks.append(.init(reportID: reportID, reason: .unmatchedPrompt(questionID: id)))
         let index = questions.count
         questions.append(
@@ -176,6 +195,11 @@ private struct Builder {
         return index
     }
 
+    /// A stable 16-hex-digit digest, for IDs derived from text.
+    static func hash(_ string: String) -> String {
+        SHA256.hash(data: Data(string.utf8)).prefix(8).map { String(format: "%02x", $0) }.joined()
+    }
+
     // MARK: Snapshots
 
     mutating func addSnapshot(_ snapshot: ReporterArchive.Snapshot, index: Int) {
@@ -222,7 +246,7 @@ private struct Builder {
             responses.append(
                 Response(
                     questionID: question.id, prompt: reporterResponse.questionPrompt,
-                    value: preferred?.value)
+                    value: preferred.map { value(of: $0, questionID: question.id, date: date) })
             )
             questionIDs.insert(question.id)
         }
@@ -305,38 +329,149 @@ private struct Builder {
         }
     }
 
+    /// An answer field from the export, not yet converted, so that tokens are
+    /// only created for the answer that's kept.
+    enum Answer {
+        case options([String])
+        case tokens([ReporterText])
+        case text(String)
+        case number(Decimal)
+        case place(ReporterLocationResponse)
+
+        var kind: AnswerKind {
+            switch self {
+            case .options: .options
+            case .tokens: .tokens
+            case .text: .text
+            case .number: .number
+            case .place: .place
+            }
+        }
+    }
+
     /// Every answer field present in the response.
-    static func answers(in response: ReporterResponse) -> [(kind: AnswerKind, value: ResponseValue)]
-    {
-        var answers: [(kind: AnswerKind, value: ResponseValue)] = []
+    static func answers(in response: ReporterResponse) -> [Answer] {
+        var answers: [Answer] = []
         if let options = response.answeredOptions {
-            answers.append((.options, .options(options)))
+            answers.append(.options(options))
         }
         if let tokens = response.tokens {
-            answers.append((.tokens, .tokens(tokens.map(\.text))))
+            answers.append(.tokens(tokens))
         }
         if let texts = response.textResponses {
-            answers.append((.text, .text(texts.map(\.text).joined(separator: "\n"))))
+            answers.append(.text(texts.map(\.text).joined(separator: "\n")))
         }
         if let number = response.numericResponse {
-            answers.append((.number, .number(number.value)))
+            answers.append(.number(number.value))
         }
         if let location = response.locationResponse {
-            let place = Place(
-                name: location.text,
-                coordinate: location.location.map {
-                    Coordinate(latitude: $0.latitude.value, longitude: $0.longitude.value)
-                },
-                accuracy: location.location?.horizontalAccuracy.flatMap(Self.nonNegative),
-                externalID: location.foursquareVenueId.map {
-                    ExternalPlaceID(source: .foursquare, value: $0)
-                }
-            )
-            answers.append((.place, .place(place)))
+            answers.append(.place(location))
         }
         return answers
     }
 
+    /// Converts an answer, registering the tokens it uses.
+    private mutating func value(of answer: Answer, questionID: String, date: Date) -> ResponseValue
+    {
+        switch answer {
+        case .options(let options):
+            return .options(options)
+        case .text(let text):
+            return .text(text)
+        case .number(let number):
+            return .number(number)
+        case .tokens(let tokens):
+            return .tokens(
+                tokens.map {
+                    registerToken(
+                        id: $0.uniqueIdentifier, text: $0.text, questionID: questionID, date: date)
+                })
+        case .place(let location):
+            let coordinate = location.location.map {
+                Coordinate(latitude: $0.latitude.value, longitude: $0.longitude.value)
+            }
+            let tokenID = registerToken(
+                id: location.uniqueIdentifier,
+                text: location.text,
+                questionID: questionID,
+                date: date,
+                place: (
+                    coordinate,
+                    location.foursquareVenueId.map {
+                        ExternalPlaceID(source: .foursquare, value: $0)
+                    }
+                )
+            )
+            return .place(
+                PlaceAnswer(
+                    tokenID: tokenID,
+                    coordinate: coordinate,
+                    accuracy: location.location?.horizontalAccuracy.flatMap(Self.nonNegative)
+                ))
+        }
+    }
+
+    /// Records a use of a token and returns its ID. Reporter shares a token's
+    /// ID between all the answers using it; a token without one gets an ID
+    /// derived from its question and text.
+    private mutating func registerToken(
+        id: String?,
+        text: String,
+        questionID: String,
+        date: Date,
+        place: (coordinate: Coordinate?, externalID: ExternalPlaceID?)? = nil
+    ) -> String {
+        let id = id ?? "reporter-token-" + Self.hash(questionID + "\u{0}" + text)
+        var pending =
+            pendingTokens[id]
+            ?? PendingToken(
+                token: Token(
+                    id: id,
+                    questionID: questionID,
+                    text: text,
+                    place: place.map { _ in PlaceDetails() },
+                    modifiedAt: now
+                ),
+                lastUsed: date
+            )
+        if pending.token.questionID != questionID {
+            tokensInSeveralQuestions.insert(id)
+        }
+        if pending.token.text != text {
+            tokensWithSeveralTexts.insert(id)
+        }
+        if date >= pending.lastUsed {
+            pending.lastUsed = date
+            pending.token.text = text
+            if let externalID = place?.externalID {
+                pending.token.place?.externalID = externalID
+            }
+        }
+        if let coordinate = place?.coordinate {
+            pending.coordinates.append(coordinate)
+        }
+        pendingTokens[id] = pending
+        return id
+    }
+
+    /// The tokens used by the archive, each place at the centre of the
+    /// answers given for it.
+    func tokens() -> [Token] {
+        pendingTokens.values.map { pending in
+            var token = pending.token
+            let coordinates = pending.coordinates
+            if !coordinates.isEmpty {
+                let count = Double(coordinates.count)
+                token.place?.coordinate = Coordinate(
+                    latitude: coordinates.map(\.latitude).reduce(0, +) / count,
+                    longitude: coordinates.map(\.longitude).reduce(0, +) / count
+                )
+            }
+            return token
+        }
+        .sorted { $0.id < $1.id }
+    }
+
     // MARK: Context
 
     static func context(of snapshot: ReporterSnapshot) -> Context {
@@ -590,6 +725,16 @@ private struct Builder {
         summary.fallbacks = fallbacks
         summary.failures = failures
         summary.warnings = warnings
+        if !tokensWithSeveralTexts.isEmpty {
+            summary.warnings.append(
+                "\(tokensWithSeveralTexts.count) tokens have different texts in different "
+                    + "answers; each keeps the text of its latest answer")
+        }
+        if !tokensInSeveralQuestions.isEmpty {
+            summary.warnings.append(
+                "\(tokensInSeveralQuestions.count) tokens are used by more than one question; "
+                    + "each belongs to the first question it was found in")
+        }
         return summary
     }
 }

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

@@ -25,6 +25,11 @@
                 let report = try entity.report()
                 stored[report.id] = report
             }
+            var tokens: [String: Token] = [:]
+            for entity in try context.fetch(TokenEntity.fetchRequest()) {
+                let token = try entity.token()
+                tokens[token.id] = token
+            }
 
             var mismatches: [Mismatch] = []
             for snapshot in archive.snapshots {
@@ -58,7 +63,7 @@
                     if response.prompt != reporterResponse.questionPrompt {
                         mismatch("response \(index) prompt differs")
                     }
-                    if !matches(response.value, reporterResponse) {
+                    if !matches(response.value, reporterResponse, tokens: tokens) {
                         mismatch("response \(index) value differs")
                     }
                 }
@@ -66,7 +71,11 @@
             return mismatches
         }
 
-        private static func matches(_ value: ResponseValue?, _ response: ReporterResponse) -> Bool {
+        /// Token texts are compared too, so this is only meaningful straight
+        /// after an import, before any token has been renamed.
+        private static func matches(
+            _ value: ResponseValue?, _ response: ReporterResponse, tokens: [String: Token]
+        ) -> Bool {
             switch value {
             case nil:
                 return response.answeredOptions == nil && response.tokens == nil
@@ -74,17 +83,26 @@
                     && response.locationResponse == nil
             case .options(let options):
                 return options == response.answeredOptions
-            case .tokens(let tokens):
-                return tokens == response.tokens?.map(\.text)
+            case .tokens(let ids):
+                guard let reporterTokens = response.tokens, ids.count == reporterTokens.count
+                else { return false }
+                return zip(ids, reporterTokens).allSatisfy { id, reporterToken in
+                    (reporterToken.uniqueIdentifier.map { $0 == id } ?? true)
+                        && tokens[id]?.text == reporterToken.text
+                }
             case .text(let text):
                 return text == response.textResponses?.map(\.text).joined(separator: "\n")
             case .number(let number):
                 return number == response.numericResponse?.value
-            case .place(let place):
-                return place.name == response.locationResponse?.text
-                    && place.externalID?.value == response.locationResponse?.foursquareVenueId
-                    && place.coordinate?.latitude
-                        == response.locationResponse?.location?.latitude.value
+            case .place(let answer):
+                guard let location = response.locationResponse, let token = tokens[answer.tokenID]
+                else { return false }
+                return (location.uniqueIdentifier.map { $0 == answer.tokenID } ?? true)
+                    && token.text == location.text
+                    && (location.foursquareVenueId.map { $0 == token.place?.externalID?.value }
+                        ?? true)
+                    && answer.coordinate?.latitude == location.location?.latitude.value
+                    && answer.coordinate?.longitude == location.location?.longitude.value
             }
         }
     }

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

@@ -3,10 +3,11 @@ import Foundation
 
 /// Imports a Reporter JSON export into the store.
 ///
-/// The import is idempotent: questions and reports keep their Reporter IDs,
-/// and reports already in the store are left alone, so importing a newer
-/// export adds only what's new. Existing questions keep any edits made in
-/// Reportage; only their choice options grow.
+/// The import is idempotent: questions, tokens and reports keep their
+/// Reporter IDs, and reports already in the store are left alone, so
+/// 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.
 struct ReporterImporter: Sendable {
     static let batchSize = 500
 
@@ -26,6 +27,17 @@ struct ReporterImporter: Sendable {
         }
     }
 
+    private static func existingIDs<ID: Hashable>(
+        of entityName: String,
+        as type: ID.Type,
+        in context: NSManagedObjectContext
+    ) throws -> Set<ID> {
+        let request = NSFetchRequest<NSDictionary>(entityName: entityName)
+        request.resultType = .dictionaryResultType
+        request.propertiesToFetch = ["id"]
+        return Set(try context.fetch(request).compactMap { $0["id"] as? ID })
+    }
+
     private static func write(
         _ plan: ReporterImportPlan,
         into context: NSManagedObjectContext
@@ -54,10 +66,19 @@ struct ReporterImporter: Sendable {
         try context.save()
         context.reset()
 
-        let idRequest = NSFetchRequest<NSDictionary>(entityName: "ReportEntity")
-        idRequest.resultType = .dictionaryResultType
-        idRequest.propertiesToFetch = ["id"]
-        let existingIDs = Set(try context.fetch(idRequest).compactMap { $0["id"] as? UUID })
+        let existingTokenIDs = try existingIDs(of: "TokenEntity", as: String.self, in: context)
+        for token in plan.tokens {
+            if existingTokenIDs.contains(token.id) {
+                summary.tokensAlreadyPresent += 1
+            } else {
+                try TokenEntity(context: context).update(from: token)
+                summary.tokensInserted += 1
+            }
+        }
+        try context.save()
+        context.reset()
+
+        let existingIDs = try existingIDs(of: "ReportEntity", as: UUID.self, in: context)
 
         var unsaved = 0
         for report in plan.reports {

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

@@ -10,13 +10,16 @@ struct Response: Codable, Hashable, Sendable {
 }
 
 /// An answer, tagged by shape. Encodes as a single-key object, for example
-/// `{"tokens": ["coffee", "work"]}`.
+/// `{"options": ["Yes"]}`.
 enum ResponseValue: Hashable, Sendable {
     case options([String])
+    /// Token IDs, for `tokens` and `people` questions. Answers refer to
+    /// tokens rather than copying their text, so renaming a token renames it
+    /// throughout history.
     case tokens([String])
     case number(Decimal)
     case text(String)
-    case place(Place)
+    case place(PlaceAnswer)
 }
 
 extension ResponseValue: Codable {
@@ -43,7 +46,7 @@ extension ResponseValue: Codable {
         case .tokens: self = .tokens(try container.decode([String].self, forKey: key))
         case .number: self = .number(try container.decode(Decimal.self, forKey: key))
         case .text: self = .text(try container.decode(String.self, forKey: key))
-        case .place: self = .place(try container.decode(Place.self, forKey: key))
+        case .place: self = .place(try container.decode(PlaceAnswer.self, forKey: key))
         }
     }
 
@@ -59,26 +62,13 @@ extension ResponseValue: Codable {
     }
 }
 
-/// A named place given as an answer to a location question.
-struct Place: Codable, Hashable, Sendable {
-    var name: String
+/// The answer to a location question: the place token chosen, and where the
+/// answer was given.
+struct PlaceAnswer: Codable, Hashable, Sendable {
+    var tokenID: String
     var coordinate: Coordinate?
     /// Horizontal accuracy of `coordinate`, in metres.
     var accuracy: Double?
-    var externalID: ExternalPlaceID?
-}
-
-/// An identifier for a place in an external directory.
-struct ExternalPlaceID: Codable, Hashable, Sendable {
-    enum Source: String, Codable, Sendable {
-        /// Foursquare venue IDs, from Reporter.
-        case foursquare
-        /// `MKMapItem.Identifier` raw values.
-        case mapKit
-    }
-
-    var source: Source
-    var value: String
 }
 
 struct Coordinate: Codable, Hashable, Sendable {

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

@@ -0,0 +1,53 @@
+import Foundation
+
+/// A reusable answer to a `tokens`, `people` or `location` question: an
+/// activity, a person or a place. Responses refer to tokens by ID, so editing
+/// a token's text renames it throughout history, as Reporter did.
+struct Token: Hashable, Sendable {
+    /// Imported tokens keep Reporter's `uniqueIdentifier`, which Reporter
+    /// shared between every answer using the token. New tokens use UUIDs.
+    var id: String
+    /// The question whose answers the token belongs to.
+    var questionID: String
+    /// The name shown for the token. For a place picked from a directory and
+    /// never renamed, this is the directory's name at the time.
+    var text: String
+    /// Set for tokens of `location` questions.
+    var place: PlaceDetails?
+    /// When set, the token was merged into the token with this ID, and
+    /// answers referring to it should be read as referring to that token.
+    var mergedInto: String?
+    var archivedAt: Date?
+    var modifiedAt: Date
+}
+
+struct PlaceDetails: Codable, Hashable, Sendable {
+    /// A representative coordinate for the place: the directory's coordinate,
+    /// or the centre of the answers given for it.
+    var coordinate: Coordinate?
+    /// Names from the directory, by language. The token's `text` is what the
+    /// user chose; these let the place be shown in the local language.
+    var names: [LocalisedName] = []
+    var externalID: ExternalPlaceID?
+}
+
+struct LocalisedName: Codable, Hashable, Sendable {
+    /// BCP 47 language tag, for example `ja` or `en`.
+    var language: String
+    var text: String
+}
+
+/// An identifier for a place in an external directory. Stored alongside the
+/// place's names and coordinate, never instead of them, so the record keeps
+/// its meaning if the directory goes away.
+struct ExternalPlaceID: Codable, Hashable, Sendable {
+    enum Source: String, Codable, Sendable {
+        /// Foursquare venue IDs, from Reporter.
+        case foursquare
+        /// `MKMapItem.Identifier` raw values.
+        case mapKit
+    }
+
+    var source: Source
+    var value: String
+}

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

@@ -2,7 +2,7 @@ import CoreData
 import Foundation
 
 /// Conversions between the value types in `Models/` and their Core Data
-/// entities. Encoded fields (`options`, `context`, `value`) are JSON.
+/// entities. Encoded fields (`options`, `context`, `place`, `value`) are JSON.
 enum ModelCoding {
     static func encode<T: Encodable>(_ value: T) throws -> Data {
         let encoder = JSONEncoder()
@@ -55,6 +55,34 @@ extension QuestionEntity {
     }
 }
 
+extension TokenEntity {
+    func update(from token: Token) throws {
+        id = token.id
+        questionID = token.questionID
+        text = token.text
+        place = try token.place.map { try ModelCoding.encode($0) }
+        mergedInto = token.mergedInto
+        archivedAt = token.archivedAt
+        modifiedAt = token.modifiedAt
+    }
+
+    func token() throws -> Token {
+        guard let id, let questionID, let text, let modifiedAt else {
+            throw EntityMappingError.missingField(
+                entity: "Token", field: "id/questionID/text/modifiedAt")
+        }
+        return Token(
+            id: id,
+            questionID: questionID,
+            text: text,
+            place: try place.map { try ModelCoding.decode(PlaceDetails.self, from: $0) },
+            mergedInto: mergedInto,
+            archivedAt: archivedAt,
+            modifiedAt: modifiedAt
+        )
+    }
+}
+
 extension ReportEntity {
     /// Copies `report` into the entity, replacing any existing responses.
     func update(from report: Report) throws {

diff --git a/Shared/Persistence/ReportageModel.xcdatamodeld/ReportageModel.xcdatamodel/contents b/Shared/Persistence/ReportageModel.xcdatamodeld/ReportageModel.xcdatamodel/contents

@@ -41,6 +41,23 @@
             <fetchIndexElement property="state" type="Binary" order="ascending"/>
         </fetchIndex>
     </entity>
+    <entity name="TokenEntity" representedClassName="TokenEntity" syncable="YES" codeGenerationType="class">
+        <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO"/>
+        <attribute name="id" attributeType="String"/>
+        <attribute name="mergedInto" optional="YES" attributeType="String"/>
+        <attribute name="modifiedAt" attributeType="Date" usesScalarValueType="NO"/>
+        <attribute name="place" optional="YES" attributeType="Binary"/>
+        <attribute name="questionID" attributeType="String"/>
+        <attribute name="text" attributeType="String"/>
+        <uniquenessConstraints>
+            <uniquenessConstraint>
+                <constraint value="id"/>
+            </uniquenessConstraint>
+        </uniquenessConstraints>
+        <fetchIndex name="byQuestionID">
+            <fetchIndexElement property="questionID" type="Binary" order="ascending"/>
+        </fetchIndex>
+    </entity>
     <entity name="ResponseEntity" representedClassName="ResponseEntity" syncable="YES" codeGenerationType="class">
         <attribute name="order" attributeType="Integer 16" defaultValueString="0" usesScalarValueType="YES"/>
         <attribute name="prompt" attributeType="String"/>

diff --git a/Tests/Support/reporter-fixture.json b/Tests/Support/reporter-fixture.json

@@ -31,12 +31,12 @@
   {"questionPrompt":"Are you outside?","answeredOptions":["No"],"uniqueIdentifier":"B0000009-0000-4000-8000-000000000000"},
   {"questionPrompt":"What are you doing?","tokens":[{"text":"Fireworks","uniqueIdentifier":"C0000007-0000-4000-8000-000000000000"}],"uniqueIdentifier":"B000000A-0000-4000-8000-000000000000"},
   {"questionPrompt":"Where are you?","uniqueIdentifier":"B000000B-0000-4000-8000-000000000000"},
-  {"questionPrompt":"Who are you with?","tokens":[{"text":"Alex","uniqueIdentifier":"C0000008-0000-4000-8000-000000000000"},{"text":"Sam","uniqueIdentifier":"C0000009-0000-4000-8000-000000000000"}],"uniqueIdentifier":"B000000C-0000-4000-8000-000000000000"}]},
+  {"questionPrompt":"Who are you with?","tokens":[{"text":"Alex","uniqueIdentifier":"C0000005-0000-4000-8000-000000000000"},{"text":"Sam","uniqueIdentifier":"C0000009-0000-4000-8000-000000000000"}],"uniqueIdentifier":"B000000C-0000-4000-8000-000000000000"}]},
 {"battery":0.29,"connection":2,"steps":800,"background":1,"draft":0,"sectionIdentifier":"1-2020-1-1","reportImpetus":2,"uniqueIdentifier":"0A1B2C3D-0005-4000-8000-000000000005","date":"2020-01-01T03:00:00+0900",
  "location":{"latitude":-33.87,"longitude":151.2,"horizontalAccuracy":1414,"verticalAccuracy":-1,"speed":-1,"course":-1,"timestamp":"2020-01-01T02:58:00+0900","uniqueIdentifier":"A0000011-0000-4000-8000-000000000000","placemark":{"uniqueIdentifier":"A0000012-0000-4000-8000-000000000000"}},
  "responses":[
   {"questionPrompt":"Are you outside?","answeredOptions":["Yes"],"uniqueIdentifier":"B000000D-0000-4000-8000-000000000000"},
-  {"questionPrompt":"What are you doing?","tokens":[{"text":"Walking","uniqueIdentifier":"C000000A-0000-4000-8000-000000000000"}],"uniqueIdentifier":"B000000E-0000-4000-8000-000000000000"}]},
+  {"questionPrompt":"What are you doing?","tokens":[{"text":"Walking","uniqueIdentifier":"C0000001-0000-4000-8000-000000000000"}],"uniqueIdentifier":"B000000E-0000-4000-8000-000000000000"}]},
 {"battery":0.9,"connection":1,"steps":3000,"background":0,"draft":0,"sectionIdentifier":"1-2020-1-5","reportImpetus":2,"uniqueIdentifier":"0A1B2C3D-0006-4000-8000-000000000006","date":"2020-01-05T10:00:00+0900",
  "location":{"latitude":10.7769,"longitude":106.7009,"altitude":9,"horizontalAccuracy":20,"verticalAccuracy":6,"speed":0.5,"course":180,"timestamp":"2020-01-05T09:59:00+0900","uniqueIdentifier":"A0000013-0000-4000-8000-000000000000","placemark":{"name":"Example Street","country":"ベトナム","administrativeArea":"Thành Phố Hồ Chí Minh","uniqueIdentifier":"A0000014-0000-4000-8000-000000000000"}},
  "responses":[
@@ -45,7 +45,7 @@
 {"battery":0.8,"connection":1,"steps":4000,"background":0,"draft":0,"sectionIdentifier":"1-2020-1-6","reportImpetus":2,"uniqueIdentifier":"0A1B2C3D-0007-4000-8000-000000000007","date":"2020-01-06T10:00:00+0900",
  "location":{"latitude":22.2793,"longitude":114.1628,"altitude":15,"horizontalAccuracy":10,"verticalAccuracy":5,"speed":-1,"course":-1,"timestamp":"2020-01-06T09:59:00+0900","uniqueIdentifier":"A0000015-0000-4000-8000-000000000000","placemark":{"name":"Example Road","country":"香港","administrativeArea":"香港","uniqueIdentifier":"A0000016-0000-4000-8000-000000000000"}},
  "responses":[
-  {"questionPrompt":"Are you outside?","answeredOptions":["No"],"tokens":[{"text":"Stray","uniqueIdentifier":"C000000C-0000-4000-8000-000000000000"}],"uniqueIdentifier":"B0000011-0000-4000-8000-000000000000"}]},
+  {"questionPrompt":"Are you outside?","answeredOptions":["No"],"tokens":[{"text":"Walking","uniqueIdentifier":"C0000001-0000-4000-8000-000000000000"}],"uniqueIdentifier":"B0000011-0000-4000-8000-000000000000"}]},
 {"battery":0.7,"connection":1,"steps":5000,"background":0,"draft":0,"sectionIdentifier":"1-2020-1-7","uniqueIdentifier":"0A1B2C3D-0008-4000-8000-000000000008","date":"2020-01-07T12:00:00+0900",
  "location":{"latitude":48.8584,"longitude":2.2945,"altitude":35,"horizontalAccuracy":12,"verticalAccuracy":-1,"speed":-2.5,"course":-1,"timestamp":"2020-01-07T11:59:00+0900","uniqueIdentifier":"A0000017-0000-4000-8000-000000000000","placemark":{"name":"Example Avenue","country":"France","administrativeArea":"Île-de-France","uniqueIdentifier":"A0000018-0000-4000-8000-000000000000"}},
  "responses":[

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

@@ -20,11 +20,10 @@ struct ModelCodingTests {
             .number(Decimal(string: "7.25")!),
             .text("Note\nwith a line break"),
             .place(
-                Place(
-                    name: "Somewhere",
+                PlaceAnswer(
+                    tokenID: "T1",
                     coordinate: Coordinate(latitude: 1.5, longitude: -2.25),
-                    accuracy: 10,
-                    externalID: ExternalPlaceID(source: .mapKit, value: "I123")
+                    accuracy: 10
                 )
             ),
         ]

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

@@ -66,7 +66,7 @@ struct RealExportVerificationTests {
             """
             REAL EXPORT SUMMARY
               import time: \(importDuration)
-              questions: \(summary.questionCount), reports: \(summary.reportCount), failures: \(summary.failures.count)
+              questions: \(summary.questionCount), tokens: \(summary.tokenCount), reports: \(summary.reportCount), failures: \(summary.failures.count)
               by kind: \(summary.reportsByKind.sorted { $0.key.rawValue < $1.key.rawValue })
               by year: \(summary.reportsByYear.sorted { $0.key < $1.key })
               by zone: \(summary.reportsByTimeZone.sorted { $0.key < $1.key })
@@ -75,13 +75,14 @@ struct RealExportVerificationTests {
               fallbacks: \(fallbackCounts.sorted { $0.key < $1.key })
               warnings: \(summary.warnings.count)
               mismatches: \(mismatchCounts.sorted { $0.key < $1.key })
-              re-import: inserted \(reimport.reportsInserted), already present \(reimport.reportsAlreadyPresent)
+              re-import: inserted \(reimport.reportsInserted), already present \(reimport.reportsAlreadyPresent), tokens inserted \(reimport.tokensInserted)
             """
         )
 
         #expect(summary.failures.isEmpty)
         #expect(mismatches.isEmpty)
         #expect(reimport.reportsInserted == 0)
+        #expect(reimport.tokensInserted == 0)
         #expect(reimport.reportsAlreadyPresent == summary.reportCount)
     }
 }

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

@@ -205,46 +205,109 @@ struct ReporterImportPlanTests {
             ])
         #expect(first.responses[0].prompt == "Are you outside?")
         #expect(first.responses[0].value == .options(["Yes"]))
-        #expect(first.responses[1].value == .tokens(["Walking", "Podcast"]))
-        #expect(first.responses[3].value == .tokens(["Alex"]))
+        #expect(first.responses[1].value == .tokens([Self.tokenID(1), Self.tokenID(2)]))
+        #expect(first.responses[3].value == .tokens([Self.tokenID(5)]))
         #expect(
             first.responses[2].value
                 == .place(
-                    Place(
-                        name: "Corner Café",
+                    PlaceAnswer(
+                        tokenID: Self.tokenID(3),
                         coordinate: Coordinate(latitude: 35.6582, longitude: 139.7016),
-                        accuracy: 30,
-                        externalID: ExternalPlaceID(
-                            source: .foursquare, value: "4b0000000000000000000001")
-                    )
-                )
+                        accuracy: 30
+                    ))
         )
         #expect(try report(2).responses[0].value == .text("Long day."))
         #expect(try report(3).responses[1].value == .number(Decimal(string: "6.5")!))
     }
 
-    @Test("Skipped questions are kept with no value")
-    func skippedQuestions() throws {
-        let response = try report(4).responses[2]
-        #expect(response.questionID == "default-question-4")
-        #expect(response.value == nil)
-        #expect(plan.summary.answersByQuestion["default-question-4"] == 2)
+    // MARK: Tokens
+
+    /// Token IDs in the fixture, which follow Reporter in sharing one ID
+    /// between every answer using a token.
+    private static func tokenID(_ number: Int) -> String {
+        String(format: "C%07X-0000-4000-8000-000000000000", number)
+    }
+
+    private func token(_ id: String) throws -> Token {
+        try #require(plan.tokens.first { $0.id == id })
+    }
+
+    @Test("Tokens keep Reporter's IDs and are shared between answers")
+    func sharedTokens() throws {
+        // 'Walking' in reports 1 and 5, 'Alex' in reports 1 and 4.
+        #expect(try report(5).responses[1].value == .tokens([Self.tokenID(1)]))
+        #expect(try report(4).responses[3].value == .tokens([Self.tokenID(5), Self.tokenID(9)]))
+
+        let walking = try token(Self.tokenID(1))
+        #expect(walking.text == "Walking")
+        #expect(walking.questionID == "default-question-3")
+        #expect(walking.place == nil)
+        #expect(try token(Self.tokenID(5)).questionID == "default-question-5")
+
+        // Six activities, two people, two places and one token of the
+        // synthesised question.
+        #expect(plan.tokens.count == 11)
+        #expect(plan.summary.tokenCount == 11)
+        #expect(plan.summary.warnings.isEmpty)
+    }
+
+    @Test("Place tokens carry the venue ID and the centre of their answers")
+    func placeTokens() throws {
+        let cafe = try token(Self.tokenID(3))
+        #expect(cafe.text == "Corner Café")
+        #expect(cafe.questionID == "default-question-4")
+        #expect(
+            cafe.place
+                == PlaceDetails(
+                    coordinate: Coordinate(latitude: 35.6582, longitude: 139.7016),
+                    externalID: ExternalPlaceID(
+                        source: .foursquare, value: "4b0000000000000000000001")
+                ))
     }
 
     @Test("Places with an invalid accuracy and no venue ID")
     func placeWithoutExtras() throws {
-        guard case .place(let place) = try report(14).responses[2].value else {
+        guard case .place(let answer) = try report(14).responses[2].value else {
             Issue.record("Expected a place")
             return
         }
-        #expect(place.accuracy == nil)
-        #expect(place.externalID == nil)
+        #expect(answer.accuracy == nil)
+        let office = try token(answer.tokenID)
+        #expect(office.text == "Office")
+        #expect(office.place?.externalID == nil)
+        #expect(office.place?.coordinate == Coordinate(latitude: 35.66, longitude: 139.7))
+    }
+
+    @Test("A token's latest text wins, and the conflict is reported")
+    func conflictingTokenTexts() throws {
+        let json = #"""
+            {"questions":[{"uniqueIdentifier":"q","prompt":"Doing?","questionType":0}],"snapshots":[
+            {"uniqueIdentifier":"00000000-0000-4000-8000-000000000002","date":"2016-01-02T12:00:00+0900","reportImpetus":2,"responses":[{"questionPrompt":"Doing?","tokens":[{"text":"Driving a car","uniqueIdentifier":"T"}]}]},
+            {"uniqueIdentifier":"00000000-0000-4000-8000-000000000001","date":"2016-01-01T12:00:00+0900","reportImpetus":2,"responses":[{"questionPrompt":"Doing?","tokens":[{"text":"Driving","uniqueIdentifier":"T"},{"text":"Reading"}]}]}]}
+            """#
+        let plan = ReporterImportPlan(archive: try ReporterArchive(data: Data(json.utf8)))
+        #expect(plan.tokens.first { $0.id == "T" }?.text == "Driving a car")
+        #expect(plan.summary.warnings.count == 1)
+        // A token without an ID gets a stable one derived from its text.
+        let reading = try #require(plan.tokens.first { $0.text == "Reading" })
+        #expect(reading.id.hasPrefix("reporter-token-"))
+    }
+
+    @Test("Skipped questions are kept with no value")
+    func skippedQuestions() throws {
+        let response = try report(4).responses[2]
+        #expect(response.questionID == "default-question-4")
+        #expect(response.value == nil)
+        #expect(plan.summary.answersByQuestion["default-question-4"] == 2)
     }
 
     @Test("An answer in an unexpected extra field is ignored and logged")
     func extraAnswer() throws {
         #expect(try report(7).responses[0].value == .options(["No"]))
         #expect(fallbacks(7) == [.extraAnswerIgnored(questionID: "default-question-2")])
+        // The ignored field's token reuses an activity's ID, as one does in
+        // the real export, without moving the token to this question.
+        #expect(try token(Self.tokenID(1)).questionID == "default-question-3")
     }
 
     // MARK: Context

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

@@ -36,10 +36,41 @@ struct ReporterImporterTests {
         let plan = ReporterImportPlan(archive: try Fixtures.reporterArchive(), now: now)
 
         #expect(summary.questionsInserted == 9)
+        #expect(summary.tokensInserted == 11)
         #expect(summary.reportsInserted == 14)
         #expect(summary.reportsAlreadyPresent == 0)
         #expect(try await storedReports() == plan.reports)
         #expect(Set(try await storedQuestions()) == Set(plan.questions))
+        #expect(Set(try await storedTokens()) == Set(plan.tokens))
+    }
+
+    private func storedTokens() async throws -> [Token] {
+        let context = persistence.newBackgroundContext()
+        return try await context.perform {
+            try context.fetch(TokenEntity.fetchRequest()).map { try $0.token() }
+        }
+    }
+
+    @Test("Re-importing keeps renamed tokens renamed")
+    func tokenRenamesSurvive() async throws {
+        _ = try await importer.importArchive(try Fixtures.reporterExport())
+        let walkingID = "C0000001-0000-4000-8000-000000000000"
+
+        let context = persistence.newBackgroundContext()
+        try await context.perform {
+            let request = TokenEntity.fetchRequest()
+            request.predicate = NSPredicate(format: "id == %@", walkingID)
+            let entity = try #require(try context.fetch(request).first)
+            var token = try entity.token()
+            token.text = "Walking outside"
+            try entity.update(from: token)
+            try context.save()
+        }
+
+        let summary = try await importer.importArchive(try Fixtures.reporterExport())
+        #expect(summary.tokensInserted == 0)
+        #expect(summary.tokensAlreadyPresent == 11)
+        #expect(try await storedTokens().first { $0.id == walkingID }?.text == "Walking outside")
     }
 
     @Test("Re-importing the same export changes nothing")