← All repositories

reportage

A life-logging app for iPhone

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


commit f3695c6a2bab9d3ed92c25fc448bb6e074c352b5
parent d070ed3e091b8ca44591ce96c6cae39837bf3f02
Author: Michael Camilleri <[email protected]>
Date:   Tue, 20 Oct 2026 23:50:04 +0900

Merge and separate tokens in the Vocabulary screen

This commit lets the user merge an activity, person or place entered
twice into another of the same kind. 'Merge Into…' on a token's detail
screen picks the token to keep and asks for confirmation. The surviving
token lists what was merged into it under 'Merged Into This', with each
token's own report count, and swiping one separates it again.

A merge only sets the token's mergedInto, which reports already
followed, so no answer is rewritten and separating restores the token
with its name and narrative form. A merged token's name still finds the
token it went into when answering a survey, so typing an old name
doesn't add it again. An answer that used two tokens which are
subsequently merged only shows the token once.

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

Diffstat

MNotes/Design.md | 19+++++++++++++++----
MReportage/Services/Narrative/NarrativeBuilder.swift | 13++++++++++---
MReportage/Views/Home/ReportSummary.swift | 6++++++
MReportage/Views/Report/ReportDetails.swift | 2+-
MReportage/Views/Settings/VocabularyView.swift | 162++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
MReportage/Views/Survey/PlacePicker.swift | 11++++++++---
MReportage/Views/Survey/SurveyModel.swift | 10++++++----
MShared/Persistence/ReportStore.swift | 18++++++++++++++++++
MShared/Persistence/Vocabulary.swift | 45+++++++++++++++++++++++++++++++++++++++++----
MTests/Unit/ReportStoreTests.swift | 33+++++++++++++++++++++++++++++++++
MTests/Unit/ReportSummaryTests.swift | 10++++++++++
MTests/Unit/SurveyModelTests.swift | 14++++++++++++++

12 files changed, 318 insertions(+), 25 deletions(-)

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

@@ -287,6 +287,21 @@ 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).
 
+**Settings → Vocabulary** lists the activities, people and places in use,
+most used first, where each can be renamed and given a narrative form. A
+token can also be merged into another of the same kind, from any question
+of that kind: **Merge Into…** on its detail screen picks the other token
+and asks for confirmation. The surviving token's screen lists what was
+merged into it, under **Merged Into This**, with each token's own report
+count, and swiping one separates it again. A merge only sets `mergedInto`,
+so separating restores the token as it was, with its name and narrative
+form. Merges can chain: a token merged into one that's later merged
+elsewhere follows it, and is listed on the token at the end of the chain.
+
+A merged token's name still finds the token it went into when answering a
+survey, so typing an old name doesn't add it again. An answer that used two
+tokens since merged names the token once.
+
 ### Vocabulary (local only)
 
 Suggestions for token, people and place answers are ranked from a derived
@@ -992,8 +1007,4 @@ the app as a fresh install has it. Prompt settings are kept.
   count, a lead-in for a note), and a blank rule shows the answer as prompt
   and answer.
 - **Narratives in other languages.** Narratives are English only.
