commit b7b3d947c09568f8876b4c79df6f2ffad1e21c4f
parent b5a2a8831d21b1082bcc90775ed661f9ffe2ae9f
Author: Michael Camilleri <[email protected]>
Date: Mon, 19 Oct 2026 17:22:12 +0900
Write entries without the on-device model
Reportage tried to use the on-device model to write a grammatically
correct narrative describing a user's report. This did not work reliably
and this version replaces it with a deterministic algorithm.
Entries are now built entirely from the answers, so they appear at once,
read the same way every time and need no 'Writing narrative…' state. A
place reads after 'at' by rules instead: a name from MapKit or
Foursquare is shown as written while the token's text is still the
directory's name; places such as home and work are lowercased without an
article; ordinary words are lowercased and take 'the'; and anything else
is taken to be a name.
Entries also open differently. How the user slept now comes first (when
that is provided), then the activities, place and people, then the other
answers in survey order.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat
| M | Notes/Design.md | | | 139 | +++++++++++++++++++++++++++++++------------------------------------------------ |
| M | Reportage.xcodeproj/project.pbxproj | | | 16 | ++++++++-------- |
| M | Reportage/Services/Narrative/DisplayRule.swift | | | 14 | +++++++++++--- |
| R | Reportage/Services/Narrative/EntryDraft.swift -> Reportage/Services/Narrative/EntryBuilder.swift | | | 110 | ++++++++++++++++++++++++++++--------------------------------------------------- |
| D | Reportage/Services/Narrative/NarrativePolisher.swift | | | 246 | ------------------------------------------------------------------------------- |
| A | Reportage/Services/Narrative/PlacePhrase.swift | | | 46 | ++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Reportage/Views/Home/HomeView.swift | | | 72 | +----------------------------------------------------------------------- |
| M | Reportage/Views/Home/ReportSummary.swift | | | 34 | ++++++++++++---------------------- |
| M | Tests/Unit/ReportSummaryTests.swift | | | 153 | +++++++++++++++++++++++++++++++++++++------------------------------------------ |
9 files changed, 243 insertions(+), 587 deletions(-)
diff --git a/Notes/Design.md b/Notes/Design.md
@@ -199,9 +199,7 @@ question the user reworded gets the wrong phrasing.
| `context` | Encoded `Context` value (below). |
| `legacy` | For imported reports: the original Reporter snapshot JSON, compressed. This guarantees a lossless import without modelling every Reporter-specific field. |
| `modifiedAt` | Used for last-writer-wins on sync. |
-| `narrative` | Local only. The polished entry (see [Entries](#entries)). Derived, so not exported or synced: each device writes its own. |
-| `narrativeDraft` | Local only. The draft `narrative` was made from. The narrative is current only while it matches the report's draft. |
-| `narrativeVersion` | Local only. The version of the polishing pass that wrote `narrative`. An older version is rewritten. |
+| `narrative`, `narrativeDraft`, `narrativeVersion` | Unused. They held the model-polished entry, which is gone (see [Entries](#entries)). Kept until the Core Data model is next versioned, because removing them without an earlier version to migrate from would stop existing stores opening. |
### Response
@@ -377,10 +375,9 @@ Context fields fall into two groups, and this shapes the whole capture design:
## Entries
-Each report reads as a short written entry. It's built deterministically from
-the answers, then lightly polished by the on-device model. The draft is always
-correct and always available, and the polish only improves its English: it
-can't add, drop or change anything the user said.
+Each report reads as a short written entry, built deterministically from the
+answers. The same answers always read the same way, with nothing invented,
+dropped or changed.
### Drafts
@@ -389,16 +386,18 @@ Each question has a `DisplayRule` saying how its answer reads:
| Rule | Used for | Example |
|------|----------|---------|
| Activities | `tokens` questions | 'Reading, drinking coffee and watching Netflix…' |
-| Place | `location` questions | '…at Library…' |
+| Place | `location` questions | '…at the library…' |
| People | `people` questions | '…, with Sam and Kai.' |
| Phrases | yes/no | 'Yes' → 'Working', 'No' → 'Not working' |
| Template | choice | 'Feeling %@' → 'Feeling great' |
| Count | number | '1 coffee', '2 coffees' |
| Quote | note | "Learned: 'The neighbours are nice people.'" |
-Activities, place and people join one clause, placed where the first of those
-answers comes in the survey. Other answers follow in survey order, one
-sentence each. An answer to a question with no rule is shown beneath the entry
+Activities, place and people join one clause. How the night went comes
+first ('Slept well.'), then the clause, since it's what was happening, then
+the other answers in survey order, one sentence each. So 'Are you working?'
+being asked before 'What are you doing?' doesn't make the entry open with
+'Working.'. An answer to a question with no rule is shown beneath the entry
as its prompt and answer, so nothing is hidden.
Notes are quoted exactly as written and never rewritten: free writing breaks
@@ -408,76 +407,49 @@ Later activities in a list are lowercased only when the first word is
capitalised just at its start, its lowercase form is an ordinary English word
(`UITextChecker`) and the language tagger doesn't mark it as a name. So
'Drinking coffee' becomes 'drinking coffee', while 'Watching Netflix',
-'Studying Japanese' and 'TV' keep their capitals. People and places are shown
-as written.
-
-Drafts are English only for now, as is the polish.
-
-### Polishing
-
-`NarrativePolisher` sends the draft to the on-device model
-(`SystemLanguageModel`, with `permissiveContentTransformations` guardrails)
-with these instructions:
-
- Proofread the input. Correct spelling, grammar and punctuation only.
- Reply with the corrected text only.
-
-- **Protection.** People, quoted notes and every word with letters outside
- ASCII are swapped for placeholders (`X1`, `X2`…) first and put back
- afterwards, because the model romanises Japanese names whatever it's told
- (吉祥寺駅 becomes 'Kyoji-ji Station') and strips accents ('Lumière').
- Placeholders look like ordinary words, since the model rewrites bracketed
- ones such as `[[1]]`.
-- **The check.** `NarrativeCheck` accepts the output only if every placeholder
- appears exactly once, the number of sentences is unchanged, no content word
- is added or dropped (connecting words such as 'the', 'and' and 'with' may
- change), a capital is only removed from an ordinary word, a place lowercased
- after 'at' gains an article unless it reads without one ('home', 'work'),
- and no article appears before a placeholder that didn't have one.
-- **Attempts.** The model returns text unchanged about three times in ten
- even when it fixes the same text on other runs ('at Home' left as it was),
- so an unchanged or failing output is tried again, up to three attempts. The
- first passing output that changes something is used.
-- **Outcomes.** A passing output is stored. If every attempt fails or leaves
- the draft unchanged, the draft is stored, so the report isn't retried every
- time it's shown. If the model is unavailable, nothing is stored and it's
- tried again later.
-- **Versions.** Each narrative stores the version of the polishing pass that
- wrote it (`NarrativePolisher.version`). Raising the version, when the
- instructions or the check change, rewrites every entry the next time it's
- shown.
-- One request runs at a time, responses are capped at 150 tokens so a
- runaway response stops early rather than at the model's 8,192-token limit,
- and scrolling away cancels a waiting request.
-
-### When entries are written
-
-An entry is polished the first time it's shown: when its row appears and has
-no narrative, the row shows the draft with 'Writing narrative…' until the
-polish is stored. The narrative is stored with the draft it came from, so
-editing an answer or renaming a token changes the draft and the entry is
-rewritten the next time it's shown. A new report's entry is written as soon as
-the survey closes, because it appears at the top of the list. Entries for an
-imported archive are only ever written for the reports someone scrolls to.
-
-### Why the model only proofreads
+'Studying Japanese' and 'TV' keep their capitals. People are shown as written,
+and places as below.
+
+Entries are English only for now.
+
+### Places
+
+A place reads after 'at', decided in this order:
+
+1. **A directory's name** is shown as written: a place with a MapKit or
+ Foursquare ID whose text is still one of its directory names ('at Blue
+ Bottle Coffee', 'at 吉祥寺駅'). A place with no directory names, as with
+ imported Foursquare venues, counts as named by its directory. Once renamed,
+ the place is the user's own word and goes through the rules below.
+2. **Places that read without an article** (`PlacePhrase.barePlaces`: home,
+ work, school, bed, church…) are lowercased: 'at home'.
+3. **Ordinary words** are lowercased and take 'the' ('at the library', 'at
+ the coffee shop'), or keep an article they already have ('The beach'
+ becomes 'the beach'). That means only the first letter is a capital,
+ every word has letters with case and nothing else, every word passes the
+ spell checker (`UITextChecker`), and the language tagger doesn't mark the
+ text as a name.
+4. **Anything else** is taken to be a name and shown as written: 'Central
+ Library', 'IKEA', 'Mum's', 'Kichijōji'.
+
+The rules guess wrong now and then (a restaurant typed as 'Bank' becomes 'the
+bank'), so each place is planned to have a form the user can set, which wins
+over the rules. See [Open Questions](#open-questions).
+
+### Why not the on-device model
+
+Entries used to be proofread by the on-device model (`SystemLanguageModel`)
+to add articles and fix casing. It was dropped:
- **Writing entries from scratch** invents details (a kitchen table, a date, a
time of night), changes what notes mean, drops answers and assigns people to
- the wrong activities. A short proofreading request does the right job:
- articles ('at the library', 'at home'), casing and commas. Writing Tools
- (`UIWritingToolsCoordinator`) would do the same, but only works through its
- on-screen interface.
-- **Display rules are written in natural English.** The model reliably
- rewrites stiff phrases ('5.5 hours asleep'), which fails the check.
-- **It doesn't fix every place** ('Gardening at Park' stays), which per-token
- inline forms are planned to cover.
-- **A model of its own** is a possible upgrade: an app can plug one in
- through the `LanguageModel` protocol (system model adapters are gone in
- iOS 27). A small model trained for this one task would replace the system
- model only if it clearly beats it on a fixed test set. Private Cloud
- Compute (`PrivateCloudComputeLanguageModel`) is off-device and
- rate-limited, so it isn't used.
+ the wrong activities.
+- **Proofreading** was safe only behind placeholders for names and non-ASCII
+ words, and a check that every output kept every word. Even then the model
+ left text unchanged about three times in ten ('at Home' kept its capital),
+ so entries needed retries, storage, versioning and a 'Writing narrative…'
+ state while they were written. By then its only real job was places, which
+ the rules above do reliably, at once and the same way every time.
## Prompt Scheduling
@@ -884,12 +856,11 @@ the app as a fresh install has it. Prompt settings are kept.
whether the one custom question in the real export joins it. The wording
should come from the user rather than being copied from the export.
- **Display rules for custom questions.** How the user writes one when adding
- a question. The on-device model could suggest a rule for the user to check.
-- **Inline forms.** How the user sets a token's mid-sentence form ('the park'),
- and whether the model should suggest one when a token is created, accepted
- only if it changes nothing but case and a leading article. The model gets
- common places right but also suggests 'the home' and 'the uniqlo'.
-- **Entries in other languages.** Drafts and the polish are English only.
+ a question.
+- **Place forms.** A field on a place token for how it reads after 'at' ('the
+ office', 'my desk'), filled from the [place rules](#places) and winning over
+ them. It changes the token record, so it lands with the sync schema.
+- **Entries in other languages.** Entries are English only.
- **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
@@ -35,7 +35,7 @@
6F06CC539C4D17B343A9321C /* LegacyBlob.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30FFB17809ADA84F1036E2A7 /* LegacyBlob.swift */; };
7488B9EE97D419E2B6B9FCEA /* PromptNotification.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9C326FBA3249ED86912FBF5 /* PromptNotification.swift */; };
7676E79864C7C26CB9EA4B10 /* PromptSchedule.swift in Sources */ = {isa = PBXBuildFile; fileRef = 86474CD2E8EC300CD6B37BB2 /* PromptSchedule.swift */; };
- 770B4C77FABB2A7A0B2C5E3A /* EntryDraft.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14AD1548EA722CF1E19BCE42 /* EntryDraft.swift */; };
+ 7A6543B7C48EC93D468EBBD8 /* PlacePhrase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 577EC17EF58F65207B7EA15D /* PlacePhrase.swift */; };
7ACDA81EC3D7811F891CA029 /* ReportSummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1BBAB5AD6266B8F6E3507AE3 /* ReportSummary.swift */; };
81B485BD03549DE6E7AA94A7 /* AppBadge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CE5E7D863F9BD3DF363AA9A /* AppBadge.swift */; };
83E954F0DAC9719D2AA02111 /* HomeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36C7E4E96538BB14AD6956CA /* HomeView.swift */; };
@@ -54,6 +54,7 @@
B00AC94E13BC9C602179953E /* SurveyModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E382405EE9DBEC8EE616C1D /* SurveyModelTests.swift */; };
B454D3067CD611AE55E30A1D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 633FE6CD8111A433CA9BE7EC /* AppDelegate.swift */; };
B510BB2C1C11D72DFE15E3C7 /* ReportageExportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DB6FF151DCEBC3913131834 /* ReportageExportTests.swift */; };
+ B6A7D4DE1FF9314F459A73CB /* EntryBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8E21C29422DA372F6363365 /* EntryBuilder.swift */; };
BD8D81CBF8C3DE544BB7540C /* DefaultQuestions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 94DB0CA378AEF82B3CB27B67 /* DefaultQuestions.swift */; };
C5D94FEC4507054E6497E85B /* PersistenceController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61C0B5BB02ECDBE84F5F73FA /* PersistenceController.swift */; };
C71E99843CC3D9DE4468B36B /* Environment.swift in Sources */ = {isa = PBXBuildFile; fileRef = 878CE0FF7A2598F4197E8E61 /* Environment.swift */; };
@@ -78,7 +79,6 @@
EA730F4FD060F5843CC5B422 /* SurveyView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7998F9826B899741323C0C7 /* SurveyView.swift */; };
EFF44121C9ECBFBCAC1D7730 /* ReportageModel.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = A49FBFD55992A79B9A6492C4 /* ReportageModel.xcdatamodeld */; };
F38A1CCFAF016AB982EAB791 /* Question.swift in Sources */ = {isa = PBXBuildFile; fileRef = B007E6BACAA214C7332EF77C /* Question.swift */; };
- F6F2DD23C77A981D76BE0480 /* NarrativePolisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF426915E941538164D91B18 /* NarrativePolisher.swift */; };
FBE598AB29E0297BC232ED75 /* ReportDetailsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BEB5080BDA34F703DDC08ADB /* ReportDetailsTests.swift */; };
FD41318BC8EEAF3208CD59B7 /* RootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A70B6E5B7C07D2CE13E9E771 /* RootView.swift */; };
/* End PBXBuildFile section */
@@ -96,7 +96,6 @@
/* Begin PBXFileReference section */
0734316A58943D5F2E26F718 /* ReportSummaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportSummaryTests.swift; sourceTree = "<group>"; };
0B35602A218BE4EE399835FD /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
- 14AD1548EA722CF1E19BCE42 /* EntryDraft.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EntryDraft.swift; sourceTree = "<group>"; };
1B6C4141A26EED99B1F03FBE /* PlacePickerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlacePickerTests.swift; sourceTree = "<group>"; };
1BBAB5AD6266B8F6E3507AE3 /* ReportSummary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportSummary.swift; sourceTree = "<group>"; };
1C4665B55B0307E899595C1D /* PromptScheduler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptScheduler.swift; sourceTree = "<group>"; };
@@ -114,6 +113,7 @@
48D44876FDE4293FA0460595 /* ReporterImporter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImporter.swift; sourceTree = "<group>"; };
4C40E7F6C3A90E317C8CB5B1 /* PlacePicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlacePicker.swift; sourceTree = "<group>"; };
5591E042089D038B59B26E9F /* ReportKind+Title.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ReportKind+Title.swift"; sourceTree = "<group>"; };
+ 577EC17EF58F65207B7EA15D /* PlacePhrase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlacePhrase.swift; sourceTree = "<group>"; };
5BE7248E73E2859EFF232170 /* EntityMapping.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EntityMapping.swift; sourceTree = "<group>"; };
5C2AB8F226532A0889E2BCAD /* Reportage.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = Reportage.app; sourceTree = BUILT_PRODUCTS_DIR; };
5C606A9B0EF8D84950B9681B /* ModelCodingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelCodingTests.swift; sourceTree = "<group>"; };
@@ -150,8 +150,8 @@
A3BE62142CCC4A791F05163A /* Token.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Token.swift; sourceTree = "<group>"; };
A70B6E5B7C07D2CE13E9E771 /* RootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootView.swift; sourceTree = "<group>"; };
A7DD8E44D1A1F7789F528BD3 /* EventLogTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EventLogTests.swift; sourceTree = "<group>"; };
+ A8E21C29422DA372F6363365 /* EntryBuilder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EntryBuilder.swift; sourceTree = "<group>"; };
A9C326FBA3249ED86912FBF5 /* PromptNotification.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptNotification.swift; sourceTree = "<group>"; };
- AF426915E941538164D91B18 /* NarrativePolisher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NarrativePolisher.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>"; };
B7998F9826B899741323C0C7 /* SurveyView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SurveyView.swift; sourceTree = "<group>"; };
@@ -346,9 +346,9 @@
isa = PBXGroup;
children = (
8E609FFCB918B4EF9BFCC018 /* DisplayRule.swift */,
- 14AD1548EA722CF1E19BCE42 /* EntryDraft.swift */,
+ A8E21C29422DA372F6363365 /* EntryBuilder.swift */,
A00E589A8387E7A1E348503C /* InlineCasing.swift */,
- AF426915E941538164D91B18 /* NarrativePolisher.swift */,
+ 577EC17EF58F65207B7EA15D /* PlacePhrase.swift */,
);
path = Narrative;
sourceTree = "<group>";
@@ -567,7 +567,7 @@
16CDDFE25EBB07C0EA9AC5AA /* DiagnosticsSection.swift in Sources */,
D0497C9835A2502936591DC1 /* DisplayRule.swift in Sources */,
406D536D7764B3FEB140CAA0 /* EntityMapping.swift in Sources */,
- 770B4C77FABB2A7A0B2C5E3A /* EntryDraft.swift in Sources */,
+ B6A7D4DE1FF9314F459A73CB /* EntryBuilder.swift in Sources */,
C71E99843CC3D9DE4468B36B /* Environment.swift in Sources */,
123470F9E3205890526D3A89 /* EventLog.swift in Sources */,
226A38BE6D7171D892EA35B3 /* FirstLaunch.swift in Sources */,
@@ -575,11 +575,11 @@
6E21E729F89178EBD019980E /* InlineCasing.swift in Sources */,
3244B8439B5E4F79FF84C156 /* JSONSlicer.swift in Sources */,
6F06CC539C4D17B343A9321C /* LegacyBlob.swift in Sources */,
- F6F2DD23C77A981D76BE0480 /* NarrativePolisher.swift in Sources */,
D1F2257DDB68439AF352B57D /* PassiveLog.swift in Sources */,
C5D94FEC4507054E6497E85B /* PersistenceController.swift in Sources */,
2EE68329C383FA1C5295ACA9 /* PlaceAnswerView.swift in Sources */,
D3C3046B927DB98443E005C8 /* PlaceDirectory.swift in Sources */,
+ 7A6543B7C48EC93D468EBBD8 /* PlacePhrase.swift in Sources */,
D74CE3807E9593D470DADAA8 /* PlacePicker.swift in Sources */,
633A94E029055EA5D50D00AC /* PlaceRanking.swift in Sources */,
7488B9EE97D419E2B6B9FCEA /* PromptNotification.swift in Sources */,
diff --git a/Reportage/Services/Narrative/DisplayRule.swift b/Reportage/Services/Narrative/DisplayRule.swift
@@ -3,13 +3,12 @@ import Foundation
/// How a question's answer reads in a report's entry. Questions without a
/// rule are shown as their prompt and answer instead.
///
-/// Rules write English. The entry is English-only for now, as is the
-/// proofreading pass that polishes it.
+/// Rules write English. The entry is English-only for now.
enum DisplayRule: Equatable, Sendable {
/// Joins the entry's main clause as what was happening:
/// 'Reading and drinking coffee…'.
case activities
- /// Joins the main clause as where: '…at Library'.
+ /// Joins the main clause as where: '…at the library'.
case place
/// Joins the main clause as who with: '…with Sam and Kai'.
case people
@@ -59,6 +58,15 @@ enum DisplayRule: Equatable, Sendable {
return rules
}()
+ /// Questions whose answers open the entry, before the main clause: the
+ /// night comes before what's happening now. Includes Reporter's
+ /// questions that ask the same things.
+ static let leading: Set<String> = {
+ let names: Set<String> = ["sleep-quality"]
+ let reporterIDs = reporterQuestions.filter { names.contains($0.value) }.keys
+ return Set(names.map { DefaultQuestions.idPrefix + $0 }).union(reporterIDs)
+ }()
+
/// Reporter's built-in questions, by the default question that asks the
/// same thing.
private static let reporterQuestions = [
diff --git a/Reportage/Services/Narrative/EntryDraft.swift b/Reportage/Services/Narrative/EntryBuilder.swift
@@ -1,26 +1,5 @@
import Foundation
-/// A report's entry as built from its answers, before any polishing.
-///
-/// Fixed parts (people and quoted notes) must reach the reader exactly as
-/// written, so the proofreading pass never sees them.
-struct EntryDraft: Equatable, Sendable {
- enum Part: Equatable, Sendable {
- case text(String)
- case fixed(String)
-
- var string: String {
- switch self {
- case .text(let text), .fixed(let text): text
- }
- }
- }
-
- var parts: [Part]
-
- var text: String { parts.map(\.string).joined() }
-}
-
/// An answer the entry doesn't cover, shown as its question and answer.
struct AnswerDetail: Equatable, Identifiable, Sendable {
var id: String { questionID }
@@ -35,100 +14,102 @@ enum EntryBuilder {
static func build(
responses: [Response],
lookup: SummaryLookup
- ) -> (draft: EntryDraft?, details: [AnswerDetail]) {
+ ) -> (entry: String?, details: [AnswerDetail]) {
+ // Sentences that open the entry, then the rest in survey order.
+ var leading: [Sentence] = []
var sentences: [Sentence] = []
var details: [AnswerDetail] = []
var activities: [String] = []
var people: [String] = []
var place: String?
- // The main clause goes where its first answer would have.
- var clauseIndex: Int?
for response in responses {
guard let value = response.value else { continue }
+ let start = sentences.count
+ defer {
+ if DisplayRule.leading.contains(response.questionID) {
+ leading += sentences[start...]
+ sentences.removeSubrange(start...)
+ }
+ }
let rule = DisplayRule.rule(
for: response.questionID, kind: lookup.questionKinds[response.questionID])
switch (rule, value) {
case (.activities, .tokens(let ids)):
activities += ids.compactMap { lookup.tokenTexts[$0] }
- clauseIndex = clauseIndex ?? sentences.count
case (.people, .tokens(let ids)):
people += ids.compactMap { lookup.tokenTexts[$0] }
- clauseIndex = clauseIndex ?? sentences.count
case (.place, .place(let answer)):
- place = place ?? lookup.tokenTexts[answer.tokenID]
- clauseIndex = clauseIndex ?? sentences.count
+ place = place ?? placePhrase(for: answer.tokenID, lookup: lookup)
case (.phrases(let phrases), .options(let options)):
if let phrase = options.lazy.compactMap({ phrases[$0] }).first {
- sentences.append(Sentence([.text(phrase)]))
+ sentences.append(Sentence(phrase))
} else {
details.append(detail(for: response, answer: displayOptions(options)))
}
case (.template(let template), .options(let options)):
let answer = joined(options.map(InlineCasing.inline))
- sentences.append(Sentence([.text(template.replacingOccurrences(of: "%@", with: answer))]))
+ sentences.append(Sentence(template.replacingOccurrences(of: "%@", with: answer)))
case (.count(let singular, let plural), .number(let number)):
let noun = number == 1 ? singular : plural
- sentences.append(Sentence([.text("\(number.formatted()) \(noun)")]))
+ sentences.append(Sentence("\(number.formatted()) \(noun)"))
case (.quote(let lead), .text(let note)):
let note = note.trimmingCharacters(in: .whitespacesAndNewlines)
let ended = note.last.map { ".!?".contains($0) } ?? false
- sentences.append(Sentence([.text("\(lead): "), .fixed("'\(note)'")], isEnded: ended))
+ sentences.append(Sentence("\(lead): '\(note)'", isEnded: ended))
default:
details.append(detail(for: response, answer: describe(value, lookup: lookup)))
}
}
+ // What's happening comes before the answers about it.
if let clause = mainClause(activities: activities, place: place, people: people) {
- sentences.insert(clause, at: min(clauseIndex ?? 0, sentences.count))
+ sentences.insert(clause, at: 0)
}
+ sentences = leading + sentences
guard !sentences.isEmpty else { return (nil, details) }
- var parts: [EntryDraft.Part] = []
- for (index, sentence) in sentences.enumerated() {
- if index > 0 { parts.append(.text(" ")) }
- parts += sentence.capitalised().parts
- if !sentence.isEnded { parts.append(.text(".")) }
+ let entry = sentences.map { sentence in
+ sentence.capitalised + (sentence.isEnded ? "" : ".")
}
- return (EntryDraft(parts: merged(parts)), details)
+ return (entry.joined(separator: " "), details)
}
private struct Sentence {
- var parts: [EntryDraft.Part]
+ var text: String
var isEnded = false
- init(_ parts: [EntryDraft.Part], isEnded: Bool = false) {
- self.parts = parts
+ init(_ text: String, isEnded: Bool = false) {
+ self.text = text
self.isEnded = isEnded
}
- func capitalised() -> Sentence {
- guard case .text(let first)? = parts.first, let initial = first.first else { return self }
- var copy = self
- copy.parts[0] = .text(initial.uppercased() + first.dropFirst())
- return copy
+ var capitalised: String {
+ guard let initial = text.first else { return text }
+ return initial.uppercased() + text.dropFirst()
}
}
- /// 'Reading and drinking coffee at Library, with Sam and Kai'.
+ /// 'Reading and drinking coffee at the library, with Sam and Kai'.
private static func mainClause(activities: [String], place: String?, people: [String]) -> Sentence? {
- var parts: [EntryDraft.Part] = []
+ var text = ""
if !activities.isEmpty {
- parts.append(.text(joined(activities.map(InlineCasing.inline))))
+ text += joined(activities.map(InlineCasing.inline))
}
if let place {
- parts.append(.text(parts.isEmpty ? "At " : " at "))
- parts.append(.text(place))
+ text += (text.isEmpty ? "At " : " at ") + place
}
if !people.isEmpty {
- parts.append(.text(parts.isEmpty ? "With " : ", with "))
- for (index, person) in people.enumerated() {
- if index > 0 { parts.append(.text(index == people.count - 1 ? " and " : ", ")) }
- parts.append(.fixed(person))
- }
+ text += (text.isEmpty ? "With " : ", with ") + joined(people)
}
- return parts.isEmpty ? nil : Sentence(parts)
+ return text.isEmpty ? nil : Sentence(text)
+ }
+
+ /// How a place reads after 'at'. A directory's name is shown as written.
+ private static func placePhrase(for tokenID: String, lookup: SummaryLookup) -> String? {
+ guard let text = lookup.tokenTexts[tokenID] else { return nil }
+ return lookup.directoryPlaces.contains(tokenID) ? text : PlacePhrase.phrase(for: text)
}
/// 'a', 'a and b', 'a, b and c'.
@@ -137,19 +118,6 @@ enum EntryBuilder {
return items.dropLast().joined(separator: ", ") + " and " + items[items.count - 1]
}
- /// Adjacent text parts as one, so the draft is easy to compare and read.
- private static func merged(_ parts: [EntryDraft.Part]) -> [EntryDraft.Part] {
- var result: [EntryDraft.Part] = []
- for part in parts {
- if case .text(let text) = part, case .text(let previous)? = result.last {
- result[result.count - 1] = .text(previous + text)
- } else {
- result.append(part)
- }
- }
- return result
- }
-
private static func detail(for response: Response, answer: String) -> AnswerDetail {
AnswerDetail(questionID: response.questionID, prompt: response.prompt, answer: answer)
}
diff --git a/Reportage/Services/Narrative/NarrativePolisher.swift b/Reportage/Services/Narrative/NarrativePolisher.swift
@@ -1,246 +0,0 @@
-import Foundation
-import FoundationModels
-
-/// What became of an attempt to polish an entry.
-enum PolishOutcome: Equatable, Sendable {
- /// The polished entry, which passed the check. It may equal the draft.
- case polished(String)
- /// The model's output failed the check, so the draft stands.
- case rejected
- /// The model couldn't be used: Apple Intelligence is unavailable, or the
- /// request failed or was cancelled. Worth trying again later.
- case unavailable
-}
-
-/// Polishes entries with the on-device model: articles, casing and
-/// punctuation, nothing else.
-///
-/// The model never sees text that must stay exact. Fixed parts (people,
-/// quoted notes) and any word with letters outside ASCII (Japanese names,
-/// 'Lumière') are swapped for placeholders like `X1` first, because the
-/// model romanises or strips them whatever it's told. Its output is used
-/// only if it passes `NarrativeCheck`.
-actor NarrativePolisher {
- static let shared = NarrativePolisher()
-
- static let instructions =
- "Proofread the input. Correct spelling, grammar and punctuation only. Reply with the corrected text only."
-
- /// The version of the polishing pass. Raise it when the instructions or
- /// the check change, so stored narratives are written again.
- static let version: Int16 = 2
-
- /// Attempts per entry. The model leaves text unchanged about three times
- /// in ten even when it would fix it on another run, so an unchanged or
- /// failing result is tried again.
- static let attempts = 3
-
- private let model = SystemLanguageModel(guardrails: .permissiveContentTransformations)
-
- /// One request at a time, so scrolling quickly doesn't queue up dozens of
- /// concurrent generations.
- private var isBusy = false
- private var waiting: [CheckedContinuation<Void, Never>] = []
-
- func polish(_ draft: EntryDraft) async -> PolishOutcome {
- guard model.isAvailable else { return .unavailable }
- let protected = ProtectedText(draft)
- // Nothing the model could improve.
- guard protected.text.contains(where: \.isLetter) else { return .polished(draft.text) }
-
- await acquire()
- defer { release() }
- guard !Task.isCancelled else { return .unavailable }
-
- var passedUnchanged = false
- for _ in 1...Self.attempts {
- guard !Task.isCancelled else { return .unavailable }
- let output: String
- do {
- let session = LanguageModelSession(model: model, instructions: Self.instructions)
- output = try await session.respond(
- to: protected.text, options: GenerationOptions(maximumResponseTokens: 150)
- ).content.trimmingCharacters(in: .whitespacesAndNewlines)
- } catch {
- return .unavailable
- }
- let problem = await MainActor.run {
- NarrativeCheck.problem(in: output, comparedWith: protected)
- }
- guard problem == nil else { continue }
- if output != protected.text { return .polished(protected.restore(output)) }
- passedUnchanged = true
- }
- // Every attempt left the draft as it was, or failed the check.
- return passedUnchanged ? .polished(draft.text) : .rejected
- }
-
- private func acquire() async {
- if isBusy {
- await withCheckedContinuation { waiting.append($0) }
- } else {
- isBusy = true
- }
- }
-
- private func release() {
- if waiting.isEmpty {
- isBusy = false
- } else {
- waiting.removeFirst().resume()
- }
- }
-}
-
-/// A draft with its protected text swapped for placeholders.
-struct ProtectedText: Equatable, Sendable {
- var text: String
- /// Placeholders and the text each stands for, in order.
- var spans: [(placeholder: String, original: String)]
-
- static func == (lhs: ProtectedText, rhs: ProtectedText) -> Bool {
- lhs.text == rhs.text && lhs.spans.map(\.placeholder) == rhs.spans.map(\.placeholder)
- && lhs.spans.map(\.original) == rhs.spans.map(\.original)
- }
-
- init(_ draft: EntryDraft) {
- // Placeholders look like ordinary words, which the model leaves
- // alone; bracketed ones got rewritten. Avoid a letter the draft
- // already uses before a digit.
- let letter = ["X", "Q", "Z"].first { candidate in
- !draft.text.contains(try! Regex("\(candidate)[0-9]"))
- } ?? "X"
-
- var text = ""
- var spans: [(String, String)] = []
- func placeholder(for original: String) -> String {
- let placeholder = "\(letter)\(spans.count + 1)"
- spans.append((placeholder, original))
- return placeholder
- }
-
- for part in draft.parts {
- switch part {
- case .fixed(let original):
- text += placeholder(for: original)
- case .text(let string):
- var word = ""
- func flush() {
- if word.unicodeScalars.contains(where: { !$0.isASCII }) {
- text += placeholder(for: word)
- } else {
- text += word
- }
- word = ""
- }
- for character in string {
- if character.isLetter || character.isNumber || character == "'" || character == "’" {
- word.append(character)
- } else {
- flush()
- text.append(character)
- }
- }
- flush()
- }
- }
- self.text = text
- self.spans = spans
- }
-
- /// `output` with its placeholders swapped back. The highest numbers go
- /// first, so `X1` doesn't match the start of `X12`.
- func restore(_ output: String) -> String {
- spans.reversed().reduce(output) { result, span in
- result.replacingOccurrences(of: span.placeholder, with: span.original)
- }
- }
-}
-
-/// Decides whether a polished entry is faithful to its draft. The polish may
-/// change letter case, punctuation and connecting words, and nothing else.
-@MainActor
-enum NarrativeCheck {
- /// Words a correction may add or remove.
- static let connectingWords: Set<String> = ["the", "a", "an", "and", "with", "at", "of", "to", "in", "on"]
-
- /// Places that read naturally without 'the' once lowercased: 'at home'.
- static let barePlaces: Set<String> = [
- "home", "work", "school", "bed", "church", "college", "university", "hospital", "town",
- "class", "uni",
- ]
-
- /// Why `output` fails, or nil if it passes. Both texts still hold their
- /// placeholders.
- static func problem(in output: String, comparedWith draft: ProtectedText) -> String? {
- for span in draft.spans {
- let count = output.components(separatedBy: span.placeholder).count - 1
- if count != 1 { return "placeholder \(span.placeholder) appears \(count) times" }
- }
- if sentenceCount(output) != sentenceCount(draft.text) {
- return "sentences merged or split"
- }
-
- let inWords = words(draft.text)
- let outWords = words(output)
- // Protected text is a name or a quotation; 'with the Sam' or 'at the
- // 吉祥寺駅' would read wrongly.
- func article(before placeholder: String, in words: [String]) -> String? {
- guard let index = words.firstIndex(of: placeholder), index > 0 else { return nil }
- let previous = words[index - 1].lowercased()
- return ["the", "a", "an"].contains(previous) ? previous : nil
- }
- for span in draft.spans
- where article(before: span.placeholder, in: outWords) != article(before: span.placeholder, in: inWords) {
- return "article changed before \(span.placeholder)"
- }
- let inLower = Set(inWords.map { $0.lowercased() })
- let outLower = Set(outWords.map { $0.lowercased() })
- if let dropped = inLower.subtracting(outLower).subtracting(connectingWords).sorted().first {
- return "dropped '\(dropped)'"
- }
- if let added = outLower.subtracting(inLower).subtracting(connectingWords).sorted().first {
- return "added '\(added)'"
- }
-
- // A capital may only be removed from an ordinary word, and a place
- // lowercased that way needs an article unless it reads without one.
- let capitalised = Set(inWords.filter { $0.first?.isUppercase == true })
- for (index, word) in outWords.enumerated() where word.first?.isLowercase == true {
- let original = word.prefix(1).uppercased() + word.dropFirst()
- guard capitalised.contains(original), !inWords.contains(word) else { continue }
- guard InlineCasing.isDictionaryWord(word) else { return "lowercased '\(original)'" }
- let previous = index > 0 ? outWords[index - 1].lowercased() : ""
- if !["the", "a", "an"].contains(previous), !barePlaces.contains(word),
- ["at", "in", "on"].contains(previous)
- {
- return "'\(word)' without an article"
- }
- }
- return nil
- }
-
- static func sentenceCount(_ text: String) -> Int {
- text.matches(of: /[.!?](?=\s|$)/).count
- }
-
- /// Words and numbers, keeping decimals like '5.5' whole.
- static func words(_ text: String) -> [String] {
- var result: [String] = []
- var current = ""
- let characters = Array(text)
- for (index, character) in characters.enumerated() {
- let isDecimalPoint =
- character == "." && current.last?.isNumber == true
- && characters.indices.contains(index + 1) && characters[index + 1].isNumber
- if character.isLetter || character.isNumber || isDecimalPoint {
- current.append(character)
- } else if !current.isEmpty {
- result.append(current)
- current = ""
- }
- }
- if !current.isEmpty { result.append(current) }
- return result
- }
-}
diff --git a/Reportage/Services/Narrative/PlacePhrase.swift b/Reportage/Services/Narrative/PlacePhrase.swift
@@ -0,0 +1,46 @@
+import NaturalLanguage
+
+/// How a place the user named reads after 'at': 'at home', 'at the library',
+/// 'at Blue Bottle'. Names from a place directory don't come here; they're
+/// shown as written.
+@MainActor
+enum PlacePhrase {
+ /// Places that read without an article once lowercased: 'at home'.
+ static let barePlaces: Set<String> = [
+ "home", "work", "school", "bed", "church", "college", "university", "hospital", "town",
+ "class", "uni",
+ ]
+
+ private static var cache: [String: String] = [:]
+
+ static func phrase(for text: String) -> String {
+ if let cached = cache[text] { return cached }
+ let result = compute(text)
+ cache[text] = result
+ return result
+ }
+
+ /// Lowercased, with 'the' unless it reads without one, if the text is
+ /// ordinary words capitalised only at its start and isn't tagged as a
+ /// name. Anything else is taken to be a name and shown as written.
+ private static func compute(_ text: String) -> String {
+ let lower = text.lowercased()
+ if barePlaces.contains(lower) { return lower }
+
+ // 'Central Library' and 'IKEA' are names, and so is 'Mum's'. The
+ // spell checker passes scripts without case, such as Japanese.
+ let words = lower.split(separator: " ").map(String.init)
+ guard !words.isEmpty, text.dropFirst().allSatisfy({ !$0.isUppercase }),
+ words.allSatisfy({ word in
+ word.allSatisfy { $0.isLetter && $0.isCased } && InlineCasing.isDictionaryWord(word)
+ })
+ else { return text }
+
+ let tagger = NLTagger(tagSchemes: [.nameType])
+ tagger.string = text
+ let (tag, _) = tagger.tag(at: text.startIndex, unit: .word, scheme: .nameType)
+ if let tag, [.personalName, .placeName, .organizationName].contains(tag) { return text }
+
+ return ["the", "a", "an"].contains(words[0]) ? lower : "the " + lower
+ }
+}
diff --git a/Reportage/Views/Home/HomeView.swift b/Reportage/Views/Home/HomeView.swift
@@ -77,14 +77,10 @@ struct HomeView: View {
@Observable
final class ReportDescriber {
private(set) var lookup = SummaryLookup()
- /// Whether `lookup` has loaded. Until it has, drafts are missing their
- /// token names and aren't worth polishing.
- private(set) var isLoaded = false
func load(from store: ReportStore?) async {
guard let store, let lookup = try? await store.summaryLookup() else { return }
self.lookup = lookup
- isLoaded = true
}
func summary(of report: ReportEntity) -> ReportSummary {
@@ -97,17 +93,6 @@ final class ReportDescriber {
}
extension ReportEntity {
- /// The entry to show: the stored narrative if it was made from the
- /// current draft, otherwise the draft itself. A narrative from an older
- /// polishing pass is still shown until it's rewritten.
- func displayedEntry(for draft: EntryDraft?) -> String? {
- guard let draft else { return nil }
- if narrativeDraft == draft.text, let narrative {
- return narrative
- }
- return draft.text
- }
-
/// The calendar day of the report in the device's time zone, for grouping
/// the list. Grouping by each report's own zone would put reports out of
/// order around midnight when the user changes zones, which a sectioned
@@ -346,8 +331,6 @@ struct ReportRow: View {
@ObservedObject var report: ReportEntity
let describer: ReportDescriber
- @Environment(\.reportStore) private var store
- @State private var isWriting = false
/// Wide enough for '10:20' in the time's font, and scaled with it, so
/// the time never wraps and every row's column lines up.
@ScaledMetric(relativeTo: .title3) private var timeWidth: CGFloat = 60
@@ -364,46 +347,17 @@ struct ReportRow: View {
VStack(alignment: .leading, spacing: 6) {
ReportKindLabel(kind: kind, isLogged: isLogged)
ReportSummaryText(
- entry: entry(for: summary.draft),
- isWriting: isWriting,
+ entry: summary.entry,
details: summary.details,
context: summary.context,
isLogged: isLogged
)
}
}
- .task(id: describer.isLoaded ? summary.draft?.text : nil) {
- await polish(summary.draft)
- }
}
/// Whether the report was logged for later and has no answers yet.
private var isLogged: Bool { report.state == ReportState.passive.rawValue }
-
- private func entry(for draft: EntryDraft?) -> String? {
- report.displayedEntry(for: draft)
- }
-
- private func isCurrent(_ draft: EntryDraft) -> Bool {
- report.narrativeDraft == draft.text && report.narrativeVersion == NarrativePolisher.version
- }
-
- /// Polishes the entry the first time it's shown, and again whenever its
- /// draft changes. A rejected polish stores the draft, so it isn't retried
- /// every time the row appears; an unavailable model stores nothing.
- private func polish(_ draft: EntryDraft?) async {
- guard describer.isLoaded, let draft, !isCurrent(draft), let store, let id = report.id
- else { return }
- withAnimation { isWriting = true }
- defer { withAnimation { isWriting = false } }
- let narrative: String
- switch await NarrativePolisher.shared.polish(draft) {
- case .polished(let text): narrative = text
- case .rejected: narrative = draft.text
- case .unavailable: return
- }
- try? await store.saveNarrative(narrative, draft: draft.text, for: id)
- }
}
/// A report's local time. On a 12-hour clock the period goes beneath the
@@ -476,25 +430,8 @@ struct ReportKindLabel: View {
}
}
-/// Shown in place of an entry while its narrative is being written.
-struct WritingIndicator: View {
- var body: some View {
- HStack(spacing: 6) {
- ProgressView()
- .controlSize(.mini)
- Text("Writing narrative…", comment: "Shown while an entry is being polished")
- }
- .font(Theme.serif(.body).italic())
- .foregroundStyle(Theme.muted)
- .transition(.opacity)
- }
-}
-
struct ReportSummaryText: View {
let entry: String?
- /// Whether the entry is being rewritten. It's hidden but keeps its space,
- /// so the row doesn't change height, with a message over it.
- let isWriting: Bool
let details: [AnswerDetail]
let context: String?
/// A report logged for later has no answers, and doesn't say so.
@@ -509,13 +446,6 @@ struct ReportSummaryText: View {
Text(entry)
.font(Theme.serif(.body))
.foregroundStyle(Theme.ink)
- .opacity(isWriting ? 0 : 1)
- .accessibilityHidden(isWriting)
- .overlay(alignment: .topLeading) {
- if isWriting {
- WritingIndicator()
- }
- }
} else if details.isEmpty, !isLogged {
Text("No answers", comment: "Shown for a report whose questions were all skipped")
.font(Theme.serif(.body).italic())
diff --git a/Reportage/Views/Home/ReportSummary.swift b/Reportage/Views/Home/ReportSummary.swift
@@ -7,6 +7,9 @@ struct SummaryLookup: Equatable, Sendable {
/// Token texts by ID. A merged token's ID maps to the text of the token
/// it was merged into.
var tokenTexts: [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> = []
var questionKinds: [String: QuestionKind] = [:]
}
@@ -15,12 +18,12 @@ struct SummaryLookup: Equatable, Sendable {
/// line of context.
@MainActor
struct ReportSummary: Equatable {
- var draft: EntryDraft?
+ var entry: String?
var details: [AnswerDetail]
var context: String?
init(responses: [Response], context: Context, lookup: SummaryLookup) {
- (draft, details) = EntryBuilder.build(responses: responses, lookup: lookup)
+ (entry, details) = EntryBuilder.build(responses: responses, lookup: lookup)
self.context = Self.contextLine(context)
}
@@ -68,6 +71,13 @@ extension ReportStore {
current = next
}
lookup.tokenTexts[token.id] = current.text
+ // Imported Foursquare venues and some MapKit places have no
+ // directory names, so their text is the directory's.
+ if let place = current.place, place.externalID != nil,
+ place.names.isEmpty || place.names.contains(where: { $0.text == current.text })
+ {
+ lookup.directoryPlaces.insert(token.id)
+ }
}
for entity in try context.fetch(QuestionEntity.fetchRequest()) {
let question = try entity.question()
@@ -77,23 +87,3 @@ extension ReportStore {
}
}
}
-
-extension ReportStore {
- /// Stores the polished entry for a report, with the draft it came from
- /// and the version of the polishing pass. The entry stays valid until the
- /// report's draft changes, for example when an answer is edited or a
- /// token renamed, or the polishing pass changes.
- func saveNarrative(_ narrative: String, draft: String, for reportID: UUID) async throws {
- let context = persistence.newBackgroundContext()
- try await context.perform {
- let request = ReportEntity.fetchRequest()
- request.predicate = NSPredicate(format: "id == %@", reportID as CVarArg)
- request.fetchLimit = 1
- guard let entity = try context.fetch(request).first else { return }
- entity.narrative = narrative
- entity.narrativeDraft = draft
- entity.narrativeVersion = NarrativePolisher.version
- try context.save()
- }
- }
-}
diff --git a/Tests/Unit/ReportSummaryTests.swift b/Tests/Unit/ReportSummaryTests.swift
@@ -10,8 +10,10 @@ struct EntryBuilderTests {
private static let lookup = SummaryLookup(
tokenTexts: [
"read": "Reading", "coffee": "Drinking coffee", "netflix": "Watching Netflix",
- "library": "Library", "sam": "Sam", "kai": "Kai", "tanaka": "田中さん",
+ "library": "Library", "home": "Home", "bottle": "Blue bottle", "sam": "Sam", "kai": "Kai",
+ "tanaka": "田中さん",
],
+ directoryPlaces: ["bottle"],
questionKinds: [
"activity": .tokens, "people": .people, "place": .location, "custom": .yesNo,
]
@@ -21,30 +23,41 @@ struct EntryBuilderTests {
Response(questionID: questionID, prompt: "Prompt \(questionID)?", value: value)
}
- private static func build(_ responses: [Response]) -> (draft: EntryDraft?, details: [AnswerDetail]) {
+ private static func build(_ responses: [Response]) -> (entry: String?, details: [AnswerDetail]) {
EntryBuilder.build(responses: responses, lookup: lookup)
}
@Test("Activities, place and people make one clause, with later activities lowercased")
func mainClause() {
- let (draft, details) = Self.build([
+ let (entry, details) = Self.build([
Self.response("activity", .tokens(["read", "coffee", "netflix"])),
Self.response("place", .place(PlaceAnswer(tokenID: "library"))),
Self.response("people", .tokens(["sam", "kai"])),
])
- #expect(draft?.text == "Reading, drinking coffee and watching Netflix at Library, with Sam and Kai.")
+ #expect(entry == "Reading, drinking coffee and watching Netflix at the library, with Sam and Kai.")
#expect(details.isEmpty)
}
- @Test("People are fixed parts, so polishing never sees them")
- func fixedPeople() {
- let draft = Self.build([Self.response("people", .tokens(["sam", "tanaka"]))]).draft
- #expect(draft?.parts == [.text("With "), .fixed("Sam"), .text(" and "), .fixed("田中さん"), .text(".")])
+ @Test("People are shown as written")
+ func people() {
+ let entry = Self.build([Self.response("people", .tokens(["sam", "tanaka"]))]).entry
+ #expect(entry == "With Sam and 田中さん.")
}
- @Test("Built-in rules phrase each kind of answer, in survey order")
+ @Test("A place from a directory is shown as written, and others are phrased")
+ func places() {
+ let home = Self.build([Self.response("place", .place(PlaceAnswer(tokenID: "home")))]).entry
+ #expect(home == "At home.")
+ let bottle = Self.build([
+ Self.response("activity", .tokens(["read"])),
+ Self.response("place", .place(PlaceAnswer(tokenID: "bottle"))),
+ ]).entry
+ #expect(bottle == "Reading at Blue bottle.")
+ }
+
+ @Test("Built-in rules phrase each kind of answer")
func builtInRules() {
- let (draft, _) = Self.build([
+ let (entry, _) = Self.build([
Self.response("reportage-default-working", .options([ResponseValue.noOption])),
Self.response("activity", .tokens(["read"])),
Self.response("reportage-default-mood", .options(["Great"])),
@@ -52,107 +65,57 @@ struct EntryBuilderTests {
Self.response("reportage-default-learned", .text("The neighbours are nice people.")),
])
#expect(
- draft?.text
- == "Not working. Reading. Feeling great. 1 coffee. Learned: 'The neighbours are nice people.'")
+ entry
+ == "Reading. Not working. Feeling great. 1 coffee. Learned: 'The neighbours are nice people.'")
+ }
+
+ @Test("Sleep opens the entry, then the main clause, then the rest in survey order")
+ func order() {
+ let (entry, _) = Self.build([
+ Self.response("reportage-default-working", .options([ResponseValue.yesOption])),
+ Self.response("activity", .tokens(["read"])),
+ Self.response("place", .place(PlaceAnswer(tokenID: "library"))),
+ Self.response("reportage-default-mood", .options(["Good"])),
+ Self.response("reportage-default-sleep-quality", .options(["Well"])),
+ ])
+ #expect(entry == "Slept well. Reading at the library. Working. Feeling good.")
}
@Test("Reporter's built-in questions read like the defaults that ask the same things")
func reporterRules() {
- let (draft, details) = Self.build([
+ let (entry, details) = Self.build([
Self.response("default-question-1", .options(["Poorly"])),
Self.response("default-question-2", .options([ResponseValue.yesOption])),
Self.response("default-question-6", .number(2)),
])
- #expect(draft?.text == "Slept poorly. Working. 2 coffees.")
+ #expect(entry == "Slept poorly. Working. 2 coffees.")
#expect(details.isEmpty)
}
@Test("Counts use the plural noun for anything but one")
func counts() {
- let draft = Self.build([Self.response("reportage-default-coffee", .number(2))]).draft
- #expect(draft?.text == "2 coffees.")
+ let entry = Self.build([Self.response("reportage-default-coffee", .number(2))]).entry
+ #expect(entry == "2 coffees.")
}
@Test("A note without final punctuation gets a full stop after the quotation")
func unendedNote() {
- let draft = Self.build([Self.response("reportage-default-learned", .text("Tide tables"))]).draft
- #expect(draft?.parts == [.text("Learned: "), .fixed("'Tide tables'"), .text(".")])
+ let entry = Self.build([Self.response("reportage-default-learned", .text("Tide tables"))]).entry
+ #expect(entry == "Learned: 'Tide tables'.")
}
@Test("Answers without a rule are listed as question and answer")
func details() {
- let (draft, details) = Self.build([
+ let (entry, details) = Self.build([
Self.response("custom", .options([ResponseValue.yesOption])),
Self.response("unknown", .number(7)),
Self.response("activity", nil),
])
- #expect(draft == nil)
+ #expect(entry == nil)
#expect(details.map(\.answer) == ["Yes", "7"])
}
}
-@MainActor
-@Suite("NarrativeCheck")
-struct NarrativeCheckTests {
-
- private static let draft = EntryDraft(parts: [
- .text("Reading at Library, with "), .fixed("Sam"), .text(". Learned: "),
- .fixed("'How tides work.'"),
- ])
-
- @Test("Fixed parts and non-ASCII words become placeholders, and come back")
- func protection() {
- let protected = ProtectedText(
- EntryDraft(parts: [.text("Lunch at Café Lumière and すき家, with "), .fixed("Kai"), .text(".")]))
- #expect(protected.text == "Lunch at X1 X2 and X3, with X4.")
- #expect(protected.spans.map(\.original) == ["Café", "Lumière", "すき家", "Kai"])
- #expect(protected.restore(protected.text) == "Lunch at Café Lumière and すき家, with Kai.")
- }
-
- @Test("Restoring swaps higher numbers first")
- func restoreOrder() {
- let parts = (1...12).flatMap { index -> [EntryDraft.Part] in [.fixed("P\(index)"), .text(" ")] }
- let protected = ProtectedText(EntryDraft(parts: parts))
- #expect(protected.restore("X12 X1") == "P12 P1")
- }
-
- @Test("A light correction passes")
- func passes() {
- let protected = ProtectedText(Self.draft)
- #expect(NarrativeCheck.problem(in: "Reading at the library, with X1. Learned: X2", comparedWith: protected) == nil)
- #expect(NarrativeCheck.problem(in: protected.text, comparedWith: protected) == nil)
- }
-
- @Test(
- "Unfaithful corrections fail",
- arguments: [
- ("Reading at the library, with X1.", "placeholder"),
- ("Reading at the library, with X1. Learned: X2 X2", "placeholder"),
- ("Reading at the library, with X1, learned: X2", "sentences"),
- ("Reading quietly at the library, with X1. Learned: X2", "added"),
- ("At the library, with X1. Learned: X2", "dropped"),
- ("Reading at library, with X1. Learned: X2", "article"),
- ("Reading at the library, with the X1. Learned: X2", "article"),
- ]
- )
- func fails(output: String, reason: String) {
- let problem = NarrativeCheck.problem(in: output, comparedWith: ProtectedText(Self.draft))
- #expect(problem?.contains(reason) == true, "\(problem ?? "passed")")
- }
-
- @Test("A capital may only be removed from an ordinary word")
- func lowercasing() {
- let protected = ProtectedText(EntryDraft(parts: [.text("Shopping at Uniqlo. At Home.")]))
- #expect(NarrativeCheck.problem(in: "Shopping at uniqlo. At Home.", comparedWith: protected) != nil)
- #expect(NarrativeCheck.problem(in: "Shopping at Uniqlo. At home.", comparedWith: protected) == nil)
- }
-
- @Test("Decimals count as one word")
- func decimals() {
- #expect(NarrativeCheck.words("Slept 5.5 hours.") == ["Slept", "5.5", "hours"])
- }
-}
-
@MainActor
@Suite("InlineCasing")
struct InlineCasingTests {
@@ -174,6 +137,32 @@ struct InlineCasingTests {
}
}
+@MainActor
+@Suite("PlacePhrase")
+struct PlacePhraseTests {
+
+ @Test(
+ "Ordinary places are lowercased, with 'the' unless they read without it, and names are kept",
+ arguments: [
+ ("Home", "home"),
+ ("Work", "work"),
+ ("Library", "the library"),
+ ("Gym", "the gym"),
+ ("Coffee shop", "the coffee shop"),
+ ("The beach", "the beach"),
+ ("Central Library", "Central Library"),
+ ("IKEA", "IKEA"),
+ ("Mum's", "Mum's"),
+ ("Gate 3", "Gate 3"),
+ ("Kichijōji", "Kichijōji"),
+ ("吉祥寺駅", "吉祥寺駅"),
+ ]
+ )
+ func phrase(text: String, expected: String) {
+ #expect(PlacePhrase.phrase(for: text) == expected)
+ }
+}
+
@MainActor
@Suite("ReportSummary")
struct ReportSummaryTests {