Compare commits
29 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 55fc14b125 | |||
| e63563755b | |||
| 512c300973 | |||
| a63232e8d7 | |||
| cc9cc11b0b | |||
| a7d0fca31a | |||
| aa1e8b6f66 | |||
| 21f4496910 | |||
| 6a3ca84aaa | |||
| 2b5cd719c1 | |||
| d091c31b49 | |||
| 6fee00f5b3 | |||
| b150c64af7 | |||
| 5e41a449a4 | |||
| 6d29e4a4c9 | |||
| 85df2c43b5 | |||
| 77a865f625 | |||
| 3ed91eea7b | |||
| 1e8d1cda5a | |||
| fb7171c3a7 | |||
| 2b216855fc | |||
| e8b7bdfebf | |||
| 84dc67076a | |||
| abc5a5c3a8 | |||
| 08bc8b58fa | |||
| 793bcd7701 | |||
| 2962b13696 | |||
| 118ad5a2d4 | |||
| 1f60ddd17a |
@@ -8,4 +8,8 @@ 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) |
|
||||
| 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 art pipeline and the art board: STYLE.md (S1–S5 approved; fox F1–F4 draft), 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) |
|
||||
| Keep her safe: the browser's promise, save her to a file, bring her back | 0–1 | Merged to `main`; built, not deployed | [keep-her-safe.md](features/keep-her-safe.md) | [feature-keep-her-safe.md](reviews/feature-keep-her-safe.md) |
|
||||
| The rose: care by feel, growth from days of care, drift, moods, her numbers; the care log and the identity | 1 | Merged to `main`; built, not deployed. Tuning is the author's | [rose.md](features/rose.md) | [feature-rose-care.md](reviews/feature-rose-care.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 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) |
|
||||
|
||||
@@ -27,11 +27,11 @@ board exist, and the first real picture is the author's to make.
|
||||
| ~~G0.8~~ | ~~Never tested under the Pages sub-path~~ | Closed for the local build 2026-11-01. `shell.spec.ts` serves `dist/` at `/Rosea/` and asserts manifest scope = start_url = SW scope. Mutation: scope `/` fails it. **On real GitHub Pages: still predicted** (G0.13). |
|
||||
| ~~G0.9~~ | ~~No proof the app opens offline~~ | Closed for the shell 2026-11-01. `offline.spec.ts` closes the server, then reload, cold start and a deep link all render. Mutations: `clientsClaim: false` and no `navigateFallback` both fail it. |
|
||||
| G0.10 | No calm *refresh* control for a waiting service worker (CLAUDE.md §8, stale SW) | Open. `registerType: 'prompt'` and `skipWaiting: false` are set, so a new worker waits. Nothing tells the player yet. |
|
||||
| G0.11 | IndexedDB eviction: no `navigator.storage.persist()`, no export-my-rose (§8) | Open. Arrives with `packages/storage`. |
|
||||
| ~~G0.11~~ | ~~IndexedDB eviction: no `navigator.storage.persist()`, no export-my-rose (§8)~~ | Closed 2026-11-02 on `feature/keep-her-safe`: *Keep her safe* asks the browser (and an installed app asks by itself), saves her to a file without the town or the private key, and brings her back additively on any device. e2e: saved on one browser profile, restored on a fresh one, survives a reload. Not seen in Firefox or Safari. |
|
||||
| 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.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: `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 and the rose (`profile`, `events`, `keys`); `identity` with the rose (a keypair, nothing signed yet). |
|
||||
| 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.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). |
|
||||
@@ -40,11 +40,24 @@ board exist, and the first real picture is the author's to make.
|
||||
| G0.21 | No PNG icons | Open (predicted trap). iOS ignores SVG for `apple-touch-icon`. Comes through the art pipeline. |
|
||||
| G0.22 | No CI | Open. Every gate ran on this machine only. With G0.13. |
|
||||
| G0.23 | Source maps are built and would be published | Open. `sourcemap: true`; maps are not precached. Decide with G0.13 whether the repository is public. If not, use `'hidden'`. |
|
||||
| G0.24 | No art pipeline: `docs/ART.md`, `art/STYLE.md` (drafted with the author), `art/manifest.json` for Phase 1 assets, SVG placeholders, `tools/art-prep` | **Pipeline built 2026-11-01** (`feature/art-board`): docs/ART.md, the Phase 1 manifest (25 pictures), 29 generated stand-ins, `tools/art-prep` (50 tests; 5 of 5 put-back bugs caught), the art board published. STYLE.md approved by the author 2026-11-01 (S1–S5 kept as drafted; `docs/style-approved`). The board grew to 53 pictures with Phases 2–3 (`art/phase2-3-pictures`; the fox's look F1–F4 is a draft). **Still open:** the **Phase 0 gate**, one real picture through every step into `art/final/`. |
|
||||
| G0.24 | No art pipeline: `docs/ART.md`, `art/STYLE.md` (drafted with the author), `art/manifest.json` for Phase 1 assets, SVG placeholders, `tools/art-prep` | **Pipeline built 2026-11-01** (`feature/art-board`): docs/ART.md, the Phase 1 manifest (25 pictures), 29 generated stand-ins, `tools/art-prep` (50 tests; 5 of 5 put-back bugs caught), the art board published. STYLE.md approved by the author 2026-11-01 (S1–S5 kept as drafted; `docs/style-approved`). The board grew to 53 pictures with Phases 2–3 (`art/phase2-3-pictures`); the fox's look F1–F4 approved with a deep red-orange coat (`art/fox-coat`). **Still open:** the **Phase 0 gate**, one real picture through every step into `art/final/`. |
|
||||
| ~~G0.25~~ | ~~No slot for *A Letter from the Gardener*~~ | Closed 2026-11-01, merged to `main`. `docs/LETTER.md` holds slots as comments only; the page opens at `#letter` once it has words. 16 ui tests, and e2e on both the empty and a temporary written letter. Mutations caught: the link while empty, any link scheme, focus not moving, *heal* in the letter. |
|
||||
| G0.27 | The quiet door to real help has no numbers (§5.6 rule 5) | Open. The slot is in `docs/LETTER.md`. Support lines are real-world facts the author must verify, per country, so the door exists only once the letter does. |
|
||||
| ~~G0.26~~ | ~~Not decided: how the sunset invitation reaches the player on the web~~ | Closed 2026-11-01 by the author (Q6): in-app only on the web, no push server; local notifications through the Tauri shell in Phase 6. Recorded in ROADMAP Phase 0 and CLAUDE.md §8. |
|
||||
|
||||
## Phase 1 — The rose alone
|
||||
|
||||
**Started 2026-11-01** with the sun, while the Phase 0 gate waits on the author (pictures,
|
||||
sentences). Nothing in Phase 1 is visible to the player yet.
|
||||
|
||||
| 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.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.4~~ | ~~No rose~~ | Closed 2026-11-02 on `feature/rose-care`: care with a touch of skill (water by holding, shade, weeds, petals), growth from days of care, drift, moods, her numbers; the care log in IndexedDB, replayed by the engine. Tuning R2/R4/R5/R6 is the author's. 7 of 7 put-back bugs caught after two test holes were closed. |
|
||||
| G1.5 | The day's sentence and the folded petal; the in-game sunset with the chair | Open. The sentence needs the library (G0.18). |
|
||||
| G1.3 | Towns have no Czech names (*Vídeň*) | Open. Natural Earth has none; arrives with Czech copy. |
|
||||
|
||||
## Design questions — answered
|
||||
|
||||
Raised by GAMEPLAY.md and ROADMAP.md, answered by the author 2026-11-01. Details in
|
||||
@@ -60,4 +73,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) |
|
||||
| ~~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 |
|
||||
| ~~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. |
|
||||
|
||||
@@ -61,7 +61,7 @@ typecheck and lint. Nothing imports it: not the app, not the packages.
|
||||
| A10 | Claude writes its review and the `final` paths into the board's rows. The card shows them. | Mark sees on the card what Claude checked and whether the picture is in the game, with no separate report to read. |
|
||||
| A11 | *Added 2026-11-01 (`art/phase2-3-pictures`).* The manifest also holds Phase 2 (the fox, berries, the bush, the brush) and the Phase 3 pictures whose mechanics are already decided (paths, lanterns). Every card carries a `phase`, the manifest lists phases in order, and the board shows *Phase N* on each card. | Mark asked for more pictures on the board. Making them now lets the fox's look settle before Phase 2 code depends on it. The phase on the card keeps a Phase 3 picture from being taken for something Phase 1 needs. |
|
||||
| A12 | **The planets are not on the board.** | Each planet is designed in its own feature doc (ROADMAP Phase 2), and their grown-ups are the book's most recognisable drawings. Asking for pictures before the design exists would fix a look with the highest likeness risk and no design behind it. |
|
||||
| A13 | The fox is a second character with his own sheet (`fox-sheet`) and two review points (STYLE.md §7, 8–9). His look (F1–F4 in STYLE.md §0) is a **draft for Mark**. Mark's approval covered S1–S5 only. | The same mechanism that keeps the rose consistent, reused. The draft is marked as one, so the approval is not stretched over choices he never saw. |
|
||||
| A13 | The fox is a second character with his own sheet (`fox-sheet`) and two review points (STYLE.md §7, 8–9). His look (F1–F4 in STYLE.md §0) was a draft, and Mark approved it on 2026-11-01 with one change: a deep red-orange coat (`#BC4A22`) instead of muted russet (`art/fox-coat`). | The same mechanism that keeps the rose consistent, reused. The draft was marked as one, so the rose's approval was not stretched over choices he had not seen. |
|
||||
| A14 | A stand-in with no drawing **stops the build**. Before this, an unknown cell got an empty box. | 28 new pictures made a silent blank likely. A blank stand-in looks like a layout bug, not a missing drawing. |
|
||||
|
||||
## 3. Risk analysis
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
# Keep her safe — the browser's promise, a file, and bringing her back
|
||||
|
||||
Status: built on `feature/keep-her-safe`. Gap G0.11, CLAUDE.md §8: *IndexedDB is evictable … call
|
||||
`navigator.storage.persist()` where it exists, prompt iOS players to install, and make export-my-rose
|
||||
a first-class feature. A player returning to find their rose gone is the cruellest bug this product
|
||||
could have.* Review: [`feature-keep-her-safe.md`](../reviews/feature-keep-her-safe.md).
|
||||
|
||||
---
|
||||
|
||||
## 1. Why and what, in the player's terms
|
||||
|
||||
Beside *Her numbers* there is now **Keep her safe**. It opens a small, quiet section:
|
||||
|
||||
- **What the browser has promised**, in one true sentence: that it keeps her, or that it may clear
|
||||
her if the garden is not opened for a long time.
|
||||
- **Ask the browser to keep her**, when it has not promised yet. If it says no, that is said calmly,
|
||||
and the file is the answer.
|
||||
- On an iPhone or iPad that has not added the garden to the Home Screen: *add it, to keep her.*
|
||||
- **Save her to a file**: a small file the player keeps, named for the day. It holds her care and
|
||||
when it was given; it never holds the town.
|
||||
- **Bring her back from a file**: on a new phone, or after the browser cleared her. Everything she
|
||||
had comes back, and nothing she has now is lost. Bringing the same file twice adds nothing twice.
|
||||
|
||||
An installed garden asks the browser to keep her by itself, once, after the first care of a visit.
|
||||
|
||||
## 2. Technical architecture
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph app["apps/rosea"]
|
||||
wire["App.svelte<br/>navigator.storage, file download"]
|
||||
end
|
||||
subgraph ui["packages/ui"]
|
||||
keep["KeepSafe.svelte"]
|
||||
rose["Rose.svelte<br/>keys = current + past"]
|
||||
end
|
||||
subgraph storage["packages/storage"]
|
||||
exp["exportRose / importRose<br/>asRoseFile"]
|
||||
past[("profile: pastKeys")]
|
||||
ev[("events")]
|
||||
end
|
||||
subgraph engine["packages/engine"]
|
||||
replay["roseAt(events, keys)<br/>one replay per key"]
|
||||
dedupe["newCare: each act once"]
|
||||
end
|
||||
wire --> keep --> exp --> ev & past
|
||||
exp --> dedupe
|
||||
rose --> replay
|
||||
```
|
||||
|
||||
### Decisions
|
||||
|
||||
| # | Decision | Why |
|
||||
|:--|:--|:--|
|
||||
| K1 | The file holds `{ format: 'rosea-rose', version: 1, keys, events }`: her public keys and her whole care log. **Never the private key** (it cannot be exported: rose.md R9), **never the sunset town**. | The town is the one location Rosea knows; choosing it again is one tap. The care log alone is what cannot be remade. |
|
||||
| K2 | A rose is named by **a list of keys**: the current identity first, then the keys she had on other devices (`profile.pastKeys`). | The private key cannot move, so a rose brought back lives under a new key, and her old care names the old one. The log is never rewritten (CLAUDE.md §6.2). |
|
||||
| K3 | **Each key's care is replayed on its own**; her days of care are the union. Water and today's needs come from the current key; stage, drift and warmth from all. | Replaying everything as one log could take a day away: one device's watering can make the other's "too much". Separate replays make bringing her back strictly additive, which is property-tested. |
|
||||
| K4 | Import **appends only acts not already there** (same moment, giver, rose, act and amount) in one transaction, and **refuses a file that is not a rose** before writing anything. | Contributions only add (CLAUDE.md §1). A wrong file is an ordinary mistake, said calmly. |
|
||||
| K5 | `persist()` is called **automatically only in an installed app**, once per visit, after the first care. Otherwise only when the player asks. | Chrome and Safari grant or refuse silently; Firefox shows a prompt. A prompt the player did not ask for, right after watering, would be a strange interruption. |
|
||||
| K6 | The download is made on the device (`Blob`, `<a download>`), and the import reads a file the player picks. | Nothing is sent anywhere; the CSP stays `'self'`. |
|
||||
|
||||
## 3. Risk analysis
|
||||
|
||||
| Risk | Answer |
|
||||
|:--|:--|
|
||||
| **The cruellest bug**: her care gone. | The file brings it back on any device, tested end to end with a fresh browser profile. |
|
||||
| **Privacy**: the file is a diary of when someone was in the app. | It is made only when the player asks, stays wherever they put it, and the screen says what it holds. No town, no private key (tested). |
|
||||
| **Feeling worse**: "the browser may clear her" can frighten. | It is said once, only on request, with the remedy in the same sentence. |
|
||||
| **A merged rose loses days.** | K3, property-tested: merging two logs never lowers either one's days of care. |
|
||||
| **A tampered file** gives a rose days she was never given. | It only fools the player's own garden; nothing is compared with anyone (CLAUDE.md §1, *never count people*). Phase 3 must not trust imported care as proof towards friends. |
|
||||
|
||||
## 4. Gap analysis
|
||||
|
||||
| Gap | State |
|
||||
|:--|:--|
|
||||
| G0.11 eviction: `persist()`, export-my-rose | Built: persist on request and when installed; save; bring back |
|
||||
| A reminder to save her now and then | Open: no nagging by design; the Letter can mention it |
|
||||
| iOS install prompt beyond one sentence | Open: Safari has no install API |
|
||||
|
||||
## 5. Verification matrix
|
||||
|
||||
| Case | Kind | Where |
|
||||
|:--|:--|:--|
|
||||
| A moved rose keeps every day under her old key; her water starts afresh; care under the new key adds | unit | `engine/test/rose.test.ts` |
|
||||
| A moved rose that is opening drops petals, and gathering them helps | unit | same |
|
||||
| Merging two logs never takes a day from either | property | same |
|
||||
| `newCare` adds each act once, however often | unit | same |
|
||||
| The file holds keys and care, no town, no private key; survives JSON | unit | `storage/test/rose-file.test.ts` |
|
||||
| Bringing her back on a new device, twice, onto a device with care of its own, from this very device; refusing seven kinds of not-a-rose and changing nothing | unit | same |
|
||||
| Keep her safe: the browser's answer, asking, a refusal said calmly, saving a dated file, bringing her back, a wrong file | unit | `ui/test/rose.test.ts` |
|
||||
| Save on one browser profile, bring her back on a fresh one, reload: one day of care; the file has no town; axe | e2e | `e2e/shell.spec.ts` |
|
||||
@@ -0,0 +1,120 @@
|
||||
# The rose — care with a touch of skill, growth from days of care, drift instead of loss
|
||||
|
||||
Status: built on `feature/rose-care`. ROADMAP Phase 1: *one rose with her face: care with a touch of
|
||||
skill (water by feel, shade, weeds, petals), moods, thorns, growth from total days of care, drift
|
||||
instead of loss, her numbers one tap away, and speech-bubble teaching* (GAMEPLAY.md §1–2, §4).
|
||||
Review: [`feature-rose-care.md`](../reviews/feature-rose-care.md). Not yet here: the day's sentence
|
||||
and the folded petal (the library is empty, G0.18), the in-game sunset with the chair.
|
||||
|
||||
---
|
||||
|
||||
## 1. Why and what, in the player's terms
|
||||
|
||||
The garden now has **the rose**. She stands in her bed under the sunset line, with a face in her
|
||||
bloom, and she says, in a small bubble, what she needs.
|
||||
|
||||
- **Water by feel.** Press and hold *Water*: the can pours slowly, and the rose's leaves lift when she
|
||||
has enough. Let go then. Pour too long and she is *too full*, which helps no more than too little.
|
||||
On a keyboard, hold Space or Enter; a screen reader hears when the leaves lift.
|
||||
- **Weeds** appear some mornings. **Fallen petals** some days, once she is opening. **Wind** comes on
|
||||
some days for an hour and a half: *Shade her* while it blows. Each button shows only when it is
|
||||
needed, so the screen stays quiet.
|
||||
- **She grows from days of care that helped**: a calendar day on which at least one act met a real
|
||||
need. Ten acts on one day count as one day. A long visit is worth no more than a short one.
|
||||
Bud → opening → half bloom → full bloom.
|
||||
- **She drifts, never breaks.** Some days without care and she turns a little away; a week, and she
|
||||
closes a little and waits. Her stage never goes down. The first helpful touch brings her back.
|
||||
- **Her numbers** are one tap away: water, warmth, days of care, and how she is doing. Nothing is
|
||||
counted against the player; there is no streak and no "missed".
|
||||
|
||||
## 2. Technical architecture
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph app["apps/rosea"]
|
||||
wire["App.svelte<br/>identity, zone, now, events"]
|
||||
end
|
||||
subgraph ui["packages/ui"]
|
||||
rose["Rose.svelte<br/>picture, bubble, care, numbers"]
|
||||
end
|
||||
subgraph engine["packages/engine (pure)"]
|
||||
model["rose/rose.ts<br/>roseAt(events, seed, now, zone)"]
|
||||
days["time/localDay.ts<br/>localDay, localMinutes"]
|
||||
model --> days
|
||||
end
|
||||
subgraph storage["packages/storage"]
|
||||
events[("events<br/>append-only")]
|
||||
keys[("keys")]
|
||||
end
|
||||
subgraph identity["packages/identity (new)"]
|
||||
id["createIdentity()<br/>ECDSA P-256, private key non-extractable"]
|
||||
end
|
||||
schema["packages/schema<br/>care event + amount"]
|
||||
wire --> rose --> model
|
||||
wire --> events & keys
|
||||
wire --> id
|
||||
model --> schema
|
||||
events --> schema
|
||||
```
|
||||
|
||||
- **The log is the truth** (CLAUDE.md §4). Every care act is one append-only `care` event. The rose
|
||||
at any moment is `roseAt(events, seed, now, timeZone)`: a pure replay. Nothing about her is stored
|
||||
except the log; `derived` is not needed while the replay is this cheap.
|
||||
- **Her hidden state** is a water level that falls over time and rises when poured. Weeds, petals and
|
||||
wind come from a seeded hash of the rose's own key and the local day, so they are the same on every
|
||||
replay and every device, and no randomness enters the engine.
|
||||
- **Identity** arrives because the care event names `from` and `to` by public key. For her own rose
|
||||
both are the player's key. The private key is non-extractable and kept by `@rosea/storage` as an
|
||||
opaque `CryptoKey`; nothing signs anything yet.
|
||||
|
||||
### Decisions
|
||||
|
||||
| # | Decision | Why |
|
||||
|:--|:--|:--|
|
||||
| R1 | **The care event gains `amount`** (0–1, required for `water`, absent otherwise). | "Pour slowly until the leaves lift; too much is as bad as too little" cannot be replayed from the act alone. The schema change is the sanctioned way to make it derivable (CLAUDE.md §6.2). |
|
||||
| R2 | **Water**: the level falls by 0.3 a day; a full pour (holding about 3 s) adds 0.6. She is thirsty below 0.25, needs water below 0.4, has enough from 0.4, and is too full above 0.95. A new rose starts at 0.3, so the first watering helps and teaches. | *Assumption for the author*: one helpful watering about every day and a half. |
|
||||
| R3 | **A pour helps** only when she needed it (below 0.4) and it leaves her between 0.4 and 0.95. | GAMEPLAY §1: too much is as bad as too little. |
|
||||
| R4 | **Weeds** grow overnight on about 40 % of days; **fallen petals** on about 30 % of days from the opening stage; **wind** on about 25 % of days, for 90 minutes starting between 9:00 and 18:00 local time. Each is a need until met that day. | *Assumption for the author.* Seeded per rose and day (FNV-1a), so replays agree. |
|
||||
| R5 | **Stages** from days of care: bud 0–2, opening 3–9, half bloom 10–24, full bloom 25+. | *Assumption for the author*: full bloom after about a month of real days. |
|
||||
| R6 | **Drift** from local days since the last helpful day: 0–2 none, 3–6 a little (turned away), 7+ more (closed a little, waiting). It changes her face, never her stage. | GAMEPLAY §1 and CLAUDE.md §8, *drift that reads as blame*: drawn as waiting. |
|
||||
| R7 | **Warmth** is the number of days of care in the last seven, said as *"3 days this week"*, and *"resting"* at none. **Trend**: *growing* (a day of care in the last two), *steady*, or *waiting* (drift). | GAMEPLAY §2 asks for warmth and trend. Words that never say *missed*. |
|
||||
| R8 | The day of an act is the local day **in the rose's zone**: the sunset town's zone, or the device's if there is none. | One zone for the sunset and the care, so a day means the same thing in both. |
|
||||
| R9 | **ECDSA P-256** for the identity keypair, not Ed25519. | Every browser that can install the PWA has it; Ed25519 arrived in Chrome only in 2025. Revisited with the Phase 3 identity doc. |
|
||||
| R10 | Her pictures are the **art board's stand-ins** until real art is accepted. A mood picture shows only at full bloom; before that, the stage picture. | The stand-ins exist for every stage and mood; the moods are drawn at full bloom only (art manifest). |
|
||||
|
||||
## 3. Risk analysis
|
||||
|
||||
| Risk | Answer |
|
||||
|:--|:--|
|
||||
| **Guilt.** A thirsty, closed rose after a week away can read as *you neglected me*. | She is *waiting*, never hurt; her words never say *forgot* or *missed*; one touch brightens her. The bubble copy passes `lint:copy` and the soul review below. |
|
||||
| **Streak by another name.** Warmth counts recent days. | It is shown only on request, never counts absence (*resting*, not *0 of 7*), and changes nothing about growth. |
|
||||
| **Compulsion.** Tapping for growth. | Growth is days, not acts: ten acts in one day are one day (property-tested). Buttons appear only when there is a need. |
|
||||
| **Skill as a barrier.** Holding to pour is hard for some hands. | Holding Space or Enter works; the leaves lifting is announced; a short pour can be topped up. |
|
||||
| **Location / reachability.** | None new. The events stay on the device; the key never leaves it. |
|
||||
| **A lost rose.** IndexedDB eviction (CLAUDE.md §8). | Not solved here: G0.11 (`persist()`, export-my-rose) is next. Stated in the review. |
|
||||
|
||||
## 4. Gap analysis
|
||||
|
||||
| Gap | Solution | State |
|
||||
|:--|:--|:--|
|
||||
| G1.4 The rose: care, growth, drift, moods, numbers | This feature | Built |
|
||||
| G0.15 `identity` deferred | `@rosea/identity`: create and keep a keypair | Built (minimal) |
|
||||
| G0.19 Event kinds other than `care` | Not needed yet | Open |
|
||||
| G0.11 Eviction: `persist()`, export-my-rose | Next | Open, more urgent now that there is a rose to lose |
|
||||
| The day's sentence, the folded petal | Needs the library (G0.18) | Open |
|
||||
| Speech-bubble lines from a curated library | Lines live in `ui/copy`, passing `lint:copy` | Built for the rose's needs |
|
||||
|
||||
## 5. Verification matrix
|
||||
|
||||
| Case | Kind | Where |
|
||||
|:--|:--|:--|
|
||||
| Water falls over time, a pour raises it, too much is too full; a pour helps only when needed and in range | unit | `engine/test/rose.test.ts` |
|
||||
| Weeds, petals and wind are the same on every replay, differ between roses, appear at about their rates | unit, property | same |
|
||||
| **Growth never decreases** as events are added; **many acts on one day count once**; **a gap never lowers the stage**; **replaying the same log twice gives identical state**; drift never changes the stage | property (fast-check) | same |
|
||||
| Drift levels at 0, 3 and 7 days; the first helpful act after a gap clears drift | unit | same |
|
||||
| Schema: `amount` required for water, refused elsewhere, bounded 0–1 | unit | `schema/test` |
|
||||
| Identity: a public key that fits the schema; the private key cannot be exported | unit | `identity/test` |
|
||||
| Storage: events append and come back in order; a malformed event is refused; keys round-trip | unit (fake-indexeddb) | `storage/test` |
|
||||
| UI: the rose shows her stage; holding Water pours and the leaves-lift announcement comes; Weed appears only with weeds; the numbers open on request | unit (testing-library) | `ui/test/rose.test.ts` |
|
||||
| Built app: water the rose by holding, see *1 day of care*, reload, still 1 | e2e | `e2e/shell.spec.ts` |
|
||||
| Offline: tend the rose with the server gone, reload, the care survived | offline | `e2e/offline.spec.ts` |
|
||||
@@ -0,0 +1,107 @@
|
||||
# The sun — real sunrise and sunset, on the device
|
||||
|
||||
Status: built on `feature/sun`. ROADMAP Phase 1, *the sun*. Review:
|
||||
[`feature-sun.md`](../reviews/feature-sun.md). The first piece of Phase 1, and the one the
|
||||
spike leaves behind even if the answer is no (ROADMAP §0: *a reusable sentence library and a sun
|
||||
module*).
|
||||
|
||||
---
|
||||
|
||||
## 1. Why and what, in the player's terms
|
||||
|
||||
Every day, at the player's **real** local sunset, the game invites them to put the phone down and
|
||||
look at the real one (CLAUDE.md §1). The rose's sentence is best opened then. The in-game sunset
|
||||
says when tonight's real one is. All of that needs one honest answer: *when does the sun set
|
||||
here, today?*
|
||||
|
||||
What the player gets from this piece alone: nothing on screen yet. What it guarantees:
|
||||
|
||||
- **The time is real.** It is computed from the sun's position and checked against a published
|
||||
almanac for six cities on four continents, both hemispheres, the equator and the Arctic.
|
||||
- **It never needs the network.** It is maths on the device. No lookup, no service.
|
||||
- **It never needs GPS.** The place is a city the player chose, or a guess from the device's time
|
||||
zone (CLAUDE.md §5.6 rule 6). Choosing that city is the app's job, later in Phase 1.
|
||||
- **The far north is not forgotten.** Where the sun does not set in summer or rise in winter, the
|
||||
engine still gives a gentle moment for the invitation (D4), never an error and never silence.
|
||||
- **A clock change is the clock's doing.** The sun moves a minute or two a day. When the clocks
|
||||
change, the sunset on the clock jumps an hour while the sun itself does nothing. The engine
|
||||
works in instants, so the jump only appears where the clock is read.
|
||||
|
||||
## 2. Technical architecture
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
app["apps/rosea (later in Phase 1)<br/>the chosen city or the device zone"] -->|"place, day"| sun
|
||||
subgraph engine["packages/engine (pure)"]
|
||||
sun["sun/sun.ts<br/>sunDay(day, place)<br/>invitation(sunDay)"]
|
||||
time["time/localDay.ts<br/>the only place a day is computed"]
|
||||
sun --> time
|
||||
end
|
||||
golden["engine/test/fixtures/sun-usno.json<br/>28 published days"] -.->|golden tests| sun
|
||||
script["scripts/fetch-sun-golden.ts<br/>run by hand, never by a test"] -.->|records| golden
|
||||
```
|
||||
|
||||
- **`sunDay(day, place)`** takes a `LocalDay` and `{ lat, lon, timeZone }` and returns one of
|
||||
three shapes: `sun-sets` (sunrise, solar noon, sunset), `polar-day` (solar noon, lowest light) or
|
||||
`polar-night` (solar noon). Every time is an epoch-milliseconds instant.
|
||||
- **`invitation(sunDay)`** is the instant the game invites the player outside: the sunset, or the
|
||||
polar alternative (D4). The app renders it and decides nothing.
|
||||
- **The algorithm** is NOAA's solar calculator (after Meeus, *Astronomical Algorithms*): the sun's
|
||||
declination and the equation of time at a given instant, then the hour angle at which its
|
||||
centre is 0.833° below the horizon (refraction and the sun's radius). Each event is refined by
|
||||
recomputing at its own instant.
|
||||
|
||||
### Decisions
|
||||
|
||||
| # | Decision | Why |
|
||||
|:--|:--|:--|
|
||||
| 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. |
|
||||
| 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. **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. |
|
||||
| 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. |
|
||||
| D8 | Where a clock is about twelve hours off the sun, one calendar day a year can hold no solar noon. The engine then gives the nearest noon and never throws. | Found by fast-check at 179.9° W on UTC: noon crosses midnight in late December, so 26 December has none. No real zone is that far off the sun (the worst are about three hours), so the property tests give each place a zone that follows its longitude, and a unit test pins the impossible case. |
|
||||
|
||||
## 3. Risk analysis
|
||||
|
||||
Risk here means a person feeling worse, a person's location, or a person becoming reachable.
|
||||
|
||||
| Risk | Where | Answer |
|
||||
|:--|:--|:--|
|
||||
| **A wrong sunset sends someone out to a dark sky**, or too late. A broken promise from the one feature that points beyond the screen. | Correctness | Golden tests in six cities, including DST days; property tests across latitudes and days. |
|
||||
| **The far north gets nothing** — no sunset, so no invitation, every day for months. A person left out by geography. | Soul | D4: a defined, gentle moment on every day, tested at Tromsø and at ±80°. |
|
||||
| **The time is used to find someone.** A sunset time narrows down where a person lives. | Privacy | It is computed and kept on the device. This module has no I/O at all, and the engine's lint rule forbids it. Phase 4's shared sky uses a coarse cell and a day bucket only (CLAUDE.md §4), never this. |
|
||||
| **The test fixture holds coordinates.** | Privacy | City centres from public sources, never a player. No test uses a real person's location (§5.5). |
|
||||
| **A DST day records the wrong local day** for a sunset, and the rose's sentence moves to the wrong day. | Correctness | The day is only ever computed by `localDay`. Tested on all six DST transition days in the fixture. |
|
||||
|
||||
Reachability: none. The module talks to no one.
|
||||
|
||||
## 4. Gap analysis and the designed solution
|
||||
|
||||
| Gap | Solution | State |
|
||||
|:--|:--|:--|
|
||||
| No `engine/src/sun/` (CLAUDE.md §2, §7: *one module computes the sun*) | `sun/sun.ts`: `sunDay`, `invitation` | Built |
|
||||
| Polar day and night: a predicted trap (CLAUDE.md §8) | Two defined kinds and D4. **Measured**: Tromsø has no rise or set on 21 June and no events on 21 December | 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 |
|
||||
| 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) | Noon twilight | Decided by the author (Q10) |
|
||||
|
||||
## 5. Verification matrix
|
||||
|
||||
| Case | Kind | Where |
|
||||
|:--|:--|:--|
|
||||
| Sunrise, solar noon and sunset match the USNO table within 2 min, in the city's own clock, on 26 days in 6 cities | unit, golden | `engine/test/sun.test.ts` |
|
||||
| The fixture's offset agrees with the IANA zone on every day, so the table and the zone database tell the same story | unit, golden | same |
|
||||
| Tromsø 21 June is polar day; 21 December is polar night | unit, golden | same |
|
||||
| Reykjavík midsummer: tonight's sunset falls after midnight, on the next local day (D2) | unit, golden | same |
|
||||
| A DST change moves the clock's sunset by an hour while the instant moves by about a day | unit | same |
|
||||
| For any latitude within ±60°, any longitude and any day of 2026: sunrise < noon < sunset, noon is midway, noon is on the asked day | property | same |
|
||||
| Sunsets on consecutive days are never more than 5 minutes apart within ±60° | property | same |
|
||||
| ±80° on the solstices: polar day and night, the right way round in each hemisphere | unit | same |
|
||||
| The invitation is the sunset, the lowest light, or noon, by kind | unit, property | same |
|
||||
| A day that does not exist, a latitude above 90°, an unknown zone: refused | unit | same |
|
||||
| Nothing leaves the device | lint | the engine purity rule already covers `src/sun/` |
|
||||
| Choosing a city, and seeing the time in the app | e2e, offline | **later in Phase 1** |
|
||||
@@ -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` |
|
||||
@@ -10,11 +10,11 @@ and **how to apply it**.
|
||||
| `architecture.md` | none yet | Layering, ownership, seams. |
|
||||
| `design.md` | none yet | Wording, silence, empty states. |
|
||||
| [`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. |
|
||||
| [`testing.md`](testing.md) | 6 | What makes a test worth having, and how a passing test lies. |
|
||||
| [`testing.md`](testing.md) | 9 | 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.) |
|
||||
| [`process.md`](process.md) | 2 | Workflow, commits, credentials, honesty about what shipped. |
|
||||
| [`process.md`](process.md) | 3 | Workflow, commits, credentials, honesty about what shipped. |
|
||||
|
||||
A file is created with its first real entry. An empty lessons file only looks like
|
||||
knowledge.
|
||||
|
||||
@@ -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
|
||||
return or `&&` (`const target = heading; if (moved) target?.focus();`). Test the
|
||||
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, {})`.
|
||||
|
||||
@@ -31,3 +31,17 @@ better source of versions than the registry.
|
||||
|
||||
**How to apply it.** Start a new repository from a sibling's resolved versions, and
|
||||
pin them exactly. Unpin deliberately, in its own commit, after upgrading Node (G0.20).
|
||||
|
||||
## A rule checked by reading a number is broken by the next command
|
||||
|
||||
**What happened.** CLAUDE.md §5.7 says not to start a full run above ~80 % CPU. Three
|
||||
times on 2026-11-02 a run started above it. Once the load was not checked at all; twice it
|
||||
was read (85 %, then 100 %, another project's tests) and the run started anyway, once
|
||||
because the check and the run were chained in one command that did not depend on it.
|
||||
|
||||
**Why it bit.** A rule that relies on a person reading a number before acting holds only
|
||||
while nothing else is competing for attention.
|
||||
|
||||
**How to apply it.** Make the run refuse to start: a gate script that samples the load
|
||||
and exits above 80 %, waiting or saying so. Until it exists, read the number in its own
|
||||
step and decide before starting the run.
|
||||
|
||||
@@ -87,3 +87,47 @@ 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
|
||||
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.
|
||||
|
||||
## A test that fails for another reason proves nothing about this one
|
||||
|
||||
**What happened.** On 2026-11-02 two bug drills on the rose passed. Making too much water
|
||||
"help" was not caught: every too-full test poured on a rose that did not need water, so
|
||||
it failed for that reason and never reached the too-full rule. Replaying the log in
|
||||
stored order instead of time order was not caught either: the shuffle property rarely
|
||||
built a log in which order changes the outcome.
|
||||
|
||||
**Why it bit.** A guard with two conditions is tested only when one input passes the
|
||||
first and fails the second. A random property can pass a hundred runs and never build
|
||||
the one case that matters.
|
||||
|
||||
**How to apply it.** For each condition, write the case where only it decides (from
|
||||
0.39 a full can overshoots: needed, too full). For an order property, add one fixed
|
||||
log where order changes the answer. Then put the bug back and watch the test fail.
|
||||
|
||||
## `toEqual` cannot see a field that is `undefined`
|
||||
|
||||
**What happened.** On 2026-11-02 a drill made the rose's export file carry an extra field
|
||||
taken from the identity. The test passed: it kept no identity, so the field was
|
||||
`undefined`; `toEqual` treats a missing property and an undefined one as equal, and
|
||||
`JSON.stringify` drops it, so the text check saw nothing either.
|
||||
|
||||
**Why it bit.** "Nothing else in it" is a claim about absent fields, and the default
|
||||
equality is blind to exactly the field that is absent by accident.
|
||||
|
||||
**How to apply it.** For "holds this and nothing else", use `toStrictEqual`, and give the
|
||||
test something real to leak (here, a kept identity).
|
||||
|
||||
@@ -48,7 +48,7 @@ cards with *Phase N* on each, and no broken image.
|
||||
| 5 | Test honesty | Two tests used *fox* as their example of a thing not in the manifest (`unknown character "fox"`, `"fox-sheet" is not a picture`). Adding the fox made them fail for the wrong reason. | **Fixed**: the example is now *owl*. Lesson: `testing.md`. |
|
||||
| 6 | Soul | A lantern unlit could read as *nobody answered*. | **Covered by the game, not the picture**: a lantern only one player lit is never shown to the other (CLAUDE.md §8). The unlit cell is described as "quiet, not sad". |
|
||||
| 7 | Scope | Paths and lanterns are Phase 3. The screen that shows two roses and the path between them is not designed. | **Deferred, said on the card**: F4 and the card's *usedBy* say the Phase 3 feature doc may ask for them again. |
|
||||
| 8 | Process | STYLE.md was approved an hour earlier. Adding the fox under that heading would stretch the approval over choices Mark never saw. | **Fixed**: F1–F4 are listed as a draft in §0. HANDOVER asks Mark to approve them before `fox-sheet`. |
|
||||
| 8 | Process | STYLE.md was approved an hour earlier. Adding the fox under that heading would stretch the approval over choices Mark never saw. | **Fixed**: F1–F4 were listed as a draft in §0. Mark then approved them with a deeper red-orange coat (`art/fox-coat`). |
|
||||
| 9 | Process | The full run started with the machine at 85 % CPU. §5.7 says not above ~80 %. The load was not checked first. | **Noted.** The run passed and nothing else was disturbed, but the check comes first next time. |
|
||||
| 10 | Process | A cleanup step in the drill command would have removed `F:\manifest.bak`, a path at the drive's root. The safety check refused it, and nothing ran. | **Fixed**: the drill was rerun with backups only in the scratchpad and no removal. |
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# Review — `feature/keep-her-safe`
|
||||
|
||||
Adversarial self-review (CLAUDE.md §5.3). Analysis: [`features/keep-her-safe.md`](../features/keep-her-safe.md).
|
||||
Reviewed 2026-11-02 on Node 22.11.0, Windows 10. There is no PR: the only remote is Gitea.
|
||||
|
||||
## Gates
|
||||
|
||||
Counts are on the merge; HANDOVER repeats them. New here: engine +4, storage +6, ui +5, e2e +1
|
||||
(save on one browser profile, bring her back on a fresh one, reload).
|
||||
|
||||
**The app changed** (CLAUDE.md §5.4): *Keep her safe* beside *Her numbers*. Rebuilt by the e2e run;
|
||||
**not deployed** (no host, G0.13).
|
||||
|
||||
## Bug drills — each put back once
|
||||
|
||||
| Put back | Result |
|
||||
|:--|:--|
|
||||
| Only the current key counts | CAUGHT: 3 |
|
||||
| One replay for all keys (the lossy merge K3 avoids) | CAUGHT: 2, the merge property among them |
|
||||
| Import appends acts already there | CAUGHT: 2 |
|
||||
| Export leaks a field from the identity | **MISSED at first** (finding 1), then CAUGHT |
|
||||
| A file with one bad act half-imports the rest | CAUGHT |
|
||||
|
||||
## Findings
|
||||
|
||||
| # | Area | Finding | Resolution |
|
||||
|:--|:--|:--|:--|
|
||||
| 1 | Test honesty | The "nothing else in the file" test kept no identity, so a leaked field was `undefined`; `toEqual` treats a missing and an undefined property as equal, and `JSON.stringify` drops it. The leak drill passed. | **Fixed**: the test keeps a real identity and uses `toStrictEqual`. Lesson: `testing.md`. |
|
||||
| 2 | Correctness | The private key cannot be exported, so a rose brought back lives under a new key. | K2: a rose is named by her current key and her past keys; the log is never rewritten. |
|
||||
| 3 | Correctness | Replaying two devices' care as one log can take a day away (one watering makes the other "too much"). | K3: one replay per key, days unioned; property-tested. |
|
||||
| 4 | Correctness | Weeds, petals and wind are seeded by key, so a moved rose's pattern of needs changes. | Accepted: the pattern is arbitrary, and her days, stage and drift come with her. A moved rose that is opening still drops petals (tested). |
|
||||
| 5 | Privacy | The file is a diary of when someone was in the app. | Made only on request; the screen says what it holds; no town and no private key (tested in unit and e2e). It goes wherever the player puts it, which Rosea cannot see. |
|
||||
| 6 | Privacy | A file brought back could have been edited by hand to give her days she was never given. | It only changes the player's own garden; nothing is counted against anyone (CLAUDE.md §1). Phase 3 must not treat imported care as proof towards friends: noted in the analysis. |
|
||||
| 7 | Soul | "This browser may clear her" can frighten. | Shown only behind *Keep her safe*, with the remedy in the same sentence; a refusal is said calmly. Nothing reminds or nags. |
|
||||
| 8 | Process | The first e2e run **and the full gate run** both started with the CPU at 100 %, above the 80 % rule (CLAUDE.md §5.7). The load was another project's test run on this machine. The second time the reading was taken, but the run was chained after it without depending on it. Both passed. | **Not fixed by intention alone**: a gate script that refuses to start above 80 % would make the rule real. Lesson: `process.md`. |
|
||||
| 9 | Accessibility | A file input styled as a button. | The real input stays in place, labelled by its text, keyboard-operable; axe passes on the restored garden. Not tested with a screen reader. |
|
||||
|
||||
## What was not verified
|
||||
|
||||
- `persist()` in real browsers: Chromium under Playwright only answers for itself. Firefox's prompt,
|
||||
Safari's behaviour, and an installed app's automatic call (K5) were not seen.
|
||||
- The iOS hint on a real iPhone.
|
||||
- A file saved by a later version of Rosea (`version` 2): refused today, by design.
|
||||
@@ -0,0 +1,55 @@
|
||||
# Review — `feature/rose-care`
|
||||
|
||||
Adversarial self-review (CLAUDE.md §5.3). Analysis: [`features/rose.md`](../features/rose.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
|
||||
|
||||
Counts are on the merge; HANDOVER repeats them.
|
||||
|
||||
| Gate | Result |
|
||||
|:--|:--|
|
||||
| `pnpm lint` / `pnpm typecheck` | exit 0 / exit 0, `@rosea/identity` included |
|
||||
| `pnpm test` | see HANDOVER; new: **engine rose 21**, **identity 5**, **storage +27**, **ui rose 7**, schema +1 |
|
||||
| `pnpm test:e2e` | **12 passed** (+2): water the rose by holding, reload, one day of care; axe on the rose and her numbers |
|
||||
| `pnpm test:offline` | **1 passed**: the rose is watered with the server gone, the tab closed, and the care is still there |
|
||||
|
||||
**The app changed** (CLAUDE.md §5.4): the garden has the rose. The bundle was rebuilt by the e2e and
|
||||
offline runs; it is **not deployed** (no host, G0.13). Seen at phone width (390 px) in Chromium,
|
||||
in three states: new, pouring, with her numbers open.
|
||||
|
||||
## Bug drills — each put back once
|
||||
|
||||
| Put back | Result |
|
||||
|:--|:--|
|
||||
| Growth counts acts, not days | CAUGHT: 10 |
|
||||
| Drift lowers the stage | CAUGHT: 3 (the gap property among them) |
|
||||
| Too much water still helps | **MISSED at first** (finding 1), then CAUGHT |
|
||||
| The log replayed in stored order, not time order | **MISSED at first** (finding 1), then CAUGHT |
|
||||
| Storage lets `amount` ride on a weed | CAUGHT: 2 (one is the agreement with the schema validator) |
|
||||
| Letting go does not stop the pour | CAUGHT: 2 |
|
||||
| No greeting after a gap | CAUGHT |
|
||||
|
||||
## Findings
|
||||
|
||||
| # | Area | Finding | Resolution |
|
||||
|:--|:--|:--|:--|
|
||||
| 1 | Test honesty | Two drills passed. Every too-full test started from a rose that did not need water, so it failed for the other reason; and the shuffled-replay property rarely built a log where order changes anything. | **Fixed**: a full can from 0.39 overshoots and must not help; two waterings stored in reverse must still be two days. Lesson: `testing.md`. |
|
||||
| 2 | Soul | After a month away she is dry (0), and a half can leaves her at 0.3, still below "enough": the player poured, she still waits. | **Kept, with care**: the can says *Her leaves lift* only when they do, and her line asks for water slowly. A fuller pour brings her back. If players read it as failure, R2's numbers change, not the rule. |
|
||||
| 3 | Soul | Warmth counts recent days, a streak by another name. | Shown only on request, *resting* at none, never *0 of 7*, and it changes nothing. Watch it in the Phase 1 gate. |
|
||||
| 4 | Soul | Drift could read as blame. | She is turned a little away and *waiting*; her first words are *"There you are."*; nothing says *forgot* or *missed* (`lint:copy` passes, copy read by hand). |
|
||||
| 5 | Correctness | `amount` was added to a contract (§6.2). | R1. Required for water, refused elsewhere; Ajv, the generated type and storage's own check agree on 20 variants. The root `if`/`then`/`else` keeps `CareEvent` a strict interface (an `allOf` had added `[k: string]: unknown`). |
|
||||
| 6 | Correctness | Two tabs creating two identities. | `keepIdentity` keeps the first in one transaction and returns it to both; tested with two connections racing. Two tabs **appending care** at once is fine: the log is append-only and the replay sorts by time. |
|
||||
| 7 | Correctness | A DST day or a zone change. | The day of an act is recorded when it happens and never recomputed. Wind uses the local clock in the rose's zone. A player who changes their sunset town to another zone shifts later days only. |
|
||||
| 8 | Privacy | A keypair now exists. | Made on the device; the private key is non-extractable (tested); nothing signs or sends anything. The public key appears only in the local log. |
|
||||
| 9 | Privacy | The care log is a diary of when someone was in the app. | It never leaves the device; no feature reads it but the replay. Phase 3 must decide what a friend may see, against CLAUDE.md §6.3. |
|
||||
| 10 | Scope | IndexedDB eviction can take the rose (CLAUDE.md §8, *the cruellest bug*). | **Not solved here**: G0.11 (`persist()`, export-my-rose) is now the most urgent open gap. |
|
||||
| 11 | Design | The water meter is the browser's default green; *"The garden is being prepared."* is now a little stale. | Cosmetic, left for the garden's real art. |
|
||||
| 12 | Accessibility | Holding is hard for some hands. | Space and Enter pour too (tested); the leaves lifting is announced (`role=status`); a short pour can be topped up. axe passes. Not tested with a real screen reader. |
|
||||
|
||||
## What was not verified
|
||||
|
||||
- A real phone, touch, Safari, Firefox, a screen reader.
|
||||
- The tuning (R2, R4, R5, R6): no person has played it for a week. These are the author's to set.
|
||||
- Wind and petals in the browser: their days depend on the random key, so e2e cannot predict them;
|
||||
unit tests cover them with fixed keys.
|
||||
@@ -0,0 +1,51 @@
|
||||
# Review — `feature/sun`
|
||||
|
||||
Adversarial self-review (CLAUDE.md §5.3). Analysis: [`features/sun.md`](../features/sun.md).
|
||||
Reviewed 2026-11-01 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, the engine purity rule included: `src/sun/` reads no clock, no network, no device |
|
||||
| `pnpm typecheck` | exit 0, `scripts/fetch-sun-golden.ts` included |
|
||||
| `pnpm test` | **236 passed**: schema 15, content 47, art-prep 56, **engine 102 (+50 sun)**, ui 16 |
|
||||
| `pnpm test:e2e` / `test:offline` | 7 passed / 1 passed. **The app is unchanged**: nothing imports the sun yet |
|
||||
|
||||
**Golden.** 26 published days in 6 cities match the U.S. Naval Observatory's tables within
|
||||
2 minutes on the city's own clock, for sunrise, solar noon and sunset. Two more days, Tromsø's polar
|
||||
day and night, match the table's *no event*. The table's clock offset agrees with the IANA zone
|
||||
database on all 28 days.
|
||||
|
||||
**Stable.** The property tests ran three times with fresh seeds, 50 of 50 each time.
|
||||
|
||||
## Bug drills — each put back once, in `src/sun/sun.ts`
|
||||
|
||||
| Put back | Result |
|
||||
|:--|:--|
|
||||
| No refraction: the horizon at 90° instead of 90.833° | CAUGHT: 27 failures, every golden day |
|
||||
| No equation of time | CAUGHT: 25 failures |
|
||||
| Polar day and polar night swapped | CAUGHT: 8 failures |
|
||||
| No local-day correction of solar noon | CAUGHT: 2 failures (Kiritimati, D8) |
|
||||
| The UTC date derived back from the noon instant (finding 2's bug) | CAUGHT: 3 failures (properties near 180°) |
|
||||
|
||||
## Findings
|
||||
|
||||
| # | Area | Finding | Resolution |
|
||||
|:--|:--|:--|:--|
|
||||
| 1 | Correctness | The published table for Reykjavík on 21 June lists a sunset at 00:04. That is the **previous evening's** sunset. A naive "events within the calendar day" design would tell a player in Reykjavík that tonight's sunset was 00:04 this morning. | **By design (D2)**: today's sunset is the one after today's solar noon. Tested: it falls on 22 June, local. |
|
||||
| 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. |
|
||||
| 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 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. |
|
||||
| 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). |
|
||||
| 9 | Test honesty | The DST tests read the clock with `Intl` in the test, which is also what `localDay` uses. A bug in the platform's zone data would hide in both. | Cross-checked: the USNO table states each day's offset independently, and a test asserts the zone database agrees on all 28 days. |
|
||||
|
||||
## What was not verified
|
||||
|
||||
- Accuracy on the days right at the edge of polar day or night (finding 4).
|
||||
- Latitudes above 72° on ordinary days, other than Tromsø's 69.6°.
|
||||
- Years far from 2026. The method holds for centuries, but only 2026 is tested.
|
||||
- The app: choosing a city, the time-zone guess, and showing the time are later in Phase 1 (G1.2).
|
||||
@@ -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.
|
||||
@@ -115,8 +115,8 @@ feed of anything.
|
||||
|
||||
## 2. Repository layout
|
||||
|
||||
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 0 scaffolded `schema`, `engine`, `content`, `ui`, `apps/rosea`, `tools/art-prep` and `art/`;
|
||||
Phase 1 added `storage` (`profile`, `events`, `keys`) and `identity` (a keypair). `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).
|
||||
|
||||
```
|
||||
@@ -214,13 +214,15 @@ pnpm build # turbo: schema -> engine/content/ui ->
|
||||
pnpm lint # ESLint, incl. the engine-purity rule (§7)
|
||||
pnpm typecheck # tsc + svelte-check, every package plus e2e/ and scripts/
|
||||
pnpm test # vitest, all packages — quote counts per package
|
||||
pnpm --filter @rosea/engine test # incl. fast-check property tests (sun golden tests: later)
|
||||
pnpm --filter @rosea/engine test # incl. fast-check property tests and the sun golden tests
|
||||
tsx scripts/fetch-sun-golden.ts # re-records the sun's published tables (network; by hand, never in a test)
|
||||
pnpm test:e2e # builds, then Playwright against the BUILT app under /Rosea/
|
||||
pnpm test:offline # builds, loads once, CLOSES the server, reloads
|
||||
pnpm validate:library # every hope sentence; fixtures must FAIL
|
||||
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: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:
|
||||
cargo test --manifest-path services/lucerna/Cargo.toml # Phase 4 onward
|
||||
@@ -488,8 +490,8 @@ No timestamp finer than a day, no precise location, no free text, no link to the
|
||||
| Trap | Why it bites |
|
||||
|:--|:--|
|
||||
| **A PWA cannot schedule a local notification** *(predicted — verify first)* | The sunset invitation is time-based. A web app generally cannot fire a notification at a set time while closed without a **push server** sending it, and a push server that knows when someone's sunset is knows roughly where they are. On iOS, web push works only for a site added to the home screen. **Decided in Phase 0 (2026-11-01):** in-app sunset only for the web build — no push server — and local notifications through the Tauri shell later (Phase 6). |
|
||||
| **Polar day and polar night** *(predicted)* | Above the Arctic Circle the sun does not set in summer or rise in winter. "Every day at sunset" has no answer there. The engine must return a defined state and the game must have a gentle alternative (e.g. the hour the light is lowest). |
|
||||
| **DST and the local day** *(predicted)* | Sunset jumps an hour twice a year under a player who did nothing; a day boundary computed in UTC records Monday-evening care as Tuesday's. One module computes the day. |
|
||||
| **Polar day and polar night** *(measured 2026-11-01)* | Above the Arctic Circle the sun does not set in summer or rise in winter. "Every day at sunset" has no answer there. Measured: the almanac has no rise or set in Tromsø on 21 June and no events at all on 21 December. `engine/sun` returns `polar-day` or `polar-night` and a gentle moment for each (the lowest light; noon twilight) — `.agents/features/sun.md` D4. |
|
||||
| **DST and the local day** *(measured 2026-11-01)* | Sunset jumps an hour twice a year under a player who did nothing: Prague's is 18:28 on 28 March and 19:29 on the 29th, while the sun moved one minute. A day boundary computed in UTC records Monday-evening care as Tuesday's. One module computes the day; the sun works in instants. |
|
||||
| **Comfort becomes wallpaper** | The same words every day stop meaning anything. Comfort words are occasional; the real trace of a real person is constant. Track repetition in tests. |
|
||||
| **Guilt sneaks in through "gentle" reminders** | "Your rose misses you" is guilt wearing a ribbon. No notification ever refers to neglect — the player's or anyone else's. |
|
||||
| **Streak creep** | Someone will propose "just a small streak". Growth is from total care; a missed day never resets anything. |
|
||||
@@ -500,7 +502,7 @@ No timestamp finer than a day, no precise location, no free text, no link to the
|
||||
| **The library as a scam channel** | If any field lets a sender attach free text, a lonely recipient can be manipulated. The id-only contract (§6.1) is the defence. |
|
||||
| **Copyright through the back door** | An image prompt "in the style of" the book's drawings, a fox or rose that looks like the original, or a famous line "paraphrased" too closely. All forbidden (§5.6); the art pipeline checks likeness (`docs/ART.md`). |
|
||||
| **Medical claims in a store listing** | One word like *heal* in marketing copy can pull the product toward medical-device rules. `lint:copy` also runs on store text kept in the repo. |
|
||||
| **IndexedDB is evictable** *(predicted)* | WebKit can discard origin storage after seven days without interaction — exactly the shape of a player who drifted away and comes back. Call `navigator.storage.persist()` where it exists, prompt iOS players to install, and make export-my-rose a first-class feature. A player returning to find their rose gone is the cruellest bug this product could have. |
|
||||
| **IndexedDB is evictable** *(predicted; answered by `keep-her-safe.md`)* | WebKit can discard origin storage after seven days without interaction — exactly the shape of a player who drifted away and comes back. Call `navigator.storage.persist()` where it exists, prompt iOS players to install, and make export-my-rose a first-class feature. A player returning to find their rose gone is the cruellest bug this product could have. |
|
||||
| **The stale service worker** | A precached shell keeps serving old JS to a player who has "updated". Detect a waiting worker and offer an explicit, calm *refresh* control. |
|
||||
| **Two tabs, one database** *(predicted)* | Two event streams into one store; derived state drifts. Use a `BroadcastChannel` lock. |
|
||||
| **GitHub Pages serves under a sub-path** *(predicted)* | A project site lives at `/<repo>/`, not `/`. Vite `base`, the web manifest `start_url` and `scope`, and the service worker scope must all agree, or the installed app opens a 404 or never updates. The offline suite runs against the same base path. |
|
||||
|
||||
@@ -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).
|
||||
Review, with counts and the mutation results:
|
||||
[`.agents/reviews/feature-phase0-workspace.md`](.agents/reviews/feature-phase0-workspace.md).
|
||||
- **Gates:** all pass on this machine. Unit tests: 186 (schema 15, content 47,
|
||||
art-prep 56, engine 52, ui 16). E2E: 7. Offline: 1. `lint:copy`: 12 files, 0 problems.
|
||||
- **Gates:** all pass on this machine. Unit tests: 373 (identity 5, schema 16, content 71,
|
||||
storage 51, art-prep 56, engine 136, ui 38). E2E: 13. Offline: 1. `lint:copy`: 19 files, 0 problems.
|
||||
`validate:library`: 13 of 13 fixtures rejected.
|
||||
- **Built, not deployed:** there is no host yet.
|
||||
- **Roadmap and gameplay docs:** `docs/ROADMAP.md` and `docs/GAMEPLAY.md` are on
|
||||
@@ -35,6 +35,37 @@ Rewritten at the end of each session (CLAUDE.md §5.1).
|
||||
republish `tools/art-prep/dist/board/` to that URL. Review:
|
||||
[`.agents/reviews/feature-art-board.md`](.agents/reviews/feature-art-board.md).
|
||||
|
||||
- **The sun (Phase 1 begins):** merged to `main`. `packages/engine/src/sun/sun.ts` gives
|
||||
sunrise, solar noon and sunset for a local day and a place, or polar day or night, and the
|
||||
moment the game invites the player out. It matches the U.S. Naval Observatory's tables within
|
||||
2 minutes in Prague, Reykjavík, Tromsø, Quito, Sydney and Anchorage, DST days included.
|
||||
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).
|
||||
|
||||
- **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).
|
||||
|
||||
- **The rose (Phase 1):** merged to `main`. She stands in the garden with her face and says what
|
||||
she needs. Water by holding the button until her leaves lift (Space or Enter too); shade her in
|
||||
the wind, pull the weeds, gather fallen petals, each shown only when needed. She grows from days
|
||||
on which care helped, drifts and waits when left, never loses her stage; her numbers are one tap
|
||||
away. Every act is one append-only event in IndexedDB (`events`), replayed by `engine/rose`. The
|
||||
care event gained `amount` for watering. `@rosea/identity` makes the player's keypair, kept in
|
||||
`keys`. Analysis: [`.agents/features/rose.md`](.agents/features/rose.md). Review:
|
||||
[`.agents/reviews/feature-rose-care.md`](.agents/reviews/feature-rose-care.md).
|
||||
- **Keep her safe (G0.11):** merged to `main`. Beside *Her numbers*, *Keep her safe* says what the
|
||||
browser has promised, asks it to keep her, saves her to a file (her care and keys; never the town,
|
||||
never the private key) and brings her back from one, on any device, without losing anything she
|
||||
has there. A rose is now named by her current key and her past keys. Analysis:
|
||||
[`.agents/features/keep-her-safe.md`](.agents/features/keep-her-safe.md). Review:
|
||||
[`.agents/reviews/feature-keep-her-safe.md`](.agents/reviews/feature-keep-her-safe.md).
|
||||
|
||||
**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
|
||||
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).
|
||||
@@ -46,13 +77,17 @@ The notification decision is made: in-app only on the web (G0.26).
|
||||
door to real help (G0.27), and Q9 (may the letter name the book).
|
||||
2. **Sentences:** an agent may propose public-domain candidates with their sources.
|
||||
Only the author can mark one verified.
|
||||
3. **Art:** the style is approved (S1–S5). The fox's look, F1–F4 in `art/STYLE.md` §0, is a draft:
|
||||
approve it or change it before making `fox-sheet`. Make `rose-sheet` on the board and accept it. That is the first step of the Phase 0 art gate.
|
||||
3. **Art:** the style is approved (S1–S5), and so is the fox (F1–F4, with a deep red-orange coat).
|
||||
Make `rose-sheet` on the board and accept it; `fox-sheet` comes first for Phase 2. That is the first step of the Phase 0 art gate.
|
||||
After an accept, Claude reads the row (`ArtifactData get art/<id>`), downloads the picture
|
||||
(`Artifact read` with the asset id as `path`), runs `pnpm art:accept`, commits on `art/<set>`,
|
||||
and writes `final` back into the row.
|
||||
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).
|
||||
6. **The rose's tuning** (`.agents/features/rose.md` R2, R4, R5, R6, all in `ROSE` in
|
||||
`packages/engine/src/rose/rose.ts`): how fast she gets thirsty, how often weeds, petals and wind
|
||||
come, and how many days of care each stage takes (full bloom after 25). Play it for a week,
|
||||
then say what feels wrong.
|
||||
|
||||
**How this machine works** (not in the code):
|
||||
|
||||
|
||||
@@ -10,7 +10,10 @@
|
||||
"typecheck": "svelte-check --threshold error --output human"
|
||||
},
|
||||
"dependencies": {
|
||||
"@rosea/content": "workspace:*",
|
||||
"@rosea/identity": "workspace:*",
|
||||
"@rosea/schema": "workspace:*",
|
||||
"@rosea/storage": "workspace:*",
|
||||
"@rosea/ui": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,7 +1,97 @@
|
||||
<script lang="ts">
|
||||
import { Shell } from '@rosea/ui';
|
||||
import { guessTown } from '@rosea/content/guess';
|
||||
import { createIdentity } from '@rosea/identity';
|
||||
import { openStorage } from '@rosea/storage';
|
||||
import { Shell, type RoseWiring, type SunsetWiring } from '@rosea/ui';
|
||||
import { version } from '../package.json';
|
||||
// Bundled at build time, so the letter is precached and opens offline (letter-slot.md L1).
|
||||
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 storage = openStorage();
|
||||
|
||||
// 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: () => storage.loadSunsetPlace(),
|
||||
save: (choice) => storage.saveSunsetPlace(choice),
|
||||
now: () => Date.now()
|
||||
};
|
||||
|
||||
// The player's key names their rose (rose.md). Kept once; if the device will not
|
||||
// keep it, this visit still has a rose, under a key that lasts until closing.
|
||||
let identity: ReturnType<RoseWiring['identity']> | undefined;
|
||||
async function findIdentity(): ReturnType<RoseWiring['identity']> {
|
||||
try {
|
||||
const kept = await storage.loadIdentity();
|
||||
if (kept) return { publicKey: kept.publicKey, kept: true };
|
||||
} catch (error) {
|
||||
console.error('identity: the device could not read the kept key', error);
|
||||
}
|
||||
const fresh = await createIdentity();
|
||||
try {
|
||||
return { publicKey: (await storage.keepIdentity(fresh)).publicKey, kept: true };
|
||||
} catch (error) {
|
||||
console.error('identity: the device could not keep the key; this visit uses one that lasts until closing', error);
|
||||
return { publicKey: fresh.publicKey, kept: false };
|
||||
}
|
||||
}
|
||||
|
||||
// --- Keeping her (keep-her-safe.md) -------------------------------------
|
||||
const browserStorage = typeof navigator !== 'undefined' ? navigator.storage : undefined;
|
||||
const keeping: RoseWiring['keeping'] = {
|
||||
persisted: async () => (browserStorage?.persisted ? browserStorage.persisted() : null),
|
||||
persist: async () => (browserStorage?.persist ? browserStorage.persist() : null)
|
||||
};
|
||||
const installed = (): boolean =>
|
||||
matchMedia('(display-mode: standalone)').matches || (navigator as Navigator & { standalone?: boolean }).standalone === true;
|
||||
// An installed app is asked once, after the first care of a visit: by then there is
|
||||
// something to lose, and installed apps are not met with a permission prompt (K5).
|
||||
let askedToKeep = false;
|
||||
function keepAfterCare(): void {
|
||||
if (askedToKeep || !installed()) return;
|
||||
askedToKeep = true;
|
||||
keeping.persist().catch((error: unknown) => console.error('keep: asking the browser to keep the garden failed', error));
|
||||
}
|
||||
|
||||
function saveFile(name: string, text: string): void {
|
||||
// A file made here and handed over; nothing is sent anywhere.
|
||||
const url = URL.createObjectURL(new Blob([text], { type: 'application/json' }));
|
||||
const a = Object.assign(document.createElement('a'), { href: url, download: name });
|
||||
document.body.append(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 10_000);
|
||||
}
|
||||
|
||||
const rose: RoseWiring = {
|
||||
identity: () => (identity ??= findIdentity()),
|
||||
loadCare: () => storage.loadCare(),
|
||||
appendCare: async (event) => {
|
||||
await storage.appendCare(event);
|
||||
keepAfterCare();
|
||||
},
|
||||
clientVersion: version,
|
||||
deviceZone,
|
||||
now: () => Date.now(),
|
||||
pastKeys: () => storage.loadPastKeys(),
|
||||
exportRose: (currentKey) => storage.exportRose(currentKey),
|
||||
importRose: (file, currentKey) => storage.importRose(file, currentKey),
|
||||
saveFile,
|
||||
keeping,
|
||||
installHint: /iPhone|iPad|iPod/.test(navigator.userAgent) && !installed()
|
||||
};
|
||||
</script>
|
||||
|
||||
<Shell {letter} />
|
||||
<Shell {letter} {sunset} {rose} />
|
||||
|
||||
@@ -10,8 +10,9 @@ A picture that is off-style goes back for another try. It is never shipped.
|
||||
> the rose's character sheet, is still the test. If it looks wrong, this file changes before
|
||||
> anything else is made, and `pnpm art:board` rebuilds every prompt.
|
||||
>
|
||||
> **Added later the same day, a draft again:** the fox and the Phase 2–3 pictures (F1–F4 in §0,
|
||||
> §3a, the new rows in §2 and §4, review points 8–9). Mark's approval above covers S1–S5 only.
|
||||
> **The fox and the Phase 2–3 pictures** (F1–F4 in §0, §3a, the new rows in §2 and §4, review
|
||||
> points 8–9) were added later the same day and **approved by Mark** with one change: the fox's
|
||||
> coat is a deep red-orange, not the drafted muted russet.
|
||||
|
||||
---
|
||||
|
||||
@@ -25,11 +26,11 @@ A picture that is off-style goes back for another try. It is never shipped.
|
||||
| S4 | The palette | §2 | It starts from the app's tokens (`--rose #b4485e`, `--paper #fbf6f1`). |
|
||||
| S5 | The sky | Drawn in code, never painted | The sun moves at the player's real time, and the stars are the real constellations. A painted sky could do neither. |
|
||||
|
||||
**Draft, waiting for Mark: the fox and the Phase 2–3 pictures.**
|
||||
**The fox and the Phase 2–3 pictures, decided 2026-11-01.**
|
||||
|
||||
| # | Choice | The draft says | Why |
|
||||
| # | Choice | Decided | Why |
|
||||
|:--|:--|:--|:--|
|
||||
| F1 | The fox's look | A small russet fox with a cream mask round his eyes and muzzle, dark legs, and a bushy tail with faint darker rings | The mask and the rings are the quiet nod to Ulfík the red panda (CLAUDE.md §1). They also keep him far from the book's fox, which is pale and sandy with very long ears. |
|
||||
| F1 | The fox's look | A small, young, shy fox with a **deep red-orange** coat, a cream mask round his eyes and muzzle, dark legs, and a bushy tail with faint darker rings. *Mark changed the coat from the drafted muted russet; the rest is as drafted.* | The mask and the rings are the quiet nod to Ulfík the red panda (CLAUDE.md §1), and the deeper coat is closer to his. All of it keeps him far from the book's fox, which is pale and sandy with very long ears. |
|
||||
| F2 | His size | Sitting, he is about as tall as the rose | They share the garden bed and must read together on a phone. |
|
||||
| F3 | Bush and berries | One wild bush in three states. The berries are their own small pictures, placed on the bush in code | Five berry kinds (GAMEPLAY.md §3) then need one bush, not five. |
|
||||
| F4 | Paths and lanterns (Phase 3) | Small vignettes for now | The screen that shows two roses and the path between them is not designed yet. Its feature doc may ask for them again. |
|
||||
@@ -72,7 +73,7 @@ The main tones. Small shades in between are fine.
|
||||
| Sunset glow | coral | `#E9846A` |
|
||||
| Night | dusk indigo | `#2E3561` |
|
||||
| Lamps and stars | lamp gold | `#F4D58D` |
|
||||
| Fox coat | russet | `#B65A35` |
|
||||
| Fox coat | deep red-orange | `#BC4A22` |
|
||||
| Fox mask, chest, tail tip | cream | `#F3E3C8` |
|
||||
| Fox legs, ear tips | deep brown | `#5A3A33` |
|
||||
| Wild strawberries | strawberry | `#D2554E` |
|
||||
@@ -109,11 +110,11 @@ The rose is the only character in Phase 1. Every rose picture follows the charac
|
||||
|
||||
---
|
||||
|
||||
## 3a. The fox (Phase 2, draft: F1–F2)
|
||||
## 3a. The fox (Phase 2: F1–F2)
|
||||
|
||||
The fox is the second character. Every fox picture follows the character sheet `fox-sheet`.
|
||||
|
||||
- **A small, young fox** with a warm russet coat (`#B65A35`). His face has a cream mask
|
||||
- **A small, young fox** with a deep red-orange coat (`#BC4A22`), warm and glowing, never neon. His face has a cream mask
|
||||
(`#F3E3C8`): cream cheeks and muzzle, and a small cream spot above each eye. His legs and
|
||||
paws are deep brown (`#5A3A33`). His ears are rounded and of middle size, cream inside with
|
||||
dark tips. His tail is big and bushy, with three faint darker rings and a cream tip.
|
||||
@@ -212,7 +213,7 @@ tick them: *Accept* is one tap.
|
||||
5. The size and background are right for its kind in §5.
|
||||
6. It reads clearly at the smallest size it is shown.
|
||||
7. It is gentle: nothing blames, frightens or looks hurt, and drift looks like waiting.
|
||||
8. It reads as one young russet fox with a cream mask and a ringed tail, shy and gentle, and
|
||||
8. It reads as one young red-orange fox with a cream mask and a ringed tail, shy and gentle, and
|
||||
nothing like the book's sandy, long-eared fox.
|
||||
9. He matches `fox-sheet`: the same mask, ears, leg colour, tail rings and size.
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
},
|
||||
"fox": {
|
||||
"sheet": "fox-sheet",
|
||||
"description": "The fox: a small, young fox; sitting, he is about as tall as the rose. A warm russet coat (#B65A35). A cream mask (#F3E3C8) on his face: cream cheeks and muzzle and a small cream spot above each eye. Deep brown legs and paws (#5A3A33). Rounded ears of middle size, cream inside with dark tips. A big bushy tail with three faint darker rings and a cream tip. Small dark eyes, often half-closed, a tiny dark nose and mouth. A fox's pointed muzzle and a fox's body: the mask and the tail rings are only a nod to a red panda. Shy, curious and gentle, never sly."
|
||||
"description": "The fox: a small, young fox; sitting, he is about as tall as the rose. A deep red-orange coat (#BC4A22), warm and glowing, never neon. A cream mask (#F3E3C8) on his face: cream cheeks and muzzle and a small cream spot above each eye. Deep brown legs and paws (#5A3A33). Rounded ears of middle size, cream inside with dark tips. A big bushy tail with three faint darker rings and a cream tip. Small dark eyes, often half-closed, a tiny dark nose and mouth. A fox's pointed muzzle and a fox's body: the mask and the tail rings are only a nod to a red panda. Shy, curious and gentle, never sly."
|
||||
}
|
||||
},
|
||||
"avoid": [
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
|
||||
<!-- Stand-in for fox-asleep (art/placeholders, CLAUDE.md §2): form and layout only, not art. Built by tools/art-prep. -->
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><circle cx="150" cy="160" r="66" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><path d="M205 200 Q 170 235 110 205" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M205 200 Q 170 235 110 205" fill="none" stroke="#b65a35" stroke-width="30" stroke-linecap="round"/><path d="M205 200 Q 170 235 110 205" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><path d="M96.5 150 l12 -27 l12 27z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><path d="M123.5 150 l12 -27 l12 27z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><g transform="rotate(0 125 168)"><circle cx="125" cy="168" r="30" fill="#b65a35" stroke="#3a2730" stroke-width="4"/> <ellipse cx="108.5" cy="178.5" rx="16.5" ry="11.4" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="113" cy="154.5" r="5" fill="#f3e3c8"/><circle cx="135" cy="154.5" r="5" fill="#f3e3c8"/> <path d="M106 164 q6 6 12 0" fill="none" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><path d="M128 164 q6 6 12 0" fill="none" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><circle cx="96.5" cy="177" r="5" fill="#3a2730"/> </g></g>
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><circle cx="150" cy="160" r="66" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><path d="M205 200 Q 170 235 110 205" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M205 200 Q 170 235 110 205" fill="none" stroke="#bc4a22" stroke-width="30" stroke-linecap="round"/><path d="M205 200 Q 170 235 110 205" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><path d="M96.5 150 l12 -27 l12 27z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><path d="M123.5 150 l12 -27 l12 27z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><g transform="rotate(0 125 168)"><circle cx="125" cy="168" r="30" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/> <ellipse cx="108.5" cy="178.5" rx="16.5" ry="11.4" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="113" cy="154.5" r="5" fill="#f3e3c8"/><circle cx="135" cy="154.5" r="5" fill="#f3e3c8"/> <path d="M106 164 q6 6 12 0" fill="none" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><path d="M128 164 q6 6 12 0" fill="none" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><circle cx="96.5" cy="177" r="5" fill="#3a2730"/> </g></g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 1.4 KiB |
@@ -1,4 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
|
||||
<!-- Stand-in for fox-brushed (art/placeholders, CLAUDE.md §2): form and layout only, not art. Built by tools/art-prep. -->
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#3a2730" stroke-width="46" stroke-linecap="round"/><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#b65a35" stroke-width="38" stroke-linecap="round"/><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#5a3a33" stroke-width="40" stroke-dasharray="6 26" opacity=".45"/><ellipse cx="160" cy="150" rx="50" ry="64" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><ellipse cx="148" cy="160" rx="24" ry="38" fill="#f3e3c8"/><path d="M140 175 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M168 175 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M112.1 49.2 l12 -34.2 l12 34.2z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><path d="M146.3 49.2 l12 -34.2 l12 34.2z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><g transform="rotate(8 145 72)"><circle cx="145" cy="72" r="38" fill="#b65a35" stroke="#3a2730" stroke-width="4"/> <ellipse cx="122.5" cy="85.3" rx="20.900000000000002" ry="14.44" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="133" cy="54.9" r="5" fill="#f3e3c8"/><circle cx="155" cy="54.9" r="5" fill="#f3e3c8"/> <path d="M126 68 q6 4 12 0" fill="#3a2730" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><path d="M148 68 q6 4 12 0" fill="#3a2730" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><circle cx="110.5" cy="83.4" r="5" fill="#3a2730"/> </g></g>
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#3a2730" stroke-width="46" stroke-linecap="round"/><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#bc4a22" stroke-width="38" stroke-linecap="round"/><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#5a3a33" stroke-width="40" stroke-dasharray="6 26" opacity=".45"/><ellipse cx="160" cy="150" rx="50" ry="64" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><ellipse cx="148" cy="160" rx="24" ry="38" fill="#f3e3c8"/><path d="M140 175 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M168 175 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M112.1 49.2 l12 -34.2 l12 34.2z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><path d="M146.3 49.2 l12 -34.2 l12 34.2z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><g transform="rotate(8 145 72)"><circle cx="145" cy="72" r="38" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/> <ellipse cx="122.5" cy="85.3" rx="20.900000000000002" ry="14.44" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="133" cy="54.9" r="5" fill="#f3e3c8"/><circle cx="155" cy="54.9" r="5" fill="#f3e3c8"/> <path d="M126 68 q6 4 12 0" fill="#3a2730" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><path d="M148 68 q6 4 12 0" fill="#3a2730" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><circle cx="110.5" cy="83.4" r="5" fill="#3a2730"/> </g></g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 1.7 KiB |
@@ -1,4 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
|
||||
<!-- Stand-in for fox-carrying-petal (art/placeholders, CLAUDE.md §2): form and layout only, not art. Built by tools/art-prep. -->
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#b65a35" stroke-width="30" stroke-linecap="round"/><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><path d="M110 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M130 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M200 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M220 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><ellipse cx="165" cy="128" rx="80" ry="38" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><path d="M49.3 77.6 l12 -30.6 l12 30.6z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><path d="M79.9 77.6 l12 -30.6 l12 30.6z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><g transform="rotate(0 80 98)"><circle cx="80" cy="98" r="34" fill="#b65a35" stroke="#3a2730" stroke-width="4"/> <ellipse cx="60.5" cy="109.9" rx="18.700000000000003" ry="12.92" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="68" cy="82.7" r="5" fill="#f3e3c8"/><circle cx="90" cy="82.7" r="5" fill="#f3e3c8"/> <path d="M61 94 q6 4 12 0" fill="#3a2730" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><path d="M83 94 q6 4 12 0" fill="#3a2730" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><circle cx="48.5" cy="108.2" r="5" fill="#3a2730"/> <ellipse cx="44.5" cy="123.5" rx="16" ry="9" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/></g></g>
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#bc4a22" stroke-width="30" stroke-linecap="round"/><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><path d="M110 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M130 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M200 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M220 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><ellipse cx="165" cy="128" rx="80" ry="38" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><path d="M49.3 77.6 l12 -30.6 l12 30.6z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><path d="M79.9 77.6 l12 -30.6 l12 30.6z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><g transform="rotate(0 80 98)"><circle cx="80" cy="98" r="34" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/> <ellipse cx="60.5" cy="109.9" rx="18.700000000000003" ry="12.92" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="68" cy="82.7" r="5" fill="#f3e3c8"/><circle cx="90" cy="82.7" r="5" fill="#f3e3c8"/> <path d="M61 94 q6 4 12 0" fill="#3a2730" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><path d="M83 94 q6 4 12 0" fill="#3a2730" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><circle cx="48.5" cy="108.2" r="5" fill="#3a2730"/> <ellipse cx="44.5" cy="123.5" rx="16" ry="9" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/></g></g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.9 KiB After Width: | Height: | Size: 1.9 KiB |
@@ -1,4 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
|
||||
<!-- Stand-in for fox-curious (art/placeholders, CLAUDE.md §2): form and layout only, not art. Built by tools/art-prep. -->
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#b65a35" stroke-width="30" stroke-linecap="round"/><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><path d="M110 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M130 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M200 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M220 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><ellipse cx="165" cy="128" rx="80" ry="38" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><path d="M49.3 77.6 l12 -30.6 l12 30.6z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><path d="M79.9 77.6 l12 -30.6 l12 30.6z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><g transform="rotate(-14 80 98)"><circle cx="80" cy="98" r="34" fill="#b65a35" stroke="#3a2730" stroke-width="4"/> <ellipse cx="60.5" cy="109.9" rx="18.700000000000003" ry="12.92" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="68" cy="82.7" r="5" fill="#f3e3c8"/><circle cx="90" cy="82.7" r="5" fill="#f3e3c8"/> <circle cx="67" cy="94" r="4" fill="#3a2730"/><circle cx="89" cy="94" r="4" fill="#3a2730"/><circle cx="48.5" cy="108.2" r="5" fill="#3a2730"/> </g></g>
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#bc4a22" stroke-width="30" stroke-linecap="round"/><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><path d="M110 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M130 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M200 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M220 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><ellipse cx="165" cy="128" rx="80" ry="38" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><path d="M49.3 77.6 l12 -30.6 l12 30.6z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><path d="M79.9 77.6 l12 -30.6 l12 30.6z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><g transform="rotate(-14 80 98)"><circle cx="80" cy="98" r="34" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/> <ellipse cx="60.5" cy="109.9" rx="18.700000000000003" ry="12.92" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="68" cy="82.7" r="5" fill="#f3e3c8"/><circle cx="90" cy="82.7" r="5" fill="#f3e3c8"/> <circle cx="67" cy="94" r="4" fill="#3a2730"/><circle cx="89" cy="94" r="4" fill="#3a2730"/><circle cx="48.5" cy="108.2" r="5" fill="#3a2730"/> </g></g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 1.7 KiB |
@@ -1,4 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
|
||||
<!-- Stand-in for fox-eating (art/placeholders, CLAUDE.md §2): form and layout only, not art. Built by tools/art-prep. -->
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#b65a35" stroke-width="30" stroke-linecap="round"/><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><path d="M110 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M130 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M200 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M220 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><ellipse cx="165" cy="128" rx="80" ry="38" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><path d="M49.3 77.6 l12 -30.6 l12 30.6z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><path d="M79.9 77.6 l12 -30.6 l12 30.6z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><g transform="rotate(-30 80 98)"><circle cx="80" cy="98" r="34" fill="#b65a35" stroke="#3a2730" stroke-width="4"/> <ellipse cx="60.5" cy="109.9" rx="18.700000000000003" ry="12.92" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="68" cy="82.7" r="5" fill="#f3e3c8"/><circle cx="90" cy="82.7" r="5" fill="#f3e3c8"/> <path d="M61 94 q6 6 12 0" fill="none" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><path d="M83 94 q6 6 12 0" fill="none" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><circle cx="48.5" cy="108.2" r="5" fill="#3a2730"/> </g></g>
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#bc4a22" stroke-width="30" stroke-linecap="round"/><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><path d="M110 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M130 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M200 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M220 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><ellipse cx="165" cy="128" rx="80" ry="38" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><path d="M49.3 77.6 l12 -30.6 l12 30.6z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><path d="M79.9 77.6 l12 -30.6 l12 30.6z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><g transform="rotate(-30 80 98)"><circle cx="80" cy="98" r="34" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/> <ellipse cx="60.5" cy="109.9" rx="18.700000000000003" ry="12.92" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="68" cy="82.7" r="5" fill="#f3e3c8"/><circle cx="90" cy="82.7" r="5" fill="#f3e3c8"/> <path d="M61 94 q6 6 12 0" fill="none" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><path d="M83 94 q6 6 12 0" fill="none" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><circle cx="48.5" cy="108.2" r="5" fill="#3a2730"/> </g></g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.8 KiB After Width: | Height: | Size: 1.8 KiB |
@@ -1,4 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
|
||||
<!-- Stand-in for fox-leading (art/placeholders, CLAUDE.md §2): form and layout only, not art. Built by tools/art-prep. -->
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><g transform="translate(300 0) scale(-1 1)"><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#b65a35" stroke-width="30" stroke-linecap="round"/><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><path d="M110 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M130 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M200 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M220 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><ellipse cx="165" cy="128" rx="80" ry="38" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><path d="M221.7 77.6 l12 -30.6 l12 30.6z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><path d="M191.1 77.6 l12 -30.6 l12 30.6z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><g transform="rotate(0 215 98)"><circle cx="215" cy="98" r="34" fill="#b65a35" stroke="#3a2730" stroke-width="4"/> <ellipse cx="234.5" cy="109.9" rx="18.700000000000003" ry="12.92" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="227" cy="82.7" r="5" fill="#f3e3c8"/><circle cx="205" cy="82.7" r="5" fill="#f3e3c8"/> <circle cx="228" cy="94" r="4" fill="#3a2730"/><circle cx="206" cy="94" r="4" fill="#3a2730"/><circle cx="246.5" cy="108.2" r="5" fill="#3a2730"/> </g></g></g>
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><g transform="translate(300 0) scale(-1 1)"><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#bc4a22" stroke-width="30" stroke-linecap="round"/><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><path d="M110 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M130 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M200 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M220 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><ellipse cx="165" cy="128" rx="80" ry="38" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><path d="M221.7 77.6 l12 -30.6 l12 30.6z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><path d="M191.1 77.6 l12 -30.6 l12 30.6z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><g transform="rotate(0 215 98)"><circle cx="215" cy="98" r="34" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/> <ellipse cx="234.5" cy="109.9" rx="18.700000000000003" ry="12.92" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="227" cy="82.7" r="5" fill="#f3e3c8"/><circle cx="205" cy="82.7" r="5" fill="#f3e3c8"/> <circle cx="228" cy="94" r="4" fill="#3a2730"/><circle cx="206" cy="94" r="4" fill="#3a2730"/><circle cx="246.5" cy="108.2" r="5" fill="#3a2730"/> </g></g></g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 9.4 KiB After Width: | Height: | Size: 9.4 KiB |
@@ -1,4 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
|
||||
<!-- Stand-in for fox-petted (art/placeholders, CLAUDE.md §2): form and layout only, not art. Built by tools/art-prep. -->
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#b65a35" stroke-width="30" stroke-linecap="round"/><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><ellipse cx="160" cy="150" rx="50" ry="64" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><ellipse cx="148" cy="160" rx="24" ry="38" fill="#f3e3c8"/><path d="M140 175 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M168 175 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M112.1 49.2 l12 -34.2 l12 34.2z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><path d="M146.3 49.2 l12 -34.2 l12 34.2z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><g transform="rotate(-18 145 72)"><circle cx="145" cy="72" r="38" fill="#b65a35" stroke="#3a2730" stroke-width="4"/> <ellipse cx="122.5" cy="85.3" rx="20.900000000000002" ry="14.44" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="133" cy="54.9" r="5" fill="#f3e3c8"/><circle cx="155" cy="54.9" r="5" fill="#f3e3c8"/> <path d="M126 68 q6 6 12 0" fill="none" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><path d="M148 68 q6 6 12 0" fill="none" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><circle cx="110.5" cy="83.4" r="5" fill="#3a2730"/> </g></g>
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#bc4a22" stroke-width="30" stroke-linecap="round"/><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><ellipse cx="160" cy="150" rx="50" ry="64" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><ellipse cx="148" cy="160" rx="24" ry="38" fill="#f3e3c8"/><path d="M140 175 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M168 175 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M112.1 49.2 l12 -34.2 l12 34.2z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><path d="M146.3 49.2 l12 -34.2 l12 34.2z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><g transform="rotate(-18 145 72)"><circle cx="145" cy="72" r="38" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/> <ellipse cx="122.5" cy="85.3" rx="20.900000000000002" ry="14.44" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="133" cy="54.9" r="5" fill="#f3e3c8"/><circle cx="155" cy="54.9" r="5" fill="#f3e3c8"/> <path d="M126 68 q6 6 12 0" fill="none" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><path d="M148 68 q6 6 12 0" fill="none" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><circle cx="110.5" cy="83.4" r="5" fill="#3a2730"/> </g></g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 1.7 KiB |
@@ -1,4 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
|
||||
<!-- Stand-in for fox-resting (art/placeholders, CLAUDE.md §2): form and layout only, not art. Built by tools/art-prep. -->
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><path d="M250 205 Q 285 215 290 180" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M250 205 Q 285 215 290 180" fill="none" stroke="#b65a35" stroke-width="30" stroke-linecap="round"/><path d="M250 205 Q 285 215 290 180" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><ellipse cx="170" cy="192" rx="92" ry="30" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><path d="M70 215 V 222" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M42.4 158.8 l12 -28.8 l12 28.8z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><path d="M71.2 158.8 l12 -28.8 l12 28.8z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><g transform="rotate(0 72 178)"><circle cx="72" cy="178" r="32" fill="#b65a35" stroke="#3a2730" stroke-width="4"/> <ellipse cx="54" cy="189.2" rx="17.6" ry="12.16" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="60" cy="163.6" r="5" fill="#f3e3c8"/><circle cx="82" cy="163.6" r="5" fill="#f3e3c8"/> <path d="M53 174 q6 4 12 0" fill="#3a2730" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><path d="M75 174 q6 4 12 0" fill="#3a2730" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><circle cx="42" cy="187.6" r="5" fill="#3a2730"/> </g></g>
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><path d="M250 205 Q 285 215 290 180" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M250 205 Q 285 215 290 180" fill="none" stroke="#bc4a22" stroke-width="30" stroke-linecap="round"/><path d="M250 205 Q 285 215 290 180" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><ellipse cx="170" cy="192" rx="92" ry="30" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><path d="M70 215 V 222" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M42.4 158.8 l12 -28.8 l12 28.8z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><path d="M71.2 158.8 l12 -28.8 l12 28.8z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><g transform="rotate(0 72 178)"><circle cx="72" cy="178" r="32" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/> <ellipse cx="54" cy="189.2" rx="17.6" ry="12.16" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="60" cy="163.6" r="5" fill="#f3e3c8"/><circle cx="82" cy="163.6" r="5" fill="#f3e3c8"/> <path d="M53 174 q6 4 12 0" fill="#3a2730" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><path d="M75 174 q6 4 12 0" fill="#3a2730" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><circle cx="42" cy="187.6" r="5" fill="#3a2730"/> </g></g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 10 KiB |
@@ -1,4 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
|
||||
<!-- Stand-in for fox-sitting (art/placeholders, CLAUDE.md §2): form and layout only, not art. Built by tools/art-prep. -->
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#b65a35" stroke-width="30" stroke-linecap="round"/><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><ellipse cx="160" cy="150" rx="50" ry="64" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><ellipse cx="148" cy="160" rx="24" ry="38" fill="#f3e3c8"/><path d="M140 175 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M168 175 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M112.1 49.2 l12 -34.2 l12 34.2z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><path d="M146.3 49.2 l12 -34.2 l12 34.2z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><g transform="rotate(0 145 72)"><circle cx="145" cy="72" r="38" fill="#b65a35" stroke="#3a2730" stroke-width="4"/> <ellipse cx="122.5" cy="85.3" rx="20.900000000000002" ry="14.44" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="133" cy="54.9" r="5" fill="#f3e3c8"/><circle cx="155" cy="54.9" r="5" fill="#f3e3c8"/> <path d="M126 68 q6 4 12 0" fill="#3a2730" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><path d="M148 68 q6 4 12 0" fill="#3a2730" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><circle cx="110.5" cy="83.4" r="5" fill="#3a2730"/> </g></g>
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#bc4a22" stroke-width="30" stroke-linecap="round"/><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><ellipse cx="160" cy="150" rx="50" ry="64" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><ellipse cx="148" cy="160" rx="24" ry="38" fill="#f3e3c8"/><path d="M140 175 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M168 175 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M112.1 49.2 l12 -34.2 l12 34.2z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><path d="M146.3 49.2 l12 -34.2 l12 34.2z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><g transform="rotate(0 145 72)"><circle cx="145" cy="72" r="38" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/> <ellipse cx="122.5" cy="85.3" rx="20.900000000000002" ry="14.44" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="133" cy="54.9" r="5" fill="#f3e3c8"/><circle cx="155" cy="54.9" r="5" fill="#f3e3c8"/> <path d="M126 68 q6 4 12 0" fill="#3a2730" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><path d="M148 68 q6 4 12 0" fill="#3a2730" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><circle cx="110.5" cy="83.4" r="5" fill="#3a2730"/> </g></g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 1.7 KiB |
@@ -1,4 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
|
||||
<!-- Stand-in for fox-trotting (art/placeholders, CLAUDE.md §2): form and layout only, not art. Built by tools/art-prep. -->
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#b65a35" stroke-width="30" stroke-linecap="round"/><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><path d="M110 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M130 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M200 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M220 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><ellipse cx="165" cy="128" rx="80" ry="38" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><path d="M49.3 77.6 l12 -30.6 l12 30.6z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><path d="M79.9 77.6 l12 -30.6 l12 30.6z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><g transform="rotate(0 80 98)"><circle cx="80" cy="98" r="34" fill="#b65a35" stroke="#3a2730" stroke-width="4"/> <ellipse cx="60.5" cy="109.9" rx="18.700000000000003" ry="12.92" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="68" cy="82.7" r="5" fill="#f3e3c8"/><circle cx="90" cy="82.7" r="5" fill="#f3e3c8"/> <circle cx="67" cy="94" r="4" fill="#3a2730"/><circle cx="89" cy="94" r="4" fill="#3a2730"/><circle cx="48.5" cy="108.2" r="5" fill="#3a2730"/> </g></g>
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#bc4a22" stroke-width="30" stroke-linecap="round"/><path d="M235 120 Q 280 110 290 60" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><path d="M110 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M130 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M200 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M220 140 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><ellipse cx="165" cy="128" rx="80" ry="38" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><path d="M49.3 77.6 l12 -30.6 l12 30.6z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><path d="M79.9 77.6 l12 -30.6 l12 30.6z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><g transform="rotate(0 80 98)"><circle cx="80" cy="98" r="34" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/> <ellipse cx="60.5" cy="109.9" rx="18.700000000000003" ry="12.92" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="68" cy="82.7" r="5" fill="#f3e3c8"/><circle cx="90" cy="82.7" r="5" fill="#f3e3c8"/> <circle cx="67" cy="94" r="4" fill="#3a2730"/><circle cx="89" cy="94" r="4" fill="#3a2730"/><circle cx="48.5" cy="108.2" r="5" fill="#3a2730"/> </g></g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 9.1 KiB After Width: | Height: | Size: 9.1 KiB |
@@ -1,4 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
|
||||
<!-- Stand-in for fox-visiting (art/placeholders, CLAUDE.md §2): form and layout only, not art. Built by tools/art-prep. -->
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#b65a35" stroke-width="30" stroke-linecap="round"/><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><ellipse cx="160" cy="150" rx="50" ry="64" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><ellipse cx="148" cy="160" rx="24" ry="38" fill="#f3e3c8"/><path d="M140 175 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M168 175 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M112.1 49.2 l12 -34.2 l12 34.2z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><path d="M146.3 49.2 l12 -34.2 l12 34.2z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><g transform="rotate(16 145 72)"><circle cx="145" cy="72" r="38" fill="#b65a35" stroke="#3a2730" stroke-width="4"/> <ellipse cx="122.5" cy="85.3" rx="20.900000000000002" ry="14.44" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="133" cy="54.9" r="5" fill="#f3e3c8"/><circle cx="155" cy="54.9" r="5" fill="#f3e3c8"/> <path d="M126 68 q6 4 12 0" fill="#3a2730" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><path d="M148 68 q6 4 12 0" fill="#3a2730" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><circle cx="110.5" cy="83.4" r="5" fill="#3a2730"/> </g></g>
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#bc4a22" stroke-width="30" stroke-linecap="round"/><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><ellipse cx="160" cy="150" rx="50" ry="64" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><ellipse cx="148" cy="160" rx="24" ry="38" fill="#f3e3c8"/><path d="M140 175 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M168 175 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M112.1 49.2 l12 -34.2 l12 34.2z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><path d="M146.3 49.2 l12 -34.2 l12 34.2z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><g transform="rotate(16 145 72)"><circle cx="145" cy="72" r="38" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/> <ellipse cx="122.5" cy="85.3" rx="20.900000000000002" ry="14.44" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="133" cy="54.9" r="5" fill="#f3e3c8"/><circle cx="155" cy="54.9" r="5" fill="#f3e3c8"/> <path d="M126 68 q6 4 12 0" fill="#3a2730" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><path d="M148 68 q6 4 12 0" fill="#3a2730" stroke="#3a2730" stroke-width="3" stroke-linecap="round"/><circle cx="110.5" cy="83.4" r="5" fill="#3a2730"/> </g></g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 1.7 KiB |
@@ -1,4 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
|
||||
<!-- Stand-in for fox-watching (art/placeholders, CLAUDE.md §2): form and layout only, not art. Built by tools/art-prep. -->
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#b65a35" stroke-width="30" stroke-linecap="round"/><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><ellipse cx="160" cy="150" rx="50" ry="64" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><ellipse cx="148" cy="160" rx="24" ry="38" fill="#f3e3c8"/><path d="M140 175 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M168 175 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M183.9 49.2 l12 -34.2 l12 34.2z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><path d="M149.7 49.2 l12 -34.2 l12 34.2z" fill="#b65a35" stroke="#3a2730" stroke-width="4"/><g transform="rotate(0 175 72)"><circle cx="175" cy="72" r="38" fill="#b65a35" stroke="#3a2730" stroke-width="4"/> <ellipse cx="197.5" cy="85.3" rx="20.900000000000002" ry="14.44" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="187" cy="54.9" r="5" fill="#f3e3c8"/><circle cx="165" cy="54.9" r="5" fill="#f3e3c8"/> <circle cx="188" cy="68" r="4" fill="#3a2730"/><circle cx="166" cy="68" r="4" fill="#3a2730"/><circle cx="209.5" cy="83.4" r="5" fill="#3a2730"/> </g></g>
|
||||
<g transform="translate(61.4 100.4) scale(1.2971)"><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#3a2730" stroke-width="38" stroke-linecap="round"/><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#bc4a22" stroke-width="30" stroke-linecap="round"/><path d="M185 215 Q 250 205 240 150" fill="none" stroke="#5a3a33" stroke-width="32" stroke-dasharray="6 26" opacity=".45"/><ellipse cx="160" cy="150" rx="50" ry="64" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><ellipse cx="148" cy="160" rx="24" ry="38" fill="#f3e3c8"/><path d="M140 175 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M168 175 V 225" stroke="#5a3a33" stroke-width="14" stroke-linecap="round"/><path d="M183.9 49.2 l12 -34.2 l12 34.2z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><path d="M149.7 49.2 l12 -34.2 l12 34.2z" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/><g transform="rotate(0 175 72)"><circle cx="175" cy="72" r="38" fill="#bc4a22" stroke="#3a2730" stroke-width="4"/> <ellipse cx="197.5" cy="85.3" rx="20.900000000000002" ry="14.44" fill="#f3e3c8" stroke="#3a2730" stroke-width="4"/> <circle cx="187" cy="54.9" r="5" fill="#f3e3c8"/><circle cx="165" cy="54.9" r="5" fill="#f3e3c8"/> <circle cx="188" cy="68" r="4" fill="#3a2730"/><circle cx="166" cy="68" r="4" fill="#3a2730"/><circle cx="209.5" cy="83.4" r="5" fill="#3a2730"/> </g></g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.6 KiB After Width: | Height: | Size: 1.6 KiB |
@@ -4,7 +4,7 @@ Every illustration in Rosea Domi goes through this pipeline. A picture that skip
|
||||
not shipped, however good it looks (CLAUDE.md §7).
|
||||
|
||||
- **What the pictures look like:** [`art/STYLE.md`](../art/STYLE.md). Mark approved it on
|
||||
2026-11-01 (S1–S5 in its §0). The fox and the Phase 2–3 pictures (F1–F4) are a draft.
|
||||
2026-11-01 (S1–S5 in its §0). The fox and the Phase 2–3 pictures (F1–F4) were approved the same day, with a deep red-orange coat.
|
||||
- **Which pictures exist:** [`art/manifest.json`](../art/manifest.json), in phase order: Phase 1 (the rose and her garden), Phase 2 (the fox, berries, the bush), and the decided Phase 3 pictures (paths, lanterns). The planets wait for their own feature docs.
|
||||
- **The tools:** [`tools/art-prep/`](../tools/art-prep/). It turns those two files into prompts,
|
||||
stand-ins and the board, and moves accepted pictures into `art/final/`.
|
||||
|
||||
@@ -2,6 +2,7 @@ import { expect, test } from '@playwright/test';
|
||||
import { PRODUCT_NAME } from '@rosea/schema';
|
||||
import { en } from '@rosea/ui/copy';
|
||||
import { startStaticServer } from './static-server.js';
|
||||
import { storedCare, storedTown } from './stored.js';
|
||||
|
||||
/**
|
||||
* 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 }) => {
|
||||
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;
|
||||
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
await page.clock.setFixedTime(Date.parse('2026-03-29T12:00:00+02:00'));
|
||||
await page.goto(server.url);
|
||||
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.
|
||||
// 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 });
|
||||
@@ -47,13 +56,35 @@ test('the shell opens from the service worker with the server gone', async ({ br
|
||||
await page.reload();
|
||||
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
|
||||
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ň');
|
||||
|
||||
// Tending the rose offline: hold Water, as a finger would (rose.md).
|
||||
await page.getByRole('button', { name: en.rose.water }).hover();
|
||||
await page.mouse.down();
|
||||
await page.waitForTimeout(1500);
|
||||
await page.mouse.up();
|
||||
await expect(page.getByText(en.rose.says.thanks)).toBeVisible();
|
||||
await storedCare(page, 1);
|
||||
|
||||
// 2. Close the tab and open a fresh one: a cold start, the shape of a player
|
||||
// coming back days later with no signal.
|
||||
await page.close();
|
||||
const again = await context.newPage();
|
||||
await again.clock.setFixedTime(Date.parse('2026-03-29T12:00:00+02:00'));
|
||||
await again.goto(server.url);
|
||||
await expect(again.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
|
||||
await expect(again.locator('.sun p').first()).toHaveText(/in Plzeň\.$/);
|
||||
// The care given offline survived the closed tab.
|
||||
await again.getByRole('button', { name: en.rose.numbers }).click();
|
||||
await expect(again.locator('#rose-numbers')).toContainText(`${en.rose.daysOfCare}1`);
|
||||
|
||||
// 3. A deep link inside the scope falls back to the shell, not an error page.
|
||||
await again.goto(`${server.url}somewhere/deeper`);
|
||||
|
||||
@@ -3,8 +3,11 @@ import { expect, test, type Page } from '@playwright/test';
|
||||
import { PRODUCT_NAME } from '@rosea/schema';
|
||||
import { en } from '@rosea/ui/copy';
|
||||
import { parseLetter } from '@rosea/ui/letter';
|
||||
import { nextInvitation } from '@rosea/engine';
|
||||
import { searchTowns } from '@rosea/content/places';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { BASE, startStaticServer, type StaticServer } from './static-server.js';
|
||||
import { storedCare, storedTown } from './stored.js';
|
||||
|
||||
let server: StaticServer;
|
||||
|
||||
@@ -127,3 +130,152 @@ 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 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([]);
|
||||
});
|
||||
});
|
||||
|
||||
// --- The rose (.agents/features/rose.md) -------------------------------------
|
||||
test.describe('the rose, in Prague at 08:00 on 1 March 2026', () => {
|
||||
test.use({ timezoneId: 'Europe/Prague', locale: 'en-US' });
|
||||
const MORNING = Date.parse('2026-03-01T08:00:00+01:00');
|
||||
|
||||
/** Holds the Water button with the mouse, as a player holds it with a finger. */
|
||||
async function pour(page: Page, ms: number): Promise<void> {
|
||||
await page.getByRole('button', { name: en.rose.water }).hover();
|
||||
await page.mouse.down();
|
||||
await page.waitForTimeout(ms);
|
||||
await page.mouse.up();
|
||||
}
|
||||
|
||||
test('a new rose is a bud; holding Water is one day of care; a reload keeps it', async ({ page }) => {
|
||||
await page.clock.setFixedTime(MORNING);
|
||||
const { requests } = await open(page);
|
||||
await expect(page.getByRole('img', { name: 'The rose, a bud.' })).toBeVisible();
|
||||
await expect(page.getByText(en.rose.says.dry)).toBeVisible();
|
||||
|
||||
await pour(page, 1500);
|
||||
await expect(page.getByText(en.rose.says.thanks)).toBeVisible();
|
||||
await page.getByRole('button', { name: en.rose.numbers }).click();
|
||||
await expect(page.locator('#rose-numbers')).toContainText(`${en.rose.daysOfCare}1`);
|
||||
|
||||
await storedCare(page, 1);
|
||||
await page.reload();
|
||||
await page.getByRole('button', { name: en.rose.numbers }).click();
|
||||
await expect(page.locator('#rose-numbers')).toContainText(`${en.rose.daysOfCare}1`);
|
||||
expect(requests.filter((url) => !url.startsWith(server.origin + '/'))).toEqual([]);
|
||||
});
|
||||
|
||||
test('the rose and her care have no accessibility violations', async ({ page }) => {
|
||||
await page.clock.setFixedTime(MORNING);
|
||||
await open(page);
|
||||
await page.getByRole('button', { name: en.rose.numbers }).click();
|
||||
await expect(page.locator('#rose-numbers')).toBeVisible();
|
||||
expect((await new AxeBuilder({ page }).analyze()).violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// --- Keeping her (.agents/features/keep-her-safe.md) --------------------------
|
||||
test.describe('keep her safe, in Prague at 08:00 on 1 March 2026', () => {
|
||||
test.use({ timezoneId: 'Europe/Prague', locale: 'en-US' });
|
||||
const MORNING = Date.parse('2026-03-01T08:00:00+01:00');
|
||||
|
||||
test('save her to a file, lose everything, bring her back: her care returns, and the file never held the town', async ({ browser }) => {
|
||||
// The first device: choose a town, tend the rose, save her.
|
||||
const first = await browser.newContext({ timezoneId: 'Europe/Prague', locale: 'en-US' });
|
||||
let saved = '';
|
||||
try {
|
||||
const page = await first.newPage();
|
||||
await page.clock.setFixedTime(MORNING);
|
||||
await page.goto(server.url);
|
||||
await page.getByRole('searchbox', { name: en.sunset.searchLabel }).fill('brno');
|
||||
await page.getByRole('button', { name: /^Brno/ }).first().click();
|
||||
await page.getByRole('button', { name: en.rose.water }).hover();
|
||||
await page.mouse.down();
|
||||
await page.waitForTimeout(1500);
|
||||
await page.mouse.up();
|
||||
await storedCare(page, 1);
|
||||
|
||||
await page.getByRole('button', { name: en.rose.safe.title }).click();
|
||||
const download = page.waitForEvent('download');
|
||||
await page.getByRole('button', { name: en.rose.safe.save }).click();
|
||||
const file = await download;
|
||||
expect(file.suggestedFilename()).toBe('rose-2026-03-01.json');
|
||||
saved = readFileSync((await file.path())!, 'utf8');
|
||||
} finally {
|
||||
await first.close();
|
||||
}
|
||||
expect(JSON.parse(saved)).toMatchObject({ format: 'rosea-rose', version: 1 });
|
||||
expect(saved).not.toMatch(/Brno|privateKey/);
|
||||
|
||||
// A fresh profile: the shape of an evicted garden, or a new phone.
|
||||
const second = await browser.newContext({ timezoneId: 'Europe/Prague', locale: 'en-US' });
|
||||
try {
|
||||
const page = await second.newPage();
|
||||
await page.clock.setFixedTime(MORNING + 3_600_000);
|
||||
await page.goto(server.url);
|
||||
await expect(page.getByRole('img', { name: 'The rose, a bud.' })).toBeVisible();
|
||||
await page.getByRole('button', { name: en.rose.safe.title }).click();
|
||||
await page.getByLabel(en.rose.safe.bringBack).setInputFiles({ name: 'rose-2026-03-01.json', mimeType: 'application/json', buffer: Buffer.from(saved) });
|
||||
await expect(page.getByText(en.rose.safe.broughtBack(1))).toBeVisible();
|
||||
await page.getByRole('button', { name: en.rose.numbers }).click();
|
||||
await expect(page.locator('#rose-numbers')).toContainText(`${en.rose.daysOfCare}1`);
|
||||
|
||||
await storedCare(page, 1);
|
||||
await page.reload();
|
||||
await page.getByRole('button', { name: en.rose.numbers }).click();
|
||||
await expect(page.locator('#rose-numbers')).toContainText(`${en.rose.daysOfCare}1`);
|
||||
expect((await new AxeBuilder({ page }).analyze()).violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
|
||||
} finally {
|
||||
await second.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
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 }
|
||||
);
|
||||
}
|
||||
|
||||
/** Waits until the care log holds at least `count` events, for the same reason as above. */
|
||||
export async function storedCare(page: Page, count: number): 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('events')) {
|
||||
db.close();
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
const n = db.transaction('events').objectStore('events').count();
|
||||
n.onsuccess = () => {
|
||||
db.close();
|
||||
resolve(n.result >= expected);
|
||||
};
|
||||
n.onerror = () => {
|
||||
db.close();
|
||||
resolve(false);
|
||||
};
|
||||
};
|
||||
}),
|
||||
count,
|
||||
{ timeout: 5_000 }
|
||||
);
|
||||
}
|
||||
@@ -25,6 +25,7 @@
|
||||
"@eslint/js": "9.39.5",
|
||||
"@playwright/test": "1.62.1",
|
||||
"@rosea/content": "workspace:*",
|
||||
"@rosea/engine": "workspace:*",
|
||||
"@rosea/schema": "workspace:*",
|
||||
"@rosea/ui": "workspace:*",
|
||||
"@types/node": "22.20.1",
|
||||
|
||||
@@ -8,7 +8,9 @@
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./validate": "./src/validator.ts"
|
||||
"./validate": "./src/validator.ts",
|
||||
"./places": "./src/places/places.ts",
|
||||
"./guess": "./src/places/guess.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
@@ -1 +1,6 @@
|
||||
export { isLocalDay, localDay, type LocalDay } from './time/localDay.js';
|
||||
export { addDays, daysBetween, isLocalDay, localDay, localMinutes, type LocalDay } from './time/localDay.js';
|
||||
export {
|
||||
careEvent, careIdentity, judgeCare, newCare, OWN_TRACE, petalsOn, pour, ROSE, roseAt, seeded, stageFor, weedsOn, windOn,
|
||||
type Judged, type Mood, type Needs, type RoseKeys, type RoseNow, type Stage, type Trend
|
||||
} from './rose/rose.js';
|
||||
export { invitation, nextInvitation, sunDay, type NamedPlace, type Place, type SunDay } from './sun/sun.js';
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
/**
|
||||
* The rose (GAMEPLAY.md §1–2, .agents/features/rose.md). Pure: the rose at any
|
||||
* moment is a replay of her care log. Time is `now`; the only "randomness" is a
|
||||
* hash of her key and the day, so every replay on every device agrees.
|
||||
*
|
||||
* She grows from the number of local days on which care helped, never from a
|
||||
* streak and never from minutes. She drifts when left, and drift never lowers
|
||||
* what was grown.
|
||||
*/
|
||||
import type { CareEvent } from '@rosea/schema';
|
||||
import { addDays, daysBetween, localDay, localMinutes, type LocalDay } from '../time/localDay.js';
|
||||
|
||||
/** Every tuning number in one place. Assumptions for the author: rose.md R2, R4, R5, R6. */
|
||||
export const ROSE = {
|
||||
/** A new rose's water: a little low, so the first pour helps and teaches. */
|
||||
waterStart: 0.3,
|
||||
waterFallPerDay: 0.3,
|
||||
/** What a full can (amount 1) adds. */
|
||||
fullPour: 0.6,
|
||||
thirsty: 0.25,
|
||||
/** Below this she needs water; at or above it her leaves lift. */
|
||||
enough: 0.4,
|
||||
tooFull: 0.95,
|
||||
weedChance: 0.4,
|
||||
petalChance: 0.3,
|
||||
windChance: 0.25,
|
||||
windEarliest: 9 * 60,
|
||||
windLatest: 18 * 60,
|
||||
windMinutes: 90,
|
||||
/** Days of care to reach opening, half bloom, full bloom. */
|
||||
stageDays: [3, 10, 25],
|
||||
/** Days since the last day of care when she turns a little away, then closes a little. */
|
||||
driftDays: [3, 7],
|
||||
/** How long she blushes after a helpful act. */
|
||||
blushMinutes: 20
|
||||
} as const;
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
|
||||
export type Stage = 'bud' | 'opening' | 'half-bloom' | 'full-bloom';
|
||||
export type Mood = 'content' | 'blushing' | 'too-full' | 'windblown' | 'waiting' | 'thirsty';
|
||||
export type Trend = 'growing' | 'steady' | 'waiting';
|
||||
|
||||
export interface Needs {
|
||||
readonly water: boolean;
|
||||
readonly weeds: boolean;
|
||||
readonly petals: boolean;
|
||||
readonly wind: boolean;
|
||||
}
|
||||
|
||||
export interface RoseNow {
|
||||
readonly stage: Stage;
|
||||
/** 0: facing you; 1: turned a little away; 2: closed a little, waiting. Never lowers the stage. */
|
||||
readonly drift: 0 | 1 | 2;
|
||||
readonly mood: Mood;
|
||||
/** Water level now: 0 is dry, from `ROSE.enough` her leaves lift, above `ROSE.tooFull` too full. */
|
||||
readonly water: number;
|
||||
readonly needs: Needs;
|
||||
/** Local days on which care helped, in all. */
|
||||
readonly daysOfCare: number;
|
||||
/** Days of care in the last seven local days, today included. */
|
||||
readonly warmth: number;
|
||||
readonly trend: Trend;
|
||||
readonly lastDayOfCare: LocalDay | null;
|
||||
}
|
||||
|
||||
/** A number in [0, 1) from the rose's key, a day and a topic: the same on every replay. FNV-1a. */
|
||||
export function seeded(seed: string, day: LocalDay, topic: string): number {
|
||||
let h = 0x811c9dc5;
|
||||
for (const ch of `${seed}|${day}|${topic}`) {
|
||||
h ^= ch.codePointAt(0)!;
|
||||
h = Math.imul(h, 0x01000193) >>> 0;
|
||||
}
|
||||
return h / 0x1_0000_0000;
|
||||
}
|
||||
|
||||
export const weedsOn = (seed: string, day: LocalDay): boolean => seeded(seed, day, 'weeds') < ROSE.weedChance;
|
||||
export const petalsOn = (seed: string, day: LocalDay): boolean => seeded(seed, day, 'petals') < ROSE.petalChance;
|
||||
|
||||
/** The day's wind, as [first, last) minutes on the local clock, or null on a still day. */
|
||||
export function windOn(seed: string, day: LocalDay): readonly [number, number] | null {
|
||||
if (seeded(seed, day, 'wind') >= ROSE.windChance) return null;
|
||||
const start = ROSE.windEarliest + Math.floor(seeded(seed, day, 'wind-start') * (ROSE.windLatest - ROSE.windEarliest));
|
||||
return [start, start + ROSE.windMinutes];
|
||||
}
|
||||
|
||||
export function stageFor(daysOfCare: number): Stage {
|
||||
const [opening, half, full] = ROSE.stageDays;
|
||||
return daysOfCare >= full ? 'full-bloom' : daysOfCare >= half ? 'half-bloom' : daysOfCare >= opening ? 'opening' : 'bud';
|
||||
}
|
||||
|
||||
/** What a pour of `amount` (0–1) would do, for the can in the player's hand. */
|
||||
export function pour(waterNow: number, amount: number): { readonly after: number; readonly leavesLift: boolean; readonly tooFull: boolean; readonly helps: boolean } {
|
||||
const after = waterNow + Math.min(1, Math.max(0, amount)) * ROSE.fullPour;
|
||||
const tooFull = after > ROSE.tooFull;
|
||||
return { after, leavesLift: after >= ROSE.enough, tooFull, helps: waterNow < ROSE.enough && after >= ROSE.enough && !tooFull };
|
||||
}
|
||||
|
||||
/**
|
||||
* The petal a player's care leaves behind (CLAUDE.md §6.2, `trace`). Every player's
|
||||
* is rose-coloured until friends can tell them apart (Phase 3).
|
||||
*/
|
||||
export const OWN_TRACE = 'petal:rose';
|
||||
|
||||
/**
|
||||
* One act of care as the log keeps it. The day is computed here, by the one module
|
||||
* that computes days, in the rose's zone (rose.md R8). `amount` only for water.
|
||||
*/
|
||||
export function careEvent(p: {
|
||||
readonly now: number;
|
||||
readonly timeZone: string;
|
||||
readonly from: string;
|
||||
readonly to: string;
|
||||
readonly act: CareEvent['act'];
|
||||
readonly amount?: number;
|
||||
readonly clientVersion: string;
|
||||
}): CareEvent {
|
||||
const base = {
|
||||
kind: 'care' as const, ts: Math.round(p.now), localDay: localDay(p.now, p.timeZone), from: p.from, to: p.to,
|
||||
act: p.act, trace: OWN_TRACE, messageId: null, clientVersion: p.clientVersion
|
||||
};
|
||||
if (p.act !== 'water') return base;
|
||||
// Two decimals are feel enough, and keep the log free of float noise.
|
||||
return { ...base, amount: Math.round(Math.min(1, Math.max(0, p.amount ?? 0)) * 100) / 100 };
|
||||
}
|
||||
|
||||
/** What makes two care events the same act: the same moment, giver, rose and act. */
|
||||
export const careIdentity = (e: CareEvent): string => `${e.ts}|${e.from}|${e.to}|${e.act}|${e.amount ?? ''}`;
|
||||
|
||||
/** The acts in `incoming` that `existing` does not hold yet: bringing a rose back twice adds nothing twice. */
|
||||
export function newCare(existing: readonly CareEvent[], incoming: readonly CareEvent[]): CareEvent[] {
|
||||
const seen = new Set(existing.map(careIdentity));
|
||||
const out: CareEvent[] = [];
|
||||
for (const e of incoming) {
|
||||
const id = careIdentity(e);
|
||||
if (!seen.has(id)) {
|
||||
seen.add(id);
|
||||
out.push(e);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** One act of the log, judged: did it meet a real need? */
|
||||
export interface Judged {
|
||||
readonly event: CareEvent;
|
||||
readonly helped: boolean;
|
||||
}
|
||||
|
||||
interface Replay {
|
||||
readonly judged: readonly Judged[];
|
||||
readonly days: ReadonlySet<LocalDay>;
|
||||
readonly water: { readonly level: number; readonly at: number | null };
|
||||
readonly met: ReadonlyMap<string, true>;
|
||||
readonly firstDay: LocalDay | null;
|
||||
}
|
||||
|
||||
const fall = (level: number, from: number | null, to: number): number =>
|
||||
from === null ? level : Math.max(0, level - (ROSE.waterFallPerDay * Math.max(0, to - from)) / DAY_MS);
|
||||
|
||||
/**
|
||||
* The rose's keys: the current one first, then any she was named by before, on
|
||||
* another device (keep-her-safe.md K2). A single key is a rose that never moved.
|
||||
*/
|
||||
export type RoseKeys = string | readonly string[];
|
||||
const keyList = (keys: RoseKeys): readonly string[] => (typeof keys === 'string' ? [keys] : keys);
|
||||
|
||||
/**
|
||||
* The care given under one key, in order, each act judged with that key's own
|
||||
* weeds, petals and wind. `inherited` are days of care earned under her other keys:
|
||||
* they count towards her stage, so a moved rose drops petals as she did before.
|
||||
*/
|
||||
function replay(events: readonly CareEvent[], seed: string, timeZone: string, inherited: ReadonlySet<LocalDay> = new Set()): Replay {
|
||||
const mine = events
|
||||
.map((e, i) => ({ e, i }))
|
||||
.filter(({ e }) => e.kind === 'care' && e.to === seed)
|
||||
.sort((a, b) => a.e.ts - b.e.ts || a.i - b.i)
|
||||
.map(({ e }) => e);
|
||||
|
||||
const grownBy = (day: LocalDay): number => new Set([...days, ...[...inherited].filter((d) => d <= day)]).size;
|
||||
const days = new Set<LocalDay>();
|
||||
const met = new Map<string, true>();
|
||||
const judged: Judged[] = [];
|
||||
let level: number = ROSE.waterStart;
|
||||
let at: number | null = null;
|
||||
|
||||
for (const e of mine) {
|
||||
const day = e.localDay; // the day recorded when it happened is the day that counts
|
||||
let helped = false;
|
||||
level = fall(level, at, e.ts);
|
||||
at = e.ts;
|
||||
switch (e.act) {
|
||||
case 'water': {
|
||||
const p = pour(level, e.amount ?? 0);
|
||||
helped = p.helps;
|
||||
level = p.after;
|
||||
break;
|
||||
}
|
||||
case 'weed':
|
||||
helped = weedsOn(seed, day) && !met.has(`${day}|weeds`);
|
||||
if (helped) met.set(`${day}|weeds`, true);
|
||||
break;
|
||||
case 'petals':
|
||||
helped = stageFor(grownBy(day)) !== 'bud' && petalsOn(seed, day) && !met.has(`${day}|petals`);
|
||||
if (helped) met.set(`${day}|petals`, true);
|
||||
break;
|
||||
case 'shade': {
|
||||
const wind = windOn(seed, day);
|
||||
const minute = localMinutes(e.ts, timeZone);
|
||||
helped = wind !== null && minute >= wind[0] && minute < wind[1] && !met.has(`${day}|wind`);
|
||||
if (helped) met.set(`${day}|wind`, true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (helped) days.add(day);
|
||||
judged.push({ event: e, helped });
|
||||
}
|
||||
return { judged, days, water: { level, at }, met, firstDay: mine[0]?.localDay ?? null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Replays every key separately: the past keys first, then the current one, which
|
||||
* inherits their days. Each key's judgments depend only on its own care, so adding
|
||||
* another key's log can never take a day of care away (keep-her-safe.md K3).
|
||||
*/
|
||||
function replayAll(events: readonly CareEvent[], keys: RoseKeys, timeZone: string): { current: Replay; all: readonly Replay[]; days: ReadonlySet<LocalDay> } {
|
||||
const [currentKey = '', ...past] = keyList(keys);
|
||||
const pastReplays = past.map((k) => replay(events, k, timeZone));
|
||||
const inherited = new Set(pastReplays.flatMap((r) => [...r.days]));
|
||||
const current = replay(events, currentKey, timeZone, inherited);
|
||||
return { current, all: [current, ...pastReplays], days: new Set([...inherited, ...current.days]) };
|
||||
}
|
||||
|
||||
/** Every act given to the rose, with whether it helped, in time order. */
|
||||
export function judgeCare(events: readonly CareEvent[], keys: RoseKeys, timeZone: string): readonly Judged[] {
|
||||
return replayAll(events, keys, timeZone).all.flatMap((r) => r.judged).sort((a, b) => a.event.ts - b.event.ts);
|
||||
}
|
||||
|
||||
/**
|
||||
* The rose at `now`: a pure replay of `events` for the rose named by `keys`. Her
|
||||
* water and today's needs come from the current key; her days of care, stage and
|
||||
* drift from all of them.
|
||||
*/
|
||||
export function roseAt(events: readonly CareEvent[], keys: RoseKeys, now: number, timeZone: string): RoseNow {
|
||||
const { current: r, all, days } = replayAll(events, keys, timeZone);
|
||||
const seed = keyList(keys)[0] ?? '';
|
||||
const today = localDay(now, timeZone);
|
||||
const water = fall(r.water.level, r.water.at, now);
|
||||
const stage = stageFor(days.size);
|
||||
const firstDay = all.map((x) => x.firstDay).filter((d): d is LocalDay => d !== null).sort()[0] ?? null;
|
||||
|
||||
const wind = windOn(seed, today);
|
||||
const minute = localMinutes(now, timeZone);
|
||||
const needs: Needs = {
|
||||
water: water < ROSE.enough,
|
||||
weeds: weedsOn(seed, today) && !r.met.has(`${today}|weeds`),
|
||||
petals: stage !== 'bud' && petalsOn(seed, today) && !r.met.has(`${today}|petals`),
|
||||
wind: wind !== null && minute >= wind[0] && minute < wind[1] && !r.met.has(`${today}|wind`)
|
||||
};
|
||||
|
||||
const careDays = [...days].filter((d) => d <= today).sort();
|
||||
const lastDayOfCare = careDays.at(-1) ?? null;
|
||||
const since = daysBetween(lastDayOfCare ?? firstDay ?? today, today);
|
||||
const drift = since >= ROSE.driftDays[1] ? 2 : since >= ROSE.driftDays[0] ? 1 : 0;
|
||||
const weekStart = addDays(today, -6);
|
||||
const warmth = careDays.filter((d) => d >= weekStart).length;
|
||||
const trend: Trend = drift > 0 ? 'waiting' : lastDayOfCare !== null && daysBetween(lastDayOfCare, today) <= 1 ? 'growing' : 'steady';
|
||||
|
||||
const lastHelp = all.flatMap((x) => x.judged).filter((j) => j.helped && j.event.ts <= now).sort((a, b) => b.event.ts - a.event.ts)[0];
|
||||
const blushing = lastHelp !== undefined && now - lastHelp.event.ts < ROSE.blushMinutes * 60_000;
|
||||
const mood: Mood = blushing ? 'blushing'
|
||||
: water > ROSE.tooFull ? 'too-full'
|
||||
: needs.wind ? 'windblown'
|
||||
: drift > 0 ? 'waiting'
|
||||
: water < ROSE.thirsty ? 'thirsty'
|
||||
: 'content';
|
||||
|
||||
return { stage, drift, mood, water, needs, daysOfCare: days.size, warmth, trend, lastDayOfCare };
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* The ONLY place in the repository where the sun is computed (CLAUDE.md §7).
|
||||
*
|
||||
* NOAA's solar calculator, after Meeus, Astronomical Algorithms: the sun's
|
||||
* declination and the equation of time at an instant, then the hour angle at
|
||||
* which the sun's centre is 0.833° below the horizon (refraction plus its
|
||||
* radius). Good to about a minute below 72° latitude.
|
||||
*
|
||||
* Every time returned is an instant (epoch milliseconds). Reading it on a clock
|
||||
* is the app's job, with the city's zone, so a DST change moves only the clock
|
||||
* (.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).
|
||||
*/
|
||||
import { addDays, isLocalDay, localDay, type LocalDay } from '../time/localDay.js';
|
||||
|
||||
export interface Place {
|
||||
/** Degrees, north positive. */
|
||||
readonly lat: number;
|
||||
/** Degrees, east positive. */
|
||||
readonly lon: number;
|
||||
/** IANA zone whose local day is asked about. */
|
||||
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
|
||||
* noon, so tonight's sunset may fall after midnight, on the next local day (D2).
|
||||
*/
|
||||
export type SunDay =
|
||||
| { readonly kind: 'sun-sets'; readonly day: LocalDay; readonly sunrise: number; readonly solarNoon: number; readonly sunset: number }
|
||||
/** The sun never sets. `lowestLight` is solar midnight, after this day's noon. */
|
||||
| { readonly kind: 'polar-day'; readonly day: LocalDay; readonly solarNoon: number; readonly lowestLight: number }
|
||||
/** The sun never rises. Solar noon is when the twilight is brightest. */
|
||||
| { readonly kind: 'polar-night'; readonly day: LocalDay; readonly solarNoon: number };
|
||||
|
||||
const MINUTE = 60_000;
|
||||
const DAY = 24 * 60 * MINUTE;
|
||||
const RAD = Math.PI / 180;
|
||||
/** The sun's centre at sunrise and sunset: 0.833° below the horizon. */
|
||||
const ZENITH = 90.833 * RAD;
|
||||
|
||||
interface Sun {
|
||||
/** Radians. */
|
||||
readonly declination: number;
|
||||
/** Minutes the true sun is ahead of the mean sun. */
|
||||
readonly equationOfTime: number;
|
||||
}
|
||||
|
||||
/** The sun's declination and the equation of time at an instant (NOAA). */
|
||||
function sunAt(epochMs: number): Sun {
|
||||
const T = (epochMs / DAY + 2440587.5 - 2451545) / 36525; // Julian centuries since J2000.0
|
||||
const L0 = (((280.46646 + T * (36000.76983 + T * 0.0003032)) % 360) + 360) % 360;
|
||||
const M = 357.52911 + T * (35999.05029 - 0.0001537 * T);
|
||||
const e = 0.016708634 - T * (0.000042037 + 0.0000001267 * T);
|
||||
const C = Math.sin(M * RAD) * (1.914602 - T * (0.004817 + 0.000014 * T))
|
||||
+ Math.sin(2 * M * RAD) * (0.019993 - 0.000101 * T)
|
||||
+ Math.sin(3 * M * RAD) * 0.000289;
|
||||
const omega = 125.04 - 1934.136 * T;
|
||||
const lambda = L0 + C - 0.00569 - 0.00478 * Math.sin(omega * RAD);
|
||||
const eps0 = 23 + (26 + (21.448 - T * (46.815 + T * (0.00059 - T * 0.001813))) / 60) / 60;
|
||||
const eps = (eps0 + 0.00256 * Math.cos(omega * RAD)) * RAD;
|
||||
const y = Math.tan(eps / 2) ** 2;
|
||||
const eq = y * Math.sin(2 * L0 * RAD) - 2 * e * Math.sin(M * RAD)
|
||||
+ 4 * e * y * Math.sin(M * RAD) * Math.cos(2 * L0 * RAD)
|
||||
- 0.5 * y * y * Math.sin(4 * L0 * RAD) - 1.25 * e * e * Math.sin(2 * M * RAD);
|
||||
return { declination: Math.asin(Math.sin(eps) * Math.sin(lambda * RAD)), equationOfTime: (4 * eq) / RAD };
|
||||
}
|
||||
|
||||
/** cos of the hour angle at sunrise and sunset. Above 1: never rises. Below -1: never sets. */
|
||||
function cosHourAngle(lat: number, declination: number): number {
|
||||
return Math.cos(ZENITH) / (Math.cos(lat * RAD) * Math.cos(declination)) - Math.tan(lat * RAD) * Math.tan(declination);
|
||||
}
|
||||
|
||||
/** Solar noon nearest 12:00 mean solar time on the UTC date starting at `utcMidnight`. */
|
||||
function solarNoonOn(utcMidnight: number, lon: number): number {
|
||||
let noon = utcMidnight + (720 - 4 * lon) * MINUTE;
|
||||
for (let i = 0; i < 2; i++) noon = utcMidnight + (720 - 4 * lon - sunAt(noon).equationOfTime) * MINUTE;
|
||||
return noon;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sunrise (`side` -1) or sunset (`side` +1) around the solar noon of the UTC date
|
||||
* starting at `utcMidnight`, refined at its own instant. The date is passed in,
|
||||
* never derived from noon: near 180° the noon itself can fall on the next UTC date.
|
||||
* An hour angle out of range, only near the edge of polar day or night, is clamped (D5).
|
||||
*/
|
||||
function horizonCrossing(utcMidnight: number, noon: number, lat: number, lon: number, side: -1 | 1): number {
|
||||
let at = noon;
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const sun = sunAt(at);
|
||||
const H = Math.acos(Math.min(1, Math.max(-1, cosHourAngle(lat, sun.declination)))) / RAD; // degrees
|
||||
// Minutes from this UTC midnight; below 0 or above 1440 is the day before or after.
|
||||
const fromMidnight = 720 - 4 * lon - sun.equationOfTime + side * 4 * H;
|
||||
at = utcMidnight + fromMidnight * MINUTE;
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
function check(day: LocalDay, place: Place): number {
|
||||
if (!isLocalDay(day)) throw new RangeError(`sunDay: '${day}' is not a LocalDay (YYYY-MM-DD)`);
|
||||
const [y, m, d] = day.split('-').map(Number) as [number, number, number];
|
||||
const utcMidnight = Date.UTC(y, m - 1, d);
|
||||
if (new Date(utcMidnight).getUTCDate() !== d) throw new RangeError(`sunDay: ${day} does not exist`);
|
||||
if (!(Math.abs(place.lat) <= 90)) throw new RangeError(`sunDay: latitude ${place.lat} is outside -90..90`);
|
||||
if (!(Math.abs(place.lon) <= 180)) throw new RangeError(`sunDay: longitude ${place.lon} is outside -180..180`);
|
||||
return utcMidnight;
|
||||
}
|
||||
|
||||
/** The sun on one local day at one place. */
|
||||
export function sunDay(day: LocalDay, place: Place): SunDay {
|
||||
const { lat, lon, timeZone } = place;
|
||||
let utcMidnight = check(day, place);
|
||||
|
||||
// The solar noon that falls on this local day. Zones far from their longitude
|
||||
// (UTC+14 at 157° W) put it on the UTC date before or after. A clock twelve
|
||||
// hours off the sun can leave a day with no noon at all; then the nearest is
|
||||
// used (D8). No real zone is that far off.
|
||||
let solarNoon = solarNoonOn(utcMidnight, lon);
|
||||
for (let i = 0; i < 2; i++) {
|
||||
const on = localDay(solarNoon, timeZone);
|
||||
if (on === day) break;
|
||||
utcMidnight += on < day ? DAY : -DAY;
|
||||
solarNoon = solarNoonOn(utcMidnight, lon);
|
||||
}
|
||||
|
||||
const c = cosHourAngle(lat, sunAt(solarNoon).declination);
|
||||
if (c > 1) return { kind: 'polar-night', day, solarNoon };
|
||||
// Solar midnight: halfway to the next solar noon.
|
||||
if (c < -1) return { kind: 'polar-day', day, solarNoon, lowestLight: (solarNoon + solarNoonOn(utcMidnight + DAY, lon)) / 2 };
|
||||
return {
|
||||
kind: 'sun-sets', day, solarNoon,
|
||||
sunrise: horizonCrossing(utcMidnight, solarNoon, lat, lon, -1),
|
||||
sunset: horizonCrossing(utcMidnight, solarNoon, lat, lon, 1)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* light; in polar night noon, when the twilight is brightest (D4; decided by the
|
||||
* author, Q10).
|
||||
*/
|
||||
export function invitation(sun: SunDay): number {
|
||||
switch (sun.kind) {
|
||||
case 'sun-sets': return sun.sunset;
|
||||
case 'polar-day': return sun.lowestLight;
|
||||
case 'polar-night': return sun.solarNoon;
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,39 @@ export function localDay(epochMs: number, timeZone: string): LocalDay {
|
||||
return day;
|
||||
}
|
||||
|
||||
const clockFormatters = new Map<string, Intl.DateTimeFormat>();
|
||||
|
||||
/** Minutes after local midnight on the clock of `timeZone` (0–1439): what a clock there shows. */
|
||||
export function localMinutes(epochMs: number, timeZone: string): number {
|
||||
if (!Number.isFinite(epochMs)) throw new RangeError(`localMinutes: epochMs must be a finite number, got ${String(epochMs)}`);
|
||||
let f = clockFormatters.get(timeZone);
|
||||
if (f === undefined) {
|
||||
f = new Intl.DateTimeFormat('en-GB', { timeZone, hour: '2-digit', minute: '2-digit', hourCycle: 'h23', numberingSystem: 'latn' });
|
||||
clockFormatters.set(timeZone, f);
|
||||
}
|
||||
const parts = f.formatToParts(epochMs);
|
||||
const n = (type: Intl.DateTimeFormatPartTypes): number => Number(parts.find((p) => p.type === type)?.value);
|
||||
return n('hour') * 60 + n('minute');
|
||||
}
|
||||
|
||||
/** Whole calendar days from `from` to `to`: positive when `to` is later. */
|
||||
export function daysBetween(from: LocalDay, to: LocalDay): number {
|
||||
const utc = (day: LocalDay): number => {
|
||||
if (!isLocalDay(day)) throw new RangeError(`daysBetween: '${day}' is not a LocalDay`);
|
||||
const [y, m, d] = day.split('-').map(Number) as [number, number, number];
|
||||
return Date.UTC(y, m - 1, d);
|
||||
};
|
||||
return Math.round((utc(to) - utc(from)) / 86_400_000);
|
||||
}
|
||||
|
||||
/** 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. */
|
||||
export function isLocalDay(value: string): value is LocalDay {
|
||||
return LOCAL_DAY.test(value);
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
{
|
||||
"source": "https://aa.usno.navy.mil/api/rstt/oneday (U.S. Naval Observatory, Astronomical Applications). Times are HH:MM on the local clock at utcOffset; null means the event does not happen that day.",
|
||||
"recorded": "2026-11-01",
|
||||
"rows": [
|
||||
{
|
||||
"city": "Prague",
|
||||
"lat": 50.0755,
|
||||
"lon": 14.4378,
|
||||
"timeZone": "Europe/Prague",
|
||||
"day": "2026-03-28",
|
||||
"utcOffset": 1,
|
||||
"why": "the day before DST starts",
|
||||
"rise": "05:48",
|
||||
"transit": "12:07",
|
||||
"set": "18:28"
|
||||
},
|
||||
{
|
||||
"city": "Prague",
|
||||
"lat": 50.0755,
|
||||
"lon": 14.4378,
|
||||
"timeZone": "Europe/Prague",
|
||||
"day": "2026-03-29",
|
||||
"utcOffset": 2,
|
||||
"why": "DST starts",
|
||||
"rise": "06:46",
|
||||
"transit": "13:07",
|
||||
"set": "19:29"
|
||||
},
|
||||
{
|
||||
"city": "Prague",
|
||||
"lat": 50.0755,
|
||||
"lon": 14.4378,
|
||||
"timeZone": "Europe/Prague",
|
||||
"day": "2026-06-21",
|
||||
"utcOffset": 2,
|
||||
"why": "midsummer",
|
||||
"rise": "04:53",
|
||||
"transit": "13:04",
|
||||
"set": "21:16"
|
||||
},
|
||||
{
|
||||
"city": "Prague",
|
||||
"lat": 50.0755,
|
||||
"lon": 14.4378,
|
||||
"timeZone": "Europe/Prague",
|
||||
"day": "2026-10-24",
|
||||
"utcOffset": 2,
|
||||
"why": "the day before DST ends",
|
||||
"rise": "07:39",
|
||||
"transit": "12:46",
|
||||
"set": "17:54"
|
||||
},
|
||||
{
|
||||
"city": "Prague",
|
||||
"lat": 50.0755,
|
||||
"lon": 14.4378,
|
||||
"timeZone": "Europe/Prague",
|
||||
"day": "2026-10-25",
|
||||
"utcOffset": 1,
|
||||
"why": "DST ends",
|
||||
"rise": "06:40",
|
||||
"transit": "11:46",
|
||||
"set": "16:52"
|
||||
},
|
||||
{
|
||||
"city": "Prague",
|
||||
"lat": 50.0755,
|
||||
"lon": 14.4378,
|
||||
"timeZone": "Europe/Prague",
|
||||
"day": "2026-12-21",
|
||||
"utcOffset": 1,
|
||||
"why": "midwinter",
|
||||
"rise": "07:58",
|
||||
"transit": "12:00",
|
||||
"set": "16:02"
|
||||
},
|
||||
{
|
||||
"city": "Reykjavík",
|
||||
"lat": 64.1466,
|
||||
"lon": -21.9426,
|
||||
"timeZone": "Atlantic/Reykjavik",
|
||||
"day": "2026-03-20",
|
||||
"utcOffset": 0,
|
||||
"why": "equinox",
|
||||
"rise": "07:29",
|
||||
"transit": "13:35",
|
||||
"set": "19:43"
|
||||
},
|
||||
{
|
||||
"city": "Reykjavík",
|
||||
"lat": 64.1466,
|
||||
"lon": -21.9426,
|
||||
"timeZone": "Atlantic/Reykjavik",
|
||||
"day": "2026-06-21",
|
||||
"utcOffset": 0,
|
||||
"why": "midsummer: a sunset near midnight",
|
||||
"rise": "02:55",
|
||||
"transit": "13:30",
|
||||
"set": "00:04"
|
||||
},
|
||||
{
|
||||
"city": "Reykjavík",
|
||||
"lat": 64.1466,
|
||||
"lon": -21.9426,
|
||||
"timeZone": "Atlantic/Reykjavik",
|
||||
"day": "2026-12-21",
|
||||
"utcOffset": 0,
|
||||
"why": "midwinter: four hours of day",
|
||||
"rise": "11:22",
|
||||
"transit": "13:26",
|
||||
"set": "15:29"
|
||||
},
|
||||
{
|
||||
"city": "Tromsø",
|
||||
"lat": 69.6492,
|
||||
"lon": 18.9553,
|
||||
"timeZone": "Europe/Oslo",
|
||||
"day": "2026-03-29",
|
||||
"utcOffset": 2,
|
||||
"why": "DST starts",
|
||||
"rise": "06:03",
|
||||
"transit": "12:49",
|
||||
"set": "19:37"
|
||||
},
|
||||
{
|
||||
"city": "Tromsø",
|
||||
"lat": 69.6492,
|
||||
"lon": 18.9553,
|
||||
"timeZone": "Europe/Oslo",
|
||||
"day": "2026-06-21",
|
||||
"utcOffset": 2,
|
||||
"why": "polar day",
|
||||
"rise": null,
|
||||
"transit": "12:46",
|
||||
"set": null
|
||||
},
|
||||
{
|
||||
"city": "Tromsø",
|
||||
"lat": 69.6492,
|
||||
"lon": 18.9553,
|
||||
"timeZone": "Europe/Oslo",
|
||||
"day": "2026-10-25",
|
||||
"utcOffset": 1,
|
||||
"why": "DST ends",
|
||||
"rise": "07:38",
|
||||
"transit": "11:28",
|
||||
"set": "15:17"
|
||||
},
|
||||
{
|
||||
"city": "Tromsø",
|
||||
"lat": 69.6492,
|
||||
"lon": 18.9553,
|
||||
"timeZone": "Europe/Oslo",
|
||||
"day": "2026-12-21",
|
||||
"utcOffset": 1,
|
||||
"why": "polar night",
|
||||
"rise": null,
|
||||
"transit": null,
|
||||
"set": null
|
||||
},
|
||||
{
|
||||
"city": "Quito",
|
||||
"lat": -0.1807,
|
||||
"lon": -78.4678,
|
||||
"timeZone": "America/Guayaquil",
|
||||
"day": "2026-03-20",
|
||||
"utcOffset": -5,
|
||||
"why": "equinox on the equator",
|
||||
"rise": "06:18",
|
||||
"transit": "12:21",
|
||||
"set": "18:24"
|
||||
},
|
||||
{
|
||||
"city": "Quito",
|
||||
"lat": -0.1807,
|
||||
"lon": -78.4678,
|
||||
"timeZone": "America/Guayaquil",
|
||||
"day": "2026-06-21",
|
||||
"utcOffset": -5,
|
||||
"why": "June solstice",
|
||||
"rise": "06:12",
|
||||
"transit": "12:16",
|
||||
"set": "18:19"
|
||||
},
|
||||
{
|
||||
"city": "Quito",
|
||||
"lat": -0.1807,
|
||||
"lon": -78.4678,
|
||||
"timeZone": "America/Guayaquil",
|
||||
"day": "2026-12-21",
|
||||
"utcOffset": -5,
|
||||
"why": "December solstice",
|
||||
"rise": "06:08",
|
||||
"transit": "12:12",
|
||||
"set": "18:16"
|
||||
},
|
||||
{
|
||||
"city": "Sydney",
|
||||
"lat": -33.8688,
|
||||
"lon": 151.2093,
|
||||
"timeZone": "Australia/Sydney",
|
||||
"day": "2026-04-04",
|
||||
"utcOffset": 11,
|
||||
"why": "the day before DST ends",
|
||||
"rise": "07:09",
|
||||
"transit": "12:58",
|
||||
"set": "18:47"
|
||||
},
|
||||
{
|
||||
"city": "Sydney",
|
||||
"lat": -33.8688,
|
||||
"lon": 151.2093,
|
||||
"timeZone": "Australia/Sydney",
|
||||
"day": "2026-04-05",
|
||||
"utcOffset": 10,
|
||||
"why": "DST ends",
|
||||
"rise": "06:10",
|
||||
"transit": "11:58",
|
||||
"set": "17:45"
|
||||
},
|
||||
{
|
||||
"city": "Sydney",
|
||||
"lat": -33.8688,
|
||||
"lon": 151.2093,
|
||||
"timeZone": "Australia/Sydney",
|
||||
"day": "2026-06-21",
|
||||
"utcOffset": 10,
|
||||
"why": "midwinter",
|
||||
"rise": "07:00",
|
||||
"transit": "11:57",
|
||||
"set": "16:54"
|
||||
},
|
||||
{
|
||||
"city": "Sydney",
|
||||
"lat": -33.8688,
|
||||
"lon": 151.2093,
|
||||
"timeZone": "Australia/Sydney",
|
||||
"day": "2026-10-03",
|
||||
"utcOffset": 10,
|
||||
"why": "the day before DST starts",
|
||||
"rise": "05:30",
|
||||
"transit": "11:44",
|
||||
"set": "17:59"
|
||||
},
|
||||
{
|
||||
"city": "Sydney",
|
||||
"lat": -33.8688,
|
||||
"lon": 151.2093,
|
||||
"timeZone": "Australia/Sydney",
|
||||
"day": "2026-10-04",
|
||||
"utcOffset": 11,
|
||||
"why": "DST starts",
|
||||
"rise": "06:29",
|
||||
"transit": "12:44",
|
||||
"set": "19:00"
|
||||
},
|
||||
{
|
||||
"city": "Sydney",
|
||||
"lat": -33.8688,
|
||||
"lon": 151.2093,
|
||||
"timeZone": "Australia/Sydney",
|
||||
"day": "2026-12-21",
|
||||
"utcOffset": 11,
|
||||
"why": "midsummer",
|
||||
"rise": "05:41",
|
||||
"transit": "12:53",
|
||||
"set": "20:05"
|
||||
},
|
||||
{
|
||||
"city": "Anchorage",
|
||||
"lat": 61.2181,
|
||||
"lon": -149.9003,
|
||||
"timeZone": "America/Anchorage",
|
||||
"day": "2026-03-07",
|
||||
"utcOffset": -9,
|
||||
"why": "the day before DST starts",
|
||||
"rise": "07:41",
|
||||
"transit": "13:10",
|
||||
"set": "18:41"
|
||||
},
|
||||
{
|
||||
"city": "Anchorage",
|
||||
"lat": 61.2181,
|
||||
"lon": -149.9003,
|
||||
"timeZone": "America/Anchorage",
|
||||
"day": "2026-03-08",
|
||||
"utcOffset": -8,
|
||||
"why": "DST starts",
|
||||
"rise": "08:38",
|
||||
"transit": "14:10",
|
||||
"set": "19:44"
|
||||
},
|
||||
{
|
||||
"city": "Anchorage",
|
||||
"lat": 61.2181,
|
||||
"lon": -149.9003,
|
||||
"timeZone": "America/Anchorage",
|
||||
"day": "2026-06-21",
|
||||
"utcOffset": -8,
|
||||
"why": "midsummer",
|
||||
"rise": "04:20",
|
||||
"transit": "14:02",
|
||||
"set": "23:43"
|
||||
},
|
||||
{
|
||||
"city": "Anchorage",
|
||||
"lat": 61.2181,
|
||||
"lon": -149.9003,
|
||||
"timeZone": "America/Anchorage",
|
||||
"day": "2026-10-31",
|
||||
"utcOffset": -8,
|
||||
"why": "the day before DST ends",
|
||||
"rise": "09:26",
|
||||
"transit": "13:43",
|
||||
"set": "18:00"
|
||||
},
|
||||
{
|
||||
"city": "Anchorage",
|
||||
"lat": 61.2181,
|
||||
"lon": -149.9003,
|
||||
"timeZone": "America/Anchorage",
|
||||
"day": "2026-11-01",
|
||||
"utcOffset": -9,
|
||||
"why": "DST ends",
|
||||
"rise": "08:28",
|
||||
"transit": "12:43",
|
||||
"set": "16:57"
|
||||
},
|
||||
{
|
||||
"city": "Anchorage",
|
||||
"lat": 61.2181,
|
||||
"lon": -149.9003,
|
||||
"timeZone": "America/Anchorage",
|
||||
"day": "2026-12-21",
|
||||
"utcOffset": -9,
|
||||
"why": "midwinter",
|
||||
"rise": "10:14",
|
||||
"transit": "12:58",
|
||||
"set": "15:41"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import fc from 'fast-check';
|
||||
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);
|
||||
|
||||
@@ -86,3 +86,27 @@ describe('localDay — properties', () => {
|
||||
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));
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
import fc from 'fast-check';
|
||||
import type { CareEvent } from '@rosea/schema';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { careEvent, judgeCare, newCare, OWN_TRACE, petalsOn, pour, ROSE, roseAt, stageFor, weedsOn, windOn, type Stage } from '../src/rose/rose.js';
|
||||
import { addDays, localDay } from '../src/time/localDay.js';
|
||||
|
||||
const ZONE = 'Europe/Prague';
|
||||
const ME = 'M'.repeat(43);
|
||||
const SOMEONE = 'S'.repeat(43);
|
||||
const HOUR = 3_600_000;
|
||||
const DAY = 24 * HOUR;
|
||||
/** 08:00 in Prague on 1 March 2026, before any wind can start. */
|
||||
const START = Date.parse('2026-03-01T08:00:00+01:00');
|
||||
|
||||
function care(ts: number, act: CareEvent['act'], amount?: number, to = ME): CareEvent {
|
||||
return {
|
||||
kind: 'care', ts, localDay: localDay(ts, ZONE), from: ME, to, act,
|
||||
trace: 'petal:pale-pink', messageId: null, clientVersion: '0.1.0',
|
||||
...(act === 'water' ? { amount: amount ?? 0.5 } : {})
|
||||
};
|
||||
}
|
||||
const at = (events: CareEvent[], now: number) => roseAt(events, ME, now, ZONE);
|
||||
/** Water her helpfully once a day for `n` days, 08:00 each morning. */
|
||||
const dailyWater = (n: number, from = START): CareEvent[] => Array.from({ length: n }, (_, i) => care(from + i * DAY, 'water', 0.5));
|
||||
const RANK: Record<Stage, number> = { bud: 0, opening: 1, 'half-bloom': 2, 'full-bloom': 3 };
|
||||
|
||||
/** The first day from START on which `has` is true for this rose. */
|
||||
function firstDayWith(has: (day: string) => boolean): number {
|
||||
for (let i = 0; i < 400; i++) if (has(localDay(START + i * DAY, ZONE))) return START + i * DAY;
|
||||
throw new Error('no such day in 400');
|
||||
}
|
||||
|
||||
describe('a new rose', () => {
|
||||
it('is a bud, a little low on water so the first pour helps, and not drifting', () => {
|
||||
const r = at([], START);
|
||||
expect(r).toMatchObject({ stage: 'bud', drift: 0, daysOfCare: 0, warmth: 0, lastDayOfCare: null });
|
||||
expect(r.water).toBe(ROSE.waterStart);
|
||||
expect(r.needs.water).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('water by feel', () => {
|
||||
it('the can tells when the leaves lift, and when it is too much', () => {
|
||||
expect(pour(0.3, 0.1)).toMatchObject({ leavesLift: false, helps: false });
|
||||
expect(pour(0.3, 0.5)).toMatchObject({ leavesLift: true, tooFull: false, helps: true });
|
||||
expect(pour(0.3, 1)).toMatchObject({ leavesLift: true, tooFull: false, helps: true });
|
||||
expect(pour(0.5, 1)).toMatchObject({ tooFull: true, helps: false });
|
||||
expect(pour(0.5, 0.1).helps, 'she did not need it').toBe(false);
|
||||
// She needed it, but a full can from just below "enough" overshoots: too much helps no more than too little.
|
||||
expect(pour(0.39, 1)).toMatchObject({ leavesLift: true, tooFull: true, helps: false });
|
||||
});
|
||||
|
||||
it('a pour that meets her need is a day of care, and she blushes for a while', () => {
|
||||
const r = at([care(START, 'water', 0.5)], START + 60_000);
|
||||
expect(r).toMatchObject({ daysOfCare: 1, mood: 'blushing', trend: 'growing' });
|
||||
expect(r.needs.water).toBe(false);
|
||||
expect(at([care(START, 'water', 0.5)], START + 2 * HOUR).mood).toBe('content');
|
||||
});
|
||||
|
||||
it('too much is as bad as too little: no day of care, and she is too full', () => {
|
||||
const r = at([care(START, 'water', 1), care(START + 60_000, 'water', 1)], START + 2 * HOUR);
|
||||
expect(r.daysOfCare).toBe(1); // the first pour helped; the second only overfilled her
|
||||
expect(r.mood).toBe('too-full');
|
||||
expect(judgeCare([care(START, 'water', 1), care(START + 60_000, 'water', 1)], ME, ZONE).map((j) => j.helped)).toEqual([true, false]);
|
||||
});
|
||||
|
||||
it('water falls by ROSE.waterFallPerDay a day, never below zero', () => {
|
||||
const events = [care(START, 'water', 0.5)];
|
||||
expect(at(events, START + DAY).water).toBeCloseTo(0.6 - ROSE.waterFallPerDay, 6);
|
||||
expect(at(events, START + 30 * DAY).water).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('weeds, petals, wind', () => {
|
||||
it('pulling weeds helps on a day with weeds, once; on a day without, it does not', () => {
|
||||
const weedy = firstDayWith((d) => weedsOn(ME, d));
|
||||
const clear = firstDayWith((d) => !weedsOn(ME, d));
|
||||
expect(judgeCare([care(weedy, 'weed'), care(weedy + 60_000, 'weed')], ME, ZONE).map((j) => j.helped)).toEqual([true, false]);
|
||||
expect(judgeCare([care(clear, 'weed')], ME, ZONE)[0]?.helped).toBe(false);
|
||||
expect(at([], weedy).needs.weeds).toBe(true);
|
||||
expect(at([care(weedy, 'weed')], weedy + 60_000).needs.weeds).toBe(false);
|
||||
});
|
||||
|
||||
it('shade helps only while the wind blows', () => {
|
||||
const windy = firstDayWith((d) => windOn(ME, d) !== null);
|
||||
const [from] = windOn(ME, localDay(windy, ZONE))!;
|
||||
const midnight = windy - 8 * HOUR; // windy is 08:00 local
|
||||
const during = midnight + (from + 10) * 60_000;
|
||||
const before = midnight + (from - 30) * 60_000;
|
||||
expect(at([], during).needs.wind).toBe(true);
|
||||
expect(at([], during).mood).toBe('windblown');
|
||||
expect(judgeCare([care(before, 'shade')], ME, ZONE)[0]?.helped).toBe(false);
|
||||
expect(judgeCare([care(during, 'shade')], ME, ZONE)[0]?.helped).toBe(true);
|
||||
expect(at([care(during, 'shade')], during + 60_000).needs.wind).toBe(false);
|
||||
});
|
||||
|
||||
it('a bud drops no petals; from the opening stage, petals can be gathered', () => {
|
||||
const grown = dailyWater(ROSE.stageDays[0]);
|
||||
const after = START + ROSE.stageDays[0] * DAY;
|
||||
const petalDay = firstDayWith((d) => petalsOn(ME, d) && d >= localDay(after, ZONE));
|
||||
expect(at([], petalDay).needs.petals, 'a bud').toBe(false);
|
||||
expect(at(grown, petalDay).stage).toBe('opening');
|
||||
expect(at(grown, petalDay).needs.petals).toBe(true);
|
||||
});
|
||||
|
||||
it('come at about their rates, and differ between two roses', () => {
|
||||
const days = Array.from({ length: 2000 }, (_, i) => addDays('2026-01-01', i));
|
||||
const rate = (f: (d: string) => boolean): number => days.filter(f).length / days.length;
|
||||
expect(Math.abs(rate((d) => weedsOn(ME, d)) - ROSE.weedChance)).toBeLessThan(0.04);
|
||||
expect(Math.abs(rate((d) => petalsOn(ME, d)) - ROSE.petalChance)).toBeLessThan(0.04);
|
||||
expect(Math.abs(rate((d) => windOn(ME, d) !== null) - ROSE.windChance)).toBeLessThan(0.04);
|
||||
expect(days.filter((d) => weedsOn(ME, d) !== weedsOn(SOMEONE, d)).length).toBeGreaterThan(500);
|
||||
for (const d of days) {
|
||||
const w = windOn(ME, d);
|
||||
if (w) expect(w[0] >= ROSE.windEarliest && w[0] < ROSE.windLatest && w[1] - w[0] === ROSE.windMinutes).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('growth and drift', () => {
|
||||
it('stages come from days of care: bud, opening, half bloom, full bloom', () => {
|
||||
const [opening, half, full] = ROSE.stageDays;
|
||||
expect([0, opening - 1, opening, half, full, 400].map(stageFor)).toEqual(['bud', 'bud', 'opening', 'half-bloom', 'full-bloom', 'full-bloom']);
|
||||
expect(at(dailyWater(full), START + full * DAY).stage).toBe('full-bloom');
|
||||
});
|
||||
|
||||
it('drifts a little after 3 days, more after 7, never losing her stage; one helpful touch brings her back', () => {
|
||||
const events = dailyWater(12);
|
||||
const last = START + 11 * DAY;
|
||||
const r = (d: number) => at(events, last + d * DAY);
|
||||
expect([0, 2, 3, 6, 7, 60].map((d) => r(d).drift)).toEqual([0, 0, 1, 1, 2, 2]);
|
||||
expect(r(60).stage).toBe(r(0).stage);
|
||||
expect(r(60).daysOfCare).toBe(12);
|
||||
expect(r(60).mood).toBe('waiting');
|
||||
expect(r(60).trend).toBe('waiting');
|
||||
// Dry after two months, she needs a fuller pour before her leaves lift.
|
||||
const back = [...events, care(last + 60 * DAY, 'water', 1)];
|
||||
expect(at(back, last + 60 * DAY + HOUR).drift).toBe(0);
|
||||
});
|
||||
|
||||
it('warmth is days of care in the last seven, and says nothing of the rest', () => {
|
||||
const events = dailyWater(10);
|
||||
expect(at(events, START + 9 * DAY).warmth).toBe(7);
|
||||
expect(at(events, START + 12 * DAY).warmth).toBe(4);
|
||||
expect(at(events, START + 40 * DAY).warmth).toBe(0);
|
||||
});
|
||||
|
||||
it('the log is replayed in time order, however it was stored', () => {
|
||||
const [first, second] = [care(START, 'water', 0.5), care(START + DAY, 'water', 0.5)];
|
||||
expect(at([first, second], START + 2 * DAY).daysOfCare).toBe(2);
|
||||
expect(at([second, first], START + 2 * DAY).daysOfCare).toBe(2);
|
||||
});
|
||||
|
||||
it('only care given to this rose counts', () => {
|
||||
expect(at([care(START, 'water', 0.5, SOMEONE)], START + HOUR).daysOfCare).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('properties (CLAUDE.md §5.5)', () => {
|
||||
const act = fc.constantFrom<CareEvent['act']>('water', 'shade', 'weed', 'petals');
|
||||
/** A log over two months: acts at random moments, in time order, as a real log is. */
|
||||
const log = fc.array(fc.tuple(fc.integer({ min: 0, max: 60 * 24 * 60 - 1 }), act, fc.double({ min: 0, max: 1, noNaN: true })), { maxLength: 80 })
|
||||
.map((xs) => xs.map(([minute, a, amount]) => care(START + minute * 60_000, a, amount)).sort((x, y) => x.ts - y.ts));
|
||||
const END = START + 70 * DAY;
|
||||
|
||||
it('growth never decreases as the log grows', () => {
|
||||
fc.assert(fc.property(log, (events) => {
|
||||
let previous = -1;
|
||||
for (let k = 0; k <= events.length; k++) {
|
||||
const r = at(events.slice(0, k), END);
|
||||
if (r.daysOfCare < previous) return false;
|
||||
previous = r.daysOfCare;
|
||||
}
|
||||
return true;
|
||||
}), { numRuns: 60 });
|
||||
});
|
||||
|
||||
it('a gap never lowers the stage or the days of care', () => {
|
||||
fc.assert(fc.property(log, fc.integer({ min: 1, max: 3650 }), (events, gap) => {
|
||||
const a = at(events, END);
|
||||
const b = at(events, END + gap * DAY);
|
||||
return RANK[b.stage] === RANK[a.stage] && b.daysOfCare === a.daysOfCare;
|
||||
}), { numRuns: 100 });
|
||||
});
|
||||
|
||||
it('a long session is worth no more than a short one: days of care never exceed the days with care', () => {
|
||||
fc.assert(fc.property(log, (events) => at(events, END).daysOfCare <= new Set(events.map((e) => e.localDay)).size), { numRuns: 200 });
|
||||
});
|
||||
|
||||
it('replaying the same log twice, in any order it was stored, gives identical state', () => {
|
||||
fc.assert(fc.property(log, fc.integer(), (events, seed) => {
|
||||
const shuffled = [...events].sort((a, b) => ((a.ts * 31 + seed) % 7) - ((b.ts * 31 + seed) % 7));
|
||||
return JSON.stringify(at(events, END)) === JSON.stringify(at(events, END)) && JSON.stringify(at(shuffled, END)) === JSON.stringify(at(events, END));
|
||||
}), { numRuns: 100 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('careEvent — one act as the log keeps it', () => {
|
||||
it('is the schema\'s shape, with the day in the rose\'s zone and the amount only for water', async () => {
|
||||
const { validateCareEvent } = await import('@rosea/schema/validate');
|
||||
// 00:30 in Prague on 31 March is the 31st there, though UTC still says the 30th.
|
||||
const late = Date.parse('2026-03-31T00:30:00+02:00');
|
||||
const w = careEvent({ now: late, timeZone: ZONE, from: ME, to: ME, act: 'water', amount: 0.4567, clientVersion: '0.1.0' });
|
||||
expect(w).toMatchObject({ localDay: '2026-03-31', amount: 0.46, trace: OWN_TRACE, messageId: null });
|
||||
expect(validateCareEvent(w)).toMatchObject({ ok: true });
|
||||
const s = careEvent({ now: late, timeZone: ZONE, from: ME, to: ME, act: 'shade', amount: 0.5, clientVersion: '0.1.0' });
|
||||
expect('amount' in s).toBe(false);
|
||||
expect(validateCareEvent(s)).toMatchObject({ ok: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('a rose brought back under a new key (keep-her-safe.md)', () => {
|
||||
const NEW = 'N'.repeat(43);
|
||||
const careAs = (to: string, ts: number, amount = 0.5): CareEvent => ({ ...care(ts, 'water', amount), from: to, to });
|
||||
|
||||
it('keeps every day of care given under her old key, and starts her water afresh under the new one', () => {
|
||||
const old = dailyWater(12);
|
||||
const now = START + 12 * DAY;
|
||||
const before = roseAt(old, ME, now, ZONE);
|
||||
const moved = roseAt(old, [NEW, ME], now, ZONE);
|
||||
expect(moved.daysOfCare).toBe(before.daysOfCare);
|
||||
expect(moved.stage).toBe(before.stage);
|
||||
expect(moved.lastDayOfCare).toBe(before.lastDayOfCare);
|
||||
expect(moved.water).toBe(ROSE.waterStart); // no care under the new key yet
|
||||
// Care under the new key adds to the old days.
|
||||
const after = roseAt([...old, careAs(NEW, now)], [NEW, ME], now + 60_000, ZONE);
|
||||
expect(after.daysOfCare).toBe(before.daysOfCare + 1);
|
||||
});
|
||||
|
||||
it('a moved rose that is opening drops petals, and gathering them helps', () => {
|
||||
const old = dailyWater(ROSE.stageDays[0]);
|
||||
const from = START + ROSE.stageDays[0] * DAY;
|
||||
let day = from;
|
||||
while (!petalsOn(NEW, localDay(day, ZONE))) day += DAY;
|
||||
expect(roseAt(old, [NEW, ME], day, ZONE).needs.petals).toBe(true);
|
||||
const gathered = { ...care(day, 'petals'), from: NEW, to: NEW };
|
||||
expect(judgeCare([...old, gathered], [NEW, ME], ZONE).at(-1)?.helped).toBe(true);
|
||||
});
|
||||
|
||||
it('merging two logs never takes a day of care away from either', () => {
|
||||
const act = fc.constantFrom<CareEvent['act']>('water', 'shade', 'weed', 'petals');
|
||||
const logAs = (to: string) => fc.array(fc.tuple(fc.integer({ min: 0, max: 40 * 24 * 60 }), act, fc.double({ min: 0, max: 1, noNaN: true })), { maxLength: 40 })
|
||||
.map((xs) => xs.map(([m, a, amount]) => ({ ...care(START + m * 60_000, a, amount), from: to, to })));
|
||||
fc.assert(fc.property(logAs(ME), logAs(NEW), (a, b) => {
|
||||
const end = START + 50 * DAY;
|
||||
const merged = roseAt([...a, ...b], [NEW, ME], end, ZONE).daysOfCare;
|
||||
return merged >= roseAt(a, ME, end, ZONE).daysOfCare && merged >= roseAt(b, NEW, end, ZONE).daysOfCare;
|
||||
}), { numRuns: 150 });
|
||||
});
|
||||
|
||||
it('newCare adds each act once, however often the same file is brought back', () => {
|
||||
const log = dailyWater(3);
|
||||
expect(newCare([], log)).toEqual(log);
|
||||
expect(newCare(log, log)).toEqual([]);
|
||||
expect(newCare(log.slice(0, 1), [...log, ...log])).toEqual(log.slice(1));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,257 @@
|
||||
import fc from 'fast-check';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { invitation, nextInvitation, sunDay, type Place, type SunDay } from '../src/sun/sun.js';
|
||||
import { addDays, localDay } from '../src/time/localDay.js';
|
||||
|
||||
/** Recorded by scripts/fetch-sun-golden.ts from the U.S. Naval Observatory. */
|
||||
interface Row {
|
||||
readonly city: string;
|
||||
readonly lat: number;
|
||||
readonly lon: number;
|
||||
readonly timeZone: string;
|
||||
readonly day: string;
|
||||
readonly utcOffset: number;
|
||||
readonly why: string;
|
||||
readonly rise: string | null;
|
||||
readonly transit: string | null;
|
||||
readonly set: string | null;
|
||||
}
|
||||
const golden = JSON.parse(readFileSync(new URL('./fixtures/sun-usno.json', import.meta.url), 'utf8')) as { rows: Row[] };
|
||||
|
||||
/** The almanac rounds to the minute, and NOAA's method is good to about a minute below 72°. */
|
||||
const TOLERANCE_MINUTES = 2;
|
||||
const MINUTE = 60_000;
|
||||
const HOUR = 60 * MINUTE;
|
||||
|
||||
const clocks = new Map<string, Intl.DateTimeFormat>();
|
||||
/** Minutes after midnight on the local clock of `timeZone`: what a person there reads. */
|
||||
function clock(epochMs: number, timeZone: string): number {
|
||||
let f = clocks.get(timeZone);
|
||||
if (!f) {
|
||||
f = new Intl.DateTimeFormat('en-GB', { timeZone, hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23' });
|
||||
clocks.set(timeZone, f);
|
||||
}
|
||||
const p = Object.fromEntries(f.formatToParts(epochMs).map((x) => [x.type, x.value]));
|
||||
return Number(p.hour) * 60 + Number(p.minute) + Number(p.second) / 60;
|
||||
}
|
||||
const minutes = (hhmm: string): number => Number(hhmm.slice(0, 2)) * 60 + Number(hhmm.slice(3));
|
||||
/** The shortest way round the clock face, so 23:59 and 00:01 are 2 minutes apart. */
|
||||
const apart = (a: number, b: number): number => Math.min(Math.abs(a - b), 1440 - Math.abs(a - b));
|
||||
|
||||
function offsetHours(epochMs: number, timeZone: string): number {
|
||||
const name = new Intl.DateTimeFormat('en-US', { timeZone, timeZoneName: 'longOffset' }).formatToParts(epochMs).find((p) => p.type === 'timeZoneName')?.value ?? '';
|
||||
const m = /GMT([+-])(\d\d):(\d\d)/.exec(name);
|
||||
return m ? (m[1] === '-' ? -1 : 1) * (Number(m[2]) + Number(m[3]) / 60) : 0;
|
||||
}
|
||||
|
||||
const placeOf = (r: Row): Place => ({ lat: r.lat, lon: r.lon, timeZone: r.timeZone });
|
||||
const UTC = (lat: number, lon: number): Place => ({ lat, lon, timeZone: 'UTC' });
|
||||
/**
|
||||
* A place whose clock follows its longitude, as real zones roughly do. Etc/GMT
|
||||
* signs are inverted: Etc/GMT-5 is UTC+5.
|
||||
*/
|
||||
const zoned = (lat: number, lon: number): Place => {
|
||||
const offset = Math.round(lon / 15);
|
||||
return { lat, lon, timeZone: offset === 0 ? 'Etc/GMT' : `Etc/GMT${offset > 0 ? '-' : '+'}${Math.abs(offset)}` };
|
||||
};
|
||||
|
||||
describe('sunDay — golden, against the U.S. Naval Observatory tables', () => {
|
||||
it('the fixture covers six cities, both hemispheres, the equator, the Arctic and every DST change it names', () => {
|
||||
expect(new Set(golden.rows.map((r) => r.city))).toEqual(new Set(['Prague', 'Reykjavík', 'Tromsø', 'Quito', 'Sydney', 'Anchorage']));
|
||||
expect(golden.rows.filter((r) => /DST (starts|ends)/.test(r.why) && !r.why.startsWith('the day before'))).toHaveLength(8);
|
||||
});
|
||||
|
||||
const sunny = golden.rows.filter((r) => r.rise !== null && r.set !== null);
|
||||
it.each(sunny.map((r) => [r.city, r.day, r.why, r] as const))('%s %s (%s): rise, noon and set within 2 min, on the local clock', (_c, _d, _w, r) => {
|
||||
const s = sunDay(r.day, placeOf(r));
|
||||
if (s.kind !== 'sun-sets') throw new Error(`expected a sunset, got ${s.kind}`);
|
||||
// The table and the zone database agree about the clock that day.
|
||||
expect(offsetHours(s.solarNoon, r.timeZone)).toBe(r.utcOffset);
|
||||
expect(apart(clock(s.sunrise, r.timeZone), minutes(r.rise ?? ''))).toBeLessThanOrEqual(TOLERANCE_MINUTES);
|
||||
expect(apart(clock(s.solarNoon, r.timeZone), minutes(r.transit ?? ''))).toBeLessThanOrEqual(TOLERANCE_MINUTES);
|
||||
expect(apart(clock(s.sunset, r.timeZone), minutes(r.set ?? ''))).toBeLessThanOrEqual(TOLERANCE_MINUTES);
|
||||
expect(localDay(s.solarNoon, r.timeZone)).toBe(r.day);
|
||||
});
|
||||
|
||||
it('Reykjavík at midsummer: tonight\'s sunset falls after midnight, so it is on the next local day (D2)', () => {
|
||||
const r = golden.rows.find((x) => x.city === 'Reykjavík' && x.day === '2026-06-21');
|
||||
const s = sunDay('2026-06-21', placeOf(r!));
|
||||
if (s.kind !== 'sun-sets') throw new Error(s.kind);
|
||||
// The table lists 00:04 on the 21st: that is the evening of the 20th. Ours is the evening of the 21st.
|
||||
expect(localDay(s.sunset, 'Atlantic/Reykjavik')).toBe('2026-06-22');
|
||||
expect(s.sunset - s.solarNoon).toBeGreaterThan(10 * HOUR);
|
||||
});
|
||||
|
||||
it('Tromsø: polar day on 21 June, polar night on 21 December, as the table says', () => {
|
||||
const tromso = golden.rows.filter((r) => r.city === 'Tromsø');
|
||||
const june = tromso.find((r) => r.day === '2026-06-21')!;
|
||||
const december = tromso.find((r) => r.day === '2026-12-21')!;
|
||||
expect([june.rise, june.set, december.rise, december.set]).toEqual([null, null, null, null]);
|
||||
|
||||
const summer = sunDay(june.day, placeOf(june));
|
||||
expect(summer.kind).toBe('polar-day');
|
||||
expect(apart(clock(summer.solarNoon, june.timeZone), minutes(june.transit ?? ''))).toBeLessThanOrEqual(TOLERANCE_MINUTES);
|
||||
expect(sunDay(december.day, placeOf(december)).kind).toBe('polar-night');
|
||||
});
|
||||
});
|
||||
|
||||
describe('sunDay — the clock changes, the sun does not', () => {
|
||||
it('Prague, 29 March: the sunset on the clock jumps an hour, the instant moves about a day', () => {
|
||||
const prague: Place = { lat: 50.0755, lon: 14.4378, timeZone: 'Europe/Prague' };
|
||||
const before = sunDay('2026-03-28', prague);
|
||||
const after = sunDay('2026-03-29', prague);
|
||||
if (before.kind !== 'sun-sets' || after.kind !== 'sun-sets') throw new Error('expected sunsets');
|
||||
const moved = after.sunset - before.sunset;
|
||||
expect(Math.abs(moved - 24 * HOUR)).toBeLessThan(3 * MINUTE); // the sun: a minute or two
|
||||
const onTheClock = clock(after.sunset, prague.timeZone) - clock(before.sunset, prague.timeZone);
|
||||
expect(onTheClock).toBeGreaterThan(58);
|
||||
expect(onTheClock).toBeLessThan(63); // the clock: an hour
|
||||
});
|
||||
|
||||
it('Sydney, 5 April: the clocks go back, and the sunset on the clock comes an hour earlier', () => {
|
||||
const sydney: Place = { lat: -33.8688, lon: 151.2093, timeZone: 'Australia/Sydney' };
|
||||
const before = sunDay('2026-04-04', sydney);
|
||||
const after = sunDay('2026-04-05', sydney);
|
||||
if (before.kind !== 'sun-sets' || after.kind !== 'sun-sets') throw new Error('expected sunsets');
|
||||
const onTheClock = clock(after.sunset, sydney.timeZone) - clock(before.sunset, sydney.timeZone);
|
||||
expect(onTheClock).toBeLessThan(-58);
|
||||
expect(onTheClock).toBeGreaterThan(-63);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sunDay — properties', () => {
|
||||
const days2026 = fc.integer({ min: 0, max: 364 }).map((n) => localDay(Date.UTC(2026, 0, 1) + n * 24 * HOUR, 'UTC'));
|
||||
const midLatitudes = fc.double({ min: -60, max: 60, noNaN: true });
|
||||
const longitudes = fc.double({ min: -180, max: 180, noNaN: true });
|
||||
|
||||
it('within ±60°, at any longitude with its own clock: sunrise before noon before sunset, noon midway, noon on the asked day', () => {
|
||||
fc.assert(fc.property(midLatitudes, longitudes, days2026, (lat, lon, day) => {
|
||||
const place = zoned(lat, lon);
|
||||
const s = sunDay(day, place);
|
||||
if (s.kind !== 'sun-sets') return false;
|
||||
const morning = s.solarNoon - s.sunrise;
|
||||
const afternoon = s.sunset - s.solarNoon;
|
||||
return s.sunrise < s.solarNoon && s.solarNoon < s.sunset
|
||||
&& Math.abs(morning - afternoon) < 2 * MINUTE
|
||||
&& s.sunset - s.sunrise < 24 * HOUR
|
||||
&& localDay(s.solarNoon, place.timeZone) === day;
|
||||
}), { numRuns: 500 });
|
||||
});
|
||||
|
||||
it('within ±60°, sunsets on consecutive days are never more than 5 minutes apart on the sun\'s own clock', () => {
|
||||
fc.assert(fc.property(midLatitudes, longitudes, fc.integer({ min: 0, max: 363 }), (lat, lon, n) => {
|
||||
const day = (k: number): string => localDay(Date.UTC(2026, 0, 1) + k * 24 * HOUR, 'UTC');
|
||||
const a = sunDay(day(n), zoned(lat, lon));
|
||||
const b = sunDay(day(n + 1), zoned(lat, lon));
|
||||
if (a.kind !== 'sun-sets' || b.kind !== 'sun-sets') return false;
|
||||
return Math.abs(b.sunset - a.sunset - 24 * HOUR) < 5 * MINUTE;
|
||||
}), { numRuns: 300 });
|
||||
});
|
||||
|
||||
it('the invitation is always a defined instant near the asked day, for every latitude', () => {
|
||||
fc.assert(fc.property(fc.double({ min: -90, max: 90, noNaN: true }), longitudes, days2026, (lat, lon, day) => {
|
||||
const s = sunDay(day, UTC(lat, lon));
|
||||
const at = invitation(s);
|
||||
return Number.isFinite(at) && at >= s.solarNoon - 12 * HOUR && at <= s.solarNoon + 24 * HOUR;
|
||||
}), { numRuns: 500 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('sunDay — the far north and south (D4)', () => {
|
||||
it.each([
|
||||
[80, '2026-06-21', 'polar-day'], [80, '2026-12-21', 'polar-night'],
|
||||
[-80, '2026-06-21', 'polar-night'], [-80, '2026-12-21', 'polar-day'],
|
||||
[90, '2026-06-21', 'polar-day'], [-90, '2026-06-21', 'polar-night']
|
||||
] as const)('latitude %s on %s is %s', (lat, day, kind) => {
|
||||
expect(sunDay(day, UTC(lat, 0)).kind).toBe(kind);
|
||||
});
|
||||
|
||||
it('polar day invites at the lowest light, about twelve hours after noon; polar night at noon, when the twilight is brightest', () => {
|
||||
const summer = sunDay('2026-06-21', UTC(80, 15));
|
||||
if (summer.kind !== 'polar-day') throw new Error(summer.kind);
|
||||
expect(invitation(summer)).toBe(summer.lowestLight);
|
||||
expect(Math.abs(summer.lowestLight - summer.solarNoon - 12 * HOUR)).toBeLessThan(MINUTE);
|
||||
const winter = sunDay('2026-12-21', UTC(80, 15));
|
||||
expect(invitation(winter)).toBe(winter.solarNoon);
|
||||
});
|
||||
|
||||
it('where the sun sets, the invitation is the sunset', () => {
|
||||
const s: SunDay = sunDay('2026-06-21', { lat: 50.0755, lon: 14.4378, timeZone: 'Europe/Prague' });
|
||||
if (s.kind !== 'sun-sets') throw new Error(s.kind);
|
||||
expect(invitation(s)).toBe(s.sunset);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sunDay — the edges of the clock face', () => {
|
||||
it('Kiritimati, UTC+14 at 157° W: noon falls on the next UTC date, and is still on the asked local day', () => {
|
||||
const kiritimati: Place = { lat: 1.87, lon: -157.4, timeZone: 'Pacific/Kiritimati' };
|
||||
for (const day of ['2026-01-01', '2026-06-21', '2026-12-31']) {
|
||||
const s = sunDay(day, kiritimati);
|
||||
expect(localDay(s.solarNoon, kiritimati.timeZone)).toBe(day);
|
||||
expect(localDay(s.solarNoon, 'UTC') < day).toBe(true); // UTC is still on the day before
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('sunDay — a clock twelve hours off the sun (D8)', () => {
|
||||
it('at 179.9° W on UTC, 26 December has no solar noon of its own; the engine gives the nearest one, never throws', () => {
|
||||
// Found by fast-check. Solar noon sits at midnight there and crosses it in late
|
||||
// December, so one calendar day holds none. No real zone is this far off the sun.
|
||||
const place = UTC(0, -179.92);
|
||||
const noons = ['2026-12-25', '2026-12-26', '2026-12-27'].map((d) => sunDay(d, place).solarNoon);
|
||||
expect(noons.map((n) => localDay(n, 'UTC'))).toEqual(['2026-12-25', '2026-12-27', '2026-12-27']);
|
||||
for (const n of noons) expect(Math.abs(n - Date.UTC(2026, 11, 26, 24))).toBeLessThan(25 * HOUR);
|
||||
});
|
||||
});
|
||||
|
||||
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', () => {
|
||||
it.each([
|
||||
['2026-02-30', UTC(50, 14), /does not exist/],
|
||||
['2026-6-1', UTC(50, 14), /not a LocalDay/],
|
||||
['2026-06-21', UTC(91, 14), /latitude/],
|
||||
['2026-06-21', UTC(50, 181), /longitude/],
|
||||
['2026-06-21', UTC(Number.NaN, 14), /latitude/],
|
||||
['2026-06-21', { lat: 50, lon: 14, timeZone: 'Europe/Pargue' }, /time zone/i]
|
||||
] as const)('%s at %o', (day, place, message) => {
|
||||
expect(() => sunDay(day, place)).toThrow(message);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "@rosea/identity",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Keypair lifecycle. The ONLY module that creates key material (CLAUDE.md §2).",
|
||||
"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": {},
|
||||
"devDependencies": {
|
||||
"typescript": "5.9.3",
|
||||
"vitest": "3.2.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* The player's identity: a keypair made on the device, and nothing else (CLAUDE.md §1,
|
||||
* *Anonymous*). No account, no name, no number. The public key is how the care log
|
||||
* names the rose (`from`, `to`); the private key cannot be exported, so it can never
|
||||
* leave this browser even by mistake. Nothing signs anything yet: that arrives with
|
||||
* friends (Phase 3).
|
||||
*
|
||||
* ECDSA P-256, not Ed25519: every browser that can install the PWA has it
|
||||
* (.agents/features/rose.md R9).
|
||||
*/
|
||||
|
||||
export interface Identity {
|
||||
/** The raw public key, base64url without padding: 87 characters. */
|
||||
readonly publicKey: string;
|
||||
/** Non-extractable. Kept by @rosea/storage as an opaque CryptoKey. */
|
||||
readonly privateKey: CryptoKey;
|
||||
}
|
||||
|
||||
const ALGORITHM: EcKeyGenParams = { name: 'ECDSA', namedCurve: 'P-256' };
|
||||
/** The schema's public-key pattern (packages/schema care-event, `publicKey`). */
|
||||
const PUBLIC_KEY = /^[A-Za-z0-9_-]{32,128}$/;
|
||||
|
||||
function base64url(bytes: Uint8Array): string {
|
||||
let s = '';
|
||||
for (const b of bytes) s += String.fromCharCode(b);
|
||||
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
/** Makes a new identity. `subtle` is a parameter so a test can pass Node's. */
|
||||
export async function createIdentity(subtle: SubtleCrypto = globalThis.crypto.subtle): Promise<Identity> {
|
||||
// extractable: false applies to the private key; the public key is always exportable.
|
||||
const pair = await subtle.generateKey(ALGORITHM, false, ['sign', 'verify']);
|
||||
const publicKey = base64url(new Uint8Array(await subtle.exportKey('raw', pair.publicKey)));
|
||||
return { publicKey, privateKey: pair.privateKey };
|
||||
}
|
||||
|
||||
/** The shape check for an identity read back from storage. */
|
||||
export function isIdentity(value: unknown): value is Identity {
|
||||
if (typeof value !== 'object' || value === null) return false;
|
||||
const v = value as Record<string, unknown>;
|
||||
return typeof v['publicKey'] === 'string' && PUBLIC_KEY.test(v['publicKey']) && typeof CryptoKey !== 'undefined' && v['privateKey'] instanceof CryptoKey;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { createIdentity, isIdentity } from '../src/index.js';
|
||||
|
||||
describe('createIdentity', () => {
|
||||
it('makes a public key that fits the care event\'s key pattern', async () => {
|
||||
const id = await createIdentity();
|
||||
expect(id.publicKey).toMatch(/^[A-Za-z0-9_-]{32,128}$/);
|
||||
expect(id.publicKey).toHaveLength(87); // 65 raw bytes of an uncompressed P-256 point
|
||||
});
|
||||
|
||||
it('two identities are two different keys', async () => {
|
||||
const [a, b] = await Promise.all([createIdentity(), createIdentity()]);
|
||||
expect(a.publicKey).not.toBe(b.publicKey);
|
||||
});
|
||||
|
||||
it('the private key cannot be exported, so it cannot leave the device', async () => {
|
||||
const id = await createIdentity();
|
||||
expect(id.privateKey.extractable).toBe(false);
|
||||
await expect(crypto.subtle.exportKey('pkcs8', id.privateKey)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('the private key still signs, and the public key verifies it', async () => {
|
||||
const id = await createIdentity();
|
||||
const data = new TextEncoder().encode('a petal');
|
||||
const sig = await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, id.privateKey, data);
|
||||
const raw = Uint8Array.from(atob(id.publicKey.replace(/-/g, '+').replace(/_/g, '/') + '='), (c) => c.charCodeAt(0));
|
||||
const pub = await crypto.subtle.importKey('raw', raw, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify']);
|
||||
expect(await crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, pub, sig, data)).toBe(true);
|
||||
});
|
||||
|
||||
it('isIdentity accepts one and refuses lookalikes', async () => {
|
||||
const id = await createIdentity();
|
||||
expect(isIdentity(id)).toBe(true);
|
||||
expect(isIdentity({ publicKey: id.publicKey, privateKey: 'secret' })).toBe(false);
|
||||
expect(isIdentity({ publicKey: 'short', privateKey: id.privateKey })).toBe(false);
|
||||
expect(isIdentity(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "test/**/*.ts"]
|
||||
}
|
||||
@@ -5,27 +5,102 @@
|
||||
"description": "One act of care, append-only and never edited (CLAUDE.md §6.2). The other event kinds arrive with docs/GAMEPLAY.md.",
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["kind", "ts", "localDay", "from", "to", "act", "trace", "messageId", "clientVersion"],
|
||||
"required": [
|
||||
"kind",
|
||||
"ts",
|
||||
"localDay",
|
||||
"from",
|
||||
"to",
|
||||
"act",
|
||||
"trace",
|
||||
"messageId",
|
||||
"clientVersion"
|
||||
],
|
||||
"properties": {
|
||||
"kind": { "const": "care" },
|
||||
"ts": { "description": "Epoch milliseconds. Stays on the device; never part of a trace.", "type": "integer", "minimum": 0 },
|
||||
"kind": {
|
||||
"const": "care"
|
||||
},
|
||||
"ts": {
|
||||
"description": "Epoch milliseconds. Stays on the device; never part of a trace.",
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"localDay": {
|
||||
"description": "The player's local day, from engine/src/time/localDay.ts and nowhere else.",
|
||||
"type": "string",
|
||||
"pattern": "^\\d{4}-\\d{2}-\\d{2}$"
|
||||
},
|
||||
"from": { "$ref": "#/definitions/publicKey" },
|
||||
"to": { "$ref": "#/definitions/publicKey" },
|
||||
"act": { "type": "string", "enum": ["water", "shade", "weed", "petals"] },
|
||||
"trace": { "type": "string", "pattern": "^petal:[a-z]+(-[a-z]+)*$" },
|
||||
"from": {
|
||||
"$ref": "#/definitions/publicKey"
|
||||
},
|
||||
"to": {
|
||||
"$ref": "#/definitions/publicKey"
|
||||
},
|
||||
"act": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"water",
|
||||
"shade",
|
||||
"weed",
|
||||
"petals"
|
||||
]
|
||||
},
|
||||
"trace": {
|
||||
"type": "string",
|
||||
"pattern": "^petal:[a-z]+(-[a-z]+)*$"
|
||||
},
|
||||
"messageId": {
|
||||
"description": "A hope-library id or null. Never text: the pattern admits no space, so no sentence fits (CLAUDE.md §5.6 rule 1).",
|
||||
"oneOf": [
|
||||
{ "type": "string", "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$", "maxLength": 64 },
|
||||
{ "type": "null" }
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$",
|
||||
"maxLength": 64
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"clientVersion": { "type": "string", "pattern": "^\\d+\\.\\d+\\.\\d+$" }
|
||||
"clientVersion": {
|
||||
"type": "string",
|
||||
"pattern": "^\\d+\\.\\d+\\.\\d+$"
|
||||
},
|
||||
"amount": {
|
||||
"description": "How much was poured, 0 to 1 of a full can. Water only: the skill of watering by feel is replayed from it (.agents/features/rose.md R1).",
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
}
|
||||
},
|
||||
"if": {
|
||||
"properties": {
|
||||
"act": {
|
||||
"const": "water"
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"amount": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"amount"
|
||||
]
|
||||
},
|
||||
"else": {
|
||||
"not": {
|
||||
"properties": {
|
||||
"amount": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"amount"
|
||||
]
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"publicKey": {
|
||||
|
||||
@@ -10,7 +10,7 @@ const careEvent = {
|
||||
localDay: '2026-10-24',
|
||||
from: KEY_A,
|
||||
to: KEY_B,
|
||||
act: 'water',
|
||||
act: 'shade',
|
||||
trace: 'petal:pale-pink',
|
||||
messageId: 'ps-23-4',
|
||||
clientVersion: '0.1.0'
|
||||
@@ -64,9 +64,19 @@ describe('hope sentence', () => {
|
||||
|
||||
describe('care event', () => {
|
||||
it('accepts every act the rose has', () => {
|
||||
for (const act of ['water', 'shade', 'weed', 'petals']) {
|
||||
for (const act of ['shade', 'weed', 'petals']) {
|
||||
expect(validateCareEvent({ ...careEvent, act }), act).toMatchObject({ ok: true });
|
||||
}
|
||||
expect(validateCareEvent({ ...careEvent, act: 'water', amount: 0.5 })).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it('water carries how much was poured, 0 to 1; no other act carries it (rose.md R1)', () => {
|
||||
expect(validateCareEvent({ ...careEvent, act: 'water' }).ok, 'water without amount').toBe(false);
|
||||
expect(validateCareEvent({ ...careEvent, act: 'water', amount: 0 }).ok).toBe(true);
|
||||
expect(validateCareEvent({ ...careEvent, act: 'water', amount: 1 }).ok).toBe(true);
|
||||
expect(validateCareEvent({ ...careEvent, act: 'water', amount: 1.01 }).ok).toBe(false);
|
||||
expect(validateCareEvent({ ...careEvent, act: 'water', amount: -0.1 }).ok).toBe(false);
|
||||
expect(validateCareEvent({ ...careEvent, act: 'weed', amount: 0.5 }).ok, 'weeds are pulled, not poured').toBe(false);
|
||||
});
|
||||
|
||||
it('rejects the acts §6.2 used to list by mistake', () => {
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"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:*",
|
||||
"@rosea/identity": "workspace:*",
|
||||
"@rosea/schema": "workspace:*",
|
||||
"dexie": "4.4.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"fake-indexeddb": "6.2.5",
|
||||
"typescript": "5.9.3",
|
||||
"vitest": "3.2.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
/**
|
||||
* 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` (the sunset place, sunset-place.md), `events` (the rose's care
|
||||
* log, rose.md) and `keys` (the identity, rose.md).
|
||||
*
|
||||
* The database name changes together with the product name (CLAUDE.md preamble).
|
||||
* Everything written is a fresh plain copy that passed a shape check: a Svelte 5
|
||||
* state Proxy cannot be structured-cloned (lessons/code.md), and nothing malformed
|
||||
* may enter a log that is never edited.
|
||||
*/
|
||||
import Dexie, { type DexieOptions, type Table } from 'dexie';
|
||||
import { newCare, type NamedPlace } from '@rosea/engine';
|
||||
import { isIdentity, type Identity } from '@rosea/identity';
|
||||
import { DATABASE_NAME, type CareEvent } from '@rosea/schema';
|
||||
|
||||
export { DATABASE_NAME };
|
||||
|
||||
/** 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;
|
||||
}
|
||||
interface EventRow {
|
||||
readonly id?: number;
|
||||
readonly event: unknown;
|
||||
}
|
||||
interface KeyRow {
|
||||
readonly id: string;
|
||||
readonly publicKey: string;
|
||||
readonly privateKey: CryptoKey;
|
||||
}
|
||||
|
||||
const SUNSET_PLACE = 'sunsetPlace';
|
||||
const SELF = 'self';
|
||||
const PAST_KEYS = 'pastKeys';
|
||||
|
||||
/** The file a rose is saved to and brought back from (keep-her-safe.md K4). Never the private key, never the town. */
|
||||
export const ROSE_FILE_FORMAT = 'rosea-rose';
|
||||
export interface RoseFile {
|
||||
readonly format: typeof ROSE_FILE_FORMAT;
|
||||
readonly version: 1;
|
||||
/** The keys that have named her, the one she had when saved first. Public keys only. */
|
||||
readonly keys: readonly string[];
|
||||
readonly events: readonly CareEvent[];
|
||||
}
|
||||
|
||||
export interface Storage {
|
||||
/** The saved sunset place, or null if the player has not answered yet. */
|
||||
loadSunsetPlace(): Promise<SunsetPlace | null>;
|
||||
saveSunsetPlace(place: SunsetPlace): Promise<void>;
|
||||
/** Appends one act of care. The log is never edited or shortened. */
|
||||
appendCare(event: CareEvent): Promise<void>;
|
||||
/** The whole care log, in the order it was written. */
|
||||
loadCare(): Promise<CareEvent[]>;
|
||||
/**
|
||||
* The player's identity: the one already kept, or `fresh` kept now. With two tabs
|
||||
* racing, both get the same one: the first write wins and the other is dropped.
|
||||
*/
|
||||
keepIdentity(fresh: Identity): Promise<Identity>;
|
||||
loadIdentity(): Promise<Identity | null>;
|
||||
/** Keys the rose was named by before, on another device; the current one is not among them. */
|
||||
loadPastKeys(): Promise<string[]>;
|
||||
/** The rose, as a file the player keeps (keep-her-safe.md). */
|
||||
exportRose(currentKey: string): Promise<RoseFile>;
|
||||
/**
|
||||
* Brings a saved rose back: her keys join the past keys and every act not already
|
||||
* here is appended. Nothing is edited or removed. Rejects a file that is not a rose.
|
||||
*/
|
||||
importRose(file: unknown, currentKey: string): Promise<{ readonly added: number }>;
|
||||
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';
|
||||
const matches = (x: unknown, re: RegExp): x is string => typeof x === 'string' && re.test(x);
|
||||
|
||||
/** 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'] } };
|
||||
}
|
||||
|
||||
const CARE_KEYS = new Set(['kind', 'ts', 'localDay', 'from', 'to', 'act', 'trace', 'messageId', 'clientVersion', 'amount']);
|
||||
const ACTS = new Set(['water', 'shade', 'weed', 'petals']);
|
||||
const KEY = /^[A-Za-z0-9_-]{32,128}$/;
|
||||
|
||||
/**
|
||||
* The care event contract (packages/schema care-event.schema.json), checked by hand:
|
||||
* Ajv compiles with `new Function`, which the app's CSP forbids (GAP_ANALYSIS G0.12).
|
||||
* `storage/test` checks this agrees with the schema's own validator.
|
||||
*/
|
||||
export function asCareEvent(value: unknown): CareEvent | null {
|
||||
if (typeof value !== 'object' || value === null) return null;
|
||||
const v = value as Record<string, unknown>;
|
||||
if (Object.keys(v).some((k) => !CARE_KEYS.has(k))) return null;
|
||||
if (v['kind'] !== 'care' || !Number.isSafeInteger(v['ts']) || (v['ts'] as number) < 0) return null;
|
||||
if (!matches(v['localDay'], /^\d{4}-\d{2}-\d{2}$/) || !matches(v['from'], KEY) || !matches(v['to'], KEY)) return null;
|
||||
if (!isString(v['act']) || !ACTS.has(v['act']) || !matches(v['trace'], /^petal:[a-z]+(-[a-z]+)*$/)) return null;
|
||||
const messageId = v['messageId'];
|
||||
if (messageId !== null && !(matches(messageId, /^[a-z0-9]+(-[a-z0-9]+)*$/) && messageId.length <= 64)) return null;
|
||||
if (!matches(v['clientVersion'], /^\d+\.\d+\.\d+$/)) return null;
|
||||
const isWater = v['act'] === 'water';
|
||||
if (isWater !== ('amount' in v)) return null;
|
||||
if (isWater && !(typeof v['amount'] === 'number' && v['amount'] >= 0 && v['amount'] <= 1)) return null;
|
||||
const base = {
|
||||
kind: 'care' as const, ts: v['ts'] as number, localDay: v['localDay'], from: v['from'], to: v['to'],
|
||||
act: v['act'] as CareEvent['act'], trace: v['trace'], messageId, clientVersion: v['clientVersion']
|
||||
};
|
||||
return isWater ? { ...base, amount: v['amount'] as number } : base;
|
||||
}
|
||||
|
||||
const isKeyList = (x: unknown): x is string[] => Array.isArray(x) && x.every((k) => matches(k, KEY));
|
||||
|
||||
/** The shape check for a saved rose. Every act must pass the care event contract. */
|
||||
export function asRoseFile(value: unknown): RoseFile | null {
|
||||
if (typeof value !== 'object' || value === null) return null;
|
||||
const v = value as Record<string, unknown>;
|
||||
if (v['format'] !== ROSE_FILE_FORMAT || v['version'] !== 1) return null;
|
||||
if (!isKeyList(v['keys']) || v['keys'].length === 0 || !Array.isArray(v['events'])) return null;
|
||||
const events: CareEvent[] = [];
|
||||
for (const e of v['events'] as unknown[]) {
|
||||
const plain = asCareEvent(e);
|
||||
if (plain === null) return null;
|
||||
events.push(plain);
|
||||
}
|
||||
return { format: ROSE_FILE_FORMAT, version: 1, keys: [...new Set(v['keys'])], events };
|
||||
}
|
||||
|
||||
class RoseaDatabase extends Dexie {
|
||||
profile!: Table<ProfileRow, string>;
|
||||
events!: Table<EventRow, number>;
|
||||
keys!: Table<KeyRow, string>;
|
||||
|
||||
constructor(options?: DexieOptions) {
|
||||
super(DATABASE_NAME, options);
|
||||
this.version(1).stores({ profile: 'key' });
|
||||
// Version 2 adds the care log and the identity; version 1 data is kept as it is.
|
||||
this.version(2).stores({ profile: 'key', events: '++id', keys: 'id' });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the player's database. `options` lets a test pass fake-indexeddb; the app
|
||||
* passes nothing and gets the browser's IndexedDB.
|
||||
*/
|
||||
export function openStorage(options?: DexieOptions): Storage {
|
||||
const db = new RoseaDatabase(options);
|
||||
const asIdentity = (row: KeyRow | undefined): Identity | null => {
|
||||
const id = row ? { publicKey: row.publicKey, privateKey: row.privateKey } : null;
|
||||
return id && isIdentity(id) ? id : null;
|
||||
};
|
||||
const api: Storage = {
|
||||
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) {
|
||||
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 });
|
||||
},
|
||||
async appendCare(event) {
|
||||
const plain = asCareEvent(event);
|
||||
if (plain === null) throw new TypeError('storage: refusing to append a care event of an unknown shape');
|
||||
await db.events.add({ event: plain });
|
||||
},
|
||||
async loadCare() {
|
||||
const rows = await db.events.orderBy('id').toArray();
|
||||
const events: CareEvent[] = [];
|
||||
for (const row of rows) {
|
||||
const e = asCareEvent(row.event);
|
||||
// A broken entry is said out loud and left in place: the log is never edited.
|
||||
if (e === null) console.warn('storage: a care event has an unknown shape; it is skipped, not removed', row);
|
||||
else events.push(e);
|
||||
}
|
||||
return events;
|
||||
},
|
||||
async keepIdentity(fresh) {
|
||||
if (!isIdentity(fresh)) throw new TypeError('storage: refusing to keep an identity of an unknown shape');
|
||||
return db.transaction('rw', db.keys, async () => {
|
||||
const kept = asIdentity(await db.keys.get(SELF));
|
||||
if (kept) return kept;
|
||||
await db.keys.add({ id: SELF, publicKey: fresh.publicKey, privateKey: fresh.privateKey });
|
||||
return { publicKey: fresh.publicKey, privateKey: fresh.privateKey };
|
||||
});
|
||||
},
|
||||
async loadIdentity() {
|
||||
return asIdentity(await db.keys.get(SELF));
|
||||
},
|
||||
async loadPastKeys() {
|
||||
const row = await db.profile.get(PAST_KEYS);
|
||||
if (row === undefined) return [];
|
||||
if (!isKeyList(row.value)) {
|
||||
console.warn('storage: the past keys have an unknown shape; ignoring them', row.value);
|
||||
return [];
|
||||
}
|
||||
return row.value;
|
||||
},
|
||||
async exportRose(currentKey) {
|
||||
const past = await api.loadPastKeys();
|
||||
return { format: ROSE_FILE_FORMAT, version: 1, keys: [...new Set([currentKey, ...past])], events: await api.loadCare() };
|
||||
},
|
||||
async importRose(file, currentKey) {
|
||||
const rose = asRoseFile(file);
|
||||
if (rose === null) throw new TypeError('storage: this file does not hold a rose');
|
||||
return db.transaction('rw', db.events, db.profile, async () => {
|
||||
const row = await db.profile.get(PAST_KEYS);
|
||||
const past = isKeyList(row?.value) ? row.value : [];
|
||||
const keys = [...new Set([...past, ...rose.keys])].filter((k) => k !== currentKey);
|
||||
await db.profile.put({ key: PAST_KEYS, value: keys });
|
||||
const existing = (await db.events.orderBy('id').toArray()).map((r) => asCareEvent(r.event)).filter((e): e is CareEvent => e !== null);
|
||||
const added = newCare(existing, rose.events);
|
||||
await db.events.bulkAdd(added.map((event) => ({ event })));
|
||||
return { added: added.length };
|
||||
});
|
||||
},
|
||||
close() {
|
||||
db.close();
|
||||
}
|
||||
};
|
||||
return api;
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { createIdentity } from '@rosea/identity';
|
||||
import type { CareEvent } from '@rosea/schema';
|
||||
import { validateCareEvent } from '@rosea/schema/validate';
|
||||
import Dexie from 'dexie';
|
||||
import { IDBFactory, IDBKeyRange } from 'fake-indexeddb';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { asCareEvent, openStorage, type Storage } from '../src/index.js';
|
||||
|
||||
const KEY = 'K'.repeat(87);
|
||||
const water: CareEvent = {
|
||||
kind: 'care', ts: 1774944000000, localDay: '2026-03-31', from: KEY, to: KEY, act: 'water',
|
||||
trace: 'petal:pale-pink', messageId: null, clientVersion: '0.1.0', amount: 0.5
|
||||
};
|
||||
const weed: CareEvent = { kind: 'care', ts: 1774944060000, localDay: '2026-03-31', from: KEY, to: KEY, act: 'weed', trace: 'petal:pale-pink', messageId: null, clientVersion: '0.1.0' };
|
||||
|
||||
const opened: Storage[] = [];
|
||||
const open = (indexedDB: IDBFactory = new IDBFactory()): Storage => {
|
||||
const s = openStorage({ indexedDB, IDBKeyRange });
|
||||
opened.push(s);
|
||||
return s;
|
||||
};
|
||||
afterEach(() => {
|
||||
for (const s of opened.splice(0)) s.close();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('the care log', () => {
|
||||
it('appends and comes back in the order written, across a reopen', async () => {
|
||||
const factory = new IDBFactory();
|
||||
const s = open(factory);
|
||||
await s.appendCare(water);
|
||||
await s.appendCare(new Proxy(weed, {})); // as Svelte 5 state would hand it over
|
||||
s.close();
|
||||
expect(await open(factory).loadCare()).toEqual([water, weed]);
|
||||
});
|
||||
|
||||
it('refuses to append anything the contract refuses', async () => {
|
||||
const s = open();
|
||||
for (const bad of [
|
||||
{ ...water, note: 'hello' },
|
||||
{ ...weed, amount: 0.5 },
|
||||
{ ...water, amount: 2 },
|
||||
{ ...weed, messageId: 'meet me at the station' }
|
||||
]) {
|
||||
await expect(s.appendCare(bad as CareEvent)).rejects.toThrow(/unknown shape/);
|
||||
}
|
||||
expect(await s.loadCare()).toEqual([]);
|
||||
});
|
||||
|
||||
it('a broken entry already in the log is skipped and said, never removed', async () => {
|
||||
const factory = new IDBFactory();
|
||||
const s = open(factory);
|
||||
await s.appendCare(water);
|
||||
s.close();
|
||||
const raw = new Dexie('rosea', { indexedDB: factory, IDBKeyRange });
|
||||
raw.version(2).stores({ profile: 'key', events: '++id', keys: 'id' });
|
||||
await raw.table('events').add({ event: { kind: 'care', act: 'dance' } });
|
||||
raw.close();
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
|
||||
expect(await open(factory).loadCare()).toEqual([water]);
|
||||
expect(warn).toHaveBeenCalledWith(expect.stringMatching(/skipped, not removed/), expect.anything());
|
||||
});
|
||||
});
|
||||
|
||||
describe('asCareEvent agrees with the schema\'s own validator', () => {
|
||||
const variants: Record<string, unknown>[] = [
|
||||
water, weed,
|
||||
{ ...water, amount: 0 }, { ...water, amount: 1 }, { ...water, amount: 1.5 }, { ...water, amount: -1 },
|
||||
{ ...water, amount: undefined }, { ...weed, amount: 0.2 }, { ...weed, act: 'water' },
|
||||
{ ...weed, act: 'wind' }, { ...weed, ts: -1 }, { ...weed, ts: 1.5 }, { ...weed, localDay: '2026-3-31' },
|
||||
{ ...weed, from: 'short' }, { ...weed, trace: 'petal:Pink' }, { ...weed, messageId: 'ps-23-4' },
|
||||
{ ...weed, messageId: 'x'.repeat(65) }, { ...weed, clientVersion: '1.0' }, { ...weed, kind: 'sunset' },
|
||||
{ ...weed, extra: true }
|
||||
].map((v) => Object.fromEntries(Object.entries(v).filter(([, x]) => x !== undefined)));
|
||||
|
||||
it.each(variants.map((v, i) => [i, v] as const))('variant %i', (_i, v) => {
|
||||
expect(asCareEvent(v) !== null).toBe(validateCareEvent(v).ok);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the identity', () => {
|
||||
it('is kept once; a second, racing one is dropped and the first returned', async () => {
|
||||
const factory = new IDBFactory();
|
||||
const s = open(factory);
|
||||
const [first, second] = [await createIdentity(), await createIdentity()];
|
||||
const [a, b] = await Promise.all([s.keepIdentity(first), open(factory).keepIdentity(second)]);
|
||||
expect(a.publicKey).toBe(b.publicKey);
|
||||
expect((await open(factory).loadIdentity())?.publicKey).toBe(a.publicKey);
|
||||
});
|
||||
|
||||
it('the private key comes back still unexportable', async () => {
|
||||
const factory = new IDBFactory();
|
||||
await open(factory).keepIdentity(await createIdentity());
|
||||
const back = await open(factory).loadIdentity();
|
||||
expect(back?.privateKey.extractable).toBe(false);
|
||||
});
|
||||
|
||||
it('nothing kept reads null', async () => {
|
||||
expect(await open().loadIdentity()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the database version', () => {
|
||||
it('upgrading from version 1 keeps the sunset place', async () => {
|
||||
const factory = new IDBFactory();
|
||||
const v1 = new Dexie('rosea', { indexedDB: factory, IDBKeyRange });
|
||||
v1.version(1).stores({ profile: 'key' });
|
||||
await v1.table('profile').put({ key: 'sunsetPlace', value: { kind: 'device-zone' } });
|
||||
v1.close();
|
||||
const s = open(factory);
|
||||
expect(await s.loadSunsetPlace()).toEqual({ kind: 'device-zone' });
|
||||
expect(await s.loadCare()).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import { IDBFactory, IDBKeyRange } from 'fake-indexeddb';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { asSunsetPlace, openStorage, type Storage, 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: Storage[] = [];
|
||||
/** A fresh, empty fake database per call unless one is passed: tests never share state. */
|
||||
function open(indexedDB: IDBFactory = new IDBFactory()): Storage {
|
||||
const p = openStorage({ 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(openStorage({ 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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import { createIdentity } from '@rosea/identity';
|
||||
import type { CareEvent } from '@rosea/schema';
|
||||
import { IDBFactory, IDBKeyRange } from 'fake-indexeddb';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { asRoseFile, openStorage, ROSE_FILE_FORMAT, type Storage } from '../src/index.js';
|
||||
|
||||
const OLD = 'O'.repeat(87);
|
||||
const NEW = 'N'.repeat(87);
|
||||
const act = (to: string, ts: number): CareEvent => ({
|
||||
kind: 'care', ts, localDay: '2026-03-01', from: to, to, act: 'water',
|
||||
trace: 'petal:rose', messageId: null, clientVersion: '0.1.0', amount: 0.5
|
||||
});
|
||||
|
||||
const opened: Storage[] = [];
|
||||
const open = (indexedDB: IDBFactory = new IDBFactory()): Storage => {
|
||||
const s = openStorage({ indexedDB, IDBKeyRange });
|
||||
opened.push(s);
|
||||
return s;
|
||||
};
|
||||
afterEach(() => {
|
||||
for (const s of opened.splice(0)) s.close();
|
||||
});
|
||||
|
||||
describe('saving the rose to a file', () => {
|
||||
it('holds her keys and her care, and nothing else: no private key, no town', async () => {
|
||||
const s = open();
|
||||
// A real identity is kept, so a leak of anything from it would have something to leak.
|
||||
await s.keepIdentity(await createIdentity());
|
||||
await s.saveSunsetPlace({ kind: 'town', town: { name: 'Brno', region: '', country: 'Czechia', lat: 49.2, lon: 16.61, timeZone: 'Europe/Prague' } });
|
||||
await s.appendCare(act(OLD, 1));
|
||||
const file = await s.exportRose(OLD);
|
||||
expect(file).toStrictEqual({ format: ROSE_FILE_FORMAT, version: 1, keys: [OLD], events: [act(OLD, 1)] });
|
||||
expect(JSON.stringify(file)).not.toMatch(/Brno|privateKey|CryptoKey/);
|
||||
});
|
||||
|
||||
it('survives a trip through JSON text unchanged', async () => {
|
||||
const s = open();
|
||||
await s.appendCare(act(OLD, 1));
|
||||
const file = await s.exportRose(OLD);
|
||||
expect(asRoseFile(JSON.parse(JSON.stringify(file)))).toEqual(file);
|
||||
});
|
||||
});
|
||||
|
||||
describe('bringing her back', () => {
|
||||
it('on a new device: her old key joins the past keys and all her care comes back', async () => {
|
||||
const old = open();
|
||||
await old.appendCare(act(OLD, 1));
|
||||
await old.appendCare(act(OLD, 2));
|
||||
const file = JSON.parse(JSON.stringify(await old.exportRose(OLD)));
|
||||
|
||||
const fresh = open();
|
||||
expect(await fresh.importRose(file, NEW)).toEqual({ added: 2 });
|
||||
expect(await fresh.loadPastKeys()).toEqual([OLD]);
|
||||
expect(await fresh.loadCare()).toEqual([act(OLD, 1), act(OLD, 2)]);
|
||||
});
|
||||
|
||||
it('twice is the same as once, and the care given here meanwhile stays', async () => {
|
||||
const old = open();
|
||||
await old.appendCare(act(OLD, 1));
|
||||
const file = await old.exportRose(OLD);
|
||||
const here = open();
|
||||
await here.appendCare(act(NEW, 5));
|
||||
await here.importRose(file, NEW);
|
||||
expect(await here.importRose(file, NEW)).toEqual({ added: 0 });
|
||||
expect(await here.loadCare()).toEqual([act(NEW, 5), act(OLD, 1)]);
|
||||
expect(await here.loadPastKeys()).toEqual([OLD]);
|
||||
});
|
||||
|
||||
it('a file saved on this very device adds nothing and does not list its own key as past', async () => {
|
||||
const s = open();
|
||||
await s.appendCare(act(NEW, 1));
|
||||
expect(await s.importRose(await s.exportRose(NEW), NEW)).toEqual({ added: 0 });
|
||||
expect(await s.loadPastKeys()).toEqual([]);
|
||||
});
|
||||
|
||||
it('refuses anything that is not a rose, and changes nothing', async () => {
|
||||
const s = open();
|
||||
await s.appendCare(act(NEW, 1));
|
||||
for (const bad of [
|
||||
null, 'rose', { format: 'other', version: 1, keys: [OLD], events: [] },
|
||||
{ format: ROSE_FILE_FORMAT, version: 2, keys: [OLD], events: [] },
|
||||
{ format: ROSE_FILE_FORMAT, version: 1, keys: [], events: [] },
|
||||
{ format: ROSE_FILE_FORMAT, version: 1, keys: ['short'], events: [] },
|
||||
{ format: ROSE_FILE_FORMAT, version: 1, keys: [OLD], events: [{ ...act(OLD, 1), note: 'hello' }] }
|
||||
]) {
|
||||
await expect(s.importRose(bad, NEW)).rejects.toThrow(/does not hold a rose/);
|
||||
}
|
||||
expect(await s.loadCare()).toEqual([act(NEW, 1)]);
|
||||
expect(await s.loadPastKeys()).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "test/**/*.ts"]
|
||||
}
|
||||
@@ -23,6 +23,7 @@
|
||||
"test": "vitest run --reporter=verbose"
|
||||
},
|
||||
"dependencies": {
|
||||
"@rosea/engine": "workspace:*",
|
||||
"@rosea/schema": "workspace:*"
|
||||
},
|
||||
"peerDependencies": {
|
||||
|
||||
@@ -1,11 +1,78 @@
|
||||
<script lang="ts">
|
||||
import { PRODUCT_NAME } from '@rosea/schema';
|
||||
import { tick } from 'svelte';
|
||||
import { en } from './copy/en.js';
|
||||
import Letter from './letter/Letter.svelte';
|
||||
import { parseLetter } from './letter/parse.js';
|
||||
import Rose from './rose/Rose.svelte';
|
||||
import type { RoseWiring } from './rose/types.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 { letter = '' }: { letter?: string } = $props();
|
||||
let {
|
||||
letter = '',
|
||||
sunset,
|
||||
rose
|
||||
}: {
|
||||
/** 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;
|
||||
/** The rose and her care log. Absent, the garden has no rose. */
|
||||
rose?: RoseWiring;
|
||||
} = $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));
|
||||
// One zone for the sunset and the rose's days: the chosen town's, else the device's (rose.md R8).
|
||||
const roseZone = $derived(choice?.kind === 'town' ? choice.town.timeZone : (rose?.deviceZone ?? 'UTC'));
|
||||
|
||||
$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';
|
||||
// Any hash but the letter's is the garden. A bare '#' is not a valid link target.
|
||||
@@ -45,6 +112,31 @@
|
||||
<main class="shell">
|
||||
<h1 bind:this={heading} tabindex="-1">{PRODUCT_NAME}</h1>
|
||||
<p>{en.shell.preparing}</p>
|
||||
{#if rose}
|
||||
<Rose wiring={rose} timeZone={roseZone} />
|
||||
{/if}
|
||||
{#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}
|
||||
<a href={LETTER_HASH}>{en.letter.title}</a>
|
||||
{/if}
|
||||
@@ -87,4 +179,34 @@
|
||||
a {
|
||||
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>
|
||||
|
||||
@@ -10,6 +10,84 @@ export const en = {
|
||||
/** The one line on the Phase 0 page. True, calm, and asks nothing. */
|
||||
preparing: 'The garden is being prepared.'
|
||||
},
|
||||
rose: {
|
||||
care: 'Care for her',
|
||||
water: 'Water',
|
||||
/** Watering is by feel (GAMEPLAY §1): hold, and let go when the leaves lift. */
|
||||
waterHint: 'Hold to pour. Let go when her leaves lift.',
|
||||
leavesLift: 'Her leaves lift.',
|
||||
plenty: 'That is plenty.',
|
||||
shade: 'Shade her',
|
||||
weed: 'Pull the weeds',
|
||||
petals: 'Gather the petals',
|
||||
numbers: 'Her numbers',
|
||||
waterLevel: 'Water',
|
||||
daysOfCare: 'Days of care',
|
||||
warmth: 'Warmth',
|
||||
trend: 'How she is',
|
||||
/** Never counts absence: no "0 of 7" (rose.md R7). */
|
||||
warmthDays: (n: number): string => (n === 0 ? 'resting' : n === 1 ? '1 day this week' : `${n} days this week`),
|
||||
trendWords: { growing: 'growing', steady: 'steady', waiting: 'waiting' },
|
||||
stageWords: { bud: 'a bud', opening: 'opening', 'half-bloom': 'in half bloom', 'full-bloom': 'in full bloom' },
|
||||
moodWords: {
|
||||
content: '',
|
||||
blushing: ', blushing',
|
||||
'too-full': ', full of water',
|
||||
windblown: ', in the wind',
|
||||
waiting: ', turned a little away, waiting',
|
||||
thirsty: ', thirsty'
|
||||
},
|
||||
picture: (stage: string, mood: string): string => `The rose, ${stage}${mood}.`,
|
||||
/** What she says. One line at a time; nothing at all when she needs nothing. Never blame. */
|
||||
says: {
|
||||
back: 'There you are.',
|
||||
thanks: 'Thank you.',
|
||||
wind: 'The wind is pulling at me. Could you shade me?',
|
||||
thirsty: 'A little water, please. Pour slowly, and stop when my leaves lift.',
|
||||
dry: 'My soil is getting dry.',
|
||||
weeds: 'Some weeds came up in the night.',
|
||||
petals: 'A few of my petals have fallen. Would you gather them?',
|
||||
tooFull: 'That was a lot of water. I will be fine by tomorrow.'
|
||||
},
|
||||
notKept: 'This device could not keep today’s care, so it lasts only until the garden closes.',
|
||||
/** Keeping her (keep-her-safe.md). True and calm: a browser can clear a site's data. */
|
||||
safe: {
|
||||
title: 'Keep her safe',
|
||||
kept: 'This browser has promised to keep her.',
|
||||
mayClear: 'This browser may clear her if the garden is not opened for a long time. A saved file keeps her for sure.',
|
||||
unknown: 'This browser decides for itself how long it keeps her. A saved file keeps her for sure.',
|
||||
ask: 'Ask the browser to keep her',
|
||||
refused: 'The browser did not promise. A saved file keeps her for sure.',
|
||||
install: 'On an iPhone or iPad, add the garden to your Home Screen to keep her.',
|
||||
save: 'Save her to a file',
|
||||
fileNote: 'The file holds her care and when it was given. It never holds your town.',
|
||||
bringBack: 'Bring her back from a file',
|
||||
broughtBack: (n: number): string => (n === 1 ? 'She is back, with 1 act of care.' : `She is back, with ${n} acts of care.`),
|
||||
alreadyHere: 'Everything in that file is already here.',
|
||||
notARose: 'That file does not hold a rose.'
|
||||
}
|
||||
},
|
||||
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: {
|
||||
/** The help section's name (ROADMAP §1). The letter itself is the author's, in docs/LETTER.md. */
|
||||
title: 'A Letter from the Gardener',
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
export { default as Shell } from './Shell.svelte';
|
||||
export { en, type Copy } from './copy/en.js';
|
||||
export { parseLetter, type Inline, type LetterBlock } from './letter/parse.js';
|
||||
export type { SunsetChoice, SunsetWiring } from './sunset/types.js';
|
||||
export type { RoseWiring } from './rose/types.js';
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
<script lang="ts">
|
||||
import { en } from '../copy/en.js';
|
||||
import type { RoseWiring } from './types.js';
|
||||
|
||||
/**
|
||||
* Keeping her (keep-her-safe.md): what the browser has promised, asking it to keep
|
||||
* her, saving her to a file, and bringing her back from one. Decides nothing; the
|
||||
* file's shape is checked by storage.
|
||||
*/
|
||||
let { wiring, currentKey, today, onrestored }: { wiring: RoseWiring; currentKey: string; today: string; onrestored: () => void } = $props();
|
||||
|
||||
const uid = $props.id();
|
||||
let persisted = $state<boolean | null | undefined>(undefined);
|
||||
let refused = $state(false);
|
||||
let said = $state('');
|
||||
|
||||
$effect(() => {
|
||||
wiring.keeping.persisted().then(
|
||||
(p) => (persisted = p),
|
||||
(error: unknown) => {
|
||||
console.error('keep: the browser could not say whether it keeps the garden', error);
|
||||
persisted = null;
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
async function ask(): Promise<void> {
|
||||
try {
|
||||
const granted = await wiring.keeping.persist();
|
||||
persisted = granted;
|
||||
refused = granted !== true;
|
||||
} catch (error) {
|
||||
console.error('keep: asking the browser to keep the garden failed', error);
|
||||
refused = true;
|
||||
}
|
||||
}
|
||||
|
||||
async function save(): Promise<void> {
|
||||
try {
|
||||
const file = await wiring.exportRose(currentKey);
|
||||
wiring.saveFile(`rose-${today}.json`, JSON.stringify(file, null, 1));
|
||||
} catch (error) {
|
||||
console.error('keep: the rose could not be saved to a file', error);
|
||||
}
|
||||
}
|
||||
|
||||
async function bringBack(event: Event & { currentTarget: HTMLInputElement }): Promise<void> {
|
||||
const input = event.currentTarget;
|
||||
const file = input.files?.[0];
|
||||
if (!file) return;
|
||||
try {
|
||||
const { added } = await wiring.importRose(JSON.parse(await file.text()), currentKey);
|
||||
said = added === 0 ? en.rose.safe.alreadyHere : en.rose.safe.broughtBack(added);
|
||||
onrestored();
|
||||
} catch (error) {
|
||||
// A wrong file is an ordinary thing to choose; the player is told calmly, the console fully.
|
||||
console.warn('keep: the chosen file is not a rose', error);
|
||||
said = en.rose.safe.notARose;
|
||||
} finally {
|
||||
input.value = '';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<section class="safe" aria-labelledby="{uid}-title">
|
||||
<h3 id="{uid}-title">{en.rose.safe.title}</h3>
|
||||
{#if persisted !== undefined}
|
||||
<p>{refused ? en.rose.safe.refused : persisted === true ? en.rose.safe.kept : persisted === false ? en.rose.safe.mayClear : en.rose.safe.unknown}</p>
|
||||
{/if}
|
||||
{#if persisted === false && !refused}
|
||||
<button type="button" class="quiet" onclick={ask}>{en.rose.safe.ask}</button>
|
||||
{/if}
|
||||
{#if wiring.installHint}
|
||||
<p>{en.rose.safe.install}</p>
|
||||
{/if}
|
||||
|
||||
<button type="button" onclick={save}>{en.rose.safe.save}</button>
|
||||
<p class="note">{en.rose.safe.fileNote}</p>
|
||||
|
||||
<label class="file">
|
||||
<span>{en.rose.safe.bringBack}</span>
|
||||
<input type="file" accept="application/json,.json" onchange={bringBack} />
|
||||
</label>
|
||||
<p class="said" role="status">{said}</p>
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.safe {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
justify-items: center;
|
||||
max-width: 24rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-family: var(--font-display);
|
||||
font-weight: 400;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.note,
|
||||
.said {
|
||||
color: var(--ink-soft);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.said:empty {
|
||||
display: none;
|
||||
}
|
||||
|
||||
button,
|
||||
.file {
|
||||
font: inherit;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--rose);
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.quiet {
|
||||
border: none;
|
||||
padding: var(--space-1) 0;
|
||||
color: var(--rose);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.file {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* The real input stays operable and labelled; only its default look is hidden. */
|
||||
.file input {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
opacity: 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.file:focus-within,
|
||||
button:focus-visible {
|
||||
outline: 2px solid var(--rose);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,303 @@
|
||||
<script lang="ts">
|
||||
import { careEvent, localDay, pour, roseAt, ROSE, type Mood, type RoseNow, type Stage } from '@rosea/engine';
|
||||
import type { CareEvent } from '@rosea/schema';
|
||||
import { en } from '../copy/en.js';
|
||||
import KeepSafe from './KeepSafe.svelte';
|
||||
import type { RoseWiring } from './types.js';
|
||||
// The art board's stand-ins until real art is accepted (rose.md R10, docs/ART.md).
|
||||
import bud from '../../../../art/placeholders/rose-bud.svg?url';
|
||||
import opening from '../../../../art/placeholders/rose-opening.svg?url';
|
||||
import halfBloom from '../../../../art/placeholders/rose-half-bloom.svg?url';
|
||||
import fullBloom from '../../../../art/placeholders/rose-full-bloom.svg?url';
|
||||
import thirsty from '../../../../art/placeholders/rose-thirsty.svg?url';
|
||||
import overwatered from '../../../../art/placeholders/rose-overwatered.svg?url';
|
||||
import windblown from '../../../../art/placeholders/rose-windblown.svg?url';
|
||||
import blushing from '../../../../art/placeholders/rose-blushing.svg?url';
|
||||
import waiting from '../../../../art/placeholders/rose-waiting.svg?url';
|
||||
|
||||
/**
|
||||
* The rose. Everything she is comes from the engine's replay of her care log
|
||||
* (rose.md); this renders it and turns the player's hands into care events.
|
||||
*/
|
||||
let { wiring, timeZone }: { wiring: RoseWiring; timeZone: string } = $props();
|
||||
|
||||
const STAGE_PICTURE: Record<Stage, string> = { bud, opening, 'half-bloom': halfBloom, 'full-bloom': fullBloom };
|
||||
const MOOD_PICTURE: Record<Mood, string> = { content: fullBloom, thirsty, 'too-full': overwatered, windblown, blushing, waiting };
|
||||
|
||||
let seed = $state<string | null>(null);
|
||||
/** Keys she was named by on another device (keep-her-safe.md K2). */
|
||||
let pastKeys = $state.raw<readonly string[]>([]);
|
||||
let showSafe = $state(false);
|
||||
let events = $state.raw<readonly CareEvent[]>([]);
|
||||
let now = $state(0);
|
||||
let kept = $state(true);
|
||||
let showNumbers = $state(false);
|
||||
|
||||
$effect(() => {
|
||||
const w = wiring;
|
||||
now = w.now();
|
||||
Promise.all([w.identity(), w.loadCare(), w.pastKeys()]).then(
|
||||
([id, log, past]) => {
|
||||
seed = id.publicKey;
|
||||
events = log;
|
||||
pastKeys = past;
|
||||
if (!id.kept) kept = false;
|
||||
},
|
||||
(error: unknown) => {
|
||||
console.error('rose: could not read her care log', error);
|
||||
kept = false;
|
||||
}
|
||||
);
|
||||
// Wind comes and goes, and a blush fades: look again now and then.
|
||||
const timer = setInterval(() => (now = w.now()), 30_000);
|
||||
return () => clearInterval(timer);
|
||||
});
|
||||
|
||||
const rose = $derived<RoseNow | null>(seed === null ? null : roseAt(events, [seed, ...pastKeys], now, timeZone));
|
||||
|
||||
/** After she is brought back from a file: read her log and keys again. */
|
||||
function restored(): void {
|
||||
Promise.all([wiring.loadCare(), wiring.pastKeys()]).then(
|
||||
([log, past]) => {
|
||||
events = log;
|
||||
pastKeys = past;
|
||||
now = wiring.now();
|
||||
},
|
||||
(error: unknown) => console.error('rose: could not read her back after restoring', error)
|
||||
);
|
||||
}
|
||||
|
||||
function care(act: CareEvent['act'], amount?: number): void {
|
||||
if (seed === null) return;
|
||||
now = wiring.now();
|
||||
const event = careEvent({ now, timeZone, from: seed, to: seed, act, clientVersion: wiring.clientVersion, ...(amount === undefined ? {} : { amount }) });
|
||||
events = [...events, event];
|
||||
wiring.appendCare(event).catch((error: unknown) => {
|
||||
console.error('rose: the device could not keep this care', error);
|
||||
kept = false;
|
||||
});
|
||||
}
|
||||
|
||||
// --- Water by feel: hold to pour (GAMEPLAY §1) ---------------------------
|
||||
/** A full can in this long, held. */
|
||||
const FULL_CAN_MS = 3000;
|
||||
const TICK_MS = 50;
|
||||
let amount = $state(0);
|
||||
let pouring = $state(false);
|
||||
let pourTimer: ReturnType<typeof setInterval> | undefined;
|
||||
const can = $derived(rose ? pour(rose.water, amount) : null);
|
||||
|
||||
function startPour(): void {
|
||||
if (pouring || rose === null) return;
|
||||
pouring = true;
|
||||
amount = 0;
|
||||
pourTimer = setInterval(() => (amount = Math.min(1, amount + TICK_MS / FULL_CAN_MS)), TICK_MS);
|
||||
}
|
||||
function stopPour(): void {
|
||||
if (!pouring) return;
|
||||
clearInterval(pourTimer);
|
||||
pouring = false;
|
||||
if (amount > 0.01) care('water', amount);
|
||||
amount = 0;
|
||||
}
|
||||
$effect(() => () => clearInterval(pourTimer));
|
||||
|
||||
const isPourKey = (e: KeyboardEvent): boolean => e.key === ' ' || e.key === 'Enter';
|
||||
|
||||
// --- What she says: one line, or nothing --------------------------------
|
||||
const says = $derived.by(() => {
|
||||
if (!rose) return '';
|
||||
const s = en.rose.says;
|
||||
if (rose.mood === 'blushing') return s.thanks;
|
||||
if (rose.mood === 'too-full') return s.tooFull;
|
||||
const need = rose.needs.wind ? s.wind
|
||||
: rose.water < ROSE.thirsty ? s.thirsty
|
||||
: rose.needs.water ? s.dry
|
||||
: rose.needs.weeds ? s.weeds
|
||||
: rose.needs.petals ? s.petals
|
||||
: '';
|
||||
return [rose.drift > 0 ? s.back : '', need].filter(Boolean).join(' ');
|
||||
});
|
||||
|
||||
const picture = $derived(rose ? (rose.stage === 'full-bloom' ? MOOD_PICTURE[rose.mood] : STAGE_PICTURE[rose.stage]) : bud);
|
||||
const alt = $derived(rose ? en.rose.picture(en.rose.stageWords[rose.stage], en.rose.moodWords[rose.mood]) : '');
|
||||
const percent = (x: number): string => `${Math.round(Math.max(0, Math.min(1, x)) * 100)} %`;
|
||||
</script>
|
||||
|
||||
{#if rose}
|
||||
<section class="rose">
|
||||
<figure>
|
||||
<img src={picture} {alt} width="120" height="320" class:turned={rose.drift > 0} />
|
||||
{#if says}
|
||||
<figcaption class="bubble" aria-live="polite">{says}</figcaption>
|
||||
{/if}
|
||||
</figure>
|
||||
|
||||
<div class="care" role="group" aria-label={en.rose.care}>
|
||||
<button
|
||||
type="button"
|
||||
class="water"
|
||||
class:pouring
|
||||
aria-describedby="rose-water-hint"
|
||||
onpointerdown={(e) => {
|
||||
e.preventDefault();
|
||||
(e.currentTarget as HTMLElement).setPointerCapture?.(e.pointerId);
|
||||
startPour();
|
||||
}}
|
||||
onpointerup={stopPour}
|
||||
onpointercancel={stopPour}
|
||||
onkeydown={(e) => {
|
||||
if (!isPourKey(e)) return;
|
||||
e.preventDefault();
|
||||
if (!e.repeat) startPour();
|
||||
}}
|
||||
onkeyup={(e) => {
|
||||
if (isPourKey(e)) stopPour();
|
||||
}}
|
||||
onblur={stopPour}
|
||||
>{en.rose.water}</button>
|
||||
{#if rose.needs.wind}
|
||||
<button type="button" onclick={() => care('shade')}>{en.rose.shade}</button>
|
||||
{/if}
|
||||
{#if rose.needs.weeds}
|
||||
<button type="button" onclick={() => care('weed')}>{en.rose.weed}</button>
|
||||
{/if}
|
||||
{#if rose.needs.petals}
|
||||
<button type="button" onclick={() => care('petals')}>{en.rose.petals}</button>
|
||||
{/if}
|
||||
</div>
|
||||
<p id="rose-water-hint" class="hint">{en.rose.waterHint}</p>
|
||||
|
||||
{#if pouring && can}
|
||||
<div class="can">
|
||||
<meter min="0" max="1.2" low={ROSE.enough} high={ROSE.tooFull} optimum="0.7" value={Math.min(1.2, can.after)} aria-label={en.rose.waterLevel}></meter>
|
||||
</div>
|
||||
{/if}
|
||||
<p class="said" role="status" aria-live="assertive">{pouring && can ? (can.tooFull ? en.rose.plenty : can.leavesLift ? en.rose.leavesLift : '') : ''}</p>
|
||||
|
||||
{#if !kept}
|
||||
<p class="hint">{en.rose.notKept}</p>
|
||||
{/if}
|
||||
|
||||
<div class="more">
|
||||
<button type="button" class="quiet" aria-expanded={showNumbers} aria-controls="rose-numbers" onclick={() => (showNumbers = !showNumbers)}>{en.rose.numbers}</button>
|
||||
<button type="button" class="quiet" aria-expanded={showSafe} onclick={() => (showSafe = !showSafe)}>{en.rose.safe.title}</button>
|
||||
</div>
|
||||
{#if showNumbers}
|
||||
<dl id="rose-numbers" class="numbers">
|
||||
<dt>{en.rose.waterLevel}</dt><dd>{percent(rose.water)}</dd>
|
||||
<dt>{en.rose.daysOfCare}</dt><dd>{rose.daysOfCare}</dd>
|
||||
<dt>{en.rose.warmth}</dt><dd>{en.rose.warmthDays(rose.warmth)}</dd>
|
||||
<dt>{en.rose.trend}</dt><dd>{en.rose.trendWords[rose.trend]}</dd>
|
||||
</dl>
|
||||
{/if}
|
||||
{#if showSafe && seed}
|
||||
<KeepSafe {wiring} currentKey={seed} today={localDay(now, timeZone)} onrestored={restored} />
|
||||
{/if}
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.rose {
|
||||
display: grid;
|
||||
justify-items: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
figure {
|
||||
margin: 0;
|
||||
display: grid;
|
||||
justify-items: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
img {
|
||||
height: 13rem;
|
||||
width: auto;
|
||||
transition: transform 0.6s ease;
|
||||
}
|
||||
|
||||
/* Drift is drawn as waiting: turned a little away, never hurt (CLAUDE.md §8). */
|
||||
img.turned {
|
||||
transform: rotate(-4deg) scaleX(-1);
|
||||
}
|
||||
|
||||
.bubble {
|
||||
max-width: 22rem;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border-radius: 1rem;
|
||||
background: color-mix(in srgb, var(--rose) 12%, var(--paper));
|
||||
}
|
||||
|
||||
.care {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.care button {
|
||||
font: inherit;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--rose);
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
cursor: pointer;
|
||||
touch-action: none;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.care button.pouring {
|
||||
background: color-mix(in srgb, var(--rose) 18%, var(--paper));
|
||||
}
|
||||
|
||||
.hint,
|
||||
.said {
|
||||
margin: 0;
|
||||
color: var(--ink-soft);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.said:empty {
|
||||
display: none;
|
||||
}
|
||||
|
||||
meter {
|
||||
width: 12rem;
|
||||
}
|
||||
|
||||
.quiet {
|
||||
font: inherit;
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--rose);
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.more {
|
||||
display: flex;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.numbers {
|
||||
display: grid;
|
||||
grid-template-columns: auto auto;
|
||||
gap: var(--space-1) var(--space-3);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
dt {
|
||||
color: var(--ink-soft);
|
||||
}
|
||||
|
||||
dd {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
button:focus-visible {
|
||||
outline: 2px solid var(--rose);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { CareEvent } from '@rosea/schema';
|
||||
|
||||
/**
|
||||
* What the rose needs from the app: her care log, her key, and the clock. The app
|
||||
* provides it; ui imports neither storage nor identity (CLAUDE.md §2).
|
||||
*/
|
||||
export interface RoseWiring {
|
||||
/** The player's public key, which names the rose. `kept` is false if the device could not keep it. */
|
||||
readonly identity: () => Promise<{ readonly publicKey: string; readonly kept: boolean }>;
|
||||
readonly loadCare: () => Promise<CareEvent[]>;
|
||||
readonly appendCare: (event: CareEvent) => Promise<void>;
|
||||
readonly clientVersion: string;
|
||||
/** The device's own zone: the rose's day when no sunset town is chosen (rose.md R8). */
|
||||
readonly deviceZone: string;
|
||||
/** The clock. A parameter, so tests and the e2e suite can fix it. */
|
||||
readonly now: () => number;
|
||||
/** Keys the rose was named by before, on another device (keep-her-safe.md K2). */
|
||||
readonly pastKeys: () => Promise<string[]>;
|
||||
/** The rose as a file's contents, and bringing one back. */
|
||||
readonly exportRose: (currentKey: string) => Promise<unknown>;
|
||||
readonly importRose: (file: unknown, currentKey: string) => Promise<{ readonly added: number }>;
|
||||
/** Hands the player a file to keep. */
|
||||
readonly saveFile: (name: string, text: string) => void;
|
||||
/** The browser's promise to keep the garden: true, false, or null when it cannot say. */
|
||||
readonly keeping: {
|
||||
readonly persisted: () => Promise<boolean | null>;
|
||||
readonly persist: () => Promise<boolean | null>;
|
||||
};
|
||||
/** True on an iPhone or iPad not yet added to the Home Screen, where Safari may clear her. */
|
||||
readonly installHint: boolean;
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,228 @@
|
||||
import { careEvent, localDay, weedsOn } from '@rosea/engine';
|
||||
import type { CareEvent } from '@rosea/schema';
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/svelte';
|
||||
import { tick } from 'svelte';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { en } from '../src/copy/en.js';
|
||||
import Rose from '../src/rose/Rose.svelte';
|
||||
import type { RoseWiring } from '../src/rose/types.js';
|
||||
|
||||
const ZONE = 'Europe/Prague';
|
||||
const ME = 'M'.repeat(87);
|
||||
/** 08:00 in Prague: before any wind can start, so the wind button never surprises a test. */
|
||||
const MORNING = Date.parse('2026-03-01T08:00:00+01:00');
|
||||
const DAY = 86_400_000;
|
||||
|
||||
function wiring(over: Partial<RoseWiring> & { log?: CareEvent[]; at?: number } = {}): RoseWiring & { appended: CareEvent[]; saved: { name: string; text: string }[] } {
|
||||
const appended: CareEvent[] = [];
|
||||
const saved: { name: string; text: string }[] = [];
|
||||
const at = over.at ?? MORNING;
|
||||
return {
|
||||
identity: async () => ({ publicKey: ME, kept: true }),
|
||||
loadCare: async () => over.log ?? [],
|
||||
appendCare: async (e) => {
|
||||
appended.push(e);
|
||||
},
|
||||
clientVersion: '0.1.0',
|
||||
deviceZone: ZONE,
|
||||
now: () => at,
|
||||
pastKeys: async () => [],
|
||||
exportRose: async (key) => ({ format: 'rosea-rose', version: 1, keys: [key], events: [...(over.log ?? []), ...appended] }),
|
||||
importRose: async () => ({ added: 0 }),
|
||||
saveFile: (name, text) => {
|
||||
saved.push({ name, text });
|
||||
},
|
||||
keeping: { persisted: async () => false, persist: async () => true },
|
||||
installHint: false,
|
||||
...over,
|
||||
appended,
|
||||
saved
|
||||
};
|
||||
}
|
||||
const water = (now: number, amount: number): CareEvent => careEvent({ now, timeZone: ZONE, from: ME, to: ME, act: 'water', amount, clientVersion: '0.1.0' });
|
||||
|
||||
/** Holds the Water button for `ms`, with the pour's own timer under control. */
|
||||
async function hold(ms: number, how: 'pointer' | 'keyboard' = 'pointer'): Promise<void> {
|
||||
const button = screen.getByRole('button', { name: en.rose.water });
|
||||
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
|
||||
try {
|
||||
if (how === 'pointer') await fireEvent.pointerDown(button, { pointerId: 1 });
|
||||
else await fireEvent.keyDown(button, { key: ' ' });
|
||||
vi.advanceTimersByTime(ms);
|
||||
await tick();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
}
|
||||
const release = async (how: 'pointer' | 'keyboard' = 'pointer'): Promise<void> => {
|
||||
const button = screen.getByRole('button', { name: en.rose.water });
|
||||
if (how === 'pointer') await fireEvent.pointerUp(button, { pointerId: 1 });
|
||||
else await fireEvent.keyUp(button, { key: ' ' });
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('the rose', () => {
|
||||
it('a new rose is a bud whose soil is getting dry, and says so', async () => {
|
||||
render(Rose, { wiring: wiring(), timeZone: ZONE });
|
||||
expect(await screen.findByRole('img', { name: 'The rose, a bud.' })).toBeTruthy();
|
||||
expect(screen.getByText(en.rose.says.dry)).toBeTruthy();
|
||||
});
|
||||
|
||||
it('hold Water: the leaves lift while pouring; let go and it is one act of care, and she thanks you', async () => {
|
||||
const w = wiring();
|
||||
render(Rose, { wiring: w, timeZone: ZONE });
|
||||
await screen.findByRole('img');
|
||||
await hold(1500); // half a can
|
||||
expect(screen.getByRole('status').textContent).toBe(en.rose.leavesLift);
|
||||
await release();
|
||||
expect(w.appended).toHaveLength(1);
|
||||
expect(w.appended[0]).toMatchObject({ act: 'water', amount: 0.5, localDay: '2026-03-01', from: ME, to: ME });
|
||||
expect(await screen.findByText(en.rose.says.thanks)).toBeTruthy();
|
||||
|
||||
await fireEvent.click(screen.getByRole('button', { name: en.rose.numbers }));
|
||||
const numbers = document.getElementById('rose-numbers');
|
||||
expect(numbers?.textContent).toContain(`${en.rose.daysOfCare}1`);
|
||||
expect(numbers?.textContent).toContain(en.rose.warmthDays(1));
|
||||
});
|
||||
|
||||
it('pouring too long says that is plenty', async () => {
|
||||
render(Rose, { wiring: wiring({ log: [water(MORNING - 60_000, 0.5)] }), timeZone: ZONE });
|
||||
await screen.findByRole('img');
|
||||
await hold(3000);
|
||||
expect(screen.getByRole('status').textContent).toBe(en.rose.plenty);
|
||||
});
|
||||
|
||||
it('pours with the keyboard too: hold Space, let go', async () => {
|
||||
const w = wiring();
|
||||
render(Rose, { wiring: w, timeZone: ZONE });
|
||||
await screen.findByRole('img');
|
||||
await hold(1200, 'keyboard');
|
||||
await release('keyboard');
|
||||
expect(w.appended[0]).toMatchObject({ act: 'water', amount: 0.4 });
|
||||
});
|
||||
|
||||
it('Pull the weeds shows only on a day with weeds, and goes once they are pulled', async () => {
|
||||
let day = MORNING;
|
||||
while (!weedsOn(ME, localDay(day, ZONE))) day += DAY;
|
||||
const w = wiring({ at: day });
|
||||
render(Rose, { wiring: w, timeZone: ZONE });
|
||||
await fireEvent.click(await screen.findByRole('button', { name: en.rose.weed }));
|
||||
expect(w.appended[0]?.act).toBe('weed');
|
||||
await waitFor(() => expect(screen.queryByRole('button', { name: en.rose.weed })).toBeNull());
|
||||
|
||||
let clear = MORNING;
|
||||
while (weedsOn(ME, localDay(clear, ZONE))) clear += DAY;
|
||||
cleanup();
|
||||
render(Rose, { wiring: wiring({ at: clear }), timeZone: ZONE });
|
||||
await screen.findByRole('img');
|
||||
expect(screen.queryByRole('button', { name: en.rose.weed })).toBeNull();
|
||||
});
|
||||
|
||||
it('after weeks away she is turned a little away and waiting, and greets, never blames', async () => {
|
||||
const log = [water(MORNING - 30 * DAY, 0.5)];
|
||||
render(Rose, { wiring: wiring({ log }), timeZone: ZONE });
|
||||
const img = await screen.findByRole('img', { name: /waiting/ });
|
||||
expect(img.className).toContain('turned');
|
||||
expect(screen.getByText(new RegExp(`^${en.rose.says.back}`))).toBeTruthy();
|
||||
await fireEvent.click(screen.getByRole('button', { name: en.rose.numbers }));
|
||||
expect(document.getElementById('rose-numbers')?.textContent).toContain(en.rose.warmthDays(0));
|
||||
expect(document.getElementById('rose-numbers')?.textContent).toContain(`${en.rose.daysOfCare}1`);
|
||||
});
|
||||
|
||||
it('if the device cannot keep the care, the care still counts now, and she says it lasts only until closing', async () => {
|
||||
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
const w = wiring({ appendCare: () => Promise.reject(new Error('IndexedDB blocked')) });
|
||||
render(Rose, { wiring: w, timeZone: ZONE });
|
||||
await screen.findByRole('img');
|
||||
await hold(1500);
|
||||
await release();
|
||||
expect(await screen.findByText(en.rose.says.thanks)).toBeTruthy();
|
||||
expect(await screen.findByText(en.rose.notKept)).toBeTruthy();
|
||||
expect(error).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// jsdom's File has no text(); every browser the app runs in does. Read it as a browser would.
|
||||
if (typeof File.prototype.text !== 'function') {
|
||||
File.prototype.text = function (this: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(String(reader.result));
|
||||
reader.onerror = () => reject(reader.error);
|
||||
reader.readAsText(this);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
describe('keep her safe (keep-her-safe.md)', () => {
|
||||
const OLD = 'O'.repeat(87);
|
||||
const open = async (): Promise<void> => {
|
||||
await screen.findByRole('img');
|
||||
await fireEvent.click(screen.getByRole('button', { name: en.rose.safe.title }));
|
||||
};
|
||||
|
||||
it('says the browser may clear her, asks it to keep her on request, and says when it promised', async () => {
|
||||
render(Rose, { wiring: wiring(), timeZone: ZONE });
|
||||
await open();
|
||||
expect(await screen.findByText(en.rose.safe.mayClear)).toBeTruthy();
|
||||
await fireEvent.click(screen.getByRole('button', { name: en.rose.safe.ask }));
|
||||
expect(await screen.findByText(en.rose.safe.kept)).toBeTruthy();
|
||||
expect(screen.queryByRole('button', { name: en.rose.safe.ask })).toBeNull();
|
||||
});
|
||||
|
||||
it('a browser that will not promise is told calmly, and the file is offered', async () => {
|
||||
render(Rose, { wiring: wiring({ keeping: { persisted: async () => false, persist: async () => false } }), timeZone: ZONE });
|
||||
await open();
|
||||
await fireEvent.click(await screen.findByRole('button', { name: en.rose.safe.ask }));
|
||||
expect(await screen.findByText(en.rose.safe.refused)).toBeTruthy();
|
||||
});
|
||||
|
||||
it('saves her as a dated file holding her care, and says the file never holds the town', async () => {
|
||||
const log = [water(MORNING - 60_000, 0.5)];
|
||||
const w = wiring({ log });
|
||||
render(Rose, { wiring: w, timeZone: ZONE });
|
||||
await open();
|
||||
expect(screen.getByText(en.rose.safe.fileNote)).toBeTruthy();
|
||||
await fireEvent.click(screen.getByRole('button', { name: en.rose.safe.save }));
|
||||
await waitFor(() => expect(w.saved).toHaveLength(1));
|
||||
expect(w.saved[0]?.name).toBe('rose-2026-03-01.json');
|
||||
expect(JSON.parse(w.saved[0]?.text ?? '{}')).toMatchObject({ keys: [ME], events: log });
|
||||
});
|
||||
|
||||
it('bringing her back from a file restores her days of care under her old key', async () => {
|
||||
const old = [{ ...water(MORNING - 2 * DAY, 0.5), from: OLD, to: OLD }];
|
||||
let restored = false;
|
||||
const w = wiring({
|
||||
loadCare: async () => (restored ? old : []),
|
||||
pastKeys: async () => (restored ? [OLD] : []),
|
||||
importRose: async (file) => {
|
||||
expect(file).toMatchObject({ keys: [OLD] });
|
||||
restored = true;
|
||||
return { added: 1 };
|
||||
}
|
||||
});
|
||||
render(Rose, { wiring: w, timeZone: ZONE });
|
||||
await open();
|
||||
const input = screen.getByLabelText(en.rose.safe.bringBack) as HTMLInputElement;
|
||||
const file = new File([JSON.stringify({ format: 'rosea-rose', version: 1, keys: [OLD], events: old })], 'rose.json', { type: 'application/json' });
|
||||
await fireEvent.change(input, { target: { files: [file] } });
|
||||
expect(await screen.findByText(en.rose.safe.broughtBack(1))).toBeTruthy();
|
||||
await fireEvent.click(screen.getByRole('button', { name: en.rose.numbers }));
|
||||
await waitFor(() => expect(document.getElementById('rose-numbers')?.textContent).toContain(`${en.rose.daysOfCare}1`));
|
||||
});
|
||||
|
||||
it('a file that is not a rose is said calmly, and nothing changes', async () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
|
||||
render(Rose, { wiring: wiring({ importRose: () => Promise.reject(new TypeError('storage: this file does not hold a rose')) }), timeZone: ZONE });
|
||||
await open();
|
||||
const input = screen.getByLabelText(en.rose.safe.bringBack);
|
||||
await fireEvent.change(input, { target: { files: [new File(['not json'], 'x.json')] } });
|
||||
expect(await screen.findByText(en.rose.safe.notARose)).toBeTruthy();
|
||||
expect(warn).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -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
|
||||
});
|
||||
});
|
||||
@@ -20,6 +20,9 @@ importers:
|
||||
'@rosea/content':
|
||||
specifier: workspace:*
|
||||
version: link:packages/content
|
||||
'@rosea/engine':
|
||||
specifier: workspace:*
|
||||
version: link:packages/engine
|
||||
'@rosea/schema':
|
||||
specifier: workspace:*
|
||||
version: link:packages/schema
|
||||
@@ -62,9 +65,18 @@ importers:
|
||||
|
||||
apps/rosea:
|
||||
dependencies:
|
||||
'@rosea/content':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/content
|
||||
'@rosea/identity':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/identity
|
||||
'@rosea/schema':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/schema
|
||||
'@rosea/storage':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/storage
|
||||
'@rosea/ui':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/ui
|
||||
@@ -120,6 +132,15 @@ importers:
|
||||
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/identity:
|
||||
devDependencies:
|
||||
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/schema:
|
||||
dependencies:
|
||||
ajv:
|
||||
@@ -136,8 +157,36 @@ importers:
|
||||
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/storage:
|
||||
dependencies:
|
||||
'@rosea/engine':
|
||||
specifier: workspace:*
|
||||
version: link:../engine
|
||||
'@rosea/identity':
|
||||
specifier: workspace:*
|
||||
version: link:../identity
|
||||
'@rosea/schema':
|
||||
specifier: workspace:*
|
||||
version: link:../schema
|
||||
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:
|
||||
dependencies:
|
||||
'@rosea/engine':
|
||||
specifier: workspace:*
|
||||
version: link:../engine
|
||||
'@rosea/schema':
|
||||
specifier: workspace:*
|
||||
version: link:../schema
|
||||
@@ -1924,6 +1973,9 @@ packages:
|
||||
devalue@5.9.4:
|
||||
resolution: {integrity: sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==}
|
||||
|
||||
dexie@4.4.6:
|
||||
resolution: {integrity: sha512-hJP/BO6mjB+tX6hToIO1kmxYLNmun90wYbfcoAoLpKEyDYal/k33dg0TAfoUe2TDsbbLoVIzljJ3BN2UbR5EOg==}
|
||||
|
||||
dom-accessibility-api@0.5.16:
|
||||
resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==}
|
||||
|
||||
@@ -2074,6 +2126,10 @@ packages:
|
||||
resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}
|
||||
engines: {node: '>=12.0.0'}
|
||||
|
||||
fake-indexeddb@6.2.5:
|
||||
resolution: {integrity: sha512-CGnyrvbhPlWYMngksqrSSUT1BAVP49dZocrHuK0SvtR0D5TMs5wP0o3j7jexDJW01KSadjBp1M/71o/KR3nD1w==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
fast-check@3.23.2:
|
||||
resolution: {integrity: sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A==}
|
||||
engines: {node: '>=8.0.0'}
|
||||
@@ -4990,6 +5046,8 @@ snapshots:
|
||||
|
||||
devalue@5.9.4: {}
|
||||
|
||||
dexie@4.4.6: {}
|
||||
|
||||
dom-accessibility-api@0.5.16: {}
|
||||
|
||||
dunder-proto@1.0.1:
|
||||
@@ -5262,6 +5320,8 @@ snapshots:
|
||||
|
||||
expect-type@1.4.0: {}
|
||||
|
||||
fake-indexeddb@6.2.5: {}
|
||||
|
||||
fast-check@3.23.2:
|
||||
dependencies:
|
||||
pure-rand: 6.1.0
|
||||
|
||||
@@ -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}`);
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Records the sun's published times for the golden tests (CLAUDE.md §5.5) into
|
||||
* packages/engine/test/fixtures/sun-usno.json. Run by hand, never by a test: the
|
||||
* tests read the recorded file and make no network call.
|
||||
*
|
||||
* tsx scripts/fetch-sun-golden.ts
|
||||
*
|
||||
* Source: the U.S. Naval Observatory's Astronomical Applications API (one day of
|
||||
* rise, upper transit and set for a point). Each row asks for the clock offset the
|
||||
* place keeps on that date after any DST change, so the table is the local clock a
|
||||
* person there reads. The cities and coordinates are public places, never a player.
|
||||
*/
|
||||
import { writeFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
interface City {
|
||||
readonly name: string;
|
||||
readonly lat: number;
|
||||
readonly lon: number;
|
||||
readonly timeZone: string;
|
||||
/** [local day, the UTC offset in hours the clocks show that day after any change, why this day]. */
|
||||
readonly days: readonly (readonly [string, number, string])[];
|
||||
}
|
||||
|
||||
const CITIES: readonly City[] = [
|
||||
{ name: 'Prague', lat: 50.0755, lon: 14.4378, timeZone: 'Europe/Prague', days: [
|
||||
['2026-03-28', 1, 'the day before DST starts'], ['2026-03-29', 2, 'DST starts'],
|
||||
['2026-06-21', 2, 'midsummer'], ['2026-10-24', 2, 'the day before DST ends'],
|
||||
['2026-10-25', 1, 'DST ends'], ['2026-12-21', 1, 'midwinter']] },
|
||||
{ name: 'Reykjavík', lat: 64.1466, lon: -21.9426, timeZone: 'Atlantic/Reykjavik', days: [
|
||||
['2026-03-20', 0, 'equinox'], ['2026-06-21', 0, 'midsummer: a sunset near midnight'], ['2026-12-21', 0, 'midwinter: four hours of day']] },
|
||||
{ name: 'Tromsø', lat: 69.6492, lon: 18.9553, timeZone: 'Europe/Oslo', days: [
|
||||
['2026-03-29', 2, 'DST starts'], ['2026-06-21', 2, 'polar day'],
|
||||
['2026-10-25', 1, 'DST ends'], ['2026-12-21', 1, 'polar night']] },
|
||||
{ name: 'Quito', lat: -0.1807, lon: -78.4678, timeZone: 'America/Guayaquil', days: [
|
||||
['2026-03-20', -5, 'equinox on the equator'], ['2026-06-21', -5, 'June solstice'], ['2026-12-21', -5, 'December solstice']] },
|
||||
{ name: 'Sydney', lat: -33.8688, lon: 151.2093, timeZone: 'Australia/Sydney', days: [
|
||||
['2026-04-04', 11, 'the day before DST ends'], ['2026-04-05', 10, 'DST ends'],
|
||||
['2026-06-21', 10, 'midwinter'], ['2026-10-03', 10, 'the day before DST starts'],
|
||||
['2026-10-04', 11, 'DST starts'], ['2026-12-21', 11, 'midsummer']] },
|
||||
{ name: 'Anchorage', lat: 61.2181, lon: -149.9003, timeZone: 'America/Anchorage', days: [
|
||||
['2026-03-07', -9, 'the day before DST starts'], ['2026-03-08', -8, 'DST starts'],
|
||||
['2026-06-21', -8, 'midsummer'], ['2026-10-31', -8, 'the day before DST ends'],
|
||||
['2026-11-01', -9, 'DST ends'], ['2026-12-21', -9, 'midwinter']] }
|
||||
];
|
||||
|
||||
const API = 'https://aa.usno.navy.mil/api/rstt/oneday';
|
||||
|
||||
interface Phenomenon { readonly phen: string; readonly time: string }
|
||||
|
||||
async function oneDay(c: City, day: string, tz: number): Promise<Record<string, string | null>> {
|
||||
const url = `${API}?date=${day}&coords=${c.lat},${c.lon}&tz=${tz}&dst=false`;
|
||||
const res = await fetch(url);
|
||||
if (!res.ok) throw new Error(`${url}: HTTP ${res.status}`);
|
||||
const body = (await res.json()) as { properties: { data: { sundata: Phenomenon[] } } };
|
||||
const at = (phen: string): string | null => body.properties.data.sundata.find((p) => p.phen === phen)?.time ?? null;
|
||||
return { rise: at('Rise'), transit: at('Upper Transit'), set: at('Set') };
|
||||
}
|
||||
|
||||
const rows = [];
|
||||
for (const c of CITIES) {
|
||||
for (const [day, tz, why] of c.days) {
|
||||
rows.push({ city: c.name, lat: c.lat, lon: c.lon, timeZone: c.timeZone, day, utcOffset: tz, why, ...(await oneDay(c, day, tz)) });
|
||||
}
|
||||
}
|
||||
|
||||
const out = fileURLToPath(new URL('../packages/engine/test/fixtures/sun-usno.json', import.meta.url));
|
||||
writeFileSync(out, JSON.stringify({
|
||||
source: `${API} (U.S. Naval Observatory, Astronomical Applications). Times are HH:MM on the local clock at utcOffset; null means the event does not happen that day.`,
|
||||
recorded: new Date().toISOString().slice(0, 10),
|
||||
rows
|
||||
}, null, 2) + '\n');
|
||||
console.log(`fetch-sun-golden: ${rows.length} days -> ${out}`);
|
||||
@@ -21,7 +21,7 @@ const C = {
|
||||
coral: '#e9846a',
|
||||
night: '#2e3561',
|
||||
lamp: '#f4d58d',
|
||||
fox: '#b65a35',
|
||||
fox: '#bc4a22',
|
||||
cream: '#f3e3c8',
|
||||
foxLeg: '#5a3a33',
|
||||
strawberry: '#d2554e',
|
||||
|
||||
@@ -20,7 +20,7 @@ describe('STYLE.md', () => {
|
||||
it('§7 has the ten review points, a point split over two lines read as one', () => {
|
||||
const points = reviewPoints(readStyle());
|
||||
expect(points).toHaveLength(10);
|
||||
expect(points[8]).toBe("It reads as one young russet fox with a cream mask and a ringed tail, shy and gentle, and nothing like the book's sandy, long-eared fox.");
|
||||
expect(points[8]).toBe("It reads as one young red-orange fox with a cream mask and a ringed tail, shy and gentle, and nothing like the book's sandy, long-eared fox.");
|
||||
expect(points[3]).toBe('Nothing from the book: no glass dome, screen, tiny planet, desert, child or scarf, and no look of its drawings.');
|
||||
});
|
||||
|
||||
|
||||