[app] Rose: Merge the rose and her care
This commit is contained in:
@@ -8,6 +8,7 @@ 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 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) | **Open, and now urgent**: since 2026-11-02 there is a rose to lose. `packages/storage` exists. |
|
||||
| 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: `identity`, `sync`, `services/lucerna` | Open by design (D1). Each arrives with its first feature. `tools/art-prep` arrived with the art board; `storage` with the sunset place (2026-11-02, the `profile` store only). |
|
||||
| G0.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). |
|
||||
@@ -54,6 +54,8 @@ sentences). Nothing in Phase 1 is visible to the player yet.
|
||||
|:--|:--|:--|
|
||||
| ~~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
|
||||
|
||||
@@ -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` |
|
||||
@@ -12,7 +12,7 @@ and **how to apply it**.
|
||||
| [`art.md`](art.md) | 2 | The image pipeline. |
|
||||
| [`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) | 7 | What makes a test worth having, and how a passing test lies. |
|
||||
| [`testing.md`](testing.md) | 8 | 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. |
|
||||
|
||||
|
||||
@@ -102,3 +102,19 @@ 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.
|
||||
|
||||
@@ -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.
|
||||
@@ -116,7 +116,7 @@ feed of anything.
|
||||
## 2. Repository layout
|
||||
|
||||
Phase 0 scaffolded `schema`, `engine`, `content`, `ui`, `apps/rosea`, `tools/art-prep` and `art/`;
|
||||
Phase 1 added `storage` (the `profile` store). `identity`, `sync` and `services/lucerna` arrive with their first feature, because an
|
||||
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).
|
||||
|
||||
```
|
||||
|
||||
+17
-2
@@ -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: 299 (schema 15, storage 18, content 71,
|
||||
art-prep 56, engine 113, ui 26). E2E: 10. Offline: 1. `lint:copy`: 15 files, 0 problems.
|
||||
- **Gates:** all pass on this machine. Unit tests: 358 (identity 5, schema 16, content 71,
|
||||
storage 45, art-prep 56, engine 132, ui 33). E2E: 12. Offline: 1. `lint:copy`: 18 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
|
||||
@@ -51,6 +51,17 @@ Rewritten at the end of each session (CLAUDE.md §5.1).
|
||||
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).
|
||||
- **Most urgent open gap: G0.11.** There is now a rose to lose, and nothing yet asks the browser to
|
||||
keep it or lets the player export it.
|
||||
|
||||
**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).
|
||||
@@ -69,6 +80,10 @@ The notification decision is made: in-app only on the web (G0.26).
|
||||
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):
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@rosea/content": "workspace:*",
|
||||
"@rosea/identity": "workspace:*",
|
||||
"@rosea/schema": "workspace:*",
|
||||
"@rosea/storage": "workspace:*",
|
||||
"@rosea/ui": "workspace:*"
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
<script lang="ts">
|
||||
import { guessTown } from '@rosea/content/guess';
|
||||
import { openProfile } from '@rosea/storage';
|
||||
import { Shell, type SunsetWiring } from '@rosea/ui';
|
||||
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 profile = openProfile();
|
||||
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.
|
||||
@@ -22,10 +24,38 @@
|
||||
const sunset: SunsetWiring = {
|
||||
guess: guessTown(deviceZone),
|
||||
search: async (query) => (await loadTowns()).searchTowns(query),
|
||||
load: () => profile.loadSunsetPlace(),
|
||||
save: (choice) => profile.saveSunsetPlace(choice),
|
||||
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 };
|
||||
}
|
||||
}
|
||||
|
||||
const rose: RoseWiring = {
|
||||
identity: () => (identity ??= findIdentity()),
|
||||
loadCare: () => storage.loadCare(),
|
||||
appendCare: (event) => storage.appendCare(event),
|
||||
clientVersion: version,
|
||||
deviceZone,
|
||||
now: () => Date.now()
|
||||
};
|
||||
</script>
|
||||
|
||||
<Shell {letter} {sunset} />
|
||||
<Shell {letter} {sunset} {rose} />
|
||||
|
||||
+12
-1
@@ -2,7 +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 { storedTown } from './stored.js';
|
||||
import { storedCare, storedTown } from './stored.js';
|
||||
|
||||
/**
|
||||
* The offline suite. CLAUDE.md §3 describes its full shape: tend the rose, walk
|
||||
@@ -66,6 +66,14 @@ test('the shell opens from the service worker with the server gone', async ({ br
|
||||
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();
|
||||
@@ -74,6 +82,9 @@ test('the shell opens from the service worker with the server gone', async ({ br
|
||||
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`);
|
||||
|
||||
+41
-1
@@ -7,7 +7,7 @@ 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 { storedTown } from './stored.js';
|
||||
import { storedCare, storedTown } from './stored.js';
|
||||
|
||||
let server: StaticServer;
|
||||
|
||||
@@ -182,3 +182,43 @@ test.describe('the sunset place, in Prague\'s time zone at noon on 29 March 2026
|
||||
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([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -34,3 +34,33 @@ export async function storedTown(page: Page, name: string): Promise<void> {
|
||||
{ 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 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,2 +1,6 @@
|
||||
export { addDays, isLocalDay, localDay, type LocalDay } from './time/localDay.js';
|
||||
export { addDays, daysBetween, isLocalDay, localDay, localMinutes, type LocalDay } from './time/localDay.js';
|
||||
export {
|
||||
careEvent, judgeCare, OWN_TRACE, petalsOn, pour, ROSE, roseAt, seeded, stageFor, weedsOn, windOn,
|
||||
type Judged, type Mood, type Needs, 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,231 @@
|
||||
/**
|
||||
* 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 };
|
||||
}
|
||||
|
||||
/** 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 log in order, each act judged. Only care given to this rose counts. */
|
||||
function replay(events: readonly CareEvent[], seed: string, timeZone: string): 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 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(days.size) !== '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 };
|
||||
}
|
||||
|
||||
/** Every act of the log with whether it helped, in order. */
|
||||
export function judgeCare(events: readonly CareEvent[], seed: string, timeZone: string): readonly Judged[] {
|
||||
return replay(events, seed, timeZone).judged;
|
||||
}
|
||||
|
||||
/** The rose at `now`: a pure replay of `events` for the rose whose key is `seed`. */
|
||||
export function roseAt(events: readonly CareEvent[], seed: string, now: number, timeZone: string): RoseNow {
|
||||
const r = replay(events, seed, timeZone);
|
||||
const today = localDay(now, timeZone);
|
||||
const water = fall(r.water.level, r.water.at, now);
|
||||
const stage = stageFor(r.days.size);
|
||||
|
||||
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 = [...r.days].filter((d) => d <= today).sort();
|
||||
const lastDayOfCare = careDays.at(-1) ?? null;
|
||||
const since = daysBetween(lastDayOfCare ?? r.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 = [...r.judged].reverse().find((j) => j.helped && j.event.ts <= now);
|
||||
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: r.days.size, warmth, trend, lastDayOfCare };
|
||||
}
|
||||
@@ -61,6 +61,31 @@ 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`);
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
import fc from 'fast-check';
|
||||
import type { CareEvent } from '@rosea/schema';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { careEvent, judgeCare, 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 });
|
||||
});
|
||||
});
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@rosea/engine": "workspace:*",
|
||||
"@rosea/identity": "workspace:*",
|
||||
"@rosea/schema": "workspace:*",
|
||||
"dexie": "4.4.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
/**
|
||||
* The ONLY module that touches IndexedDB (CLAUDE.md §2). The database `rosea` and its
|
||||
* stores are listed in CLAUDE.md §4; each store arrives with the feature that writes
|
||||
* it. So far: `profile`, written by the sunset-place question
|
||||
* (.agents/features/sunset-place.md).
|
||||
* 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 type { NamedPlace } from '@rosea/engine';
|
||||
import { isIdentity, type Identity } from '@rosea/identity';
|
||||
import { DATABASE_NAME, type CareEvent } from '@rosea/schema';
|
||||
|
||||
export const DATABASE_NAME = 'rosea';
|
||||
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' };
|
||||
@@ -18,18 +23,39 @@ 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';
|
||||
|
||||
export interface Profile {
|
||||
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>;
|
||||
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 {
|
||||
@@ -43,12 +69,45 @@ export function asSunsetPlace(value: unknown): SunsetPlace | 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;
|
||||
}
|
||||
|
||||
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' });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,8 +115,12 @@ class RoseaDatabase extends Dexie {
|
||||
* Opens the player's database. `options` lets a test pass fake-indexeddb; the app
|
||||
* passes nothing and gets the browser's IndexedDB.
|
||||
*/
|
||||
export function openProfile(options?: DexieOptions): Profile {
|
||||
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;
|
||||
};
|
||||
return {
|
||||
async loadSunsetPlace() {
|
||||
const row = await db.profile.get(SUNSET_PLACE);
|
||||
@@ -68,13 +131,38 @@ export function openProfile(options?: DexieOptions): Profile {
|
||||
return place;
|
||||
},
|
||||
async saveSunsetPlace(place) {
|
||||
// Write a fresh plain copy, never the caller's object: a Svelte 5 state Proxy
|
||||
// cannot be structured-cloned, and IndexedDB refuses it (DataCloneError). The
|
||||
// same shape check as on reading, so nothing malformed is ever written.
|
||||
const plain = asSunsetPlace(place);
|
||||
if (plain === null) throw new TypeError('storage: refusing to save a sunset place of an unknown shape');
|
||||
await db.profile.put({ key: SUNSET_PLACE, value: plain });
|
||||
},
|
||||
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));
|
||||
},
|
||||
close() {
|
||||
db.close();
|
||||
}
|
||||
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
@@ -1,16 +1,16 @@
|
||||
import { IDBFactory, IDBKeyRange } from 'fake-indexeddb';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { asSunsetPlace, openProfile, type Profile, type SunsetPlace } from '../src/index.js';
|
||||
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: Profile[] = [];
|
||||
const opened: Storage[] = [];
|
||||
/** A fresh, empty fake database per call unless one is passed: tests never share state. */
|
||||
function open(indexedDB: IDBFactory = new IDBFactory()): Profile {
|
||||
const p = openProfile({ indexedDB, IDBKeyRange });
|
||||
function open(indexedDB: IDBFactory = new IDBFactory()): Storage {
|
||||
const p = openStorage({ indexedDB, IDBKeyRange });
|
||||
opened.push(p);
|
||||
return p;
|
||||
}
|
||||
@@ -83,7 +83,7 @@ describe('the profile store — the sunset place', () => {
|
||||
it('a database that cannot open rejects, so the app can fall back to the session', async () => {
|
||||
const broken = new IDBFactory();
|
||||
broken.open = () => { throw new DOMException('blocked by the browser', 'SecurityError'); };
|
||||
await expect(openProfile({ indexedDB: broken, IDBKeyRange }).loadSunsetPlace()).rejects.toThrow();
|
||||
await expect(openStorage({ indexedDB: broken, IDBKeyRange }).loadSunsetPlace()).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -4,18 +4,23 @@
|
||||
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';
|
||||
|
||||
let {
|
||||
letter = '',
|
||||
sunset
|
||||
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) ---------------------------------------
|
||||
@@ -28,6 +33,8 @@
|
||||
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;
|
||||
@@ -105,6 +112,9 @@
|
||||
<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}
|
||||
|
||||
@@ -10,6 +10,47 @@ 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.'
|
||||
},
|
||||
sunset: {
|
||||
/** ROADMAP Phase 1, word for word. */
|
||||
question: 'Where do you want your sunset?',
|
||||
|
||||
@@ -2,3 +2,4 @@ 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,275 @@
|
||||
<script lang="ts">
|
||||
import { careEvent, 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 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);
|
||||
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()]).then(
|
||||
([id, log]) => {
|
||||
seed = id.publicKey;
|
||||
events = log;
|
||||
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, now, timeZone));
|
||||
|
||||
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}
|
||||
|
||||
<button type="button" class="quiet" aria-expanded={showNumbers} aria-controls="rose-numbers" onclick={() => (showNumbers = !showNumbers)}>{en.rose.numbers}</button>
|
||||
{#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}
|
||||
</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;
|
||||
}
|
||||
|
||||
.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,17 @@
|
||||
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;
|
||||
}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,138 @@
|
||||
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[] } {
|
||||
const appended: CareEvent[] = [];
|
||||
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,
|
||||
...over,
|
||||
appended
|
||||
};
|
||||
}
|
||||
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();
|
||||
});
|
||||
});
|
||||
Generated
+18
@@ -68,6 +68,9 @@ importers:
|
||||
'@rosea/content':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/content
|
||||
'@rosea/identity':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/identity
|
||||
'@rosea/schema':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/schema
|
||||
@@ -129,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:
|
||||
@@ -150,6 +162,12 @@ importers:
|
||||
'@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
|
||||
|
||||
Reference in New Issue
Block a user