← All repositories

reportage

A life-logging app for iPhone

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


commit 92774323a2c928807f1f3821c7bf9661b0bc711a
parent de2ce6e35c8faaaaf9fb6fa3d2ea99804c7dad9d
Author: Michael Camilleri <[email protected]>
Date:   Sat, 17 Oct 2026 09:53:56 +0900

Add random prompts with notification actions

This commit sends prompts at random times within the user's waking
hours. Each day's window is split into equal slots with one time drawn
in each, keeping a minimum gap, so prompts neither cluster nor leave
long silences. The draws are seeded from a per-install secret and the
date, so working out a day's times again gives the same answer, and the
scheduler only adds and removes the difference between its plan and
what is pending. It keeps about a week of prompts pending, within iOS's
limit of 64, and replaces the last with a reminder to open the app, so
a long stretch away ends with a nudge rather than silence. It tops up
on launch, on returning to the foreground, after a notification action,
after saving a report and from background refresh. Prompts fire at the
same local time wherever the phone is.

A prompt offers 'Log for Later', which saves an instant report without
opening the app, and 'Snooze', which repeats it after a set time.
Tapping it opens the survey for the moment it came. Reports made from a
prompt record the notification as their trigger and when the prompt
first fired, even after a snooze. A tapped prompt waits for a survey
already open to close.

Settings moves into a tab beside the Timeline, set in the timeline's
typography. It turns prompts on, sets how many come each day, the
waking hours (separately for weekends if wanted), the minimum gap and
the snooze length. Turning prompts on asks for notifications, with the
badge that counts instant reports, then explains why Log for Later
wants location set to 'Always' before asking for it. Prompts default to
four a day between 9:00 and 22:00, 30 minutes apart, and stay in
UserDefaults until sync arrives.

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

Diffstat

MNotes/Design.md | 58++++++++++++++++++++++++++++++++++++++++------------------
MReportage.xcodeproj/project.pbxproj | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
AReportage/AppDelegate.swift | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MReportage/Info.plist | 8++++++++
MReportage/ReportageApp.swift | 31++++++++++++++++++++++++++-----
AReportage/Services/Prompts/PromptNotification.swift | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AReportage/Services/Prompts/PromptSchedule.swift | 123+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AReportage/Services/Prompts/PromptScheduler.swift | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AReportage/Services/Prompts/PromptSettings.swift | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MReportage/Views/Home/HomeView.swift | 12++++++++++++
AReportage/Views/RootView.swift | 28++++++++++++++++++++++++++++
AReportage/Views/Settings/SettingsView.swift | 262+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MReportage/Views/Survey/SurveyModel.swift | 20++++++++++++++++----
MReportage/Views/Survey/SurveyView.swift | 6++++++
ATests/Unit/PromptScheduleTests.swift | 150+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ATests/Unit/PromptSchedulerTests.swift | 219+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MTests/Unit/SurveyModelTests.swift | 13+++++++++++++
Mproject.yml | 4++++

18 files changed, 1325 insertions(+), 27 deletions(-)

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

@@ -81,6 +81,10 @@ The look is called Almanac: ink on paper, like a printed journal.
   prompts, answers and token names. SF for everything around it. Labels such
   as dates and report kinds use small spaced capitals. All sizes are Dynamic
   Type styles.
+- **Tabs:** Timeline and Settings, with Visualisations joining them in
+  Phase 7. The timeline keeps its serif 'Reportage' title, beside the quick
+  log and new report buttons. A tapped prompt switches to the timeline to
+  open its survey.
 - **Home screen:** reports grouped under day headings, newest first. Each
   shows its own local time (the period beneath on a 12-hour clock, so times
   fit one column), its kind, its entry, any answers the entry doesn't cover,
@@ -458,19 +462,30 @@ Other options looked at:
 
 ### Generating times
 
-Settings: prompts per day `n`, a waking window (start and end time, which can
-differ on weekends), and a minimum gap between prompts (default 30 minutes).
-
-Times are **stratified random**. The waking window is split into `n` equal
-slots and one time is drawn uniformly within each slot, then adjusted to
-respect the minimum gap. Unlike drawing `n` times uniformly from the whole day,
-this avoids clusters and long silences, while still keeping each prompt
-unpredictable.
-
-Draws are **deterministic per day**. The random generator is seeded from a
-per-install secret plus the calendar date. Rescheduling is then idempotent:
-re-running the scheduler at any point produces the same times, so pending
-notifications don't get reshuffled every time the app launches.
+Settings (`PromptSettings`): prompts on or off, prompts per day `n` (default
+4), a waking window (default 9:00 to 22:00, optionally different on weekends,
+and able to run past midnight), a minimum gap between prompts (default 30
+minutes) and the snooze length (default 15 minutes). Prompts are off until the
+user turns them on in Settings. The settings live in `UserDefaults` until
+Phase 4 moves them into the `Config` zone.
+
+Times are **stratified random** (`PromptSchedule`). The waking window is split
+into `n` equal slots with one time drawn uniformly in each. Unlike drawing `n`
+times uniformly from the whole day, this avoids clusters and long silences,
+while still keeping each prompt unpredictable. To keep the minimum gap, the
+slots share the window less the `n - 1` gaps, and each later time is pushed on
+by one more gap. A gap too large for the window shrinks to fit.
+
+Draws are **deterministic per day**. The random generator (SplitMix64, written
+out so an OS update can't change it) is seeded from a per-install secret plus
+the calendar date. Rescheduling is then idempotent: re-running the scheduler
+at any point produces the same times, so pending notifications don't get
+reshuffled every time the app launches.
+
+Prompts use calendar triggers without a time zone, so they fire at the same
+local time wherever the phone is. Each notification's identifier is its kind
+and local fire time (`prompt.20261014-090507`), so the scheduler only adds and
+removes the difference between the plan and what's pending.
 
 ### The 64-notification limit
 
@@ -481,7 +496,7 @@ for snoozes) and tops it up whenever the app gets execution time:
 - launch and moving to the foreground
 - handling a notification action (actions launch the app in the background)
 - saving a report
-- a `BGAppRefreshTask`
+- a `BGAppRefreshTask`, requested about every six hours while prompts are on
 
 The last notification in the horizon is replaced by a "keep the prompts coming"
 reminder, so a long stretch without opening the app ends with a nudge instead
@@ -502,12 +517,19 @@ Category `prompt`:
   prompt in 15 minutes (configurable). The snoozed prompt keeps the original
   `promptedAt`.
 - **Tapping the notification** opens the survey with `date` set to the fire
-  time.
+  time (for a snoozed prompt, when the repeat came) and `promptedAt` set to
+  when the prompt first fired. If a survey or Settings is already open, it
+  waits until that closes.
 
 Location for background actions requires "Always" authorisation. Without it,
 passive reports logged from a notification get no location. The app asks for
 "When In Use" first and explains the trade-off before asking to upgrade.
 
+Turning prompts on asks for notification permission (alert, sound and badge)
+and, once it's granted, explains why Log for Later wants 'Always' location
+before asking for it. Whether a capture started from a background action gets
+a fix with 'Always' needs checking on a device.
+
 ## Passive Reports and the Watch
 
 A passive report records "this moment" with its context and nothing else. It
@@ -786,9 +808,9 @@ default); when included, each is the original JSON text as a string.
 
 - **Missed prompts.** Should prompts that were delivered but never answered be
   recorded? Doing so costs little and makes the sampling honest for later
-  analysis. Reporter didn't record them.
-- **Defaults.** Default number of prompts per day and the minimum gap. The
-  archive averages about 3.4 notification-triggered reports per day.
+  analysis. Reporter didn't record them. Deferred past Phase 3: the plan is
+  deterministic, so the prompts sent on a day can be worked out again from the
+  settings in force that day, if those are kept.
 - **"Always" location.** Settled: requested as an upgrade when prompts are
   turned on (see [Location](#location)).
 - **Backfills.** Weather from August 2021 onwards and Health from 2014 onwards.

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

@@ -11,12 +11,14 @@
 		047D3797389624E8B4AF44B4 /* ReportageExporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD433A98973E8B13E42230A1 /* ReportageExporter.swift */; };
 		06415D2A2EDA6E92ECAC96FA /* Report.swift in Sources */ = {isa = PBXBuildFile; fileRef = B03734F91822E7F161432075 /* Report.swift */; };
 		0F052B8A2C73437F57E927E7 /* ReportStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84E55C093BA98D8700F406AE /* ReportStoreTests.swift */; };
+		16D2FB106A2C588BAAB3EB06 /* PromptSchedulerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2425CB4D9B12D422467F6FD7 /* PromptSchedulerTests.swift */; };
 		22EA393B887791E20B6FE625 /* PlacePickerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B6C4141A26EED99B1F03FBE /* PlacePickerTests.swift */; };
 		25BC9F95DC40E31B1E4C6FBA /* Token.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3BE62142CCC4A791F05163A /* Token.swift */; };
 		28D2CDAAB0777233D4465A83 /* ReporterArchiveTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 487F88C880B5DE69964C6A37 /* ReporterArchiveTests.swift */; };
 		2EE68329C383FA1C5295ACA9 /* PlaceAnswerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9856D1F8123B9CAD7D39071D /* PlaceAnswerView.swift */; };
 		3175E324135E1CF5A73683D1 /* ReporterTimeZones.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7196D553D769071DB876B606 /* ReporterTimeZones.swift */; };
 		3244B8439B5E4F79FF84C156 /* JSONSlicer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 643C730A99F0B7BA8C1F8A8E /* JSONSlicer.swift */; };
+		35D02EAE3D95DB5CCEE8A82E /* PromptScheduleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC27A2AF600780976CFA295C /* PromptScheduleTests.swift */; };
 		36A35625365E87B39CB88194 /* ReporterImporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48D44876FDE4293FA0460595 /* ReporterImporter.swift */; };
 		3FBE5C53D33EF78752BEACE0 /* ReporterImportVerifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3ED0CAE575381DCB86FB8EE9 /* ReporterImportVerifier.swift */; };
 		406D536D7764B3FEB140CAA0 /* EntityMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BE7248E73E2859EFF232170 /* EntityMapping.swift */; };
