Compare commits

...

13 Commits

Author SHA1 Message Date
mnovak ff3a996482 [docs] CalmRefresh: Analysis, review, and G0.10 closed 2026-11-02 01:18:10 +01:00
mnovak a5480d2877 [app] CalmRefresh: Register the worker in the app and offer the waiting version; e2e publishes a real second one 2026-11-02 01:18:09 +01:00
mnovak beea8eaa10 [ui] CalmRefresh: One quiet line and Refresh when a new version of the garden is waiting 2026-11-02 01:18:08 +01:00
mnovak 8c84cbbb52 [tools] CpuGuard: Merge the CPU guard 2026-11-02 00:51:47 +01:00
mnovak 8ee3e1ce28 [docs] CpuGuard: Record the guard in CLAUDE.md 5.7, its review, and G0.28 closed 2026-11-02 00:51:46 +01:00
mnovak f9883e22ba [tools] CpuGuard: Full test runs wait for, then refuse, a machine above 80 % CPU 2026-11-02 00:51:45 +01:00
mnovak 8b1c2eaee2 [app] KeepSafe: Merge keeping the rose safe 2026-11-02 00:44:28 +01:00
mnovak 55fc14b125 [docs] KeepSafe: Analysis, review, lessons, and G0.11 closed 2026-11-02 00:44:24 +01:00
mnovak e63563755b [app] KeepSafe: Wire persist, the file download and import; e2e restores her on a fresh profile 2026-11-02 00:44:22 +01:00
mnovak 512c300973 [ui] KeepSafe: Say what the browser promised, ask it to keep her, save her to a file, bring her back 2026-11-02 00:44:20 +01:00
mnovak a63232e8d7 [storage] RoseFile: Save the rose's keys and care to a file and bring them back additively; never the town or the private key 2026-11-02 00:44:18 +01:00
mnovak cc9cc11b0b [engine] Rose: Name a rose by her current and past keys, replay each key on its own, and add each act once 2026-11-02 00:44:16 +01:00
mnovak a7d0fca31a [app] Rose: Merge the rose and her care 2026-11-02 00:21:01 +01:00
39 changed files with 1392 additions and 55 deletions
+3
View File
@@ -8,6 +8,9 @@ One row per feature, with its analysis document (CLAUDE.md §5.1). Gaps live in
| Workspace, contracts, gates, PWA shell | 0 | Merged to `main` 2026-11-01 (`d11d242`); built, not deployed. Phase 0 gate still open | [phase0-workspace.md](features/phase0-workspace.md) | [feature-phase0-workspace.md](reviews/feature-phase0-workspace.md) |
| Roadmap and gameplay docs, read against the code | 0 | Merged 2026-11-01; Q1–Q7 answered by the author | — | [docs-roadmap-gameplay.md](reviews/docs-roadmap-gameplay.md) |
| The Letter slot: page at `#letter`, empty `docs/LETTER.md` | 0 | Merged to `main`; built, not deployed. Invisible until the author writes | [letter-slot.md](features/letter-slot.md) | [feature-letter-slot.md](reviews/feature-letter-slot.md) |
| A calm refresh: a waiting new version is offered in one line, never swapped in by itself | 0 | Merged to `main`; built, not deployed | [calm-refresh.md](features/calm-refresh.md) | [feature-calm-refresh.md](reviews/feature-calm-refresh.md) |
| The CPU guard: full runs wait for, then refuse, a busy machine | 0 | Merged to `main` | — | [fix-cpu-guard.md](reviews/fix-cpu-guard.md) |
| Keep her safe: the browser's promise, save her to a file, bring her back | 0–1 | Merged to `main`; built, not deployed | [keep-her-safe.md](features/keep-her-safe.md) | [feature-keep-her-safe.md](reviews/feature-keep-her-safe.md) |
| The rose: care by feel, growth from days of care, drift, moods, her numbers; the care log and the identity | 1 | Merged to `main`; built, not deployed. Tuning is the author's | [rose.md](features/rose.md) | [feature-rose-care.md](reviews/feature-rose-care.md) |
| Where the sunset is: choose a town (or skip to a guess from the device's zone), kept on the device; tonight's sunset in the garden | 1 | Merged to `main`; built, not deployed | [sunset-place.md](features/sunset-place.md) | [feature-sunset-place.md](reviews/feature-sunset-place.md) |
| The sun: real sunrise, sunset and solar noon on the device; polar day and night | 1 | Merged to `main`; engine only, the app does not show it yet | [sun.md](features/sun.md) | [feature-sun.md](reviews/feature-sun.md) |
+3 -2
View File
@@ -26,8 +26,8 @@ board exist, and the first real picture is the author's to make.
| ~~G0.7~~ | ~~No commit guards~~ | Closed 2026-11-01. `pre-commit` blocked a 5.7 MB probe; `commit-msg` blocked a `Co-Authored-By: Claude` trailer; both passed clean input. |
| ~~G0.8~~ | ~~Never tested under the Pages sub-path~~ | Closed for the local build 2026-11-01. `shell.spec.ts` serves `dist/` at `/Rosea/` and asserts manifest scope = start_url = SW scope. Mutation: scope `/` fails it. **On real GitHub Pages: still predicted** (G0.13). |
| ~~G0.9~~ | ~~No proof the app opens offline~~ | Closed for the shell 2026-11-01. `offline.spec.ts` closes the server, then reload, cold start and a deep link all render. Mutations: `clientsClaim: false` and no `navigateFallback` both fail it. |
| G0.10 | No calm *refresh* control for a waiting service worker (CLAUDE.md §8, stale SW) | Open. `registerType: 'prompt'` and `skipWaiting: false` are set, so a new worker waits. Nothing tells the player yet. |
| G0.11 | IndexedDB eviction: no `navigator.storage.persist()`, no export-my-rose (§8) | **Open, and now urgent**: since 2026-11-02 there is a rose to lose. `packages/storage` exists. |
| ~~G0.10~~ | ~~No calm *refresh* control for a waiting service worker (CLAUDE.md §8, stale SW)~~ | Closed 2026-11-02 on `feature/calm-refresh`: the app registers the worker and shows *A new version of the garden is ready.* with *Refresh*. e2e publishes a real second version: offered, not swapped, then taken over on Refresh; 3 of 3 put-back bugs caught. |
| ~~G0.11~~ | ~~IndexedDB eviction: no `navigator.storage.persist()`, no export-my-rose (§8)~~ | Closed 2026-11-02 on `feature/keep-her-safe`: *Keep her safe* asks the browser (and an installed app asks by itself), saves her to a file without the town or the private key, and brings her back additively on any device. e2e: saved on one browser profile, restored on a fresh one, survives a reload. Not seen in Firefox or Safari. |
| G0.12 | The app cannot validate content in the browser | Open. Ajv compiles with `new Function`, which the CSP forbids. Needs standalone pre-compiled validators before the app reads the library. |
| G0.13 | No GitHub remote, no Pages deploy workflow, no mirror check (§5.2) | Open. Only the Gitea remote exists. |
| G0.14 | Author-owned docs missing: `docs/PRINCIPLES.md`, `docs/ART.md`, `art/STYLE.md`, `docs/LETTER.md` | Open, narrowed 2026-11-01: `docs/ROADMAP.md` and `docs/GAMEPLAY.md` were added on `docs/roadmap-gameplay`, as the author gave them. Agents scaffold LETTER.md; they never write its voice. |
@@ -42,6 +42,7 @@ board exist, and the first real picture is the author's to make.
| G0.23 | Source maps are built and would be published | Open. `sourcemap: true`; maps are not precached. Decide with G0.13 whether the repository is public. If not, use `'hidden'`. |
| G0.24 | No art pipeline: `docs/ART.md`, `art/STYLE.md` (drafted with the author), `art/manifest.json` for Phase 1 assets, SVG placeholders, `tools/art-prep` | **Pipeline built 2026-11-01** (`feature/art-board`): docs/ART.md, the Phase 1 manifest (25 pictures), 29 generated stand-ins, `tools/art-prep` (50 tests; 5 of 5 put-back bugs caught), the art board published. STYLE.md approved by the author 2026-11-01 (S1–S5 kept as drafted; `docs/style-approved`). The board grew to 53 pictures with Phases 2–3 (`art/phase2-3-pictures`); the fox's look F1–F4 approved with a deep red-orange coat (`art/fox-coat`). **Still open:** the **Phase 0 gate**, one real picture through every step into `art/final/`. |
| ~~G0.25~~ | ~~No slot for *A Letter from the Gardener*~~ | Closed 2026-11-01, merged to `main`. `docs/LETTER.md` holds slots as comments only; the page opens at `#letter` once it has words. 16 ui tests, and e2e on both the empty and a temporary written letter. Mutations caught: the link while empty, any link scheme, focus not moving, *heal* in the letter. |
| ~~G0.28~~ | ~~CLAUDE.md §5.7's CPU limit was only read, and broken three times on 2026-11-02~~ | Closed 2026-11-02 on `fix/cpu-guard`: `pnpm guard:cpu` runs before every full run, waits up to 3 min, then refuses. 13 tests; seen waiting 51 s on a busy machine, refusing, and stopping `pnpm test` before any test ran. |
| G0.27 | The quiet door to real help has no numbers (§5.6 rule 5) | Open. The slot is in `docs/LETTER.md`. Support lines are real-world facts the author must verify, per country, so the door exists only once the letter does. |
| ~~G0.26~~ | ~~Not decided: how the sunset invitation reaches the player on the web~~ | Closed 2026-11-01 by the author (Q6): in-app only on the web, no push server; local notifications through the Tauri shell in Phase 6. Recorded in ROADMAP Phase 0 and CLAUDE.md §8. |
+62
View File
@@ -0,0 +1,62 @@
# A calm refresh — when a new version of the garden is waiting
Status: built on `feature/calm-refresh`. Gap G0.10; CLAUDE.md §8, *the stale service worker: a
precached shell keeps serving old JS to a player who has "updated". Detect a waiting worker and offer
an explicit, calm refresh control.* Needed before the Phase 1 gate, where the author plays the
installed app daily while fixes are deployed. Review:
[`feature-calm-refresh.md`](../reviews/feature-calm-refresh.md).
## 1. Why and what, in the player's terms
The garden works offline because a service worker keeps a copy of it. When a new version is
published, the browser fetches it in the background and **waits**: the garden the player has open
never changes under their hands. When the new one is ready, one quiet line appears at the foot of
the page: **"A new version of the garden is ready."** with a **Refresh** button. The player
refreshes when they like; nothing is lost either way, since the rose lives in the device's
database, not in the code.
## 2. Technical architecture
```mermaid
sequenceDiagram
participant P as the open garden (version A)
participant B as the browser
participant S as the server
B->>S: sw.js (on a navigation or a check)
S-->>B: version B's bytes differ
B->>B: install B, precache; B waits (skipWaiting: false)
B-->>P: "waiting" (workbox-window, via virtual:pwa-register)
P->>P: show "A new version of the garden is ready." + Refresh
P->>B: Refresh: SKIP_WAITING to B
B-->>P: B controls; the page reloads under B
```
| # | Decision | Why |
|:--|:--|:--|
| U1 | Register through `virtual:pwa-register` in the app; `injectRegister: false`. | The emitted `registerSW.js` registers but tells the page nothing; the virtual module reports the waiting worker. Bundled, so the CSP needs no inline script. |
| U2 | **Never refresh by itself.** The line waits for the player. | CLAUDE.md §1, *gentle*; a reload in the middle of pouring water would lose the pour. |
| U3 | The line sits in its own `aside` at the foot, on the garden and the Letter alike. | It is about the whole app, not one page; a landmark keeps it findable. |
| U4 | The e2e test serves a **real second version** (version A's build with `sw.js` changed) from the same origin. | A waiting worker exists only between two builds; a mock would test the mock. |
## 3. Risk analysis
| Risk | Answer |
|:--|:--|
| A player keeps old code forever and never sees a fix. | The line appears as soon as a new worker waits; tested end to end. |
| A silent swap mid-action loses care. | U2; the test asserts the old worker still controls the page until Refresh. |
| Feeling pushed. | One line, no badge, no repeat, no count; nothing happens if it is ignored. |
| Privacy | Nothing new leaves the device: update checks were already made by the browser to the same origin. |
## 4. Gaps
| Gap | State |
|:--|:--|
| G0.10 | Built |
| What changed in a version (release notes) | Open: not needed for the Phase 1 gate |
## 5. Verification matrix
| Case | Kind | Where |
|:--|:--|:--|
| No line without a waiting version; the line and Refresh when there is one; Refresh calls the app; on the Letter too | unit | `ui/test/Shell.test.ts` |
| Built app: version A controls; version B published; the line appears; A still controls; Refresh; B controls and the line is gone; axe | e2e | `e2e/update.spec.ts` |
+91
View File
@@ -0,0 +1,91 @@
# Keep her safe — the browser's promise, a file, and bringing her back
Status: built on `feature/keep-her-safe`. Gap G0.11, CLAUDE.md §8: *IndexedDB is evictable … call
`navigator.storage.persist()` where it exists, prompt iOS players to install, and make export-my-rose
a first-class feature. A player returning to find their rose gone is the cruellest bug this product
could have.* Review: [`feature-keep-her-safe.md`](../reviews/feature-keep-her-safe.md).
---
## 1. Why and what, in the player's terms
Beside *Her numbers* there is now **Keep her safe**. It opens a small, quiet section:
- **What the browser has promised**, in one true sentence: that it keeps her, or that it may clear
her if the garden is not opened for a long time.
- **Ask the browser to keep her**, when it has not promised yet. If it says no, that is said calmly,
and the file is the answer.
- On an iPhone or iPad that has not added the garden to the Home Screen: *add it, to keep her.*
- **Save her to a file**: a small file the player keeps, named for the day. It holds her care and
when it was given; it never holds the town.
- **Bring her back from a file**: on a new phone, or after the browser cleared her. Everything she
had comes back, and nothing she has now is lost. Bringing the same file twice adds nothing twice.
An installed garden asks the browser to keep her by itself, once, after the first care of a visit.
## 2. Technical architecture
```mermaid
flowchart LR
subgraph app["apps/rosea"]
wire["App.svelte<br/>navigator.storage, file download"]
end
subgraph ui["packages/ui"]
keep["KeepSafe.svelte"]
rose["Rose.svelte<br/>keys = current + past"]
end
subgraph storage["packages/storage"]
exp["exportRose / importRose<br/>asRoseFile"]
past[("profile: pastKeys")]
ev[("events")]
end
subgraph engine["packages/engine"]
replay["roseAt(events, keys)<br/>one replay per key"]
dedupe["newCare: each act once"]
end
wire --> keep --> exp --> ev & past
exp --> dedupe
rose --> replay
```
### Decisions
| # | Decision | Why |
|:--|:--|:--|
| K1 | The file holds `{ format: 'rosea-rose', version: 1, keys, events }`: her public keys and her whole care log. **Never the private key** (it cannot be exported: rose.md R9), **never the sunset town**. | The town is the one location Rosea knows; choosing it again is one tap. The care log alone is what cannot be remade. |
| K2 | A rose is named by **a list of keys**: the current identity first, then the keys she had on other devices (`profile.pastKeys`). | The private key cannot move, so a rose brought back lives under a new key, and her old care names the old one. The log is never rewritten (CLAUDE.md §6.2). |
| K3 | **Each key's care is replayed on its own**; her days of care are the union. Water and today's needs come from the current key; stage, drift and warmth from all. | Replaying everything as one log could take a day away: one device's watering can make the other's "too much". Separate replays make bringing her back strictly additive, which is property-tested. |
| K4 | Import **appends only acts not already there** (same moment, giver, rose, act and amount) in one transaction, and **refuses a file that is not a rose** before writing anything. | Contributions only add (CLAUDE.md §1). A wrong file is an ordinary mistake, said calmly. |
| K5 | `persist()` is called **automatically only in an installed app**, once per visit, after the first care. Otherwise only when the player asks. | Chrome and Safari grant or refuse silently; Firefox shows a prompt. A prompt the player did not ask for, right after watering, would be a strange interruption. |
| K6 | The download is made on the device (`Blob`, `<a download>`), and the import reads a file the player picks. | Nothing is sent anywhere; the CSP stays `'self'`. |
## 3. Risk analysis
| Risk | Answer |
|:--|:--|
| **The cruellest bug**: her care gone. | The file brings it back on any device, tested end to end with a fresh browser profile. |
| **Privacy**: the file is a diary of when someone was in the app. | It is made only when the player asks, stays wherever they put it, and the screen says what it holds. No town, no private key (tested). |
| **Feeling worse**: "the browser may clear her" can frighten. | It is said once, only on request, with the remedy in the same sentence. |
| **A merged rose loses days.** | K3, property-tested: merging two logs never lowers either one's days of care. |
| **A tampered file** gives a rose days she was never given. | It only fools the player's own garden; nothing is compared with anyone (CLAUDE.md §1, *never count people*). Phase 3 must not trust imported care as proof towards friends. |
## 4. Gap analysis
| Gap | State |
|:--|:--|
| G0.11 eviction: `persist()`, export-my-rose | Built: persist on request and when installed; save; bring back |
| A reminder to save her now and then | Open: no nagging by design; the Letter can mention it |
| iOS install prompt beyond one sentence | Open: Safari has no install API |
## 5. Verification matrix
| Case | Kind | Where |
|:--|:--|:--|
| A moved rose keeps every day under her old key; her water starts afresh; care under the new key adds | unit | `engine/test/rose.test.ts` |
| A moved rose that is opening drops petals, and gathering them helps | unit | same |
| Merging two logs never takes a day from either | property | same |
| `newCare` adds each act once, however often | unit | same |
| The file holds keys and care, no town, no private key; survives JSON | unit | `storage/test/rose-file.test.ts` |
| Bringing her back on a new device, twice, onto a device with care of its own, from this very device; refusing seven kinds of not-a-rose and changing nothing | unit | same |
| Keep her safe: the browser's answer, asking, a refusal said calmly, saving a dated file, bringing her back, a wrong file | unit | `ui/test/rose.test.ts` |
| Save on one browser profile, bring her back on a fresh one, reload: one day of care; the file has no town; axe | e2e | `e2e/shell.spec.ts` |
+2 -2
View File
@@ -12,9 +12,9 @@ and **how to apply it**.
| [`art.md`](art.md) | 2 | The image pipeline. |
| [`code.md`](code.md) | 3 | TypeScript, Svelte, async ordering, Rust. |
| [`technical.md`](technical.md) | 5 | The browser and the build as platforms. |
| [`testing.md`](testing.md) | 8 | What makes a test worth having, and how a passing test lies. |
| [`testing.md`](testing.md) | 9 | What makes a test worth having, and how a passing test lies. |
| `privacy.md` | none yet | What could leave the device or make a person findable. (The geocell finding is in the review, not here: it was caught before it cost anything.) |
| [`process.md`](process.md) | 2 | Workflow, commits, credentials, honesty about what shipped. |
| [`process.md`](process.md) | 3 | Workflow, commits, credentials, honesty about what shipped. |
A file is created with its first real entry. An empty lessons file only looks like
knowledge.
+14
View File
@@ -31,3 +31,17 @@ better source of versions than the registry.
**How to apply it.** Start a new repository from a sibling's resolved versions, and
pin them exactly. Unpin deliberately, in its own commit, after upgrading Node (G0.20).
## A rule checked by reading a number is broken by the next command
**What happened.** CLAUDE.md §5.7 says not to start a full run above ~80 % CPU. Three
times on 2026-11-02 a run started above it. Once the load was not checked at all; twice it
was read (85 %, then 100 %, another project's tests) and the run started anyway, once
because the check and the run were chained in one command that did not depend on it.
**Why it bit.** A rule that relies on a person reading a number before acting holds only
while nothing else is competing for attention.
**How to apply it.** Make the run refuse to start. Done: `pnpm guard:cpu` (in
`tools/cpu-guard`) runs before every full run, waits up to three minutes, then refuses. Do
not set `ROSEA_CPU_MAX` to get past a busy desktop; it is for dedicated machines.
+13
View File
@@ -118,3 +118,16 @@ the one case that matters.
**How to apply it.** For each condition, write the case where only it decides (from
0.39 a full can overshoots: needed, too full). For an order property, add one fixed
log where order changes the answer. Then put the bug back and watch the test fail.
## `toEqual` cannot see a field that is `undefined`
**What happened.** On 2026-11-02 a drill made the rose's export file carry an extra field
taken from the identity. The test passed: it kept no identity, so the field was
`undefined`; `toEqual` treats a missing property and an undefined one as equal, and
`JSON.stringify` drops it, so the text check saw nothing either.
**Why it bit.** "Nothing else in it" is a claim about absent fields, and the default
equality is blind to exactly the field that is absent by accident.
**How to apply it.** For "holds this and nothing else", use `toStrictEqual`, and give the
test something real to leak (here, a kept identity).
+39
View File
@@ -0,0 +1,39 @@
# Review — `feature/calm-refresh`
Adversarial self-review (CLAUDE.md §5.3). Analysis: [`features/calm-refresh.md`](../features/calm-refresh.md).
Reviewed 2026-11-02 on Node 22.11.0, Windows 10. There is no PR: the only remote is Gitea.
## Gates
Counts are on the merge; HANDOVER repeats them. New: ui +3 (the line, Refresh, on the Letter);
e2e +1 (`update.spec.ts`: a real second version).
**The app changed** (CLAUDE.md §5.4): the worker is registered by the app (`virtual:pwa-register`)
instead of the emitted `registerSW.js`, and a waiting version shows one line with *Refresh*. Rebuilt by
the e2e and offline runs; **not deployed** (G0.13). This is the change that lets every later fix
reach an installed garden.
## Bug drills — each put back once, the app rebuilt each time
| Put back | Result |
|:--|:--|
| The app never hears that a version waits | CAUGHT |
| The new worker swaps itself in silently (`skipWaiting: true`) | CAUGHT: version B controlled the page before Refresh |
| Refresh does nothing | CAUGHT: version A still controlled after Refresh |
## Findings
| # | Area | Finding | Resolution |
|:--|:--|:--|:--|
| 1 | Test honesty | A waiting worker cannot be faked without testing the fake. | The test publishes a real version B (A's build, `sw.js` changed) on the same origin; B's own listener says which worker controls the page, before and after. |
| 2 | Correctness | Registration moved from `registerSW.js` to the app bundle. The first worker must still control the first page, or the offline promise breaks. | `clientsClaim: true` unchanged; the offline suite (first load, server closed, reload, cold start) passes on the merge. |
| 3 | Correctness | A player who ignores the line keeps version A until every garden tab closes, which is how service workers work. | Accepted and intended (U2). Closing and reopening the app also brings B. |
| 4 | Soul | An update line can nag. | One line, no badge, no count, never repeated in a modal; it disappears after Refresh. |
| 5 | Privacy | Update checks are requests. | They already happened (the browser checks `sw.js` on navigation), same origin only; nothing new is sent. |
| 6 | Correctness | Two tabs: Refresh in one reloads only that one; the other keeps showing the line until it reloads. | Accepted; it is still true there. |
## What was not verified
- An installed PWA on a real phone, and Safari's update timing.
- The leftover `dist/registerSW.js` from older builds is no longer emitted; GitHub Pages will simply
not serve it. No page references it.
+43
View File
@@ -0,0 +1,43 @@
# Review — `feature/keep-her-safe`
Adversarial self-review (CLAUDE.md §5.3). Analysis: [`features/keep-her-safe.md`](../features/keep-her-safe.md).
Reviewed 2026-11-02 on Node 22.11.0, Windows 10. There is no PR: the only remote is Gitea.
## Gates
Counts are on the merge; HANDOVER repeats them. New here: engine +4, storage +6, ui +5, e2e +1
(save on one browser profile, bring her back on a fresh one, reload).
**The app changed** (CLAUDE.md §5.4): *Keep her safe* beside *Her numbers*. Rebuilt by the e2e run;
**not deployed** (no host, G0.13).
## Bug drills — each put back once
| Put back | Result |
|:--|:--|
| Only the current key counts | CAUGHT: 3 |
| One replay for all keys (the lossy merge K3 avoids) | CAUGHT: 2, the merge property among them |
| Import appends acts already there | CAUGHT: 2 |
| Export leaks a field from the identity | **MISSED at first** (finding 1), then CAUGHT |
| A file with one bad act half-imports the rest | CAUGHT |
## Findings
| # | Area | Finding | Resolution |
|:--|:--|:--|:--|
| 1 | Test honesty | The "nothing else in the file" test kept no identity, so a leaked field was `undefined`; `toEqual` treats a missing and an undefined property as equal, and `JSON.stringify` drops it. The leak drill passed. | **Fixed**: the test keeps a real identity and uses `toStrictEqual`. Lesson: `testing.md`. |
| 2 | Correctness | The private key cannot be exported, so a rose brought back lives under a new key. | K2: a rose is named by her current key and her past keys; the log is never rewritten. |
| 3 | Correctness | Replaying two devices' care as one log can take a day away (one watering makes the other "too much"). | K3: one replay per key, days unioned; property-tested. |
| 4 | Correctness | Weeds, petals and wind are seeded by key, so a moved rose's pattern of needs changes. | Accepted: the pattern is arbitrary, and her days, stage and drift come with her. A moved rose that is opening still drops petals (tested). |
| 5 | Privacy | The file is a diary of when someone was in the app. | Made only on request; the screen says what it holds; no town and no private key (tested in unit and e2e). It goes wherever the player puts it, which Rosea cannot see. |
| 6 | Privacy | A file brought back could have been edited by hand to give her days she was never given. | It only changes the player's own garden; nothing is counted against anyone (CLAUDE.md §1). Phase 3 must not treat imported care as proof towards friends: noted in the analysis. |
| 7 | Soul | "This browser may clear her" can frighten. | Shown only behind *Keep her safe*, with the remedy in the same sentence; a refusal is said calmly. Nothing reminds or nags. |
| 8 | Process | The first e2e run **and the full gate run** both started with the CPU at 100 %, above the 80 % rule (CLAUDE.md §5.7). The load was another project's test run on this machine. The second time the reading was taken, but the run was chained after it without depending on it. Both passed. | **Fixed on `fix/cpu-guard`**: `pnpm guard:cpu` now runs before every full run. Lesson: `process.md`. |
| 9 | Accessibility | A file input styled as a button. | The real input stays in place, labelled by its text, keyboard-operable; axe passes on the restored garden. Not tested with a screen reader. |
## What was not verified
- `persist()` in real browsers: Chromium under Playwright only answers for itself. Firefox's prompt,
Safari's behaviour, and an installed app's automatic call (K5) were not seen.
- The iOS hint on a real iPhone.
- A file saved by a later version of Rosea (`version` 2): refused today, by design.
+47
View File
@@ -0,0 +1,47 @@
# Review — `fix/cpu-guard`
Adversarial self-review (CLAUDE.md §5.3). Reviewed 2026-11-02 on Node 22.11.0, Windows 10.
There is no PR: the only remote is Gitea.
## Why and what
CLAUDE.md §5.7: *do not start a full run above ~80 % CPU.* On 2026-11-02 that was broken three times
(lessons/process.md), twice right after reading the number. Now `pnpm test`, `test:e2e` and
`test:offline` first run `pnpm guard:cpu` (`tools/cpu-guard`):
```mermaid
flowchart LR
run["pnpm test / test:e2e / test:offline"] --> guard["guard:cpu<br/>sample 2 s with os.cpus()"]
guard -->|"≤ 80 %"| go["the run starts"]
guard -->|"> 80 %"| wait["wait 10 s, sample again"] --> guard
wait -->|"after 180 s"| stop["exit 1: not starting"]
```
Node's `os.cpus()`, not a shell command, so it works the same on Windows, Linux and macOS. A
dedicated machine sets `ROSEA_CPU_MAX` (100 never refuses) and `ROSEA_CPU_WAIT_SECONDS`; a value
that is not a whole number in range is refused, never quietly the default.
## Checks
| Check | Result |
|:--|:--|
| Unit tests, `tools/cpu-guard` | **13 passed**: the busy share between two readings (not since boot), system time as busy, no NaN on equal readings, defaults, overrides, five bad settings, start / wait / refuse |
| On this machine, busy with another project's tests | waited 51 s at 93–100 %, then started at 61 % |
| Forced refusal (`ROSEA_CPU_MAX=1`, no wait) | exit 1 with the reason |
| `pnpm test` behind a refusal | stopped before Turbo ran a single test |
| The guard's reading beside Windows' own counter, sampled together | 64 / 75, 93 / 96, 96 / 98 % |
## Findings
| # | Finding | Resolution |
|:--|:--|:--|
| 1 | The guard measures before the run, not during it: a machine that becomes busy mid-run is not seen. | Accepted: §5.7 is about starting. Stopping a run halfway would leave browsers and servers half-closed, the very mess §5.7 exists to avoid. |
| 2 | `ROSEA_CPU_MAX=100` is a way round the rule. | Documented as for dedicated machines only, in CLAUDE.md §5.7 and the lesson. An override nobody can use would push people to edit the script instead. |
| 3 | The guard adds 2 s to every full run on a quiet machine. | Accepted. |
| 4 | Filtered runs (`pnpm --filter X test`) and drills are not guarded. | By design: they are not full runs. |
| 5 | Its own 2 s sample could read its own start-up as load. | It samples after Node has started. Not measured on a quiet machine: this one was busy all session. Beside Windows' counter it read 2–11 points lower, never higher. |
## Not verified
- macOS and Linux (only Windows 10 here).
- A CI runner: there is none yet (G0.22).
+7 -3
View File
@@ -220,6 +220,7 @@ pnpm test:e2e # builds, then Playwright against the B
pnpm test:offline # builds, loads once, CLOSES the server, reloads
pnpm validate:library # every hope sentence; fixtures must FAIL
pnpm lint:copy # forbidden words and names (§5.6)
pnpm guard:cpu # waits for, then refuses, a machine above 80 % CPU (§5.7)
pnpm art:board # prompts + stand-ins -> tools/art-prep/dist/board/ (docs/ART.md)
pnpm art:accept <id> <file> # an accepted picture -> art/final/*.webp, sheets cut
tsx scripts/build-places.ts <folder> # rebuilds the town list from downloaded Natural Earth + tzdb (by hand)
@@ -412,7 +413,10 @@ happened twice.)*
### 5.7 A test run leaves the machine as it found it
Nothing binds to anything but `127.0.0.1`. Every browser a test starts is closed in `finally`. Do not
start a full run above ~80% CPU. *(Imported from Ludus and Aeterna.)*
start a full run above ~80% CPU. *(Imported from Ludus and Aeterna.)* **Enforced, not trusted:**
`pnpm test`, `test:e2e` and `test:offline` first run `pnpm guard:cpu`, which waits up to three minutes
for the machine to calm and then refuses (`tools/cpu-guard`, lessons/process.md). A dedicated machine
such as CI sets `ROSEA_CPU_MAX` (100 never refuses); never set it to get past a busy desktop.
---
@@ -502,8 +506,8 @@ No timestamp finer than a day, no precise location, no free text, no link to the
| **The library as a scam channel** | If any field lets a sender attach free text, a lonely recipient can be manipulated. The id-only contract (§6.1) is the defence. |
| **Copyright through the back door** | An image prompt "in the style of" the book's drawings, a fox or rose that looks like the original, or a famous line "paraphrased" too closely. All forbidden (§5.6); the art pipeline checks likeness (`docs/ART.md`). |
| **Medical claims in a store listing** | One word like *heal* in marketing copy can pull the product toward medical-device rules. `lint:copy` also runs on store text kept in the repo. |
| **IndexedDB is evictable** *(predicted)* | WebKit can discard origin storage after seven days without interaction — exactly the shape of a player who drifted away and comes back. Call `navigator.storage.persist()` where it exists, prompt iOS players to install, and make export-my-rose a first-class feature. A player returning to find their rose gone is the cruellest bug this product could have. |
| **The stale service worker** | A precached shell keeps serving old JS to a player who has "updated". Detect a waiting worker and offer an explicit, calm *refresh* control. |
| **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. |
| **Two tabs, one database** *(predicted)* | Two event streams into one store; derived state drifts. Use a `BroadcastChannel` lock. |
| **GitHub Pages serves under a sub-path** *(predicted)* | A project site lives at `/<repo>/`, not `/`. Vite `base`, the web manifest `start_url` and `scope`, and the service worker scope must all agree, or the installed app opens a 404 or never updates. The offline suite runs against the same base path. |
| **GitHub Pages cannot set response headers** *(predicted)* | No custom CSP or cache headers. The content-security policy goes in a `<meta>` tag; caching is controlled by the service worker and hashed filenames. |
+16 -4
View File
@@ -12,8 +12,8 @@ Rewritten at the end of each session (CLAUDE.md §5.1).
Gitea hashes match. Analysis: [`.agents/features/phase0-workspace.md`](.agents/features/phase0-workspace.md).
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: 358 (identity 5, schema 16, content 71,
storage 45, art-prep 56, engine 132, ui 33). E2E: 12. Offline: 1. `lint:copy`: 18 files, 0 problems.
- **Gates:** all pass on this machine. Unit tests: 389 (cpu-guard 13, identity 5, schema 16,
content 71, storage 51, art-prep 56, engine 136, ui 41). E2E: 14. Offline: 1. `lint:copy`: 19 files, 0 problems.
`validate:library`: 13 of 13 fixtures rejected.
- **Built, not deployed:** there is no host yet.
- **Roadmap and gameplay docs:** `docs/ROADMAP.md` and `docs/GAMEPLAY.md` are on
@@ -59,8 +59,17 @@ Rewritten at the end of each session (CLAUDE.md §5.1).
care event gained `amount` for watering. `@rosea/identity` makes the player's keypair, kept in
`keys`. Analysis: [`.agents/features/rose.md`](.agents/features/rose.md). Review:
[`.agents/reviews/feature-rose-care.md`](.agents/reviews/feature-rose-care.md).
- **Most urgent open gap: G0.11.** There is now a rose to lose, and nothing yet asks the browser to
keep it or lets the player export it.
- **Keep her safe (G0.11):** merged to `main`. Beside *Her numbers*, *Keep her safe* says what the
browser has promised, asks it to keep her, saves her to a file (her care and keys; never the town,
never the private key) and brings her back from one, on any device, without losing anything she
has there. A rose is now named by her current key and her past keys. Analysis:
[`.agents/features/keep-her-safe.md`](.agents/features/keep-her-safe.md). Review:
[`.agents/reviews/feature-keep-her-safe.md`](.agents/reviews/feature-keep-her-safe.md).
- **A calm refresh (G0.10):** merged to `main`. When a new version of the garden is published, the
installed app fetches it and waits; one quiet line, *A new version of the garden is ready.*, offers
*Refresh*. Nothing reloads by itself. With this, fixes can reach a phone once the app is hosted.
Review: [`.agents/reviews/feature-calm-refresh.md`](.agents/reviews/feature-calm-refresh.md).
**Phase 0 is not finished.** The roadmap's Phase 0 is more than the workspace. Its
gate needs 60 verified sentences (G0.18) and one illustration through the art
@@ -87,6 +96,9 @@ The notification decision is made: in-app only on the web (G0.26).
**How this machine works** (not in the code):
- **The CPU guard:** the full runs wait for this machine to drop to 80 % CPU (§5.7). Other projects'
test runs share it, so a wait of a minute or two is normal; three minutes, and the run is refused.
- **Commit identity:** `mnovak <giteatruenasadminacc.from729@passmail.net>`, set in
this repository only.
- **Pushing:** it uses a repo-local `credential.helper`, copied from Ludus. Do not
+2 -1
View File
@@ -22,6 +22,7 @@
"svelte-check": "4.7.6",
"typescript": "5.9.3",
"vite": "6.4.3",
"vite-plugin-pwa": "1.3.0"
"vite-plugin-pwa": "1.3.0",
"workbox-window": "7.4.1"
}
}
+49 -3
View File
@@ -3,6 +3,7 @@
import { createIdentity } from '@rosea/identity';
import { openStorage } from '@rosea/storage';
import { Shell, type RoseWiring, type SunsetWiring } from '@rosea/ui';
import { registerSW } from 'virtual:pwa-register';
import { version } from '../package.json';
// Bundled at build time, so the letter is precached and opens offline (letter-slot.md L1).
import letter from '../../../docs/LETTER.md?raw';
@@ -48,14 +49,59 @@
}
}
// --- Keeping her (keep-her-safe.md) -------------------------------------
const browserStorage = typeof navigator !== 'undefined' ? navigator.storage : undefined;
const keeping: RoseWiring['keeping'] = {
persisted: async () => (browserStorage?.persisted ? browserStorage.persisted() : null),
persist: async () => (browserStorage?.persist ? browserStorage.persist() : null)
};
const installed = (): boolean =>
matchMedia('(display-mode: standalone)').matches || (navigator as Navigator & { standalone?: boolean }).standalone === true;
// An installed app is asked once, after the first care of a visit: by then there is
// something to lose, and installed apps are not met with a permission prompt (K5).
let askedToKeep = false;
function keepAfterCare(): void {
if (askedToKeep || !installed()) return;
askedToKeep = true;
keeping.persist().catch((error: unknown) => console.error('keep: asking the browser to keep the garden failed', error));
}
function saveFile(name: string, text: string): void {
// A file made here and handed over; nothing is sent anywhere.
const url = URL.createObjectURL(new Blob([text], { type: 'application/json' }));
const a = Object.assign(document.createElement('a'), { href: url, download: name });
document.body.append(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 10_000);
}
// --- A new version waiting (calm-refresh.md) ----------------------------
// The worker is registered here so the page hears when a new version has installed
// and waits. It is offered, never swapped in by itself (U2).
let updateReady = $state(false);
const updateSW = registerSW({
onNeedRefresh: () => (updateReady = true),
onRegisterError: (error: unknown) => console.error('update: the service worker could not be registered', error)
});
const rose: RoseWiring = {
identity: () => (identity ??= findIdentity()),
loadCare: () => storage.loadCare(),
appendCare: (event) => storage.appendCare(event),
appendCare: async (event) => {
await storage.appendCare(event);
keepAfterCare();
},
clientVersion: version,
deviceZone,
now: () => Date.now()
now: () => Date.now(),
pastKeys: () => storage.loadPastKeys(),
exportRose: (currentKey) => storage.exportRose(currentKey),
importRose: (file, currentKey) => storage.importRose(file, currentKey),
saveFile,
keeping,
installHint: /iPhone|iPad|iPod/.test(navigator.userAgent) && !installed()
};
</script>
<Shell {letter} {sunset} {rose} />
<Shell {letter} {sunset} {rose} {updateReady} onrefresh={() => void updateSW(true)} />
+1
View File
@@ -1,2 +1,3 @@
/// <reference types="svelte" />
/// <reference types="vite/client" />
/// <reference types="vite-plugin-pwa/client" />
+4 -3
View File
@@ -66,9 +66,10 @@ export default defineConfig({
// Never swap a running app silently. A new worker waits until the player
// is offered a calm refresh control (CLAUDE.md §8, GAP_ANALYSIS G0.10).
registerType: 'prompt',
// An emitted registerSW.js file, not an inline snippet: the CSP has no
// 'unsafe-inline' for scripts.
injectRegister: 'script',
// The app registers the worker itself through virtual:pwa-register, so it hears
// when a new version is waiting (calm-refresh.md U1). Bundled, not inline: the
// CSP has no 'unsafe-inline' for scripts.
injectRegister: false,
manifest: {
// The web manifest: one of the three places the name lives, built from
// the constants in @rosea/schema so the strings exist only there.
+1 -1
View File
@@ -7,7 +7,7 @@ import { defineConfig, devices } from '@playwright/test';
*/
export default defineConfig({
testDir: '.',
testMatch: /shell\.spec\.ts/,
testMatch: /(shell|update)\.spec\.ts/,
fullyParallel: false,
workers: 1,
retries: 0,
+57
View File
@@ -222,3 +222,60 @@ 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([]);
});
});
// --- Keeping her (.agents/features/keep-her-safe.md) --------------------------
test.describe('keep her safe, in Prague at 08:00 on 1 March 2026', () => {
test.use({ timezoneId: 'Europe/Prague', locale: 'en-US' });
const MORNING = Date.parse('2026-03-01T08:00:00+01:00');
test('save her to a file, lose everything, bring her back: her care returns, and the file never held the town', async ({ browser }) => {
// The first device: choose a town, tend the rose, save her.
const first = await browser.newContext({ timezoneId: 'Europe/Prague', locale: 'en-US' });
let saved = '';
try {
const page = await first.newPage();
await page.clock.setFixedTime(MORNING);
await page.goto(server.url);
await page.getByRole('searchbox', { name: en.sunset.searchLabel }).fill('brno');
await page.getByRole('button', { name: /^Brno/ }).first().click();
await page.getByRole('button', { name: en.rose.water }).hover();
await page.mouse.down();
await page.waitForTimeout(1500);
await page.mouse.up();
await storedCare(page, 1);
await page.getByRole('button', { name: en.rose.safe.title }).click();
const download = page.waitForEvent('download');
await page.getByRole('button', { name: en.rose.safe.save }).click();
const file = await download;
expect(file.suggestedFilename()).toBe('rose-2026-03-01.json');
saved = readFileSync((await file.path())!, 'utf8');
} finally {
await first.close();
}
expect(JSON.parse(saved)).toMatchObject({ format: 'rosea-rose', version: 1 });
expect(saved).not.toMatch(/Brno|privateKey/);
// A fresh profile: the shape of an evicted garden, or a new phone.
const second = await browser.newContext({ timezoneId: 'Europe/Prague', locale: 'en-US' });
try {
const page = await second.newPage();
await page.clock.setFixedTime(MORNING + 3_600_000);
await page.goto(server.url);
await expect(page.getByRole('img', { name: 'The rose, a bud.' })).toBeVisible();
await page.getByRole('button', { name: en.rose.safe.title }).click();
await page.getByLabel(en.rose.safe.bringBack).setInputFiles({ name: 'rose-2026-03-01.json', mimeType: 'application/json', buffer: Buffer.from(saved) });
await expect(page.getByText(en.rose.safe.broughtBack(1))).toBeVisible();
await page.getByRole('button', { name: en.rose.numbers }).click();
await expect(page.locator('#rose-numbers')).toContainText(`${en.rose.daysOfCare}1`);
await storedCare(page, 1);
await page.reload();
await page.getByRole('button', { name: en.rose.numbers }).click();
await expect(page.locator('#rose-numbers')).toContainText(`${en.rose.daysOfCare}1`);
expect((await new AxeBuilder({ page }).analyze()).violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
} finally {
await second.close();
}
});
});
+10 -4
View File
@@ -19,7 +19,7 @@ import { fileURLToPath } from 'node:url';
*/
export const BASE = process.env['ROSEA_BASE'] ?? '/Rosea/';
const DIST = fileURLToPath(new URL('../apps/rosea/dist', import.meta.url));
export const DIST = fileURLToPath(new URL('../apps/rosea/dist', import.meta.url));
const MIME: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
@@ -36,6 +36,8 @@ export interface StaticServer {
readonly url: string;
readonly origin: string;
readonly close: () => Promise<void>;
/** Serves another build from now on, at the same URL: a new version being published. */
readonly serveFrom: (dir: string) => void;
}
export async function startStaticServer(): Promise<StaticServer> {
@@ -45,6 +47,7 @@ export async function startStaticServer(): Promise<StaticServer> {
throw new Error(`No built app at ${DIST}. Run \`pnpm build\` first. (${String(error)})`);
}
let root = DIST;
const server: Server = createServer((req, res) => {
const path = decodeURIComponent((req.url ?? '/').split('?')[0] ?? '/');
@@ -55,9 +58,9 @@ export async function startStaticServer(): Promise<StaticServer> {
}
const rel = normalize(path.slice(BASE.length) || 'index.html');
const file = join(DIST, rel);
// Confine to DIST: a test server is still a server.
if (!file.startsWith(DIST + sep) && file !== DIST) {
const file = join(root, rel);
// Confine to the served folder: a test server is still a server.
if (!file.startsWith(root + sep) && file !== root) {
res.writeHead(403).end();
return;
}
@@ -90,6 +93,9 @@ export async function startStaticServer(): Promise<StaticServer> {
return {
origin,
url: `${origin}${BASE}`,
serveFrom: (dir) => {
root = dir;
},
close: () =>
new Promise<void>((resolve) => {
server.closeAllConnections();
+79
View File
@@ -0,0 +1,79 @@
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 { appendFileSync, cpSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DIST, startStaticServer } from './static-server.js';
/**
* The stale service worker (CLAUDE.md §8, calm-refresh.md). A waiting worker exists
* only between two builds, so this publishes a real second one: version A's build
* with `sw.js` changed, served at the same URL. Its extra listener answers "which
* version are you?", so the test knows for certain which worker controls the page.
*/
const VERSION_B = `
// Added by e2e/update.spec.ts: version B of the worker, and a way to ask.
self.addEventListener('message', (event) => {
if (event.data === 'rosea-which-version') event.source?.postMessage('B');
});
`;
/** "A" unless the controlling worker answers that it is B. */
async function whichVersion(page: Page): Promise<string> {
return page.evaluate(
() =>
new Promise<string>((resolve) => {
const controller = navigator.serviceWorker.controller;
if (!controller) return resolve('none');
const timer = setTimeout(() => resolve('A'), 1500);
navigator.serviceWorker.addEventListener('message', (e) => {
if (e.data === 'B') {
clearTimeout(timer);
resolve('B');
}
});
controller.postMessage('rosea-which-version');
})
);
}
test('a new version waits, is offered in one quiet line, and comes only when the player refreshes', async ({ browser }) => {
const server = await startStaticServer();
const context = await browser.newContext();
const versionB = mkdtempSync(join(tmpdir(), 'rosea-version-b-'));
try {
const page = await context.newPage();
await page.goto(server.url);
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
await page.waitForFunction(() => navigator.serviceWorker.controller !== null, null, { timeout: 20_000 });
expect(await whichVersion(page)).toBe('A');
await expect(page.getByText(en.update.ready)).toHaveCount(0);
// Publish version B at the same URL.
cpSync(DIST, versionB, { recursive: true });
appendFileSync(join(versionB, 'sw.js'), VERSION_B);
server.serveFrom(versionB);
// A navigation makes the browser check for a new worker, as it does for a player.
await page.reload();
await expect(page.getByText(en.update.ready)).toBeVisible({ timeout: 20_000 });
// Offered, not swapped: A still controls the page, and B waits.
expect(await whichVersion(page)).toBe('A');
expect(await page.evaluate(async () => (await navigator.serviceWorker.getRegistration())?.waiting !== null)).toBe(true);
expect((await new AxeBuilder({ page }).analyze()).violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
// The player refreshes: B takes over and the page reloads under it.
await Promise.all([page.waitForEvent('load'), page.getByRole('button', { name: en.update.refresh }).click()]);
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
await expect.poll(() => whichVersion(page), { timeout: 10_000 }).toBe('B');
await expect(page.getByText(en.update.ready)).toHaveCount(0);
} finally {
// A test run leaves the machine as it found it (CLAUDE.md §5.7).
await context.close();
await server.close();
rmSync(versionB, { recursive: true, force: true });
}
});
+5 -4
View File
@@ -12,13 +12,14 @@
"build": "turbo run build",
"typecheck": "turbo run typecheck && tsc -p tsconfig.json --noEmit",
"lint": "eslint .",
"test": "turbo run test",
"test:e2e": "turbo run build --filter=@rosea/app && playwright test --config=e2e/playwright.config.ts",
"test:offline": "turbo run build --filter=@rosea/app && playwright test --config=e2e/playwright.offline.config.ts",
"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",
"validate:library": "tsx scripts/validate-library.ts",
"lint:copy": "tsx scripts/lint-copy.ts",
"art:board": "tsx tools/art-prep/src/cli-board.ts",
"art:accept": "tsx tools/art-prep/src/cli-accept.ts"
"art:accept": "tsx tools/art-prep/src/cli-accept.ts",
"guard:cpu": "tsx tools/cpu-guard/src/cli.ts"
},
"devDependencies": {
"@axe-core/playwright": "4.13.0",
+2 -2
View File
@@ -1,6 +1,6 @@
export { addDays, daysBetween, isLocalDay, localDay, localMinutes, type LocalDay } from './time/localDay.js';
export {
careEvent, judgeCare, OWN_TRACE, petalsOn, pour, ROSE, roseAt, seeded, stageFor, weedsOn, windOn,
type Judged, type Mood, type Needs, type RoseNow, type Stage, type Trend
careEvent, careIdentity, judgeCare, newCare, OWN_TRACE, petalsOn, pour, ROSE, roseAt, seeded, stageFor, weedsOn, windOn,
type Judged, type Mood, type Needs, type RoseKeys, type RoseNow, type Stage, type Trend
} from './rose/rose.js';
export { invitation, nextInvitation, sunDay, type NamedPlace, type Place, type SunDay } from './sun/sun.js';
+62 -14
View File
@@ -124,6 +124,23 @@ export function careEvent(p: {
return { ...base, amount: Math.round(Math.min(1, Math.max(0, p.amount ?? 0)) * 100) / 100 };
}
/** What makes two care events the same act: the same moment, giver, rose and act. */
export const careIdentity = (e: CareEvent): string => `${e.ts}|${e.from}|${e.to}|${e.act}|${e.amount ?? ''}`;
/** The acts in `incoming` that `existing` does not hold yet: bringing a rose back twice adds nothing twice. */
export function newCare(existing: readonly CareEvent[], incoming: readonly CareEvent[]): CareEvent[] {
const seen = new Set(existing.map(careIdentity));
const out: CareEvent[] = [];
for (const e of incoming) {
const id = careIdentity(e);
if (!seen.has(id)) {
seen.add(id);
out.push(e);
}
}
return out;
}
/** One act of the log, judged: did it meet a real need? */
export interface Judged {
readonly event: CareEvent;
@@ -141,14 +158,26 @@ interface Replay {
const fall = (level: number, from: number | null, to: number): number =>
from === null ? level : Math.max(0, level - (ROSE.waterFallPerDay * Math.max(0, to - from)) / DAY_MS);
/** The log in order, each act judged. Only care given to this rose counts. */
function replay(events: readonly CareEvent[], seed: string, timeZone: string): Replay {
/**
* The rose's keys: the current one first, then any she was named by before, on
* another device (keep-her-safe.md K2). A single key is a rose that never moved.
*/
export type RoseKeys = string | readonly string[];
const keyList = (keys: RoseKeys): readonly string[] => (typeof keys === 'string' ? [keys] : keys);
/**
* The care given under one key, in order, each act judged with that key's own
* weeds, petals and wind. `inherited` are days of care earned under her other keys:
* they count towards her stage, so a moved rose drops petals as she did before.
*/
function replay(events: readonly CareEvent[], seed: string, timeZone: string, inherited: ReadonlySet<LocalDay> = new Set()): Replay {
const mine = events
.map((e, i) => ({ e, i }))
.filter(({ e }) => e.kind === 'care' && e.to === seed)
.sort((a, b) => a.e.ts - b.e.ts || a.i - b.i)
.map(({ e }) => e);
const grownBy = (day: LocalDay): number => new Set([...days, ...[...inherited].filter((d) => d <= day)]).size;
const days = new Set<LocalDay>();
const met = new Map<string, true>();
const judged: Judged[] = [];
@@ -172,7 +201,7 @@ function replay(events: readonly CareEvent[], seed: string, timeZone: string): R
if (helped) met.set(`${day}|weeds`, true);
break;
case 'petals':
helped = stageFor(days.size) !== 'bud' && petalsOn(seed, day) && !met.has(`${day}|petals`);
helped = stageFor(grownBy(day)) !== 'bud' && petalsOn(seed, day) && !met.has(`${day}|petals`);
if (helped) met.set(`${day}|petals`, true);
break;
case 'shade': {
@@ -189,17 +218,36 @@ function replay(events: readonly CareEvent[], seed: string, timeZone: string): R
return { judged, days, water: { level, at }, met, firstDay: mine[0]?.localDay ?? null };
}
/** Every act of the log with whether it helped, in order. */
export function judgeCare(events: readonly CareEvent[], seed: string, timeZone: string): readonly Judged[] {
return replay(events, seed, timeZone).judged;
/**
* Replays every key separately: the past keys first, then the current one, which
* inherits their days. Each key's judgments depend only on its own care, so adding
* another key's log can never take a day of care away (keep-her-safe.md K3).
*/
function replayAll(events: readonly CareEvent[], keys: RoseKeys, timeZone: string): { current: Replay; all: readonly Replay[]; days: ReadonlySet<LocalDay> } {
const [currentKey = '', ...past] = keyList(keys);
const pastReplays = past.map((k) => replay(events, k, timeZone));
const inherited = new Set(pastReplays.flatMap((r) => [...r.days]));
const current = replay(events, currentKey, timeZone, inherited);
return { current, all: [current, ...pastReplays], days: new Set([...inherited, ...current.days]) };
}
/** The rose at `now`: a pure replay of `events` for the rose whose key is `seed`. */
export function roseAt(events: readonly CareEvent[], seed: string, now: number, timeZone: string): RoseNow {
const r = replay(events, seed, timeZone);
/** Every act given to the rose, with whether it helped, in time order. */
export function judgeCare(events: readonly CareEvent[], keys: RoseKeys, timeZone: string): readonly Judged[] {
return replayAll(events, keys, timeZone).all.flatMap((r) => r.judged).sort((a, b) => a.event.ts - b.event.ts);
}
/**
* The rose at `now`: a pure replay of `events` for the rose named by `keys`. Her
* water and today's needs come from the current key; her days of care, stage and
* drift from all of them.
*/
export function roseAt(events: readonly CareEvent[], keys: RoseKeys, now: number, timeZone: string): RoseNow {
const { current: r, all, days } = replayAll(events, keys, timeZone);
const seed = keyList(keys)[0] ?? '';
const today = localDay(now, timeZone);
const water = fall(r.water.level, r.water.at, now);
const stage = stageFor(r.days.size);
const stage = stageFor(days.size);
const firstDay = all.map((x) => x.firstDay).filter((d): d is LocalDay => d !== null).sort()[0] ?? null;
const wind = windOn(seed, today);
const minute = localMinutes(now, timeZone);
@@ -210,15 +258,15 @@ export function roseAt(events: readonly CareEvent[], seed: string, now: number,
wind: wind !== null && minute >= wind[0] && minute < wind[1] && !r.met.has(`${today}|wind`)
};
const careDays = [...r.days].filter((d) => d <= today).sort();
const careDays = [...days].filter((d) => d <= today).sort();
const lastDayOfCare = careDays.at(-1) ?? null;
const since = daysBetween(lastDayOfCare ?? r.firstDay ?? today, today);
const since = daysBetween(lastDayOfCare ?? firstDay ?? today, today);
const drift = since >= ROSE.driftDays[1] ? 2 : since >= ROSE.driftDays[0] ? 1 : 0;
const weekStart = addDays(today, -6);
const warmth = careDays.filter((d) => d >= weekStart).length;
const trend: Trend = drift > 0 ? 'waiting' : lastDayOfCare !== null && daysBetween(lastDayOfCare, today) <= 1 ? 'growing' : 'steady';
const lastHelp = [...r.judged].reverse().find((j) => j.helped && j.event.ts <= now);
const lastHelp = all.flatMap((x) => x.judged).filter((j) => j.helped && j.event.ts <= now).sort((a, b) => b.event.ts - a.event.ts)[0];
const blushing = lastHelp !== undefined && now - lastHelp.event.ts < ROSE.blushMinutes * 60_000;
const mood: Mood = blushing ? 'blushing'
: water > ROSE.tooFull ? 'too-full'
@@ -227,5 +275,5 @@ export function roseAt(events: readonly CareEvent[], seed: string, now: number,
: water < ROSE.thirsty ? 'thirsty'
: 'content';
return { stage, drift, mood, water, needs, daysOfCare: r.days.size, warmth, trend, lastDayOfCare };
return { stage, drift, mood, water, needs, daysOfCare: days.size, warmth, trend, lastDayOfCare };
}
+48 -1
View File
@@ -1,7 +1,7 @@
import fc from 'fast-check';
import type { CareEvent } from '@rosea/schema';
import { describe, expect, it } from 'vitest';
import { careEvent, judgeCare, OWN_TRACE, petalsOn, pour, ROSE, roseAt, stageFor, weedsOn, windOn, type Stage } from '../src/rose/rose.js';
import { careEvent, judgeCare, newCare, OWN_TRACE, petalsOn, pour, ROSE, roseAt, stageFor, weedsOn, windOn, type Stage } from '../src/rose/rose.js';
import { addDays, localDay } from '../src/time/localDay.js';
const ZONE = 'Europe/Prague';
@@ -208,3 +208,50 @@ describe('careEvent — one act as the log keeps it', () => {
expect(validateCareEvent(s)).toMatchObject({ ok: true });
});
});
describe('a rose brought back under a new key (keep-her-safe.md)', () => {
const NEW = 'N'.repeat(43);
const careAs = (to: string, ts: number, amount = 0.5): CareEvent => ({ ...care(ts, 'water', amount), from: to, to });
it('keeps every day of care given under her old key, and starts her water afresh under the new one', () => {
const old = dailyWater(12);
const now = START + 12 * DAY;
const before = roseAt(old, ME, now, ZONE);
const moved = roseAt(old, [NEW, ME], now, ZONE);
expect(moved.daysOfCare).toBe(before.daysOfCare);
expect(moved.stage).toBe(before.stage);
expect(moved.lastDayOfCare).toBe(before.lastDayOfCare);
expect(moved.water).toBe(ROSE.waterStart); // no care under the new key yet
// Care under the new key adds to the old days.
const after = roseAt([...old, careAs(NEW, now)], [NEW, ME], now + 60_000, ZONE);
expect(after.daysOfCare).toBe(before.daysOfCare + 1);
});
it('a moved rose that is opening drops petals, and gathering them helps', () => {
const old = dailyWater(ROSE.stageDays[0]);
const from = START + ROSE.stageDays[0] * DAY;
let day = from;
while (!petalsOn(NEW, localDay(day, ZONE))) day += DAY;
expect(roseAt(old, [NEW, ME], day, ZONE).needs.petals).toBe(true);
const gathered = { ...care(day, 'petals'), from: NEW, to: NEW };
expect(judgeCare([...old, gathered], [NEW, ME], ZONE).at(-1)?.helped).toBe(true);
});
it('merging two logs never takes a day of care away from either', () => {
const act = fc.constantFrom<CareEvent['act']>('water', 'shade', 'weed', 'petals');
const logAs = (to: string) => fc.array(fc.tuple(fc.integer({ min: 0, max: 40 * 24 * 60 }), act, fc.double({ min: 0, max: 1, noNaN: true })), { maxLength: 40 })
.map((xs) => xs.map(([m, a, amount]) => ({ ...care(START + m * 60_000, a, amount), from: to, to })));
fc.assert(fc.property(logAs(ME), logAs(NEW), (a, b) => {
const end = START + 50 * DAY;
const merged = roseAt([...a, ...b], [NEW, ME], end, ZONE).daysOfCare;
return merged >= roseAt(a, ME, end, ZONE).daysOfCare && merged >= roseAt(b, NEW, end, ZONE).daysOfCare;
}), { numRuns: 150 });
});
it('newCare adds each act once, however often the same file is brought back', () => {
const log = dailyWater(3);
expect(newCare([], log)).toEqual(log);
expect(newCare(log, log)).toEqual([]);
expect(newCare(log.slice(0, 1), [...log, ...log])).toEqual(log.slice(1));
});
});
+67 -2
View File
@@ -10,7 +10,7 @@
* may enter a log that is never edited.
*/
import Dexie, { type DexieOptions, type Table } from 'dexie';
import type { NamedPlace } from '@rosea/engine';
import { newCare, type NamedPlace } from '@rosea/engine';
import { isIdentity, type Identity } from '@rosea/identity';
import { DATABASE_NAME, type CareEvent } from '@rosea/schema';
@@ -35,6 +35,17 @@ interface KeyRow {
const SUNSET_PLACE = 'sunsetPlace';
const SELF = 'self';
const PAST_KEYS = 'pastKeys';
/** The file a rose is saved to and brought back from (keep-her-safe.md K4). Never the private key, never the town. */
export const ROSE_FILE_FORMAT = 'rosea-rose';
export interface RoseFile {
readonly format: typeof ROSE_FILE_FORMAT;
readonly version: 1;
/** The keys that have named her, the one she had when saved first. Public keys only. */
readonly keys: readonly string[];
readonly events: readonly CareEvent[];
}
export interface Storage {
/** The saved sunset place, or null if the player has not answered yet. */
@@ -50,6 +61,15 @@ export interface Storage {
*/
keepIdentity(fresh: Identity): Promise<Identity>;
loadIdentity(): Promise<Identity | null>;
/** Keys the rose was named by before, on another device; the current one is not among them. */
loadPastKeys(): Promise<string[]>;
/** The rose, as a file the player keeps (keep-her-safe.md). */
exportRose(currentKey: string): Promise<RoseFile>;
/**
* Brings a saved rose back: her keys join the past keys and every act not already
* here is appended. Nothing is edited or removed. Rejects a file that is not a rose.
*/
importRose(file: unknown, currentKey: string): Promise<{ readonly added: number }>;
close(): void;
}
@@ -98,6 +118,23 @@ export function asCareEvent(value: unknown): CareEvent | null {
return isWater ? { ...base, amount: v['amount'] as number } : base;
}
const isKeyList = (x: unknown): x is string[] => Array.isArray(x) && x.every((k) => matches(k, KEY));
/** The shape check for a saved rose. Every act must pass the care event contract. */
export function asRoseFile(value: unknown): RoseFile | null {
if (typeof value !== 'object' || value === null) return null;
const v = value as Record<string, unknown>;
if (v['format'] !== ROSE_FILE_FORMAT || v['version'] !== 1) return null;
if (!isKeyList(v['keys']) || v['keys'].length === 0 || !Array.isArray(v['events'])) return null;
const events: CareEvent[] = [];
for (const e of v['events'] as unknown[]) {
const plain = asCareEvent(e);
if (plain === null) return null;
events.push(plain);
}
return { format: ROSE_FILE_FORMAT, version: 1, keys: [...new Set(v['keys'])], events };
}
class RoseaDatabase extends Dexie {
profile!: Table<ProfileRow, string>;
events!: Table<EventRow, number>;
@@ -121,7 +158,7 @@ export function openStorage(options?: DexieOptions): Storage {
const id = row ? { publicKey: row.publicKey, privateKey: row.privateKey } : null;
return id && isIdentity(id) ? id : null;
};
return {
const api: Storage = {
async loadSunsetPlace() {
const row = await db.profile.get(SUNSET_PLACE);
if (row === undefined) return null;
@@ -163,8 +200,36 @@ export function openStorage(options?: DexieOptions): Storage {
async loadIdentity() {
return asIdentity(await db.keys.get(SELF));
},
async loadPastKeys() {
const row = await db.profile.get(PAST_KEYS);
if (row === undefined) return [];
if (!isKeyList(row.value)) {
console.warn('storage: the past keys have an unknown shape; ignoring them', row.value);
return [];
}
return row.value;
},
async exportRose(currentKey) {
const past = await api.loadPastKeys();
return { format: ROSE_FILE_FORMAT, version: 1, keys: [...new Set([currentKey, ...past])], events: await api.loadCare() };
},
async importRose(file, currentKey) {
const rose = asRoseFile(file);
if (rose === null) throw new TypeError('storage: this file does not hold a rose');
return db.transaction('rw', db.events, db.profile, async () => {
const row = await db.profile.get(PAST_KEYS);
const past = isKeyList(row?.value) ? row.value : [];
const keys = [...new Set([...past, ...rose.keys])].filter((k) => k !== currentKey);
await db.profile.put({ key: PAST_KEYS, value: keys });
const existing = (await db.events.orderBy('id').toArray()).map((r) => asCareEvent(r.event)).filter((e): e is CareEvent => e !== null);
const added = newCare(existing, rose.events);
await db.events.bulkAdd(added.map((event) => ({ event })));
return { added: added.length };
});
},
close() {
db.close();
}
};
return api;
}
+91
View File
@@ -0,0 +1,91 @@
import { createIdentity } from '@rosea/identity';
import type { CareEvent } from '@rosea/schema';
import { IDBFactory, IDBKeyRange } from 'fake-indexeddb';
import { afterEach, describe, expect, it } from 'vitest';
import { asRoseFile, openStorage, ROSE_FILE_FORMAT, type Storage } from '../src/index.js';
const OLD = 'O'.repeat(87);
const NEW = 'N'.repeat(87);
const act = (to: string, ts: number): CareEvent => ({
kind: 'care', ts, localDay: '2026-03-01', from: to, to, act: 'water',
trace: 'petal:rose', messageId: null, clientVersion: '0.1.0', amount: 0.5
});
const opened: Storage[] = [];
const open = (indexedDB: IDBFactory = new IDBFactory()): Storage => {
const s = openStorage({ indexedDB, IDBKeyRange });
opened.push(s);
return s;
};
afterEach(() => {
for (const s of opened.splice(0)) s.close();
});
describe('saving the rose to a file', () => {
it('holds her keys and her care, and nothing else: no private key, no town', async () => {
const s = open();
// A real identity is kept, so a leak of anything from it would have something to leak.
await s.keepIdentity(await createIdentity());
await s.saveSunsetPlace({ kind: 'town', town: { name: 'Brno', region: '', country: 'Czechia', lat: 49.2, lon: 16.61, timeZone: 'Europe/Prague' } });
await s.appendCare(act(OLD, 1));
const file = await s.exportRose(OLD);
expect(file).toStrictEqual({ format: ROSE_FILE_FORMAT, version: 1, keys: [OLD], events: [act(OLD, 1)] });
expect(JSON.stringify(file)).not.toMatch(/Brno|privateKey|CryptoKey/);
});
it('survives a trip through JSON text unchanged', async () => {
const s = open();
await s.appendCare(act(OLD, 1));
const file = await s.exportRose(OLD);
expect(asRoseFile(JSON.parse(JSON.stringify(file)))).toEqual(file);
});
});
describe('bringing her back', () => {
it('on a new device: her old key joins the past keys and all her care comes back', async () => {
const old = open();
await old.appendCare(act(OLD, 1));
await old.appendCare(act(OLD, 2));
const file = JSON.parse(JSON.stringify(await old.exportRose(OLD)));
const fresh = open();
expect(await fresh.importRose(file, NEW)).toEqual({ added: 2 });
expect(await fresh.loadPastKeys()).toEqual([OLD]);
expect(await fresh.loadCare()).toEqual([act(OLD, 1), act(OLD, 2)]);
});
it('twice is the same as once, and the care given here meanwhile stays', async () => {
const old = open();
await old.appendCare(act(OLD, 1));
const file = await old.exportRose(OLD);
const here = open();
await here.appendCare(act(NEW, 5));
await here.importRose(file, NEW);
expect(await here.importRose(file, NEW)).toEqual({ added: 0 });
expect(await here.loadCare()).toEqual([act(NEW, 5), act(OLD, 1)]);
expect(await here.loadPastKeys()).toEqual([OLD]);
});
it('a file saved on this very device adds nothing and does not list its own key as past', async () => {
const s = open();
await s.appendCare(act(NEW, 1));
expect(await s.importRose(await s.exportRose(NEW), NEW)).toEqual({ added: 0 });
expect(await s.loadPastKeys()).toEqual([]);
});
it('refuses anything that is not a rose, and changes nothing', async () => {
const s = open();
await s.appendCare(act(NEW, 1));
for (const bad of [
null, 'rose', { format: 'other', version: 1, keys: [OLD], events: [] },
{ format: ROSE_FILE_FORMAT, version: 2, keys: [OLD], events: [] },
{ format: ROSE_FILE_FORMAT, version: 1, keys: [], events: [] },
{ format: ROSE_FILE_FORMAT, version: 1, keys: ['short'], events: [] },
{ format: ROSE_FILE_FORMAT, version: 1, keys: [OLD], events: [{ ...act(OLD, 1), note: 'hello' }] }
]) {
await expect(s.importRose(bad, NEW)).rejects.toThrow(/does not hold a rose/);
}
expect(await s.loadCare()).toEqual([act(NEW, 1)]);
expect(await s.loadPastKeys()).toEqual([]);
});
});
+44 -1
View File
@@ -13,7 +13,9 @@
let {
letter = '',
sunset,
rose
rose,
updateReady = false,
onrefresh
}: {
/** The author's Markdown from docs/LETTER.md. Empty means there is no way to the page. */
letter?: string;
@@ -21,6 +23,10 @@
sunset?: SunsetWiring;
/** The rose and her care log. Absent, the garden has no rose. */
rose?: RoseWiring;
/** A new version of the garden is installed and waiting (calm-refresh.md). */
updateReady?: boolean;
/** Swap to the waiting version and reload. Only ever called by the player's tap. */
onrefresh?: () => void;
} = $props();
// --- The sunset (sunset-place.md) ---------------------------------------
@@ -143,6 +149,14 @@
</main>
{/if}
{#if updateReady && onrefresh}
<aside class="update" aria-label={en.update.ready}>
<p role="status">{en.update.ready}</p>
<button type="button" onclick={onrefresh}>{en.update.refresh}</button>
</aside>
{/if}
<style>
.shell {
min-height: 100dvh;
@@ -205,6 +219,35 @@
cursor: pointer;
}
.update {
position: sticky;
bottom: 0;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
gap: var(--space-2);
padding: var(--space-2) var(--space-3);
background: var(--paper);
border-top: 1px solid color-mix(in srgb, var(--ink-soft) 30%, transparent);
}
.update p {
margin: 0;
color: var(--ink-soft);
}
.update button {
font: inherit;
padding: var(--space-1) var(--space-3);
border-radius: 999px;
border: 1px solid var(--rose);
background: var(--paper);
color: var(--ink);
cursor: pointer;
}
.update button:focus-visible,
.quiet:focus-visible {
outline: 2px solid var(--rose);
outline-offset: 2px;
+22 -1
View File
@@ -49,7 +49,23 @@ export const en = {
petals: 'A few of my petals have fallen. Would you gather them?',
tooFull: 'That was a lot of water. I will be fine by tomorrow.'
},
notKept: 'This device could not keep today’s care, so it lasts only until the garden closes.'
notKept: 'This device could not keep today’s care, so it lasts only until the garden closes.',
/** Keeping her (keep-her-safe.md). True and calm: a browser can clear a site's data. */
safe: {
title: 'Keep her safe',
kept: 'This browser has promised to keep her.',
mayClear: 'This browser may clear her if the garden is not opened for a long time. A saved file keeps her for sure.',
unknown: 'This browser decides for itself how long it keeps her. A saved file keeps her for sure.',
ask: 'Ask the browser to keep her',
refused: 'The browser did not promise. A saved file keeps her for sure.',
install: 'On an iPhone or iPad, add the garden to your Home Screen to keep her.',
save: 'Save her to a file',
fileNote: 'The file holds her care and when it was given. It never holds your town.',
bringBack: 'Bring her back from a file',
broughtBack: (n: number): string => (n === 1 ? 'She is back, with 1 act of care.' : `She is back, with ${n} acts of care.`),
alreadyHere: 'Everything in that file is already here.',
notARose: 'That file does not hold a rose.'
}
},
sunset: {
/** ROADMAP Phase 1, word for word. */
@@ -72,6 +88,11 @@ export const en = {
/** When the device refuses to keep anything (a private window). Calm, and true. */
notKept: 'This device could not keep your choice, so the garden will ask again next time.'
},
update: {
/** One quiet line when a new version waits; nothing reloads by itself (calm-refresh.md U2). */
ready: 'A new version of the garden is ready.',
refresh: 'Refresh'
},
letter: {
/** The help section's name (ROADMAP §1). The letter itself is the author's, in docs/LETTER.md. */
title: 'A Letter from the Gardener',
+152
View File
@@ -0,0 +1,152 @@
<script lang="ts">
import { en } from '../copy/en.js';
import type { RoseWiring } from './types.js';
/**
* Keeping her (keep-her-safe.md): what the browser has promised, asking it to keep
* her, saving her to a file, and bringing her back from one. Decides nothing; the
* file's shape is checked by storage.
*/
let { wiring, currentKey, today, onrestored }: { wiring: RoseWiring; currentKey: string; today: string; onrestored: () => void } = $props();
const uid = $props.id();
let persisted = $state<boolean | null | undefined>(undefined);
let refused = $state(false);
let said = $state('');
$effect(() => {
wiring.keeping.persisted().then(
(p) => (persisted = p),
(error: unknown) => {
console.error('keep: the browser could not say whether it keeps the garden', error);
persisted = null;
}
);
});
async function ask(): Promise<void> {
try {
const granted = await wiring.keeping.persist();
persisted = granted;
refused = granted !== true;
} catch (error) {
console.error('keep: asking the browser to keep the garden failed', error);
refused = true;
}
}
async function save(): Promise<void> {
try {
const file = await wiring.exportRose(currentKey);
wiring.saveFile(`rose-${today}.json`, JSON.stringify(file, null, 1));
} catch (error) {
console.error('keep: the rose could not be saved to a file', error);
}
}
async function bringBack(event: Event & { currentTarget: HTMLInputElement }): Promise<void> {
const input = event.currentTarget;
const file = input.files?.[0];
if (!file) return;
try {
const { added } = await wiring.importRose(JSON.parse(await file.text()), currentKey);
said = added === 0 ? en.rose.safe.alreadyHere : en.rose.safe.broughtBack(added);
onrestored();
} catch (error) {
// A wrong file is an ordinary thing to choose; the player is told calmly, the console fully.
console.warn('keep: the chosen file is not a rose', error);
said = en.rose.safe.notARose;
} finally {
input.value = '';
}
}
</script>
<section class="safe" aria-labelledby="{uid}-title">
<h3 id="{uid}-title">{en.rose.safe.title}</h3>
{#if persisted !== undefined}
<p>{refused ? en.rose.safe.refused : persisted === true ? en.rose.safe.kept : persisted === false ? en.rose.safe.mayClear : en.rose.safe.unknown}</p>
{/if}
{#if persisted === false && !refused}
<button type="button" class="quiet" onclick={ask}>{en.rose.safe.ask}</button>
{/if}
{#if wiring.installHint}
<p>{en.rose.safe.install}</p>
{/if}
<button type="button" onclick={save}>{en.rose.safe.save}</button>
<p class="note">{en.rose.safe.fileNote}</p>
<label class="file">
<span>{en.rose.safe.bringBack}</span>
<input type="file" accept="application/json,.json" onchange={bringBack} />
</label>
<p class="said" role="status">{said}</p>
</section>
<style>
.safe {
display: grid;
gap: var(--space-2);
justify-items: center;
max-width: 24rem;
text-align: center;
}
h3 {
margin: 0;
font-family: var(--font-display);
font-weight: 400;
font-size: 1.1rem;
}
p {
margin: 0;
}
.note,
.said {
color: var(--ink-soft);
font-size: 0.9rem;
}
.said:empty {
display: none;
}
button,
.file {
font: inherit;
padding: var(--space-2) var(--space-3);
border-radius: 999px;
border: 1px solid var(--rose);
background: var(--paper);
color: var(--ink);
cursor: pointer;
}
.quiet {
border: none;
padding: var(--space-1) 0;
color: var(--rose);
text-decoration: underline;
}
.file {
position: relative;
}
/* The real input stays operable and labelled; only its default look is hidden. */
.file input {
position: absolute;
inset: 0;
opacity: 0;
cursor: pointer;
}
.file:focus-within,
button:focus-visible {
outline: 2px solid var(--rose);
outline-offset: 2px;
}
</style>
+33 -5
View File
@@ -1,7 +1,8 @@
<script lang="ts">
import { careEvent, pour, roseAt, ROSE, type Mood, type RoseNow, type Stage } from '@rosea/engine';
import { careEvent, localDay, pour, roseAt, ROSE, type Mood, type RoseNow, type Stage } from '@rosea/engine';
import type { CareEvent } from '@rosea/schema';
import { en } from '../copy/en.js';
import KeepSafe from './KeepSafe.svelte';
import type { RoseWiring } from './types.js';
// The art board's stand-ins until real art is accepted (rose.md R10, docs/ART.md).
import bud from '../../../../art/placeholders/rose-bud.svg?url';
@@ -24,6 +25,9 @@
const MOOD_PICTURE: Record<Mood, string> = { content: fullBloom, thirsty, 'too-full': overwatered, windblown, blushing, waiting };
let seed = $state<string | null>(null);
/** Keys she was named by on another device (keep-her-safe.md K2). */
let pastKeys = $state.raw<readonly string[]>([]);
let showSafe = $state(false);
let events = $state.raw<readonly CareEvent[]>([]);
let now = $state(0);
let kept = $state(true);
@@ -32,10 +36,11 @@
$effect(() => {
const w = wiring;
now = w.now();
Promise.all([w.identity(), w.loadCare()]).then(
([id, log]) => {
Promise.all([w.identity(), w.loadCare(), w.pastKeys()]).then(
([id, log, past]) => {
seed = id.publicKey;
events = log;
pastKeys = past;
if (!id.kept) kept = false;
},
(error: unknown) => {
@@ -48,7 +53,19 @@
return () => clearInterval(timer);
});
const rose = $derived<RoseNow | null>(seed === null ? null : roseAt(events, seed, now, timeZone));
const rose = $derived<RoseNow | null>(seed === null ? null : roseAt(events, [seed, ...pastKeys], now, timeZone));
/** After she is brought back from a file: read her log and keys again. */
function restored(): void {
Promise.all([wiring.loadCare(), wiring.pastKeys()]).then(
([log, past]) => {
events = log;
pastKeys = past;
now = wiring.now();
},
(error: unknown) => console.error('rose: could not read her back after restoring', error)
);
}
function care(act: CareEvent['act'], amount?: number): void {
if (seed === null) return;
@@ -162,7 +179,10 @@
<p class="hint">{en.rose.notKept}</p>
{/if}
<button type="button" class="quiet" aria-expanded={showNumbers} aria-controls="rose-numbers" onclick={() => (showNumbers = !showNumbers)}>{en.rose.numbers}</button>
<div class="more">
<button type="button" class="quiet" aria-expanded={showNumbers} aria-controls="rose-numbers" onclick={() => (showNumbers = !showNumbers)}>{en.rose.numbers}</button>
<button type="button" class="quiet" aria-expanded={showSafe} onclick={() => (showSafe = !showSafe)}>{en.rose.safe.title}</button>
</div>
{#if showNumbers}
<dl id="rose-numbers" class="numbers">
<dt>{en.rose.waterLevel}</dt><dd>{percent(rose.water)}</dd>
@@ -171,6 +191,9 @@
<dt>{en.rose.trend}</dt><dd>{en.rose.trendWords[rose.trend]}</dd>
</dl>
{/if}
{#if showSafe && seed}
<KeepSafe {wiring} currentKey={seed} today={localDay(now, timeZone)} onrestored={restored} />
{/if}
</section>
{/if}
@@ -253,6 +276,11 @@
cursor: pointer;
}
.more {
display: flex;
gap: var(--space-3);
}
.numbers {
display: grid;
grid-template-columns: auto auto;
+14
View File
@@ -14,4 +14,18 @@ export interface RoseWiring {
readonly deviceZone: string;
/** The clock. A parameter, so tests and the e2e suite can fix it. */
readonly now: () => number;
/** Keys the rose was named by before, on another device (keep-her-safe.md K2). */
readonly pastKeys: () => Promise<string[]>;
/** The rose as a file's contents, and bringing one back. */
readonly exportRose: (currentKey: string) => Promise<unknown>;
readonly importRose: (file: unknown, currentKey: string) => Promise<{ readonly added: number }>;
/** Hands the player a file to keep. */
readonly saveFile: (name: string, text: string) => void;
/** The browser's promise to keep the garden: true, false, or null when it cannot say. */
readonly keeping: {
readonly persisted: () => Promise<boolean | null>;
readonly persist: () => Promise<boolean | null>;
};
/** True on an iPhone or iPad not yet added to the Home Screen, where Safari may clear her. */
readonly installHint: boolean;
}
+24
View File
@@ -83,3 +83,27 @@ describe('Shell and the Letter', () => {
expect(screen.getByText(/or not\./)).toBeTruthy();
});
});
describe('Shell and a new version waiting (calm-refresh.md)', () => {
it('says nothing while no new version waits', () => {
render(Shell, { onrefresh: () => undefined });
expect(screen.queryByText(en.update.ready)).toBeNull();
expect(screen.queryByRole('button', { name: en.update.refresh })).toBeNull();
});
it('when one waits: one quiet line and Refresh, which only the player\'s tap sends', async () => {
let refreshed = 0;
render(Shell, { updateReady: true, onrefresh: () => (refreshed += 1) });
expect(screen.getByRole('status').textContent).toBe(en.update.ready);
expect(refreshed).toBe(0);
await fireEvent.click(screen.getByRole('button', { name: en.update.refresh }));
expect(refreshed).toBe(1);
});
it('is there on the Letter too', () => {
window.location.hash = '#letter';
render(Shell, { letter: LETTER, updateReady: true, onrefresh: () => undefined });
expect(h1().textContent).toBe(en.letter.title);
expect(screen.getByRole('button', { name: en.update.refresh })).toBeTruthy();
});
});
+92 -2
View File
@@ -13,8 +13,9 @@ const ME = 'M'.repeat(87);
const MORNING = Date.parse('2026-03-01T08:00:00+01:00');
const DAY = 86_400_000;
function wiring(over: Partial<RoseWiring> & { log?: CareEvent[]; at?: number } = {}): RoseWiring & { appended: CareEvent[] } {
function wiring(over: Partial<RoseWiring> & { log?: CareEvent[]; at?: number } = {}): RoseWiring & { appended: CareEvent[]; saved: { name: string; text: string }[] } {
const appended: CareEvent[] = [];
const saved: { name: string; text: string }[] = [];
const at = over.at ?? MORNING;
return {
identity: async () => ({ publicKey: ME, kept: true }),
@@ -25,8 +26,17 @@ function wiring(over: Partial<RoseWiring> & { log?: CareEvent[]; at?: number } =
clientVersion: '0.1.0',
deviceZone: ZONE,
now: () => at,
pastKeys: async () => [],
exportRose: async (key) => ({ format: 'rosea-rose', version: 1, keys: [key], events: [...(over.log ?? []), ...appended] }),
importRose: async () => ({ added: 0 }),
saveFile: (name, text) => {
saved.push({ name, text });
},
keeping: { persisted: async () => false, persist: async () => true },
installHint: false,
...over,
appended
appended,
saved
};
}
const water = (now: number, amount: number): CareEvent => careEvent({ now, timeZone: ZONE, from: ME, to: ME, act: 'water', amount, clientVersion: '0.1.0' });
@@ -136,3 +146,83 @@ describe('the rose', () => {
expect(error).toHaveBeenCalled();
});
});
// jsdom's File has no text(); every browser the app runs in does. Read it as a browser would.
if (typeof File.prototype.text !== 'function') {
File.prototype.text = function (this: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result));
reader.onerror = () => reject(reader.error);
reader.readAsText(this);
});
};
}
describe('keep her safe (keep-her-safe.md)', () => {
const OLD = 'O'.repeat(87);
const open = async (): Promise<void> => {
await screen.findByRole('img');
await fireEvent.click(screen.getByRole('button', { name: en.rose.safe.title }));
};
it('says the browser may clear her, asks it to keep her on request, and says when it promised', async () => {
render(Rose, { wiring: wiring(), timeZone: ZONE });
await open();
expect(await screen.findByText(en.rose.safe.mayClear)).toBeTruthy();
await fireEvent.click(screen.getByRole('button', { name: en.rose.safe.ask }));
expect(await screen.findByText(en.rose.safe.kept)).toBeTruthy();
expect(screen.queryByRole('button', { name: en.rose.safe.ask })).toBeNull();
});
it('a browser that will not promise is told calmly, and the file is offered', async () => {
render(Rose, { wiring: wiring({ keeping: { persisted: async () => false, persist: async () => false } }), timeZone: ZONE });
await open();
await fireEvent.click(await screen.findByRole('button', { name: en.rose.safe.ask }));
expect(await screen.findByText(en.rose.safe.refused)).toBeTruthy();
});
it('saves her as a dated file holding her care, and says the file never holds the town', async () => {
const log = [water(MORNING - 60_000, 0.5)];
const w = wiring({ log });
render(Rose, { wiring: w, timeZone: ZONE });
await open();
expect(screen.getByText(en.rose.safe.fileNote)).toBeTruthy();
await fireEvent.click(screen.getByRole('button', { name: en.rose.safe.save }));
await waitFor(() => expect(w.saved).toHaveLength(1));
expect(w.saved[0]?.name).toBe('rose-2026-03-01.json');
expect(JSON.parse(w.saved[0]?.text ?? '{}')).toMatchObject({ keys: [ME], events: log });
});
it('bringing her back from a file restores her days of care under her old key', async () => {
const old = [{ ...water(MORNING - 2 * DAY, 0.5), from: OLD, to: OLD }];
let restored = false;
const w = wiring({
loadCare: async () => (restored ? old : []),
pastKeys: async () => (restored ? [OLD] : []),
importRose: async (file) => {
expect(file).toMatchObject({ keys: [OLD] });
restored = true;
return { added: 1 };
}
});
render(Rose, { wiring: w, timeZone: ZONE });
await open();
const input = screen.getByLabelText(en.rose.safe.bringBack) as HTMLInputElement;
const file = new File([JSON.stringify({ format: 'rosea-rose', version: 1, keys: [OLD], events: old })], 'rose.json', { type: 'application/json' });
await fireEvent.change(input, { target: { files: [file] } });
expect(await screen.findByText(en.rose.safe.broughtBack(1))).toBeTruthy();
await fireEvent.click(screen.getByRole('button', { name: en.rose.numbers }));
await waitFor(() => expect(document.getElementById('rose-numbers')?.textContent).toContain(`${en.rose.daysOfCare}1`));
});
it('a file that is not a rose is said calmly, and nothing changes', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
render(Rose, { wiring: wiring({ importRose: () => Promise.reject(new TypeError('storage: this file does not hold a rose')) }), timeZone: ZONE });
await open();
const input = screen.getByLabelText(en.rose.safe.bringBack);
await fireEvent.change(input, { target: { files: [new File(['not json'], 'x.json')] } });
expect(await screen.findByText(en.rose.safe.notARose)).toBeTruthy();
expect(warn).toHaveBeenCalled();
});
});
+15
View File
@@ -99,6 +99,9 @@ importers:
vite-plugin-pwa:
specifier: 1.3.0
version: 1.3.0(vite@6.4.3(@types/node@22.20.1)(terser@5.51.2)(tsx@4.23.12))(workbox-build@7.4.1)(workbox-window@7.4.1)
workbox-window:
specifier: 7.4.1
version: 7.4.1
packages/content:
dependencies:
@@ -238,6 +241,18 @@ importers:
specifier: 3.2.7
version: 3.2.7(@types/node@22.20.1)(jsdom@25.0.1)(terser@5.51.2)(tsx@4.23.12)
tools/cpu-guard:
devDependencies:
'@types/node':
specifier: 22.20.1
version: 22.20.1
typescript:
specifier: 5.9.3
version: 5.9.3
vitest:
specifier: 3.2.7
version: 3.2.7(@types/node@22.20.1)(jsdom@25.0.1)(terser@5.51.2)(tsx@4.23.12)
packages:
'@apideck/better-ajv-errors@0.3.7':
+16
View File
@@ -0,0 +1,16 @@
{
"name": "@rosea/cpu-guard",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "Refuses to start a full test run while the machine is busy (CLAUDE.md §5.7). Never imported by the app.",
"scripts": {
"typecheck": "tsc -p tsconfig.json",
"test": "vitest run --reporter=verbose"
},
"devDependencies": {
"@types/node": "22.20.1",
"typescript": "5.9.3",
"vitest": "3.2.7"
}
}
+45
View File
@@ -0,0 +1,45 @@
/**
* `pnpm guard:cpu` — samples the machine for 2 s; starts if it is at or under the
* limit, waits and samples again while it is not, and exits 1 once the wait is used
* up. The full runs (`pnpm test`, `test:e2e`, `test:offline`) call it first.
*/
import { cpus } from 'node:os';
import { setTimeout as sleep } from 'node:timers/promises';
import { busyPercent, decide, limitsFrom } from './guard.js';
const SAMPLE_MS = 2_000;
const PAUSE_MS = 10_000;
async function sample(): Promise<number> {
const before = cpus();
await sleep(SAMPLE_MS);
return busyPercent(before, cpus());
}
let limits;
try {
limits = limitsFrom(process.env);
} catch (error) {
console.error(`guard:cpu: ${(error as Error).message}`);
process.exit(2);
}
const started = Date.now();
for (;;) {
const busy = await sample();
const waited = Math.round((Date.now() - started) / 1000);
const verdict = decide(busy, waited, limits);
if (verdict === 'start') {
console.log(`guard:cpu: ${busy} % busy, at or under ${limits.max} %. Starting.`);
break;
}
if (verdict === 'refuse') {
console.error(
`guard:cpu: still ${busy} % busy after ${waited} s, above ${limits.max} % (CLAUDE.md §5.7). Not starting.\n` +
' Close what is busy, or on a dedicated machine set ROSEA_CPU_MAX (100 never refuses).'
);
process.exit(1);
}
console.log(`guard:cpu: ${busy} % busy, above ${limits.max} %. Waiting (${waited} of ${limits.waitSeconds} s).`);
await sleep(PAUSE_MS);
}
+53
View File
@@ -0,0 +1,53 @@
/**
* CLAUDE.md §5.7: do not start a full run above ~80 % CPU. Read by a person, the rule
* was broken three times in one day (lessons/process.md), so a full run now asks
* this guard first. The logic is pure; `cli.ts` does the sampling and the waiting.
*/
import type { CpuInfo } from 'node:os';
/** The default limit, CLAUDE.md §5.7. */
export const DEFAULT_MAX = 80;
/** How long a busy machine is waited for before the run is refused. */
export const DEFAULT_WAIT_SECONDS = 180;
/** Whole-machine busy share between two `os.cpus()` readings, 0–100. */
export function busyPercent(before: readonly CpuInfo[], after: readonly CpuInfo[]): number {
let busy = 0;
let total = 0;
for (let i = 0; i < Math.min(before.length, after.length); i++) {
const a = before[i]!.times;
const b = after[i]!.times;
const idle = b.idle - a.idle;
const all = b.user - a.user + (b.nice - a.nice) + (b.sys - a.sys) + (b.irq - a.irq) + idle;
busy += all - idle;
total += all;
}
return total <= 0 ? 0 : Math.round((busy / total) * 100);
}
export interface Limits {
readonly max: number;
readonly waitSeconds: number;
}
/**
* The limits, from the environment. `ROSEA_CPU_MAX` is for a dedicated machine such as
* CI (100 never refuses); `ROSEA_CPU_WAIT_SECONDS` for how long to wait. A value that
* is not a whole number in range is an error, never quietly the default.
*/
export function limitsFrom(env: Readonly<Record<string, string | undefined>>): Limits {
const read = (name: string, fallback: number, min: number, max: number): number => {
const raw = env[name];
if (raw === undefined || raw.trim() === '') return fallback;
const n = Number(raw);
if (!Number.isInteger(n) || n < min || n > max) throw new RangeError(`${name} must be a whole number from ${min} to ${max}, got '${raw}'`);
return n;
};
return { max: read('ROSEA_CPU_MAX', DEFAULT_MAX, 1, 100), waitSeconds: read('ROSEA_CPU_WAIT_SECONDS', DEFAULT_WAIT_SECONDS, 0, 3600) };
}
/** Start once a sample is at or under the limit; refuse once the wait is used up. */
export function decide(busy: number, waitedSeconds: number, limits: Limits): 'start' | 'wait' | 'refuse' {
if (busy <= limits.max) return 'start';
return waitedSeconds >= limits.waitSeconds ? 'refuse' : 'wait';
}
+57
View File
@@ -0,0 +1,57 @@
import type { CpuInfo } from 'node:os';
import { describe, expect, it } from 'vitest';
import { busyPercent, decide, DEFAULT_MAX, DEFAULT_WAIT_SECONDS, limitsFrom } from '../src/guard.js';
const core = (user: number, idle: number, sys = 0): CpuInfo => ({ model: 'test', speed: 1, times: { user, nice: 0, sys, idle, irq: 0 } });
describe('busyPercent', () => {
it('measures the whole machine between two readings, not since boot', () => {
// Since boot both cores look idle; between the readings one is full and one is idle.
const before = [core(1_000, 99_000), core(1_000, 99_000)];
const after = [core(2_000, 99_000), core(1_000, 100_000)];
expect(busyPercent(before, after)).toBe(50);
});
it('counts system time as busy, and an idle machine as 0', () => {
expect(busyPercent([core(0, 0)], [core(300, 100, 600)])).toBe(90);
expect(busyPercent([core(5, 5)], [core(5, 1005)])).toBe(0);
});
it('two readings with no time between them are 0, never NaN', () => {
expect(busyPercent([core(1, 1)], [core(1, 1)])).toBe(0);
});
});
describe('limitsFrom', () => {
it('defaults to CLAUDE.md §5.7: 80 %, waiting three minutes', () => {
expect(limitsFrom({})).toEqual({ max: DEFAULT_MAX, waitSeconds: DEFAULT_WAIT_SECONDS });
expect(DEFAULT_MAX).toBe(80);
});
it('reads a dedicated machine\'s limit and wait', () => {
expect(limitsFrom({ ROSEA_CPU_MAX: '100', ROSEA_CPU_WAIT_SECONDS: '0' })).toEqual({ max: 100, waitSeconds: 0 });
});
it.each(['abc', '0', '101', '80.5', '-5'])('refuses ROSEA_CPU_MAX=%s rather than quietly using the default', (raw) => {
expect(() => limitsFrom({ ROSEA_CPU_MAX: raw })).toThrow(/ROSEA_CPU_MAX must be a whole number from 1 to 100/);
});
});
describe('decide', () => {
const limits = { max: 80, waitSeconds: 180 };
it('starts at or under the limit', () => {
expect(decide(80, 0, limits)).toBe('start');
expect(decide(12, 500, limits)).toBe('start');
});
it('waits while busy, then refuses once the wait is used up', () => {
expect(decide(81, 0, limits)).toBe('wait');
expect(decide(100, 179, limits)).toBe('wait');
expect(decide(100, 180, limits)).toBe('refuse');
});
it('with no wait, refuses at once', () => {
expect(decide(95, 0, { max: 80, waitSeconds: 0 })).toBe('refuse');
});
});
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node"]
},
"include": ["src/**/*.ts", "test/**/*.ts"]
}