diff --git a/.agents/FEATURES.md b/.agents/FEATURES.md index 037f7a0..cf2e974 100644 --- a/.agents/FEATURES.md +++ b/.agents/FEATURES.md @@ -20,4 +20,5 @@ One row per feature, with its analysis document (CLAUDE.md §5.1). Gaps live in | 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) | +| Her planet and the gardener: a round tiny planet, a boy or girl chosen at the first open, the ring of care by a tap on her, care by gesture (tilt the can, swipe weeds up, sweep petals, drag the windbreak, stroke her); every gesture also a button | 1 | Merged to `main`; built, not deployed. Code stand-ins; the painted art waits on the board | [planet-garden.md](features/planet-garden.md) | [feature-planet-garden.md](reviews/feature-planet-garden.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) | diff --git a/.agents/GAP_ANALYSIS.md b/.agents/GAP_ANALYSIS.md index 726d488..dbf137b 100644 --- a/.agents/GAP_ANALYSIS.md +++ b/.agents/GAP_ANALYSIS.md @@ -49,7 +49,7 @@ board exist, and the first real picture is the author's to make. ## Phase 1 — The rose alone **Started 2026-11-01** with the sun, while the Phase 0 gate waits on the author (pictures, -sentences). Nothing in Phase 1 is visible to the player yet. +sentences). Phase 1 is built in code, not deployed (no host yet, G0.13). | Id | Gap | Status / evidence | |:--|:--|:--| @@ -61,6 +61,7 @@ sentences). Nothing in Phase 1 is visible to the player yet. | ~~G1.7~~ | ~~Thorns were on the roadmap but undesigned~~ | Closed 2026-11-02 on `feature/thorns`, as the author chose: thorns teach gentleness. `engine/touch` (2 properties: spaced taps are never a rush; one blush a visit); a tremor is one touch; nothing recorded. 6 of 6 put-back bugs caught. | | ~~G1.8~~ | ~~Two tabs (CLAUDE.md §8, predicted)~~ | Closed 2026-11-07 on `fix/two-tabs`. Measured first: two e2e tests failed (an open tab saw neither care nor a town from the other). Storage announces committed writes on a `BroadcastChannel`; the rose and the garden read again, adding to what they show. No lock needed: nothing stored drifts. 7 of 7 put-back bugs caught. | | ~~G1.10~~ | ~~The garden named only the sunset, never the sunrise (ROADMAP Phase 1: *sunset and sunrise*)~~ | Closed 2026-11-17 on `feature/sunrise`: from sunset until it comes, the line names the real sunrise; the in-game sunset still names the sunset. engine `nextSunEvent` with a 300-run property; e2e at 05:00 in Brno; seen on a real Android tablet. 5 of 5 put-back bugs caught. | +| ~~G1.9~~ | ~~The garden was a page of buttons, not a game (the author, 2026-11-17)~~ | Closed 2026-11-17 on `feature/planet-garden`: her round planet, a gardener the player chooses at the first open (fixed lists, kept in `profile`, never in the rose file), the ring of care by a tap on her, care by gesture with a button for each. 84 ui tests incl. 7 on the planet and 7 on gestures; e2e `planet.spec.ts` 3; 9 of 9 put-back bugs caught (2 only after tests were added); 7 of 7 by real touch on the Android tablet. **Open in it:** painted art for the planet and the gardener, and how customised looks are drawn (STYLE.md §3b, the author's). | | G1.3 | Towns have no Czech names (*Vídeň*) | Open. Natural Earth has none; arrives with Czech copy. | ## The platform track — four versions (from 2026-11-17) @@ -83,6 +84,12 @@ Svelte codebase, the apps through a Tauri 2 shell. Analysis: | G-T8 | Webview storage eviction | Partly measured: `persist()` is `false` in WebView2 and Android WebView. Pressure eviction of app storage not measured. G-T4 is the answer either way. | | G-T9 | The app icon is the placeholder | Open. With G0.21. | +## Phase 6 — Release + +| Id | Gap | Status / evidence | +|:--|:--|:--| +| G6.1 | A legal check of the look: a child on a small round planet with a rose is the book's best-known image, and its estate holds trademarks | Open, **before any public release**. The author accepted the risk on 2026-11-17 (CLAUDE.md §8); the guards are STYLE.md S2, S6, §3b and review points 10–11. | + ## Design questions — answered Raised by GAMEPLAY.md and ROADMAP.md, answered by the author 2026-11-01. Details in diff --git a/.agents/features/planet-garden.md b/.agents/features/planet-garden.md new file mode 100644 index 0000000..d229b94 --- /dev/null +++ b/.agents/features/planet-garden.md @@ -0,0 +1,121 @@ +# The planet garden — a gardener, gestures, and her own small world + +Status: built on `feature/planet-garden`, merged to `main` 2026-11-17; built, not deployed. Decided by the author, Mark, on 2026-11-17, after +seeing the garden as a page of buttons: *"It is a game: create a proper planet, a character who does +the care, animations of how the character does it; tap the rose for actions; swipe in patterns; +pull weeds by tapping them and swiping."* His answers the same day: + +- **Her world:** a **round tiny planet** (reverses STYLE.md S2). +- **The character:** a **human gardener, a boy or a girl, customised at the beginning** (reverses + STYLE.md's *no people*). +- **Gestures:** tap her to choose care; swipe weeds out; pour by tilting; patterns for the rest + (sweep petals, drag the windbreak, stroke her petals). **Buttons stay** for keyboard and screen + readers (CLAUDE.md §7: accessibility is not a phase). + +Review: `feature-planet-garden.md`. + +## 0. The risk the author accepted, and the guards + +A child tending a rose on a small round planet is the most recognisable image of the book whose +text, names and drawings CLAUDE.md §5.6 rule 3 forbids, and whose estate holds trademarks +(GAMEPLAY.md §7). The author was told this in the choice itself and chose it. Recorded here, in +STYLE.md and CLAUDE.md, with these guards, which become review points and avoid lines: + +| Guard | Why | +|:--|:--| +| **The gardener is the player's own**: chosen and customised (boy or girl, skin tone, hair style and colour, clothes colour, a hat or not) | No two players' gardeners need look alike, and none is a fixed character from anywhere. | +| **Never**: a scarf, a long coat or cape, a green suit with epaulettes, a crown, a sword; no outfit option recreates one | The book's boy is drawn with these. | +| **The planet is a cultivated garden world**: meadow, the dry-stone wall, the garden bed, the chair, the wild berry bush; **no volcanoes, no baobab-like trees, no single lamp post** | The book's planet is bare with volcanoes and baobabs. | +| **The look is our gouache** (STYLE.md §1), never pen-and-wash | The book's drawings are pen and watercolour. | +| **No glass dome over her, ever; the windbreak is woven willow** | Unchanged (§4). | +| **A legal check of the look before any public release** (store listings, Pages made public) | New gap; the author's risk, made visible. | + +## 1. Why and what, in the player's terms + +**The first open.** Before the garden, one quiet question: *Who tends her?* The player chooses a +boy or a girl, then skin tone, hair, clothes colour, a hat. A small preview of their gardener turns +as they choose. *This is me* finishes it. It can be changed later, from the garden. + +**The garden is a small round world.** Her planet fills the lower half of the screen, the real sky +above it (code, as now). On its top: the garden bed with the rose, the wall behind, the chair, the +watering can by the bed; the gardener stands beside her. + +**Tap the rose** and the care she needs right now opens around her as a small ring of choices (only +what she needs; *Touch her* is always there). Choose one and the gardener walks over and does it, +with the player's own hand in the gesture: + +| Care | The gesture | The gardener | +|:--|:--|:--| +| **Water** | **Press the can and tilt**: drag sideways from it; the further the tilt, the faster the pour. Let go when her leaves lift (the same *by feel* as now). | Holds the can, tilting it as the player tilts; water falls. | +| **Weeds** | Weeds show in the bed. **Tap a weed, then swipe up** from it: it stretches, then pops out with its roots. | Bends, tugs, the weed comes free, the gardener bumps down on the grass and gets up. | +| **Fallen petals** | **Sweep**: one swipe sideways across the petals gathers them. | Sweeps them into a little pile and pockets them. | +| **Wind** | **Drag the windbreak** from the side of the bed into the wind, on her windward side. | Carries it and sets it in the ground. | +| **Touch her** | **Stroke** slowly across her petals: a fond answer. Quick, rushed taps: *Gently. I have thorns.* (thorns.md) | Reaches out and touches a petal. | + +Every act is the same event as today (rose.md, thorns.md): nothing about growth, drift, the petal or +her numbers changes. The gestures are how the player's hand meets the same rules. + +**Keyboard and screen readers.** The ring's choices are buttons; each one also works without its +gesture: *Water* still pours while Space or Enter is held; *Pull the weeds* pulls them all, one by +one, while the gardener does it; *Gather the petals*, *Shade her*, *Touch her* likewise. The scene +says what happens in one polite line. + +**Reduced motion.** The gardener does not walk or bend: the scene shows the result at once. + +## 2. Technical architecture + +```mermaid +flowchart LR + app["apps/rosea
App.svelte"] --> shell["packages/ui
Shell: first-open choice, then the scene"] + shell --> scene["packages/ui/scene
Planet.svelte (SVG): planet, bed, rose, can,
weeds, petals, windbreak, gardener"] + scene --> gestures["packages/ui/scene/gestures.ts
pure: tilt, swipe up, sweep, drag, stroke"] + scene --> engine["packages/engine
rose (care, pour), touch (thorns),
scene/ weedsToday, petalsToday (seeded counts)"] + shell --> storage["packages/storage
profile: gardener (shape-checked)"] +``` + +| # | Decision | Why | +|:--|:--|:--| +| G1 | **One SVG scene** (`Planet.svelte`), every part its own group with a stand-in drawn in code until art is accepted; the sky stays code (S5). | One coordinate system for gestures, animation and layout; no canvas, so every part can carry an accessible name. | +| G2 | **Gesture recognisers are pure functions** of pointer samples (`gestures.ts`): `tiltOf`, `isSwipeUp`, `isSweep`, `dropTarget`, `strokeOf`. Unit- and property-tested. | Input interpretation is not game logic, but it must be testable without a browser. The rules stay in the engine. | +| G3 | **How many weeds and petals** a day shows is the engine's: `weedsToday(seed, day)` (2–4 when `weedsOn`), `petalsToday(seed, day)` (3–5 when `petalsOn`). One `weed` / `petals` care event when the **last** one is pulled or gathered. | A count on screen is the engine's (CLAUDE.md §6.2). Half-pulled weeds are not care yet: nothing is written until the job is done, and leaving half-way loses nothing earned. | +| G4 | **Pour by tilt** maps tilt to the same pour rate the hold uses (`ROSE.fullPour` over `FULL_CAN_MS`), scaled 0–1.5× by tilt; the event's `amount` is unchanged in meaning. | Watering by feel (rose.md R1) stays one rule. | +| G5 | **The gardener** is a separate component with poses (`stand`, `walk`, `pour`, `bend`, `pull`, `sweep`, `carry`, `reach`, `sit`) and a look from the player's choice. Poses are SVG stand-ins now; real art replaces them sheet by sheet. | Art and animation can arrive later without touching gestures or rules. | +| G6 | **The gardener's look is stored in `profile`** as `{ presentation: 'boy' \| 'girl', skin, hair, hairColour, clothes, hat }`, each from a fixed list; shape-checked like every stored value. Never sent anywhere. | No free text; nothing identifying; local only (CLAUDE.md §4). | +| G7 | **The ring** opens on a tap of the rose; it holds only her current needs plus *Touch her*; Escape or a tap outside closes it; focus moves into it and back. | Silence and calm: no permanent row of buttons over her. | + +## 3. Risk analysis + +| Risk | Answer | +|:--|:--| +| **Likeness to the book** (the author's accepted risk) | §0's guards, as avoid lines in every prompt, review points, and a legal check before release. | +| **Soul: a child avatar for adult players** | The author chose boy or girl. Recorded as a question for his two-week play: does an adult player see themselves in a child gardener? A grown-up option is one list entry away. | +| **Soul: fiddly gestures that make care feel like failing** | Generous thresholds; every gesture has a button; a missed gesture does nothing and says nothing; nothing is lost. | +| **Motion** | `prefers-reduced-motion`: no walking or bending; results at once. | +| **Accessibility** | Buttons for every act (G7); one polite line says what the gardener did; keyboard focus never trapped. | +| Privacy | The gardener's look stays in `profile`, on the device; it is not in the rose file (keep-her-safe.md K4 is unchanged). | +| Offline | Everything is code and bundled stand-ins. | + +## 4. Gap analysis + +- New: **G1.9** the planet garden (this); **G6.x** a legal check of the look before any public release. +- STYLE.md: S2 (where she lives) and *no people* are reversed by the author; §3b *the gardener* is + new; §4 and §7 gain the guards; the manifest gains the planet, the gardener's sheet and pose + sheets, and the customisation parts. +- Not in this feature: the gardener on the journey's other planets (Phase 2), the fox on her planet. + +## 5. Verification matrix + +| Case | Kind | Where | +|:--|:--|:--| +| `tiltOf`: sideways drag → 0–1 tilt; `isSwipeUp` needs upward distance and direction; `isSweep` needs sideways distance across the petals; `strokeOf` tells a slow stroke from a tap | unit + property | `ui/test/gestures.test.ts` | +| `weedsToday` / `petalsToday`: 0 on a day without, 2–4 / 3–5 with, the same on every replay | unit + property | `engine/test/scene.test.ts` | +| Gardener look: every option list is fixed; storage refuses anything else; it never enters the rose file | unit | `storage/test` | +| First open asks *Who tends her?*; the choice is kept; *Change gardener* reopens it | unit | `ui/test/gardener.test.ts` | +| Tap the rose: the ring shows only her needs plus *Touch her*; Escape closes it and focus returns | unit | `ui/test/planet.test.ts` | +| Pulling every weed writes one `weed` event; leaving half-way writes none | unit | same | +| A sweep across the petals writes one `petals` event; dragging the windbreak onto the windward side writes `shade` | unit | same | +| Pour by tilt writes one `water` event whose amount follows the tilt and time | unit | same | +| Buttons do every act without a gesture | unit | same | +| Reduced motion: no animation classes | unit | same | +| Built app: first-open choice, tap the rose, pull weeds by swiping, axe | e2e | `e2e/planet.spec.ts` | +| The real tablet: the same by real touch | device | `scripts/android-smoke.ts` (made permanent here) | diff --git a/.agents/lessons/README.md b/.agents/lessons/README.md index fc17bea..9754858 100644 --- a/.agents/lessons/README.md +++ b/.agents/lessons/README.md @@ -10,9 +10,9 @@ and **how to apply it**. | `architecture.md` | none yet | Layering, ownership, seams. | | [`design.md`](design.md) | 1 | Wording, silence, empty states. | | [`art.md`](art.md) | 3 | The image pipeline. | -| [`code.md`](code.md) | 3 | TypeScript, Svelte, async ordering, Rust. | +| [`code.md`](code.md) | 4 | TypeScript, Svelte, async ordering, Rust. | | [`technical.md`](technical.md) | 9 | The browser and the build as platforms. | -| [`testing.md`](testing.md) | 13 | What makes a test worth having, and how a passing test lies. | +| [`testing.md`](testing.md) | 15 | 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) | 4 | Workflow, commits, credentials, honesty about what shipped. | diff --git a/.agents/lessons/code.md b/.agents/lessons/code.md index 4040a83..d6782e0 100644 --- a/.agents/lessons/code.md +++ b/.agents/lessons/code.md @@ -50,3 +50,16 @@ hands out Proxies wherever state is deep. **How to apply it.** At every storage or messaging boundary, write a plain copy built field by field (in `@rosea/storage`, the same shape check used on reading). Keep lists that are only passed along as `$state.raw`. Test the boundary with `new Proxy(value, {})`. + +## `svelte/motion` reads `matchMedia` when it is imported + +**What happened.** On 2026-11-17 the gardener's walk used `Tween` from `svelte/motion`. Every UI +test file failed at import: jsdom has no `window.matchMedia`, and the module reads it at load (for +its reduced-motion store), not when a tween runs. + +**Why it bit.** An import with side effects breaks every file that imports it, even transitively, +and the error points at the module, not at the component that needed it. + +**How to apply it.** In `packages/ui`, animate with a small `setInterval` easing inside an +`$effect` (`packages/ui/src/scene/Planet.svelte`), reading reduced motion once through a guarded +`matchMedia` call. If `svelte/motion` is wanted later, stub `matchMedia` in the test setup first. diff --git a/.agents/lessons/testing.md b/.agents/lessons/testing.md index be22088..9777a65 100644 --- a/.agents/lessons/testing.md +++ b/.agents/lessons/testing.md @@ -184,3 +184,31 @@ failures; retrying nothing makes the check a coin toss. **How to apply it.** Retry only the failure that names the link (`offline`, `closed`, `no devices`), after `adb wait-for-device`, a bounded number of times; find the device handle again after a drop; let every other failure end the check at once. Report how many runs failed and why. + +## jsdom has no `PointerEvent`, so a test pointer carries no coordinates + +**What happened.** On 2026-11-17 the planet garden's gesture tests fired `pointerDown` and +`pointerMove` with `clientX`/`clientY`, and every gesture read as a tap at (0, 0). jsdom has no +`PointerEvent`; testing-library falls back to a plain `Event`, which drops the coordinates. + +**Why it bit.** The test looked like a finger and measured nothing. A missing browser API in the +test environment does not fail loudly; it quietly hands the code a poorer event. + +**How to apply it.** Before testing pointer gestures in jsdom, polyfill `PointerEvent` on +`MouseEvent` (`packages/ui/test/planet.test.ts`) and assert one coordinate-dependent outcome first +(a sideways swipe does *not* pull a weed). Check real fingers on the device (`pnpm test:android`). + +## A device test's clean-up must cover its very first step + +**What happened.** On 2026-11-17 `scripts/android-smoke.ts` connected to Chrome on the tablet +*before* its `try`. Chrome was still cold-starting, the connect failed with *socket hang up*, and +the `finally` that stops Chrome and removes the adb mappings never ran: Chrome stayed open on a +device the author asked to leave as it was found. It was stopped by hand. + +**Why it bit.** Clean-up written for the failures you expect (a step fails) misses the one that +happens first (the setup fails). On a shared device, a leftover is somebody else's problem. + +**How to apply it.** Open the `try` before the first command that changes the device; make the +clean-up tolerate half-done setup (`page?.close()`, `browser?.close()`); retry connections that +race a cold start (the script tries for 30 s). After every device run, check: `pidof` the app is +empty, `reverse --list` and `forward --list` are empty. diff --git a/.agents/reviews/feature-planet-garden.md b/.agents/reviews/feature-planet-garden.md new file mode 100644 index 0000000..2d34c2c --- /dev/null +++ b/.agents/reviews/feature-planet-garden.md @@ -0,0 +1,68 @@ +# Review — `feature/planet-garden` + +Adversarial self-review (CLAUDE.md §5.3). Analysis: [`features/planet-garden.md`](../features/planet-garden.md). +Reviewed 2026-11-17 on Node 22.23.4, Windows 10. There is no PR: the only remote is Gitea. + +## What the author decided, and what was built + +Mark, on 2026-11-17: *a game, with a proper planet, a character who does the care with animations, +taps on the rose and swiped patterns; weeds tapped and swiped out.* He chose a **round tiny planet**, +a **human gardener, a boy or a girl, customised at the beginning**, and **all four gesture sets**. + +- The first open asks **Who tends her?**: boy or girl, skin tone, hair style and colour, clothes + colour, a hat, with a live preview; kept on the device (`profile.gardener`, a JSON Schema of + fixed lists). *Change gardener* reopens it. +- The garden is **her planet** (SVG): the real sky's light (engine `lightAt`), the meadow world, her + bed, the wall, the chair, the watering can, the day's weeds and fallen petals (engine + `weedsToday`, `petalsToday`), the windbreak on a windy hour, and **the gardener**, who walks round + the world to the work and takes a pose for it (stand-ins until art). +- **Tap her** (or Enter on her) opens **the ring** of what she needs, plus *Touch her* and *Close*; + Escape closes it, focus returns to her. **Press the can and tilt** to pour (the tilt sets the + rate); **swipe each weed up**; **sweep across the petals**; **drag the windbreak** to her + windward side; **stroke her petals** slowly. Every gesture has its button in the ring. +- The art board gains the gardener's sheet and eight poses, and her home planet in three lights; + STYLE.md records S2 (reversed) and S6 with their guards and review points 10–11. + +Also on this branch: the tap-highlight fix (seen on the real tablet) and `pnpm test:android`. + +## Bug drills + +| Put back | Result | +|:--|:--| +| A sideways swipe pulls a weed | **MISSED at first**, then CAUGHT: the "sideways" tests were also too short, so the distance rule hid the direction rule; a long diagonal test added | +| Every pulled weed is written as care, not only the last | CAUGHT | +| The sweep need not cover every petal | CAUGHT | +| The windbreak counts wherever it is dropped | CAUGHT | +| Tilt is ignored (pours at the steady rate) | CAUGHT | +| A stroke opens the ring instead of touching her | CAUGHT | +| The gardener question is not shown at the first open | CAUGHT: 2 | +| The gardener's look accepts any value | CAUGHT: 2 | +| Reduced motion still walks | **MISSED at first**, then CAUGHT: the test checked a CSS class, not where the gardener stands; it now reads his angle straight after an act | + +The first rerun of the reduced-motion drill reported CAUGHT against a test that was failing on its own (it looked before the garden loaded); fixed, then every drill was run again against a green suite. + +## Findings + +| # | Area | Finding | Resolution | +|:--|:--|:--|:--| +| 1 | Likeness / legal | A child tending a rose on a small round planet is the book's most recognisable image. | The author's decision, made knowingly. Guards: the gardener is the player's own, in work clothes; nothing to choose recreates the book's boy (tested on the option lists); the planet is a cultivated garden; review points 10–11; **G6.1: a legal check of the look before any public release.** | +| 2 | Soul | A child gardener for players who are mostly grown-ups. | Recorded as a question for the author's two-week play; a grown-up option is one list entry away (`gardener.schema.json`). | +| 3 | Soul | Gestures can feel like failing. | Generous thresholds; a missed gesture does nothing and says nothing; every act also has a button. | +| 4 | Accessibility | Gestures are not keyboard or screen-reader operable. | The ring's buttons do every act; the rose target is a focusable `role=button` with `aria-expanded`; one polite line says what the gardener did; axe passes on the choice, the scene and the ring (e2e). | +| 5 | Motion | Walking and swaying. | `prefers-reduced-motion`: the gardener is placed at once (tested); the global rule shortens the rest. | +| 6 | Two tabs | A gardener changed in one tab is not shown in another until reload (storage announces `gardener`, the UI does not listen yet). | Deferred: harmless (nothing is lost) and rare; noted for the next touch of the Shell. | +| 7 | Correctness | Half the weeds pulled, then the tab closed: nothing written, the weeds come back. | By design (G3): care is the finished job; nothing earned is lost. | +| 8 | Testing | jsdom has no `PointerEvent`: test pointers carried no coordinates, and `svelte/motion` read `matchMedia` at import, failing every file. | A `PointerEvent` polyfill in the planet tests; the walk is a small interval instead of `Tween`. Lessons in `testing.md` and `code.md`. | +| 9 | Process | The first look in the browser was the **old** garden: the preview's service worker served the cached build, as a player's would until *Refresh*. | Cleared for the check; it is exactly what calm-refresh exists for. | +| 10 | Design | The first stand-in had a shading arc that read as a smile on the planet. | Removed after looking. | +| 11 | Art | Painted art cannot simply be recoloured for every skin tone, hair and clothes choice the way the code stand-in is. | The board makes the first look; **how the other looks are drawn is open for the author** (STYLE.md §3b). | +| 12 | Testing | The first tablet run failed to connect while Chrome cold-started, and the connect sat **before** the `try`: Chrome was left running on the tablet. | Stopped by hand at once; the script now opens `try` before the first adb command, retries the connect for 30 s and tolerates half-done setup. Lesson in `testing.md`. | +| — | Privacy | The gardener's look stays in `profile`; it is not in the rose file (tested); nothing is sent. | — | + +## Gates and devices + +Counts are on the merge (HANDOVER). The tablet (WAVE 10C, 2026-11-17): `pnpm test:android` **7 of 7** +by real touch: the gardener question (a boy, a cap), the town, the ring opened by a tap on her and +closed, pouring by tilting the can, a stroke across her petals, and offline with the server +unreachable. Afterwards Chrome was stopped (`pidof` empty) and both adb mappings removed. **Not verified:** a screen reader; Safari; a phone smaller +than the tablet; weeds and petals by real touch on the device (their days depend on the key). diff --git a/CLAUDE.md b/CLAUDE.md index 1d616d6..33e4d5f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -59,6 +59,12 @@ encouraging, never ruling), never a name or a quote. Neglect makes her **drift** — turn away, close a little — never break. Short visits hold her; real time — calendar days on which care helped, never minutes on screen — brings full bloom. One tap shows her real numbers (water, warmth, days of care, trend). +- **Her planet and the gardener** *(decided by the author, 2026-11-17)* — she lives on a round tiny + planet of her own, cultivated as a garden, and **a gardener the player chooses** (a boy or a girl, + dressed at the first open) does the care, animated. The player cares by hand: tap her to open the + ring of care, tilt the can to pour, swipe weeds out, sweep petals, drag the windbreak, stroke her + petals; every gesture also has a button. The guards against the book's likeness are in + `art/STYLE.md` S2, S6, §3b and `.agents/features/planet-garden.md` §0. - **The planets** — a journey through lonely grown-ups (the king, the vain man, the businessman, the lamplighter, the geographer…). Each planet lets the player feel one shape of loneliness. - **The fox** — follows at a distance from the first planet and comes closer through touch (pet, @@ -590,6 +596,7 @@ No timestamp finer than a day, no precise location, no free text, no link to the | **Location makes people findable** | Coarse cells next to a sparse population identify a house. Cell size must adapt to density, traces must be delayed and auto-deleted, and stranger contact is consent-only (§5.6). | | **The library as a scam channel** | If any field lets a sender attach free text, a lonely recipient can be manipulated. The id-only contract (§6.1) is the defence. | | **Copyright through the back door** | An image prompt "in the style of" the book's drawings, a fox or rose that looks like the original, or a famous line "paraphrased" too closely. All forbidden (§5.6); the art pipeline checks likeness (`docs/ART.md`). | +| **A child on a small round planet with a rose** *(a risk the author accepted, 2026-11-17)* | It is the book's most recognisable image, and its estate holds trademarks. The author chose it knowingly. Keep every guard (STYLE.md S2, S6, §3b, review points 10–11: the gardener is the player's own, in work clothes, never a scarf, coat, cape, suit or crown; the planet is a cultivated garden, never volcanoes, baobabs or a lone lamp post), and **a legal check of the look comes before any public release** (G6.1). | | **Medical claims in a store listing** | One word like *heal* in marketing copy can pull the product toward medical-device rules. `lint:copy` also runs on store text kept in the repo. | | **IndexedDB is evictable** *(predicted; answered by `keep-her-safe.md`)* | WebKit can discard origin storage after seven days without interaction — exactly the shape of a player who drifted away and comes back. Call `navigator.storage.persist()` where it exists, prompt iOS players to install, and make export-my-rose a first-class feature. A player returning to find their rose gone is the cruellest bug this product could have. | | **The stale service worker** *(answered by `calm-refresh.md`)* | A precached shell keeps serving old JS to a player who has "updated". Detect a waiting worker and offer an explicit, calm *refresh* control. | diff --git a/HANDOVER.md b/HANDOVER.md index 040d790..54ae8a5 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -2,7 +2,7 @@ Rewritten at the end of each session (CLAUDE.md §5.1). -## Last session — 2026-10-31 to 2026-11-01 +## Last session — 2026-10-31 to 2026-11-17 **Done.** @@ -12,8 +12,9 @@ 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: 489 (cpu-guard 13, identity 5, schema 19, - content 88, storage 65, art-prep 61, engine 174, ui 64). E2E: 22. Offline: 1. `lint:copy`: 21 files, 0 problems. +- **Gates (2026-11-17, the planet garden merged with the Tauri shells):** all pass on this machine. + Unit tests: 561 (cpu-guard 13, identity 5, schema 19, content 88, storage 70, art-prep 63, tauri 40, + engine 179, ui 84). E2E: 26. Offline: 1. Tablet (`pnpm test:android`): 7. `lint:copy`: 26 files, 0 problems. `validate:library`: 13 of 13 fixtures rejected; 78 candidates pass. - **Built, not deployed:** there is no host yet. - **Roadmap and gameplay docs:** `docs/ROADMAP.md` and `docs/GAMEPLAY.md` are on @@ -113,6 +114,19 @@ Rewritten at the end of each session (CLAUDE.md §5.1). still on 127.0.0.1), driven through Chrome's DevTools socket: first open, the town, watering by a real held touch, the in-game sunset, and **offline** reloads with the server unreachable all pass. When device testing ends, the app used is stopped at once (the author's rule). +- **Her planet and the gardener (2026-11-17, G1.9):** merged to `main`, as the author decided after + seeing a page of buttons. She lives on a round tiny planet; at the first open *Who tends her?* lets + the player dress a boy or a girl (fixed lists, kept in `profile`, never in the rose file; *Change + gardener* reopens it). A tap on her opens the ring of what she needs today plus *Touch her*; the + gardener walks round the planet to the work. By hand: press the can and move sideways to tilt and + pour (further tilts pour faster), swipe each weed up and out, sweep across the fallen petals, drag + the windbreak to her windward side, stroke her petals slowly. Every gesture is also a button. + The pictures are code stand-ins until the board's are painted. **Accepted risk:** a child on a + small round planet with a rose is the book's best-known image; the guards are in STYLE.md (S2, S6, + §3b, review points 10–11), and a legal check comes before any public release (G6.1). Tested by + real touch on the Android tablet (`pnpm test:android`, 7 of 7). Analysis: + [`.agents/features/planet-garden.md`](.agents/features/planet-garden.md). Review: + [`.agents/reviews/feature-planet-garden.md`](.agents/reviews/feature-planet-garden.md). - **Four versions, one garden (2026-11-17):** merged to `main`, as the author decided: the PWA plus an Android, iOS and desktop app from one codebase through a Tauri 2 shell, `apps/rosea-tauri` (CLAUDE.md §2 *Four versions*, §3, §4, §8; ROADMAP *The platform track*). The **Windows app** @@ -148,9 +162,13 @@ The notification decision is made: in-app only on the web (G0.26). After an accept, Claude reads the row (`ArtifactData get art/`), downloads the picture (`Artifact read` with the asset id as `path`), runs `pnpm art:accept`, commits on `art/`, and writes `final` back into the row. -4. **A GitHub repository** for Pages, and whether it is public (G0.13, G0.23). -5. **Node is upgraded** (22.23.4); unpinning the dependencies pinned for 22.11 remains (G0.20). -6. **The rose's tuning** (`.agents/features/rose.md` R2, R4, R5, R6, all in `ROSE` in +4. **The gardener in paint:** the board asks for the first look (a girl, braids, sage, a straw hat). + Painted art cannot be recoloured for every skin, hair and clothes choice the way the stand-in is: + layered parts, a few painted looks, or tints? (STYLE.md §3b). Also: a gardener changed in one tab + shows in another only after a reload (the rose's care does update live). +5. **A GitHub repository** for Pages, and whether it is public (G0.13, G0.23). +6. **Node is upgraded** (22.23.4); unpinning the dependencies pinned for 22.11 remains (G0.20). +7. **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. @@ -169,6 +187,9 @@ The notification decision is made: in-app only on the web (G0.26). download: ask first). The cause is unknown. - **The Android tablet:** WAVE 10C on USB debugging; always `adb -s WAVE10CEEA036785` (an emulator attaches too, and other projects use the same tablet). Stop the app used when testing ends. + `pnpm test:android` with `ROSEA_ADB=F:\Tools\Android\Sdk\platform-tools\adb.exe` and + `ROSEA_ANDROID_SERIAL=WAVE10CEEA036785`, while `vite preview` serves the build on 127.0.0.1:4173; + it stops Chrome and removes its mappings itself, even when it fails. Its USB link drops now and then (`device offline`); `e2e/apps/check-garden.ts` waits and retries. - **Building the apps:** Rust 1.99 (MSVC) with the four Android targets, JDK 17, the Android SDK at `F:\Tools\Android\Sdk` (NDK 27.1), VS 2022 Build Tools, WebView2 and NSIS are all installed; a diff --git a/apps/rosea/src/App.svelte b/apps/rosea/src/App.svelte index 03c1f3e..ee17a8c 100644 --- a/apps/rosea/src/App.svelte +++ b/apps/rosea/src/App.svelte @@ -106,6 +106,8 @@ sentences, loadOpened: () => storage.loadOpened(), appendOpened: (event) => storage.appendOpened(event), + // The player's gardener, chosen at the first open (planet-garden.md G6). + gardener: { load: () => storage.loadGardener(), save: (look) => storage.saveGardener(look) }, // Another tab gave care, opened a petal or brought her back (two-tabs.md). changes: (listener) => storage.onChange((what) => what === 'log' && listener()), clientVersion: version, diff --git a/art/STYLE.md b/art/STYLE.md index 980446f..0c1ecb6 100644 --- a/art/STYLE.md +++ b/art/STYLE.md @@ -21,6 +21,14 @@ A picture that is off-style goes back for another try. It is never shipped. > the petals, and §6 makes prompts short enough for a generator to follow. The book's motifs > are no longer named in prompts (naming them invites them); they stay in §4 and §7, where the > review catches them. The picture list grew to every picture Phases 1–5 need (§4). +> +> **Changed by Mark, 2026-11-17: her world is a round tiny planet, and a gardener tends her.** +> Seeing the garden as a page of buttons, he asked for a game: a planet, a character who does the +> care with animations, gestures. He chose a **round tiny planet** (S2 below, reversed) and a +> **human gardener, a boy or a girl, chosen and dressed by the player** (S6, new), knowing that +> a child tending a rose on a small round planet is close to the book's most recognisable image. +> The guards that keep them our own are in §3b, §4 and review points 10–11, and a legal check of +> the look comes before any public release (`.agents/features/planet-garden.md` §0). --- @@ -29,7 +37,8 @@ A picture that is off-style goes back for another try. It is never shipped. | # | Choice | Decided | Why | |:--|:--|:--|:--| | S1 | The medium | Matte gouache on warm paper, with soft brush outlines | It is gentle and hand-made like the rest of Domi. It is also clearly not the book's look, which is a thin pen line with loose, pale watercolour. | -| S2 | Where the rose lives | A small garden bed on a hillside meadow, with a low dry-stone wall and a wide sky to the west | The sunset is real, so the scene needs a real horizon. It is an ordinary garden, never a tiny planet. | +| S2 | Where the rose lives | ~~A small garden bed on a hillside meadow~~ **A round tiny planet of her own, cultivated as a garden**: meadow over it, her bed on top, a low dry-stone wall, the chair, the wild bush. *Reversed by Mark 2026-11-17.* | He wants a world of her own, as a game has. It stays a garden, never a bare rock: no volcanoes, no baobab-like trees, no single lamp post (§4). The real sky is still code behind it (S5); the in-game sunset keeps the hillside garden for its wide horizon. | +| S6 | Who tends her | **A human gardener: a boy or a girl, chosen and dressed by the player** at the first open (skin tone, hair and its colour, clothes colour, a hat). *Decided by Mark 2026-11-17.* | The care is done by a character, with animations. The gardener is the player's own, so no two need look alike; simple work clothes and an apron, never a scarf, a long coat or cape, a green suit, a crown or a sword (§3b). | | S3 | The rose's face | A face in the middle of the bloom: two small eyes, often half-closed, a tiny mouth and a blush | This is the description in CLAUDE.md §1, drawn as written. | | S4 | The palette | §2 | It starts from the app's tokens (`--rose #b4485e`, `--paper #fbf6f1`). | | S5 | The sky | Drawn in code, never painted | The sun moves at the player's real time, and the stars are the real constellations. A painted sky could do neither. | @@ -59,7 +68,8 @@ A picture that is off-style goes back for another try. It is never shipped. > book for adults: understated, never sugary, never a children's sticker or a cute mascot. > Characters are alive but small-featured: their faces are a few tiny marks painted directly on > them, with eyes as small dark dots or crescents, often half-closed. No text, letters or numbers -> anywhere. No people, hands or human faces. Not watercolour: no wet washes, bleeding edges, blooms or +> anywhere. No people, hands or human faces, except the player's gardener where the picture names +> them. Not watercolour: no wet washes, bleeding edges, blooms or > pale tints. Not digital: no 3D rendering, gloss, airbrush gradients or lens effects. An > original design, in the manner of no existing artist, book or film. @@ -129,6 +139,26 @@ The rose is the only character in Phase 1. Every rose picture follows the charac --- +## 3b. The gardener (S6, decided by Mark 2026-11-17) + +The player's own gardener: a boy or a girl of about ten, chosen and dressed at the first open. +Every gardener picture follows `gardener-sheet`. + +- **Simple work clothes:** a plain short-sleeved shirt (the boy, with trousers) or tunic (the girl, + with bare legs), a cream canvas apron with one pocket, small sturdy boots. Hands small and simple. +- **A face like the others':** a few tiny painted marks, eyes often half-closed, calm and kind. +- **The choices the player makes** (skin tone, hair style and colour, clothes colour, straw hat, + cap or none) are the app's (`gardener.schema.json`). The board paints **the first look** (the girl: + braids, brown hair, sage clothes, straw hat; and the boy, short hair, the same colours) so the + character can be judged. **How the other looks are drawn** (separate layers for hair and hat, or + clothes painted to be tinted in code) **is still open** and waits for Mark: it decides how many + pictures the gardener needs. +- **Never:** a scarf, a long coat or cape, a suit with epaulettes, a crown, a sword, golden curls + with a green outfit, or anything that recreates the book's boy. He or she is a gardener at work. +- **Size:** standing, a little taller than the rose. + +--- + ## 3a. The fox (Phase 2: F1–F2) The fox is the second character. Every fox picture follows the character sheet `fox-sheet`. @@ -188,7 +218,11 @@ The fox is the second character. Every fox picture follows the character sheet ` sunset wave are pictures. - **The share frame (Phase 5):** a border of meadow round an empty middle where the player's sky is drawn. -- No flags, religious symbols, buildings, vehicles or people. +- **Her home planet (S2, reversed 2026-11-17):** a small round world seen whole, covered in meadow, + with her round garden bed on top, a low dry-stone wall curving behind it, the wooden chair on its + shoulder and a few meadow flowers. Everything outside the planet is transparent: the sky is code. + **Never** volcanoes, baobab-like trees or a lone lamp post on it: it is a garden, not a rock. +- No flags, religious symbols, buildings or vehicles. No people except the player's gardener. --- @@ -255,6 +289,10 @@ tick them: *Accept* is one tap. 8. It reads as one young red-orange fox with a cream mask and a ringed tail, shy and gentle, and nothing like the book's sandy, long-eared fox. 9. He matches `fox-sheet`: the same mask, ears, leg colour, tail rings and size. +10. The gardener is a child at garden work, matching `gardener-sheet`: plain shirt or tunic, an + apron, boots; no scarf, long coat, cape, suit, crown or sword, and nothing like the book's boy. +11. Her planet is a cultivated garden world: meadow, her bed, the wall, the chair; no volcanoes, + no baobab-like trees, no lone lamp post, and not the look of the book's little planet. --- diff --git a/art/manifest.json b/art/manifest.json index 172de5a..3a93c5a 100644 --- a/art/manifest.json +++ b/art/manifest.json @@ -8,6 +8,10 @@ "fox": { "sheet": "fox-sheet", "description": "The fox: a small, young fox; sitting, he is about as tall as the rose. A deep red-orange coat (#BC4A22), warm and glowing, never neon. A cream mask (#F3E3C8) on his face: cream cheeks and muzzle and a small cream spot above each eye. Deep brown legs and paws (#5A3A33). Rounded ears of middle size, cream inside with dark tips. A big bushy tail with three faint darker rings and a cream tip. Small dark eyes, often half-closed, a tiny dark nose and mouth. A fox's pointed muzzle and a fox's body: the mask and the tail rings are only a nod to a red panda. Shy, curious and gentle, never sly." + }, + "gardener": { + "sheet": "gardener-sheet", + "description": "The gardener: the player's own, a child of about ten at garden work, a little taller than the rose. The first look: a girl with brown hair in two braids, a wide straw hat, a plain sage-green short-sleeved tunic, a cream canvas apron with one pocket, bare legs and small sturdy brown boots; or a boy with short brown hair, the same straw hat, a plain sage-green shirt and trousers, the same apron and boots. A face of a few tiny painted marks: small dark eyes, often half-closed, a short calm mouth. Kind, absorbed in the work, never posing." } }, "avoid": [ @@ -675,6 +679,217 @@ 6 ] }, + { + "phase": 1, + "shipped": false, + "character": "gardener", + "allow": [ + "people, hands or human faces" + ], + "checks": [ + 2, + 3, + 4, + 5, + 10 + ], + "id": "gardener-sheet", + "type": "sheet", + "width": 1536, + "height": 1024, + "background": "full", + "smallest": null, + "usedBy": [ + "The reference for every gardener picture (STYLE.md §3b). Make it right after rose-sheet." + ], + "purpose": "Reference sheet that fixes the gardener's first look, the girl and the boy; never shown in the app.", + "subject": "The gardener, as described below, painted eight times: the top row the girl (front view; three-quarter view facing left; side view facing left; back view), the bottom row the boy in the same four views.", + "setting": "Isolated on plain warm off-white paper (#FBF6F1), no scenery, no ground.", + "composition": "Eight full figures in two rows of four, evenly spaced, all at the same scale, nothing overlapping.", + "include": [ + "identical proportions, clothes and apron in every view", + "the same tiny painted face in every view that shows it" + ], + "avoid": [ + "a pose that looks posed for a photograph", + "any tool or prop in their hands" + ] + }, + { + "phase": 1, + "shipped": true, + "character": "gardener", + "allow": [ + "people, hands or human faces" + ], + "checks": [ + 2, + 3, + 4, + 5, + 6, + 7, + 10 + ], + "id": "gardener-poses-sheet", + "type": "spritesheet", + "width": 1536, + "height": 1024, + "background": "transparent", + "smallest": 120, + "usedBy": [ + "The gardener at work on her planet (planet-garden.md G5): each pose is shown while the care it belongs to happens." + ], + "purpose": "The gardener's poses for each act of care, the girl in the first look.", + "angle": "The whole girl gardener in every cell, in side view facing right unless the cell says otherwise, at the same scale as gardener-sheet, the same light from the left.", + "grid": { + "cols": 4, + "rows": 2 + }, + "cells": [ + { + "id": "gardener-stand", + "does": "standing beside something just out of the picture, hands at the sides, looking at it fondly." + }, + { + "id": "gardener-walk", + "does": "walking to the right, mid-step, arms swinging a little." + }, + { + "id": "gardener-pour", + "does": "holding a small round sage-green watering can in both hands, tipping it forward to the right, a thin stream of water falling." + }, + { + "id": "gardener-pull", + "does": "crouched, both hands round something low on the ground just out of the picture, leaning back to pull." + }, + { + "id": "gardener-sweep", + "does": "bending a little, sweeping one hand across the grass to the right, gathering." + }, + { + "id": "gardener-carry", + "does": "carrying a small curved woven willow hurdle upright in front of them with both arms." + }, + { + "id": "gardener-reach", + "does": "reaching one hand out gently to the right and up, as if to touch a petal, fingers soft." + }, + { + "id": "gardener-sit", + "does": "sitting on nothing (the chair is its own picture), in three-quarter view facing left towards a sunset outside the picture, hands in the lap." + } + ], + "include": [ + "the same gardener as gardener-sheet in every cell" + ], + "avoid": [ + "ground or grass under them", + "the rose or any plant in the picture" + ] + }, + { + "id": "home-planet-day", + "type": "layer", + "phase": 1, + "width": 1024, + "height": 1024, + "background": "transparent", + "shipped": true, + "smallest": null, + "usedBy": [ + "Her home planet in the garden scene (planet-garden.md), chosen by the real sun's light (engine lightAt)." + ], + "purpose": "Her own small round world, seen whole, with everything around it transparent for the real sky behind.", + "subject": "No characters. A small round planet seen whole from the side, cultivated as a garden: soft meadow grass all over it with a few small meadow flowers, warm earth showing at its underside, on its top a round garden bed of warm umber soil (empty: the rose is her own picture), a low curving dry-stone wall behind the bed, a small weathered wooden chair with a pale pink cushion on its right shoulder.", + "setting": "The same planet in soft bright daylight from high on the left, fresh greens.", + "composition": "Square. The planet centred, about 70 % of the width across; its top, with the empty bed, a little above the middle. Everything outside the planet fully transparent.", + "include": [ + "a fully transparent sky", + "an empty garden bed on top, centred" + ], + "avoid": [ + "a painted sky, sun, moon or stars", + "a rose or any large flower in the bed", + "people or animals" + ], + "checks": [ + 2, + 3, + 4, + 5, + 6, + 11 + ] + }, + { + "id": "home-planet-golden", + "type": "layer", + "phase": 1, + "width": 1024, + "height": 1024, + "background": "transparent", + "shipped": true, + "smallest": null, + "usedBy": [ + "Her home planet in the garden scene (planet-garden.md), chosen by the real sun's light (engine lightAt)." + ], + "purpose": "Her own small round world, seen whole, with everything around it transparent for the real sky behind.", + "subject": "No characters. A small round planet seen whole from the side, cultivated as a garden: soft meadow grass all over it with a few small meadow flowers, warm earth showing at its underside, on its top a round garden bed of warm umber soil (empty: the rose is her own picture), a low curving dry-stone wall behind the bed, a small weathered wooden chair with a pale pink cushion on its right shoulder.", + "setting": "The same planet in low evening light from the left: amber gold (#F2B860) and coral (#E9846A) on the wall and grass, long soft shadows to the right.", + "composition": "Square. The planet centred, about 70 % of the width across; its top, with the empty bed, a little above the middle. Everything outside the planet fully transparent.", + "include": [ + "a fully transparent sky", + "an empty garden bed on top, centred" + ], + "avoid": [ + "a painted sky, sun, moon or stars", + "a rose or any large flower in the bed", + "people or animals" + ], + "checks": [ + 2, + 3, + 4, + 5, + 6, + 11 + ] + }, + { + "id": "home-planet-night", + "type": "layer", + "phase": 1, + "width": 1024, + "height": 1024, + "background": "transparent", + "shipped": true, + "smallest": null, + "usedBy": [ + "Her home planet in the garden scene (planet-garden.md), chosen by the real sun's light (engine lightAt)." + ], + "purpose": "Her own small round world, seen whole, with everything around it transparent for the real sky behind.", + "subject": "No characters. A small round planet seen whole from the side, cultivated as a garden: soft meadow grass all over it with a few small meadow flowers, warm earth showing at its underside, on its top a round garden bed of warm umber soil (empty: the rose is her own picture), a low curving dry-stone wall behind the bed, a small weathered wooden chair with a pale pink cushion on its right shoulder.", + "setting": "The same planet in night: dusk indigo (#2E3561) shadows, soft silver-blue light from above, one or two lamp-gold glow-worms in the grass; calm and safe.", + "composition": "Square. The planet centred, about 70 % of the width across; its top, with the empty bed, a little above the middle. Everything outside the planet fully transparent.", + "include": [ + "a fully transparent sky", + "an empty garden bed on top, centred" + ], + "avoid": [ + "a painted sky, sun, moon or stars", + "a rose or any large flower in the bed", + "people or animals" + ], + "checks": [ + 2, + 3, + 4, + 5, + 6, + 11 + ] + }, { "id": "fox-sheet", "type": "sheet", diff --git a/art/placeholders/gardener-carry.svg b/art/placeholders/gardener-carry.svg new file mode 100644 index 0000000..91a665e --- /dev/null +++ b/art/placeholders/gardener-carry.svg @@ -0,0 +1,4 @@ + + + + diff --git a/art/placeholders/gardener-poses-sheet.svg b/art/placeholders/gardener-poses-sheet.svg new file mode 100644 index 0000000..66ba910 --- /dev/null +++ b/art/placeholders/gardener-poses-sheet.svg @@ -0,0 +1,4 @@ + + + + diff --git a/art/placeholders/gardener-pour.svg b/art/placeholders/gardener-pour.svg new file mode 100644 index 0000000..8c24246 --- /dev/null +++ b/art/placeholders/gardener-pour.svg @@ -0,0 +1,4 @@ + + + + diff --git a/art/placeholders/gardener-pull.svg b/art/placeholders/gardener-pull.svg new file mode 100644 index 0000000..666f590 --- /dev/null +++ b/art/placeholders/gardener-pull.svg @@ -0,0 +1,4 @@ + + + + diff --git a/art/placeholders/gardener-reach.svg b/art/placeholders/gardener-reach.svg new file mode 100644 index 0000000..b68508b --- /dev/null +++ b/art/placeholders/gardener-reach.svg @@ -0,0 +1,4 @@ + + + + diff --git a/art/placeholders/gardener-sheet.svg b/art/placeholders/gardener-sheet.svg new file mode 100644 index 0000000..c910949 --- /dev/null +++ b/art/placeholders/gardener-sheet.svg @@ -0,0 +1,4 @@ + + + + diff --git a/art/placeholders/gardener-sit.svg b/art/placeholders/gardener-sit.svg new file mode 100644 index 0000000..e553fc8 --- /dev/null +++ b/art/placeholders/gardener-sit.svg @@ -0,0 +1,4 @@ + + + + diff --git a/art/placeholders/gardener-stand.svg b/art/placeholders/gardener-stand.svg new file mode 100644 index 0000000..94db29c --- /dev/null +++ b/art/placeholders/gardener-stand.svg @@ -0,0 +1,4 @@ + + + + diff --git a/art/placeholders/gardener-sweep.svg b/art/placeholders/gardener-sweep.svg new file mode 100644 index 0000000..873b8ee --- /dev/null +++ b/art/placeholders/gardener-sweep.svg @@ -0,0 +1,4 @@ + + + + diff --git a/art/placeholders/gardener-walk.svg b/art/placeholders/gardener-walk.svg new file mode 100644 index 0000000..5c64d37 --- /dev/null +++ b/art/placeholders/gardener-walk.svg @@ -0,0 +1,4 @@ + + + + diff --git a/art/placeholders/home-planet-day.svg b/art/placeholders/home-planet-day.svg new file mode 100644 index 0000000..21a15fa --- /dev/null +++ b/art/placeholders/home-planet-day.svg @@ -0,0 +1,4 @@ + + + + diff --git a/art/placeholders/home-planet-golden.svg b/art/placeholders/home-planet-golden.svg new file mode 100644 index 0000000..4b157f6 --- /dev/null +++ b/art/placeholders/home-planet-golden.svg @@ -0,0 +1,4 @@ + + + + diff --git a/art/placeholders/home-planet-night.svg b/art/placeholders/home-planet-night.svg new file mode 100644 index 0000000..de154e6 --- /dev/null +++ b/art/placeholders/home-planet-night.svg @@ -0,0 +1,4 @@ + + + + diff --git a/e2e/apps/check-garden.ts b/e2e/apps/check-garden.ts index d593fef..1434301 100644 --- a/e2e/apps/check-garden.ts +++ b/e2e/apps/check-garden.ts @@ -18,6 +18,7 @@ import { expect, _android as android, chromium, type Page } from '@playwright/test'; import { PRODUCT_NAME } from '@rosea/schema'; import { en } from '@rosea/ui/copy'; +import { openRing, pastGardener } from '../garden.js'; import { spawn, spawnSync, type ChildProcess } from 'node:child_process'; import { existsSync, mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -47,7 +48,7 @@ async function garden(page: Page): Promise { await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME, { timeout: 20_000 }); } -/** The first visit: skip the town (no town is the private choice), water her, wait for the write. */ +/** The first visit: the first gardener, skip the town (no town is the private choice), water her from the ring, wait for the write. */ async function firstVisit(page: Page): Promise { await garden(page); const seen = watch(page); @@ -60,9 +61,11 @@ async function firstVisit(page: Page): Promise { report['manifestLink'] = await page.evaluate(() => document.querySelector('link[rel="manifest"]') !== null); report['cspMeta'] = await page.evaluate(() => document.querySelector('meta[http-equiv="Content-Security-Policy"]') !== null); + await pastGardener(page); const skip = page.getByRole('button', { name: /^Not now/ }); if (await skip.isVisible().catch(() => false)) await skip.click(); + await openRing(page); const water = page.getByRole('button', { name: en.rose.water }); await expect(water).toBeVisible(); const box = await water.boundingBox(); diff --git a/e2e/garden.ts b/e2e/garden.ts new file mode 100644 index 0000000..ce5ae97 --- /dev/null +++ b/e2e/garden.ts @@ -0,0 +1,21 @@ +import { expect, type Page } from '@playwright/test'; +import { en } from '@rosea/ui/copy'; + +/** + * The first open asks *Who tends her?* (planet-garden.md §1). Tests that are not about the + * gardener answer it with the first look, so they reach the garden as a returning player does. + */ +export async function pastGardener(page: Page): Promise { + const question = page.getByRole('heading', { level: 2, name: en.gardener.question }); + const garden = page.getByRole('button', { name: en.rose.care }); + await expect(question.or(garden)).toBeVisible({ timeout: 20_000 }); + if (await question.isVisible()) await page.getByRole('button', { name: en.gardener.done }).click(); + await expect(garden).toBeVisible(); +} + +/** Opens the ring of care, as Enter on her (or a tap) does (planet-garden.md G7). */ +export async function openRing(page: Page): Promise { + const ring = page.getByRole('group', { name: en.scene.ring }); + if (!(await ring.isVisible())) await page.getByRole('button', { name: en.rose.care }).press('Enter'); + await expect(ring).toBeVisible(); +} diff --git a/e2e/offline.spec.ts b/e2e/offline.spec.ts index 6b9320d..cab783a 100644 --- a/e2e/offline.spec.ts +++ b/e2e/offline.spec.ts @@ -2,6 +2,7 @@ import { expect, test } from '@playwright/test'; import { PRODUCT_NAME } from '@rosea/schema'; import { en } from '@rosea/ui/copy'; import { startStaticServer } from './static-server.js'; +import { openRing, pastGardener } from './garden.js'; import { storedCare, storedTown } from './stored.js'; /** @@ -24,6 +25,7 @@ test('the shell opens from the service worker with the server gone', async ({ br await page.clock.setFixedTime(Date.parse('2026-03-29T12:00:00+02:00')); await page.goto(server.url); await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME); + await pastGardener(page); // The player answers the sunset question while online (sunset-place.md). await page.getByRole('searchbox', { name: en.sunset.searchLabel }).fill('brno'); @@ -67,6 +69,7 @@ test('the shell opens from the service worker with the server gone', async ({ br await storedTown(page, 'Plzeň'); // Tending the rose offline: hold Water, as a finger would (rose.md). + await openRing(page); await page.getByRole('button', { name: en.rose.water }).hover(); await page.mouse.down(); await page.waitForTimeout(1500); diff --git a/e2e/petal.spec.ts b/e2e/petal.spec.ts index 430185e..aed2c72 100644 --- a/e2e/petal.spec.ts +++ b/e2e/petal.spec.ts @@ -7,6 +7,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { startStaticServer, type StaticServer } from './static-server.js'; +import { pastGardener } from './garden.js'; import { storedCare } from './stored.js'; import fixture from './fixtures/library/fixture.json' with { type: 'json' }; @@ -35,7 +36,7 @@ test.afterEach(async () => { async function open(page: Page): Promise { await page.clock.setFixedTime(MORNING); await page.goto(server.url); - await expect(page.getByRole('button', { name: en.rose.water })).toBeVisible(); + await pastGardener(page); } test('with the shipped library still empty, she holds no petal and says nothing about one', async ({ page }) => { diff --git a/e2e/planet.spec.ts b/e2e/planet.spec.ts new file mode 100644 index 0000000..e3eddec --- /dev/null +++ b/e2e/planet.spec.ts @@ -0,0 +1,83 @@ +import AxeBuilder from '@axe-core/playwright'; +import { expect, test, type Page } from '@playwright/test'; +import { PRODUCT_NAME } from '@rosea/schema'; +import { en } from '@rosea/ui/copy'; +import { startStaticServer, type StaticServer } from './static-server.js'; +import { storedCare } from './stored.js'; + +/** + * Her planet in the BUILT app (.agents/features/planet-garden.md): the first-open choice of + * gardener, the ring of care, and care by the player's own hand on the can. + */ +test.use({ timezoneId: 'Europe/Prague', locale: 'en-US' }); +const MORNING = Date.parse('2026-03-01T08:00:00+01:00'); + +let server: StaticServer; +test.beforeEach(async () => { + server = await startStaticServer(); +}); +test.afterEach(async () => { + await server.close(); +}); + +const axe = async (page: Page): Promise => (await new AxeBuilder({ page }).analyze()).violations.map((v) => `${v.id}: ${v.help}`); + +test('the first open asks who tends her; the chosen gardener stays after a reload', async ({ page }) => { + await page.clock.setFixedTime(MORNING); + await page.goto(server.url); + await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME); + await expect(page.getByRole('heading', { level: 2, name: en.gardener.question })).toBeVisible(); + await expect(page.getByRole('img', { name: en.gardener.preview })).toBeVisible(); + expect(await axe(page)).toEqual([]); + + await page.getByText(en.gardener.values.presentation.boy, { exact: true }).click(); + await page.getByText(en.gardener.values.hat.cap, { exact: true }).click(); + await page.getByRole('button', { name: en.gardener.done }).click(); + await expect(page.getByRole('group', { name: en.scene.planet })).toBeVisible(); + expect(await axe(page)).toEqual([]); + + await page.waitForFunction( + () => + new Promise((resolve) => { + const req = indexedDB.open('rosea'); + req.onsuccess = () => { + const get = req.result.transaction('profile').objectStore('profile').get('gardener'); + get.onsuccess = () => resolve((get.result as { value?: { presentation?: string } } | undefined)?.value?.presentation === 'boy'); + get.onerror = () => resolve(false); + }; + req.onerror = () => resolve(false); + }) + ); + await page.reload(); + await expect(page.getByRole('group', { name: en.scene.planet })).toBeVisible(); + await expect(page.getByRole('heading', { name: en.gardener.question })).toHaveCount(0); +}); + +test('a tap on her opens the ring of what she needs; Escape closes it', async ({ page }) => { + await page.clock.setFixedTime(MORNING); + await page.goto(server.url); + await page.getByRole('button', { name: en.gardener.done }).click(); + await page.getByRole('button', { name: en.rose.care }).click(); + const ring = page.getByRole('group', { name: en.scene.ring }); + await expect(ring).toBeVisible(); + await expect(ring.getByRole('button', { name: en.rose.water })).toBeFocused(); + expect(await axe(page)).toEqual([]); + await page.keyboard.press('Escape'); + await expect(ring).toHaveCount(0); + await expect(page.getByRole('button', { name: en.rose.care })).toBeFocused(); +}); + +test('pressing the can and tilting it pours: she thanks the player, and it is kept', async ({ page }) => { + await page.clock.setFixedTime(MORNING); + await page.goto(server.url); + await page.getByRole('button', { name: en.gardener.done }).click(); + const can = page.getByRole('img', { name: en.scene.can }); + const box = (await can.boundingBox())!; + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2); + await page.mouse.down(); + await page.mouse.move(box.x + box.width / 2 + 90, box.y + box.height / 2, { steps: 5 }); + await page.waitForTimeout(1300); + await page.mouse.up(); + await expect(page.getByText(en.rose.says.thanks)).toBeVisible(); + await storedCare(page, 1); +}); diff --git a/e2e/playwright.config.ts b/e2e/playwright.config.ts index 4101856..16f1f22 100644 --- a/e2e/playwright.config.ts +++ b/e2e/playwright.config.ts @@ -7,7 +7,7 @@ import { defineConfig, devices } from '@playwright/test'; */ export default defineConfig({ testDir: '.', - testMatch: /(shell|update|petal)\.spec\.ts/, + testMatch: /(shell|update|petal|planet)\.spec\.ts/, fullyParallel: false, workers: 1, retries: 0, diff --git a/e2e/shell.spec.ts b/e2e/shell.spec.ts index aaa7455..90e409a 100644 --- a/e2e/shell.spec.ts +++ b/e2e/shell.spec.ts @@ -7,6 +7,7 @@ import { nextInvitation, nextSunEvent } from '@rosea/engine'; import { searchTowns } from '@rosea/content/places'; import { readFileSync } from 'node:fs'; import { BASE, startStaticServer, type StaticServer } from './static-server.js'; +import { openRing, pastGardener } from './garden.js'; import { storedCare, storedTown } from './stored.js'; let server: StaticServer; @@ -29,6 +30,7 @@ async function open(page: Page): Promise<{ requests: string[]; cspViolations: st }); await page.goto(server.url); await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME); + await pastGardener(page); // Let the worker register and precache, so its requests are counted too. await page.waitForFunction(() => navigator.serviceWorker.ready.then(() => true), null, { timeout: 20_000 }); return { requests, cspViolations }; @@ -204,6 +206,7 @@ test.describe('the rose, in Prague at 08:00 on 1 March 2026', () => { /** Holds the Water button with the mouse, as a player holds it with a finger. */ async function pour(page: Page, ms: number): Promise { + await openRing(page); await page.getByRole('button', { name: en.rose.water }).hover(); await page.mouse.down(); await page.waitForTimeout(ms); @@ -232,6 +235,7 @@ test.describe('the rose, in Prague at 08:00 on 1 March 2026', () => { // The clock is driven, not frozen: taps at one frozen instant would be one touch. await page.clock.install({ time: MORNING }); await open(page); + await openRing(page); const touch = page.getByRole('button', { name: en.rose.touch.label }); await touch.click(); await expect(page.locator('.bubble')).toHaveText(en.rose.touch.fond[0]!); @@ -246,6 +250,14 @@ test.describe('the rose, in Prague at 08:00 on 1 March 2026', () => { expect((await new AxeBuilder({ page }).analyze()).violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]); }); + test('a touched control shows no browser tap box (seen on a real Android tablet)', async ({ page }) => { + await page.clock.setFixedTime(MORNING); + await open(page); + await openRing(page); + const highlight = await page.getByRole('button', { name: en.rose.water }).evaluate((el) => getComputedStyle(el).getPropertyValue('-webkit-tap-highlight-color')); + expect(highlight.replace(/\s/g, '')).toBe('rgba(0,0,0,0)'); + }); + test('the rose and her care have no accessibility violations', async ({ page }) => { await page.clock.setFixedTime(MORNING); await open(page); @@ -267,6 +279,7 @@ test.describe('two tabs of the garden, in Prague at 08:00 on 1 March 2026', () = await open(p); await expect(p.getByText(en.rose.says.dry)).toBeVisible(); } + await openRing(page); await page.getByRole('button', { name: en.rose.water }).hover(); await page.mouse.down(); await page.waitForTimeout(1500); @@ -307,8 +320,10 @@ test.describe('keep her safe, in Prague at 08:00 on 1 March 2026', () => { const page = await first.newPage(); await page.clock.setFixedTime(MORNING); await page.goto(server.url); + await pastGardener(page); await page.getByRole('searchbox', { name: en.sunset.searchLabel }).fill('brno'); await page.getByRole('button', { name: /^Brno/ }).first().click(); + await openRing(page); await page.getByRole('button', { name: en.rose.water }).hover(); await page.mouse.down(); await page.waitForTimeout(1500); @@ -333,6 +348,7 @@ test.describe('keep her safe, in Prague at 08:00 on 1 March 2026', () => { const page = await second.newPage(); await page.clock.setFixedTime(MORNING + 3_600_000); await page.goto(server.url); + await pastGardener(page); await expect(page.getByRole('img', { name: 'The rose, a bud.' })).toBeVisible(); await page.getByRole('button', { name: en.rose.safe.title }).click(); await page.getByLabel(en.rose.safe.bringBack).setInputFiles({ name: 'rose-2026-03-01.json', mimeType: 'application/json', buffer: Buffer.from(saved) }); diff --git a/package.json b/package.json index 78e7747..6280f30 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "test": "pnpm guard:cpu && turbo run test", "test:e2e": "pnpm guard:cpu && turbo run build --filter=@rosea/app && playwright test --config=e2e/playwright.config.ts", "test:offline": "pnpm guard:cpu && turbo run build --filter=@rosea/app && playwright test --config=e2e/playwright.offline.config.ts", + "test:android": "tsx scripts/android-smoke.ts", "validate:library": "tsx scripts/validate-library.ts", "library:verify": "tsx scripts/verify-sentences.ts", "lint:copy": "tsx scripts/lint-copy.ts", diff --git a/packages/engine/src/index.ts b/packages/engine/src/index.ts index 21fe8d8..0b29bc6 100644 --- a/packages/engine/src/index.ts +++ b/packages/engine/src/index.ts @@ -3,8 +3,9 @@ export { careEvent, careIdentity, judgeCare, newCare, OWN_TRACE, petalsOn, pour, ROSE, roseAt, seeded, stageFor, weedsOn, windOn, type Judged, type Mood, type Needs, type RoseKeys, type RoseNow, type Stage, type Trend } from './rose/rose.js'; -export { invitation, nextInvitation, nextSunEvent, sunDay, type NamedPlace, type Place, type SunDay } from './sun/sun.js'; +export { invitation, lightAt, nextInvitation, nextSunEvent, sunDay, type Light, type NamedPlace, type Place, type SunDay } from './sun/sun.js'; export { goodMoment, newOpened, openedIdentity, PETAL, petalAt, petalOrder, sentenceOpened, type PetalNow, type PetalSentence } from './petal/petal.js'; export { touch, TOUCH, UNTOUCHED, type TouchReply, type TouchState } from './touch/touch.js'; +export { petalsToday, weedsToday } from './scene/scene.js'; diff --git a/packages/engine/src/scene/scene.ts b/packages/engine/src/scene/scene.ts new file mode 100644 index 0000000..0bc1f1c --- /dev/null +++ b/packages/engine/src/scene/scene.ts @@ -0,0 +1,16 @@ +/** + * What the planet garden shows of her day (.agents/features/planet-garden.md G3). Pure: the + * rose's key and the local day are parameters, so a replay shows the same weeds every time. + */ +import { petalsOn, seeded, weedsOn } from '../rose/rose.js'; +import type { LocalDay } from '../time/localDay.js'; + +/** How many weeds came up in the night: 2–4 on a day with weeds, else none. */ +export function weedsToday(seed: string, day: LocalDay): number { + return weedsOn(seed, day) ? 2 + Math.floor(seeded(seed, day, 'weed-count') * 3) : 0; +} + +/** How many of her petals have fallen: 3–5 on a day with fallen petals, else none. */ +export function petalsToday(seed: string, day: LocalDay): number { + return petalsOn(seed, day) ? 3 + Math.floor(seeded(seed, day, 'petal-count') * 3) : 0; +} diff --git a/packages/engine/src/sun/sun.ts b/packages/engine/src/sun/sun.ts index 72309d8..e82cec6 100644 --- a/packages/engine/src/sun/sun.ts +++ b/packages/engine/src/sun/sun.ts @@ -159,6 +159,27 @@ export function nextInvitation(now: number, place: Place): { readonly sun: SunDa throw new Error(`nextInvitation: no invitation within two days of ${today}`); } +/** The light over her planet now (planet-garden.md): the scene's sky follows the real sun. */ +export type Light = 'day' | 'golden' | 'night'; + +/** + * Golden within 45 minutes before and 30 after the sunset or sunrise (in polar day, around the + * lowest light; in polar night, around the brightest twilight at noon); day between, night outside. + */ +export function lightAt(now: number, place: Place): Light { + const sun = sunDay(localDay(now, place.timeZone), place); + const near = (at: number, before: number, after: number): boolean => now >= at - before * MINUTE && now <= at + after * MINUTE; + switch (sun.kind) { + case 'polar-day': + return near(sun.lowestLight, 60, 60) ? 'golden' : 'day'; + case 'polar-night': + return near(sun.solarNoon, 90, 90) ? 'golden' : 'night'; + case 'sun-sets': + if (near(sun.sunset, 45, 30) || near(sun.sunrise, 30, 30)) return 'golden'; + return now > sun.sunrise && now < sun.sunset ? 'day' : 'night'; + } +} + /** * The next thing to look up for (sunrise.md R1): the sunrise of the next invitation's * day while it is still ahead, otherwise the invitation itself. Built on diff --git a/packages/engine/test/scene.test.ts b/packages/engine/test/scene.test.ts new file mode 100644 index 0000000..e382257 --- /dev/null +++ b/packages/engine/test/scene.test.ts @@ -0,0 +1,36 @@ +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import { petalsOn, weedsOn } from '../src/rose/rose.js'; +import { petalsToday, weedsToday } from '../src/scene/scene.js'; +import { addDays } from '../src/time/localDay.js'; + +const KEY = 'K'.repeat(43); +const days = Array.from({ length: 120 }, (_, i) => addDays('2026-01-01', i)); + +describe('what the planet garden shows of her day (planet-garden.md G3)', () => { + it('weeds: none on a day without, 2–4 on a day with', () => { + for (const day of days) { + const n = weedsToday(KEY, day); + expect(n === 0 ? !weedsOn(KEY, day) : weedsOn(KEY, day) && n >= 2 && n <= 4).toBe(true); + } + expect(new Set(days.map((d) => weedsToday(KEY, d)).filter(Boolean)).size).toBeGreaterThan(1); + }); + + it('fallen petals: none on a day without, 3–5 on a day with', () => { + for (const day of days) { + const n = petalsToday(KEY, day); + expect(n === 0 ? !petalsOn(KEY, day) : petalsOn(KEY, day) && n >= 3 && n <= 5).toBe(true); + } + }); + + it('property: the same rose on the same day always shows the same count', () => { + fc.assert( + fc.property(fc.stringMatching(/^[A-Za-z0-9_-]{43}$/), fc.integer({ min: 0, max: 3000 }), (key, offset) => { + const day = addDays('2026-01-01', offset); + expect(weedsToday(key, day)).toBe(weedsToday(key, day)); + expect(petalsToday(key, day)).toBe(petalsToday(key, day)); + }), + { numRuns: 200 } + ); + }); +}); diff --git a/packages/engine/test/sun.test.ts b/packages/engine/test/sun.test.ts index 2fd582c..92aa84a 100644 --- a/packages/engine/test/sun.test.ts +++ b/packages/engine/test/sun.test.ts @@ -1,7 +1,7 @@ import fc from 'fast-check'; import { readFileSync } from 'node:fs'; import { describe, expect, it } from 'vitest'; -import { invitation, nextInvitation, nextSunEvent, sunDay, type Place, type SunDay } from '../src/sun/sun.js'; +import { invitation, lightAt, nextInvitation, nextSunEvent, sunDay, type Place, type SunDay } from '../src/sun/sun.js'; import { addDays, localDay } from '../src/time/localDay.js'; /** Recorded by scripts/fetch-sun-golden.ts from the U.S. Naval Observatory. */ @@ -317,3 +317,27 @@ describe('nextSunEvent — the next thing to look up for (sunrise.md)', () => { ); }); }); + +describe('lightAt — the sky over her planet (planet-garden.md)', () => { + const brno: Place = { lat: 49.1951, lon: 16.6068, timeZone: 'Europe/Prague' }; + const day = sunDay('2026-03-02', brno); + if (day.kind !== 'sun-sets') throw new Error('Brno has a sunset in March'); + + it('night before dawn, golden at sunrise, day at noon, golden at sunset, night after', () => { + expect(lightAt(day.sunrise - 2 * HOUR, brno)).toBe('night'); + expect(lightAt(day.sunrise, brno)).toBe('golden'); + expect(lightAt(day.solarNoon, brno)).toBe('day'); + expect(lightAt(day.sunset - 30 * MINUTE, brno)).toBe('golden'); + expect(lightAt(day.sunset + 2 * HOUR, brno)).toBe('night'); + }); + + it('polar day is day, golden around the lowest light; polar night is night, golden at noon', () => { + const tromso: Place = { lat: 69.6492, lon: 18.9553, timeZone: 'Europe/Oslo' }; + const summer = sunDay('2026-06-21', tromso); + const winter = sunDay('2026-12-21', tromso); + if (summer.kind !== 'polar-day' || winter.kind !== 'polar-night') throw new Error('Tromsø: polar day and night'); + expect(lightAt(summer.solarNoon, tromso)).toBe('day'); + expect(lightAt(winter.solarNoon, tromso)).toBe('golden'); + expect(lightAt(winter.solarNoon + 4 * HOUR, tromso)).toBe('night'); + }); +}); diff --git a/packages/schema/schemas/gardener.schema.json b/packages/schema/schemas/gardener.schema.json new file mode 100644 index 0000000..d6e2669 --- /dev/null +++ b/packages/schema/schemas/gardener.schema.json @@ -0,0 +1,17 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://rosea.invalid/schema/gardener.json", + "title": "Gardener", + "description": "The look of the player's gardener, chosen at the first open (.agents/features/planet-garden.md G6). Every value is from a fixed list: no free text, nothing that identifies a person. Kept on the device in `profile`; never sent, never in the rose file. No option recreates the book's boy: there is no scarf, coat, cape, suit or crown to choose.", + "type": "object", + "additionalProperties": false, + "required": ["presentation", "skin", "hair", "hairColour", "clothes", "hat"], + "properties": { + "presentation": { "enum": ["girl", "boy"] }, + "skin": { "enum": ["skin-1", "skin-2", "skin-3", "skin-4", "skin-5", "skin-6"] }, + "hair": { "enum": ["short", "curly", "ponytail", "braids", "bob", "bun"] }, + "hairColour": { "enum": ["black", "dark-brown", "brown", "auburn", "red", "fair"] }, + "clothes": { "enum": ["sage", "rose", "honey", "dusk", "plum"] }, + "hat": { "enum": ["straw-hat", "cap", "none"] } + } +} diff --git a/packages/schema/src/gardener.ts b/packages/schema/src/gardener.ts new file mode 100644 index 0000000..d1d84d7 --- /dev/null +++ b/packages/schema/src/gardener.ts @@ -0,0 +1,15 @@ +/** + * The gardener's fixed lists, read from gardener.schema.json itself, so the choice the player + * sees, the shape storage checks and the contract can never disagree (planet-garden.md G6). + */ +import schema from '../schemas/gardener.schema.json' with { type: 'json' }; +import type { Gardener } from './generated/index.js'; + +type Options = { readonly [K in keyof Gardener]: readonly Gardener[K][] }; + +export const GARDENER_OPTIONS: Options = Object.fromEntries( + Object.entries(schema.properties).map(([k, v]) => [k, v.enum]) +) as unknown as Options; + +/** The order the choice asks in. */ +export const GARDENER_FIELDS = schema.required as readonly (keyof Gardener)[]; diff --git a/packages/schema/src/index.ts b/packages/schema/src/index.ts index 9aff762..a99d1a4 100644 --- a/packages/schema/src/index.ts +++ b/packages/schema/src/index.ts @@ -1,2 +1,3 @@ export * from './constants.js'; export type * from './generated/index.js'; +export { GARDENER_FIELDS, GARDENER_OPTIONS } from './gardener.js'; diff --git a/packages/schema/src/validate.ts b/packages/schema/src/validate.ts index efb35d8..9fcc89e 100644 --- a/packages/schema/src/validate.ts +++ b/packages/schema/src/validate.ts @@ -9,10 +9,11 @@ */ import { Ajv, type ErrorObject, type ValidateFunction } from 'ajv'; import careEvent from '../schemas/care-event.schema.json' with { type: 'json' }; +import gardener from '../schemas/gardener.schema.json' with { type: 'json' }; import hopeSentence from '../schemas/hope-sentence.schema.json' with { type: 'json' }; import sentenceOpened from '../schemas/sentence-opened.schema.json' with { type: 'json' }; import trace from '../schemas/trace.schema.json' with { type: 'json' }; -import type { CareEvent, HopeSentence, SentenceOpened, Trace } from './generated/index.js'; +import type { CareEvent, Gardener, HopeSentence, SentenceOpened, Trace } from './generated/index.js'; export type SchemaResult = | { readonly ok: true; readonly value: T } @@ -40,4 +41,5 @@ function describe(error: ErrorObject): string { export const validateHopeSentence = wrap(ajv.compile(hopeSentence)); export const validateCareEvent = wrap(ajv.compile(careEvent)); export const validateSentenceOpened = wrap(ajv.compile(sentenceOpened)); +export const validateGardener = wrap(ajv.compile(gardener)); export const validateTrace = wrap(ajv.compile(trace)); diff --git a/packages/storage/src/index.ts b/packages/storage/src/index.ts index 7b31263..3eaea62 100644 --- a/packages/storage/src/index.ts +++ b/packages/storage/src/index.ts @@ -12,7 +12,7 @@ import Dexie, { type DexieOptions, type Table } from 'dexie'; import { newCare, newOpened, type NamedPlace } from '@rosea/engine'; import { isIdentity, type Identity } from '@rosea/identity'; -import { DATABASE_NAME, type CareEvent, type SentenceOpened } from '@rosea/schema'; +import { DATABASE_NAME, GARDENER_FIELDS, GARDENER_OPTIONS, type CareEvent, type Gardener, type SentenceOpened } from '@rosea/schema'; export { DATABASE_NAME }; @@ -34,6 +34,17 @@ interface KeyRow { } const SUNSET_PLACE = 'sunsetPlace'; +const GARDENER = 'gardener'; + +/** The shape check for a stored gardener: exactly the six fields, each from its list. */ +export function asGardener(value: unknown): Gardener | null { + if (typeof value !== 'object' || value === null) return null; + const v = value as Record; + const keys = GARDENER_FIELDS; + if (Object.keys(v).length !== keys.length) return null; + for (const k of keys) if (!(GARDENER_OPTIONS[k] as readonly unknown[]).includes(v[k])) return null; + return Object.fromEntries(keys.map((k) => [k, v[k]])) as unknown as Gardener; +} const SELF = 'self'; const PAST_KEYS = 'pastKeys'; @@ -55,6 +66,9 @@ export interface RoseFile { export interface Storage { /** The saved sunset place, or null if the player has not answered yet. */ loadSunsetPlace(): Promise; + /** The player's gardener, or null before they chose one (planet-garden.md G6). */ + loadGardener(): Promise; + saveGardener(look: Gardener): Promise; saveSunsetPlace(place: SunsetPlace): Promise; /** Appends one act of care. The log is never edited or shortened. */ appendCare(event: CareEvent): Promise; @@ -194,7 +208,7 @@ class RoseaDatabase extends Dexie { } /** What another tab changed (two-tabs.md W2): only which part, never the data. */ -export type Change = 'log' | 'place'; +export type Change = 'log' | 'place' | 'gardener'; /** The channel every tab of the garden announces its writes on (two-tabs.md W1). */ export const CHANGES_CHANNEL = `${DATABASE_NAME}-changes`; @@ -213,7 +227,7 @@ export function openStorage(options?: DexieOptions, settings: { readonly channel if (channel) { channel.onmessage = (message: MessageEvent) => { const what = message.data; - if (what !== 'log' && what !== 'place') return; + if (what !== 'log' && what !== 'place' && what !== 'gardener') return; for (const listener of listeners) { try { listener(what); @@ -250,6 +264,19 @@ export function openStorage(options?: DexieOptions, settings: { readonly channel await db.profile.put({ key: SUNSET_PLACE, value: plain }); announce('place'); }, + async loadGardener() { + const row = await db.profile.get(GARDENER); + if (row === undefined) return null; + const look = asGardener(row.value); + if (look === null) console.warn('storage: the saved gardener has an unknown shape; asking again', row.value); + return look; + }, + async saveGardener(look) { + const plain = asGardener(look); + if (plain === null) throw new TypeError('storage: refusing to save a gardener of an unknown shape'); + await db.profile.put({ key: GARDENER, value: plain }); + announce('gardener'); + }, async appendCare(event) { const plain = asCareEvent(event); if (plain === null) throw new TypeError('storage: refusing to append a care event of an unknown shape'); diff --git a/packages/storage/test/gardener.test.ts b/packages/storage/test/gardener.test.ts new file mode 100644 index 0000000..4beb3d8 --- /dev/null +++ b/packages/storage/test/gardener.test.ts @@ -0,0 +1,71 @@ +import { GARDENER_FIELDS, GARDENER_OPTIONS, type Gardener } from '@rosea/schema'; +import { validateGardener } from '@rosea/schema/validate'; +import { IDBFactory, IDBKeyRange } from 'fake-indexeddb'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { asGardener, openStorage, type Change, type Storage } from '../src/index.js'; + +const look: Gardener = { presentation: 'girl', skin: 'skin-3', hair: 'braids', hairColour: 'auburn', clothes: 'sage', hat: 'straw-hat' }; +const KEY = 'K'.repeat(87); + +const opened: Storage[] = []; +const open = (indexedDB: IDBFactory = new IDBFactory(), channel: string | null = null): Storage => { + const s = openStorage({ indexedDB, IDBKeyRange }, { channel }); + opened.push(s); + return s; +}; +afterEach(() => { + for (const s of opened.splice(0)) s.close(); + vi.restoreAllMocks(); +}); + +describe('the gardener (planet-garden.md G6)', () => { + it('is null before the player chose, then kept across a reopen', async () => { + const factory = new IDBFactory(); + const s = open(factory); + expect(await s.loadGardener()).toBeNull(); + await s.saveGardener(new Proxy(look, {})); + s.close(); + expect(await open(factory).loadGardener()).toEqual(look); + }); + + it('refuses a value off its list, a missing field, an extra field, or free text', async () => { + const s = open(); + for (const bad of [ + { ...look, hat: 'crown' }, + { ...look, clothes: 'green suit' }, + { ...look, extra: 'a scarf' }, + (({ hat: _, ...rest }) => rest)(look), + { ...look, presentation: 'Marek' } + ]) { + await expect(s.saveGardener(bad as unknown as Gardener)).rejects.toThrow(/unknown shape/); + } + expect(await s.loadGardener()).toBeNull(); + }); + + it('the hand check, the schema and the lists agree', () => { + expect([...GARDENER_FIELDS].sort()).toEqual(Object.keys(GARDENER_OPTIONS).sort()); + for (const k of GARDENER_FIELDS) { + for (const v of GARDENER_OPTIONS[k]) expect(validateGardener({ ...look, [k]: v }).ok).toBe(true); + expect(asGardener({ ...look, [k]: 'other' })).toBeNull(); + expect(validateGardener({ ...look, [k]: 'other' }).ok).toBe(false); + } + expect(asGardener(look)).toEqual(look); + }); + + it('never offers what would recreate the book\'s boy', () => { + const everything = JSON.stringify(GARDENER_OPTIONS).toLowerCase(); + for (const word of ['scarf', 'coat', 'cape', 'suit', 'crown', 'sword', 'golden']) expect(everything).not.toContain(word); + }); + + it('is announced to the other tabs, and never travels in the rose file', async () => { + const factory = new IDBFactory(); + const a = open(factory, 'rosea-test-gardener'); + const b = open(factory, 'rosea-test-gardener'); + const heard: Change[] = []; + b.onChange((w) => heard.push(w)); + await a.saveGardener(look); + await new Promise((r) => setTimeout(r, 100)); + expect(heard).toEqual(['gardener']); + expect(JSON.stringify(await a.exportRose(KEY))).not.toMatch(/braids|auburn|skin-3|gardener/); + }); +}); diff --git a/packages/ui/src/Shell.svelte b/packages/ui/src/Shell.svelte index 6996b68..4f0358f 100644 --- a/packages/ui/src/Shell.svelte +++ b/packages/ui/src/Shell.svelte @@ -1,5 +1,5 @@ + + + + + + diff --git a/packages/ui/src/scene/GardenerChoice.svelte b/packages/ui/src/scene/GardenerChoice.svelte new file mode 100644 index 0000000..370f757 --- /dev/null +++ b/packages/ui/src/scene/GardenerChoice.svelte @@ -0,0 +1,177 @@ + + +
+

{en.gardener.question}

+

{en.gardener.why}

+ + + + +
{ + e.preventDefault(); + onchoose({ ...look }); + }} + > + {#each GARDENER_FIELDS as field (field)} +
+ {en.gardener.labels[field]} +
+ {#each GARDENER_OPTIONS[field] as value (value)} + + {/each} +
+
+ {/each} +
+ + {#if oncancel}{/if} +
+
+
+ + diff --git a/packages/ui/src/scene/Planet.svelte b/packages/ui/src/scene/Planet.svelte new file mode 100644 index 0000000..cf879a8 --- /dev/null +++ b/packages/ui/src/scene/Planet.svelte @@ -0,0 +1,427 @@ + + + + +
+ { + if (petals > 0) start(e, { kind: 'sweep', samples: [point(e)] }); + }} + onpointermove={move} + onpointerup={end} + onpointercancel={() => { + if (drag?.kind === 'can') onpourend(); + drag = null; + windbreakAt = null; + }} + > + + + + + + + + + + + + + + {#if wind} + + {/if} + + + + {#each [-58, -52, -46, 46, 52] as a (a)} + {@const s = surface(a, 3)} + + {/each} + + + + + + start(e, { kind: 'rose', samples: [point(e)] })} + onkeydown={(e) => { + if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault(); + if (!e.repeat) onrose(); + } + }} + /> + + + {#each WEED_AT.slice(0, weeds) as a, i (a)} + {#if !pulled.has(i)} + {@const s = surface(a, 1)} + start(e, { kind: 'weed', index: i, samples: [point(e)] })} + > + + + + {/if} + {/each} + + + {#each PETAL_AT.slice(0, petals) as a (a)} + {@const s = surface(a, 2)} + + {/each} + + + {#if wind} + + {@const at = windbreakAt ?? resting} + start(e, { kind: 'windbreak', samples: [point(e)] })} + > + + {#each [-12, -6, 0, 6, 12] as x (x)}{/each} + + {/if} + + + {#if !pouring} + start(e, { kind: 'can', samples: [point(e)] })} + > + + + + + {:else} + {@const p = surface(-6, 40)} + + {/if} + + + + + + + + +

{said}

+
+ + diff --git a/packages/ui/src/scene/gestures.ts b/packages/ui/src/scene/gestures.ts new file mode 100644 index 0000000..46c168c --- /dev/null +++ b/packages/ui/src/scene/gestures.ts @@ -0,0 +1,78 @@ +/** + * The planet garden's gestures (.agents/features/planet-garden.md G2): pure functions of + * pointer samples, in the scene's own units. They read the player's hand; every rule about + * what care does stays in the engine. + */ + +export interface Sample { + readonly x: number; + readonly y: number; + /** Milliseconds. */ + readonly t: number; +} + +export interface Box { + readonly x0: number; + readonly y0: number; + readonly x1: number; + readonly y1: number; +} + +/** The thresholds, generous on purpose: a missed gesture must never feel like failing. */ +export const GESTURE = { + /** Sideways travel before the can starts to tip, and at which it pours fastest. */ + tiltStart: 12, + tiltFull: 140, + /** A pull: this far up, mostly upwards, within this long. */ + pullUp: 48, + pullMs: 2000, + /** A sweep: this far sideways, no more than this far up or down. */ + sweepAcross: 110, + sweepDrift: 70, + /** A stroke: this much travel, taking at least this long (a tap is quicker and shorter). */ + strokeTravel: 30, + strokeMs: 220, + tapTravel: 10 +} as const; + +const first = (s: readonly Sample[]): Sample => s[0] ?? { x: 0, y: 0, t: 0 }; +const last = (s: readonly Sample[]): Sample => s[s.length - 1] ?? first(s); +const travel = (s: readonly Sample[]): number => + s.reduce((sum, p, i) => (i === 0 ? 0 : sum + Math.hypot(p.x - s[i - 1]!.x, p.y - s[i - 1]!.y)), 0); + +/** How far the can is tipped, 0 to 1, from how far the hand has moved sideways since pressing. */ +export function tiltOf(start: Sample, now: Sample): number { + const dx = Math.abs(now.x - start.x); + if (dx <= GESTURE.tiltStart) return 0; + return Math.min(1, (dx - GESTURE.tiltStart) / (GESTURE.tiltFull - GESTURE.tiltStart)); +} + +/** How fast a can tipped by `tilt` pours, as a multiple of a steady hold (the button's pour). */ +export const pourRate = (tilt: number): number => 0.4 + 1.1 * Math.min(1, Math.max(0, tilt)); + +/** Whether the samples pull a weed: up far enough, mostly upwards, quickly enough. */ +export function isPull(samples: readonly Sample[]): boolean { + const a = first(samples), b = last(samples); + const up = a.y - b.y; + return up >= GESTURE.pullUp && Math.abs(b.x - a.x) <= up && b.t - a.t <= GESTURE.pullMs; +} + +/** Whether the samples sweep across everything between `from` and `to` on the x axis. */ +export function isSweep(samples: readonly Sample[], from: number, to: number): boolean { + if (samples.length < 2) return false; + const xs = samples.map((p) => p.x), ys = samples.map((p) => p.y); + const across = Math.abs(last(samples).x - first(samples).x); + const lo = Math.min(...xs), hi = Math.max(...xs); + const covers = lo <= Math.min(from, to) && hi >= Math.max(from, to); + return across >= GESTURE.sweepAcross && Math.max(...ys) - Math.min(...ys) <= GESTURE.sweepDrift && covers; +} + +export const inside = (p: Pick, b: Box): boolean => p.x >= b.x0 && p.x <= b.x1 && p.y >= b.y0 && p.y <= b.y1; + +/** A slow stroke across her petals, a quick tap, or neither. */ +export function strokeOf(samples: readonly Sample[]): 'stroke' | 'tap' | 'none' { + const moved = travel(samples); + const took = last(samples).t - first(samples).t; + if (moved <= GESTURE.tapTravel) return 'tap'; + return moved >= GESTURE.strokeTravel && took >= GESTURE.strokeMs ? 'stroke' : 'none'; +} diff --git a/packages/ui/src/scene/look.ts b/packages/ui/src/scene/look.ts new file mode 100644 index 0000000..f5c6700 --- /dev/null +++ b/packages/ui/src/scene/look.ts @@ -0,0 +1,4 @@ +import type { Gardener } from '@rosea/schema'; + +/** The gardener the choice starts from, and who tends her if the device could not keep a choice. */ +export const FIRST_LOOK: Gardener = { presentation: 'girl', skin: 'skin-3', hair: 'braids', hairColour: 'brown', clothes: 'sage', hat: 'straw-hat' }; diff --git a/packages/ui/src/tokens.css b/packages/ui/src/tokens.css index 3a919f6..3a811bf 100644 --- a/packages/ui/src/tokens.css +++ b/packages/ui/src/tokens.css @@ -36,6 +36,9 @@ body { color: var(--ink); font-family: var(--font-body); line-height: 1.5; + /* Android Chrome paints a blue box behind a touched control (seen on a real tablet, + 2026-11-17); our controls show their own pressed and focus states instead. */ + -webkit-tap-highlight-color: transparent; } @media (prefers-reduced-motion: reduce) { diff --git a/packages/ui/test/gardener.test.ts b/packages/ui/test/gardener.test.ts new file mode 100644 index 0000000..6a8c0d5 --- /dev/null +++ b/packages/ui/test/gardener.test.ts @@ -0,0 +1,81 @@ +import type { Gardener } from '@rosea/schema'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/svelte'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import Shell from '../src/Shell.svelte'; +import { en } from '../src/copy/en.js'; +import type { RoseWiring } from '../src/rose/types.js'; + +const ZONE = 'Europe/Prague'; +const MORNING = Date.parse('2026-03-01T09:00:00+01:00'); +const saved: Gardener = { presentation: 'boy', skin: 'skin-5', hair: 'curly', hairColour: 'black', clothes: 'dusk', hat: 'cap' }; + +function rose(gardener: RoseWiring['gardener'] | undefined): RoseWiring { + return { + identity: async () => ({ publicKey: 'M'.repeat(87), kept: true }), + loadCare: async () => [], + appendCare: async () => undefined, + sentences: [], + loadOpened: async () => [], + appendOpened: async () => undefined, + clientVersion: '0.1.0', + deviceZone: ZONE, + now: () => MORNING, + pastKeys: async () => [], + exportRose: async () => ({}), + importRose: async () => ({ added: 0, petals: 0 }), + saveFile: () => undefined, + keeping: { persisted: async () => false, persist: async () => true }, + installHint: false, + ...(gardener ? { gardener } : {}) + }; +} + +afterEach(() => { + vi.restoreAllMocks(); + cleanup(); +}); + +describe('who tends her (planet-garden.md §1)', () => { + it('the first open asks before the garden; the choice is kept and the garden opens', async () => { + const saves: Gardener[] = []; + render(Shell, { rose: rose({ load: async () => null, save: async (g) => void saves.push(g) }) }); + expect(await screen.findByRole('heading', { level: 2, name: en.gardener.question })).toBeTruthy(); + expect(screen.queryByRole('button', { name: en.rose.care })).toBeNull(); + await fireEvent.click(screen.getByLabelText(en.gardener.values.presentation.boy)); + await fireEvent.click(screen.getByLabelText(en.gardener.values.hair.curly)); + await fireEvent.click(screen.getByLabelText(en.gardener.values.hat.cap)); + await fireEvent.click(screen.getByRole('button', { name: en.gardener.done })); + expect(saves).toEqual([{ presentation: 'boy', skin: 'skin-3', hair: 'curly', hairColour: 'brown', clothes: 'sage', hat: 'cap' }]); + expect(await screen.findByRole('button', { name: en.rose.care })).toBeTruthy(); + expect(screen.queryByRole('heading', { name: en.gardener.question })).toBeNull(); + }); + + it('a saved gardener: no question; Change gardener opens it with their choices, and Close keeps them', async () => { + const save = vi.fn(async () => undefined); + render(Shell, { rose: rose({ load: async () => saved, save }) }); + await screen.findByRole('button', { name: en.rose.care }); + expect(screen.queryByRole('heading', { name: en.gardener.question })).toBeNull(); + await fireEvent.click(screen.getByRole('button', { name: en.gardener.change })); + expect((screen.getByLabelText(en.gardener.values.presentation.boy) as HTMLInputElement).checked).toBe(true); + expect((screen.getByLabelText(en.gardener.values.skin['skin-5']) as HTMLInputElement).checked).toBe(true); + await fireEvent.click(screen.getByRole('button', { name: en.scene.close })); + expect(await screen.findByRole('button', { name: en.rose.care })).toBeTruthy(); + expect(save).not.toHaveBeenCalled(); + }); + + it('a device that cannot keep the choice: the garden still opens, and says it will ask again', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined); + render(Shell, { rose: rose({ load: async () => null, save: () => Promise.reject(new Error('IndexedDB blocked')) }) }); + await fireEvent.click(await screen.findByRole('button', { name: en.gardener.done })); + expect(await screen.findByRole('button', { name: en.rose.care })).toBeTruthy(); + await waitFor(() => expect(screen.getByText(en.gardener.notKept)).toBeTruthy()); + expect(error).toHaveBeenCalled(); + }); + + it('without a place to keep a gardener, the garden asks nothing', async () => { + render(Shell, { rose: rose(undefined) }); + expect(await screen.findByRole('button', { name: en.rose.care })).toBeTruthy(); + expect(screen.queryByRole('heading', { name: en.gardener.question })).toBeNull(); + expect(screen.queryByRole('button', { name: en.gardener.change })).toBeNull(); + }); +}); diff --git a/packages/ui/test/gestures.test.ts b/packages/ui/test/gestures.test.ts new file mode 100644 index 0000000..2bba82b --- /dev/null +++ b/packages/ui/test/gestures.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from 'vitest'; +import { GESTURE, inside, isPull, isSweep, pourRate, strokeOf, tiltOf, type Sample } from '../src/scene/gestures.js'; + +const at = (x: number, y: number, t = 0): Sample => ({ x, y, t }); +/** A straight line from a to b in `n` steps over `ms`. */ +const line = (a: Sample, b: Sample, ms: number, n = 10): Sample[] => + Array.from({ length: n + 1 }, (_, i) => ({ x: a.x + ((b.x - a.x) * i) / n, y: a.y + ((b.y - a.y) * i) / n, t: (ms * i) / n })); + +describe('tilting the can (planet-garden.md G4)', () => { + it('a little movement does not tip it; far enough tips it fully; either way round', () => { + expect(tiltOf(at(100, 100), at(108, 100))).toBe(0); + expect(tiltOf(at(100, 100), at(100 + GESTURE.tiltFull, 100))).toBe(1); + expect(tiltOf(at(100, 100), at(100 - GESTURE.tiltFull, 100))).toBe(1); + expect(tiltOf(at(100, 100), at(176, 100))).toBeCloseTo(0.5, 1); + }); + + it('tilt stays within 0–1 and never falls as the hand moves further (every distance to 500)', () => { + let previous = 0; + for (let d = 0; d <= 500; d++) { + const t = tiltOf(at(0, 0), at(d, 0)); + expect(t).toBeGreaterThanOrEqual(previous); + expect(t).toBeLessThanOrEqual(1); + previous = t; + } + }); + + it('pours slower than a steady hold when barely tipped, faster when fully tipped', () => { + expect(pourRate(0)).toBeLessThan(1); + expect(pourRate(0.55)).toBeCloseTo(1, 1); + expect(pourRate(1)).toBeGreaterThan(1); + expect(pourRate(5)).toBe(pourRate(1)); + }); +}); + +describe('pulling a weed', () => { + it('up and quick enough pulls it; sideways, too short or too slow does not', () => { + expect(isPull(line(at(100, 200), at(104, 140), 300))).toBe(true); + expect(isPull(line(at(100, 200), at(180, 180), 300))).toBe(false); + expect(isPull(line(at(100, 200), at(100, 170), 300))).toBe(false); + expect(isPull(line(at(100, 200), at(100, 120), GESTURE.pullMs + 1))).toBe(false); + expect(isPull(line(at(100, 200), at(100, 280), 300))).toBe(false); + }); + + it('far enough up but more sideways than up is not a pull (only the direction decides)', () => { + expect(isPull(line(at(100, 200), at(200, 140), 300))).toBe(false); + expect(isPull(line(at(100, 200), at(150, 140), 300))).toBe(true); + }); +}); + +describe('sweeping the petals', () => { + it('a long sideways swipe across all of them gathers them, either direction', () => { + expect(isSweep(line(at(60, 300), at(260, 310), 400), 100, 220)).toBe(true); + expect(isSweep(line(at(260, 300), at(60, 290), 400), 100, 220)).toBe(true); + }); + + it('one that misses some, wanders up and down, or is too short does not', () => { + expect(isSweep(line(at(60, 300), at(180, 300), 400), 100, 220)).toBe(false); + expect(isSweep(line(at(60, 300), at(260, 420), 400), 100, 220)).toBe(false); + expect(isSweep([at(100, 300)], 100, 220)).toBe(false); + }); +}); + +describe('touching her', () => { + it('a slow stroke across her petals is a stroke; a short press is a tap; a flick is neither', () => { + expect(strokeOf(line(at(100, 100), at(160, 104), 600))).toBe('stroke'); + expect(strokeOf(line(at(100, 100), at(104, 102), 80))).toBe('tap'); + expect(strokeOf(line(at(100, 100), at(160, 100), 60))).toBe('none'); + }); +}); + +describe('dropping the windbreak', () => { + it('lands inside a box or not', () => { + const box = { x0: 40, y0: 100, x1: 120, y1: 200 }; + expect(inside(at(80, 150), box)).toBe(true); + expect(inside(at(130, 150), box)).toBe(false); + }); +}); diff --git a/packages/ui/test/petal.test.ts b/packages/ui/test/petal.test.ts index 4f6b577..fe8989f 100644 --- a/packages/ui/test/petal.test.ts +++ b/packages/ui/test/petal.test.ts @@ -98,7 +98,7 @@ describe('the folded petal (day-sentence.md)', () => { it('with an empty library: no petal, and she says nothing about one', async () => { const q = quietMoment(MORNING); render(Rose, { wiring: wiring({ log: q.log, at: q.now, sentences: [] }), timeZone: ZONE }); - await screen.findByRole('button', { name: en.rose.water }); + await screen.findByRole('button', { name: en.rose.care }); expect(screen.queryByRole('button', { name: en.rose.petal.open })).toBeNull(); expect(bubble()).not.toContain('petal'); }); diff --git a/packages/ui/test/planet.test.ts b/packages/ui/test/planet.test.ts new file mode 100644 index 0000000..2e97415 --- /dev/null +++ b/packages/ui/test/planet.test.ts @@ -0,0 +1,204 @@ +import { careEvent, localDay, petalsOn, petalsToday, weedsOn, weedsToday, windOn } from '@rosea/engine'; +import type { CareEvent } from '@rosea/schema'; +import { cleanup, fireEvent, render, screen } 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'; + +// jsdom has no PointerEvent: without it a test pointer carries no coordinates. Every browser has one. +if (typeof window.PointerEvent !== 'function') { + class PointerEventPolyfill extends MouseEvent { + readonly pointerId: number; + readonly pointerType: string; + constructor(type: string, init: PointerEventInit = {}) { + super(type, init); + this.pointerId = init.pointerId ?? 1; + this.pointerType = init.pointerType ?? 'touch'; + } + } + Object.assign(window, { PointerEvent: PointerEventPolyfill }); +} + +const ZONE = 'Europe/Prague'; +const ME = 'M'.repeat(87); +const DAY = 86_400_000; +const MINUTE = 60_000; +/** 1 March 2026, local midnight in Prague (CET, before the clocks change). */ +const MARCH = Date.parse('2026-03-01T00:00:00+01:00'); + +function wiring(at: number, log: CareEvent[] = []): RoseWiring & { appended: CareEvent[] } { + const appended: CareEvent[] = []; + return { + identity: async () => ({ publicKey: ME, kept: true }), + loadCare: async () => log, + appendCare: async (e) => void appended.push(e), + sentences: [], + loadOpened: async () => [], + appendOpened: async () => undefined, + clientVersion: '0.1.0', + deviceZone: ZONE, + now: () => at, + pastKeys: async () => [], + exportRose: async () => ({}), + importRose: async () => ({ added: 0, petals: 0 }), + saveFile: () => undefined, + keeping: { persisted: async () => false, persist: async () => true }, + installHint: false, + appended + }; +} + +/** The first morning in March for which `has` holds. */ +function morningWhen(has: (day: string) => boolean): number { + for (let i = 0; i < 27; i++) { + const at = MARCH + i * DAY + 9 * 60 * MINUTE; + if (has(localDay(at, ZONE))) return at; + } + throw new Error('no such day in March'); +} + +/** + * A pointer moving from a to b on `target`, then let go on the scene, as a finger does. jsdom stamps + * events with the real clock, so `ms` is waited for real when a gesture's speed matters. + */ +async function gesture(target: Element, a: [number, number], b: [number, number], ms = 0, steps = 6): Promise { + const scene = screen.getByRole('group', { name: en.scene.planet }); + await fireEvent.pointerDown(target, { pointerId: 1, clientX: a[0], clientY: a[1] }); + for (let i = 1; i <= steps; i++) { + if (ms > 0) await new Promise((r) => setTimeout(r, ms / steps)); + const x = a[0] + ((b[0] - a[0]) * i) / steps, y = a[1] + ((b[1] - a[1]) * i) / steps; + await fireEvent.pointerMove(scene, { pointerId: 1, clientX: x, clientY: y }); + } + await fireEvent.pointerUp(scene, { pointerId: 1, clientX: b[0], clientY: b[1] }); + await tick(); +} + +afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + cleanup(); +}); + +describe('her planet (planet-garden.md)', () => { + it('tapping her opens the ring of what she needs, with Touch her; Escape closes it and focus comes back to her', async () => { + render(Rose, { wiring: wiring(morningWhen((d) => !weedsOn(ME, d) && !petalsOn(ME, d))), timeZone: ZONE }); + const her = await screen.findByRole('button', { name: en.rose.care }); + expect(her.getAttribute('aria-expanded')).toBe('false'); + await fireEvent.keyDown(her, { key: 'Enter' }); + await tick(); + const ring = screen.getByRole('group', { name: en.scene.ring }); + expect(her.getAttribute('aria-expanded')).toBe('true'); + expect(document.activeElement?.textContent).toBe(en.rose.water); + expect(screen.getByRole('button', { name: en.rose.touch.label })).toBeTruthy(); + expect(screen.queryByRole('button', { name: en.rose.weed })).toBeNull(); + await fireEvent.keyDown(ring, { key: 'Escape' }); + await tick(); + expect(screen.queryByRole('group', { name: en.scene.ring })).toBeNull(); + expect(document.activeElement).toBe(her); + }); + + it('weeds: each one swiped up comes out; only when the last is out is it one act of care', async () => { + const at = morningWhen((d) => weedsOn(ME, d)); + const w = wiring(at); + render(Rose, { wiring: w, timeZone: ZONE }); + await screen.findByRole('button', { name: en.rose.care }); + const n = weedsToday(ME, localDay(at, ZONE)); + expect(screen.getAllByRole('img', { name: en.scene.weed })).toHaveLength(n); + + // A sideways swipe does not pull it. + await gesture(screen.getAllByRole('img', { name: en.scene.weed })[0]!, [200, 180], [280, 175]); + expect(screen.getAllByRole('img', { name: en.scene.weed })).toHaveLength(n); + + for (let pulled = 1; pulled <= n; pulled++) { + await gesture(screen.getAllByRole('img', { name: en.scene.weed })[0]!, [200, 180], [202, 110]); + expect(w.appended).toHaveLength(pulled === n ? 1 : 0); + } + expect(w.appended[0]?.act).toBe('weed'); + }); + + it('fallen petals: one sweep across all of them gathers them; a short swipe does not', async () => { + const at = morningWhen((d) => petalsOn(ME, d) && !weedsOn(ME, d)); + // Petals fall only once she has opened: four earlier days of helpful watering. + const opened = [4, 3, 2, 1].map((d) => careEvent({ now: at - d * DAY, timeZone: ZONE, from: ME, to: ME, act: 'water', amount: 0.5, clientVersion: '0.1.0' })); + const w = wiring(at, opened); + render(Rose, { wiring: w, timeZone: ZONE }); + await screen.findByRole('button', { name: en.rose.care }); + expect(screen.getAllByRole('img', { name: en.scene.petals })).toHaveLength(petalsToday(ME, localDay(at, ZONE))); + const scene = screen.getByRole('group', { name: en.scene.planet }); + await gesture(scene, [200, 160], [230, 160]); + expect(w.appended).toEqual([]); + await gesture(scene, [180, 160], [320, 170]); + expect(w.appended.map((e) => e.act)).toEqual(['petals']); + }); + + it('wind: the windbreak dragged to her windward side is shade; dropped elsewhere it goes back', async () => { + let at = 0; + for (let i = 0; i < 27 && !at; i++) { + const day = localDay(MARCH + i * DAY + 12 * 60 * MINUTE, ZONE); + const wind = windOn(ME, day); + if (wind && !petalsOn(ME, day)) at = MARCH + i * DAY + (wind[0] + 10) * MINUTE; + } + expect(at).toBeGreaterThan(0); + const w = wiring(at); + render(Rose, { wiring: w, timeZone: ZONE }); + const windbreak = await screen.findByRole('img', { name: en.scene.windbreak }); + await gesture(windbreak, [258, 250], [330, 380]); + expect(w.appended).toEqual([]); + await gesture(screen.getByRole('img', { name: en.scene.windbreak }), [258, 250], [140, 150]); + expect(w.appended.map((e) => e.act)).toEqual(['shade']); + }); + + it('the can: pressed and tilted far, it pours faster than a steady hold', async () => { + const at = morningWhen(() => true); + const w = wiring(at); + render(Rose, { wiring: w, timeZone: ZONE }); + const can = await screen.findByRole('img', { name: en.scene.can }); + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }); + const scene = screen.getByRole('group', { name: en.scene.planet }); + await fireEvent.pointerDown(can, { pointerId: 1, clientX: 100, clientY: 220 }); + await fireEvent.pointerMove(scene, { pointerId: 1, clientX: 260, clientY: 220 }); + vi.advanceTimersByTime(1000); + await fireEvent.pointerUp(scene, { pointerId: 1, clientX: 260, clientY: 220 }); + vi.useRealTimers(); + await tick(); + expect(w.appended[0]?.act).toBe('water'); + // A steady hold pours a third of a can in a second; fully tilted pours half again as fast. + expect(w.appended[0]?.amount).toBeGreaterThan(0.45); + }); + + it('a slow stroke across her petals touches her; nothing is written', async () => { + const w = wiring(morningWhen(() => true)); + render(Rose, { wiring: w, timeZone: ZONE }); + const her = await screen.findByRole('button', { name: en.rose.care }); + await gesture(her, [170, 100], [200, 104], 500); + expect(document.querySelector('.bubble')?.textContent).toBe(en.rose.touch.fond[0]); + expect(w.appended).toEqual([]); + expect(screen.queryByRole('group', { name: en.scene.ring })).toBeNull(); + }); + + /** Where the gardener stands now, in degrees round the world. */ + const gardenerAt = (): number => Number(/rotate\((-?[\d.]+)/.exec(document.querySelector('.walker')?.getAttribute('transform') ?? '')?.[1]); + + /** Asks the gardener to touch her (from the ring), and reads where they are straight after. */ + async function touchFromRing(): Promise { + await fireEvent.keyDown(await screen.findByRole('button', { name: en.rose.care }), { key: 'Enter' }); + await tick(); + await fireEvent.click(screen.getByRole('button', { name: en.rose.touch.label })); + await tick(); + return gardenerAt(); + } + + it('with reduced motion the gardener is at the work at once; otherwise still on the way', async () => { + render(Rose, { wiring: wiring(morningWhen(() => true)), timeZone: ZONE }); + expect(await touchFromRing()).toBeCloseTo(-28, 0); + cleanup(); + + vi.stubGlobal('matchMedia', (q: string) => ({ matches: q.includes('reduce'), media: q, addEventListener: () => undefined, removeEventListener: () => undefined })); + render(Rose, { wiring: wiring(morningWhen(() => true)), timeZone: ZONE }); + await screen.findByRole('button', { name: en.rose.care }); + expect(document.querySelector('.planet')?.classList.contains('reduced')).toBe(true); + expect(await touchFromRing()).toBe(-10); + }); +}); diff --git a/packages/ui/test/rose.test.ts b/packages/ui/test/rose.test.ts index 0690545..20d5317 100644 --- a/packages/ui/test/rose.test.ts +++ b/packages/ui/test/rose.test.ts @@ -44,8 +44,16 @@ function wiring(over: Partial & { log?: CareEvent[]; at?: number } = } const water = (now: number, amount: number): CareEvent => careEvent({ now, timeZone: ZONE, from: ME, to: ME, act: 'water', amount, clientVersion: '0.1.0' }); +/** Opens the ring of care, as a tap on her, or Enter on her, does (planet-garden.md G7). */ +async function openRing(): Promise { + if (screen.queryByRole('group', { name: en.scene.ring })) return; + await fireEvent.keyDown(await screen.findByRole('button', { name: en.rose.care }), { key: 'Enter' }); + await tick(); +} + /** Holds the Water button for `ms`, with the pour's own timer under control. */ async function hold(ms: number, how: 'pointer' | 'keyboard' = 'pointer'): Promise { + await openRing(); const button = screen.getByRole('button', { name: en.rose.water }); vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }); try { @@ -79,7 +87,7 @@ describe('the rose', () => { 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 screen.findByRole('img', { name: /^The rose/ }); await hold(1500); // half a can expect(screen.getByRole('status').textContent).toBe(en.rose.leavesLift); await release(); @@ -95,7 +103,7 @@ describe('the rose', () => { 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 screen.findByRole('img', { name: /^The rose/ }); await hold(3000); expect(screen.getByRole('status').textContent).toBe(en.rose.plenty); }); @@ -103,7 +111,7 @@ describe('the rose', () => { 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 screen.findByRole('img', { name: /^The rose/ }); await hold(1200, 'keyboard'); await release('keyboard'); expect(w.appended[0]).toMatchObject({ act: 'water', amount: 0.4 }); @@ -114,6 +122,7 @@ describe('the rose', () => { while (!weedsOn(ME, localDay(day, ZONE))) day += DAY; const w = wiring({ at: day }); render(Rose, { wiring: w, timeZone: ZONE }); + await openRing(); 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()); @@ -122,7 +131,8 @@ describe('the rose', () => { while (weedsOn(ME, localDay(clear, ZONE))) clear += DAY; cleanup(); render(Rose, { wiring: wiring({ at: clear }), timeZone: ZONE }); - await screen.findByRole('img'); + await screen.findByRole('img', { name: /^The rose/ }); + await openRing(); expect(screen.queryByRole('button', { name: en.rose.weed })).toBeNull(); }); @@ -130,7 +140,7 @@ describe('the rose', () => { 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(img.getAttribute('class')).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)); @@ -141,7 +151,7 @@ describe('the rose', () => { 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 screen.findByRole('img', { name: /^The rose/ }); await hold(1500); await release(); expect(await screen.findByText(en.rose.says.thanks)).toBeTruthy(); @@ -165,7 +175,7 @@ if (typeof File.prototype.text !== 'function') { describe('keep her safe (keep-her-safe.md)', () => { const OLD = 'O'.repeat(87); const open = async (): Promise => { - await screen.findByRole('img'); + await screen.findByRole('img', { name: /^The rose/ }); await fireEvent.click(screen.getByRole('button', { name: en.rose.safe.title })); }; diff --git a/packages/ui/test/touch.test.ts b/packages/ui/test/touch.test.ts index 6ba08f9..b0d6442 100644 --- a/packages/ui/test/touch.test.ts +++ b/packages/ui/test/touch.test.ts @@ -39,9 +39,18 @@ function wiring(log: CareEvent[] = []): RoseWiring & { clock: { now: number }; w const bubble = (): string => document.querySelector('.bubble')?.textContent ?? ''; +/** Opens the ring of care, where Touch her lives (planet-garden.md G7). */ +async function openRing(): Promise { + if (!screen.queryByRole('group', { name: en.scene.ring })) { + await fireEvent.keyDown(await screen.findByRole('button', { name: en.rose.care }), { key: 'Enter' }); + await tick(); + } + return screen.getByRole('button', { name: en.rose.touch.label }); +} + async function touchAt(w: ReturnType, at: number): Promise { w.clock.now = at; - await fireEvent.click(screen.getByRole('button', { name: en.rose.touch.label })); + await fireEvent.click(await openRing()); await tick(); } @@ -54,7 +63,7 @@ describe('touching her (thorns.md)', () => { it('a touch is answered fondly, then her usual line returns; nothing is written', async () => { const w = wiring(); render(Rose, { wiring: w, timeZone: ZONE }); - await screen.findByRole('button', { name: en.rose.touch.label }); + await openRing(); const usual = bubble(); vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); await touchAt(w, MORNING); @@ -70,7 +79,7 @@ describe('touching her (thorns.md)', () => { it('three quick taps: Gently. I have thorns. Taps while she rests change nothing', async () => { const w = wiring(); render(Rose, { wiring: w, timeZone: ZONE }); - await screen.findByRole('button', { name: en.rose.touch.label }); + await openRing(); vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); await touchAt(w, MORNING); await touchAt(w, MORNING + 500); @@ -84,7 +93,7 @@ describe('touching her (thorns.md)', () => { it('a held key is one touch, not a rush', async () => { const w = wiring(); render(Rose, { wiring: w, timeZone: ZONE }); - const button = await screen.findByRole('button', { name: en.rose.touch.label }); + const button = await openRing(); const repeat = new KeyboardEvent('keydown', { key: 'Enter', repeat: true, cancelable: true, bubbles: true }); button.dispatchEvent(repeat); expect(repeat.defaultPrevented).toBe(true); @@ -102,7 +111,7 @@ describe('touching her (thorns.md)', () => { w.clock.now = MORNING + 25 * DAY + 3 * 3_600_000; render(Rose, { wiring: w, timeZone: ZONE }); const img = await screen.findByRole('img', { name: /full bloom/ }); - expect(img.getAttribute('alt')).not.toMatch(/blushing/); + expect(img.getAttribute('aria-label')).not.toMatch(/blushing/); await touchAt(w, w.clock.now); expect(screen.getByRole('img', { name: /full bloom, blushing/ })).toBeTruthy(); }); diff --git a/packages/ui/test/two-tabs.test.ts b/packages/ui/test/two-tabs.test.ts index d7ed8af..e171b44 100644 --- a/packages/ui/test/two-tabs.test.ts +++ b/packages/ui/test/two-tabs.test.ts @@ -69,6 +69,8 @@ describe('two tabs, one garden (two-tabs.md)', () => { it("this tab's own care, still being written, is not lost when another tab's news arrives first", async () => { const w = roseWiring(); render(Rose, { wiring: w, timeZone: ZONE }); + // The ring of care opens on her (planet-garden.md G7); Water is in it. + await fireEvent.keyDown(await screen.findByRole('button', { name: en.rose.care }), { key: 'Enter' }); const button = await screen.findByRole('button', { name: en.rose.water }); vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }); await fireEvent.pointerDown(button, { pointerId: 1 }); diff --git a/scripts/android-smoke.ts b/scripts/android-smoke.ts new file mode 100644 index 0000000..2e2baee --- /dev/null +++ b/scripts/android-smoke.ts @@ -0,0 +1,171 @@ +/** + * `pnpm test:android` — the BUILT app on a real Android device over USB, by real touch. + * + * Needs: the device on USB debugging, the app built (`pnpm build`), and `vite preview` serving + * apps/rosea/dist on 127.0.0.1:4173 (`pnpm --filter @rosea/app exec vite preview --port 4173`). + * `ROSEA_ADB` names adb (default: on PATH); `ROSEA_ANDROID_SERIAL` names the device (default: + * the only one attached). Screenshots go to the folder given as the first argument. + * + * `adb reverse` maps the device's own localhost:4173 to this computer's 127.0.0.1:4173, so nothing + * listens on the network (CLAUDE.md §5.7), and Chrome treats localhost as secure, so the service + * worker runs as it will on the real host. Chrome is driven through its DevTools socket, as + * chrome://inspect does; every tap is Chrome's own touch input, so the gestures are a finger's. + * Offline is real: the mapping is removed, so the device cannot reach the server at all. + * + * It leaves the device as it found it, as the author asks: everything stored for + * http://localhost:4173 is deleted, the tab is closed, **Chrome is stopped**, the mappings removed. + */ +import { chromium, expect, type Browser, type Locator, type Page } from '@playwright/test'; +import { en } from '@rosea/ui/copy'; +import { execFileSync } from 'node:child_process'; +import { mkdirSync } from 'node:fs'; +import { join } from 'node:path'; + +const ADB = process.env['ROSEA_ADB'] ?? 'adb'; +const SERIAL = process.env['ROSEA_ANDROID_SERIAL']; +const URL = 'http://localhost:4173/Rosea/'; +const OUT = process.argv[2] ?? 'android-shots'; +mkdirSync(OUT, { recursive: true }); + +const adb = (...args: string[]): string => execFileSync(ADB, [...(SERIAL ? ['-s', SERIAL] : []), ...args], { encoding: 'utf8' }).trim(); +const results: string[] = []; +async function step(name: string, run: () => Promise): Promise { + const t = Date.now(); + try { + await run(); + results.push(`PASS ${name} (${((Date.now() - t) / 1000).toFixed(1)} s)`); + } catch (error) { + results.push(`FAIL ${name}: ${String(error).split('\n')[0]}`); + throw error; + } +} +const shot = (page: Page, name: string): Promise => page.screenshot({ path: join(OUT, `${name}.png`) }); + +/** A finger: touch down on the middle of `target`, move by (dx, dy) in `steps`, hold, lift. */ +async function finger(page: Page, target: Locator, o: { dx?: number; dy?: number; holdMs?: number; steps?: number; moveMs?: number } = {}): Promise { + await target.scrollIntoViewIfNeeded(); + const box = await target.boundingBox(); + if (!box) throw new Error('nothing to touch'); + const cdp = await page.context().newCDPSession(page); + const x = box.x + box.width / 2, y = box.y + box.height / 2; + const { dx = 0, dy = 0, holdMs = 60, steps = 0, moveMs = 0 } = o; + await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] }); + for (let i = 1; i <= steps; i++) { + if (moveMs) await page.waitForTimeout(moveMs / steps); + await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x: x + (dx * i) / steps, y: y + (dy * i) / steps }] }); + } + await page.waitForTimeout(holdMs); + await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }); + await cdp.detach(); +} + +console.log(`device: ${adb('shell', 'getprop', 'ro.product.model')} (${adb('get-serialno')})`); +let browser: Browser | undefined; +let page: Page | undefined; + +/** Chrome's DevTools socket comes up a moment after Chrome starts: try for half a minute. */ +async function connect(): Promise { + for (let i = 0; ; i++) { + try { + return await chromium.connectOverCDP('http://127.0.0.1:9222'); + } catch (error) { + if (i >= 30) throw error; + await new Promise((r) => setTimeout(r, 1000)); + } + } +} + +// Everything from the first mapping on is inside try, so the clean-up below always runs. +try { + adb('reverse', 'tcp:4173', 'tcp:4173'); + adb('forward', 'tcp:9222', 'localabstract:chrome_devtools_remote'); + adb('shell', 'am', 'start', '-a', 'android.intent.action.VIEW', '-d', URL, 'com.android.chrome'); + browser = await connect(); + const context = browser.contexts()[0]; + if (!context) throw new Error('Chrome on the device has no context'); + for (let i = 0; i < 30 && !page; i++) { + page = context.pages().find((p) => p.url().startsWith(URL)); + if (!page) await new Promise((r) => setTimeout(r, 1000)); + } + if (!page) throw new Error(`Chrome did not open ${URL}`); + const tab: Page = page; + + await step('opens the built app under /Rosea/; the service worker takes control', async () => { + await expect(tab.getByRole('heading', { level: 1 })).toHaveText('Rosea Domi', { timeout: 30_000 }); + await tab.waitForFunction(() => navigator.serviceWorker.ready.then(() => true), null, { timeout: 30_000 }); + await tab.waitForFunction(() => navigator.serviceWorker.controller !== null, null, { timeout: 30_000 }); + }); + + await step('Who tends her? A boy, by touch, then This is me', async () => { + await expect(tab.getByRole('heading', { level: 2, name: en.gardener.question })).toBeVisible({ timeout: 15_000 }); + await shot(tab, '1-who-tends-her'); + await finger(tab, tab.getByText(en.gardener.values.presentation.boy, { exact: true })); + await finger(tab, tab.getByText(en.gardener.values.hat.cap, { exact: true })); + await finger(tab, tab.getByRole('button', { name: en.gardener.done })); + await expect(tab.getByRole('group', { name: en.scene.planet })).toBeVisible(); + }); + + await step('chooses Brno: the line names the next sunrise or sunset', async () => { + await tab.getByRole('searchbox', { name: en.sunset.searchLabel }).fill('brno'); + await finger(tab, tab.getByRole('button', { name: /^Brno/ }).first()); + await expect(tab.locator('.sun p').first()).toHaveText(/(rises|sets) at .* in Brno\.$/); + await shot(tab, '2-planet'); + }); + + await step('a tap on her opens the ring of care; Close closes it', async () => { + await finger(tab, tab.getByRole('button', { name: en.rose.care })); + await expect(tab.getByRole('group', { name: en.scene.ring })).toBeVisible(); + await shot(tab, '3-ring'); + await finger(tab, tab.getByRole('button', { name: en.scene.close })); + await expect(tab.getByRole('group', { name: en.scene.ring })).toHaveCount(0); + }); + + await step('pressing the can and tilting it by finger pours: she thanks the player', async () => { + await finger(tab, tab.getByRole('img', { name: en.scene.can }), { dx: 90, steps: 6, moveMs: 300, holdMs: 1300 }); + await expect(tab.getByText(en.rose.says.thanks)).toBeVisible(); + await shot(tab, '4-watered'); + }); + + await step('a slow stroke across her petals touches her', async () => { + await tab.waitForTimeout(400); + await finger(tab, tab.getByRole('button', { name: en.rose.care }), { dx: 30, dy: -20, steps: 6, moveMs: 500 }); + await expect(tab.locator('.bubble')).toHaveText(en.rose.touch.fond[0]!); + }); + + await step('OFFLINE: with the server unreachable, a reload brings back the planet, the gardener, her care and the town', async () => { + adb('reverse', '--remove', 'tcp:4173'); + await tab.reload(); + await expect(tab.getByRole('group', { name: en.scene.planet })).toBeVisible({ timeout: 30_000 }); + await expect(tab.getByRole('heading', { name: en.gardener.question })).toHaveCount(0); + await expect(tab.locator('.sun p').first()).toHaveText(/in Brno\.$/); + await finger(tab, tab.getByRole('button', { name: en.rose.numbers })); + await expect(tab.locator('#rose-numbers')).toContainText(`${en.rose.daysOfCare}1`); + await shot(tab, '5-offline'); + }); +} finally { + // Leave the device as it was: nothing of this origin stays behind, and Chrome is stopped. + if (page) try { + await page.evaluate(async () => { + for (const r of await navigator.serviceWorker.getRegistrations()) await r.unregister(); + for (const k of await caches.keys()) await caches.delete(k); + await new Promise((resolve) => { + const req = indexedDB.deleteDatabase('rosea'); + req.onsuccess = req.onerror = req.onblocked = () => resolve(); + }); + }); + results.push(' cleaned: service worker, caches and the rosea database for localhost:4173'); + } catch (error) { + results.push(`WARN cleanup failed: ${String(error).split('\n')[0]}`); + } + await page?.close().catch((error: unknown) => results.push(`WARN could not close the tab: ${String(error)}`)); + await browser?.close().catch((error: unknown) => results.push(`WARN could not disconnect: ${String(error)}`)); + for (const args of [['shell', 'am', 'force-stop', 'com.android.chrome'], ['reverse', '--remove', 'tcp:4173'], ['forward', '--remove', 'tcp:9222']]) { + try { + adb(...args); + } catch (error) { + results.push(` ${args.join(' ')}: ${String(error).split('\n')[0]} (already done)`); + } + } + results.push(' stopped: Chrome on the device; adb mappings removed'); + console.log(results.join('\n')); +} diff --git a/tools/art-prep/src/manifest.ts b/tools/art-prep/src/manifest.ts index f02afdd..c3f8634 100644 --- a/tools/art-prep/src/manifest.ts +++ b/tools/art-prep/src/manifest.ts @@ -36,6 +36,8 @@ export interface Asset { readonly cells?: readonly Cell[]; readonly include: readonly string[]; readonly avoid: readonly string[]; + /** Shared avoid lines this picture may break, each named exactly (the gardener is a person: planet-garden.md). */ + readonly allow?: readonly string[]; /** Indices into STYLE.md §7, the review points shown on its card. */ readonly checks: readonly number[]; } @@ -108,6 +110,9 @@ export function checkManifest(m: Manifest, checklistLength: number): string[] { problems.push(`${a.id}: a ${a.type} sits over other pictures, so its background must be transparent`); } if (a.type !== 'spritesheet' && (a.subject ?? '').trim() === '') problems.push(`${a.id}: no subject`); + for (const line of a.allow ?? []) { + if (!m.avoid.includes(line)) problems.push(`${a.id}: allows "${line}", which is not in the shared avoid list`); + } for (const i of a.checks) { if (!Number.isInteger(i) || i < 0 || i >= checklistLength) problems.push(`${a.id}: review point ${i} is not in STYLE.md §7`); } diff --git a/tools/art-prep/src/placeholders.ts b/tools/art-prep/src/placeholders.ts index b20eb4d..72b672f 100644 --- a/tools/art-prep/src/placeholders.ts +++ b/tools/art-prep/src/placeholders.ts @@ -332,6 +332,47 @@ function planet(W: number, H: number, id: string): string { + `${drawing(things, id)}`; } +type Pose = 'stand' | 'walk' | 'pour' | 'pull' | 'sweep' | 'carry' | 'reach' | 'sit'; + +/** The gardener's stand-in in a 120 × 200 box, feet on the bottom edge, facing right (STYLE.md §3b). */ +function gardener(pose: Pose, boy = false): string { + const skin = '#cf9a72', hair = '#7a4b2e', cloth = C.leaf, apron = '#efe4d2'; + const lean = { stand: 0, walk: 4, pour: 10, pull: 28, sweep: 18, carry: 6, reach: 14, sit: 0 }[pose]; + const arm = { stand: 8, walk: -12, pour: -70, pull: -150, sweep: -40, carry: -80, reach: -95, sit: -30 }[pose]; + const legs = pose === 'sit' + ? `` + : ``; + const body = boy + ? `` + : ``; + const held = pose === 'pour' ? `` + : pose === 'carry' ? Array.from({ length: 4 }, (_, i) => ``).join('') : ''; + const braids = boy ? '' : ``; + return `${legs} + ${body} + + ${held} + ${braids} + + + `; +} + +const GARDENER_POSES: Record = { + 'gardener-stand': 'stand', 'gardener-walk': 'walk', 'gardener-pour': 'pour', 'gardener-pull': 'pull', + 'gardener-sweep': 'sweep', 'gardener-carry': 'carry', 'gardener-reach': 'reach', 'gardener-sit': 'sit' +}; + +/** Her home planet's stand-in (STYLE.md S2): a round meadow world, the empty bed on top, the wall and the chair. */ +function homePlanet(W: number, H: number, light: 'day' | 'golden' | 'night'): string { + const meadow = { day: C.meadow, golden: '#c9b07a', night: '#3c4a6a' }[light]; + const cx = W / 2, cy = H * 0.58, r = W * 0.35; + return ` + + + `; +} + /** The share frame's stand-in: meadow along the bottom and up the sides, the middle left empty. */ function shareFrame(W: number, H: number): string { return `` @@ -360,6 +401,12 @@ function single(a: Asset): string { const { width: W, height: H } = a; switch (a.type) { case 'sheet': { + if (a.character === 'gardener') { + // The girl along the top, the boy along the bottom; the side and back views are flipped stand-ins. + const row = (boy: boolean, y: number): string => + [0, 1, 2, 3].map((i) => `${gardener('stand', boy)}`).join(''); + return `${row(false, 40)}${row(true, 560)}`; + } if (a.character === 'fox') { const views: FoxLook[] = [{ pose: 'sit', eyes: 'half' }, { pose: 'stand', eyes: 'half' }, { pose: 'stand', eyes: 'half', tilt: -8 }, { pose: 'sit', eyes: 'half', behind: true }]; const figures = views.map((l, i) => `${fox(l)}`).join(''); @@ -388,6 +435,7 @@ function single(a: Asset): string { return fit(drawing({ ...PROPS, ...V2_PROPS }, a.id), 200, 200, W, H, 0.7); case 'layer': { if (a.id.startsWith('planet-')) return planet(W, H, a.id); + if (a.id.startsWith('home-planet-')) return homePlanet(W, H, a.id.endsWith('golden') ? 'golden' : a.id.endsWith('night') ? 'night' : 'day'); if (a.id === 'share-frame') return shareFrame(W, H); const time = (['morning', 'day', 'sunset', 'night'] as const).find((t) => a.id.endsWith(t)) ?? 'day'; return garden(W, H, time); @@ -426,6 +474,8 @@ function cellBody(id: string, W: number, H: number): string { if (look) return fit(rose(look), 200, 520, W, H); const pose = FOXES[id]; if (pose) return fit(fox(pose), 300, 240, W, H); + const gardenerPose = GARDENER_POSES[id]; + if (gardenerPose) return fit(gardener(gardenerPose), 120, 200, W, H); if (id in TALL || id in V2_TALL) return fit(drawing({ ...TALL, ...V2_TALL }, id), 200, 400, W, H); return fit(drawing({ ...PROPS, ...MORE_PROPS, ...V2_PROPS }, id), 200, 200, W, H, 0.7); } diff --git a/tools/art-prep/src/prompt.ts b/tools/art-prep/src/prompt.ts index bb98f44..5938b00 100644 --- a/tools/art-prep/src/prompt.ts +++ b/tools/art-prep/src/prompt.ts @@ -71,6 +71,9 @@ const MAKE: Record, string> = { const list = (items: readonly string[]): string => items.join('; '); +/** The shared avoid lines, less any this picture is allowed to break. */ +const shared = (a: Asset, m: Manifest): string[] => m.avoid.filter((line) => !(a.allow ?? []).includes(line)); + /** A sheet is cut apart, so its pictures must not touch. Everything else is said positively in the layout. */ const SHEET_AVOID = ['pictures touching or overlapping', 'grid lines, frames or labels']; @@ -116,7 +119,7 @@ export function promptFor(a: Asset, m: Manifest, style: string): string { lines.push( canvasLine(a.width, a.height, a.background, a.type === 'sprite'), `Include: ${list(a.include)}`, - `Avoid: ${list([...a.avoid, ...m.avoid])}`, + `Avoid: ${list([...a.avoid, ...shared(a, m)])}`, board(a.id) ); return lines.join('\n'); @@ -138,7 +141,7 @@ function sheetPrompt(a: Asset, m: Manifest, style: string): string { 'Pictures:', ...cells.map((c, i) => `${i + 1}. ${c.does}`), `Include: ${list(a.include)}`, - `Avoid: ${list([...a.avoid, ...SHEET_AVOID, ...m.avoid])}`, + `Avoid: ${list([...a.avoid, ...SHEET_AVOID, ...shared(a, m)])}`, board(a.id) ].join('\n'); } @@ -155,7 +158,7 @@ export function cellPromptFor(a: Asset, cell: Cell, m: Manifest, style: string): `Drawn alike: ${a.angle ?? ''}`, canvasLine(width, height, 'transparent', true), `Include: ${list(a.include)}`, - `Avoid: ${list([...a.avoid, ...m.avoid])}`, + `Avoid: ${list([...a.avoid, ...shared(a, m)])}`, board(`${cell.id} (one picture of ${a.id})`) ].join('\n'); } diff --git a/tools/art-prep/test/board.test.ts b/tools/art-prep/test/board.test.ts index be161cb..8e2ba9e 100644 --- a/tools/art-prep/test/board.test.ts +++ b/tools/art-prep/test/board.test.ts @@ -19,7 +19,7 @@ describe('the board data', () => { for (const c of a.cells ?? []) expect(c).toMatchObject({ id: expect.any(String), width: expect.any(Number), height: expect.any(Number), prompt: expect.any(String) }); } } - expect(data.checklist).toHaveLength(10); + expect(data.checklist).toHaveLength(12); expect(data.assets.every((a) => Number.isInteger(a.phase))).toBe(true); }); diff --git a/tools/art-prep/test/manifest.test.ts b/tools/art-prep/test/manifest.test.ts index e0aea42..9c356d6 100644 --- a/tools/art-prep/test/manifest.test.ts +++ b/tools/art-prep/test/manifest.test.ts @@ -18,15 +18,16 @@ describe('art/manifest.json', () => { expect(checkManifest(readManifest(), POINTS)).toEqual([]); }); - it('asks for the 34 Phase 1 pictures: the rose sheet first, then her stages, care, moments and touch, the care things, chair, garden, letter and icons', () => { + it('asks for the 46 Phase 1 pictures: the rose sheet first, then her stages, care, moments and touch, the care things, chair, garden, letter, icons, the gardener and her planet', () => { const m = readManifest(); expect(m.assets[0]?.id).toBe('rose-sheet'); const phase1 = m.assets.filter((a) => a.phase === 1); const pictures = phase1.flatMap((a: Asset) => (a.cells ? a.cells.map((c) => c.id) : [a.id])); - expect(pictures).toHaveLength(34); + expect(pictures).toHaveLength(46); expect(pictures).toEqual(expect.arrayContaining([ 'rose-bud', 'rose-full-bloom', 'rose-waiting', 'rose-tickled', 'rose-gentle', 'petal-folded', 'weeds-growing', - 'watering-can-pouring', 'garden-chair', 'garden-sunset', 'garden-night', 'letter-header', 'app-icon', 'app-icon-maskable', 'favicon-mark' + 'watering-can-pouring', 'garden-chair', 'garden-sunset', 'garden-night', 'letter-header', 'app-icon', 'app-icon-maskable', 'favicon-mark', + 'gardener-sheet', 'gardener-pour', 'gardener-pull', 'home-planet-day', 'home-planet-night' ])); }); @@ -68,6 +69,7 @@ describe('checkManifest refuses', () => { ['a Phase 1 picture listed after Phase 3', withAsset('lanterns-sheet', (a) => { a.phase = 1; }), /lanterns-sheet: phase 1 comes after phase 3; list the pictures in phase order/], ['a picture with no subject', withAsset('garden-chair', (a) => { delete a.subject; }), /no subject/], ['a picture nobody uses', withAsset('garden-chair', (a) => { a.usedBy = []; }), /usedBy is empty/], + ['an allowance for a line the shared list does not have', withAsset('gardener-sheet', (a) => { a.allow = ['a dragon']; }), /allows "a dragon", which is not in the shared avoid list/], ['a name from the book in a prompt', withAsset('garden-chair', (a) => { a.subject = 'a chair for the Little Prince'; }), /"Little Prince" \(little-prince\)/], ['a medical word in a cell', withAsset('rose-care-sheet', (a) => { (a.cells as { does: string }[])[0]!.does = 'thirsty, waiting to be healed'; }), /"healed" \(medical\)/], ['the word the game never says, in the shared avoid list', (() => { const m = clone(readManifest()); (m.avoid as string[]).push('a lonely look'); return m; })(), /avoid list: "lonely"/] diff --git a/tools/art-prep/test/prompt.test.ts b/tools/art-prep/test/prompt.test.ts index 1702853..9a370ce 100644 --- a/tools/art-prep/test/prompt.test.ts +++ b/tools/art-prep/test/prompt.test.ts @@ -23,9 +23,9 @@ describe('STYLE.md', () => { } }); - it('§7 has the ten review points, a point split over two lines read as one', () => { + it('§7 has the twelve review points, a point split over two lines read as one', () => { const points = reviewPoints(readStyle()); - expect(points).toHaveLength(10); + expect(points).toHaveLength(12); expect(points[8]).toBe("It reads as one young red-orange fox with a cream mask and a ringed tail, shy and gentle, and nothing like the book's sandy, long-eared fox."); expect(points[3]).toBe('Nothing from the book: no glass dome, screen, tiny planet, desert, child or scarf, and no look of its drawings.'); }); @@ -37,15 +37,16 @@ describe('STYLE.md', () => { }); describe('the prompts', () => { - it('every one starts with STYLE.md §1 word for word, then says what to make: 35 cards and 66 one-at-a-time prompts', () => { - expect(allPrompts).toHaveLength(35 + 66); + it('every one starts with STYLE.md §1 word for word, then says what to make: 40 cards and 74 one-at-a-time prompts', () => { + expect(allPrompts).toHaveLength(40 + 74); for (const p of allPrompts) expect(p.startsWith(style + '\n\nMake: ')).toBe(true); }); it('every one ends with the shared avoid list and its board id', () => { - const shared = readManifest().avoid.join('; '); + const m = readManifest(); for (const a of data.assets) { - expect(a.prompt).toContain(shared); + const allowed = m.assets.find((x) => x.id === a.id)?.allow ?? []; + expect(a.prompt).toContain(m.avoid.filter((l) => !allowed.includes(l)).join('; ')); expect(a.prompt.endsWith(`\nBoard id: ${a.id}`)).toBe(true); for (const c of a.cells ?? []) expect(c.prompt.endsWith(`\nBoard id: ${c.id} (one picture of ${a.id})`)).toBe(true); } @@ -76,6 +77,17 @@ describe('the prompts', () => { for (const id of ['care-props-sheet', 'favicon-mark', 'letter-header']) expect(by.get(id)?.attach).toEqual([]); }); + it("only the gardener's own pictures may show a person; every other prompt still says no people (STYLE.md S6)", () => { + const people = 'people, hands or human faces'; + for (const a of data.assets) { + const prompts = [a.prompt, ...(a.cells ?? []).map((c) => c.prompt)]; + const isGardener = a.attach.includes('gardener-sheet') || a.id === 'gardener-sheet'; + // The Avoid line only: §1 itself names the exception for every picture. + for (const p of prompts) expect((p.split('\nAvoid: ')[1] ?? '').includes(people), a.id).toBe(!isGardener); + } + expect(data.assets.find((a) => a.id === 'gardener-poses-sheet')?.attach).toEqual(['gardener-sheet']); + }); + it('every rose prompt puts her face on the petals, never on a round head', () => { for (const a of data.assets.filter((x) => x.attach.includes('rose-sheet') || x.id === 'rose-sheet')) { for (const p of [a.prompt, ...(a.cells ?? []).map((c) => c.prompt)]) {