@@ -24,8 +26,11 @@
 		540CA20A213B0446B6F71885 /* Vocabulary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74FF461F6E8A0241C18357B2 /* Vocabulary.swift */; };
 		633A94E029055EA5D50D00AC /* PlaceRanking.swift in Sources */ = {isa = PBXBuildFile; fileRef = 76FFC5FE874467974DD6BFA0 /* PlaceRanking.swift */; };
 		68DDAB8BB2E679EB7EC1E9C1 /* ReporterImportPlan.swift in Sources */ = {isa = PBXBuildFile; fileRef = 798E1DE82BD53EC5BEBA76B7 /* ReporterImportPlan.swift */; };
+		690A6B50550B9CE4B954CC0C /* PromptScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C4665B55B0307E899595C1D /* PromptScheduler.swift */; };
 		6E21E729F89178EBD019980E /* InlineCasing.swift in Sources */ = {isa = PBXBuildFile; fileRef = A00E589A8387E7A1E348503C /* InlineCasing.swift */; };
 		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 */; };
 		7ACDA81EC3D7811F891CA029 /* ReportSummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1BBAB5AD6266B8F6E3507AE3 /* ReportSummary.swift */; };
 		81B485BD03549DE6E7AA94A7 /* AppBadge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CE5E7D863F9BD3DF363AA9A /* AppBadge.swift */; };
@@ -40,10 +45,12 @@
 		97BC8348B7F48AF0473691FC /* ReportStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28AD66BC8ED4AEABF6640108 /* ReportStore.swift */; };
 		9EF3CB3707CD6B5AFFD3B767 /* ReporterArchive.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1C5F0F722477CDA949F018 /* ReporterArchive.swift */; };
 		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 */; };
 		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 */; };
+		C87E1C0465FE7B2917F92846 /* PromptSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB87A3E922FA7AE98B93DF1E /* PromptSettings.swift */; };
 		C8E02DEA2119E61D31667FFE /* ReporterImportPlanTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FD562C0C92C1D59881C771E /* ReporterImportPlanTests.swift */; };
 		CFB0A1F9494F1D8919F48CC5 /* ContextCaptureTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3157F7D5E4289B349E92402 /* ContextCaptureTests.swift */; };
 		D0497C9835A2502936591DC1 /* DisplayRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E609FFCB918B4EF9BFCC018 /* DisplayRule.swift */; };
@@ -56,12 +63,14 @@
 		D9A8839569734F5CEAC43A44 /* TokenAnswer.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF998798373C9CCAD65999B3 /* TokenAnswer.swift */; };
 		DF632654B427EE32C44C6F78 /* Context.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F200EBD30BC12D2313E6C6F /* Context.swift */; };
 		E0137FEEBF13F5D14C07656F /* ReportageExport.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7F1ECC4B803EFFD88FFF52B /* ReportageExport.swift */; };
+		E64BB44903A15E99126E73E5 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 81BA515BEA1B0B68CE0D1326 /* SettingsView.swift */; };
 		E68EF6274FD2F6D54D49F5BD /* ReporterImporterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 917C4579342FAC42F6C616FC /* ReporterImporterTests.swift */; };
 		E8CC84072697836F87D8A00D /* TestHelpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20C574BC234EDBD4056E2B7 /* TestHelpers.swift */; };
 		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 */; };
+		FD41318BC8EEAF3208CD59B7 /* RootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A70B6E5B7C07D2CE13E9E771 /* RootView.swift */; };
 /* End PBXBuildFile section */
 
 /* Begin PBXContainerItemProxy section */
@@ -80,7 +89,9 @@
 		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>"; };
 		1F200EBD30BC12D2313E6C6F /* Context.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Context.swift; sourceTree = "<group>"; };
+		2425CB4D9B12D422467F6FD7 /* PromptSchedulerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptSchedulerTests.swift; sourceTree = "<group>"; };
 		24A77AE6DE479403D1D4C9CF /* QuestionPage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuestionPage.swift; sourceTree = "<group>"; };
 		28AD66BC8ED4AEABF6640108 /* ReportStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportStore.swift; sourceTree = "<group>"; };
 		30FFB17809ADA84F1036E2A7 /* LegacyBlob.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LegacyBlob.swift; sourceTree = "<group>"; };
@@ -99,6 +110,7 @@
 		6024EA06BE24A189D4F7D0E4 /* Response.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Response.swift; sourceTree = "<group>"; };
 		60457C07EF790C11D6C47EDF /* reporter-fixture.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "reporter-fixture.json"; sourceTree = "<group>"; };
 		61C0B5BB02ECDBE84F5F73FA /* PersistenceController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PersistenceController.swift; sourceTree = "<group>"; };
+		633FE6CD8111A433CA9BE7EC /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
 		643C730A99F0B7BA8C1F8A8E /* JSONSlicer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONSlicer.swift; sourceTree = "<group>"; };
 		6E382405EE9DBEC8EE616C1D /* SurveyModelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SurveyModelTests.swift; sourceTree = "<group>"; };
 		7196D553D769071DB876B606 /* ReporterTimeZones.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterTimeZones.swift; sourceTree = "<group>"; };
@@ -109,8 +121,10 @@
 		7CE5E7D863F9BD3DF363AA9A /* AppBadge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppBadge.swift; sourceTree = "<group>"; };
 		7DB6FF151DCEBC3913131834 /* ReportageExportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageExportTests.swift; sourceTree = "<group>"; };
 		7FD562C0C92C1D59881C771E /* ReporterImportPlanTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImportPlanTests.swift; sourceTree = "<group>"; };
+		81BA515BEA1B0B68CE0D1326 /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };
 		844ABAD88442C143BA239374 /* SurveyModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SurveyModel.swift; sourceTree = "<group>"; };
 		84E55C093BA98D8700F406AE /* ReportStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportStoreTests.swift; sourceTree = "<group>"; };
+		86474CD2E8EC300CD6B37BB2 /* PromptSchedule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptSchedule.swift; sourceTree = "<group>"; };
 		878CE0FF7A2598F4197E8E61 /* Environment.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Environment.swift; sourceTree = "<group>"; };
 		8E609FFCB918B4EF9BFCC018 /* DisplayRule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DisplayRule.swift; sourceTree = "<group>"; };
 		917C4579342FAC42F6C616FC /* ReporterImporterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImporterTests.swift; sourceTree = "<group>"; };
@@ -121,17 +135,21 @@
 		A20C574BC234EDBD4056E2B7 /* TestHelpers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestHelpers.swift; sourceTree = "<group>"; };
 		A3157F7D5E4289B349E92402 /* ContextCaptureTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContextCaptureTests.swift; sourceTree = "<group>"; };
 		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>"; };
+		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>"; };
 		BBBE80E95676BAEB53CE80E0 /* PlaceDirectory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlaceDirectory.swift; sourceTree = "<group>"; };
+		BC27A2AF600780976CFA295C /* PromptScheduleTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptScheduleTests.swift; sourceTree = "<group>"; };
 		BF998798373C9CCAD65999B3 /* TokenAnswer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TokenAnswer.swift; sourceTree = "<group>"; };
 		C3C7B68925A281EF806BB9B8 /* Theme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Theme.swift; sourceTree = "<group>"; };
 		CC1C5F0F722477CDA949F018 /* ReporterArchive.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterArchive.swift; sourceTree = "<group>"; };
 		CD433A98973E8B13E42230A1 /* ReportageExporter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageExporter.swift; sourceTree = "<group>"; };
 		D03D0770BA2E26D7E4A7DECC /* ReportageModel.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = ReportageModel.xcdatamodel; sourceTree = "<group>"; };
 		D4AFF3D49ED9E8AC69390925 /* JSONSlicerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONSlicerTests.swift; sourceTree = "<group>"; };
+		DB87A3E922FA7AE98B93DF1E /* PromptSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptSettings.swift; sourceTree = "<group>"; };
 		E21F898FF60FC3A6AFCA06E9 /* Reportage Unit Tests.xctest */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.cfbundle; path = "Reportage Unit Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
 		E7F1ECC4B803EFFD88FFF52B /* ReportageExport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageExport.swift; sourceTree = "<group>"; };
 /* End PBXFileReference section */
@@ -146,6 +164,17 @@
 			path = Home;
 			sourceTree = "<group>";
 		};