-- **Merging in the Vocabulary screen.** Settings → Vocabulary lists the
-  activities, people and places in use, most used first, where each can be
-  renamed and given a narrative form. Merging is settled in the model (see
-  [Token](#token)); how it's presented there isn't.
 - **App lock.** Should there be an optional Face ID lock? The data is personal.

diff --git a/Reportage/Services/Narrative/NarrativeBuilder.swift b/Reportage/Services/Narrative/NarrativeBuilder.swift

@@ -35,10 +35,10 @@ enum NarrativeBuilder {
             else { continue }
             switch (lookup.questionRules[response.questionID], value) {
             case (.activities, .tokens(let ids)):
-                activities += ids.compactMap { form(of: $0, rule: .activities, lookup: lookup) }
+                activities += distinct(ids, lookup).compactMap { form(of: $0, rule: .activities, lookup: lookup) }
                 clauseIndex = clauseIndex ?? sentences.count
             case (.people, .tokens(let ids)):
-                people += ids.compactMap { form(of: $0, rule: .people, lookup: lookup) }
+                people += distinct(ids, lookup).compactMap { form(of: $0, rule: .people, lookup: lookup) }
                 clauseIndex = clauseIndex ?? sentences.count
             case (.place, .place(let answer)):
                 place = place ?? form(of: answer.tokenID, rule: .place, lookup: lookup)
@@ -135,6 +135,13 @@ enum NarrativeBuilder {
         return String(first)
     }
 
+    /// `ids` without those that read as a token earlier in the list, so an
+    /// answer that used two tokens since merged names the token once.
+    static func distinct(_ ids: [String], _ lookup: SummaryLookup) -> [String] {
+        var seen: Set<String> = []
+        return ids.filter { seen.insert(lookup.mergedIDs[$0] ?? $0).inserted }
+    }
+
     /// 'a', 'a and b', 'a, b and c'.
     private static func joined(_ items: [String]) -> String {
         guard items.count > 2 else { return items.joined(separator: " and ") }
@@ -149,7 +156,7 @@ enum NarrativeBuilder {
     static func describe(_ value: ResponseValue, lookup: SummaryLookup) -> String {
         switch value {
         case .options(let options): displayOptions(options)
-        case .tokens(let ids): joined(ids.compactMap { lookup.tokenTexts[$0] })
+        case .tokens(let ids): joined(distinct(ids, lookup).compactMap { lookup.tokenTexts[$0] })
         case .place(let answer): lookup.tokenTexts[answer.tokenID] ?? ""
         case .number(let number): number.formatted()
         case .text(let text): text

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

@@ -10,6 +10,9 @@ struct SummaryLookup: Equatable, Sendable {
     /// Narrative forms of the tokens that have one, by ID, following merges
     /// as `tokenTexts` does.
     var narrativeForms: [String: String] = [:]
+    /// For each merged token, the ID of the token it reads as, at the end
+    /// of its chain of merges.
+    var mergedIDs: [String: String] = [:]
     /// Place tokens, by ID, whose text is still the name a place directory
     /// gave them. A merged token's ID is here if its token's is.
     var directoryPlaces: Set<String> = []
@@ -109,6 +112,9 @@ extension ReportStore {
                     current = next
                 }
                 lookup.tokenTexts[token.id] = current.text
+                if current.id != token.id {
+                    lookup.mergedIDs[token.id] = current.id
+                }
                 if let form = current.narrativeForm, !form.trimmingCharacters(in: .whitespaces).isEmpty {
                     lookup.narrativeForms[token.id] = form
                 }

diff --git a/Reportage/Views/Report/ReportDetails.swift b/Reportage/Views/Report/ReportDetails.swift

@@ -44,7 +44,7 @@ struct ReportDetails: Equatable {
             let value: Answer.Value =
                 switch response.value {
                 case nil: .skipped
-                case .tokens(let ids): .tokens(ids.compactMap { lookup.tokenTexts[$0] })
+                case .tokens(let ids): .tokens(NarrativeBuilder.distinct(ids, lookup).compactMap { lookup.tokenTexts[$0] })
                 case let value?: .text(NarrativeBuilder.describe(value, lookup: lookup))
                 }
             return Answer(prompt: response.prompt, value: value)

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

@@ -81,16 +81,31 @@ final class VocabularyList {
         enqueue { [token] in try await $0.save(token) }
     }
 
+    /// Merges the token with `id` into the token with `target`, so reports
+    /// that use it read as using that token.
+    func merge(_ id: String, into target: String) {
+        enqueue(reloading: true) { try await $0.merge(id, into: target) }
+    }
+
+    /// Separates a token from the token it was merged into.
+    func separate(_ id: String) {
+        enqueue(reloading: true) { try await $0.merge(id, into: nil) }
+    }
+
     /// Runs saves one after another, so a later edit can't be overwritten
-    /// by an earlier one finishing after it.
-    private func enqueue(_ save: @escaping @Sendable (ReportStore) async throws -> Void) {
+    /// by an earlier one finishing after it. A save that changes which tokens
+    /// are listed reloads the list.
+    private func enqueue(
+        reloading: Bool = false, _ save: @escaping @Sendable (ReportStore) async throws -> Void
+    ) {
         guard let store else { return }
         let previous = saving
         saving = Task { [logger] in
             await previous?.value
             do {
                 try await save(store)
-                await MainActor.run { NotificationCenter.default.post(name: .summaryLookupChanged, object: nil) }
+                if reloading { await load(from: store) }
+                NotificationCenter.default.post(name: .summaryLookupChanged, object: nil)
             } catch {
                 logger.error("Couldn't save vocabulary: \(error)")
             }
@@ -177,7 +192,7 @@ private struct VocabularyKindView: View {
         let search = search.trimmingCharacters(in: .whitespaces)
         guard !search.isEmpty else { return all }
         return all.filter { item in
-            item.token.text.localizedStandardContains(search)
+            item.entry.matches(search)
                 || item.token.narrativeForm?.localizedStandardContains(search) ?? false
         }
     }
@@ -219,14 +234,17 @@ private struct VocabularyRow: View {
     }
 }
 
-/// One token, renamed and given a narrative form in place. Each field is
-/// saved when it's finished.
+/// One token, renamed and given a narrative form in place, and merged into
+/// another or separated from those merged into it. Each field is saved when
+/// it's finished.
 private struct TokenDetailView: View {
     let kind: QuestionKind
     let list: VocabularyList
     @State private var text: String
     @State private var form: String
+    @State private var isChoosingTarget = false
     @FocusState private var focus: Field?
+    @Environment(\.dismiss) private var dismiss
 
     private enum Field: Hashable {
         case text
@@ -276,6 +294,45 @@ private struct TokenDetailView: View {
             } header: {
                 SettingsHeading("In Narratives")
             }
+            if !merged.isEmpty {
+                Section {
+                    ForEach(merged) { token in
+                        LabeledContent {
+                            Text(token.useCount.formatted())
+                                .font(.footnote)
+                                .foregroundStyle(Theme.muted)
+                                .accessibilityLabel(Text("Used in ^[\(token.useCount) report](inflect: true)"))
+                        } label: {
+                            Text(token.text)
+                                .font(Theme.serif(.body))
+                        }
+                        .settingsRow()
+                        .swipeActions {
+                            Button("Separate") { list.separate(token.id) }
+                                .tint(Theme.accent)
+                        }
+                    }
+                    SettingsNote {
+                        Text("Reports that use these read as this one. Swipe one to separate it again.")
+                    }
+                } header: {
+                    SettingsHeading("Merged Into This")
+                }
+            }
+            if !targets.isEmpty {
+                Section {
+                    Button("Merge Into…") {
+                        commit()
+                        isChoosingTarget = true
+                    }
+                    .font(.body.weight(.semibold))
+                    .foregroundStyle(Theme.accent)
+                    .frame(maxWidth: .infinity, minHeight: 44)
+                    .listRowBackground(Theme.paper)
+                    .listRowSeparator(.hidden)
+                    SettingsNote { Text(mergeHint) }
+                }
+            }
         }
         .listStyle(.plain)
         .scrollContentBackground(.hidden)
@@ -285,6 +342,36 @@ private struct TokenDetailView: View {
         .navigationBarTitleDisplayMode(.inline)
         .onChange(of: focus) { commit() }
         .onDisappear { commit() }
+        .sheet(isPresented: $isChoosingTarget) {
+            MergeTargetView(kind: kind, source: name, targets: targets) { target in
+                isChoosingTarget = false
+                list.merge(token.id, into: target.id)
+                dismiss()
+            }
+        }
+    }
+
+    /// The token's saved name.
+    private var name: String {
+        list.item(id: token.id)?.token.text ?? token.text
+    }
+
+    /// The tokens merged into this one.
+    private var merged: [MergedToken] {
+        list.item(id: token.id)?.entry.merged ?? []
+    }
+
+    /// The other tokens of this kind, which this one can be merged into.
+    private var targets: [VocabularyList.Item] {
+        (list.items[kind] ?? []).filter { $0.id != token.id }
+    }
+
+    private var mergeHint: LocalizedStringKey {
+        switch kind {
+        case .people: "Merge a person entered twice, such as under a nickname, into the other."
+        case .location: "Merge a place entered twice into the other."
+        default: "Merge an activity entered twice, such as under another name, into the other."
+        }
     }
 
     private var hint: LocalizedStringKey {
@@ -331,3 +418,66 @@ private struct TokenDetailView: View {
         list.update(current)
     }
 }
+
+/// The tokens one can be merged into, searched by name. Choosing one asks
+/// for confirmation.
+private struct MergeTargetView: View {
+    let kind: QuestionKind
+    /// The name of the token being merged.
+    let source: String
+    let targets: [VocabularyList.Item]
+    let onMerge: (VocabularyList.Item) -> Void
+    @State private var search = ""
+    @State private var chosen: VocabularyList.Item?
+    @Environment(\.dismiss) private var dismiss
+
+    var body: some View {
+        NavigationStack {
+            List {
+                ForEach(matching) { item in
+                    Button {
+                        chosen = item
+                    } label: {
+                        VocabularyRow(item: item)
+                            .contentShape(Rectangle())
+                    }
+                    .buttonStyle(.plain)
+                    .settingsRow()
+                }
+                if matching.isEmpty {
+                    SettingsNote { Text("Nothing matches.") }
+                }
+            }
+            .listStyle(.plain)
+            .scrollContentBackground(.hidden)
+            .background(Theme.paper)
+            .foregroundStyle(Theme.ink)
+            .navigationTitle("Merge '\(source)' Into")
+            .navigationBarTitleDisplayMode(.inline)
+            .searchable(text: $search)
+            .toolbar {
+                ToolbarItem(placement: .cancellationAction) {
+                    Button("Cancel") { dismiss() }
+                }
+            }
+            .alert(
+                "Merge '\(source)' into '\(chosen?.token.text ?? "")'?",
+                isPresented: Binding(get: { chosen != nil }, set: { if !$0 { chosen = nil } }),
+                presenting: chosen
+            ) { target in
+                Button("Cancel", role: .cancel) {}
+                Button("Merge") { onMerge(target) }
+            } message: { target in
+                Text(
+                    "Reports that use '\(source)' will read as '\(target.token.text)'. You can separate them again from '\(target.token.text)'."
+                )
+            }
+        }
+    }
+
+    private var matching: [VocabularyList.Item] {
+        let search = search.trimmingCharacters(in: .whitespaces)
+        guard !search.isEmpty else { return targets }
+        return targets.filter { $0.entry.matches(search) }
+    }
+}

diff --git a/Reportage/Views/Survey/PlacePicker.swift b/Reportage/Views/Survey/PlacePicker.swift

@@ -285,7 +285,7 @@ final class PlacePicker {
         let matching =
             text.isEmpty
             ? entries.filter(\.isSavedPlace)
-            : entries.filter { $0.text.localizedStandardContains(text) }
+            : entries.filter { $0.matches(text) }
         let sharedNames = Self.sharedNames(in: entries)
         let own = PlaceRanking.rank(matching, from: origin).map { ranked in
             PlaceCandidate(
@@ -369,12 +369,17 @@ final class PlacePicker {
         )
     }
 
-    /// The place that typing `text` names: one with that name whose region
+    /// The place that typing `text` names, or that a place with that name
+    /// was merged into: one with that name whose region
     /// the report is in, the nearest if there are several. A place with no
     /// coordinate has no region, so its name alone decides, as it does when
     /// the report has no location.
     private func entry(named text: String) -> VocabularyEntry? {
-        let named = entries.filter { Self.nameKey($0.text) == Self.nameKey(text) }
+        let key = Self.nameKey(text)
+        var named = entries.filter { Self.nameKey($0.text) == key }
+        if named.isEmpty {
+            named = entries.filter { $0.merged.contains { Self.nameKey($0.text) == key } }
+        }
         guard let origin = location?.coordinate else { return named.first }
         let inRegion = named.compactMap { entry -> (entry: VocabularyEntry, distance: Double)? in
             guard let coordinate = entry.coordinate else { return nil }

diff --git a/Reportage/Views/Survey/SurveyModel.swift b/Reportage/Views/Survey/SurveyModel.swift

@@ -423,17 +423,19 @@ final class TokenPicker {
         }
     }
 
+    /// The token that typing `text` names: one with that name, or else one
+    /// that a token with that name was merged into.
     private func entry(named text: String) -> VocabularyEntry? {
-        entries.first {
-            $0.text.compare(text, options: [.caseInsensitive, .diacriticInsensitive])
-                == .orderedSame
+        func same(_ name: String) -> Bool {
+            name.compare(text, options: [.caseInsensitive, .diacriticInsensitive]) == .orderedSame
         }
+        return entries.first { same($0.text) } ?? entries.first { $0.merged.contains { same($0.text) } }
     }
 
     private func updateVisibleEntries() {
         let text = query.trimmingCharacters(in: .whitespacesAndNewlines)
         visibleEntries =
-            text.isEmpty ? entries : entries.filter { $0.text.localizedStandardContains(text) }
+            text.isEmpty ? entries : entries.filter { $0.matches(text) }
         canAddQuery = !text.isEmpty && entry(named: text) == nil
     }
 

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

@@ -237,6 +237,24 @@ struct ReportStore: Sendable {
         }
     }
 
+    /// Merges the token with `id` into the token with `target`, so answers
+    /// that use it read as using that token, or separates it again when
+    /// `target` is `nil`. No answer is rewritten, so a merge can be undone.
+    func merge(_ id: String, into target: String?) async throws {
+        let context = persistence.newBackgroundContext()
+        try await context.perform {
+            let request = TokenEntity.fetchRequest()
+            request.predicate = NSPredicate(format: "id == %@", id)
+            request.fetchLimit = 1
+            guard let entity = try context.fetch(request).first else { return }
+            var token = try entity.token()
+            token.mergedInto = target
+            token.modifiedAt = Date()
+            try entity.update(from: token)
+            try context.save()
+        }
+    }
+
     /// Ranked suggestions for each of `questionIDs`. See `Vocabulary`.
     func vocabulary(for questionIDs: [String]) async throws -> [String: [VocabularyEntry]] {
         let context = persistence.newBackgroundContext()

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

@@ -16,6 +16,24 @@ struct VocabularyEntry: Identifiable, Hashable, Sendable {
     /// For places: the locality of the most recent report that used it,
     /// which tells apart places with the same name.
     var locality: String?
+    /// The tokens merged into this one, directly or along a chain, most
+    /// used first. Their names still find it.
+    var merged: [MergedToken] = []
+
+    /// Whether the token's name, or the name of a token merged into it,
+    /// contains `text`.
+    func matches(_ text: String) -> Bool {
+        self.text.localizedStandardContains(text)
+            || merged.contains { $0.text.localizedStandardContains(text) }
+    }
+}
+
+/// A token merged into another, which can be separated again.
+struct MergedToken: Identifiable, Hashable, Sendable {
+    var id: String
+    var text: String
+    /// How many reports use this token itself, before the merge.
+    var useCount: Int
 }
 
 /// The derived, local-only index that ranks suggestions from response
@@ -24,7 +42,9 @@ struct VocabularyEntry: Identifiable, Hashable, Sendable {
 enum Vocabulary {
     /// Suggestions for each of `questionIDs`, most used first, then most
     /// recently used. Archived tokens and tokens merged into others are left
-    /// out; uses of a merged token count towards the token it was merged into.
+    /// out; uses of a merged token count towards the token it was merged into,
+    /// and the merged token is listed in that token's `merged`, wherever its
+    /// question.
     /// A place with no coordinate of its own is placed at the centre of where
     /// its answers were given, and each place has the locality of the last
     /// report that used it.
@@ -35,7 +55,8 @@ enum Vocabulary {
         guard !questionIDs.isEmpty else { return [:] }
 
         let tokenRequest = TokenEntity.fetchRequest()
-        tokenRequest.predicate = NSPredicate(format: "questionID IN %@", questionIDs)
+        tokenRequest.predicate = NSPredicate(
+            format: "questionID IN %@ OR mergedInto != nil", questionIDs)
         let tokens = try context.fetch(tokenRequest).map { try $0.token() }
         let mergedInto = Dictionary(
             uniqueKeysWithValues: tokens.compactMap { token in
@@ -52,6 +73,7 @@ enum Vocabulary {
         }
 
         var useCounts: [String: Int] = [:]
+        var ownUseCounts: [String: Int] = [:]
         var lastUsed: [String: Date] = [:]
         var answerCoordinates: [String: (latitude: Double, longitude: Double, count: Int)] = [:]
         var lastReports: [String: NSManagedObjectID] = [:]
@@ -84,6 +106,9 @@ enum Vocabulary {
             default: continue
             }
             let date = row["report.date"] as? Date
+            for id in Set(ids) where mergedInto[id] != nil {
+                ownUseCounts[id, default: 0] += 1
+            }
             for id in Set(ids.map(canonical)) {
                 useCounts[id, default: 0] += 1
                 if let date, date > lastUsed[id] ?? .distantPast {
@@ -94,8 +119,15 @@ enum Vocabulary {
 
         let localities = try self.localities(of: lastReports, in: context)
 
+        var merged: [String: [MergedToken]] = [:]
+        for token in tokens where token.mergedInto != nil {
+            merged[canonical(token.id), default: []].append(
+                MergedToken(id: token.id, text: token.text, useCount: ownUseCounts[token.id] ?? 0))
+        }
+
         var entries: [String: [VocabularyEntry]] = [:]
-        for token in tokens where token.mergedInto == nil && token.archivedAt == nil {
+        for token in tokens
+        where questionIDs.contains(token.questionID) && token.mergedInto == nil && token.archivedAt == nil {
             let centre = answerCoordinates[token.id].map {
                 Coordinate(
                     latitude: $0.latitude / Double($0.count),
@@ -109,7 +141,12 @@ enum Vocabulary {
                     lastUsed: lastUsed[token.id],
                     coordinate: token.place?.coordinate ?? centre,
                     externalID: token.place?.externalID,
-                    locality: localities[token.id]
+                    locality: localities[token.id],
+                    merged: (merged[token.id] ?? []).sorted { lhs, rhs in
+                        lhs.useCount != rhs.useCount
+                            ? lhs.useCount > rhs.useCount
+                            : lhs.text.localizedStandardCompare(rhs.text) == .orderedAscending
+                    }
                 ))
         }
         for questionID in entries.keys {

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

@@ -111,6 +111,39 @@ struct ReportStoreTests {
         #expect(entries[0].lastUsed == Date(timeIntervalSince1970: 4 * 3600))
     }
 
+    @Test("Merging lists a token under the one it went into, wherever its question, until separated")
+    func mergeTokens() async throws {
+        let other = Token(
+            id: "O", questionID: "Old", text: "Sammy", mergedInto: "B",
+            modifiedAt: Date(timeIntervalSince1970: 0))
+        let tokens = [Self.token("A", "Sam Lee"), Self.token("B", "Sam"), Self.token("C", "Kai"), other]
+        func answer(_ ids: String...) -> Response {
+            Response(questionID: "Q", prompt: "P", value: .tokens(ids))
+        }
+        try await store.insert(Self.report(1, responses: [answer("A", "B")]), newTokens: tokens)
+        try await store.insert(Self.report(2, responses: [answer("B")]))
+        try await store.insert(Self.report(3, responses: [answer("C")]))
+        try await store.insert(
+            Self.report(4, responses: [Response(questionID: "Old", prompt: "P", value: .tokens(["O"]))]))
+
+        try await store.merge("B", into: "A")
+        var entries = try #require(try await store.vocabulary(for: ["Q"])["Q"])
+        // Report 1 uses A and B but counts once. Sammy, merged into Sam
+        // from another question, follows it into Sam Lee.
+        #expect(entries.map(\.id) == ["A", "C"])
+        #expect(entries[0].useCount == 2)
+        #expect(entries[0].merged == [MergedToken(id: "B", text: "Sam", useCount: 2), MergedToken(id: "O", text: "Sammy", useCount: 0)])
+        #expect(entries[0].matches("sammy"))
+        #expect(try await store.tokens(for: ["Q"]).map(\.id) == ["A", "C"])
+        #expect(try await store.summaryLookup().mergedIDs == ["B": "A", "O": "A"])
+
+        try await store.merge("B", into: nil)
+        entries = try #require(try await store.vocabulary(for: ["Q"])["Q"])
+        #expect(entries.map(\.id) == ["B", "C", "A"])
+        #expect(entries.first { $0.id == "A" }?.merged.isEmpty == true)
+        #expect(entries[0].merged.map(\.id) == ["O"])
+    }
+
     @Test("The summary lookup has narrative forms, following merges and ignoring blank ones")
     func narrativeFormLookup() async throws {
         var yamada = Self.token("Y", "山田花子")

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

@@ -46,6 +46,16 @@ struct NarrativeBuilderTests {
         #expect(narrative == "With Sam, Sam, 田中さん and 田中 太郎.")
     }
 
+    @Test("Tokens merged into one another are named once")
+    func mergedTokens() {
+        var lookup = Self.lookup
+        lookup.tokenTexts["sammy"] = "Sam Lee"
+        lookup.mergedIDs["sammy"] = "lee"
+        let responses = [Self.response("people", .tokens(["sammy", "kai", "lee"]))]
+        #expect(NarrativeBuilder.build(responses: responses, lookup: lookup).narrative == "With Sam and Kai.")
+        #expect(NarrativeBuilder.describe(responses[0].value!, lookup: lookup) == "Sam Lee and Kai")
+    }
+
     @Test("A narrative form wins over the rules for people, places and activities")
     func narrativeForms() {
         let (narrative, details) = Self.build([

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

@@ -311,6 +311,20 @@ struct TokenPickerTests {
         #expect(!picker.canAddQuery)
     }
 
+    @Test("Text naming a token merged into an entry finds and selects the entry")
+    func mergedName() {
+        var cooking = VocabularyEntry(id: "2", text: "Cooking", useCount: 2)
+        cooking.merged = [MergedToken(id: "4", text: "Making dinner", useCount: 1)]
+        let picker = TokenPicker(questionID: "Q", allowsMultiple: true, entries: [cooking])
+        picker.query = "dinner"
+        #expect(picker.visibleEntries.map(\.id) == ["2"])
+        #expect(picker.canAddQuery)
+        picker.query = "making DINNER"
+        #expect(!picker.canAddQuery)
+        picker.addQuery()
+        #expect(picker.selection == ["2"])
+    }
+
     @Test("Adding text that names an entry selects the entry")
     func addExisting() {
         let picker = makePicker()