Compare commits

..

9 Commits

42 changed files with 1729 additions and 28 deletions
+1
View File
@@ -8,5 +8,6 @@ One row per feature, with its analysis document (CLAUDE.md §5.1). Gaps live in
| Workspace, contracts, gates, PWA shell | 0 | Merged to `main` 2026-11-01 (`d11d242`); built, not deployed. Phase 0 gate still open | [phase0-workspace.md](features/phase0-workspace.md) | [feature-phase0-workspace.md](reviews/feature-phase0-workspace.md) | | Workspace, contracts, gates, PWA shell | 0 | Merged to `main` 2026-11-01 (`d11d242`); built, not deployed. Phase 0 gate still open | [phase0-workspace.md](features/phase0-workspace.md) | [feature-phase0-workspace.md](reviews/feature-phase0-workspace.md) |
| Roadmap and gameplay docs, read against the code | 0 | Merged 2026-11-01; Q1–Q7 answered by the author | — | [docs-roadmap-gameplay.md](reviews/docs-roadmap-gameplay.md) | | Roadmap and gameplay docs, read against the code | 0 | Merged 2026-11-01; Q1–Q7 answered by the author | — | [docs-roadmap-gameplay.md](reviews/docs-roadmap-gameplay.md) |
| The Letter slot: page at `#letter`, empty `docs/LETTER.md` | 0 | Merged to `main`; built, not deployed. Invisible until the author writes | [letter-slot.md](features/letter-slot.md) | [feature-letter-slot.md](reviews/feature-letter-slot.md) | | The Letter slot: page at `#letter`, empty `docs/LETTER.md` | 0 | Merged to `main`; built, not deployed. Invisible until the author writes | [letter-slot.md](features/letter-slot.md) | [feature-letter-slot.md](reviews/feature-letter-slot.md) |
| Where the sunset is: choose a town (or skip to a guess from the device's zone), kept on the device; tonight's sunset in the garden | 1 | Merged to `main`; built, not deployed | [sunset-place.md](features/sunset-place.md) | [feature-sunset-place.md](reviews/feature-sunset-place.md) |
| The sun: real sunrise, sunset and solar noon on the device; polar day and night | 1 | Merged to `main`; engine only, the app does not show it yet | [sun.md](features/sun.md) | [feature-sun.md](reviews/feature-sun.md) | | The sun: real sunrise, sunset and solar noon on the device; polar day and night | 1 | Merged to `main`; engine only, the app does not show it yet | [sun.md](features/sun.md) | [feature-sun.md](reviews/feature-sun.md) |
| The art pipeline and the art board: STYLE.md (S1–S5 and the fox's F1–F4 approved), the manifest (Phase 1–3, 53 pictures), stand-ins, `tools/art-prep`, the published board | 0 | Merged to `main`; board published (private). The app is unchanged. Gate waits on the first real picture | [art-pipeline.md](features/art-pipeline.md) | [feature-art-board.md](reviews/feature-art-board.md), [art-phase2-3-pictures.md](reviews/art-phase2-3-pictures.md) | | The art pipeline and the art board: STYLE.md (S1–S5 and the fox's F1–F4 approved), the manifest (Phase 1–3, 53 pictures), stand-ins, `tools/art-prep`, the published board | 0 | Merged to `main`; board published (private). The app is unchanged. Gate waits on the first real picture | [art-pipeline.md](features/art-pipeline.md) | [feature-art-board.md](reviews/feature-art-board.md), [art-phase2-3-pictures.md](reviews/art-phase2-3-pictures.md) |
+4 -3
View File
@@ -31,7 +31,7 @@ board exist, and the first real picture is the author's to make.
| G0.12 | The app cannot validate content in the browser | Open. Ajv compiles with `new Function`, which the CSP forbids. Needs standalone pre-compiled validators before the app reads the library. | | G0.12 | The app cannot validate content in the browser | Open. Ajv compiles with `new Function`, which the CSP forbids. Needs standalone pre-compiled validators before the app reads the library. |
| G0.13 | No GitHub remote, no Pages deploy workflow, no mirror check (§5.2) | Open. Only the Gitea remote exists. | | G0.13 | No GitHub remote, no Pages deploy workflow, no mirror check (§5.2) | Open. Only the Gitea remote exists. |
| G0.14 | Author-owned docs missing: `docs/PRINCIPLES.md`, `docs/ART.md`, `art/STYLE.md`, `docs/LETTER.md` | Open, narrowed 2026-11-01: `docs/ROADMAP.md` and `docs/GAMEPLAY.md` were added on `docs/roadmap-gameplay`, as the author gave them. Agents scaffold LETTER.md; they never write its voice. | | G0.14 | Author-owned docs missing: `docs/PRINCIPLES.md`, `docs/ART.md`, `art/STYLE.md`, `docs/LETTER.md` | Open, narrowed 2026-11-01: `docs/ROADMAP.md` and `docs/GAMEPLAY.md` were added on `docs/roadmap-gameplay`, as the author gave them. Agents scaffold LETTER.md; they never write its voice. |
| G0.15 | Deferred packages: `storage`, `identity`, `sync`, `services/lucerna`, `tools/art-prep` | Open by design (D1). Each arrives with its first feature. | | G0.15 | Deferred packages: `identity`, `sync`, `services/lucerna` | Open by design (D1). Each arrives with its first feature. `tools/art-prep` arrived with the art board; `storage` with the sunset place (2026-11-02, the `profile` store only). |
| G0.16 | The outcome-phrase heuristic has no reviewed override | Open. A real sentence that trips it (a false positive) cannot enter the library. Design: a `reviewedBy` field on the entry, set only by a person. | | G0.16 | The outcome-phrase heuristic has no reviewed override | Open. A real sentence that trips it (a false positive) cannot enter the library. Design: a `reviewedBy` field on the entry, set only by a person. |
| G0.17 | Manual: install on a phone, open in airplane mode | Open. Needs a hosted build (G0.13). | | G0.17 | Manual: install on a phone, open in airplane mode | Open. Needs a hosted build (G0.13). |
| G0.18 | The library is empty | Open. **Phase 0 gate**: 60 sentences, each sourced and verified public domain (ROADMAP Phase 0). Release needs ≥ 365. `verifiedBy` is a person, so an agent may propose candidates but never mark one verified (D4). | | G0.18 | The library is empty | Open. **Phase 0 gate**: 60 sentences, each sourced and verified public domain (ROADMAP Phase 0). Release needs ≥ 365. `verifiedBy` is a person, so an agent may propose candidates but never mark one verified (D4). |
@@ -53,7 +53,8 @@ sentences). Nothing in Phase 1 is visible to the player yet.
| Id | Gap | Status / evidence | | Id | Gap | Status / evidence |
|:--|:--|:--| |:--|:--|:--|
| ~~G1.1~~ | ~~No module computes the sun (CLAUDE.md §7); polar and DST traps only predicted~~ | Closed 2026-11-01 on `feature/sun`. `engine/src/sun/sun.ts`: 26 published days in 6 cities within 2 min, polar day and night at Tromsø, 50 tests, 5 of 5 put-back bugs caught. Both traps measured (CLAUDE.md §8). | | ~~G1.1~~ | ~~No module computes the sun (CLAUDE.md §7); polar and DST traps only predicted~~ | Closed 2026-11-01 on `feature/sun`. `engine/src/sun/sun.ts`: 26 published days in 6 cities within 2 min, polar day and night at Tromsø, 50 tests, 5 of 5 put-back bugs caught. Both traps measured (CLAUDE.md §8). |
| G1.2 | The player cannot choose a city; no time-zone guess; no sunset time on screen | Open. A city list on the device (never GPS, never an IP lookup), the device zone as the fallback, the time shown in the garden. | | ~~G1.2~~ | ~~The player cannot choose a city; no time-zone guess; no sunset time on screen~~ | Closed 2026-11-02 on `feature/sunset-place`. 7,342 public-domain towns searched on the device, a guess for every zone a browser reports, the town kept in IndexedDB, tonight's sunset in the garden. 299 unit, 10 e2e, offline choosing and changing a town; 6 of 6 put-back bugs caught. |
| G1.3 | Towns have no Czech names (*Vídeň*) | Open. Natural Earth has none; arrives with Czech copy. |
## Design questions — answered ## Design questions — answered
@@ -70,5 +71,5 @@ Raised by GAMEPLAY.md and ROADMAP.md, answered by the author 2026-11-01. Details
| ~~Q6~~ | When the notification decision is due | Phase 0, in-app only (G0.26) | | ~~Q6~~ | When the notification decision is due | Phase 0, in-app only (G0.26) |
| ~~Q7~~ | Which phase holds the Amicitia bridge | Phase 3 | | ~~Q7~~ | Which phase holds the Amicitia bridge | Phase 3 |
| Q8 | "Nearby days give a little more" | Open as a rule for the Phase 1 Soul review: a gap's cost is never shown | | Q8 | "Nearby days give a little more" | Open as a rule for the Phase 1 Soul review: a gap's cost is never shown |
| Q10 | In polar night, when should the invitation come? | Open. The engine assumes solar noon, when the twilight is brightest (`features/sun.md` D4). In polar day it is the lowest light, as CLAUDE.md §8 suggests. | | ~~Q10~~ | In polar night, when should the invitation come? | At solar noon, when the twilight is brightest: answered by the author 2026-11-01 (`features/sun.md` D4). In polar day it is the lowest light, as CLAUDE.md §8 suggests. |
| Q9 | May the Letter name the book and its author for the one sentence of inspiration (GAMEPLAY §7)? | Open. `lint:copy` refuses those names in the letter as everywhere in the product. A yes needs a written, letter-only exemption. | | Q9 | May the Letter name the book and its author for the one sentence of inspiration (GAMEPLAY §7)? | Open. `lint:copy` refuses those names in the letter as everywhere in the product. A yes needs a written, letter-only exemption. |
+2 -2
View File
@@ -58,7 +58,7 @@ flowchart LR
| D1 | NOAA's algorithm, in TypeScript, in the engine. No library, no WASM. | About 80 lines of public-domain maths, accurate to about a minute below 72° latitude. CLAUDE.md §2: WASM only with a measurement that says it must. | | D1 | NOAA's algorithm, in TypeScript, in the engine. No library, no WASM. | About 80 lines of public-domain maths, accurate to about a minute below 72° latitude. CLAUDE.md §2: WASM only with a measurement that says it must. |
| D2 | **"Today's sunset" is the one after today's solar noon**, even when it falls after midnight. "Today" is the local day whose solar noon it is. | Reykjavík on 21 June sets at 00:04 on the 22nd. The published table for the 21st lists the *previous* evening's 00:04. A player in Reykjavík means tonight's sunset, not last night's. | | D2 | **"Today's sunset" is the one after today's solar noon**, even when it falls after midnight. "Today" is the local day whose solar noon it is. | Reykjavík on 21 June sets at 00:04 on the 22nd. The published table for the 21st lists the *previous* evening's 00:04. A player in Reykjavík means tonight's sunset, not last night's. |
| D3 | The engine returns instants. Clock times are read in the app, with the city's zone. | One instant has one meaning. The DST jump is then only the clock's (§1), and the engine cannot be wrong about it. | | D3 | The engine returns instants. Clock times are read in the app, with the city's zone. | One instant has one meaning. The DST jump is then only the clock's (§1), and the engine cannot be wrong about it. |
| D4 | **Polar day**: the invitation is the *lowest light*, solar midnight. **Polar night**: the invitation is solar noon, when the twilight is brightest. | CLAUDE.md §8 asks for a gentle alternative, *e.g. the hour the light is lowest*. In polar night that hour is all day, so the brightest one is the moment worth going out for. **Assumption, for the author** (Q10). | | D4 | **Polar day**: the invitation is the *lowest light*, solar midnight. **Polar night**: the invitation is solar noon, when the twilight is brightest. | CLAUDE.md §8 asks for a gentle alternative, *e.g. the hour the light is lowest*. In polar night that hour is all day, so the brightest one is the moment worth going out for. **Decided by the author 2026-11-01** (Q10). |
| D5 | Near the edge of polar day or night, an event whose hour angle leaves the possible range is clamped to solar midnight or noon. | On those few days the sun only grazes the horizon. A defined answer beats a NaN. Accuracy there is worse, and the tests say so. | | D5 | Near the edge of polar day or night, an event whose hour angle leaves the possible range is clamped to solar midnight or noon. | On those few days the sun only grazes the horizon. A defined answer beats a NaN. Accuracy there is worse, and the tests say so. |
| D6 | Golden values come from the U.S. Naval Observatory's published tables, recorded once into a fixture by `scripts/fetch-sun-golden.ts`. | CLAUDE.md §5.5 asks for published tables. Recording them keeps tests offline and deterministic, and the script shows exactly where each number came from. | | D6 | Golden values come from the U.S. Naval Observatory's published tables, recorded once into a fixture by `scripts/fetch-sun-golden.ts`. | CLAUDE.md §5.5 asks for published tables. Recording them keeps tests offline and deterministic, and the script shows exactly where each number came from. |
| D7 | Tolerance: **2 minutes**, stated in the test. | The almanac rounds to the minute; NOAA's method is good to about a minute at these latitudes. | | D7 | Tolerance: **2 minutes**, stated in the test. | The almanac rounds to the minute; NOAA's method is good to about a minute at these latitudes. |
@@ -87,7 +87,7 @@ Reachability: none. The module talks to no one.
| DST and the local day: a predicted trap | D3 and `localDay`. **Measured**: the Prague sunset is 18:28 on 28 March and 19:29 on the 29th; the sun moved one minute | Built; the trap is confirmed | | DST and the local day: a predicted trap | D3 and `localDay`. **Measured**: the Prague sunset is 18:28 on 28 March and 19:29 on the 29th; the sun moved one minute | Built; the trap is confirmed |
| Golden tests against published tables (§5.5) | 28 days in 6 cities, recorded from USNO | Built | | Golden tests against published tables (§5.5) | 28 days in 6 cities, recorded from USNO | Built |
| Choosing a city, the time-zone guess, showing the time | The app, with a city list; later in Phase 1 | **Open** (G1.2) | | Choosing a city, the time-zone guess, showing the time | The app, with a city list; later in Phase 1 | **Open** (G1.2) |
| The invitation in polar night (D4) | An assumption | **Open for the author** (Q10) | | The invitation in polar night (D4) | Noon twilight | Decided by the author (Q10) |
## 5. Verification matrix ## 5. Verification matrix
+122
View File
@@ -0,0 +1,122 @@
# Where the sunset is — choosing a town, the guess, tonight's sunset
Status: built on `feature/sunset-place`. ROADMAP Phase 1, *the sun*: "the player is asked *Where do
you want your sunset?* (a city, skippable); if skipped, it is guessed from the device time zone.
**Never GPS.**" Gap G1.2. Review: [`feature-sunset-place.md`](../reviews/feature-sunset-place.md).
Builds on [`sun.md`](sun.md).
---
## 1. Why and what, in the player's terms
The first time the player opens the garden, under the name, it asks one quiet question:
**Where do you want your sunset?** A box to type a town, and below it a way to say *not now*.
- **Typing a town** shows matching towns at once, with no network: *Brno*, *Praha*, *plzen* all
work. Choosing one says, in the garden, **"Tonight the sun sets at 7:29 PM in Brno."**
- **Not now** uses a guess from the device's clock: in Prague's time zone, Prague. The garden says
so: the line ends with *a guess from this device's time zone*. A player who travels gets the guess
for wherever their phone's clock is.
- **Change town** is always there, under the line. Choosing again replaces the town; nothing else
changes.
- **After the sunset** the line speaks of tomorrow's. **In the far north** it speaks of the lowest
light, or of the noon twilight (`sun.md` D4).
- **The town stays on this device.** It is the only place Rosea knows about the player, and it never
leaves. If the device will not keep it (a private window that blocks storage), the garden still
shows the sunset and says, calmly, that it will ask again next time.
What it never does: ask for GPS, look up an address, guess from the network, or say anything about a
missed sunset.
## 2. Technical architecture
```mermaid
flowchart LR
subgraph app["apps/rosea"]
main["App.svelte<br/>device zone, now, wiring"]
end
subgraph ui["packages/ui"]
shell["Shell.svelte"] --> ask["SunsetPlace.svelte<br/>the question and the search"]
shell --> line["SunsetLine.svelte<br/>tonight's sunset"]
end
subgraph content["packages/content"]
guess["places/guess.ts<br/>zone-guesses.json (25 KB)"]
towns["places/places.ts<br/>places.json (496 KB, loaded on demand)"]
end
subgraph storage["packages/storage (new)"]
profile["profile store<br/>sunset place"]
end
subgraph engine["packages/engine"]
next["sun.nextInvitation(now, place)"]
day["time.addDays / localDay"]
end
main --> shell
main -->|"guessTown(zone)"| guess
main -->|"import() on first search"| towns
main -->|"load / save"| profile
line --> next --> day
build["scripts/build-places.ts<br/>run by hand"] -.-> guess & towns
```
- **`@rosea/content/places`** — `searchTowns(query)`: accent- and case-blind, by English name,
local name (*Praha*) and Latin-script language names; best match first, then the larger town;
*"Sydney, Canada"* narrows by country or region. Imported dynamically, so the garden does not
carry 7,342 towns.
- **`@rosea/content/guess`** — `guessTown(zone)`: the largest town in that zone, or the zone's own
location from the time zone database. Keyed by the names browsers report (`Asia/Calcutta`) as well
as the database's (`Asia/Kolkata`). `UTC` and `Etc/*` guess nothing.
- **`@rosea/storage`** — Dexie over the IndexedDB database `rosea`. One store so far, `profile`,
holding `sunsetPlace`: either `{ kind: 'town', town }` or `{ kind: 'device-zone' }`. A record of
the wrong shape reads as *no choice yet*, with a warning in the console.
- **`@rosea/engine`** — `nextInvitation(now, place)`: the first invitation at or after now, checking
yesterday, today and tomorrow (Reykjavík, 00:02 in June). `addDays` for calendar steps.
- **`@rosea/ui`** — renders. It receives the device zone, the clock, the guess, a search function
and load/save as props; it imports neither content nor storage (CLAUDE.md §2 dependency
direction).
### Decisions
| # | Decision | Why |
|:--|:--|:--|
| P1 | **Natural Earth's populated places** (public domain), 7,342 towns. Downloaded by hand with the author's approval; only the derived JSON is committed. | The only public-domain town list with time zones. GeoNames is better but CC BY, which would need an attribution line in the product. |
| P2 | **Natural Earth's time zones are cross-checked, not trusted.** A town keeps its zone only if its clock is identical all through 2026 to one of its country's zones in the IANA database and fits its longitude (within 3.5 h, across the date line). Otherwise the five nearest trusted towns in the same country vote; with none, the country's nearest zone location. 1,205 towns were corrected. | Measured: Prague was *America/Chicago*, Cardiff *Australia/Sydney*, Sydney had none. A wrong zone shows the right sunset at the wrong clock time. |
| P3 | The guess is the **largest town in the device's zone**. | Recognisable ("Prague"), and the zone is all the device tells. |
| P4 | *Not now* stores `device-zone`, not a town. | The guess then follows the phone's clock when the player travels. |
| P5 | The town list loads **on first search**, as its own precached chunk. | 208 KB compressed is too much to parse on every open of a quiet garden. Offline it is already cached. |
| P6 | The time is shown in the **town's** zone, in the device's locale format. | It is the clock the player will see out there. |
| P7 | Storage failing is **not an error page**: the choice lives for the session and the garden says it will ask again. | CLAUDE.md §1: network and device features degrade to a calm state with an explanation. |
| P8 | `navigator.storage.persist()` is **not** called yet. | Firefox shows a prompt; asking for it on choosing a town would be strange. It belongs to G0.11 (eviction), with export-my-rose. |
## 3. Risk analysis
| Risk | Answer |
|:--|:--|
| **Location** — the chosen town is where the player lives, near enough. | It is stored only in this device's IndexedDB. Nothing in this feature makes a request: the e2e test asserts no request leaves the origin while searching and choosing. Never GPS, never IP. |
| **A wrong clock** sends someone out an hour early or late. | P2, and a test that every town's clock fits its longitude; the known bad zones are pinned by name. Residual: a town Natural Earth filed under a *same-country, same-looking* wrong zone (e.g. Dunhuang, Gansu, under Xinjiang time by its neighbours' vote) is not caught. Stated in the review. |
| **Feeling worse** — a question on the first screen can feel like a demand. | It is skippable in one tap, the skip still gives a sunset, and nothing ever counts or mentions a missed sunset. |
| **Feeling judged for where one lives** — a small town not in the list. | The empty search says *"A larger one nearby will do."*, never *not found* as an error. |
| **Reachability** | None. The town is never shared. |
## 4. Gap analysis and the designed solution
| Gap | Solution | State |
|:--|:--|:--|
| G1.2: no way to choose a town, no guess, no sunset on screen | This feature | Built |
| G0.15: `packages/storage` deferred until its first feature | `@rosea/storage` with the `profile` store | Built |
| G0.11: eviction — `persist()`, export-my-rose | Not here (P8) | Open |
| Czech names for towns (*Vídeň*) | Natural Earth has no Czech column; local names cover *Praha*, *Wien* | Open, with Czech copy |
| Planetary twins of the sunset (the in-game sunset, the chair) | Phase 1, later | Open |
## 5. Verification matrix
| Case | Kind | Where |
|:--|:--|:--|
| 7,342 towns, every zone valid, every clock fits its longitude; Prague, Cardiff, Sydney, Anchorage, Kryvyi Rih, Apia, Pristina keep the right zone | unit | `content/test/places.test.ts` |
| Search by English, local and accent-free names; larger first; comma narrows; empty and unknown are `[]` | unit | same |
| Guess for 7 zones including browser names; UTC guesses nothing; every zone Intl knows is covered | unit | same |
| `nextInvitation`: today before sunset, tomorrow after; Reykjavík after midnight; never past, ≤ 48 h, nothing earlier in between | unit, property | `engine/test/sun.test.ts` |
| `addDays` across DST, years, leap days; inverse property | unit, property | `engine/test/localDay.test.ts` |
| Storage: nothing saved reads `null`; town and device-zone round-trip; a malformed record reads `null` with a warning; a database that cannot open rejects | unit (fake-indexeddb) | `storage/test/profile.test.ts` |
| UI: asks when nothing is saved; search lists towns; choosing shows the line; *not now* shows the guess and says so; tomorrow after sunset; polar wording; storage failure says it will ask again; change and keep | unit (testing-library) | `ui/test/sunset.test.ts` |
| Built app: choose Brno, see Brno's sunset at the time the engine computes, reload and it is still Brno; nothing requested from another origin; no axe violations | e2e | `e2e/shell.spec.ts` |
| Offline: choose a town, close the server, reload: the town and the line survive | offline | `e2e/offline.spec.ts` |
+2 -2
View File
@@ -10,9 +10,9 @@ and **how to apply it**.
| `architecture.md` | none yet | Layering, ownership, seams. | | `architecture.md` | none yet | Layering, ownership, seams. |
| `design.md` | none yet | Wording, silence, empty states. | | `design.md` | none yet | Wording, silence, empty states. |
| [`art.md`](art.md) | 2 | The image pipeline. | | [`art.md`](art.md) | 2 | The image pipeline. |
| [`code.md`](code.md) | 2 | TypeScript, Svelte, async ordering, Rust. | | [`code.md`](code.md) | 3 | TypeScript, Svelte, async ordering, Rust. |
| [`technical.md`](technical.md) | 5 | The browser and the build as platforms. | | [`technical.md`](technical.md) | 5 | The browser and the build as platforms. |
| [`testing.md`](testing.md) | 6 | What makes a test worth having, and how a passing test lies. | | [`testing.md`](testing.md) | 7 | What makes a test worth having, and how a passing test lies. |
| `privacy.md` | none yet | What could leave the device or make a person findable. (The geocell finding is in the review, not here: it was caught before it cost anything.) | | `privacy.md` | none yet | What could leave the device or make a person findable. (The geocell finding is in the review, not here: it was caught before it cost anything.) |
| [`process.md`](process.md) | 2 | Workflow, commits, credentials, honesty about what shipped. | | [`process.md`](process.md) | 2 | Workflow, commits, credentials, honesty about what shipped. |
+15
View File
@@ -35,3 +35,18 @@ condition that returns early hides every read after it.
**How to apply it.** In an effect, read the state you depend on before any early **How to apply it.** In an effect, read the state you depend on before any early
return or `&&` (`const target = heading; if (moved) target?.focus();`). Test the return or `&&` (`const target = heading; if (moved) target?.focus();`). Test the
re-run, not just the first run. re-run, not just the first run.
## Svelte 5 state is a Proxy, and IndexedDB cannot clone a Proxy
**What happened.** On 2026-11-02 the sunset town was never saved in a real browser. The
search results lived in `$state`, which wraps objects in a Proxy. The town passed to
`save` was that Proxy, and IndexedDB's structured clone threw `DataCloneError`. Every
unit test passed. The e2e suite found it: after a reload, the garden asked again.
**Why it bit.** Anything that crosses a structured-clone boundary (IndexedDB,
`postMessage`, `BroadcastChannel`, `structuredClone`) refuses a Proxy, and Svelte 5
hands out Proxies wherever state is deep.
**How to apply it.** At every storage or messaging boundary, write a plain copy built
field by field (in `@rosea/storage`, the same shape check used on reading). Keep lists
that are only passed along as `$state.raw`. Test the boundary with `new Proxy(value, {})`.
+15
View File
@@ -87,3 +87,18 @@ feature lands, for a reason that has nothing to do with the feature.
**How to apply it.** For a "does not exist" example, pick a name no plan will ever add (an owl **How to apply it.** For a "does not exist" example, pick a name no plan will ever add (an owl
in a game with a fox, `owl-sheet`), never the next item on the roadmap. in a game with a fox, `owl-sheet`), never the next item on the roadmap.
## A fake that does not do what the real thing refuses hides the bug
**What happened.** The UI tests for the sunset town used a fake `save` that pushed the
value into an array. The real save goes to IndexedDB, which clones the value and refuses
a Proxy. The fake never cloned, so 10 UI tests passed while saving was broken in every
browser (`code.md`). The same feature's e2e tests then raced the IndexedDB commit by
reloading milliseconds after a click, and passed or failed on alternate runs.
**Why it bit.** A fake is a claim about the real dependency. When the real one rejects
inputs, a fake that accepts everything tests a different program.
**How to apply it.** A fake for a boundary does the boundary's checks: a storage fake
calls `structuredClone` on what it is given. An e2e test that reloads after a write first
waits for the write to be readable (`e2e/stored.ts`), never for the screen alone.
+1 -1
View File
@@ -37,7 +37,7 @@ database on all 28 days.
| 2 | Correctness | The first draft derived the UTC date back from the noon instant. Near 180° the noon falls on the next UTC date, which would move sunrise and sunset by a whole day. Spotted on re-reading, before any test ran. | **Fixed**: the date is passed in. Drill 5 shows the property tests now catch it. | | 2 | Correctness | The first draft derived the UTC date back from the noon instant. Near 180° the noon falls on the next UTC date, which would move sunrise and sunset by a whole day. Spotted on re-reading, before any test ran. | **Fixed**: the date is passed in. Drill 5 shows the property tests now catch it. |
| 3 | Correctness | fast-check found a day with no solar noon: at 179.9° W on UTC, noon crosses midnight in late December. | **Defined (D8)** and pinned by a unit test. No real zone is twelve hours off the sun, so the properties use zones that follow longitude. | | 3 | Correctness | fast-check found a day with no solar noon: at 179.9° W on UTC, noon crosses midnight in late December. | **Defined (D8)** and pinned by a unit test. No real zone is twelve hours off the sun, so the properties use zones that follow longitude. |
| 4 | Correctness | Near the edge of polar day or night the hour angle can leave its range during refinement. | **Clamped (D5).** Accuracy on those few days is not measured: no golden day sits at the edge. Said here and in *not verified*. | | 4 | Correctness | Near the edge of polar day or night the hour angle can leave its range during refinement. | **Clamped (D5).** Accuracy on those few days is not measured: no golden day sits at the edge. Said here and in *not verified*. |
| 5 | Soul | Where the sun never sets or never rises, "every day at sunset" would leave a person with no invitation for months. | **Fixed (D4)**: the lowest light in polar day, noon twilight in polar night. The second is an assumption put to the author (Q10). | | 5 | Soul | Where the sun never sets or never rises, "every day at sunset" would leave a person with no invitation for months. | **Fixed (D4)**: the lowest light in polar day, noon twilight in polar night. The author confirmed the second on 2026-11-01 (Q10). |
| 6 | Soul | A DST change could make the game look as if the sunset "moved" because of the player, or move the rose's sentence to another day. | The engine works in instants (D3); the day comes only from `localDay`. Tested on all six DST days in the fixture. | | 6 | Soul | A DST change could make the game look as if the sunset "moved" because of the player, or move the rose's sentence to another day. | The engine works in instants (D3); the day comes only from `localDay`. Tested on all six DST days in the fixture. |
| 7 | Privacy | The golden script calls a US government API with coordinates. | Only by hand, only for six public city centres, never in a test or the app. The tests read the recorded file. | | 7 | Privacy | The golden script calls a US government API with coordinates. | Only by hand, only for six public city centres, never in a test or the app. The tests read the recorded file. |
| 8 | Privacy | A sunset time narrows down where someone is. | It never leaves the device: the module has no I/O and the purity rule forbids any. Phase 4 must never send it (CLAUDE.md §4). | | 8 | Privacy | A sunset time narrows down where someone is. | It never leaves the device: the module has no I/O and the purity rule forbids any. Phase 4 must never send it (CLAUDE.md §4). |
+56
View File
@@ -0,0 +1,56 @@
# Review — `feature/sunset-place`
Adversarial self-review (CLAUDE.md §5.3). Analysis: [`features/sunset-place.md`](../features/sunset-place.md).
Reviewed 2026-11-02 on Node 22.11.0, Windows 10. There is no PR: the only remote is Gitea.
## Gates — counts, not exit codes
| Gate | Result |
|:--|:--|
| `pnpm lint` | exit 0 (after finding 6) |
| `pnpm typecheck` | exit 0, `@rosea/storage` included; `svelte-check` 0 errors, 0 warnings |
| `pnpm test` | **299 passed**: schema 15, **storage 18 (new)**, content 71 (+24), art-prep 56, engine 113 (+11), ui 26 (+10) |
| `pnpm test:e2e` | **10 passed** (+3), against the built app |
| `pnpm test:offline` | **1 passed**, now choosing a town online and changing it offline |
| `pnpm lint:copy` | 15 files, 0 problems |
| `pnpm validate:library` | 13 of 13 fixtures rejected |
**The app changed** (CLAUDE.md §5.4): the garden now asks where the sunset is and shows it. The
bundle was rebuilt by the e2e and offline runs. It is **not deployed**: there is no host yet (G0.13).
**Stable.** After finding 2, the offline suite passed 3 runs of 3 and e2e 2 of 2 in a row.
## Bug drills — each put back once
| Put back | Result |
|:--|:--|
| Storage writes the caller's object, not a plain copy | CAUGHT: the Proxy test |
| The zone guess reads inherited keys (`constructor`) | CAUGHT |
| Search without accent folding | CAUGHT, by the normalise test only: *plzen* still found Plzeň through Natural Earth's ASCII name, a second path |
| `nextInvitation` skips yesterday | CAUGHT: 2 (Reykjavík after midnight, the property) |
| "Tomorrow" said on the same day | CAUGHT: 2 |
| A failed save goes unmentioned | CAUGHT |
## Findings
| # | Area | Finding | Resolution |
|:--|:--|:--|:--|
| 1 | Correctness | **Saving never worked in a browser.** The UI's towns lived in Svelte 5 `$state`, which wraps them in a Proxy; IndexedDB cannot clone a Proxy and threw `DataCloneError`. Every unit test passed, because the fake `save` only pushed into an array. Found by e2e: after a reload the garden asked again. | **Fixed twice**: storage writes a plain copy built by its own shape check (and refuses a malformed one), and the results list is `$state.raw`. A storage test saves a Proxy. Lessons: `code.md`, `testing.md`. |
| 2 | Test honesty | The tests reloaded or closed the tab milliseconds after the click, racing the IndexedDB commit; the offline suite passed and failed on alternate runs. | **Fixed**: `e2e/stored.ts` waits until the town is in IndexedDB before a reload or close. |
| 3 | Correctness | **Natural Earth's time zones are wrong where it matters**: Prague *America/Chicago*, Cardiff *Australia/Sydney*, Anchorage *America/Juneau*, Sydney none, and 1,183 towns none. A nearest-zone fallback then made its own errors: southern Ukraine on Moscow time (Simferopol), Gansu on Xinjiang time. | **Fixed (P2)**: identical-clock check, longitude fit across the date line, neighbour vote, nearest zone location last. The cases are pinned by name in `places.test.ts`, and every town's clock is checked against its longitude. |
| 4 | Correctness | Browsers report CLDR zone names (`Asia/Calcutta`, `Europe/Kiev`), not always the tz database's. A guess table keyed only by the database's names would guess nothing in Kolkata. | **Fixed**: the guesses are also keyed by the name Intl resolves to; a test checks every zone Intl knows. |
| 5 | Correctness | Tonga and Samoa (UTC+13 at 175° W) were dropped by a longitude check that did not wrap. | **Fixed**; Apia is pinned. |
| 6 | Process | The shell turned ` ` in a heredoc into the character itself; lint caught it (`no-irregular-whitespace`). | **Fixed** with a plain `\s+`. |
| 7 | Privacy | The town is where the player lives, near enough. | It is written only to this device's IndexedDB. The e2e test asserts that searching and choosing request nothing from another origin, and that the town list came from this origin. No GPS, no IP, no lookup. |
| 8 | Privacy | The build downloaded datasets. | By hand, with the author's approval, into the session's scratch folder; only the derived JSON is committed. Public domain both. |
| 9 | Soul | A question on the first screen can feel like a demand, and a small town not found like a judgment. | One tap skips it and still gives a sunset; an empty search says *"A larger one nearby will do."* No copy mentions a missed sunset. |
| 10 | Soul | A guess shown as fact could send someone out at the wrong time. | The guessed line says it is a guess, and *Change town* is always under it. |
| 11 | Correctness | Not verified: a town Natural Earth filed under a wrong zone **of its own country with the same clock rules** (Dunhuang, Gansu, voted onto Xinjiang time by its neighbours). | **Open, stated.** The longitude check cannot see it. Rare, and the player can choose a neighbouring town. |
| 12 | Scope | `navigator.storage.persist()` is not called; a drifted-away player on iOS can lose the town (CLAUDE.md §8). | **Deferred to G0.11** with export-my-rose (P8). Losing the town only means being asked again. |
## What was not verified
- A real phone, a real install, Safari or Firefox: only Chromium under Playwright.
- A private window that refuses IndexedDB in a real browser: covered by unit tests with a rejecting store.
- Two tabs choosing different towns at once: last write wins, and the other tab shows its own until reload.
- Czech town names (*Vídeň*): Natural Earth has none.
+3 -2
View File
@@ -115,8 +115,8 @@ feed of anything.
## 2. Repository layout ## 2. Repository layout
Phase 0 scaffolded `schema`, `engine`, `content`, `ui`, `apps/rosea`, `tools/art-prep` and `art/`. Phase 0 scaffolded `schema`, `engine`, `content`, `ui`, `apps/rosea`, `tools/art-prep` and `art/`;
`storage`, `identity`, `sync` and `services/lucerna` arrive with their first feature, because an Phase 1 added `storage` (the `profile` store). `identity`, `sync` and `services/lucerna` arrive with their first feature, because an
empty package has a test suite that runs nothing ([`phase0-workspace.md`](.agents/features/phase0-workspace.md) D1). empty package has a test suite that runs nothing ([`phase0-workspace.md`](.agents/features/phase0-workspace.md) D1).
``` ```
@@ -222,6 +222,7 @@ pnpm validate:library # every hope sentence; fixtures must FA
pnpm lint:copy # forbidden words and names (§5.6) pnpm lint:copy # forbidden words and names (§5.6)
pnpm art:board # prompts + stand-ins -> tools/art-prep/dist/board/ (docs/ART.md) pnpm art:board # prompts + stand-ins -> tools/art-prep/dist/board/ (docs/ART.md)
pnpm art:accept <id> <file> # an accepted picture -> art/final/*.webp, sheets cut pnpm art:accept <id> <file> # an accepted picture -> art/final/*.webp, sheets cut
tsx scripts/build-places.ts <folder> # rebuilds the town list from downloaded Natural Earth + tzdb (by hand)
# Not yet — they arrive with their first feature: # Not yet — they arrive with their first feature:
cargo test --manifest-path services/lucerna/Cargo.toml # Phase 4 onward cargo test --manifest-path services/lucerna/Cargo.toml # Phase 4 onward
+11 -4
View File
@@ -12,8 +12,8 @@ Rewritten at the end of each session (CLAUDE.md §5.1).
Gitea hashes match. Analysis: [`.agents/features/phase0-workspace.md`](.agents/features/phase0-workspace.md). Gitea hashes match. Analysis: [`.agents/features/phase0-workspace.md`](.agents/features/phase0-workspace.md).
Review, with counts and the mutation results: Review, with counts and the mutation results:
[`.agents/reviews/feature-phase0-workspace.md`](.agents/reviews/feature-phase0-workspace.md). [`.agents/reviews/feature-phase0-workspace.md`](.agents/reviews/feature-phase0-workspace.md).
- **Gates:** all pass on this machine. Unit tests: 236 (schema 15, content 47, - **Gates:** all pass on this machine. Unit tests: 299 (schema 15, storage 18, content 71,
art-prep 56, engine 102, ui 16). E2E: 7. Offline: 1. `lint:copy`: 12 files, 0 problems. art-prep 56, engine 113, ui 26). E2E: 10. Offline: 1. `lint:copy`: 15 files, 0 problems.
`validate:library`: 13 of 13 fixtures rejected. `validate:library`: 13 of 13 fixtures rejected.
- **Built, not deployed:** there is no host yet. - **Built, not deployed:** there is no host yet.
- **Roadmap and gameplay docs:** `docs/ROADMAP.md` and `docs/GAMEPLAY.md` are on - **Roadmap and gameplay docs:** `docs/ROADMAP.md` and `docs/GAMEPLAY.md` are on
@@ -42,6 +42,15 @@ Rewritten at the end of each session (CLAUDE.md §5.1).
The app does not use it yet. Analysis: [`.agents/features/sun.md`](.agents/features/sun.md). The app does not use it yet. Analysis: [`.agents/features/sun.md`](.agents/features/sun.md).
Review: [`.agents/reviews/feature-sun.md`](.agents/reviews/feature-sun.md). Review: [`.agents/reviews/feature-sun.md`](.agents/reviews/feature-sun.md).
- **Where the sunset is (Phase 1):** merged to `main`. The garden asks *Where do you want your
sunset?*: a search over 7,342 public-domain towns on the device, or *Not now*, which guesses
from the device's time zone. The answer is kept in IndexedDB (the new `@rosea/storage`, store
`profile`), and the garden says when tonight's sunset is. Natural Earth's time zones were wrong
for Prague, Cardiff and Anchorage, among others; `scripts/build-places.ts` cross-checks every one
against the tz database. To rebuild the list, download the two sources again (the script's
header says which) and run it. Analysis: [`.agents/features/sunset-place.md`](.agents/features/sunset-place.md).
Review: [`.agents/reviews/feature-sunset-place.md`](.agents/reviews/feature-sunset-place.md).
**Phase 0 is not finished.** The roadmap's Phase 0 is more than the workspace. Its **Phase 0 is not finished.** The roadmap's Phase 0 is more than the workspace. Its
gate needs 60 verified sentences (G0.18) and one illustration through the art gate needs 60 verified sentences (G0.18) and one illustration through the art
pipeline (G0.24). The pipeline and the board are built; the first real picture is not made yet. Also open: a GitHub remote (G0.13). The Letter slot is built (G0.25). pipeline (G0.24). The pipeline and the board are built; the first real picture is not made yet. Also open: a GitHub remote (G0.13). The Letter slot is built (G0.25).
@@ -60,8 +69,6 @@ The notification decision is made: in-app only on the web (G0.26).
and writes `final` back into the row. and writes `final` back into the row.
4. **A GitHub repository** for Pages, and whether it is public (G0.13, G0.23). 4. **A GitHub repository** for Pages, and whether it is public (G0.13, G0.23).
5. **Upgrading Node** to ≥ 22.13 on this machine (G0.20). 5. **Upgrading Node** to ≥ 22.13 on this machine (G0.20).
6. **Q10:** in polar night, should the sunset invitation come at noon, when the twilight is
brightest? The engine assumes yes.
**How this machine works** (not in the code): **How this machine works** (not in the code):
+2
View File
@@ -10,7 +10,9 @@
"typecheck": "svelte-check --threshold error --output human" "typecheck": "svelte-check --threshold error --output human"
}, },
"dependencies": { "dependencies": {
"@rosea/content": "workspace:*",
"@rosea/schema": "workspace:*", "@rosea/schema": "workspace:*",
"@rosea/storage": "workspace:*",
"@rosea/ui": "workspace:*" "@rosea/ui": "workspace:*"
}, },
"devDependencies": { "devDependencies": {
+26 -2
View File
@@ -1,7 +1,31 @@
<script lang="ts"> <script lang="ts">
import { Shell } from '@rosea/ui'; import { guessTown } from '@rosea/content/guess';
import { openProfile } from '@rosea/storage';
import { Shell, type SunsetWiring } from '@rosea/ui';
// Bundled at build time, so the letter is precached and opens offline (letter-slot.md L1). // Bundled at build time, so the letter is precached and opens offline (letter-slot.md L1).
import letter from '../../../docs/LETTER.md?raw'; import letter from '../../../docs/LETTER.md?raw';
// The device's own zone, read here and nowhere else: the engine never asks the
// device anything (CLAUDE.md §2). Only the zone's name; never GPS, never a lookup.
const deviceZone = new Intl.DateTimeFormat().resolvedOptions().timeZone;
const profile = openProfile();
// The town list is large, so it loads on the first search (sunset-place.md P5).
// A failed load is forgotten, so the next keystroke tries again.
let towns: Promise<typeof import('@rosea/content/places')> | undefined;
const loadTowns = (): Promise<typeof import('@rosea/content/places')> =>
(towns ??= import('@rosea/content/places').catch((error: unknown) => {
towns = undefined;
throw error;
}));
const sunset: SunsetWiring = {
guess: guessTown(deviceZone),
search: async (query) => (await loadTowns()).searchTowns(query),
load: () => profile.loadSunsetPlace(),
save: (choice) => profile.saveSunsetPlace(choice),
now: () => Date.now()
};
</script> </script>
<Shell {letter} /> <Shell {letter} {sunset} />
+21 -1
View File
@@ -2,6 +2,7 @@ import { expect, test } from '@playwright/test';
import { PRODUCT_NAME } from '@rosea/schema'; import { PRODUCT_NAME } from '@rosea/schema';
import { en } from '@rosea/ui/copy'; import { en } from '@rosea/ui/copy';
import { startStaticServer } from './static-server.js'; import { startStaticServer } from './static-server.js';
import { storedTown } from './stored.js';
/** /**
* The offline suite. CLAUDE.md §3 describes its full shape: tend the rose, walk * The offline suite. CLAUDE.md §3 describes its full shape: tend the rose, walk
@@ -14,14 +15,22 @@ import { startStaticServer } from './static-server.js';
*/ */
test('the shell opens from the service worker with the server gone', async ({ browser }) => { test('the shell opens from the service worker with the server gone', async ({ browser }) => {
const server = await startStaticServer(); const server = await startStaticServer();
const context = await browser.newContext(); // A fixed place and day, so the sunset line is the same on every run.
const context = await browser.newContext({ timezoneId: 'Europe/Prague', locale: 'en-US' });
let serverOpen = true; let serverOpen = true;
try { try {
const page = await context.newPage(); const page = await context.newPage();
await page.clock.setFixedTime(Date.parse('2026-03-29T12:00:00+02:00'));
await page.goto(server.url); await page.goto(server.url);
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME); await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
// The player answers the sunset question while online (sunset-place.md).
await page.getByRole('searchbox', { name: en.sunset.searchLabel }).fill('brno');
await page.getByRole('button', { name: /^Brno/ }).first().click();
await expect(page.locator('.sun p').first()).toHaveText(/^Tonight the sun sets at .* in Brno\.$/);
await storedTown(page, 'Brno');
// `clientsClaim` makes the FIRST worker control the page that registered it. // `clientsClaim` makes the FIRST worker control the page that registered it.
// Without it, a player who opens the link once and loses signal has nothing. // Without it, a player who opens the link once and loses signal has nothing.
await page.waitForFunction(() => navigator.serviceWorker.controller !== null, null, { timeout: 20_000 }); await page.waitForFunction(() => navigator.serviceWorker.controller !== null, null, { timeout: 20_000 });
@@ -47,13 +56,24 @@ test('the shell opens from the service worker with the server gone', async ({ br
await page.reload(); await page.reload();
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME); await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
await expect(page.getByText(en.shell.preparing)).toBeVisible(); await expect(page.getByText(en.shell.preparing)).toBeVisible();
// The town survived in IndexedDB, and the sun is computed with no network.
await expect(page.locator('.sun p').first()).toHaveText(/^Tonight the sun sets at .* in Brno\.$/);
// Changing the town offline: the town list was precached with the shell.
await page.getByRole('button', { name: en.sunset.change }).click();
await page.getByRole('searchbox').fill('plzen');
await page.getByRole('button', { name: /^Plzeň/ }).first().click();
await expect(page.locator('.sun p').first()).toHaveText(/in Plzeň\.$/);
await storedTown(page, 'Plzeň');
// 2. Close the tab and open a fresh one: a cold start, the shape of a player // 2. Close the tab and open a fresh one: a cold start, the shape of a player
// coming back days later with no signal. // coming back days later with no signal.
await page.close(); await page.close();
const again = await context.newPage(); const again = await context.newPage();
await again.clock.setFixedTime(Date.parse('2026-03-29T12:00:00+02:00'));
await again.goto(server.url); await again.goto(server.url);
await expect(again.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME); await expect(again.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
await expect(again.locator('.sun p').first()).toHaveText(/in Plzeň\.$/);
// 3. A deep link inside the scope falls back to the shell, not an error page. // 3. A deep link inside the scope falls back to the shell, not an error page.
await again.goto(`${server.url}somewhere/deeper`); await again.goto(`${server.url}somewhere/deeper`);
+55
View File
@@ -3,8 +3,11 @@ import { expect, test, type Page } from '@playwright/test';
import { PRODUCT_NAME } from '@rosea/schema'; import { PRODUCT_NAME } from '@rosea/schema';
import { en } from '@rosea/ui/copy'; import { en } from '@rosea/ui/copy';
import { parseLetter } from '@rosea/ui/letter'; import { parseLetter } from '@rosea/ui/letter';
import { nextInvitation } from '@rosea/engine';
import { searchTowns } from '@rosea/content/places';
import { readFileSync } from 'node:fs'; import { readFileSync } from 'node:fs';
import { BASE, startStaticServer, type StaticServer } from './static-server.js'; import { BASE, startStaticServer, type StaticServer } from './static-server.js';
import { storedTown } from './stored.js';
let server: StaticServer; let server: StaticServer;
@@ -127,3 +130,55 @@ test('the Letter: no way to it while empty, and it opens from the garden once wr
await page.getByRole('link', { name: en.letter.back }).click(); await page.getByRole('link', { name: en.letter.back }).click();
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME); await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
}); });
// --- Where the sunset is (.agents/features/sunset-place.md) ------------------
test.describe('the sunset place, in Prague\'s time zone at noon on 29 March 2026', () => {
test.use({ timezoneId: 'Europe/Prague', locale: 'en-US' });
const NOON = Date.parse('2026-03-29T12:00:00+02:00');
/** Browsers and Node both put a narrow no-break space before PM; compare words, not spaces. */
const spaced = (s: string): string => s.replace(/\s+/g, ' ');
test('first open asks; choosing Brno shows the sunset the engine computes; a reload keeps it', async ({ page }) => {
await page.clock.setFixedTime(NOON);
const { requests } = await open(page);
await expect(page.getByRole('heading', { level: 2, name: en.sunset.question })).toBeVisible();
await page.getByRole('searchbox', { name: en.sunset.searchLabel }).fill('brno');
await page.getByRole('button', { name: /^Brno/ }).first().click();
const brno = searchTowns('brno')[0]!;
const { at } = nextInvitation(NOON, brno);
const time = new Intl.DateTimeFormat('en-US', { hour: 'numeric', minute: '2-digit', timeZone: brno.timeZone }).format(at);
const line = page.locator('.sun p').first();
await expect(line).toHaveText(/in Brno\.$/);
expect(spaced((await line.textContent()) ?? '')).toBe(spaced(en.sunset.tonight(time, 'Brno')));
await storedTown(page, 'Brno');
await page.reload();
await expect(line).toHaveText(/in Brno\.$/);
await expect(page.getByRole('searchbox')).toHaveCount(0);
// Searching and choosing loaded the town list from this origin and nothing else.
expect(requests.filter((url) => !url.startsWith(server.origin + '/'))).toEqual([]);
expect(requests.some((url) => /\/assets\/places-.*\.js$/.test(url))).toBe(true);
});
test('"not now" guesses Prague from the device\'s zone and says it is a guess', async ({ page }) => {
await page.clock.setFixedTime(NOON);
await open(page);
await page.getByRole('button', { name: en.sunset.skip('Prague') }).click();
await expect(page.locator('.sun p').first()).toHaveText(/^Tonight the sun sets at .* in Prague\.$/);
await expect(page.getByText(en.sunset.guessed)).toBeVisible();
});
test('the question and the answer have no accessibility violations', async ({ page }) => {
await page.clock.setFixedTime(NOON);
await open(page);
await page.getByRole('searchbox').fill('pra');
await expect(page.getByRole('status')).not.toHaveText('');
expect((await new AxeBuilder({ page }).analyze()).violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
await page.getByRole('button', { name: /^Prague/ }).first().click();
await expect(page.locator('.sun')).toBeVisible();
expect((await new AxeBuilder({ page }).analyze()).violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
});
});
+36
View File
@@ -0,0 +1,36 @@
import type { Page } from '@playwright/test';
/**
* Waits until the player's sunset town is written to IndexedDB. The garden shows a
* choice before the write commits, so a test that reloads or closes the tab at once
* races the write: it passed and failed on alternate runs before this existed.
*/
export async function storedTown(page: Page, name: string): Promise<void> {
await page.waitForFunction(
(expected) =>
new Promise<boolean>((resolve) => {
const req = indexedDB.open('rosea');
req.onerror = () => resolve(false);
req.onsuccess = () => {
const db = req.result;
if (!db.objectStoreNames.contains('profile')) {
db.close();
resolve(false);
return;
}
const get = db.transaction('profile').objectStore('profile').get('sunsetPlace');
get.onsuccess = () => {
db.close();
const value = get.result as { value?: { town?: { name?: string } } } | undefined;
resolve(value?.value?.town?.name === expected);
};
get.onerror = () => {
db.close();
resolve(false);
};
};
}),
name,
{ timeout: 5_000 }
);
}
+1
View File
@@ -25,6 +25,7 @@
"@eslint/js": "9.39.5", "@eslint/js": "9.39.5",
"@playwright/test": "1.62.1", "@playwright/test": "1.62.1",
"@rosea/content": "workspace:*", "@rosea/content": "workspace:*",
"@rosea/engine": "workspace:*",
"@rosea/schema": "workspace:*", "@rosea/schema": "workspace:*",
"@rosea/ui": "workspace:*", "@rosea/ui": "workspace:*",
"@types/node": "22.20.1", "@types/node": "22.20.1",
+3 -1
View File
@@ -8,7 +8,9 @@
"types": "./src/index.ts", "types": "./src/index.ts",
"exports": { "exports": {
".": "./src/index.ts", ".": "./src/index.ts",
"./validate": "./src/validator.ts" "./validate": "./src/validator.ts",
"./places": "./src/places/places.ts",
"./guess": "./src/places/guess.ts"
}, },
"scripts": { "scripts": {
"build": "tsc -p tsconfig.json", "build": "tsc -p tsconfig.json",
+22
View File
@@ -0,0 +1,22 @@
/**
* The guess when a player skips choosing a town: the largest town in the device's
* time zone, or the zone's own location from the time zone database (ROADMAP Phase 1:
* "if skipped, it is guessed from the device time zone"). Never GPS, never a lookup.
* Small, so the garden can load it without the town list.
*/
import data from './zone-guesses.json' with { type: 'json' };
import type { Town } from './places.js';
type Guess = readonly [name: string, country: string, lat: number, lon: number];
const guesses = data.guesses as unknown as Readonly<Record<string, Guess>>;
/**
* A town for `timeZone`, the name the device reports (Intl's, so Asia/Calcutta and
* Asia/Kolkata both work). Null for a zone that names no place, such as UTC: then
* the player has to choose.
*/
export function guessTown(timeZone: string): Town | null {
const g = Object.hasOwn(guesses, timeZone) ? guesses[timeZone] : undefined;
if (!g) return null;
return { name: g[0], region: '', country: g[1], lat: g[2], lon: g[3], timeZone };
}
File diff suppressed because one or more lines are too long
+85
View File
@@ -0,0 +1,85 @@
/**
* The towns a player can choose for the sunset (.agents/features/sunset-place.md).
* Data: places.json, built by scripts/build-places.ts from Natural Earth and the
* IANA time zone database, both public domain. Everything here runs on the device;
* a search never leaves it.
*
* Large (about 400 KB): the app imports this module only when the search opens.
* The garden's guess lives in ./guess.ts, which does not load it.
*/
import data from './places.json' with { type: 'json' };
/** A town a player may choose. The only location Rosea ever knows (CLAUDE.md §5.6 rule 6). */
export interface Town {
readonly name: string;
/** The province, state or region, or '' when it adds nothing. */
readonly region: string;
readonly country: string;
readonly lat: number;
readonly lon: number;
readonly timeZone: string;
}
type Row = readonly [string, string, string, number, number, number, number, number];
const rows = data.places as unknown as readonly Row[];
const town = (r: Row): Town => ({
name: r[0],
region: r[2],
country: data.countries[r[3]] ?? '',
lat: r[4],
lon: r[5],
timeZone: data.zones[r[6]] ?? 'UTC'
});
/** Lower case, no accents, words separated by single spaces: "Plzeň" and "plzen" meet. */
export function normalize(s: string): string {
return s.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim();
}
let index: { names: string[]; others: string[]; where: string[] } | undefined;
function searchIndex(): NonNullable<typeof index> {
index ??= {
names: rows.map((r) => normalize(r[0])),
others: rows.map((r) => normalize(r[1].replace(/\|/g, ' | '))),
where: rows.map((r) => normalize(`${r[2]} ${data.countries[r[3]] ?? ''}`))
};
return index;
}
/** How well a town's names match: lower is better, Infinity is no match. */
function score(q: string, name: string, others: string): number {
if (name === q) return 0;
if (name.startsWith(q)) return 1;
if (name.includes(` ${q}`)) return 2;
if (others.split(' | ').some((o) => o === q)) return 3;
if (others.split(' | ').some((o) => o.startsWith(q) || o.includes(` ${q}`))) return 4;
return Infinity;
}
/**
* Towns matching what the player typed, best first; among equals, the larger town
* first. "Sydney, Canada" narrows by region or country after a comma.
*/
export function searchTowns(query: string, limit = 8): Town[] {
const [namePart = '', wherePart = ''] = query.split(',');
const q = normalize(namePart);
const w = normalize(wherePart);
if (q === '') return [];
const { names, others, where } = searchIndex();
const hits: { i: number; s: number }[] = [];
for (let i = 0; i < rows.length; i++) {
const s = score(q, names[i]!, others[i]!);
if (s === Infinity) continue;
if (w && !where[i]!.split(' ').some((word) => word.startsWith(w.split(' ')[0]!)) && !where[i]!.includes(w)) continue;
hits.push({ i, s });
}
// Rows are stored largest first, so sorting by score alone keeps size order within a score.
hits.sort((a, b) => a.s - b.s || a.i - b.i);
return hits.slice(0, limit).map((h) => town(rows[h.i]!));
}
/** Every town, for checks over the whole list. */
export function allTowns(): Town[] {
return rows.map(town);
}
File diff suppressed because one or more lines are too long
+117
View File
@@ -0,0 +1,117 @@
import { describe, expect, it } from 'vitest';
import { guessTown } from '../src/places/guess.js';
import { allTowns, normalize, searchTowns, type Town } from '../src/places/places.js';
const towns = allTowns();
const first = (q: string): Town | undefined => searchTowns(q)[0];
function standardOffset(zone: string): number {
const f = new Intl.DateTimeFormat('en-US', { timeZone: zone, timeZoneName: 'longOffset' });
const at = (ms: number): number => {
const m = /GMT([+-])(\d\d):(\d\d)/.exec(f.formatToParts(ms).find((p) => p.type === 'timeZoneName')?.value ?? '');
return m ? (m[1] === '-' ? -1 : 1) * (Number(m[2]) + Number(m[3]) / 60) : 0;
};
return Math.min(at(Date.UTC(2026, 0, 15)), at(Date.UTC(2026, 6, 15)));
}
describe('the town list', () => {
it('holds every Natural Earth town, each with a position and a zone Intl knows', () => {
expect(towns).toHaveLength(7342);
const zones = new Set(towns.map((t) => t.timeZone));
for (const z of zones) expect(() => new Intl.DateTimeFormat('en', { timeZone: z })).not.toThrow();
for (const t of towns) {
expect(Math.abs(t.lat)).toBeLessThanOrEqual(90);
expect(Math.abs(t.lon)).toBeLessThanOrEqual(180);
expect(t.name).not.toBe('');
expect(t.name).not.toContain('�');
}
});
it("every town's clock fits its longitude within 3.5 hours, across the date line too", () => {
const off = new Map<string, number>();
const bad = towns.filter((t) => {
if (!off.has(t.timeZone)) off.set(t.timeZone, standardOffset(t.timeZone));
const drift = ((((off.get(t.timeZone)! - t.lon / 15) % 24) + 36) % 24) - 12;
return Math.abs(drift) > 3.5;
});
expect(bad.map((t) => `${t.name} ${t.timeZone}`)).toEqual([]);
});
// Natural Earth's own zones were wrong for these; the build corrects them.
it.each([
['Prague', 'Czechia', 'Europe/Prague'], // Natural Earth: America/Chicago
['Cardiff', 'United Kingdom', 'Europe/London'], // Natural Earth: Australia/Sydney
['Sydney', 'Australia', 'Australia/Sydney'], // Natural Earth: none
['Anchorage', 'United States of America', 'America/Anchorage'], // Natural Earth: America/Juneau
['Kryvyi Rih', 'Ukraine', 'Europe/Kyiv'], // never Simferopol's Moscow time
['Apia', 'Samoa', 'Pacific/Apia'], // UTC+13 at 172° W
['Pristina', 'Kosovo', 'Europe/Belgrade'] // no ISO code in Natural Earth
])('%s, %s, keeps %s', (name, country, zone) => {
const t = towns.find((x) => x.name === name && x.country === country);
expect(t?.timeZone).toBe(zone);
});
});
describe('searchTowns', () => {
it('finds a town by its English name, its local name, or without accents', () => {
expect(first('brno')?.name).toBe('Brno');
expect(first('praha')?.name).toBe('Prague');
expect(first('plzen')?.name).toBe('Plzeň');
expect(first('Plzeň')?.name).toBe('Plzeň');
expect(first('ceske bud')?.name).toBe('České Budějovice');
});
it('puts the larger of two towns with one name first, and a comma narrows by country or region', () => {
const sydneys = searchTowns('sydney');
expect(sydneys[0]?.country).toBe('Australia');
expect(sydneys.some((t) => t.country === 'Canada')).toBe(true);
expect(first('sydney, canada')?.country).toBe('Canada');
expect(first('sydney, nova')?.region).toBe('Nova Scotia');
});
it('an exact name beats a longer one that starts the same', () => {
expect(first('york')?.name).toBe('York');
});
it('nothing typed, or nothing found, is an empty list, never an error', () => {
expect(searchTowns('')).toEqual([]);
expect(searchTowns(' ')).toEqual([]);
expect(searchTowns('zzzzqx')).toEqual([]);
});
it('never returns more than asked', () => {
expect(searchTowns('san', 5)).toHaveLength(5);
});
it('normalize folds case, accents and punctuation', () => {
expect(normalize(' Hradec Králové! ')).toBe('hradec kralove');
expect(normalize("Nuku'alofa")).toBe('nuku alofa');
});
});
describe('guessTown', () => {
it.each([
['Europe/Prague', 'Prague'],
['America/New_York', 'New York City'],
['America/Anchorage', 'Anchorage'],
['Australia/Sydney', 'Sydney'],
['Asia/Kolkata', 'Mumbai'],
['Asia/Calcutta', 'Mumbai'], // the name browsers report
['Europe/Kiev', 'Kyiv'] // likewise
])('%s guesses %s', (zone, name) => {
const t = guessTown(zone);
expect(t?.name).toBe(name);
expect(t?.timeZone).toBe(zone);
});
it('a zone with no place, such as UTC, guesses nothing: the player chooses', () => {
expect(guessTown('UTC')).toBeNull();
expect(guessTown('Etc/GMT+3')).toBeNull();
expect(guessTown('constructor')).toBeNull(); // not a key of a plain object's prototype
});
it('every zone Intl knows has a guess or is a zone of no place', () => {
const missing = Intl.supportedValuesOf('timeZone').filter((z) => guessTown(z) === null && !/^(Etc\/|UTC$|GMT)/.test(z));
expect(missing).toEqual([]);
});
});
+2 -2
View File
@@ -1,2 +1,2 @@
export { isLocalDay, localDay, type LocalDay } from './time/localDay.js'; export { addDays, isLocalDay, localDay, type LocalDay } from './time/localDay.js';
export { invitation, sunDay, type Place, type SunDay } from './sun/sun.js'; export { invitation, nextInvitation, sunDay, type NamedPlace, type Place, type SunDay } from './sun/sun.js';
+28 -3
View File
@@ -11,7 +11,7 @@
* (.agents/features/sun.md D3). The place is a city the player chose, or a guess * (.agents/features/sun.md D3). The place is a city the player chose, or a guess
* from the device's zone: never GPS (CLAUDE.md §5.6 rule 6). * from the device's zone: never GPS (CLAUDE.md §5.6 rule 6).
*/ */
import { isLocalDay, localDay, type LocalDay } from '../time/localDay.js'; import { addDays, isLocalDay, localDay, type LocalDay } from '../time/localDay.js';
export interface Place { export interface Place {
/** Degrees, north positive. */ /** Degrees, north positive. */
@@ -22,6 +22,14 @@ export interface Place {
readonly timeZone: string; readonly timeZone: string;
} }
/** A place with the name the player knows it by: a town they chose, or the guess. */
export interface NamedPlace extends Place {
readonly name: string;
/** Province, state or region, or ''. */
readonly region: string;
readonly country: string;
}
/** /**
* One local day of sun. Sunrise and sunset are the ones around this day's solar * One local day of sun. Sunrise and sunset are the ones around this day's solar
* noon, so tonight's sunset may fall after midnight, on the next local day (D2). * noon, so tonight's sunset may fall after midnight, on the next local day (D2).
@@ -134,10 +142,27 @@ export function sunDay(day: LocalDay, place: Place): SunDay {
}; };
} }
/**
* The next invitation at or after `now`, and the sun's day it belongs to. Yesterday
* is checked first: just after midnight in Reykjavík in June, last evening's sunset
* is still a few minutes away (D2).
*/
export function nextInvitation(now: number, place: Place): { readonly sun: SunDay; readonly at: number } {
if (!Number.isFinite(now)) throw new RangeError(`nextInvitation: now must be a finite instant, got ${String(now)}`);
const today = localDay(now, place.timeZone);
for (const offset of [-1, 0, 1, 2]) {
const sun = sunDay(addDays(today, offset), place);
const at = invitation(sun);
if (at >= now) return { sun, at };
}
// Unreachable: tomorrow's invitation is always after now. Kept so a broken sun fails loudly.
throw new Error(`nextInvitation: no invitation within two days of ${today}`);
}
/** /**
* When the game invites the player outside: the sunset; in polar day the lowest * When the game invites the player outside: the sunset; in polar day the lowest
* light; in polar night noon, when the twilight is brightest (D4, an assumption * light; in polar night noon, when the twilight is brightest (D4; decided by the
* for the author: Q10). * author, Q10).
*/ */
export function invitation(sun: SunDay): number { export function invitation(sun: SunDay): number {
switch (sun.kind) { switch (sun.kind) {
+8
View File
@@ -61,6 +61,14 @@ export function localDay(epochMs: number, timeZone: string): LocalDay {
return day; return day;
} }
/** The calendar day `days` after `day` (before, if negative). A calendar step: no zone, no DST. */
export function addDays(day: LocalDay, days: number): LocalDay {
if (!isLocalDay(day)) throw new RangeError(`addDays: '${day}' is not a LocalDay`);
if (!Number.isInteger(days)) throw new RangeError(`addDays: ${days} is not a whole number of days`);
const [y, m, d] = day.split('-').map(Number) as [number, number, number];
return localDay(Date.UTC(y, m - 1, d + days), 'UTC');
}
/** Whether `value` has the shape of a LocalDay. Does not check that the date exists. */ /** Whether `value` has the shape of a LocalDay. Does not check that the date exists. */
export function isLocalDay(value: string): value is LocalDay { export function isLocalDay(value: string): value is LocalDay {
return LOCAL_DAY.test(value); return LOCAL_DAY.test(value);
+25 -1
View File
@@ -1,6 +1,6 @@
import fc from 'fast-check'; import fc from 'fast-check';
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { isLocalDay, localDay } from '../src/time/localDay.js'; import { addDays, isLocalDay, localDay } from '../src/time/localDay.js';
const at = (iso: string): number => Date.parse(iso); const at = (iso: string): number => Date.parse(iso);
@@ -86,3 +86,27 @@ describe('localDay — properties', () => {
fc.assert(fc.property(instant, zone, (t, z) => localDay(t, z) === localDay(t, z))); fc.assert(fc.property(instant, zone, (t, z) => localDay(t, z) === localDay(t, z)));
}); });
}); });
describe('addDays — a calendar step, no zone', () => {
it.each([
['2026-03-28', 1, '2026-03-29'], // across a DST change: still one day
['2026-12-31', 1, '2027-01-01'],
['2028-02-28', 1, '2028-02-29'], // leap year
['2026-03-01', -1, '2026-02-28'],
['2026-06-21', 0, '2026-06-21']
])('%s + %s = %s', (day, n, expected) => {
expect(addDays(day, n)).toBe(expected);
});
it('refuses a day that is not a LocalDay, and a part of a day', () => {
expect(() => addDays('2026-6-1', 1)).toThrow(/not a LocalDay/);
expect(() => addDays('2026-06-01', 0.5)).toThrow(/whole number/);
});
it('stepping forward and back again returns the same day', () => {
fc.assert(fc.property(fc.integer({ min: 0, max: 3000 }), fc.integer({ min: -400, max: 400 }), (k, n) => {
const day = addDays('2025-01-01', k);
return addDays(addDays(day, n), -n) === day && isLocalDay(addDays(day, n));
}));
});
});
+40 -2
View File
@@ -1,8 +1,8 @@
import fc from 'fast-check'; import fc from 'fast-check';
import { readFileSync } from 'node:fs'; import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { invitation, sunDay, type Place, type SunDay } from '../src/sun/sun.js'; import { invitation, nextInvitation, sunDay, type Place, type SunDay } from '../src/sun/sun.js';
import { localDay } from '../src/time/localDay.js'; import { addDays, localDay } from '../src/time/localDay.js';
/** Recorded by scripts/fetch-sun-golden.ts from the U.S. Naval Observatory. */ /** Recorded by scripts/fetch-sun-golden.ts from the U.S. Naval Observatory. */
interface Row { interface Row {
@@ -205,6 +205,44 @@ describe('sunDay — a clock twelve hours off the sun (D8)', () => {
}); });
}); });
describe('nextInvitation — the one the garden shows', () => {
const prague: Place = { lat: 50.0755, lon: 14.4378, timeZone: 'Europe/Prague' };
const reykjavik: Place = { lat: 64.1466, lon: -21.9426, timeZone: 'Atlantic/Reykjavik' };
it('at noon in Prague it is this evening\'s sunset; after it, tomorrow\'s', () => {
const noon = Date.parse('2026-03-29T12:00:00+02:00');
const today = nextInvitation(noon, prague);
expect(today.sun.day).toBe('2026-03-29');
expect(today.at).toBe(invitation(sunDay('2026-03-29', prague)));
const evening = nextInvitation(today.at + MINUTE, prague);
expect(evening.sun.day).toBe('2026-03-30');
});
it('just after midnight in Reykjavík in June, last evening\'s sunset is still to come', () => {
const lastEvening = sunDay('2026-06-21', reykjavik);
if (lastEvening.kind !== 'sun-sets') throw new Error(lastEvening.kind);
const justAfterMidnight = lastEvening.sunset - 2 * MINUTE;
expect(localDay(justAfterMidnight, reykjavik.timeZone)).toBe('2026-06-22');
expect(nextInvitation(justAfterMidnight, reykjavik).sun.day).toBe('2026-06-21');
});
it('is never in the past, never more than two days ahead, and no earlier invitation lies between', () => {
fc.assert(fc.property(
fc.double({ min: -89, max: 89, noNaN: true }), fc.double({ min: -180, max: 180, noNaN: true }), fc.integer({ min: Date.UTC(2026, 0, 2), max: Date.UTC(2026, 11, 30) }),
(lat, lon, now) => {
const place = zoned(lat, lon);
const { sun, at } = nextInvitation(now, place);
const before = invitation(sunDay(addDays(sun.day, -1), place));
return at >= now && at - now <= 48 * HOUR && before < now;
}
), { numRuns: 400 });
});
it('refuses an instant that is not one', () => {
expect(() => nextInvitation(Number.NaN, prague)).toThrow(/finite instant/);
});
});
describe('sunDay — refusals', () => { describe('sunDay — refusals', () => {
it.each([ it.each([
['2026-02-30', UTC(50, 14), /does not exist/], ['2026-02-30', UTC(50, 14), /does not exist/],
+26
View File
@@ -0,0 +1,26 @@
{
"name": "@rosea/storage",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "Dexie. The ONLY module that touches IndexedDB (CLAUDE.md §2, §4).",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts"
},
"scripts": {
"build": "tsc -p tsconfig.json",
"typecheck": "tsc -p tsconfig.json",
"test": "vitest run --reporter=verbose"
},
"dependencies": {
"@rosea/engine": "workspace:*",
"dexie": "4.4.6"
},
"devDependencies": {
"fake-indexeddb": "6.2.5",
"typescript": "5.9.3",
"vitest": "3.2.7"
}
}
+82
View File
@@ -0,0 +1,82 @@
/**
* The ONLY module that touches IndexedDB (CLAUDE.md §2). The database `rosea` and its
* stores are listed in CLAUDE.md §4; each store arrives with the feature that writes
* it. So far: `profile`, written by the sunset-place question
* (.agents/features/sunset-place.md).
*
* The database name changes together with the product name (CLAUDE.md preamble).
*/
import Dexie, { type DexieOptions, type Table } from 'dexie';
import type { NamedPlace } from '@rosea/engine';
export const DATABASE_NAME = 'rosea';
/** Where the player wants their sunset: a town they chose, or the guess from the device's zone. */
export type SunsetPlace = { readonly kind: 'town'; readonly town: NamedPlace } | { readonly kind: 'device-zone' };
interface ProfileRow {
readonly key: string;
readonly value: unknown;
}
const SUNSET_PLACE = 'sunsetPlace';
export interface Profile {
/** The saved sunset place, or null if the player has not answered yet. */
loadSunsetPlace(): Promise<SunsetPlace | null>;
saveSunsetPlace(place: SunsetPlace): Promise<void>;
close(): void;
}
const isNumberIn = (x: unknown, limit: number): x is number => typeof x === 'number' && Number.isFinite(x) && Math.abs(x) <= limit;
const isString = (x: unknown): x is string => typeof x === 'string';
/** The shape check a stored value must pass. A value from an older version or a broken write fails it. */
export function asSunsetPlace(value: unknown): SunsetPlace | null {
if (typeof value !== 'object' || value === null) return null;
const v = value as Record<string, unknown>;
if (v['kind'] === 'device-zone') return { kind: 'device-zone' };
if (v['kind'] !== 'town' || typeof v['town'] !== 'object' || v['town'] === null) return null;
const t = v['town'] as Record<string, unknown>;
if (!isString(t['name']) || t['name'] === '' || !isString(t['region']) || !isString(t['country']) || !isString(t['timeZone'])) return null;
if (!isNumberIn(t['lat'], 90) || !isNumberIn(t['lon'], 180)) return null;
return { kind: 'town', town: { name: t['name'], region: t['region'], country: t['country'], lat: t['lat'], lon: t['lon'], timeZone: t['timeZone'] } };
}
class RoseaDatabase extends Dexie {
profile!: Table<ProfileRow, string>;
constructor(options?: DexieOptions) {
super(DATABASE_NAME, options);
this.version(1).stores({ profile: 'key' });
}
}
/**
* Opens the player's database. `options` lets a test pass fake-indexeddb; the app
* passes nothing and gets the browser's IndexedDB.
*/
export function openProfile(options?: DexieOptions): Profile {
const db = new RoseaDatabase(options);
return {
async loadSunsetPlace() {
const row = await db.profile.get(SUNSET_PLACE);
if (row === undefined) return null;
const place = asSunsetPlace(row.value);
// Never swallowed: a broken record is said out loud, then the question is asked again.
if (place === null) console.warn('storage: the saved sunset place has an unknown shape; asking again', row.value);
return place;
},
async saveSunsetPlace(place) {
// Write a fresh plain copy, never the caller's object: a Svelte 5 state Proxy
// cannot be structured-cloned, and IndexedDB refuses it (DataCloneError). The
// same shape check as on reading, so nothing malformed is ever written.
const plain = asSunsetPlace(place);
if (plain === null) throw new TypeError('storage: refusing to save a sunset place of an unknown shape');
await db.profile.put({ key: SUNSET_PLACE, value: plain });
},
close() {
db.close();
}
};
}
+105
View File
@@ -0,0 +1,105 @@
import { IDBFactory, IDBKeyRange } from 'fake-indexeddb';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { asSunsetPlace, openProfile, type Profile, type SunsetPlace } from '../src/index.js';
const brno: SunsetPlace = {
kind: 'town',
town: { name: 'Brno', region: '', country: 'Czechia', lat: 49.2, lon: 16.61, timeZone: 'Europe/Prague' }
};
const opened: Profile[] = [];
/** A fresh, empty fake database per call unless one is passed: tests never share state. */
function open(indexedDB: IDBFactory = new IDBFactory()): Profile {
const p = openProfile({ indexedDB, IDBKeyRange });
opened.push(p);
return p;
}
afterEach(() => {
for (const p of opened.splice(0)) p.close();
vi.restoreAllMocks();
});
describe('the profile store — the sunset place', () => {
it('reads null before the player has answered', async () => {
expect(await open().loadSunsetPlace()).toBeNull();
});
it('keeps a chosen town, and keeps it across a reopen', async () => {
const factory = new IDBFactory();
const first = open(factory);
await first.saveSunsetPlace(brno);
first.close();
expect(await open(factory).loadSunsetPlace()).toEqual(brno);
});
it('keeps "not now" as the device zone, not as a town', async () => {
const p = open();
await p.saveSunsetPlace({ kind: 'device-zone' });
expect(await p.loadSunsetPlace()).toEqual({ kind: 'device-zone' });
});
it('saves a place handed over inside a Proxy, as Svelte 5 state is, by writing a plain copy', async () => {
// Found by the e2e suite: IndexedDB cannot clone a Proxy, and the UI's towns live in $state.
const proxied = new Proxy(brno, {}) as SunsetPlace;
expect(() => structuredClone(proxied)).toThrow();
const p = open();
await p.saveSunsetPlace(proxied);
expect(await p.loadSunsetPlace()).toEqual(brno);
});
it('refuses to write a place of the wrong shape', async () => {
await expect(open().saveSunsetPlace({ kind: 'town' } as unknown as SunsetPlace)).rejects.toThrow(/unknown shape/);
});
it('a new choice replaces the old one', async () => {
const p = open();
await p.saveSunsetPlace({ kind: 'device-zone' });
await p.saveSunsetPlace(brno);
expect(await p.loadSunsetPlace()).toEqual(brno);
});
it('a record of the wrong shape reads as no answer, and says so in the console', async () => {
const factory = new IDBFactory();
// Write a broken record straight into the store, as an old version or a torn write might.
const p = open(factory);
await p.saveSunsetPlace(brno);
p.close();
await new Promise<void>((resolve, reject) => {
const req = factory.open('rosea');
req.onsuccess = () => {
const tx = req.result.transaction('profile', 'readwrite');
tx.objectStore('profile').put({ key: 'sunsetPlace', value: { kind: 'town', town: { name: 'Brno', lat: 'north' } } });
tx.oncomplete = () => { req.result.close(); resolve(); };
tx.onerror = () => reject(tx.error);
};
req.onerror = () => reject(req.error);
});
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
expect(await open(factory).loadSunsetPlace()).toBeNull();
expect(warn).toHaveBeenCalledWith(expect.stringMatching(/unknown shape/), expect.anything());
});
it('a database that cannot open rejects, so the app can fall back to the session', async () => {
const broken = new IDBFactory();
broken.open = () => { throw new DOMException('blocked by the browser', 'SecurityError'); };
await expect(openProfile({ indexedDB: broken, IDBKeyRange }).loadSunsetPlace()).rejects.toThrow();
});
});
describe('asSunsetPlace — the shape check', () => {
it.each([
[null], [42], ['town'], [{ kind: 'gps' }], [{ kind: 'town' }],
[{ kind: 'town', town: { ...(brno as { town: object }).town, lat: 91 } }],
[{ kind: 'town', town: { ...(brno as { town: object }).town, lon: Number.NaN } }],
[{ kind: 'town', town: { ...(brno as { town: object }).town, name: '' } }],
[{ kind: 'town', town: { ...(brno as { town: object }).town, timeZone: 7 } }]
])('refuses %j', (value) => {
expect(asSunsetPlace(value)).toBeNull();
});
it('keeps only the fields it knows', () => {
const extra = { kind: 'town', town: { ...(brno as { town: object }).town, gps: [49.2, 16.6] } };
expect(asSunsetPlace(extra)).toEqual(brno);
});
});
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node"]
},
"include": ["src/**/*.ts", "test/**/*.ts"]
}
+1
View File
@@ -23,6 +23,7 @@
"test": "vitest run --reporter=verbose" "test": "vitest run --reporter=verbose"
}, },
"dependencies": { "dependencies": {
"@rosea/engine": "workspace:*",
"@rosea/schema": "workspace:*" "@rosea/schema": "workspace:*"
}, },
"peerDependencies": { "peerDependencies": {
+114 -2
View File
@@ -1,11 +1,71 @@
<script lang="ts"> <script lang="ts">
import { PRODUCT_NAME } from '@rosea/schema'; import { PRODUCT_NAME } from '@rosea/schema';
import { tick } from 'svelte';
import { en } from './copy/en.js'; import { en } from './copy/en.js';
import Letter from './letter/Letter.svelte'; import Letter from './letter/Letter.svelte';
import { parseLetter } from './letter/parse.js'; import { parseLetter } from './letter/parse.js';
import SunsetLine from './sunset/SunsetLine.svelte';
import SunsetPlace from './sunset/SunsetPlace.svelte';
import type { SunsetChoice, SunsetWiring } from './sunset/types.js';
/** The author's Markdown from docs/LETTER.md. Empty means there is no way to the page. */ let {
let { letter = '' }: { letter?: string } = $props(); letter = '',
sunset
}: {
/** The author's Markdown from docs/LETTER.md. Empty means there is no way to the page. */
letter?: string;
/** Where the sunset is, and how to keep it. Absent, the garden shows no sunset at all. */
sunset?: SunsetWiring;
} = $props();
// --- The sunset (sunset-place.md) ---------------------------------------
let status = $state<'loading' | 'asking' | 'set'>('loading');
let choice = $state<SunsetChoice | null>(null);
let changing = $state(false);
/** False once the device refused to keep the answer: then the garden says it will ask again. */
let kept = $state(true);
let now = $state(0);
let sunLine = $state<HTMLElement>();
const place = $derived(choice?.kind === 'town' ? choice.town : (sunset?.guess ?? null));
$effect(() => {
const wiring = sunset;
if (!wiring) return;
now = wiring.now();
wiring.load().then(
(saved) => {
choice = saved;
status = saved ? 'set' : 'asking';
},
(error: unknown) => {
console.error('sunset: the device could not read the saved town; asking again', error);
kept = false;
status = 'asking';
}
);
// The line speaks of tomorrow once tonight's sunset has passed.
const timer = setInterval(() => (now = wiring.now()), 60_000);
return () => clearInterval(timer);
});
async function choose(next: SunsetChoice): Promise<void> {
if (!sunset) return;
choice = next;
changing = false;
status = 'set';
now = sunset.now();
sunset.save(next).then(
() => (kept = true),
(error: unknown) => {
console.error('sunset: the device could not keep the town', error);
kept = false;
}
);
// The player acted, so focus follows them to the answer.
await tick();
sunLine?.focus();
}
const LETTER_HASH = '#letter'; const LETTER_HASH = '#letter';
// Any hash but the letter's is the garden. A bare '#' is not a valid link target. // Any hash but the letter's is the garden. A bare '#' is not a valid link target.
@@ -45,6 +105,28 @@
<main class="shell"> <main class="shell">
<h1 bind:this={heading} tabindex="-1">{PRODUCT_NAME}</h1> <h1 bind:this={heading} tabindex="-1">{PRODUCT_NAME}</h1>
<p>{en.shell.preparing}</p> <p>{en.shell.preparing}</p>
{#if sunset && (status === 'asking' || changing)}
<SunsetPlace
guess={sunset.guess}
current={changing ? place : null}
search={sunset.search}
focusOnOpen={changing}
onchoose={choose}
{...changing ? { oncancel: () => (changing = false) } : {}}
/>
{:else if sunset && status === 'set'}
<div class="sun" tabindex="-1" bind:this={sunLine}>
{#if place}
<SunsetLine {place} guessed={choice?.kind === 'device-zone'} {now} />
{:else}
<p>{en.sunset.noTown}</p>
{/if}
{#if !kept}
<p class="hint">{en.sunset.notKept}</p>
{/if}
<button type="button" class="quiet" onclick={() => (changing = true)}>{place ? en.sunset.change : en.sunset.choose}</button>
</div>
{/if}
{#if blocks.length > 0} {#if blocks.length > 0}
<a href={LETTER_HASH}>{en.letter.title}</a> <a href={LETTER_HASH}>{en.letter.title}</a>
{/if} {/if}
@@ -87,4 +169,34 @@
a { a {
color: var(--rose); color: var(--rose);
} }
.sun {
display: grid;
gap: var(--space-1);
justify-items: center;
margin-top: var(--space-3);
}
.sun:focus {
outline: none;
}
.hint {
font-size: 0.9rem;
}
.quiet {
font: inherit;
background: none;
border: none;
padding: var(--space-1) 0;
color: var(--rose);
text-decoration: underline;
cursor: pointer;
}
.quiet:focus-visible {
outline: 2px solid var(--rose);
outline-offset: 2px;
}
</style> </style>
+21
View File
@@ -10,6 +10,27 @@ export const en = {
/** The one line on the Phase 0 page. True, calm, and asks nothing. */ /** The one line on the Phase 0 page. True, calm, and asks nothing. */
preparing: 'The garden is being prepared.' preparing: 'The garden is being prepared.'
}, },
sunset: {
/** ROADMAP Phase 1, word for word. */
question: 'Where do you want your sunset?',
why: 'The garden follows the real sun. Choose a town near you. It is kept on this device only.',
searchLabel: 'Town or city',
/** Said aloud as the list changes. Never "not found": a small town is not a mistake. */
found: (n: number): string => (n === 0 ? 'No town by that name here. A larger one nearby will do.' : n === 1 ? 'One town' : `${n} towns`),
skip: (guess: string): string => `Not now. Use ${guess}`,
skipNoGuess: 'Not now',
keep: (town: string): string => `Keep ${town}`,
change: 'Change town',
choose: 'Choose a town',
tonight: (time: string, town: string): string => `Tonight the sun sets at ${time} in ${town}.`,
tomorrow: (time: string, town: string): string => `Tomorrow the sun sets at ${time} in ${town}.`,
polarDay: (time: string, town: string): string => `In ${town} the sun stays up tonight. The light is lowest at ${time}.`,
polarNight: (time: string, town: string): string => `In ${town} the sun stays below the horizon today. The twilight is brightest at ${time}.`,
guessed: "A guess from this device's time zone.",
noTown: 'Choose a town to see when the sun sets.',
/** When the device refuses to keep anything (a private window). Calm, and true. */
notKept: 'This device could not keep your choice, so the garden will ask again next time.'
},
letter: { letter: {
/** The help section's name (ROADMAP §1). The letter itself is the author's, in docs/LETTER.md. */ /** The help section's name (ROADMAP §1). The letter itself is the author's, in docs/LETTER.md. */
title: 'A Letter from the Gardener', title: 'A Letter from the Gardener',
+1
View File
@@ -1,3 +1,4 @@
export { default as Shell } from './Shell.svelte'; export { default as Shell } from './Shell.svelte';
export { en, type Copy } from './copy/en.js'; export { en, type Copy } from './copy/en.js';
export { parseLetter, type Inline, type LetterBlock } from './letter/parse.js'; export { parseLetter, type Inline, type LetterBlock } from './letter/parse.js';
export type { SunsetChoice, SunsetWiring } from './sunset/types.js';
+46
View File
@@ -0,0 +1,46 @@
<script lang="ts">
import { localDay, nextInvitation, type NamedPlace } from '@rosea/engine';
import { en } from '../copy/en.js';
/**
* The next sunset, or its polar alternative, in one sentence. The engine says
* when; this only reads it on the town's clock, in the device's own time format
* (sunset-place.md P6).
*/
let { place, guessed = false, now }: { place: NamedPlace; guessed?: boolean; now: number } = $props();
const line = $derived.by(() => {
const { sun, at } = nextInvitation(now, place);
const time = new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit', timeZone: place.timeZone }).format(at);
switch (sun.kind) {
case 'polar-day':
return en.sunset.polarDay(time, place.name);
case 'polar-night':
return en.sunset.polarNight(time, place.name);
case 'sun-sets':
// Tonight's sunset may fall after midnight (sun.md D2), so "tomorrow" only
// when it belongs to a later day than today.
return sun.day > localDay(now, place.timeZone) ? en.sunset.tomorrow(time, place.name) : en.sunset.tonight(time, place.name);
}
});
</script>
<p class="sunset">{line}</p>
{#if guessed}
<p class="hint">{en.sunset.guessed}</p>
{/if}
<style>
p {
margin: 0;
}
.sunset {
font-size: 1.1rem;
}
.hint {
color: var(--ink-soft);
font-size: 0.9rem;
}
</style>
+189
View File
@@ -0,0 +1,189 @@
<script lang="ts">
import type { NamedPlace } from '@rosea/engine';
import { en } from '../copy/en.js';
import type { SunsetChoice } from './types.js';
/**
* "Where do you want your sunset?" A search over towns on the device, and a way
* to say not now. Decides nothing: it reports the answer (sunset-place.md).
*/
let {
guess,
current = null,
search,
focusOnOpen = false,
onchoose,
oncancel
}: {
guess: NamedPlace | null;
/** The town already set, when the player is changing it. */
current?: NamedPlace | null;
search: (query: string) => Promise<readonly NamedPlace[]>;
focusOnOpen?: boolean;
onchoose: (choice: SunsetChoice) => void;
oncancel?: () => void;
} = $props();
const uid = $props.id();
let query = $state('');
// Raw: the towns are handed on as they came, never wrapped in a state Proxy.
let results = $state.raw<readonly NamedPlace[]>([]);
let input = $state<HTMLInputElement>();
// Only the latest query's answer is shown, however the searches finish.
let asked = 0;
$effect(() => {
const q = query;
const ticket = ++asked;
if (q.trim() === '') {
results = [];
return;
}
search(q).then(
(found) => {
if (ticket === asked) results = found;
},
(error: unknown) => {
console.error('sunset: the town search failed', error);
if (ticket === asked) results = [];
}
);
});
$effect(() => {
if (focusOnOpen) input?.focus();
});
const where = (t: NamedPlace): string => [t.region, t.country].filter(Boolean).join(', ');
</script>
<section class="ask" aria-labelledby="{uid}-q">
<h2 id="{uid}-q">{en.sunset.question}</h2>
<p class="why">{en.sunset.why}</p>
<label for="{uid}-search">{en.sunset.searchLabel}</label>
<input
id="{uid}-search"
type="search"
autocomplete="off"
spellcheck="false"
enterkeyhint="search"
bind:value={query}
bind:this={input}
/>
<p class="found" role="status" aria-live="polite">{query.trim() === '' ? '' : en.sunset.found(results.length)}</p>
{#if results.length > 0}
<ul>
{#each results as town (`${town.name}|${town.lat}|${town.lon}`)}
<li>
<button type="button" onclick={() => onchoose({ kind: 'town', town })}>
<span class="name">{town.name}</span>
<span class="where">{where(town)}</span>
</button>
</li>
{/each}
</ul>
{/if}
<div class="other">
{#if current && oncancel}
<button type="button" class="quiet" onclick={oncancel}>{en.sunset.keep(current.name)}</button>
{/if}
<button type="button" class="quiet" onclick={() => onchoose({ kind: 'device-zone' })}>
{guess ? en.sunset.skip(guess.name) : en.sunset.skipNoGuess}
</button>
</div>
</section>
<style>
.ask {
display: grid;
gap: var(--space-2);
width: min(28rem, 100%);
margin-inline: auto;
text-align: start;
}
h2 {
margin: 0;
font-family: var(--font-display);
font-weight: 400;
font-size: 1.4rem;
color: var(--ink);
}
.why,
.found {
margin: 0;
color: var(--ink-soft);
}
.found:empty {
display: none;
}
label {
font-size: 0.95rem;
}
input {
font: inherit;
padding: var(--space-2);
border: 1px solid var(--ink-soft);
border-radius: 0.5rem;
background: var(--paper);
color: var(--ink);
}
ul {
list-style: none;
margin: 0;
padding: 0;
display: grid;
gap: var(--space-1);
}
button {
font: inherit;
cursor: pointer;
border-radius: 0.5rem;
color: var(--ink);
}
li button {
width: 100%;
display: flex;
justify-content: space-between;
gap: var(--space-2);
padding: var(--space-2);
text-align: start;
background: var(--paper);
border: 1px solid color-mix(in srgb, var(--ink-soft) 40%, transparent);
}
.where {
color: var(--ink-soft);
text-align: end;
}
.other {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
.quiet {
background: none;
border: none;
padding: var(--space-1) 0;
color: var(--rose);
text-decoration: underline;
}
button:focus-visible,
input:focus-visible {
outline: 2px solid var(--rose);
outline-offset: 2px;
}
</style>
+19
View File
@@ -0,0 +1,19 @@
import type { NamedPlace } from '@rosea/engine';
/** What the player answered: a town, or "not now" (the guess from the device's zone). */
export type SunsetChoice = { readonly kind: 'town'; readonly town: NamedPlace } | { readonly kind: 'device-zone' };
/**
* Everything the garden needs to ask where the sunset is and to show it. The app
* provides it; ui imports neither content nor storage (CLAUDE.md §2).
*/
export interface SunsetWiring {
/** The device's guess for its own zone, or null for a zone of no place (UTC). */
readonly guess: NamedPlace | null;
/** Towns matching a query. The app loads the town list on the first call. */
readonly search: (query: string) => Promise<readonly NamedPlace[]>;
readonly load: () => Promise<SunsetChoice | null>;
readonly save: (choice: SunsetChoice) => Promise<void>;
/** The clock. A parameter, so tests and the e2e suite can fix it. */
readonly now: () => number;
}
+135
View File
@@ -0,0 +1,135 @@
import { invitation, sunDay, type NamedPlace } from '@rosea/engine';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/svelte';
import { afterEach, describe, expect, it, vi } from 'vitest';
import Shell from '../src/Shell.svelte';
import { en } from '../src/copy/en.js';
import type { SunsetChoice, SunsetWiring } from '../src/sunset/types.js';
const brno: NamedPlace = { name: 'Brno', region: '', country: 'Czechia', lat: 49.2, lon: 16.61, timeZone: 'Europe/Prague' };
const prague: NamedPlace = { name: 'Prague', region: '', country: 'Czechia', lat: 50.09, lon: 14.46, timeZone: 'Europe/Prague' };
const tromso: NamedPlace = { name: 'Tromsø', region: 'Troms', country: 'Norway', lat: 69.65, lon: 18.96, timeZone: 'Europe/Oslo' };
/** Noon in Prague on 29 March 2026: tonight's sunset is still to come. */
const NOON = Date.parse('2026-03-29T12:00:00+02:00');
/** The time the line must show, read exactly as the component reads it. */
const timeOf = (place: NamedPlace, at: number): string =>
new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit', timeZone: place.timeZone }).format(at);
function wiring(over: Partial<SunsetWiring> & { saved?: SunsetChoice | null } = {}): SunsetWiring & { saves: SunsetChoice[] } {
const saves: SunsetChoice[] = [];
return {
guess: prague,
search: async (q) => [brno, prague].filter((t) => t.name.toLowerCase().startsWith(q.trim().toLowerCase())),
load: async () => over.saved ?? null,
save: async (c) => {
saves.push(c);
},
now: () => NOON,
...over,
saves
};
}
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
describe('the garden asks where the sunset is', () => {
it('asks when nothing is saved, and does not take focus on first load', async () => {
render(Shell, { sunset: wiring() });
expect(await screen.findByRole('heading', { level: 2, name: en.sunset.question })).toBeTruthy();
expect(screen.getByRole('searchbox', { name: en.sunset.searchLabel })).toBeTruthy();
expect(document.activeElement).toBe(document.body);
});
it('typing lists towns, choosing one shows its sunset, keeps it, and moves focus to the answer', async () => {
const w = wiring();
render(Shell, { sunset: w });
await fireEvent.input(await screen.findByRole('searchbox'), { target: { value: 'br' } });
expect(await screen.findByRole('status')).toHaveProperty('textContent', en.sunset.found(1));
await fireEvent.click(screen.getByRole('button', { name: /Brno/ }));
const at = invitation(sunDay('2026-03-29', brno));
expect(await screen.findByText(en.sunset.tonight(timeOf(brno, at), 'Brno'))).toBeTruthy();
expect(w.saves).toEqual([{ kind: 'town', town: brno }]);
await waitFor(() => expect(document.activeElement?.className).toContain('sun'));
expect(screen.queryByText(en.sunset.guessed)).toBeNull();
});
it('nothing found says a larger town nearby will do, never an error', async () => {
render(Shell, { sunset: wiring() });
await fireEvent.input(await screen.findByRole('searchbox'), { target: { value: 'zz' } });
await waitFor(() => expect(screen.getByRole('status').textContent).toBe(en.sunset.found(0)));
});
it('"not now" uses the guess, saves the device zone, and says it is a guess', async () => {
const w = wiring();
render(Shell, { sunset: w });
await fireEvent.click(await screen.findByRole('button', { name: en.sunset.skip('Prague') }));
const at = invitation(sunDay('2026-03-29', prague));
expect(await screen.findByText(en.sunset.tonight(timeOf(prague, at), 'Prague'))).toBeTruthy();
expect(screen.getByText(en.sunset.guessed)).toBeTruthy();
expect(w.saves).toEqual([{ kind: 'device-zone' }]);
});
it('with no guess (a UTC clock), "not now" asks the player to choose a town', async () => {
render(Shell, { sunset: wiring({ guess: null }) });
await fireEvent.click(await screen.findByRole('button', { name: en.sunset.skipNoGuess }));
expect(await screen.findByText(en.sunset.noTown)).toBeTruthy();
expect(screen.getByRole('button', { name: en.sunset.choose })).toBeTruthy();
});
});
describe('the garden remembers', () => {
it('a saved town shows its sunset at once, with no question', async () => {
render(Shell, { sunset: wiring({ saved: { kind: 'town', town: brno } }) });
expect(await screen.findByText(/in Brno\.$/)).toBeTruthy();
expect(screen.queryByRole('searchbox')).toBeNull();
});
it('after the sunset, it speaks of tomorrow\'s', async () => {
const after = invitation(sunDay('2026-03-29', brno)) + 60_000;
render(Shell, { sunset: wiring({ saved: { kind: 'town', town: brno }, now: () => after }) });
const tomorrow = invitation(sunDay('2026-03-30', brno));
expect(await screen.findByText(en.sunset.tomorrow(timeOf(brno, tomorrow), 'Brno'))).toBeTruthy();
});
it('in polar night it speaks of the noon twilight; in polar day, of the lowest light', async () => {
const winter = Date.parse('2026-12-21T08:00:00+01:00');
render(Shell, { sunset: wiring({ saved: { kind: 'town', town: tromso }, now: () => winter }) });
const noon = sunDay('2026-12-21', tromso).solarNoon;
expect(await screen.findByText(en.sunset.polarNight(timeOf(tromso, noon), 'Tromsø'))).toBeTruthy();
cleanup();
const summer = Date.parse('2026-06-21T12:00:00+02:00');
render(Shell, { sunset: wiring({ saved: { kind: 'town', town: tromso }, now: () => summer }) });
expect(await screen.findByText(/In Tromsø the sun stays up tonight\. The light is lowest at/)).toBeTruthy();
});
it('change town: the search opens with focus, and Keep returns without saving anything', async () => {
const w = wiring({ saved: { kind: 'town', town: brno } });
render(Shell, { sunset: w });
await fireEvent.click(await screen.findByRole('button', { name: en.sunset.change }));
await waitFor(() => expect(document.activeElement).toBe(screen.getByRole('searchbox')));
await fireEvent.click(screen.getByRole('button', { name: en.sunset.keep('Brno') }));
expect(await screen.findByText(/in Brno\.$/)).toBeTruthy();
expect(w.saves).toEqual([]);
});
});
describe('when the device will not keep anything', () => {
it('a failed read still asks, and a failed save still shows the sunset and says it will ask again', async () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined);
const w = wiring({
load: () => Promise.reject(new Error('IndexedDB blocked')),
save: () => Promise.reject(new Error('IndexedDB blocked'))
});
render(Shell, { sunset: w });
await fireEvent.click(await screen.findByRole('button', { name: en.sunset.skip('Prague') }));
expect(await screen.findByText(/in Prague\.$/)).toBeTruthy();
expect(await screen.findByText(en.sunset.notKept)).toBeTruthy();
expect(error).toHaveBeenCalled(); // never swallowed
});
});
+42
View File
@@ -20,6 +20,9 @@ importers:
'@rosea/content': '@rosea/content':
specifier: workspace:* specifier: workspace:*
version: link:packages/content version: link:packages/content
'@rosea/engine':
specifier: workspace:*
version: link:packages/engine
'@rosea/schema': '@rosea/schema':
specifier: workspace:* specifier: workspace:*
version: link:packages/schema version: link:packages/schema
@@ -62,9 +65,15 @@ importers:
apps/rosea: apps/rosea:
dependencies: dependencies:
'@rosea/content':
specifier: workspace:*
version: link:../../packages/content
'@rosea/schema': '@rosea/schema':
specifier: workspace:* specifier: workspace:*
version: link:../../packages/schema version: link:../../packages/schema
'@rosea/storage':
specifier: workspace:*
version: link:../../packages/storage
'@rosea/ui': '@rosea/ui':
specifier: workspace:* specifier: workspace:*
version: link:../../packages/ui version: link:../../packages/ui
@@ -136,8 +145,30 @@ importers:
specifier: 3.2.7 specifier: 3.2.7
version: 3.2.7(@types/node@22.20.1)(jsdom@25.0.1)(terser@5.51.2)(tsx@4.23.12) version: 3.2.7(@types/node@22.20.1)(jsdom@25.0.1)(terser@5.51.2)(tsx@4.23.12)
packages/storage:
dependencies:
'@rosea/engine':
specifier: workspace:*
version: link:../engine
dexie:
specifier: 4.4.6
version: 4.4.6
devDependencies:
fake-indexeddb:
specifier: 6.2.5
version: 6.2.5
typescript:
specifier: 5.9.3
version: 5.9.3
vitest:
specifier: 3.2.7
version: 3.2.7(@types/node@22.20.1)(jsdom@25.0.1)(terser@5.51.2)(tsx@4.23.12)
packages/ui: packages/ui:
dependencies: dependencies:
'@rosea/engine':
specifier: workspace:*
version: link:../engine
'@rosea/schema': '@rosea/schema':
specifier: workspace:* specifier: workspace:*
version: link:../schema version: link:../schema
@@ -1924,6 +1955,9 @@ packages:
devalue@5.9.4: devalue@5.9.4:
resolution: {integrity: sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==} resolution: {integrity: sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==}
dexie@4.4.6:
resolution: {integrity: sha512-hJP/BO6mjB+tX6hToIO1kmxYLNmun90wYbfcoAoLpKEyDYal/k33dg0TAfoUe2TDsbbLoVIzljJ3BN2UbR5EOg==}
dom-accessibility-api@0.5.16: dom-accessibility-api@0.5.16:
resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==} resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==}
@@ -2074,6 +2108,10 @@ packages:
resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}
engines: {node: '>=12.0.0'} engines: {node: '>=12.0.0'}
fake-indexeddb@6.2.5:
resolution: {integrity: sha512-CGnyrvbhPlWYMngksqrSSUT1BAVP49dZocrHuK0SvtR0D5TMs5wP0o3j7jexDJW01KSadjBp1M/71o/KR3nD1w==}
engines: {node: '>=18'}
fast-check@3.23.2: fast-check@3.23.2:
resolution: {integrity: sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A==} resolution: {integrity: sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A==}
engines: {node: '>=8.0.0'} engines: {node: '>=8.0.0'}
@@ -4990,6 +5028,8 @@ snapshots:
devalue@5.9.4: {} devalue@5.9.4: {}
dexie@4.4.6: {}
dom-accessibility-api@0.5.16: {} dom-accessibility-api@0.5.16: {}
dunder-proto@1.0.1: dunder-proto@1.0.1:
@@ -5262,6 +5302,8 @@ snapshots:
expect-type@1.4.0: {} expect-type@1.4.0: {}
fake-indexeddb@6.2.5: {}
fast-check@3.23.2: fast-check@3.23.2:
dependencies: dependencies:
pure-rand: 6.1.0 pure-rand: 6.1.0
+236
View File
@@ -0,0 +1,236 @@
/**
* Builds packages/content/src/places/places.json: the towns a player can choose for
* the sunset, and the best guess for each time zone (.agents/features/sunset-place.md).
* Run by hand after downloading the two public-domain sources into one folder:
*
* tsx scripts/build-places.ts <folder>
*
* <folder>/ne/ne_10m_populated_places.dbf Natural Earth 10m populated places
* (https://www.naturalearthdata.com, public domain), from its .zip
* <folder>/zone.tab, zone1970.tab, version the IANA time zone database
* (https://data.iana.org/time-zones/tzdb/, public domain)
*
* Only the derived file is committed. The downloads stay outside the repository.
*/
import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
const folder = process.argv[2];
if (!folder) {
console.error('Usage: tsx scripts/build-places.ts <folder with ne/ and the tzdb tables>');
process.exit(2);
}
/** Reads a dBase III table: the attribute part of a shapefile. */
function readDbf(path: string): Record<string, string>[] {
const buf = readFileSync(path);
const count = buf.readUInt32LE(4);
const headerLength = buf.readUInt16LE(8);
const recordLength = buf.readUInt16LE(10);
const fields: { name: string; length: number }[] = [];
for (let at = 32; buf[at] !== 0x0d; at += 32) {
fields.push({ name: buf.toString('latin1', at, at + 11).replace(/\0.*$/, ''), length: buf[at + 16] ?? 0 });
}
const rows: Record<string, string>[] = [];
for (let i = 0; i < count; i++) {
let at = headerLength + i * recordLength;
if (buf[at] === 0x2a) continue; // deleted
at += 1;
const row: Record<string, string> = {};
for (const f of fields) {
row[f.name] = buf.toString('utf8', at, at + f.length).trim();
at += f.length;
}
rows.push(row);
}
return rows;
}
/** ±DDMM[SS]±DDDMM[SS] from zone.tab, in degrees. */
function isoCoordinates(s: string): [number, number] {
const m = /^([+-])(\d{2})(\d{2})(\d{2})?([+-])(\d{3})(\d{2})(\d{2})?$/.exec(s);
if (!m) throw new Error(`zone.tab: bad coordinates ${s}`);
const deg = (sign: string, d: string, mm: string, ss = '0'): number => (sign === '-' ? -1 : 1) * (Number(d) + Number(mm) / 60 + Number(ss) / 3600);
return [deg(m[1]!, m[2]!, m[3]!, m[4]), deg(m[5]!, m[6]!, m[7]!, m[8])];
}
const validZone = (zone: string): boolean => {
try {
new Intl.DateTimeFormat('en', { timeZone: zone });
return true;
} catch {
return false; // reported below as dropped, never silently
}
};
const round2 = (x: number): number => Math.round(x * 100) / 100;
// --- The time zone database: which zones each country has, and where -------
interface TzZone { readonly zone: string; readonly lat: number; readonly lon: number; readonly countries: readonly string[] }
const tz = new Map<string, TzZone>();
for (const file of ['zone1970.tab', 'zone.tab']) {
for (const line of readFileSync(join(folder, file), 'utf8').split('\n')) {
if (line.startsWith('#') || line.trim() === '') continue;
const [codes, coords, zone] = line.split('\t');
if (!codes || !coords || !zone || !validZone(zone)) continue;
const [lat, lon] = isoCoordinates(coords);
const old = tz.get(zone);
tz.set(zone, { zone, lat, lon, countries: [...new Set([...(old?.countries ?? []), ...codes.split(',')])] });
}
}
/** The zone's clock through 2026: its offset in minutes on the 1st and 15th of every month. */
const clocks = new Map<string, string>();
function clockOf(zone: string): string {
let c = clocks.get(zone);
if (c === undefined) {
const f = new Intl.DateTimeFormat('en-US', { timeZone: zone, timeZoneName: 'longOffset' });
c = Array.from({ length: 24 }, (_, i) => f.formatToParts(Date.UTC(2026, i >> 1, i % 2 ? 15 : 1, 12)).find((p) => p.type === 'timeZoneName')?.value ?? '').join(',');
clocks.set(zone, c);
}
return c;
}
const standardOffset = (zone: string): number => {
const hours = clockOf(zone).split(',').map((s) => {
const m = /GMT([+-])(\d\d):(\d\d)/.exec(s);
return m ? (m[1] === '-' ? -1 : 1) * (Number(m[2]) + Number(m[3]) / 60) : 0;
});
return Math.min(...hours);
};
const MAX_SOLAR_DRIFT_HOURS = 3.5; // the furthest a real zone strays from its longitude (western China: ~3)
/** Whether a zone's clock fits a longitude, the long way round the date line too (Tonga: UTC+13 at 175° W). */
const fitsLongitude = (zone: string, lon: number): boolean => {
const drift = (((standardOffset(zone) - lon / 15) % 24) + 36) % 24 - 12;
return Math.abs(drift) <= MAX_SOLAR_DRIFT_HOURS;
};
const countryZones = (country: string): TzZone[] => [...tz.values()].filter((z) => z.countries.includes(country));
const d2 = (a: { lat: number; lon: number }, b: { lat: number; lon: number }): number =>
(a.lat - b.lat) ** 2 + ((a.lon - b.lon) * Math.cos((a.lat * Math.PI) / 180)) ** 2;
/**
* Natural Earth's own TIMEZONE, if it can be trusted: a clock identical all through
* 2026 to one of the country's zones in the time zone database (which also accepts old
* names such as Europe/Kiev), with an offset that fits the longitude. Returned as the
* nearest of the country's zones with that clock, so Anchorage, filed under
* America/Juneau, is America/Anchorage.
*/
function trustedZone(neZone: string, country: string, lat: number, lon: number): string | null {
if (!neZone || !validZone(neZone) || !fitsLongitude(neZone, lon)) return null;
const same = countryZones(country).filter((z) => clockOf(z.zone) === clockOf(neZone));
return same.sort((a, b) => d2({ lat, lon }, a) - d2({ lat, lon }, b))[0]?.zone ?? null;
}
/** A name field that a fixed-width DBF did not cut in the middle of a letter. */
const clean = (s: string | undefined): string => (s && !s.includes('�') ? s : '');
// --- Natural Earth towns --------------------------------------------------
const raw = readDbf(join(folder, 'ne', 'ne_10m_populated_places.dbf'));
const zones: string[] = [];
const countries: string[] = [];
const index = (list: string[], v: string): number => {
let i = list.indexOf(v);
if (i < 0) i = list.push(v) - 1;
return i;
};
/** [name, other names for search ('|'-joined), region, country index, lat, lon, zone index, population in thousands] */
type Row = [string, string, string, number, number, number, number, number];
interface Town { r: Record<string, string>; name: string; country: string; lat: number; lon: number; zone: string | null }
/**
* Natural Earth gives these no ISO code (-99). The code here only picks the zone whose
* clock they keep; the country shown to the player is Natural Earth's own name.
*/
const CLOCK_COUNTRY: Readonly<Record<string, string>> = { Kosovo: 'RS', 'Northern Cyprus': 'CY', Somaliland: 'SO' };
/** Natural Earth's Latin-script name columns, searched as other names. */
const SEARCH_LANGUAGES = ['DE', 'ES', 'FR', 'PT', 'IT', 'NL', 'PL', 'SV', 'HU', 'TR', 'ID', 'VI'] as const;
const towns: Town[] = [];
const dropped: string[] = [];
for (const r of raw) {
const lat = Number(r['LATITUDE']);
const lon = Number(r['LONGITUDE']);
const name = clean(r['NAME_EN']) || clean(r['NAME']);
if (!name || !Number.isFinite(lat) || !Number.isFinite(lon)) {
dropped.push(`${r['NAME']} (${r['ADM0NAME']}): no usable name or position`);
continue;
}
const country = r['ISO_A2'] === '-99' ? (CLOCK_COUNTRY[r['ADM0NAME'] ?? ''] ?? '') : (r['ISO_A2'] ?? '');
towns.push({ r, name, country, lat, lon, zone: trustedZone(r['TIMEZONE'] ?? '', country, lat, lon) });
}
// A town without a trusted zone takes the zone most of its five nearest trusted
// towns in the same country share; with none, the country's nearest zone location.
const trusted = towns.filter((t) => t.zone !== null);
const corrected: string[] = [];
for (const t of towns) {
if (t.zone !== null) continue;
const near = trusted.filter((o) => o.country === t.country).sort((a, b) => d2(t, a) - d2(t, b)).slice(0, 5);
const votes = new Map<string, number>();
for (const o of near) votes.set(o.zone!, (votes.get(o.zone!) ?? 0) + 1);
const voted = [...votes.entries()].sort((a, b) => b[1] - a[1])[0]?.[0];
const location = countryZones(t.country).filter((z) => fitsLongitude(z.zone, t.lon)).sort((a, b) => d2(t, a) - d2(t, b))[0]?.zone;
t.zone = voted ?? location ?? null;
if (t.zone === null) dropped.push(`${t.name} (${t.r['ADM0NAME']}, ${t.country}): no zone for the country`);
else corrected.push(`${t.name} (${t.country}): '${t.r['TIMEZONE']}' -> ${t.zone}${voted ? ' (neighbours)' : ' (zone location)'}`);
}
const rows: Row[] = [];
for (const t of towns) {
if (t.zone === null) continue;
const { r, name } = t;
// Other names a player may type: the local name (NAMEPAR: Praha, Wien) and the
// Latin-script language columns. Natural Earth has no Czech column.
const names = [r['NAME'], r['NAMEASCII'], r['NAMEPAR'], r['MEGANAME'], ...(r['NAMEALT'] ?? '').split('|'), ...SEARCH_LANGUAGES.map((l) => r[`NAME_${l}`])];
const others = [...new Set(names.map((s) => clean(s?.trim())).filter((s) => s && s !== name))];
const region = r['ADM1NAME'] === name ? '' : clean(r['ADM1NAME']);
rows.push([name, others.join('|'), region, index(countries, r['ADM0NAME'] ?? ''), round2(t.lat), round2(t.lon), index(zones, t.zone), Math.round(Number(r['POP_MAX'] ?? 0) / 1000)]);
}
// Largest first, so a search shows the town most people mean.
rows.sort((a, b) => b[7] - a[7] || a[0].localeCompare(b[0]));
// --- One guess per time zone ----------------------------------------------
// The largest town in the zone; where Natural Earth has none, the zone's own
// location from the time zone database, named after the zone. Kept in its own
// small file, so the garden can guess without loading every town.
/** zone -> [name, country, lat, lon] */
const guesses: Record<string, [string, string, number, number]> = {};
for (const r of rows) {
const zone = zones[r[6]]!;
if (!(zone in guesses)) guesses[zone] = [r[0], countries[r[3]]!, r[4], r[5]];
}
let fromTzdb = 0;
for (const z of tz.values()) {
if (z.zone in guesses) continue;
guesses[z.zone] = [z.zone.split('/').pop()!.replace(/_/g, ' '), '', round2(z.lat), round2(z.lon)];
fromTzdb++;
}
// Browsers report a zone by the name Intl resolves it to, which is CLDR's and not
// always the time zone database's (Asia/Calcutta, Europe/Kiev). Key each guess by
// that name too, resolved by the same Intl.
let aliases = 0;
for (const zone of Object.keys(guesses)) {
const resolved = new Intl.DateTimeFormat('en', { timeZone: zone }).resolvedOptions().timeZone;
if (resolved !== zone && !(resolved in guesses)) {
guesses[resolved] = guesses[zone]!;
aliases++;
}
}
const unguessable = Intl.supportedValuesOf('timeZone').filter((z) => !(z in guesses));
const tzdb = readFileSync(join(folder, 'version'), 'utf8').trim();
const source = `Natural Earth 10m populated places (public domain) and the IANA time zone database ${tzdb} (public domain). Built by scripts/build-places.ts.`;
const dir = fileURLToPath(new URL('../packages/content/src/places/', import.meta.url));
writeFileSync(join(dir, 'places.json'), JSON.stringify({
source,
fields: ['name', 'other names', 'region', 'country', 'lat', 'lon', 'zone', 'population in thousands'],
countries,
zones,
places: rows
}) + '\n');
writeFileSync(join(dir, 'zone-guesses.json'), JSON.stringify({ source, fields: ['name', 'country', 'lat', 'lon'], guesses }, null, 0) + '\n');
console.log(`build-places: ${rows.length} towns (${rows.length - corrected.length} kept Natural Earth's zone, ${corrected.length} corrected), ${countries.length} countries, ${zones.length} zones, ${Object.keys(guesses).length} zone guesses (${fromTzdb} from tzdb, ${aliases} under Intl's name); dropped ${dropped.length}`);
console.log(` zones Intl knows with no guess: ${unguessable.join(', ') || 'none'}`);
for (const d of dropped) console.log(` dropped: ${d}`);
for (const c of corrected) console.log(` corrected: ${c}`);