+		0CECB181B29E96DE98FDF293 /* Prompts */ = {
+			isa = PBXGroup;
+			children = (
+				A9C326FBA3249ED86912FBF5 /* PromptNotification.swift */,
+				86474CD2E8EC300CD6B37BB2 /* PromptSchedule.swift */,
+				1C4665B55B0307E899595C1D /* PromptScheduler.swift */,
+				DB87A3E922FA7AE98B93DF1E /* PromptSettings.swift */,
+			);
+			path = Prompts;
+			sourceTree = "<group>";
+		};
 		23711442404F0476532D0FC2 /* Survey */ = {
 			isa = PBXGroup;
 			children = (
@@ -170,6 +199,7 @@
 		4C708676FBAD641AD92F8CA0 /* Reportage */ = {
 			isa = PBXGroup;
 			children = (
+				633FE6CD8111A433CA9BE7EC /* AppDelegate.swift */,
 				0B35602A218BE4EE399835FD /* Info.plist */,
 				383FF2C73A8FBAA2AB13D653 /* ReportageApp.swift */,
 				60B58F5030E4A690025C51F5 /* Services */,
@@ -226,6 +256,7 @@
 				AD85758A0521ED681067B90F /* Export */,
 				96D6D46E008E39350B203328 /* Narrative */,
 				580063E6A7AE05D5C6C16830 /* Places */,
+				0CECB181B29E96DE98FDF293 /* Prompts */,
 				F7B8E02FFC282DCD163E25FE /* ReporterImport */,
 			);
 			path = Services;
@@ -248,6 +279,8 @@
 				D4AFF3D49ED9E8AC69390925 /* JSONSlicerTests.swift */,
 				5C606A9B0EF8D84950B9681B /* ModelCodingTests.swift */,
 				1B6C4141A26EED99B1F03FBE /* PlacePickerTests.swift */,
+				2425CB4D9B12D422467F6FD7 /* PromptSchedulerTests.swift */,
+				BC27A2AF600780976CFA295C /* PromptScheduleTests.swift */,
 				3DF3B490F336FCE1E1E3DDBA /* RealExportVerificationTests.swift */,
 				7DB6FF151DCEBC3913131834 /* ReportageExportTests.swift */,
 				487F88C880B5DE69964C6A37 /* ReporterArchiveTests.swift */,
@@ -302,6 +335,14 @@
 			name = Products;
 			sourceTree = "<group>";
 		};
+		B74082E720FBA1EF05FE11E4 /* Settings */ = {
+			isa = PBXGroup;
+			children = (
+				81BA515BEA1B0B68CE0D1326 /* SettingsView.swift */,
+			);
+			path = Settings;
+			sourceTree = "<group>";
+		};
 		B9570B011A58C1B1BF00FB73 /* Persistence */ = {
 			isa = PBXGroup;
 			children = (
@@ -320,7 +361,9 @@
 			children = (
 				878CE0FF7A2598F4197E8E61 /* Environment.swift */,
 				5591E042089D038B59B26E9F /* ReportKind+Title.swift */,
+				A70B6E5B7C07D2CE13E9E771 /* RootView.swift */,
 				01DE4634BAAD579B60FBA5ED /* Home */,
+				B74082E720FBA1EF05FE11E4 /* Settings */,
 				23711442404F0476532D0FC2 /* Survey */,
 				28F1EEFBA9AE0C97C4ACEF89 /* Theme */,
 			);
@@ -446,6 +489,8 @@
 				8ADBA81D5D9ECCDCD5BDA742 /* JSONSlicerTests.swift in Sources */,
 				964408E4D25713F627048C77 /* ModelCodingTests.swift in Sources */,
 				22EA393B887791E20B6FE625 /* PlacePickerTests.swift in Sources */,
+				35D02EAE3D95DB5CCEE8A82E /* PromptScheduleTests.swift in Sources */,
+				16D2FB106A2C588BAAB3EB06 /* PromptSchedulerTests.swift in Sources */,
 				4A0DEFB7E69A9FC5EAAD99D4 /* RealExportVerificationTests.swift in Sources */,
 				0F052B8A2C73437F57E927E7 /* ReportStoreTests.swift in Sources */,
 				D3FF67FB406DCCB78DF9D61A /* ReportSummaryTests.swift in Sources */,
@@ -463,6 +508,7 @@
 			buildActionMask = 2147483647;
 			files = (
 				81B485BD03549DE6E7AA94A7 /* AppBadge.swift in Sources */,
+				B454D3067CD611AE55E30A1D /* AppDelegate.swift in Sources */,
 				DF632654B427EE32C44C6F78 /* Context.swift in Sources */,
 				D487802C53EA0E96698BE151 /* ContextCapture.swift in Sources */,
 				BD8D81CBF8C3DE544BB7540C /* DefaultQuestions.swift in Sources */,
@@ -481,6 +527,10 @@
 				D3C3046B927DB98443E005C8 /* PlaceDirectory.swift in Sources */,
 				D74CE3807E9593D470DADAA8 /* PlacePicker.swift in Sources */,
 				633A94E029055EA5D50D00AC /* PlaceRanking.swift in Sources */,
+				7488B9EE97D419E2B6B9FCEA /* PromptNotification.swift in Sources */,
+				7676E79864C7C26CB9EA4B10 /* PromptSchedule.swift in Sources */,
+				690A6B50550B9CE4B954CC0C /* PromptScheduler.swift in Sources */,
+				C87E1C0465FE7B2917F92846 /* PromptSettings.swift in Sources */,
 				F38A1CCFAF016AB982EAB791 /* Question.swift in Sources */,
 				85A36A88AB170F0EAC0DAC03 /* QuestionPage.swift in Sources */,
 				06415D2A2EDA6E92ECAC96FA /* Report.swift in Sources */,
@@ -497,6 +547,8 @@
 				36A35625365E87B39CB88194 /* ReporterImporter.swift in Sources */,
 				3175E324135E1CF5A73683D1 /* ReporterTimeZones.swift in Sources */,
 				8AF60BB296144ED9D11EA053 /* Response.swift in Sources */,
+				FD41318BC8EEAF3208CD59B7 /* RootView.swift in Sources */,
+				E64BB44903A15E99126E73E5 /* SettingsView.swift in Sources */,
 				89AC740ACEABE2AE5453E683 /* SurveyModel.swift in Sources */,
 				EA730F4FD060F5843CC5B422 /* SurveyView.swift in Sources */,
 				013407A07B79F11D51E23BD1 /* Theme.swift in Sources */,

diff --git a/Reportage/AppDelegate.swift b/Reportage/AppDelegate.swift

@@ -0,0 +1,80 @@
+import BackgroundTasks
+import OSLog
+import SwiftUI
+import UserNotifications
+
+/// Owns the store, and handles notifications: the notification delegate has
+/// to be set before launch finishes, or a tap that launched the app is lost.
+final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
+    let persistence = PersistenceController()
+    let inbox = PromptInbox()
+
+    private let logger = Logger(subsystem: "net.inqk.reportage", category: "Prompts")
+
+    func application(
+        _ application: UIApplication,
+        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
+    ) -> Bool {
+        let center = UNUserNotificationCenter.current()
+        center.delegate = self
+        center.setNotificationCategories(PromptNotification.categories)
+        return true
+    }
+
+    /// Prompts arriving while the app is open are shown as usual.
+    nonisolated func userNotificationCenter(
+        _ center: UNUserNotificationCenter, willPresent notification: UNNotification
+    ) async -> UNNotificationPresentationOptions {
+        [.banner, .list, .sound]
+    }
+
+    nonisolated func userNotificationCenter(
+        _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse
+    ) async {
+        await handle(PromptResponse(response))
+    }
+
+    private func handle(_ response: PromptResponse) async {
+        let store = ReportStore(persistence: persistence)
+        do {
+            let survey = try await PromptResponder(store: store)
+                .respond(to: response, settings: .load())
+            if let survey {
+                inbox.survey = survey
+            }
+        } catch {
+            logger.error("Couldn't respond to a prompt: \(error)")
+        }
+        // An action is a chance to top up the prompts.
+        await AppBadge.update(from: store)
+        await PromptScheduler().refresh()
+    }
+}
+
+/// The survey a tapped prompt asks for, held until the home screen can
+/// show it.
+@MainActor
+@Observable
+final class PromptInbox {
+    var survey: SurveyRequest?
+
+    /// Takes the waiting survey, if there is one.
+    func take() -> SurveyRequest? {
+        defer { survey = nil }
+        return survey
+    }
+}
+
+/// Background refresh tops up the prompts when the app hasn't been opened
+/// for a while.
+enum BackgroundRefresh {
+    static let identifier = "net.inqk.reportage.prompts"
+
+    /// Asks for the next refresh. Only one request is kept, so asking again
+    /// replaces it.
+    static func submit() {
+        let request = BGAppRefreshTaskRequest(identifier: identifier)
+        request.earliestBeginDate = Date(timeIntervalSinceNow: 6 * 60 * 60)
+        try? BGTaskScheduler.shared.submit(request)
+    }
+}

diff --git a/Reportage/Info.plist b/Reportage/Info.plist

@@ -2,6 +2,10 @@
 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
 <plist version="1.0">
 <dict>
+	<key>BGTaskSchedulerPermittedIdentifiers</key>
+	<array>
+		<string>net.inqk.reportage.prompts</string>
+	</array>
 	<key>CFBundleDevelopmentRegion</key>
 	<string>$(DEVELOPMENT_LANGUAGE)</string>
 	<key>CFBundleDisplayName</key>
@@ -28,6 +32,10 @@
 	<string>With Always, Reportage can record where you are when you log a report from a notification without opening the app.</string>
 	<key>NSLocationWhenInUseUsageDescription</key>
 	<string>Reportage records where you are with each report, and suggests places nearby when you say where you are.</string>
+	<key>UIBackgroundModes</key>
+	<array>
+		<string>fetch</string>
+	</array>
 	<key>UILaunchScreen</key>
 	<dict/>
 	<key>UISupportedInterfaceOrientations</key>

diff --git a/Reportage/ReportageApp.swift b/Reportage/ReportageApp.swift

@@ -3,22 +3,43 @@ import SwiftUI
 
 @main
 struct ReportageApp: App {
-    private let persistence = PersistenceController()
+    @UIApplicationDelegateAdaptor private var appDelegate: AppDelegate
+    @Environment(\.scenePhase) private var scenePhase
+
     private let logger = Logger(subsystem: "net.inqk.reportage", category: "App")
 
     var body: some Scene {
         WindowGroup {
-            HomeView()
-                .environment(\.managedObjectContext, persistence.viewContext)
-                .environment(\.reportStore, ReportStore(persistence: persistence))
+            RootView()
+                .environment(\.managedObjectContext, appDelegate.persistence.viewContext)
+                .environment(\.reportStore, ReportStore(persistence: appDelegate.persistence))
+                .environment(appDelegate.inbox)
                 .tint(Theme.accent)
                 .task { await seedDefaultQuestions() }
         }
+        .onChange(of: scenePhase) { _, phase in
+            switch phase {
+            case .active:
+                Task { await PromptScheduler().refresh() }
+            case .background:
+                if PromptSettings.load().isEnabled {
+                    BackgroundRefresh.submit()
+                }
+            default:
+                break
+            }
+        }
+        .backgroundTask(.appRefresh(BackgroundRefresh.identifier)) {
+            await PromptScheduler().refresh()
+            if PromptSettings.load().isEnabled {
+                BackgroundRefresh.submit()
+            }
+        }
     }
 
     private func seedDefaultQuestions() async {
         do {
-            try await ReportStore(persistence: persistence).seedDefaultQuestionsIfNeeded()
+            try await ReportStore(persistence: appDelegate.persistence).seedDefaultQuestionsIfNeeded()
         } catch {
             logger.error("Couldn't add the default questions: \(error)")
         }

diff --git a/Reportage/Services/Prompts/PromptNotification.swift b/Reportage/Services/Prompts/PromptNotification.swift

@@ -0,0 +1,152 @@
+import Foundation
+import UserNotifications
+
+/// The notifications prompts are sent as: their categories, actions,
+/// content and identifiers.
+enum PromptNotification {
+    static let promptCategory = "prompt"
+    static let reminderCategory = "reminder"
+    static let logAction = "log-for-later"
+    static let snoozeAction = "snooze"
+
+    /// Where a snoozed prompt keeps when the original prompt fired, as
+    /// seconds since the reference date.
+    static let promptedAtKey = "promptedAt"
+
+    /// What a pending notification's identifier says it is, or `nil` for one
+    /// that isn't the scheduler's.
+    enum Kind: String {
+        case prompt
+        case reminder
+        case snoozed
+    }
+
+    static func kind(ofIdentifier identifier: String) -> Kind? {
+        identifier.split(separator: ".", maxSplits: 1).first.flatMap { Kind(rawValue: String($0)) }
+    }
+
+    /// Log for Later and Snooze both run in the background: neither opens
+    /// the app.
+    static var categories: Set<UNNotificationCategory> {
+        let log = UNNotificationAction(
+            identifier: logAction,
+            title: String(localized: "Log for Later", comment: "Notification action that logs an instant report"),
+            icon: UNNotificationActionIcon(systemImageName: "bolt.fill"))
+        let snooze = UNNotificationAction(
+            identifier: snoozeAction,
+            title: String(localized: "Snooze", comment: "Notification action that repeats the prompt later"),
+            icon: UNNotificationActionIcon(systemImageName: "clock"))
+        return [
+            UNNotificationCategory(identifier: promptCategory, actions: [log, snooze], intentIdentifiers: []),
+            UNNotificationCategory(identifier: reminderCategory, actions: [], intentIdentifiers: []),
+        ]
+    }
+
+    static func request(for prompt: PlannedPrompt) -> UNNotificationRequest {
+        let content =
+            switch prompt.kind {
+            case .prompt: promptContent(promptedAt: nil)
+            case .reminder: reminderContent()
+            }
+        return UNNotificationRequest(
+            identifier: prompt.identifier,
+            content: content,
+            trigger: UNCalendarNotificationTrigger(dateMatching: prompt.components, repeats: false))
+    }
+
+    /// A prompt repeated after `delay`, keeping when it was first sent.
+    static func snoozeRequest(promptedAt: Date, delay: TimeInterval) -> UNNotificationRequest {
+        UNNotificationRequest(
+            identifier: "\(Kind.snoozed.rawValue).\(UUID().uuidString)",
+            content: promptContent(promptedAt: promptedAt),
+            trigger: UNTimeIntervalNotificationTrigger(timeInterval: max(delay, 1), repeats: false))
+    }
+
+    private static func promptContent(promptedAt: Date?) -> UNMutableNotificationContent {
+        let content = UNMutableNotificationContent()
+        content.body = String(
+            localized: "Time for a report. What are you doing?",
+            comment: "The body of a random prompt notification")
+        content.sound = .default
+        content.categoryIdentifier = promptCategory
+        if let promptedAt {
+            content.userInfo = [promptedAtKey: promptedAt.timeIntervalSinceReferenceDate]
+        }
+        return content
+    }
+
+    private static func reminderContent() -> UNMutableNotificationContent {
+        let content = UNMutableNotificationContent()
+        content.body = String(
+            localized: "Open Reportage to keep the prompts coming.",
+            comment: "The body of the notification that ends the scheduled prompts")
+        content.categoryIdentifier = reminderCategory
+        return content
+    }
+}
+
+/// What the user did with a delivered notification, taken out of the
+/// `UNNotificationResponse` so it can cross actors.
+struct PromptResponse: Sendable {
+    var category: String
+    var action: String
+    /// When the notification was delivered.
+    var deliveredAt: Date
+    /// When the prompt was first sent, for a snoozed prompt.
+    var promptedAt: Date?
+
+    init(category: String, action: String, deliveredAt: Date, promptedAt: Date? = nil) {
+        self.category = category
+        self.action = action
+        self.deliveredAt = deliveredAt
+        self.promptedAt = promptedAt
+    }
+
+    init(_ response: UNNotificationResponse) {
+        let notification = response.notification
+        let content = notification.request.content
+        self.init(
+            category: content.categoryIdentifier,
+            action: response.actionIdentifier,
+            deliveredAt: notification.date,
+            promptedAt: (content.userInfo[PromptNotification.promptedAtKey] as? Double)
+                .map(Date.init(timeIntervalSinceReferenceDate:)))
+    }
+
+    /// When the prompt first fired: the original time for a snoozed prompt.
+    var firedAt: Date { promptedAt ?? deliveredAt }
+}
+
+/// Carries out the user's response to a prompt.
+struct PromptResponder: Sendable {
+    let store: ReportStore
+    var center: any NotificationScheduling = SystemNotifications()
+    var capture: @Sendable () async -> Context = { await ContextCapture().capture() }
+
+    /// Logs or snoozes the prompt, and returns the survey to open when the
+    /// notification itself was tapped.
+    func respond(
+        to response: PromptResponse, settings: PromptSettings, now: Date = Date()
+    ) async throws -> SurveyRequest? {
+        guard response.category == PromptNotification.promptCategory else { return nil }
+        switch response.action {
+        case PromptNotification.logAction:
+            try await PassiveLog(store: store, capture: capture)
+                .log(kind: .random, trigger: .notification, date: now, promptedAt: response.firedAt)
+            return nil
+        case PromptNotification.snoozeAction:
+            try await center.add(
+                PromptNotification.snoozeRequest(
+                    promptedAt: response.firedAt, delay: TimeInterval(settings.snooze * 60)))
+            return nil
+        case UNNotificationDefaultActionIdentifier:
+            // The report describes when the notification came, which for a
+            // snoozed prompt is after it was first sent.
+            return SurveyRequest(
+                kind: .random, date: response.deliveredAt, trigger: .notification,
+                promptedAt: response.firedAt)
+        default:
+            return nil
+        }
+    }
+}

diff --git a/Reportage/Services/Prompts/PromptSchedule.swift b/Reportage/Services/Prompts/PromptSchedule.swift

@@ -0,0 +1,123 @@
+import Foundation
+
+/// One notification the scheduler wants pending: a prompt, or the reminder
+/// that ends the horizon.
+struct PlannedPrompt: Equatable, Sendable {
+    enum Kind: String, Sendable {
+        case prompt
+        /// Takes the place of the horizon's last prompt, so a long stretch
+        /// without opening the app ends with a nudge rather than silence.
+        case reminder
+    }
+
+    var kind: Kind
+    let date: Date
+    /// The fire time as wall-clock components, without a time zone, so the
+    /// notification fires at that local time wherever the phone is.
+    let components: DateComponents
+
+    /// Named by kind and wall-clock time, so the same plan always has the
+    /// same identifiers and rescheduling only touches what changed.
+    var identifier: String {
+        let c = components
+        return String(
+            format: "%@.%04d%02d%02d-%02d%02d%02d", kind.rawValue,
+            c.year ?? 0, c.month ?? 0, c.day ?? 0, c.hour ?? 0, c.minute ?? 0, c.second ?? 0)
+    }
+}
+
+/// Works out when prompts fire. Pure: the same settings, secret and day
+/// always give the same times.
+enum PromptSchedule {
+    /// The prompt times on `day`, in order.
+    ///
+    /// The window is split into `perDay` equal slots with one time drawn in
+    /// each, which avoids clusters and long silences while keeping each
+    /// prompt unpredictable. To keep the minimum gap, the slots share the
+    /// window less the gaps between them, and each later time is pushed on
+    /// by one gap more. A gap too large for the window shrinks to fit.
+    static func times(
+        on day: Date, settings: PromptSettings, secret: UInt64, calendar: Calendar
+    ) -> [Date] {
+        let count = settings.perDay
+        let window = settings.window(on: day, calendar: calendar)
+        guard count > 0,
+            let start = calendar.date(
+                bySettingHour: window.start / 60, minute: window.start % 60, second: 0, of: day),
+            var end = calendar.date(
+                bySettingHour: window.end / 60, minute: window.end % 60, second: 0, of: day)
+        else { return [] }
+        if end <= start {
+            end = calendar.date(byAdding: .day, value: 1, to: end) ?? end
+        }
+        let length = end.timeIntervalSince(start)
+        let gap = min(Double(settings.minimumGap * 60), length / Double(count))
+        let slot = (length - Double(count - 1) * gap) / Double(count)
+        var generator = SeededGenerator(seed: seed(for: day, secret: secret, calendar: calendar))
+        return (0..<count).map { index in
+            let offset = Double(index) * (slot + gap) + generator.nextUnit() * slot
+            return start.addingTimeInterval(offset.rounded(.down))
+        }
+    }
+
+    /// The notifications to keep pending from `now`: every prompt in the
+    /// next `days` days, up to `limit`, with the last one made a reminder.
+    /// The limit leaves room under iOS's 64 for snoozed prompts.
+    static func horizon(
+        from now: Date, settings: PromptSettings, secret: UInt64, calendar: Calendar,
+        days: Int = 7, limit: Int = 50
+    ) -> [PlannedPrompt] {
+        guard settings.isEnabled else { return [] }
+        let today = calendar.startOfDay(for: now)
+        // Yesterday too, for a window that runs past midnight.
+        let dates = (-1..<days)
+            .compactMap { calendar.date(byAdding: .day, value: $0, to: today) }
+            .flatMap { times(on: $0, settings: settings, secret: secret, calendar: calendar) }
+            .filter { $0 > now }
+            .sorted()
+            .prefix(limit)
+        var prompts = dates.map { date in
+            PlannedPrompt(
+                kind: .prompt,
+                date: date,
+                components: calendar.dateComponents(
+                    [.year, .month, .day, .hour, .minute, .second], from: date)
+            )
+        }
+        if !prompts.isEmpty {
+            prompts[prompts.count - 1].kind = .reminder
+        }
+        return prompts
+    }
+
+    /// Mixes the secret with the calendar date of `day`.
+    private static func seed(for day: Date, secret: UInt64, calendar: Calendar) -> UInt64 {
+        let c = calendar.dateComponents([.year, .month, .day], from: day)
+        let date = UInt64((c.year ?? 0) * 10_000 + (c.month ?? 0) * 100 + (c.day ?? 0))
+        return secret ^ (date &* 0x9E37_79B9_7F4A_7C15)
+    }
+}
+
+/// SplitMix64. Written out rather than using the standard library's
+/// generators and `random(in:)`, whose algorithms could change between OS
+/// versions and so move already-scheduled prompts.
+struct SeededGenerator: RandomNumberGenerator {
+    private var state: UInt64
+
+    init(seed: UInt64) {
+        state = seed
+    }
+
+    mutating func next() -> UInt64 {
+        state &+= 0x9E37_79B9_7F4A_7C15
+        var z = state
+        z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
+        z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
+        return z ^ (z >> 31)
+    }
+
+    /// A number in `0..<1`.
+    mutating func nextUnit() -> Double {
+        Double(next() >> 11) * 0x1.0p-53
+    }
+}

diff --git a/Reportage/Services/Prompts/PromptScheduler.swift b/Reportage/Services/Prompts/PromptScheduler.swift

@@ -0,0 +1,65 @@
+import Foundation
+import OSLog
+import UserNotifications
+
+/// The parts of `UNUserNotificationCenter` the scheduler uses, so tests can
+/// stand in for it.
+protocol NotificationScheduling: Sendable {
+    func pendingIdentifiers() async -> [String]
+    func add(_ request: UNNotificationRequest) async throws
+    func removePending(_ identifiers: [String])
+}
+
+struct SystemNotifications: NotificationScheduling {
+    func pendingIdentifiers() async -> [String] {
+        await UNUserNotificationCenter.current().pendingNotificationRequests().map(\.identifier)
+    }
+
+    func add(_ request: UNNotificationRequest) async throws {
+        try await UNUserNotificationCenter.current().add(request)
+    }
+
+    func removePending(_ identifiers: [String]) {
+        UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: identifiers)
+    }
+}
+
+/// Keeps the pending notifications in step with the plan. It runs whenever
+/// the app gets time (launch, foreground, a notification action, saving a
+/// report, background refresh) and only adds and removes the difference, so
+/// pending prompts aren't reshuffled.
+struct PromptScheduler: Sendable {
+    var center: any NotificationScheduling = SystemNotifications()
+
+    private static let logger = Logger(subsystem: "net.inqk.reportage", category: "Prompts")
+
+    /// Schedules from the saved settings.
+    func refresh() async {
+        await reschedule(settings: .load(), secret: PromptSecret.value())
+    }
+
+    func reschedule(
+        settings: PromptSettings, secret: UInt64, now: Date = Date(), calendar: Calendar = .current
+    ) async {
+        let plan = PromptSchedule.horizon(
+            from: now, settings: settings, secret: secret, calendar: calendar)
+        let planned = Set(plan.map(\.identifier))
+        let pending = await center.pendingIdentifiers()
+        // Snoozed prompts are left alone unless prompts are turned off.
+        let stale = pending.filter { id in
+            guard let kind = PromptNotification.kind(ofIdentifier: id) else { return false }
+            return kind == .snoozed ? !settings.isEnabled : !planned.contains(id)
+        }
+        if !stale.isEmpty {
+            center.removePending(stale)
+        }
+        let existing = Set(pending)
+        for prompt in plan where !existing.contains(prompt.identifier) {
+            do {
+                try await center.add(PromptNotification.request(for: prompt))
+            } catch {
+                Self.logger.error("Couldn't schedule \(prompt.identifier): \(error)")
+            }
+        }
+    }
+}

diff --git a/Reportage/Services/Prompts/PromptSettings.swift b/Reportage/Services/Prompts/PromptSettings.swift

@@ -0,0 +1,69 @@
+import Foundation
+
+/// When random prompts come: how many a day, within which hours, and how far
+/// apart.
+///
+/// Kept in `UserDefaults` for now. Phase 4 moves it into the `Config` zone so
+/// it syncs; the per-install secret stays local.
+struct PromptSettings: Codable, Equatable, Sendable {
+    /// Prompts are off until the user turns them on, which is when
+    /// notifications (and the upgrade to 'Always' location) are asked for.
+    var isEnabled = false
+    var perDay = 4
+    /// The waking window, every day or on weekdays only.
+    var window = WakingWindow(start: 9 * 60, end: 22 * 60)
+    /// The waking window on weekends, if it differs.
+    var weekendWindow: WakingWindow?
+    /// The least time between two prompts on the same day, in minutes.
+    var minimumGap = 30
+    /// How long Snooze puts a prompt off, in minutes.
+    var snooze = 15
+
+    /// The waking window on `day`.
+    func window(on day: Date, calendar: Calendar) -> WakingWindow {
+        if let weekendWindow, calendar.isDateInWeekend(day) {
+            return weekendWindow
+        }
+        return window
+    }
+}
+
+/// The hours prompts may come in, as minutes after midnight. An end at or
+/// before the start is on the next day, so a window can run past midnight.
+struct WakingWindow: Codable, Equatable, Sendable {
+    var start: Int
+    var end: Int
+}
+
+extension PromptSettings {
+    private static let key = "promptSettings"
+
+    /// The saved settings, or the defaults if there are none.
+    static func load(from defaults: UserDefaults = .standard) -> PromptSettings {
+        guard let data = defaults.data(forKey: key),
+            let settings = try? JSONDecoder().decode(PromptSettings.self, from: data)
+        else { return PromptSettings() }
+        return settings
+    }
+
+    func save(to defaults: UserDefaults = .standard) {
+        guard let data = try? JSONEncoder().encode(self) else { return }
+        defaults.set(data, forKey: Self.key)
+    }
+}
+
+/// A random number made once per install, which seeds each day's prompt
+/// times. Together with the date it makes the times unpredictable but the
+/// same every time they're worked out.
+enum PromptSecret {
+    private static let key = "promptSecret"
+
+    static func value(in defaults: UserDefaults = .standard) -> UInt64 {
+        if let stored = defaults.string(forKey: key), let value = UInt64(stored, radix: 16) {
+            return value
+        }
+        let value = UInt64.random(in: .min ... .max)
+        defaults.set(String(value, radix: 16), forKey: key)
+        return value
+    }
+}

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

@@ -6,6 +6,7 @@ import SwiftUI
 /// starts one.
 struct HomeView: View {
     @Environment(\.reportStore) private var store
+    @Environment(PromptInbox.self) private var inbox: PromptInbox?
     @State private var survey: SurveyRequest?
     @State private var describer = ReportDescriber()
 
@@ -28,15 +29,25 @@ struct HomeView: View {
             await describer.load(from: store)
             await AppBadge.update(from: store)
         }
+        .onChange(of: inbox?.survey?.id, initial: true) { openPrompt() }
     }
 
     private func reload() {
+        openPrompt()
         Task {
             await describer.load(from: store)
             await AppBadge.update(from: store)
+            await PromptScheduler().refresh()
         }
     }
 
+    /// Opens the survey for a tapped prompt, once nothing else is open, so
+    /// a survey in progress isn't lost.
+    private func openPrompt() {
+        guard survey == nil, let request = inbox?.take() else { return }
+        survey = request
+    }
+
     /// Logs this moment with its context and no answers. It goes straight
     /// into the timeline, where it can be filled in or left as it is.
     private func quickLog() {
@@ -48,6 +59,7 @@ struct HomeView: View {
                 logger.error("Couldn't make a quick log: \(error)")
             }
             await AppBadge.update(from: store)
+            await PromptScheduler().refresh()
         }
     }
 }

diff --git a/Reportage/Views/RootView.swift b/Reportage/Views/RootView.swift

@@ -0,0 +1,28 @@
+import SwiftUI
+
+/// The app's tabs: the timeline and Settings. Visualisations join them in
+/// Phase 7.
+struct RootView: View {
+    @Environment(PromptInbox.self) private var inbox: PromptInbox?
+    @State private var tab = RootTab.timeline
+
+    var body: some View {
+        TabView(selection: $tab) {
+            Tab("Timeline", systemImage: "calendar", value: RootTab.timeline) {
+                HomeView()
+            }
+            Tab("Settings", systemImage: "gearshape", value: RootTab.settings) {
+                SettingsView()
+            }
+        }
+        // A tapped prompt's survey opens over the timeline.
+        .onChange(of: inbox?.survey?.id, initial: true) {
+            if inbox?.survey != nil { tab = .timeline }
+        }
+    }
+}
+
+enum RootTab: Hashable {
+    case timeline
+    case settings
+}

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

@@ -0,0 +1,262 @@
+import CoreLocation
+import SwiftUI
+import UserNotifications
+
+/// Settings: for now, when random prompts come.
+struct SettingsView: View {
+    @Environment(\.reportStore) private var store
+    @Environment(\.scenePhase) private var scenePhase
+    @State private var settings = PromptSettings.load()
+    @State private var notifications: UNAuthorizationStatus?
+    @State private var isExplainingLocation = false
+    /// Held while iOS asks to upgrade location to 'Always'.
+    @State private var locationSession: CLServiceSession?
+
+    private static let gaps = [0, 15, 30, 45, 60, 90, 120]
+    private static let snoozes = [5, 10, 15, 20, 30, 60]
+
+    var body: some View {
+        NavigationStack {
+            List {
+                SettingsTitle()
+                Section {
+                    Toggle("Random Prompts", isOn: promptsEnabled)
+                        .settingsRow()
+                    if settings.isEnabled {
+                        Stepper(value: $settings.perDay, in: 1...12) {
+                            LabeledContent("Prompts a Day") {
+                                Text(settings.perDay, format: .number)
+                                    .monospacedDigit()
+                            }
+                        }
+                        .settingsRow()
+                    }
+                    SettingsNote { promptsFooter }
+                } header: {
+                    SettingsHeading("Prompts")
+                }
+                if settings.isEnabled {
+                    Section {
+                        WindowPicker(window: $settings.window)
+                        Toggle("Different Hours on Weekends", isOn: hasWeekendWindow)
+                            .settingsRow()
+                        SettingsNote {
+                            Text("Prompts come at random times between these hours, spread through the day.")
+                        }
+                    } header: {
+                        SettingsHeading(settings.weekendWindow == nil ? "Waking Hours" : "Weekdays")
+                    }
+                    if let weekend = settings.weekendWindow {
+                        Section {
+                            WindowPicker(
+                                window: Binding(
+                                    get: { weekend },
+                                    set: { settings.weekendWindow = $0 }))
+                        } header: {
+                            SettingsHeading("Weekends")
+                        }
+                    }
+                    Section {
+                        Picker("Minimum Gap", selection: $settings.minimumGap) {
+                            ForEach(Self.gaps, id: \.self) { minutes in
+                                MinutesText(minutes: minutes).tag(minutes)
+                            }
+                        }
+                        .settingsRow()
+                        Picker("Snooze For", selection: $settings.snooze) {
+                            ForEach(Self.snoozes, id: \.self) { minutes in
+                                MinutesText(minutes: minutes).tag(minutes)
+                            }
+                        }
+                        .settingsRow()
+                    } header: {
+                        SettingsHeading("Timing")
+                    }
+                }
+            }
+            .listStyle(.plain)
+            .scrollContentBackground(.hidden)
+            .background(Theme.paper)
+            .foregroundStyle(Theme.ink)
+            .toolbar(.hidden, for: .navigationBar)
+        }
+        .task { await checkNotifications() }
+        .onChange(of: scenePhase) { _, phase in
+            if phase == .active { Task { await checkNotifications() } }
+        }
+        .onChange(of: settings) { _, settings in
+            settings.save()
+            Task { await PromptScheduler().refresh() }
+        }
+        .alert("Record Location from Notifications?", isPresented: $isExplainingLocation) {
+            Button("Continue") { locationSession = LocationAuthorization.requestAlways() }
+            Button("Not Now", role: .cancel) {}
+        } message: {
+            Text(
+                "Log for Later records a report without opening Reportage. To include where you are, Reportage needs location access set to Always. Without it, these reports are saved without a location."
+            )
+        }
+        .onDisappear { locationSession?.invalidate() }
+    }
+
+    @ViewBuilder
+    private var promptsFooter: some View {
+        if notifications == .denied {
+            VStack(alignment: .leading, spacing: Theme.lineGap) {
+                Text("Notifications are turned off for Reportage, so prompts can't be sent.")
+                if let url = URL(string: UIApplication.openNotificationSettingsURLString) {
+                    Link("Open Settings", destination: url)
+                }
+            }
+        } else {
+            Text("Reportage sends a notification at random times each day, asking for a report.")
+        }
+    }
+
+    /// Turning prompts on asks for notifications first (with the badge,
+    /// which counts instant reports), then offers the upgrade to 'Always'
+    /// location that Log for Later needs.
+    private var promptsEnabled: Binding<Bool> {
+        Binding(
+            get: { settings.isEnabled },
+            set: { isOn in
+                if isOn {
+                    Task { await turnOnPrompts() }
+                } else {
+                    settings.isEnabled = false
+                }
+            })
+    }
+
+    private var hasWeekendWindow: Binding<Bool> {
+        Binding(
+            get: { settings.weekendWindow != nil },
+            set: { settings.weekendWindow = $0 ? settings.window : nil })
+    }
+
+    private func turnOnPrompts() async {
+        let center = UNUserNotificationCenter.current()
+        let granted = (try? await center.requestAuthorization(options: [.alert, .sound, .badge])) ?? false
+        await checkNotifications()
+        guard granted else { return }
+        settings.isEnabled = true
+        await AppBadge.update(from: store)
+        switch CLLocationManager().authorizationStatus {
+        case .notDetermined, .authorizedWhenInUse:
+            isExplainingLocation = true
+        default:
+            break
+        }
+    }
+
+    private func checkNotifications() async {
+        notifications = await UNUserNotificationCenter.current().notificationSettings().authorizationStatus
+    }
+}
+
+/// The start and end of a waking window.
+private struct WindowPicker: View {
+    @Binding var window: WakingWindow
+
+    var body: some View {
+        DatePicker("From", selection: time(\.start), displayedComponents: .hourAndMinute)
+            .settingsRow()
+        DatePicker("Until", selection: time(\.end), displayedComponents: .hourAndMinute)
+            .settingsRow()
+    }
+
+    /// Minutes after midnight, as a time today for the picker.
+    private func time(_ keyPath: WritableKeyPath<WakingWindow, Int>) -> Binding<Date> {
+        Binding(
+            get: {
+                let minutes = window[keyPath: keyPath]
+                return Calendar.current.date(
+                    bySettingHour: minutes / 60, minute: minutes % 60, second: 0, of: Date()) ?? Date()
+            },
+            set: { date in
+                let c = Calendar.current.dateComponents([.hour, .minute], from: date)
+                window[keyPath: keyPath] = (c.hour ?? 0) * 60 + (c.minute ?? 0)
+            })
+    }
+}
+
+/// The screen's title, set like the timeline's, with an ink rule beneath.
+private struct SettingsTitle: View {
+    var body: some View {
+        Text("Settings")
+            .font(Theme.serif(.largeTitle, weight: .medium))
+            .foregroundStyle(Theme.ink)
+            .accessibilityAddTraits(.isHeader)
+            .frame(minHeight: 44)
+            .listRowInsets(EdgeInsets(top: 8, leading: Theme.margin, bottom: 20, trailing: Theme.margin))
+            .listRowBackground(Theme.paper)
+            .listRowSeparatorTint(Theme.ink)
+            .listRowSeparator(.hidden, edges: .top)
+    }
+}
+
+/// A section heading in small spaced capitals, like a day in the timeline.
+private struct SettingsHeading: View {
+    let title: LocalizedStringKey
+
+    init(_ title: LocalizedStringKey) {
+        self.title = title
+    }
+
+    var body: some View {
+        Text(title)
+            .eyebrow()
+            .accessibilityAddTraits(.isHeader)
+            .frame(maxWidth: .infinity, alignment: .leading)
+            .padding(.horizontal, Theme.margin)
+            .padding(.top, Theme.headingTop)
+            .padding(.bottom, 4)
+            .background(Theme.paper)
+            .listRowInsets(EdgeInsets())
+    }
+}
+
+/// An explanation beneath a section's settings, in the muted footnote the
+/// timeline uses for context.
+private struct SettingsNote<Content: View>: View {
+    @ViewBuilder let content: Content
+
+    var body: some View {
+        content
+            .font(.footnote)
+            .foregroundStyle(Theme.muted)
+            .listRowInsets(EdgeInsets(top: 8, leading: Theme.margin, bottom: 12, trailing: Theme.margin))
+            .listRowBackground(Theme.paper)
+            .listRowSeparator(.hidden)
+    }
+}
+
+extension View {
+    /// A row of settings on paper, at the screen's margin, ruled like the
+    /// timeline.
+    fileprivate func settingsRow() -> some View {
+        listRowInsets(EdgeInsets(top: 10, leading: Theme.margin, bottom: 10, trailing: Theme.margin))
+            .listRowBackground(Theme.paper)
+            .listRowSeparatorTint(Theme.rule)
+    }
+}
+
+/// A number of minutes, such as '30 min' or '1 hr, 30 min'.
+private struct MinutesText: View {
+    let minutes: Int
+
+    var body: some View {
+        if minutes == 0 {
+            Text("None", comment: "No minimum gap between prompts")
+        } else {
+            Text(
+                Duration.seconds(minutes * 60),
+                format: .units(allowed: [.hours, .minutes], width: .abbreviated))
+        }
+    }
+}
+
+#Preview {
+    SettingsView()
+        .tint(Theme.accent)
+}

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

@@ -11,6 +11,9 @@ final class SurveyModel {
     /// when the report being edited was made.
     let date: Date
     let timeZone: String
+    /// What started a new report, and when its prompt was sent, if one was.
+    let trigger: ReportTrigger
+    let promptedAt: Date?
     let questions: [Question]
     /// The report this survey edits, if any: an instant report being filled
     /// in, or a finished one being changed. Its context was captured when it
@@ -33,13 +36,16 @@ final class SurveyModel {
         kind: ReportKind,
         date: Date,
         timeZone: TimeZone = .current,
+        trigger: ReportTrigger = .app,
+        promptedAt: Date? = nil,
         questions: [Question],
         vocabulary: [String: [VocabularyEntry]],
         directory: any PlaceDirectory = MapKitPlaceDirectory()
     ) {
         self.init(
-            kind: kind, date: date, timeZone: timeZone.identifier, existing: nil,
-            questions: questions, vocabulary: vocabulary, directory: directory)
+            kind: kind, date: date, timeZone: timeZone.identifier, trigger: trigger,
+            promptedAt: promptedAt, existing: nil, questions: questions, vocabulary: vocabulary,
+            directory: directory)
     }
 
     /// A survey that edits `report`, as of the moment it describes, starting
@@ -54,7 +60,8 @@ final class SurveyModel {
         directory: any PlaceDirectory = MapKitPlaceDirectory()
     ) {
         self.init(
-            kind: report.kind, date: report.date, timeZone: report.timeZone, existing: report,
+            kind: report.kind, date: report.date, timeZone: report.timeZone,
+            trigger: report.trigger, promptedAt: report.promptedAt, existing: report,
             questions: questions, vocabulary: vocabulary, directory: directory)
         for picker in placePickers.values {
             picker.setLocation(report.context.location)
@@ -76,6 +83,8 @@ final class SurveyModel {
         kind: ReportKind,
         date: Date,
         timeZone: String,
+        trigger: ReportTrigger,
+        promptedAt: Date?,
         existing: Report?,
         questions: [Question],
         vocabulary: [String: [VocabularyEntry]],
@@ -84,6 +93,8 @@ final class SurveyModel {
         self.kind = kind
         self.date = date
         self.timeZone = timeZone
+        self.trigger = trigger
+        self.promptedAt = promptedAt
         self.existing = existing
         self.questions = questions
         self.originalResponses = Dictionary(
@@ -307,8 +318,9 @@ final class SurveyModel {
             date: date,
             timeZone: timeZone,
             kind: kind,
-            trigger: .app,
+            trigger: trigger,
             state: .complete,
+            promptedAt: promptedAt,
             completedAt: now,
             context: context,
             responses: responses,

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

@@ -6,6 +6,10 @@ struct SurveyRequest: Identifiable {
     let id = UUID()
     var kind: ReportKind
     var date = Date()
+    /// What started a new report: the app, or a prompt's notification.
+    var trigger: ReportTrigger = .app
+    /// When the prompt that started a new report was sent.
+    var promptedAt: Date?
     /// The existing report to edit.
     var reportID: UUID?
 
@@ -76,6 +80,8 @@ struct SurveySheet: View {
                 model = SurveyModel(
                     kind: request.kind,
                     date: request.date,
+                    trigger: request.trigger,
+                    promptedAt: request.promptedAt,
                     questions: questions,
                     vocabulary: vocabulary
                 )

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

@@ -0,0 +1,150 @@
+import Foundation
+import Testing
+
+@testable import Reportage
+
+@Suite("PromptSchedule")
+struct PromptScheduleTests {
+
+    private static let secret: UInt64 = 0x1234_5678_9ABC_DEF0
+
+    private static var calendar: Calendar {
+        var calendar = Calendar(identifier: .gregorian)
+        calendar.timeZone = TimeZone(identifier: "Asia/Tokyo")!
+        return calendar
+    }
+
+    /// A Wednesday.
+    private static let day = calendar.date(from: DateComponents(year: 2026, month: 10, day: 14))!
+
+    private static func settings(
+        perDay: Int = 4, window: WakingWindow = WakingWindow(start: 9 * 60, end: 22 * 60),
+        weekend: WakingWindow? = nil, gap: Int = 30
+    ) -> PromptSettings {
+        var settings = PromptSettings()
+        settings.isEnabled = true
+        settings.perDay = perDay
+        settings.window = window
+        settings.weekendWindow = weekend
+        settings.minimumGap = gap
+        return settings
+    }
+
+    private static func times(_ settings: PromptSettings, on day: Date = day, secret: UInt64 = secret) -> [Date] {
+        PromptSchedule.times(on: day, settings: settings, secret: secret, calendar: calendar)
+    }
+
+    private static func at(_ hour: Int, _ minute: Int = 0, on day: Date = day) -> Date {
+        calendar.date(bySettingHour: hour, minute: minute, second: 0, of: day)!
+    }
+
+    @Test("A day's times are the same every time they're worked out")
+    func deterministic() {
+        let settings = Self.settings()
+        #expect(Self.times(settings) == Self.times(settings))
+    }
+
+    @Test("Different days and installs get different times")
+    func varies() {
+        let settings = Self.settings()
+        let nextDay = Self.calendar.date(byAdding: .day, value: 1, to: Self.day)!
+        #expect(Self.times(settings) != Self.times(settings, on: nextDay))
+        #expect(Self.times(settings) != Self.times(settings, secret: 42))
+    }
+
+    @Test("One time falls in each slot of the window, in order, a gap apart", arguments: 0..<50)
+    func stratified(seed: UInt64) {
+        let settings = Self.settings(perDay: 6, gap: 45)
+        let times = Self.times(settings, secret: seed)
+        let start = Self.at(9)
+        let end = Self.at(22)
+        let slot = end.timeIntervalSince(start) / 6
+
+        #expect(times.count == 6)
+        #expect(times == times.sorted())
+        for (index, time) in times.enumerated() {
+            #expect(time >= start.addingTimeInterval(Double(index) * slot))
+            #expect(time < start.addingTimeInterval(Double(index + 1) * slot))
+            #expect(time.timeIntervalSinceReferenceDate.rounded() == time.timeIntervalSinceReferenceDate)
+        }
+        for (earlier, later) in zip(times, times.dropFirst()) {
+            #expect(later.timeIntervalSince(earlier) >= 45 * 60 - 1)
+        }
+    }
+
+    @Test("A gap too large for the window shrinks to fit")
+    func gapTooLarge() {
+        let settings = Self.settings(
+            perDay: 6, window: WakingWindow(start: 9 * 60, end: 12 * 60), gap: 120)
+        let times = Self.times(settings)
+        #expect(times.count == 6)
+        #expect(times.allSatisfy { $0 >= Self.at(9) && $0 < Self.at(12) })
+        for (earlier, later) in zip(times, times.dropFirst()) {
+            #expect(later.timeIntervalSince(earlier) >= 30 * 60 - 1)
+        }
+    }
+
+    @Test("A window can run past midnight")
+    func pastMidnight() {
+        let settings = Self.settings(window: WakingWindow(start: 20 * 60, end: 2 * 60))
+        let times = Self.times(settings)
+        let nextDay = Self.calendar.date(byAdding: .day, value: 1, to: Self.day)!
+        #expect(times.count == 4)
+        #expect(times.allSatisfy { $0 >= Self.at(20) && $0 < Self.at(2, on: nextDay) })
+    }
+
+    @Test("Weekends use their own window")
+    func weekends() {
+        let settings = Self.settings(weekend: WakingWindow(start: 11 * 60, end: 13 * 60))
+        let saturday = Self.calendar.date(byAdding: .day, value: 3, to: Self.day)!
+        #expect(Self.times(settings, on: saturday).allSatisfy {
+            $0 >= Self.at(11, on: saturday) && $0 < Self.at(13, on: saturday)
+        })
+        #expect(Self.times(settings).contains { $0 >= Self.at(13) })
+    }
+
+    @Test("The horizon covers the coming week from now, ending with a reminder")
+    func horizon() {
+        let settings = Self.settings()
+        let now = Self.at(15)
+        let plan = PromptSchedule.horizon(
+            from: now, settings: settings, secret: Self.secret, calendar: Self.calendar)
+
+        let today = Self.times(settings).filter { $0 > now }
+        #expect(plan.count == today.count + 6 * 4)
+        #expect(plan.allSatisfy { $0.date > now })
+        #expect(plan.map(\.date) == plan.map(\.date).sorted())
+        #expect(plan.dropLast().allSatisfy { $0.kind == .prompt })
+        #expect(plan.last?.kind == .reminder)
+        #expect(Set(plan.map(\.identifier)).count == plan.count)
+    }
+
+    @Test("The horizon is capped, leaving room for snoozes")
+    func horizonLimit() {
+        let plan = PromptSchedule.horizon(
+            from: Self.at(0), settings: Self.settings(perDay: 12, gap: 15),
+            secret: Self.secret, calendar: Self.calendar)
+        #expect(plan.count == 50)
+    }
+
+    @Test("Prompts that are off plan nothing")
+    func disabled() {
+        var settings = Self.settings()
+        settings.isEnabled = false
+        #expect(
+            PromptSchedule.horizon(
+                from: Self.at(0), settings: settings, secret: Self.secret, calendar: Self.calendar
+            ).isEmpty)
+    }
+
+    @Test("Identifiers name the kind and the local fire time")
+    func identifiers() {
+        let prompt = PlannedPrompt(
+            kind: .reminder, date: Self.at(9, 5),
+            components: DateComponents(year: 2026, month: 10, day: 14, hour: 9, minute: 5, second: 7))
+        #expect(prompt.identifier == "reminder.20261014-090507")
+        #expect(PromptNotification.kind(ofIdentifier: prompt.identifier) == .reminder)
+        #expect(PromptNotification.kind(ofIdentifier: "snoozed.ABC") == .snoozed)
+        #expect(PromptNotification.kind(ofIdentifier: "something-else") == nil)
+    }
+}

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

@@ -0,0 +1,219 @@
+import Foundation
+import Testing
+import UserNotifications
+
+@testable import Reportage
+
+/// Records what's scheduled, in place of `UNUserNotificationCenter`.
+final class FakeNotifications: NotificationScheduling, @unchecked Sendable {
+    private let lock = NSLock()
+    private var requests: [String: UNNotificationRequest] = [:]
+    private(set) var addCount = 0
+
+    var identifiers: Set<String> { lock.withLock { Set(requests.keys) } }
+
+    func request(_ identifier: String) -> UNNotificationRequest? {
+        lock.withLock { requests[identifier] }
+    }
+
+    func pendingIdentifiers() async -> [String] {
+        lock.withLock { Array(requests.keys) }
+    }
+
+    func add(_ request: UNNotificationRequest) async throws {
+        lock.withLock {
+            requests[request.identifier] = request
+            addCount += 1
+        }
+    }
+
+    func removePending(_ identifiers: [String]) {
+        lock.withLock {
+            for identifier in identifiers { requests[identifier] = nil }
+        }
+    }
+}
+
+@Suite("PromptScheduler")
+struct PromptSchedulerTests {
+
+    private static var calendar: Calendar {
+        var calendar = Calendar(identifier: .gregorian)
+        calendar.timeZone = TimeZone(identifier: "Asia/Tokyo")!
+        return calendar
+    }
+
+    private static let now = calendar.date(
+        from: DateComponents(year: 2026, month: 10, day: 14, hour: 8))!
+
+    private static var settings: PromptSettings {
+        var settings = PromptSettings()
+        settings.isEnabled = true
+        return settings
+    }
+
+    private func schedule(
+        _ center: FakeNotifications, settings: PromptSettings = settings, now: Date = now
+    ) async {
+        await PromptScheduler(center: center)
+            .reschedule(settings: settings, secret: 7, now: now, calendar: Self.calendar)
+    }
+
+    private static func plan(settings: PromptSettings = settings, now: Date = now) -> Set<String> {
+        Set(
+            PromptSchedule.horizon(from: now, settings: settings, secret: 7, calendar: calendar)
+                .map(\.identifier))
+    }
+
+    @Test("Scheduling fills the horizon with prompts and a reminder")
+    func fills() async throws {
+        let center = FakeNotifications()
+        await schedule(center)
+
+        #expect(center.identifiers == Self.plan())
+        let reminder = try #require(center.identifiers.first { $0.hasPrefix("reminder.") })
+        #expect(center.request(reminder)?.content.categoryIdentifier == PromptNotification.reminderCategory)
+        let prompt = try #require(center.identifiers.first { $0.hasPrefix("prompt.") })
+        #expect(center.request(prompt)?.content.categoryIdentifier == PromptNotification.promptCategory)
+        #expect(center.request(prompt)?.trigger is UNCalendarNotificationTrigger)
+    }
+
+    @Test("Rescheduling leaves pending prompts alone")
+    func idempotent() async {
+        let center = FakeNotifications()
+        await schedule(center)
+        let added = center.addCount
+        await schedule(center)
+        #expect(center.addCount == added)
+    }
+
+    @Test("A day later, fired prompts go and the next day's come, and the old reminder becomes a prompt")
+    func rolls() async {
+        let center = FakeNotifications()
+        await schedule(center)
+        let later = Self.now.addingTimeInterval(24 * 60 * 60)
+        await schedule(center, now: later)
+        #expect(center.identifiers == Self.plan(now: later))
+    }
+
+    @Test("Changing the settings replaces the prompts, but keeps snoozed ones")
+    func settingsChange() async {
+        let center = FakeNotifications()
+        await schedule(center)
+        try? await center.add(PromptNotification.snoozeRequest(promptedAt: Self.now, delay: 900))
+        var settings = Self.settings
+        settings.perDay = 2
+        await schedule(center, settings: settings)
+
+        let snoozed = center.identifiers.filter { $0.hasPrefix("snoozed.") }
+        #expect(snoozed.count == 1)
+        #expect(center.identifiers.subtracting(snoozed) == Self.plan(settings: settings))
+    }
+
+    @Test("Turning prompts off removes them all, snoozed ones too, but not other notifications")
+    func off() async throws {
+        let center = FakeNotifications()
+        await schedule(center)
+        try await center.add(PromptNotification.snoozeRequest(promptedAt: Self.now, delay: 900))
+        try await center.add(
+            UNNotificationRequest(identifier: "other", content: UNNotificationContent(), trigger: nil))
+        var settings = Self.settings
+        settings.isEnabled = false
+        await schedule(center, settings: settings)
+        #expect(center.identifiers == ["other"])
+    }
+}
+
+@Suite("PromptResponder")
+struct PromptResponderTests {
+
+    private let persistence = makeTestPersistence()
+    private let center = FakeNotifications()
+
+    private var responder: PromptResponder {
+        PromptResponder(
+            store: ReportStore(persistence: persistence), center: center,
+            capture: { Context(device: DeviceContext(batteryLevel: 0.5)) })
+    }
+
+    private static let firedAt = Date(timeIntervalSinceReferenceDate: 800_000_000)
+    private static let deliveredAt = firedAt.addingTimeInterval(900)
+    private static let now = deliveredAt.addingTimeInterval(60)
+
+    private static func response(_ action: String, snoozed: Bool = false) -> PromptResponse {
+        PromptResponse(
+            category: PromptNotification.promptCategory, action: action,
+            deliveredAt: snoozed ? deliveredAt : firedAt,
+            promptedAt: snoozed ? firedAt : nil)
+    }
+
+    @Test("Log for Later saves an instant random report prompted when the prompt first fired")
+    func logForLater() async throws {
+        let survey = try await responder.respond(
+            to: Self.response(PromptNotification.logAction, snoozed: true),
+            settings: PromptSettings(), now: Self.now)
+        #expect(survey == nil)
+
+        let store = ReportStore(persistence: persistence)
+        #expect(try await store.passiveCount() == 1)
+        let context = persistence.newBackgroundContext()
+        let report = try await context.perform {
+            try context.fetch(ReportEntity.fetchRequest()).first?.report()
+        }
+        #expect(report?.kind == .random)
+        #expect(report?.trigger == .notification)
+        #expect(report?.state == .passive)
+        #expect(report?.date == Self.now)
+        #expect(report?.promptedAt == Self.firedAt)
+        #expect(report?.context.device?.batteryLevel == 0.5)
+    }
+
+    @Test("Snooze repeats the prompt later, keeping when it first fired")
+    func snooze() async throws {
+        var settings = PromptSettings()
+        settings.snooze = 20
+        _ = try await responder.respond(
+            to: Self.response(PromptNotification.snoozeAction), settings: settings, now: Self.now)
+
+        let id = try #require(center.identifiers.first)
+        #expect(PromptNotification.kind(ofIdentifier: id) == .snoozed)
+        let request = try #require(center.request(id))
+        #expect((request.trigger as? UNTimeIntervalNotificationTrigger)?.timeInterval == TimeInterval(20 * 60))
+        #expect(request.content.categoryIdentifier == PromptNotification.promptCategory)
+
+        // Snoozing the snoozed prompt keeps the original time.
+        let delivered = PromptResponse(
+            category: PromptNotification.promptCategory, action: UNNotificationDefaultActionIdentifier,
+            deliveredAt: Self.deliveredAt,
+            promptedAt: (request.content.userInfo[PromptNotification.promptedAtKey] as? Double)
+                .map(Date.init(timeIntervalSinceReferenceDate:)))
+        #expect(delivered.firedAt == Self.firedAt)
+    }
+
+    @Test("Tapping a prompt opens a random survey for when it came")
+    func tap() async throws {
+        let survey = try #require(
+            try await responder.respond(
+                to: Self.response(UNNotificationDefaultActionIdentifier, snoozed: true),
+                settings: PromptSettings(), now: Self.now))
+        #expect(survey.kind == .random)
+        #expect(survey.date == Self.deliveredAt)
+        #expect(survey.trigger == .notification)
+        #expect(survey.promptedAt == Self.firedAt)
+        #expect(survey.reportID == nil)
+    }
+
+    @Test("Tapping the reminder or dismissing a prompt does nothing")
+    func ignored() async throws {
+        let reminder = PromptResponse(
+            category: PromptNotification.reminderCategory, action: UNNotificationDefaultActionIdentifier,
+            deliveredAt: Self.firedAt)
+        #expect(try await responder.respond(to: reminder, settings: PromptSettings()) == nil)
+        #expect(
+            try await responder.respond(
+                to: Self.response(UNNotificationDismissActionIdentifier), settings: PromptSettings())
+                == nil)
+        #expect(center.identifiers.isEmpty)
+        #expect(try await ReportStore(persistence: persistence).passiveCount() == 0)
+    }
+}

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

@@ -57,6 +57,19 @@ struct SurveyModelTests {
         #expect(!model.hasAnswers)
     }
 
+    @Test("A survey opened from a prompt records its trigger and when the prompt came")
+    func prompted() {
+        let promptedAt = Date(timeIntervalSince1970: 50)
+        let model = SurveyModel(
+            kind: .random, date: Date(timeIntervalSince1970: 100), trigger: .notification,
+            promptedAt: promptedAt, questions: Self.questions, vocabulary: [:])
+        let report = model.makeReport(now: Date(timeIntervalSince1970: 200)).report
+        #expect(report.kind == .random)
+        #expect(report.trigger == .notification)
+        #expect(report.promptedAt == promptedAt)
+        #expect(report.date == Date(timeIntervalSince1970: 100))
+    }
+
     @Test("Answers of every kind become response values")
     func answers() throws {
         let model = makeModel()

diff --git a/project.yml b/project.yml

@@ -29,11 +29,15 @@ targets:
     info:
       path: Reportage/Info.plist
       properties:
+        BGTaskSchedulerPermittedIdentifiers:
+          - net.inqk.reportage.prompts
         CFBundleDisplayName: Reportage
         CFBundleShortVersionString: "1.0.0"
         CFBundleVersion: $(CURRENT_PROJECT_VERSION)
         ITSAppUsesNonExemptEncryption: false
         LSRequiresIPhoneOS: true
+        UIBackgroundModes:
+          - fetch
         NSLocationWhenInUseUsageDescription: Reportage records where you are with each report, and suggests places nearby when you say where you are.
         NSLocationAlwaysAndWhenInUseUsageDescription: With Always, Reportage can record where you are when you log a report from a notification without opening the app.
         UILaunchScreen: {}