Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 12fc4bd249 | |||
| 8e286b2bf6 | |||
| 7a6cf4c6d1 | |||
| a99dfe535d | |||
| ff3a996482 | |||
| a5480d2877 | |||
| beea8eaa10 | |||
| 8c84cbbb52 | |||
| 8ee3e1ce28 | |||
| f9883e22ba | |||
| 8b1c2eaee2 |
@@ -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) |
|
||||
| The in-game sunset: move the chair, half a minute of silence, then the real sunset's time | 1 | Merged to `main`; built, not deployed | [chair-sunset.md](features/chair-sunset.md) | [feature-chair-sunset.md](reviews/feature-chair-sunset.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) |
|
||||
|
||||
@@ -26,7 +26,7 @@ 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.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. |
|
||||
@@ -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. |
|
||||
|
||||
@@ -55,7 +56,8 @@ sentences). Nothing in Phase 1 is visible to the player yet.
|
||||
| ~~G1.1~~ | ~~No module computes the sun (CLAUDE.md §7); polar and DST traps only predicted~~ | Closed 2026-11-01 on `feature/sun`. `engine/src/sun/sun.ts`: 26 published days in 6 cities within 2 min, polar day and night at Tromsø, 50 tests, 5 of 5 put-back bugs caught. Both traps measured (CLAUDE.md §8). |
|
||||
| ~~G1.2~~ | ~~The player cannot choose a city; no time-zone guess; no sunset time on screen~~ | Closed 2026-11-02 on `feature/sunset-place`. 7,342 public-domain towns searched on the device, a guess for every zone a browser reports, the town kept in IndexedDB, tonight's sunset in the garden. 299 unit, 10 e2e, offline choosing and changing a town; 6 of 6 put-back bugs caught. |
|
||||
| ~~G1.4~~ | ~~No rose~~ | Closed 2026-11-02 on `feature/rose-care`: care with a touch of skill (water by holding, shade, weeds, petals), growth from days of care, drift, moods, her numbers; the care log in IndexedDB, replayed by the engine. Tuning R2/R4/R5/R6 is the author's. 7 of 7 put-back bugs caught after two test holes were closed. |
|
||||
| G1.5 | The day's sentence and the folded petal; the in-game sunset with the chair | Open. The sentence needs the library (G0.18). |
|
||||
| G1.5 | The day's sentence and the folded petal | Open. Needs the library (G0.18). |
|
||||
| ~~G1.6~~ | ~~The in-game sunset: move the chair, watch it again~~ | Closed 2026-11-02 on `feature/chair-sunset`: half a minute with nothing to press, then the real sunset's time; Escape and a tap leave; the offline suite watches one with the server gone. 4 of 4 put-back bugs caught. |
|
||||
| G1.3 | Towns have no Czech names (*Vídeň*) | Open. Natural Earth has none; arrives with Czech copy. |
|
||||
|
||||
## Design questions — answered
|
||||
|
||||
@@ -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` |
|
||||
@@ -0,0 +1,53 @@
|
||||
# The in-game sunset — move the chair, watch it again
|
||||
|
||||
Status: built on `feature/chair-sunset`. ROADMAP Phase 1: *the in-game sunset — move the chair, watch
|
||||
it again — as comfort and rehearsal; it tells the player when the real one is tonight.* CLAUDE.md §1,
|
||||
§7 (*silence is a feature: sunset … has moments with no buttons at all*). Review:
|
||||
[`feature-chair-sunset.md`](../reviews/feature-chair-sunset.md).
|
||||
|
||||
## 1. Why and what, in the player's terms
|
||||
|
||||
Under tonight's sunset line there is **Move the chair**. The garden turns into a quiet scene: the chair
|
||||
on the hillside, the sky going from day to amber to coral to dusk, the sun sinking behind the western
|
||||
horizon. **Half a minute, and nothing to press.** Then one line says when the real one is tonight, and
|
||||
two quiet choices: *Watch it again*, *Back to the rose*.
|
||||
|
||||
It is a rehearsal, never a replacement: it counts for nothing, logs nothing, and its last words point
|
||||
at the real sky.
|
||||
|
||||
## 2. Technical architecture
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
shell["Shell.svelte<br/>Move the chair"] --> scene["ChairSunset.svelte<br/>dialog: sky + sun in CSS,<br/>garden-sunset and chair stand-ins"]
|
||||
scene -->|"after 30 s"| line["SunsetLine<br/>tonight's real sunset"]
|
||||
line --> engine["engine nextInvitation"]
|
||||
```
|
||||
|
||||
| # | Decision | Why |
|
||||
|:--|:--|:--|
|
||||
| C1 | The sky and the sun are **drawn in code** (CSS gradients and one disc) behind the garden layer, which is transparent above its horizon. | STYLE.md S5: the sky is never painted, so the same layer serves the real-time sky later. |
|
||||
| C2 | **No visible button for 30 s.** Escape, or a tap anywhere, comes back early; a screen-reader-only line says so. | Silence (CLAUDE.md §7) without a trap: a keyboard or screen-reader user is never stuck. |
|
||||
| C3 | It is a modal dialog; focus goes into it and returns to *Move the chair*. | Accessibility is not a phase. |
|
||||
| C4 | **Nothing is logged.** No event kind, no count. | Rehearsal, not achievement; the real sunset's event (`sunset`, CLAUDE.md §6.2) belongs to the real one. |
|
||||
| C5 | With reduced motion, the scene shows dusk at once, still, for the same half minute. | Global `prefers-reduced-motion` rule in `tokens.css`. |
|
||||
|
||||
## 3. Risk analysis
|
||||
|
||||
| Risk | Answer |
|
||||
|:--|:--|
|
||||
| **Dependence**: the screen sunset replaces the real one. | Its last line is the real sunset's time; nothing rewards watching it. |
|
||||
| **A trap**: a full-screen scene with no buttons. | C2, C3; tested by keyboard. |
|
||||
| **Motion** for people sensitive to it. | C5. |
|
||||
| Privacy, reachability | None: nothing is stored or sent. |
|
||||
|
||||
## 4. Verification matrix
|
||||
|
||||
| Case | Kind | Where |
|
||||
|:--|:--|:--|
|
||||
| Move the chair opens a labelled dialog with no button in it; after 30 s, the real sunset's line, *Watch it again*, *Back to the rose* | unit | `ui/test/chair-sunset.test.ts` |
|
||||
| Escape and a tap come back early; focus returns to *Move the chair* | unit | same |
|
||||
| Watch it again starts it over | unit | same |
|
||||
| With no town and no guess, the line asks for a town | unit | same |
|
||||
| Built app: watch it with the clock driven; axe during and after | e2e | `e2e/shell.spec.ts` |
|
||||
| Offline: watch an in-game sunset with the server gone (CLAUDE.md §3) | offline | `e2e/offline.spec.ts` |
|
||||
@@ -42,6 +42,6 @@ because the check and the run were chained in one command that did not depend on
|
||||
**Why it bit.** A rule that relies on a person reading a number before acting holds only
|
||||
while nothing else is competing for attention.
|
||||
|
||||
**How to apply it.** Make the run refuse to start: a gate script that samples the load
|
||||
and exits above 80 %, waiting or saying so. Until it exists, read the number in its own
|
||||
step and decide before starting the run.
|
||||
**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.
|
||||
|
||||
@@ -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.
|
||||
@@ -0,0 +1,40 @@
|
||||
# Review — `feature/chair-sunset`
|
||||
|
||||
Adversarial self-review (CLAUDE.md §5.3). Analysis: [`features/chair-sunset.md`](../features/chair-sunset.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 +7, e2e +1 (watch, again, Escape, focus,
|
||||
axe during and after), and the offline suite now watches an in-game sunset with the server gone,
|
||||
which CLAUDE.md §3 has always promised.
|
||||
|
||||
**The app changed** (CLAUDE.md §5.4): *Move the chair* under tonight's sunset line. Rebuilt by the
|
||||
e2e and offline runs; **not deployed** (G0.13). Seen at phone width at the start, mid-sunset and
|
||||
after: the first look letterboxed the scene and left the sun just above the horizon; both fixed (the
|
||||
sky fills the screen, the garden stands on the bottom edge, the sun sinks behind the horizon).
|
||||
|
||||
## Bug drills
|
||||
|
||||
| Put back | Result |
|
||||
|:--|:--|
|
||||
| Buttons shown during the sunset | CAUGHT: 3 |
|
||||
| Escape does nothing | CAUGHT |
|
||||
| The half minute never ends | CAUGHT: 4 |
|
||||
| Focus not given back to *Move the chair* | CAUGHT |
|
||||
|
||||
## Findings
|
||||
|
||||
| # | Area | Finding | Resolution |
|
||||
|:--|:--|:--|:--|
|
||||
| 1 | Accessibility | A full-screen scene with no buttons can trap a keyboard or screen-reader user. | Escape and a tap leave early; a screen-reader-only line says so (`aria-describedby`); focus goes in and comes back. Tested; axe passes during and after. Not tried with a real screen reader. |
|
||||
| 2 | Soul | A screen sunset could stand in for the real one. | Its last words are the real sunset's time; it logs and counts nothing. |
|
||||
| 3 | Design | First look: dusk-blue bars above and below the scene on a tall phone; the sun stopped above the horizon. | Fixed after the screenshots. |
|
||||
| 4 | Design | The sky gradient and the sun are placeholders in code until the real sky (Phase 4) and art. | Accepted: the layer split (STYLE.md S5) is what the real sky needs. |
|
||||
| 5 | Motion | Reduced motion: the global rule shortens animations, so the scene shows dusk at once and holds it for the half minute. | Accepted (C5); not seen with the setting on. |
|
||||
| 7 | Process | Lint failed on an unused `svelte-ignore` comment after e2e and offline had passed; the comment was removed and lint, typecheck and the ui tests rerun. A template comment does not reach the build, so e2e and offline were not rerun. | Fixed. |
|
||||
| 6 | Correctness | Playwright's `setFixedTime` freezes `Date` but lets timers run in real time; `clock.install` drives them. | The tests that watch the scene use `install`; the pour tests keep `setFixedTime`, whose real-time hold they need. |
|
||||
|
||||
## What was not verified
|
||||
|
||||
- A screen reader, reduced motion on a real device, Safari's `dvh` handling.
|
||||
@@ -32,7 +32,7 @@ Counts are on the merge; HANDOVER repeats them. New here: engine +4, storage +6,
|
||||
| 5 | Privacy | The file is a diary of when someone was in the app. | Made only on request; the screen says what it holds; no town and no private key (tested in unit and e2e). It goes wherever the player puts it, which Rosea cannot see. |
|
||||
| 6 | Privacy | A file brought back could have been edited by hand to give her days she was never given. | It only changes the player's own garden; nothing is counted against anyone (CLAUDE.md §1). Phase 3 must not treat imported care as proof towards friends: noted in the analysis. |
|
||||
| 7 | Soul | "This browser may clear her" can frighten. | Shown only behind *Keep her safe*, with the remedy in the same sentence; a refusal is said calmly. Nothing reminds or nags. |
|
||||
| 8 | Process | The first e2e run **and the full gate run** both started with the CPU at 100 %, above the 80 % rule (CLAUDE.md §5.7). The load was another project's test run on this machine. The second time the reading was taken, but the run was chained after it without depending on it. Both passed. | **Not fixed by intention alone**: a gate script that refuses to start above 80 % would make the rule real. Lesson: `process.md`. |
|
||||
| 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
|
||||
|
||||
@@ -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. Later, on a quiet machine, it read 2.4–4.1 % beside Windows' 1.5–3.3 %; busy, 2–11 points lower. Close enough for an 80 % line. |
|
||||
|
||||
## Not verified
|
||||
|
||||
- macOS and Linux (only Windows 10 here).
|
||||
- A CI runner: there is none yet (G0.22).
|
||||
@@ -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.
|
||||
|
||||
---
|
||||
|
||||
@@ -503,7 +507,7 @@ No timestamp finer than a day, no precise location, no free text, no link to the
|
||||
| **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; answered by `keep-her-safe.md`)* | WebKit can discard origin storage after seven days without interaction — exactly the shape of a player who drifted away and comes back. Call `navigator.storage.persist()` where it exists, prompt iOS players to install, and make export-my-rose a first-class feature. A player returning to find their rose gone is the cruellest bug this product could have. |
|
||||
| **The stale service worker** | A precached shell keeps serving old JS to a player who has "updated". Detect a waiting worker and offer an explicit, calm *refresh* control. |
|
||||
| **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
-2
@@ -12,8 +12,8 @@ Rewritten at the end of each session (CLAUDE.md §5.1).
|
||||
Gitea hashes match. Analysis: [`.agents/features/phase0-workspace.md`](.agents/features/phase0-workspace.md).
|
||||
Review, with counts and the mutation results:
|
||||
[`.agents/reviews/feature-phase0-workspace.md`](.agents/reviews/feature-phase0-workspace.md).
|
||||
- **Gates:** all pass on this machine. Unit tests: 373 (identity 5, schema 16, content 71,
|
||||
storage 51, art-prep 56, engine 136, ui 38). E2E: 13. Offline: 1. `lint:copy`: 19 files, 0 problems.
|
||||
- **Gates:** all pass on this machine. Unit tests: 396 (cpu-guard 13, identity 5, schema 16,
|
||||
content 71, storage 51, art-prep 56, engine 136, ui 48). E2E: 15. Offline: 1. `lint:copy`: 20 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
|
||||
@@ -66,6 +66,17 @@ Rewritten at the end of each session (CLAUDE.md §5.1).
|
||||
[`.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).
|
||||
|
||||
- **The in-game sunset (Phase 1):** merged to `main`. *Move the chair* under tonight's sunset line
|
||||
opens a quiet scene: the sky drawn in code from day to dusk, the sun setting behind the garden,
|
||||
half a minute with nothing to press; then the real sunset's time, *Watch it again*, *Back to the
|
||||
rose*. Escape or a tap leaves early. Review:
|
||||
[`.agents/reviews/feature-chair-sunset.md`](.agents/reviews/feature-chair-sunset.md).
|
||||
|
||||
**Phase 0 is not finished.** The roadmap's Phase 0 is more than the workspace. Its
|
||||
gate needs 60 verified sentences (G0.18) and one illustration through the art
|
||||
pipeline (G0.24). The pipeline and the board are built; the first real picture is not made yet. Also open: a GitHub remote (G0.13). The Letter slot is built (G0.25).
|
||||
@@ -91,6 +102,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
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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';
|
||||
@@ -75,6 +76,15 @@
|
||||
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(),
|
||||
@@ -94,4 +104,4 @@
|
||||
};
|
||||
</script>
|
||||
|
||||
<Shell {letter} {sunset} {rose} />
|
||||
<Shell {letter} {sunset} {rose} {updateReady} onrefresh={() => void updateSW(true)} />
|
||||
|
||||
Vendored
+1
@@ -1,2 +1,3 @@
|
||||
/// <reference types="svelte" />
|
||||
/// <reference types="vite/client" />
|
||||
/// <reference types="vite-plugin-pwa/client" />
|
||||
|
||||
@@ -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.
|
||||
|
||||
+8
-1
@@ -78,7 +78,8 @@ test('the shell opens from the service worker with the server gone', async ({ br
|
||||
// coming back days later with no signal.
|
||||
await page.close();
|
||||
const again = await context.newPage();
|
||||
await again.clock.setFixedTime(Date.parse('2026-03-29T12:00:00+02:00'));
|
||||
// An installed clock, so the in-game sunset's half minute can be run below.
|
||||
await again.clock.install({ time: Date.parse('2026-03-29T12:00:00+02:00') });
|
||||
await again.goto(server.url);
|
||||
await expect(again.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
|
||||
await expect(again.locator('.sun p').first()).toHaveText(/in Plzeň\.$/);
|
||||
@@ -86,6 +87,12 @@ test('the shell opens from the service worker with the server gone', async ({ br
|
||||
await again.getByRole('button', { name: en.rose.numbers }).click();
|
||||
await expect(again.locator('#rose-numbers')).toContainText(`${en.rose.daysOfCare}1`);
|
||||
|
||||
// Watching an in-game sunset with no network (CLAUDE.md §3, the offline suite).
|
||||
await again.getByRole('button', { name: en.chair.move }).click();
|
||||
await again.clock.runFor(30_000);
|
||||
await expect(again.getByRole('dialog').getByText(/in Plzeň\.$/)).toBeVisible();
|
||||
await again.keyboard.press('Escape');
|
||||
|
||||
// 3. A deep link inside the scope falls back to the shell, not an error page.
|
||||
await again.goto(`${server.url}somewhere/deeper`);
|
||||
await expect(again.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -279,3 +279,31 @@ test.describe('keep her safe, in Prague at 08:00 on 1 March 2026', () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// --- The in-game sunset (.agents/features/chair-sunset.md) ---------------------
|
||||
test.describe('the in-game sunset, in Prague at noon on 29 March 2026', () => {
|
||||
test.use({ timezoneId: 'Europe/Prague', locale: 'en-US' });
|
||||
|
||||
test('move the chair: half a minute with nothing to press, then the real sunset\'s time; again; back', async ({ page }) => {
|
||||
// An installed clock, so the scene's half minute can be run in a moment.
|
||||
await page.clock.install({ time: Date.parse('2026-03-29T12:00:00+02:00') });
|
||||
await open(page);
|
||||
await page.getByRole('button', { name: /^Not now/ }).click();
|
||||
await page.getByRole('button', { name: en.chair.move }).click();
|
||||
|
||||
const scene = page.getByRole('dialog', { name: en.chair.scene });
|
||||
await expect(scene).toBeVisible();
|
||||
await expect(scene.getByRole('button')).toHaveCount(0);
|
||||
expect((await new AxeBuilder({ page }).analyze()).violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
|
||||
|
||||
await page.clock.runFor(30_000);
|
||||
await expect(scene.getByText(/^Tonight the sun sets at .* in Prague\.$/)).toBeVisible();
|
||||
expect((await new AxeBuilder({ page }).analyze()).violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
|
||||
|
||||
await scene.getByRole('button', { name: en.chair.again }).click();
|
||||
await expect(scene.getByRole('button')).toHaveCount(0);
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(scene).toHaveCount(0);
|
||||
await expect(page.getByRole('button', { name: en.chair.move })).toBeFocused();
|
||||
});
|
||||
});
|
||||
|
||||
+10
-4
@@ -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();
|
||||
|
||||
@@ -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
@@ -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",
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import { parseLetter } from './letter/parse.js';
|
||||
import Rose from './rose/Rose.svelte';
|
||||
import type { RoseWiring } from './rose/types.js';
|
||||
import ChairSunset from './sunset/ChairSunset.svelte';
|
||||
import SunsetLine from './sunset/SunsetLine.svelte';
|
||||
import SunsetPlace from './sunset/SunsetPlace.svelte';
|
||||
import type { SunsetChoice, SunsetWiring } from './sunset/types.js';
|
||||
@@ -13,7 +14,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 +24,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) ---------------------------------------
|
||||
@@ -31,6 +38,15 @@
|
||||
let kept = $state(true);
|
||||
let now = $state(0);
|
||||
let sunLine = $state<HTMLElement>();
|
||||
/** The in-game sunset is showing (chair-sunset.md). */
|
||||
let watching = $state(false);
|
||||
let chairButton = $state<HTMLButtonElement>();
|
||||
|
||||
async function stopWatching(): Promise<void> {
|
||||
watching = false;
|
||||
await tick();
|
||||
chairButton?.focus();
|
||||
}
|
||||
|
||||
const place = $derived(choice?.kind === 'town' ? choice.town : (sunset?.guess ?? null));
|
||||
// One zone for the sunset and the rose's days: the chosen town's, else the device's (rose.md R8).
|
||||
@@ -135,7 +151,11 @@
|
||||
<p class="hint">{en.sunset.notKept}</p>
|
||||
{/if}
|
||||
<button type="button" class="quiet" onclick={() => (changing = true)}>{place ? en.sunset.change : en.sunset.choose}</button>
|
||||
<button type="button" class="quiet" bind:this={chairButton} onclick={() => (watching = true)}>{en.chair.move}</button>
|
||||
</div>
|
||||
{#if watching}
|
||||
<ChairSunset {place} guessed={choice?.kind === 'device-zone'} now={sunset.now} onclose={stopWatching} />
|
||||
{/if}
|
||||
{/if}
|
||||
{#if blocks.length > 0}
|
||||
<a href={LETTER_HASH}>{en.letter.title}</a>
|
||||
@@ -143,6 +163,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 +233,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;
|
||||
|
||||
@@ -88,6 +88,20 @@ 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.'
|
||||
},
|
||||
chair: {
|
||||
/** ROADMAP Phase 1: "move the chair, watch it again". */
|
||||
move: 'Move the chair',
|
||||
scene: 'A sunset in the garden',
|
||||
/** Read by screen readers only: the scene has no buttons on purpose (chair-sunset.md C2). */
|
||||
leave: 'Press Escape or tap to come back.',
|
||||
again: 'Watch it again',
|
||||
back: 'Back to the rose'
|
||||
},
|
||||
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',
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
<script lang="ts">
|
||||
import type { NamedPlace } from '@rosea/engine';
|
||||
import { en } from '../copy/en.js';
|
||||
import SunsetLine from './SunsetLine.svelte';
|
||||
// The art board's stand-ins until real art is accepted. The garden layer is
|
||||
// transparent above its horizon (40 %): the sky is drawn here, in code (STYLE.md S5).
|
||||
import garden from '../../../../art/placeholders/garden-sunset.svg?url';
|
||||
import chair from '../../../../art/placeholders/garden-chair.svg?url';
|
||||
|
||||
/**
|
||||
* The in-game sunset (chair-sunset.md): half a minute with nothing to press, then
|
||||
* the real sunset's time. A rehearsal: it decides nothing and logs nothing.
|
||||
*/
|
||||
let {
|
||||
place,
|
||||
guessed = false,
|
||||
now,
|
||||
durationMs = SUNSET_MS,
|
||||
onclose
|
||||
}: { place: NamedPlace | null; guessed?: boolean; now: () => number; durationMs?: number; onclose: () => void } = $props();
|
||||
|
||||
const uid = $props.id();
|
||||
let phase = $state<'watching' | 'after'>('watching');
|
||||
/** Bumped by Watch it again, so the animation starts over. */
|
||||
let showing = $state(0);
|
||||
let dialog = $state<HTMLElement>();
|
||||
let afterAt = $state(0);
|
||||
|
||||
$effect(() => {
|
||||
// Read what the effect depends on first: it reruns on Watch it again.
|
||||
const run = showing;
|
||||
void run;
|
||||
phase = 'watching';
|
||||
dialog?.focus();
|
||||
const timer = setTimeout(() => {
|
||||
afterAt = now();
|
||||
phase = 'after';
|
||||
}, durationMs);
|
||||
return () => clearTimeout(timer);
|
||||
});
|
||||
|
||||
function leave(): void {
|
||||
onclose();
|
||||
}
|
||||
</script>
|
||||
|
||||
<script lang="ts" module>
|
||||
/** Half a minute: long enough to breathe, short enough to come back to the rose. */
|
||||
export const SUNSET_MS = 30_000;
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="scene"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="{uid}-title"
|
||||
aria-describedby="{uid}-leave"
|
||||
tabindex="-1"
|
||||
bind:this={dialog}
|
||||
style="--duration: {durationMs}ms"
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Escape') leave();
|
||||
}}
|
||||
onclick={() => {
|
||||
if (phase === 'watching') leave();
|
||||
}}
|
||||
>
|
||||
<h2 id="{uid}-title" class="sr-only">{en.chair.scene}</h2>
|
||||
<p id="{uid}-leave" class="sr-only">{en.chair.leave}</p>
|
||||
|
||||
{#key showing}
|
||||
<!-- The sky fills the whole screen; the garden stands on the bottom edge. -->
|
||||
<div class="sky" class:after={phase === 'after'}></div>
|
||||
<div class="frame" class:after={phase === 'after'}>
|
||||
<div class="sun"></div>
|
||||
<img class="garden" src={garden} alt="" />
|
||||
<img class="chair" src={chair} alt="" />
|
||||
</div>
|
||||
{/key}
|
||||
|
||||
{#if phase === 'after'}
|
||||
<div class="after-words">
|
||||
{#if place}
|
||||
<SunsetLine {place} {guessed} now={afterAt} />
|
||||
{:else}
|
||||
<p>{en.sunset.noTown}</p>
|
||||
{/if}
|
||||
<div class="choices">
|
||||
<button type="button" onclick={(e) => { e.stopPropagation(); showing += 1; }}>{en.chair.again}</button>
|
||||
<button type="button" class="quiet" onclick={(e) => { e.stopPropagation(); leave(); }}>{en.chair.back}</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.scene {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 10;
|
||||
display: grid;
|
||||
place-items: end center;
|
||||
overflow: hidden;
|
||||
background: #2e3561;
|
||||
color: #fbf6f1;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.frame {
|
||||
position: relative;
|
||||
height: min(100dvh, 150vw);
|
||||
aspect-ratio: 2 / 3;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Day to amber to coral to dusk, drawn in code (STYLE.md §2 palette). */
|
||||
.sky {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: linear-gradient(to bottom, #a9cbe0 0%, #f4d58d 30%, #f2b860 45%, #e9846a 62%, #7a4f6e 80%, #2e3561 100%);
|
||||
background-size: 100% 300%;
|
||||
background-position: 0 0;
|
||||
animation: dusk var(--duration) linear forwards;
|
||||
}
|
||||
|
||||
.sun {
|
||||
position: absolute;
|
||||
left: 22%;
|
||||
top: 12%;
|
||||
width: 13%;
|
||||
aspect-ratio: 1;
|
||||
border-radius: 50%;
|
||||
background: radial-gradient(circle, #fff4cf 0%, #f4d58d 55%, #f2b860 100%);
|
||||
box-shadow: 0 0 2.5rem #f2b86099;
|
||||
animation: set var(--duration) ease-in forwards;
|
||||
}
|
||||
|
||||
/* The garden layer: its sky is transparent, so the sun sets behind its horizon. */
|
||||
.garden {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.chair {
|
||||
position: absolute;
|
||||
left: 10%;
|
||||
top: 58%;
|
||||
width: 24%;
|
||||
}
|
||||
|
||||
.sky.after,
|
||||
.after .sun {
|
||||
animation-play-state: paused;
|
||||
}
|
||||
|
||||
@keyframes dusk {
|
||||
to {
|
||||
background-position: 0 100%;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes set {
|
||||
to {
|
||||
/* From 12 % down past the horizon at 40 %, where the garden hides it. */
|
||||
transform: translateY(380%);
|
||||
opacity: 0.85;
|
||||
}
|
||||
}
|
||||
|
||||
.after-words {
|
||||
position: absolute;
|
||||
inset: auto 0 0 0;
|
||||
display: grid;
|
||||
justify-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-4) var(--space-3) calc(var(--space-4) + env(safe-area-inset-bottom));
|
||||
background: linear-gradient(to top, #2e3561ee 60%, transparent);
|
||||
text-align: center;
|
||||
/* The words below read on dusk, whatever the page's own theme. */
|
||||
--ink: #fbf6f1;
|
||||
--ink-soft: #e8dccf;
|
||||
}
|
||||
|
||||
.choices {
|
||||
display: flex;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
button {
|
||||
font: inherit;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border-radius: 999px;
|
||||
border: 1px solid #f4d58d;
|
||||
background: transparent;
|
||||
color: #fbf6f1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.quiet {
|
||||
border: none;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
button:focus-visible {
|
||||
outline: 2px solid #f4d58d;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import type { NamedPlace } from '@rosea/engine';
|
||||
import { cleanup, fireEvent, render, screen, within } from '@testing-library/svelte';
|
||||
import { tick } from 'svelte';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import Shell from '../src/Shell.svelte';
|
||||
import { en } from '../src/copy/en.js';
|
||||
import { SUNSET_MS } from '../src/sunset/ChairSunset.svelte';
|
||||
import type { SunsetWiring } from '../src/sunset/types.js';
|
||||
|
||||
const brno: NamedPlace = { name: 'Brno', region: '', country: 'Czechia', lat: 49.2, lon: 16.61, timeZone: 'Europe/Prague' };
|
||||
const NOON = Date.parse('2026-03-29T12:00:00+02:00');
|
||||
|
||||
const wiring = (over: Partial<SunsetWiring> = {}): SunsetWiring => ({
|
||||
guess: brno,
|
||||
search: async () => [],
|
||||
load: async () => ({ kind: 'town', town: brno }),
|
||||
save: async () => undefined,
|
||||
now: () => NOON,
|
||||
...over
|
||||
});
|
||||
|
||||
/** Renders the garden with a town set and opens the in-game sunset; the scene's own timer is faked. */
|
||||
async function openScene(over: Partial<SunsetWiring> = {}): Promise<HTMLElement> {
|
||||
render(Shell, { sunset: wiring(over) });
|
||||
const move = await screen.findByRole('button', { name: en.chair.move });
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
|
||||
await fireEvent.click(move);
|
||||
await tick();
|
||||
return screen.getByRole('dialog', { name: en.chair.scene });
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
cleanup();
|
||||
});
|
||||
|
||||
describe('the in-game sunset (chair-sunset.md)', () => {
|
||||
it('Move the chair opens a quiet scene: labelled, focused, and with nothing to press', async () => {
|
||||
const scene = await openScene();
|
||||
expect(document.activeElement).toBe(scene);
|
||||
expect(within(scene).queryAllByRole('button')).toEqual([]);
|
||||
expect(scene.getAttribute('aria-describedby')).toBeTruthy();
|
||||
expect(document.getElementById(scene.getAttribute('aria-describedby')!)?.textContent).toBe(en.chair.leave);
|
||||
});
|
||||
|
||||
it('after half a minute, it says when the real one is, and offers to watch again or go back', async () => {
|
||||
const scene = await openScene();
|
||||
vi.advanceTimersByTime(SUNSET_MS - 1);
|
||||
await tick();
|
||||
expect(within(scene).queryAllByRole('button')).toEqual([]);
|
||||
vi.advanceTimersByTime(1);
|
||||
await tick();
|
||||
expect(within(scene).getByText(/^Tonight the sun sets at .* in Brno\.$/)).toBeTruthy();
|
||||
expect(within(scene).getByRole('button', { name: en.chair.again })).toBeTruthy();
|
||||
expect(within(scene).getByRole('button', { name: en.chair.back })).toBeTruthy();
|
||||
});
|
||||
|
||||
it('Watch it again starts it over, with nothing to press again', async () => {
|
||||
const scene = await openScene();
|
||||
vi.advanceTimersByTime(SUNSET_MS);
|
||||
await tick();
|
||||
await fireEvent.click(within(scene).getByRole('button', { name: en.chair.again }));
|
||||
await tick();
|
||||
expect(within(scene).queryAllByRole('button')).toEqual([]);
|
||||
vi.advanceTimersByTime(SUNSET_MS);
|
||||
await tick();
|
||||
expect(within(scene).getByRole('button', { name: en.chair.again })).toBeTruthy();
|
||||
});
|
||||
|
||||
it('Escape comes back early, and focus returns to Move the chair', async () => {
|
||||
const scene = await openScene();
|
||||
await fireEvent.keyDown(scene, { key: 'Escape' });
|
||||
await tick();
|
||||
expect(screen.queryByRole('dialog')).toBeNull();
|
||||
expect(document.activeElement).toBe(screen.getByRole('button', { name: en.chair.move }));
|
||||
});
|
||||
|
||||
it('a tap anywhere comes back early too', async () => {
|
||||
const scene = await openScene();
|
||||
await fireEvent.click(scene);
|
||||
await tick();
|
||||
expect(screen.queryByRole('dialog')).toBeNull();
|
||||
});
|
||||
|
||||
it('Back to the rose closes it after the sunset', async () => {
|
||||
const scene = await openScene();
|
||||
vi.advanceTimersByTime(SUNSET_MS);
|
||||
await tick();
|
||||
await fireEvent.click(within(scene).getByRole('button', { name: en.chair.back }));
|
||||
await tick();
|
||||
expect(screen.queryByRole('dialog')).toBeNull();
|
||||
});
|
||||
|
||||
it('with no town and no guess, the words after it ask for a town', async () => {
|
||||
const scene = await openScene({ guess: null, load: async () => ({ kind: 'device-zone' }) });
|
||||
vi.advanceTimersByTime(SUNSET_MS);
|
||||
await tick();
|
||||
expect(within(scene).getByText(en.sunset.noTown)).toBeTruthy();
|
||||
});
|
||||
});
|
||||
Generated
+15
@@ -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':
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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';
|
||||
}
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "test/**/*.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user