Compare commits

...

10 Commits

Author SHA1 Message Date
mnovak 9d294096d9 [docs] LetterSlot: Mark the Letter slot merged to main 2026-11-01 19:45:06 +01:00
mnovak a200832cfb [ui] LetterSlot: Add the page for A Letter from the Gardener, shown once the author writes it
docs/LETTER.md holds slots as comments only, so the player sees no change
until the author writes. The app bundles the letter at build time, a small
Markdown subset renders without {@html}, only https: and tel: become links,
and lint:copy now reads the letter. Review found turbo replaying a stale
build after the letter changed; docs/LETTER.md is now in its cache key.
2026-11-01 15:39:17 +01:00
mnovak b871ab9899 [docs] Roadmap: Merge the phase plan and gameplay loop, with the author's answers
Adds docs/ROADMAP.md and docs/GAMEPLAY.md, reads them against the code, and
records the answers to Q1-Q7. Phase 0's gate stays open: 60 sentences and
one illustration through the art pipeline.
2026-11-01 15:24:14 +01:00
mnovak 40f496d1ac [docs] Roadmap: Record the author's answers to Q1-Q7 in the docs and CLAUDE.md 2026-11-01 15:24:14 +01:00
mnovak 3829058e2e [repo] Roadmap: Read the roadmap and gameplay loop against the code
Phase 0 by the roadmap is larger than the merged workspace, so its gate is
recorded as open (G0.18, G0.24-G0.26). Eight questions for the author are
listed in the review rather than resolved by editing the author's docs.
2026-11-01 12:35:28 +01:00
mnovak 68d9c60c14 [docs] Roadmap: Add the author's phase plan and gameplay loop 2026-11-01 12:35:28 +01:00
mnovak 12f5179688 [repo] Handover: Record the Phase 0 merge and post-merge gate run
FEATURES, the analysis, the review and HANDOVER now say merged (d11d242).
The frozen-lockfile install passed on the merged tree.
2026-11-01 01:21:18 +01:00
mnovak d11d2425ee [repo] Workspace: Merge Phase 0 — workspace, contracts, gates and the PWA shell
Analysis: .agents/features/phase0-workspace.md
Review: .agents/reviews/feature-phase0-workspace.md
2026-11-01 01:19:50 +01:00
mnovak 6885a217cd [repo] Workspace: Review Phase 0 and record gaps, lessons and handover
Adversarial review with per-package counts and 13 reintroduced bugs, all
caught. Fixes from the review: the trace geocell is capped at 6 characters
(~1 km; 16 allowed centimetres), one forbidden-word hit per place, and an
e2e guard that meta charset stays within the first 1024 bytes.

CLAUDE.md §6.2 no longer contradicts itself about care acts; §2 and §3
say what Phase 0 actually built.
2026-11-01 00:36:06 +01:00
mnovak 49c8def037 [repo] Workspace: Scaffold Phase 0 with schema, engine, content, ui and the PWA shell
pnpm + turbo workspace with the commands from CLAUDE.md §3. The contracts
from §6 as JSON Schemas with generated types; localDay as the one place a
day is computed; the forbidden-word list shared by lint:copy and the
library validator, with 13 negative fixtures; a Svelte 5 PWA shell built
under /Rosea/ with a meta CSP. E2E and offline suites run against the
built bundle; the offline one closes the server rather than emulating.

Analysis: .agents/features/phase0-workspace.md
2026-11-01 00:27:33 +01:00
97 changed files with 10472 additions and 20 deletions
+10
View File
@@ -0,0 +1,10 @@
# Features
One row per feature, with its analysis document (CLAUDE.md §5.1). Gaps live in
[`GAP_ANALYSIS.md`](GAP_ANALYSIS.md).
| Feature | Phase | Status | Analysis | Review |
|:--|:--|:--|:--|:--|
| 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) |
+62
View File
@@ -0,0 +1,62 @@
# Gap analysis
What the product needs that it does not have yet, and what was closed. A closed gap
is struck through **with its evidence in the row** (CLAUDE.md §5.1).
Ids are `G<phase>.<n>`. Phases follow [`docs/ROADMAP.md`](../docs/ROADMAP.md). The
workspace part of Phase 0 is in
[`features/phase0-workspace.md`](features/phase0-workspace.md). How the roadmap and
`docs/GAMEPLAY.md` compare with the code, and the author's open questions:
[`reviews/docs-roadmap-gameplay.md`](reviews/docs-roadmap-gameplay.md).
## Phase 0 — Foundations
**Gate open.** The workspace is merged (G0.1–G0.9). Still missing for the gate: the
60 sentences (G0.18) and one illustration through the pipeline (G0.24).
| Id | Gap | Status / evidence |
|:--|:--|:--|
| ~~G0.1~~ | ~~No workspace, no commands~~ | Closed 2026-11-01 on `feature/phase0-workspace`. Every §3 command except `art:prep` and `cargo test` runs; counts in the review. |
| ~~G0.2~~ | ~~Contracts §6.1–6.3 only in prose~~ | Closed 2026-11-01. `packages/schema/schemas/*.json` with generated types; `schemas.test.ts` 15 tests. §6.2's contradictory `act` list resolved (D5). |
| ~~G0.3~~ | ~~No single place computes a day~~ | Closed 2026-11-01. `engine/src/time/localDay.ts`; 18 golden, refusal and property tests. The UTC-day trap measured: Anchorage Monday 20:00 is UTC Tuesday. |
| ~~G0.4~~ | ~~Engine purity enforced by good intentions~~ | Closed 2026-11-01. ESLint rule in `eslint.config.mjs`; `purity-lint.test.ts` proves 16 bans fire inside the engine and not outside. |
| ~~G0.5~~ | ~~No library validator~~ | Closed 2026-11-01. `content/src/validator.ts`, 13 negative fixtures, each rejected with its named rule; every rule proved by a fixture. Mutation: disabling the length cap fails `validate:library`. |
| ~~G0.6~~ | ~~No `lint:copy`~~ | Closed 2026-11-01. One forbidden list shared with the validator; 9 files checked, 0 problems. |
| ~~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. Arrives with `packages/storage`. |
| G0.12 | The app cannot validate content in the browser | Open. Ajv compiles with `new Function`, which the CSP forbids. Needs standalone pre-compiled validators before the app reads the library. |
| G0.13 | No GitHub remote, no Pages deploy workflow, no mirror check (§5.2) | Open. Only the Gitea remote exists. |
| G0.14 | Author-owned docs missing: `docs/PRINCIPLES.md`, `docs/ART.md`, `art/STYLE.md`, `docs/LETTER.md` | Open, narrowed 2026-11-01: `docs/ROADMAP.md` and `docs/GAMEPLAY.md` were added on `docs/roadmap-gameplay`, as the author gave them. Agents scaffold LETTER.md; they never write its voice. |
| G0.15 | Deferred packages: `storage`, `identity`, `sync`, `services/lucerna`, `tools/art-prep` | Open by design (D1). Each arrives with its first feature. |
| G0.16 | The outcome-phrase heuristic has no reviewed override | Open. A real sentence that trips it (a false positive) cannot enter the library. Design: a `reviewedBy` field on the entry, set only by a person. |
| G0.17 | Manual: install on a phone, open in airplane mode | Open. Needs a hosted build (G0.13). |
| G0.18 | The library is empty | Open. **Phase 0 gate**: 60 sentences, each sourced and verified public domain (ROADMAP Phase 0). Release needs ≥ 365. `verifiedBy` is a person, so an agent may propose candidates but never mark one verified (D4). |
| G0.19 | Event kinds other than `care` | Open. GAMEPLAY.md now exists; each kind arrives with the feature doc that uses it, starting in Phase 1. |
| G0.20 | Node 22.11 on the dev machine is below what some pinned dependencies declare | Open. All gates pass on 22.11 today. Upgrade to ≥ 22.13 and unpin (D11). |
| G0.21 | No PNG icons | Open (predicted trap). iOS ignores SVG for `apple-touch-icon`. Comes through the art pipeline. |
| G0.22 | No CI | Open. Every gate ran on this machine only. With G0.13. |
| G0.23 | Source maps are built and would be published | Open. `sourcemap: true`; maps are not precached. Decide with G0.13 whether the repository is public. If not, use `'hidden'`. |
| G0.24 | No art pipeline: `docs/ART.md`, `art/STYLE.md` (drafted with the author), `art/manifest.json` for Phase 1 assets, SVG placeholders, `tools/art-prep` | Open. **Phase 0 gate**: one illustration goes through prompt, paste, automatic checks, review and the author's approval into `art/final/`. |
| ~~G0.25~~ | ~~No slot for *A Letter from the Gardener*~~ | Closed 2026-11-01, merged to `main`. `docs/LETTER.md` holds slots as comments only; the page opens at `#letter` once it has words. 16 ui tests, and e2e on both the empty and a temporary written letter. Mutations caught: the link while empty, any link scheme, focus not moving, *heal* in the letter. |
| G0.27 | The quiet door to real help has no numbers (§5.6 rule 5) | Open. The slot is in `docs/LETTER.md`. Support lines are real-world facts the author must verify, per country, so the door exists only once the letter does. |
| ~~G0.26~~ | ~~Not decided: how the sunset invitation reaches the player on the web~~ | Closed 2026-11-01 by the author (Q6): in-app only on the web, no push server; local notifications through the Tauri shell in Phase 6. Recorded in ROADMAP Phase 0 and CLAUDE.md §8. |
## Design questions — answered
Raised by GAMEPLAY.md and ROADMAP.md, answered by the author 2026-11-01. Details in
[`reviews/docs-roadmap-gameplay.md`](reviews/docs-roadmap-gameplay.md) §2.
| # | Question | Answer |
|:--|:--|:--|
| ~~Q1~~ | Fox food with no friends and no Lucerna | A wild bush beside the player's own rose; other roses only add |
| ~~Q2~~ | What "real time" counts for bloom | Days on which care helped, never minutes on screen |
| ~~Q3~~ | Lucerna and the lantern share a name | Keep both; the lantern never passes through Lucerna |
| ~~Q4~~ | "Sent through Amicitia" | "A taste of Amicitia" |
| ~~Q5~~ | *No extra creatures* vs visitors | Rule removed from GAMEPLAY §3 |
| ~~Q6~~ | When the notification decision is due | Phase 0, in-app only (G0.26) |
| ~~Q7~~ | Which phase holds the Amicitia bridge | Phase 3 |
| Q8 | "Nearby days give a little more" | Open as a rule for the Phase 1 Soul review: a gap's cost is never shown |
| Q9 | May the Letter name the book and its author for the one sentence of inspiration (GAMEPLAY §7)? | Open. `lint:copy` refuses those names in the letter as everywhere in the product. A yes needs a written, letter-only exemption. |
+81
View File
@@ -0,0 +1,81 @@
# The Letter slot
Status: merged to `main`, reviewed in
[`feature-letter-slot.md`](../reviews/feature-letter-slot.md). Gap: G0.25. Roadmap: Phase 0, *a slot for A Letter
from the Gardener — the author writes it; agents only scaffold the page.*
---
## 1. Why and what, in the player's terms
*A Letter from the Gardener* is the help section. It holds the deeper why, it can be
re-read at any time, and it is never needed to play (GAMEPLAY §4). It also holds the
quiet door to real help (CLAUDE.md §5.6 rule 5).
This branch makes the place for it, not the letter itself. The author writes
`docs/LETTER.md` in plain Markdown, and the app shows it as a page. **Until the author
writes something, the player sees no change at all**: there is no link to an empty
page, no "coming soon" and no dead control.
## 2. Technical architecture
```mermaid
flowchart LR
letter[("docs/LETTER.md<br/>the author's words")]
app["apps/rosea<br/>App.svelte<br/>imports it ?raw at build time"]
ui["packages/ui<br/>letter/parse.ts → blocks<br/>Letter.svelte, Shell.svelte"]
lint["scripts/lint-copy.ts"]
letter -- "bundled, precached" --> app --> ui
lint -. scans .-> letter
```
### Decisions
| # | Decision | Why |
|:--|:--|:--|
| L1 | `docs/LETTER.md` is the only copy of the letter. The app imports it with Vite's `?raw` at build time. | No runtime fetch, so the letter is in the precached bundle and opens offline. One file means the author edits one place, in Markdown. |
| L2 | The scaffold holds only HTML comments: one slot per thing the docs say the letter carries. Comments are dropped when the page is built, so the scaffold renders as nothing. | Agents never write the letter's voice. A heading is voice too, so the slots are comments, not headings. |
| L3 | A small Markdown subset is parsed into blocks in `packages/ui/src/letter/parse.ts`: headings, paragraphs, lists, *emphasis* and links. Everything else is shown as plain text. The component renders the blocks with Svelte, **never `{@html}`**. | No HTML is ever built from text, so nothing in the file can inject markup or script, and the CSP stays `'self'`. The parser lives in `ui` because it is presentation, and `ui → content` is not an allowed dependency. |
| L4 | Only `https:` and `tel:` become links. Anything else, including `http:`, `javascript:` and `data:`, stays text. External links open in a new tab, with `rel="noopener noreferrer"`. | The support door needs web and phone links. Nothing else does. |
| L5 | The page is reached by a link on the home view, at `#letter`. The link exists **only when the letter has content**. With an empty letter, `#letter` shows the home view. | Hash routing works offline without a server rule. An entry point to an empty page is a dead control. |
| L6 | `lint:copy` scans `docs/LETTER.md` with the full list, though it lives in `docs/`. | It is player-facing. The `docs/` exemption (§5.6 rule 4) is for design documents, where the words are being discussed. |
| L7 | When the view changes, focus moves to the new view's heading. | A screen-reader user hears where they are. A hash change alone announces nothing. |
| L8 | `docs/LETTER.md` is in turbo's `globalDependencies`. | Found in review: without it, a changed letter replayed the cached build (`lessons/technical.md`). |
## 3. Risk analysis
| Risk | Where | Defence |
|:--|:--|:--|
| A forbidden or medical word reaches a player through the letter | `docs/LETTER.md` | L6, with a test that the script reads the file. |
| The letter names the book | The "one sentence of inspiration" (GAMEPLAY §7) | `lint:copy` refuses *Saint-Exupéry* and the title in the letter as everywhere else. If the author wants the letter to name its source, that is a decision to write down (Q9), not an exemption made by an agent. |
| Markup or script injected through the file | The renderer | L3 and L4, with tests for `<script>`, `javascript:` and raw HTML. |
| An empty page feels broken or turns the player away | Before the author writes | L5: there is no way to reach it. |
| A link sends the player's address somewhere | Support links | `referrer: no-referrer` is already set, and `noreferrer` is on each link. Leaving the app is the player's own choice, made with a tap. |
| Someone in crisis cannot find the door | Support lines | Not solved here: the numbers are real-world facts the author must verify. The slot exists, and G0.27 tracks the rest. |
Guilt, comparison, rejection, dependence: looked for and none found. The page asks
nothing and counts nothing.
## 4. Gap analysis and the designed solution
| Gap | Solution |
|:--|:--|
| No page for the letter | `Letter.svelte`, reached at `#letter` (L5) |
| No file for the author | `docs/LETTER.md`, slots only (L2) |
| The letter escapes `lint:copy` | L6 |
| No support lines | Slot only; verified numbers are the author's (G0.27) |
## 5. Verification matrix
| Case | Kind | Where |
|:--|:--|:--|
| The scaffold, being only comments, parses to zero blocks | unit | `packages/ui/test/letter-parse.test.ts` |
| Headings, paragraphs across lines, lists, emphasis, links parse as blocks | unit | same |
| `<script>` and raw HTML stay text; `javascript:`, `data:`, `http:` links stay text | unit | same |
| `https:` and `tel:` links render as links with `noopener noreferrer` | unit | `packages/ui/test/Shell.test.ts` |
| Empty letter: no link to it, and `#letter` shows home | unit + e2e | `Shell.test.ts`, `e2e/shell.spec.ts` |
| A letter with content: the link appears, opens the page, *Back* returns, focus moves | unit | `Shell.test.ts` |
| `lint:copy` reads `docs/LETTER.md` and fails on a forbidden word in it | script, run | the review |
| The built app still renders, offline included | e2e, offline | existing suites |
| The written-letter branch of the e2e test, with a temporary sample letter | e2e, run once | the review |
| A changed letter rebuilds the app (`cache miss`) | e2e, run | the review |
+132
View File
@@ -0,0 +1,132 @@
# Phase 0 — the workspace
Status: **merged to `main`** 2026-11-01 (`d11d242`), built, not deployed. This is the
workspace part of ROADMAP Phase 0. **The Phase 0 gate is still open** (G0.18, G0.24). Review:
[`feature-phase0-workspace.md`](../reviews/feature-phase0-workspace.md).
Gates closed and still open: [`GAP_ANALYSIS.md`](../GAP_ANALYSIS.md).
Written before `docs/ROADMAP.md` existed, so it defined its own scope. It
covers what CLAUDE.md §2 calls "confirmed when Phase 0 scaffolds it" and what §3
calls "proposed until Phase 0 scaffolds them", and nothing more. **No game code.**
`docs/GAMEPLAY.md` was added later; it must be read before any.
---
## 1. Why and what, in the player's terms
The player gets nothing they can see. This is deliberate. When they open the link,
they get a quiet page with the rose's name, and it still opens with the network off.
What Phase 0 buys is the ground everything else stands on. It proves four things
before anything exists that could hurt a person:
- **The app opens with no network at all.** It is served from a sub-path, as
GitHub Pages will serve it, and checked against the built bundle.
- **Nothing leaves the device.** No third-party request, no cookie, no
`localStorage`, enforced by a CSP in a `<meta>` tag.
- **No word can reach a player that the rules forbid.** `lint:copy` and
`validate:library` run, and they are proved to fire.
- **The engine cannot read a clock or a die.** A lint rule refuses it, and a
test proves the rule refuses it.
## 2. Technical architecture
```mermaid
flowchart LR
subgraph apps
app["apps/rosea<br/>@rosea/app<br/>Svelte 5 + Vite + PWA"]
end
subgraph packages
ui["packages/ui<br/>@rosea/ui<br/>copy/ + shell components"]
content["packages/content<br/>@rosea/content<br/>library validator, forbidden words"]
engine["packages/engine<br/>@rosea/engine<br/>time/localDay.ts"]
schema["packages/schema<br/>@rosea/schema<br/>JSON Schemas, generated types, constants"]
end
lib[("content/library/*.json<br/>content/fixtures/*.json")]
scripts["scripts/<br/>lint-copy, validate-library,<br/>git hooks"]
e2e["e2e/<br/>Playwright: built bundle,<br/>server killed for offline"]
app --> ui --> schema
engine --> schema
content --> schema
app --> schema
scripts --> content
content -. reads .-> lib
e2e -. serves .-> app
```
`ui → engine` (CLAUDE.md §2) is not drawn because nothing in `ui` calls the engine yet, and an unused
dependency is a dependency nobody tested. It arrives with the first component that renders a value
the engine computes. `app → content` likewise.
### Decisions
| # | Decision | Why |
|:--|:--|:--|
| D1 | Create `schema`, `engine`, `content`, `ui` and `apps/rosea` now. **Defer** `storage`, `identity`, `sync`, `services/lucerna` and `tools/art-prep` to their first feature. | An empty package has a test suite that runs nothing and exits 0. That is the `pnpm test` trap (§3) built into the layout on purpose. Each package arrives with the feature that gives it a test. |
| D2 | The build's base path is `/Rosea/` by default and `ROSEA_BASE` overrides it. The test server serves `dist/` **under that prefix**, never at `/`. | GitHub Pages serves a project at `/<repo>/` (§8, predicted). If Vite `base`, the manifest `scope`/`start_url` and the service-worker scope disagree, the installed app opens a 404. Testing at `/` would never see it. |
| D3 | Engine purity is an **ESLint rule** scoped to `packages/engine/src`, plus a test that lints a deliberately impure snippet and asserts each ban fires. | CLAUDE.md §7 says "lint rule". Ludus said the same and shipped a source-scanning test instead. Here it really is a lint rule, and the test is what keeps it honest. The ban includes `Intl.DateTimeFormat().resolvedOptions()`: it reads the device's time zone, which must be a parameter. |
| D4 | `content/library/` ships **empty**. The validator prints its counts and passes on zero entries, but it fails if any fixture passes. | Every sentence needs `verifiedBy` from the author (§6.1). An agent writing "verified" entries would be inventing a fact. The 365-sunset-sentence requirement is a release gate, not a Phase 0 gate. |
| D5 | The event schema defines only the `care` kind, with `act: water \| shade \| weed \| petals`. | §6.2 contradicted itself: the example listed `wind \| light` and the comment listed `weed \| petals`. §1 describes weeds and fallen petals, so the comment wins, and CLAUDE.md is corrected in the same branch. The other kinds (`sunset`, `fox`, `harvest`…) wait for `docs/GAMEPLAY.md`, because their fields are game design. |
| D6 | One forbidden-word list, in `packages/content/src/forbidden.ts`, used by **both** `lint:copy` and the library validator. Whole-word, case-insensitive. `treat` is banned outright. | Two lists drift. Banning `treat` means the fox's food is always *berries*, never *treats*. That is a little inconvenient and much cheaper than a medical-claim review. |
| D7 | The CSP lives in a `<meta>` tag: `default-src 'self'`, no inline script. The service worker is registered from an emitted file, not an inline snippet. | GitHub Pages cannot set headers (§8, predicted). An inline registration script would need `'unsafe-inline'` and quietly widen the policy for everything. |
| D8 | No deploy workflow yet. | There is no GitHub remote. A workflow for a host that does not exist is configuration nobody can test. |
| D9 | `localDay(epochMs, timeZone)` is the only day computation. It formats with `Intl.DateTimeFormat` for an explicit IANA zone. | §7: one module computes a day. The zone is always passed in. A city the player chooses maps to a zone, and so does the device fallback, which the app reads and the engine never does. |
| D10 | `apps/rosea/vite.config.ts` imports the name constants by **relative path** (`../../packages/schema/src/constants.js`), not as `@rosea/schema`. | Vite bundles a config's relative imports but externalises anything under `node_modules`, and Node cannot load a workspace package's `.ts`. `--configLoader runner` fixed `vite build` but not `svelte-check`, which still printed *failed to load config* inside a green run. The constants module is pure and has no imports. |
| D11 | Every direct dependency is **pinned exactly** to the version Ludus's lockfile resolved, and `engine-strict` is off. | This machine runs Node 22.11. Fresh resolution pulled `@axe-core/playwright@4.14` (needs ≥ 22.12) and `eslint-visitor-keys@5` (declares ≥ 22.13). Ludus runs the same packages on the same Node. Upgrading Node is G0.20. |
| D12 | The trace's `geocell` is capped at 6 characters. | Found in self-review: the first draft allowed 16, and a 16-character geohash is centimetres. Six is ~1.2 × 0.6 km, the ~1 km of CLAUDE.md §4. Anything finer is rejected by the schema, before any code could send it. |
## 3. Risk analysis
Here "risk" means a person feeling worse, a person's location, or a person being
reachable who did not ask to be.
| Risk | Where it could enter in Phase 0 | Defence |
|:--|:--|:--|
| A forbidden or medical word reaches a player | Shell copy, manifest description, `index.html` | `lint:copy` scans `packages/ui/src/copy/`, `apps/rosea/index.html`, the manifest fields in `vite.config.ts` and `store/`. Fixtures prove it fires. |
| *Lonely* / *loneliness* appears in the product | Same | On the forbidden list (§5.6 rule 4). Allowed only in `.agents/` and `docs/`, which `lint:copy` does not scan. |
| A byte leaves the device | Fonts, icons or a CDN pulled in by a dependency | CSP `default-src 'self'`. The e2e suite records every request and fails on any origin other than the test server's. |
| Storage outside IndexedDB | A library writing `localStorage` | The e2e suite asserts `localStorage.length === 0` and `document.cookie === ''` after load. |
| A day computed in UTC | The engine, later | D9, a purity-lint ban on `toISOString().slice`, and DST golden tests for `localDay`. |
| The empty shell feels like a broken app | The placeholder page | One calm line from `copy/`, no spinner, no "coming soon". It says what is true and asks nothing. |
Looked for and not found in Phase 0: guilt, comparison, rejection, dependence. There
is no mechanic yet that could carry any of them.
## 4. Gap analysis and the designed solution
| Gap | Solution in this branch |
|:--|:--|
| No workspace, no commands | `pnpm-workspace.yaml`, `turbo.json` and root scripts for every command in §3 that has something to run. |
| `pnpm test` can exit 0 having run nothing | `test` is not cached (`cache: false`). Every package has at least one real test. Counts are quoted in the review. |
| No proof the PWA works offline under a sub-path | `e2e/offline.spec.ts` starts a real static server at `/Rosea/`, waits for the worker to control the page, **kills the server**, reloads, and asserts the shell rendered. Ludus learned that `context.setOffline` acts before the service worker and tests the harness, not the cache. |
| No guard on commits | `scripts/pre-commit` (5 MB) and `scripts/commit-msg` (AI attribution), installed by `pnpm install`. |
| CRLF churn on Windows (`core.autocrlf=true` on this machine) | `.gitattributes` with `* text=auto eol=lf`. |
## 5. Verification matrix
| Case | Kind | Where |
|:--|:--|:--|
| Hope-sentence schema accepts a valid entry | unit | `packages/schema/test/schemas.test.ts` |
| Care event rejects an unknown `act`, a missing `localDay`, free text in `messageId` | unit | same |
| Trace rejects a timestamp finer than a day and extra properties | unit | same |
| `localDay` in Prague on both 2026 DST days, Sydney, Reykjavík, UTC+14, UTC−12 | unit (golden) | `packages/engine/test/localDay.test.ts` |
| Monday evening in Anchorage is Monday, though the UTC day is Tuesday (the trap, measured) | unit | same |
| An unknown zone throws instead of falling back to UTC | unit | same |
| Days never go backwards, always advance within 26 h, are deterministic (8 zones, 2000–2100) | property | same, fast-check |
| Each purity ban fires on an impure snippet; clean code passes | unit | `packages/engine/test/purity-lint.test.ts` |
| Every fixture in `content/fixtures/` fails with its named message | unit | `packages/content/test/validator.test.ts` |
| Forbidden words: whole-word, case-insensitive; no false hit on *treaty*, *healthy*, *patience* | unit | `packages/content/test/forbidden.test.ts` |
| `lint:copy` core: strings and markup caught, comments ignored, *Domi* never alone | unit | `packages/content/test/copy-lint.test.ts` |
| Shell copy passes `lint:copy` | script | `pnpm lint:copy` |
| Shell names the product from the constant, has a `main` landmark and no controls | unit | `packages/ui/test/Shell.test.ts` |
| Trace rejects a geocell finer than ~1 km | unit | `packages/schema/test/schemas.test.ts` |
| `<meta charset>` stays within the first 1024 bytes after the CSP | e2e | `e2e/shell.spec.ts` |
| Hooks block a > 5 MB file and an AI trailer, and pass a clean commit | manual, run | `.agents/reviews/feature-phase0-workspace.md` |
| Built app renders its name at `/Rosea/` | e2e | `e2e/shell.spec.ts` |
| No request to any other origin; no cookie; no `localStorage` | e2e | same |
| Manifest `scope`/`start_url` and service-worker scope equal the base | e2e | same |
| CSP meta present; no inline script in the built `index.html` | e2e | same |
| No axe violations on the shell | e2e | same |
| Shell loads with the server gone | offline | `e2e/offline.spec.ts` |
| **Manual**: install from Chrome on a phone; open in airplane mode | manual | not done — needs a hosted build (D8) |
+20
View File
@@ -0,0 +1,20 @@
# Lessons
One file per category of problem (CLAUDE.md §5.1b). Read these first when something
behaves strangely. Each entry has three parts: **what happened**, **why it bit**,
and **how to apply it**.
| File | Entries | What belongs in it |
|:--|:--|:--|
| `soul.md` | none yet | What comforts and what only looks like comfort. **The most important file here.** No mechanic exists yet that could teach anything. |
| `architecture.md` | none yet | Layering, ownership, seams. |
| `design.md` | none yet | Wording, silence, empty states. |
| `art.md` | none yet | The image pipeline. |
| [`code.md`](code.md) | 2 | TypeScript, Svelte, async ordering, Rust. |
| [`technical.md`](technical.md) | 4 | The browser and the build as platforms. |
| [`testing.md`](testing.md) | 4 | 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. |
A file is created with its first real entry. An empty lessons file only looks like
knowledge.
+37
View File
@@ -0,0 +1,37 @@
# Code
## An agent's write tool can turn `\u00a0` into a real non-breaking space
**What happened.** `packages/content/src/copy-lint.ts` was written with the regex
`[\s\u00a0]`. On disk the file held `[\s` + the bytes `C2 A0` + `]`: an actual U+00A0.
ESLint's `no-irregular-whitespace` caught it. Fixing it with `sed`, then with a
`node -e` replace, then with a quoted heredoc each wrote the same character back. The
fix that worked built both strings from char codes (`String.fromCharCode(160)`,
`String.fromCharCode(92) + 'u00a0'`).
**Why it bit.** Somewhere between the agent and the file, a single-backslash
`\uXXXX` in the input was decoded. A double-backslash `\\u00a0` inside a JS string
(`forbidden.ts`) survived. The bug is invisible on screen: the two forms look the same.
**How to apply it.** Prefer `\s` or a named class over a literal Unicode escape in a
regex. When one is needed, check the bytes after writing.
This entry was itself written with two literal NBSPs where it named the escape, and was
fixed the same way. Check with `grep -n $'\xc2\xa0' file` (the two UTF-8 bytes) or
`sed -n Np file | od -c`. Do not use `grep -P '\xA0'`: it matches the last byte of `≠`
and other characters, and raised a false alarm on the review document. Keep
`no-irregular-whitespace` on.
## A Svelte 5 effect that short-circuits never tracks what it skipped
**What happened.** `Shell.svelte` moved focus with
`$effect(() => { if (moved) heading?.focus(); })`. `moved` is a plain variable and was
`false` on the first run, so the effect never read `heading` and had no dependencies.
When the view changed and `heading` was bound to the new `<h1>`, nothing re-ran. The
Shell test caught it: the focus stayed on `<body>`.
**Why it bit.** An effect tracks only the state it actually reads on each run. A
condition that returns early hides every read after it.
**How to apply it.** In an effect, read the state you depend on before any early
return or `&&` (`const target = heading; if (moved) target?.focus();`). Test the
re-run, not just the first run.
+33
View File
@@ -0,0 +1,33 @@
# Process
## Never "try" a credential helper to see if it works
**What happened.** On 2026-10-31 the first push to Gitea failed for lack of
credentials. The agent retried with `-c credential.helper=manager`. Git Credential
Manager returned a stored login for `gitea.marek-novak.cz`, Gitea rejected it, and git
then told GCM to erase that login. The push finally worked once the author copied
Ludus's repo-local `credential.helper` into this repository.
**Why it bit.** Git calls `credential reject` after an authentication failure. With
GCM that deletes the stored credential, so a failed probe is not harmless: it can
break every other repository that relied on the entry.
**How to apply it.** When a push needs credentials, ask the author how this machine
authenticates for that host. Never probe with a different helper, and never read,
print or search for token values. On this machine, each repository carries its own
`credential.helper`.
## Pin to a sibling's lockfile when the machine's Node is old
**What happened.** The first `pnpm install` resolved the newest versions.
`@axe-core/playwright@4.14` needs Node ≥ 22.12, and `typescript-eslint@8.72` pulled in
`eslint-visitor-keys@5`, which declares ≥ 22.13. This machine runs 22.11. Pinning every
direct dependency to the versions in Ludus's `pnpm-lock.yaml` and turning
`engine-strict` off gave an install that every gate passes on.
**Why it bit.** A caret range is a promise about the future, and the future had moved
past this machine's Node. Ludus, a known-good sibling on the same machine, was a
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).
+57
View File
@@ -0,0 +1,57 @@
# Technical
## A Vite config cannot import a workspace package's TypeScript source
**What happened.** `apps/rosea/vite.config.ts` imported the name constants from
`@rosea/schema`, whose `main` is `src/index.ts`. `vite build` failed with
`ERR_UNKNOWN_FILE_EXTENSION ".ts"`. `--configLoader runner` fixed the build. But
`svelte-check` loads the same config on its own, still failed, and printed
*failed to load config* while reporting 0 errors.
**Why it bit.** Vite bundles a config's relative imports but externalises anything
resolved through `node_modules`. Workspace packages are symlinks there, so Node
loads them natively, and Node 22.11 does not strip types. A tool that reads the config
for you has its own loader.
**How to apply it.** In a Vite config, import workspace code by **relative path**
to a dependency-free module. Treat a failure message inside a green run as a
failure: find which tool printed it.
## Vite escapes the quotes in an injected `<meta>` CSP
**What happened.** The built `index.html` carries `content="default-src &#39;self&#39;…"`.
A regex over the raw HTML looking for `'self'` would never match it.
**Why it bit.** The HTML is valid and the browser decodes the entities. Only a test
that reads the bytes sees the difference.
**How to apply it.** Read attributes from the DOM:
`page.locator('meta[http-equiv=…]').getAttribute('content')`. Keep raw-HTML checks for
byte-level questions, such as whether there is an inline `<script>` or where `<meta charset>` sits.
## Svelte 5 needs no preprocessor for `lang="ts"`
**What happened.** With `vitePreprocess()` in `svelte.config.js`, `svelte-check` tried
to load `vite.config.ts` to preprocess styles, and hit the error above. Removing the
preprocessor removed the problem, and every component still typechecks.
**Why it bit.** Svelte 5 strips type annotations natively. A preprocessor is only
needed for non-CSS style languages or TS features that emit code (enums, decorators).
**How to apply it.** Leave `svelte.config.js` as `export default {}` until a component
needs SCSS or emitted TS. Add the preprocessor in the same commit as that need.
## Turbo's cache does not see a file the app imports from outside its package
**What happened.** The app imports `docs/LETTER.md?raw`. With a sample letter written
into the file, `pnpm test:e2e` printed `@rosea/app:build: cache hit` and tested the
*old* bundle, so the link to the letter was missing. Turbo hashes a package's own
files, and `docs/` belongs to no package. Adding `docs/LETTER.md` to
`globalDependencies` in `turbo.json` turned it into a `cache miss`, and the test passed.
**Why it bit.** A build cache keyed on the wrong inputs gives a stale bundle that looks
fresh. This is CLAUDE.md §5.4 again, caused by the build tool and not the service worker.
**How to apply it.** Any file the app bundles from outside its package goes into
`globalDependencies` or the task's `inputs`, in the same commit as the import. To
check, change the file, run the build, and look for `cache miss`.
+60
View File
@@ -0,0 +1,60 @@
# Testing
## A pipe hides the exit code of the command you are checking
**What happened.** On 2026-11-01 Phase 0 ran `pnpm -s lint 2>&1 | tail -30; echo "exit=$?"`.
It printed one ESLint error and then `exit=0`. The `0` belonged to `tail`, not to ESLint.
**Why it bit.** Anything piped through `tail`, `grep` or `head` reports the last command's
status. A gate read that way can be red and look green. This is the same lie as
`pnpm test` exiting 0 having run nothing, one layer further out.
**How to apply it.** When the exit code matters, redirect to a file and read `$?`
before filtering: `cmd > log 2>&1; ec=$?; grep … log; echo "exit=$ec"`. You can also use
`${PIPESTATUS[0]}` in bash. Never quote `exit=0` from the far end of a pipe.
## `setOffline` tests the harness, not the service worker *(imported from Ludus)*
**What happened.** In Ludus, `context.setOffline(true)` and `route().abort()` both
failed the navigation before the service worker was consulted. So an "offline" test
passed or failed for reasons that had nothing to do with the cache.
**Why it bit.** Both mechanisms act at the browser's network layer, which sits in
front of service-worker dispatch.
**How to apply it.** Prove offline by **closing the server**: start it, wait for
`navigator.serviceWorker.controller` and for the precache, call `server.close()`,
then navigate. `e2e/offline.spec.ts` does this, and also fetches from Node to prove
the server really is gone. Not re-measured in Rosea. Strike the "imported" mark once
someone has.
## Put the bug back before you trust the test
**What happened.** Phase 0 put 13 bugs back one at a time: `clientsClaim: false`, no
`navigateFallback`, manifest scope `/`, an inline script, a Google Fonts link, a
`localStorage` write, a hard-coded heading, a UTC `localDay`, a disabled length cap
(checked twice), a lost word boundary, a removed Domi rule, and both git hooks.
Every one was caught. The results are recorded in
`.agents/reviews/feature-phase0-workspace.md`.
**Why it bit.** It didn't, this time. But a guard that has only ever been seen not
firing has not been tested. Without the run, a review can only say "I believe".
**How to apply it.** For every guard a branch adds, apply the inverse change, run the
one suite that should catch it, record CAUGHT or MISSED, and restore the file with
`git checkout`. Commit first, so the restore is exact.
## Fill an empty slot for one run, to test the state it will have later
**What happened.** The Letter's e2e test branches: no link while `docs/LETTER.md` is
empty, and the page opens once it is written. Only the empty branch could run, because
the author has not written the letter. One run with a temporary sample letter took the
other branch. It found the stale-cache bug (`technical.md`), and then passed the
written-letter page, axe included, in a real browser. The scaffold was restored
afterwards.
**Why it bit.** A test written for a future state passes trivially until that state
arrives. Then it fails for the first time on the author's machine, with the author's words.
**How to apply it.** When a test branches on content that does not exist yet, fill the
content temporarily, run the suite, restore it, and record the run in the review.
+97
View File
@@ -0,0 +1,97 @@
# Review — `docs/roadmap-gameplay`
The author's `docs/ROADMAP.md` and `docs/GAMEPLAY.md`, added 2026-11-01, read against
CLAUDE.md and what is on `main` (`12f5179`). Both documents are the author's: their
words are kept as given (GAMEPLAY.md was pasted as plain text and only given Markdown
headings and bullets). Where they disagree with each other or with the code, the
question is written down here, not resolved by editing them.
No code changed, so the gates were not re-run.
## 1. Phase 0 is not done by the roadmap's definition
What was merged as "Phase 0" (`d11d242`) is the workspace and its contracts. The
roadmap's Phase 0 is larger, and its **gate is not met**:
| Roadmap Phase 0 item | State |
|:--|:--|
| Repo, `.gitignore`, 5 MB hook, `CLAUDE.md`, this roadmap | Done (roadmap on this branch) |
| Remotes | Gitea only; GitHub missing (G0.13) |
| `ART.md` | Missing (G0.24) |
| Schema contracts, validator with negative fixtures, `lint:copy` | Done (G0.2, G0.5, G0.6) |
| **60 sentences**, sourced and verified public domain | **Missing**: 0 entries (G0.18). `verifiedBy` needs a person. |
| `art/STYLE.md` drafted with the author, `art/manifest.json`, SVG placeholders, `tools/art-prep` end to end on one asset | **Missing** (G0.24) |
| Slot for *A Letter from the Gardener* | Missing (G0.25) |
| Decision: how the sunset invitation reaches the player on the web | **Decided** 2026-11-01: in-app only (Q6, G0.26) |
**Gate:** 60 sentences pass and every fixture fails (half met: the fixtures fail, but
there are no sentences); one illustration through the full pipeline into `art/final/`
(not started). The status docs now say *workspace merged, Phase 0 gate open* instead
of *Phase 0 merged*.
## 2. Questions only the author can answer
Each one blocks the feature named in its row. None blocks the rest of Phase 0.
| # | Where | The conflict | Blocks |
|:--|:--|:--|:--|
| Q1 | GAMEPLAY §3 vs ROADMAP Phases 2–4, §5 | Berries come from *forgotten roses of other players*, so the fox's food needs other players. But the fox arrives in Phase 2, before friends (Phase 3). Cold start says Phases 1–2 must stand alone, and the Phase 4 gate says deleting `lucerna` leaves Phases 1–3 working. **Where does the fox's food come from with no friends and no Lucerna?** | Phase 2 fox |
| Q2 | GAMEPLAY §1–2 vs ROADMAP §2, Phase 1 | *Short visits only hold her; real time brings full bloom*, plus *care hours* in the numbers. If "real time" means minutes on screen, bloom rewards staying in the app: the **dependence** risk, against *the best moments send the player away from the screen*. The roadmap says growth comes from **total days of care**. Proposed reading: calendar days with real care, where a long session is worth no more than a short one with the same care. Confirm. | Phase 1 growth |
| Q3 | ROADMAP §1 vs GAMEPLAY §5 | Two lanterns. **Lucerna** (*lantern*) is the server, and the **lantern** is the device-to-device "I'd like to talk". A player, or a later agent, could take the lantern to go through Lucerna. Rename one, or write down that the lantern never touches Lucerna. | Naming; Phase 3–4 |
| Q4 | GAMEPLAY §5 | Before a match, sentences carry *"sent through Amicitia"*. If the bytes go over Rosea's own sync, the label is untrue about where data went (Privacy: what was the player told). Either Amicitia carries them, or the wording changes, for example *a taste of Amicitia*. | The Amicitia bridge |
| Q5 | GAMEPLAY §3 vs ROADMAP Phase 2 | *No extra creatures* vs visitors who leave mementos, rare visitors, and the sheep album. Is the rule about food and the fox's screen only? | Phase 2 collections |
| Q6 | ROADMAP Phase 0 vs CLAUDE.md §8 | The notification decision is due in Phase 0 by the roadmap and in the Phase 1 feature doc by CLAUDE.md. Taken as Phase 0, since the roadmap is newer. An agent can write the options and their privacy cost; the author picks one. | G0.26 |
| Q7 | GAMEPLAY §5 vs ROADMAP | The Amicitia bridge has no phase. It needs roads (Phase 3) and swapped keys (`packages/identity`). Phase 3, 5, or its own? | Planning |
| Q8 | GAMEPLAY §1 | *Coming back on nearby days gives a little more.* This is not a streak, but a player back after a gap gets less than one back after a day. It is safe only if nobody ever sees what a gap cost them. Recorded for the Phase 1 Soul review; no answer needed now. | Phase 1 Soul review |
### Answers — the author, 2026-11-01
Written into `docs/GAMEPLAY.md`, `docs/ROADMAP.md` and CLAUDE.md, each marked
*decided 2026-11-01* in the author's docs.
| # | Answer |
|:--|:--|
| Q1 | **Own bush first.** A wild bush beside the player's own rose ripens when the care helped. Friends' forgotten roses (Phase 3) and strangers' (Phase 4) add berries, never required. Phase 2 needs no other player and the Phase 4 gate holds. Farming limit: one harvest per bush per local day. |
| Q2 | **Days of care.** Calendar days on which the care helped, never minutes on screen. The numbers panel shows *days of care* in place of *care hours* (an agent's reading of this answer; the author can reverse it). |
| Q3 | **Keep both names.** The lantern travels device to device only and never passes through `lucerna`. Written in GAMEPLAY §5 and CLAUDE.md §1–2. |
| Q4 | **"A taste of Amicitia"**, with the icon. |
| Q5 | **The rule is removed.** GAMEPLAY §3 no longer says *no extra creatures*, so Phase 2's visitors stand. |
| Q6 | **Phase 0, in-app only.** No push server on the web; local notifications come with the Tauri shell (Phase 6). Recorded in ROADMAP Phase 0 and CLAUDE.md §8. Closes G0.26. |
| Q7 | **Phase 3.** Added to ROADMAP Phase 3 with the friends' berries. |
| Q8 | No answer needed: a rule for the Phase 1 Soul review. |
## 3. Notes that need no answer
- **"treat."** GAMEPLAY §3 calls rose hips *the rare top treat*. That is fine in a
design doc. In player copy `treat` is banned (D6), so the in-game words are
different. `lint:copy` catches it.
- **The planets.** *King*, *lamplighter*, *geographer* and similar are ordinary words
and are not on the forbidden list, which is right: §7 allows the echo but never the
name or text. *The Geographer's book* and the *sheep album* are the closest echoes.
Each planet's feature doc gets a copyright line in its review.
- **The drunkard's planet** is a Soul risk for a player who drinks. It goes into that
planet's feature doc.
- **Sunset from a time zone.** A zone is not a place, and sunset needs coordinates.
Fallback: the zone's reference location from the tz database (`zone1970.tab`),
bundled offline. This goes into the Phase 1 sun feature doc. It never asks for GPS
and never makes a network call.
- **Bubble copy** has the same rules as the hope library (GAMEPLAY §4). `lint:copy`
already scans `packages/ui/src/copy/`. Whether bubbles also get ids and a validator
is decided in Phase 1.
## 4. What already agrees
- The care acts *water, shade, weeds, petals* match the `care` schema's `act` enum (D5).
- *Berries, never treats*, as in D6.
- Book and Tolkien names are already forbidden in copy (`forbidden.ts`), and
*Rosea Domi* / *Amicitia Domi* pass the Domi-alone rule.
- CLAUDE.md §8 already names the **berry farming** trap (one harvest per forgotten
rose per local day) and the **lantern as rejection** trap (one-sided lanterns are
invisible).
- "Never GPS" matches CLAUDE.md §4.
## What was NOT done
- The author's text was not changed, including where §2 shows a conflict.
- No game code was written. GAMEPLAY.md now exists, but Phase 1 starts only after
the Phase 0 gate (ROADMAP §4: *failing it means the next phase does not start*).
+74
View File
@@ -0,0 +1,74 @@
# Review — `feature/letter-slot`
Adversarial self-review (CLAUDE.md §5.3). Analysis:
[`features/letter-slot.md`](../features/letter-slot.md). Reviewed 2026-11-01 on
Node 22.11.0, Windows 10. There is no PR: the only remote is Gitea, and this session
cannot open one there.
## Gates — counts, not exit codes
| Gate | Result |
|:--|:--|
| `pnpm lint` | exit 0 |
| `pnpm typecheck` | exit 0; `svelte-check` 0 errors **0 warnings** in ui and app (a bare `href="#"` warning was fixed) |
| `pnpm test` | **130 passed**: schema 15, content 47, engine 52, ui 16 (was 3) |
| `pnpm lint:copy` | **12 files** checked (was 9: `parse.ts`, `Letter.svelte`, `docs/LETTER.md`), 0 problems |
| `pnpm validate:library` | 0 entries; 13 of 13 fixtures rejected |
| `pnpm test:e2e` | **7 passed** (was 6), on the scaffold letter |
| `pnpm test:offline` | **1 passed** |
**Built, not deployed** (§5.4): there is no host. The change is **deliberately
invisible**: with the scaffold letter, the built page looks exactly as before. The
bundle is 8 precache entries, 42.74 KiB.
**The written-letter branch, run once.** `docs/LETTER.md` was given a temporary sample
letter (headings, a paragraph across lines, *emphasis*, an `https:` and a `tel:` link).
e2e: 7 passed, including the page opening from the link, axe with no violations, and
*Back*. Offline: 1 passed. The scaffold was then restored and both suites ran again
green. That run found finding 1.
## Test honesty — bugs put back
| Bug put back | Suite | Result |
|:--|:--|:--|
| `ALLOWED_HREF = /.*/` (any link scheme) | ui unit | CAUGHT: 2 failed |
| The letter link shown while the letter is empty | ui unit | CAUGHT: 2 failed |
| same | e2e | CAUGHT: `toHaveCount(0)` failed |
| The focus effect reads `heading` only after `if (moved)` | ui unit | CAUGHT: focus stayed on `<body>`. This was the first draft's real bug (finding 2). |
| *heal* in the body of `docs/LETTER.md` | `lint:copy` | CAUGHT: `docs/LETTER.md:36 'heal' (medical)` |
| `docs/LETTER.md` missing from turbo's cache key | e2e, written letter | CAUGHT, as the real finding 1 |
Not caught by any test: removing `docs/LETTER.md` from `lint:copy`'s file list. Only
the quoted file count (12) would show it. See finding 6.
## Findings
| # | Area | Finding | Resolution |
|:--|:--|:--|:--|
| 1 | **Correctness** | Turbo hashed only the app package, so after the letter changed, `test:e2e` printed `cache hit` and tested the **old bundle**. A deploy from a warm cache would ship the old letter. | **Fixed**: `docs/LETTER.md` is in `globalDependencies` (L8). Shown as `cache miss` after the change. Lesson: `technical.md`. |
| 2 | Correctness | The first focus effect returned before reading `heading`, so it never re-ran and focus never moved. | **Fixed** before review, caught by the Shell test. Lesson: `code.md`. |
| 3 | **Offline** | The letter opens offline, because it is bundled. A support line given as an `https:` link does **not** work offline, but a `tel:` link does. | **Deferred** to G0.27, with the advice that each support line has a phone number. |
| 4 | **Privacy** | An `https:` link in the letter takes the player to another site. Nothing leaves without their tap, the referrer is stripped (`no-referrer` on the page and `noreferrer` on the link), and it opens in a new tab. Which sites the letter links to is the author's choice. | **Accepted.** |
| 5 | Correctness | The parser has blind spots. A numbered list (`1. …`) without blank lines collapses into one paragraph, and `snake_case_word` makes *case* italic. | **Accepted.** The scaffold says which Markdown works, and anything else shows as text, never as markup. |
| 6 | Test honesty | No test proves `lint:copy` reads `docs/LETTER.md`. It was shown by the *heal* mutation, but deleting the path from `FILES` would pass silently. | **Accepted for now**: the review quotes the file count. Revisit if `lint:copy` grows a file list worth testing. |
| 7 | Correctness | *Back* leaves `#garden` in the address bar. A bookmark at `#garden` or any unknown hash opens the garden. | **Accepted**: harmless, and any hash but `#letter` is home by design. |
| 8 | **Soul** | Once the letter exists, the home view offers one link, *A Letter from the Gardener*. Looked for guilt, comparison, rejection and dependence: the page asks nothing, counts nothing, and is never required (GAMEPLAY §4). Found none. | — |
| 9 | Copyright | The scaffold's comments mention "the book". They are stripped before the page and skipped by `lint:copy`. Whether the letter's own words may name the book is **Q9**, for the author. | **Open**, Q9. |
Looked for and found none:
- **Reachability.** The letter is one-way, from the author to every player. There is
no input.
- **Injection.** No `{@html}` anywhere. Raw HTML and `<script>` stay text (tests), and
only `https:` and `tel:` become links (tests, plus a mutation). Svelte escapes
attribute values.
- **Correctness cases from §5.3.** Clock, DST, partial write and two tabs do not apply:
there is no state. A tab closed on `#letter` reopens on the letter (test: *opens
straight at #letter*).
## What was NOT verified
- **A screen reader.** axe passes on both views, and the focus move is unit-tested.
Nobody has listened to it.
- **Firefox, WebKit and a phone.** Desktop Chromium only.
- **The author's real letter.** Only a sample has rendered.
+103
View File
@@ -0,0 +1,103 @@
# Review — `feature/phase0-workspace`
Adversarial self-review (CLAUDE.md §5.3). Analysis:
[`features/phase0-workspace.md`](../features/phase0-workspace.md).
Reviewed 2026-11-01 on Node 22.11.0, pnpm 9.12.3, Windows 10.
There is no PR. The only remote is Gitea, and this session has no API access to open
one there. The branch is pushed for the author to merge.
## Gates — counts, not exit codes
Each exit code was read directly (`cmd > log; ec=$?`), never through a pipe
(`lessons/testing.md`).
| Gate | Result |
|:--|:--|
| `pnpm lint` | exit 0 |
| `pnpm typecheck` | exit 0; 10 turbo tasks, `svelte-check` 0 errors 0 warnings in ui and app, plus root `tsc` over `e2e/` and `scripts/` |
| `pnpm test` | **117 passed**: schema 15, content 47, engine 52, ui 3 |
| `pnpm lint:copy` | 9 files checked, 0 problems |
| `pnpm validate:library` | 0 entries (empty by design, D4); **13 of 13 fixtures rejected** with their named rule |
| `pnpm test:e2e` | **6 passed**, against the built bundle under `/Rosea/` |
| `pnpm test:offline` | **1 passed**: reload, cold start and a deep link render after the server is closed |
The bundle was **built** (`apps/rosea/dist`) but **not deployed** (§5.4): there is no
host yet (G0.13). No player can see this change.
## Test honesty — every guard was made to fail
Each bug was reintroduced one at a time, the one suite that should catch it was run,
and the file was restored with `git checkout` after the commit `49c8def`.
| Bug put back | Suite | Result |
|:--|:--|:--|
| `clientsClaim: false` (first visit never controlled) | offline | CAUGHT: controller wait timed out |
| `navigateFallback: null` | offline | CAUGHT: deep link `ERR_CONNECTION_REFUSED` |
| manifest `scope: '/'` | e2e | CAUGHT: scope ≠ `/Rosea/` |
| inline `<script>` in `index.html` | e2e | CAUGHT: inline script list not empty |
| a Google Fonts `<link>` | e2e | CAUGHT: other-origin request recorded |
| `localStorage.setItem` on load | e2e | CAUGHT |
| `<h1>Rosea</h1>` instead of the constant | e2e | CAUGHT |
| `localDay` returns the UTC day | engine unit | CAUGHT: 11 failed |
| length cap never fires | `validate:library` | CAUGHT: `too-long.json` passed, run failed |
| length cap never fires | content unit | CAUGHT |
| forbidden match loses its trailing word boundary | content unit | CAUGHT: *treaty*, *healthy*, *patiently* flagged |
| Domi-alone rule removed | content unit | CAUGHT |
| 5.7 MB file staged / `Co-Authored-By: Claude` trailer | hooks, run directly | BLOCKED both; clean input passed both |
Not mutated: each of the 16 engine-purity bans separately. `purity-lint.test.ts`
already lints one impure snippet per ban and asserts it is reported, which is the
same check from the other side.
## Findings
| # | Area | Finding | Resolution |
|:--|:--|:--|:--|
| 1 | **Privacy** | The trace schema allowed `geocell` up to 16 characters. A 16-character geohash is centimetres: a house, not a district. | **Fixed** in this branch: capped at 6 (~1.2 × 0.6 km), with a test that 7 and 12 characters are rejected. D12. |
| 2 | Correctness | Terms with a hyphen and a space matched the same word twice, so `lint:copy` reported one word twice. Fixing that showed `Middle earth` was redundant with `Middle-earth`. | **Fixed**: one hit per index, and the redundant entry removed. Test added. |
| 3 | Correctness | The CSP meta is injected before `<meta charset>`, which must stay within 1024 bytes. Measured at byte 404 in this build. | **Fixed** with a guard: an e2e assertion on the byte offset. The order is kept, because the CSP must precede every script. |
| 4 | Correctness | `ROSEA_BASE`'s default `/Rosea/` is written twice, in `vite.config.ts` and `e2e/static-server.ts`. | **Accepted.** If they disagree, every asset 404s and every e2e test fails at once, so drift cannot be silent. |
| 5 | Architecture | `vite.config.ts` reaches into `packages/schema/src/constants.ts` by relative path. | **Accepted**, D10. The module is pure and import-free, and the alternative printed a load failure inside a green run. |
| 6 | Correctness | `validator.ts` maps Ajv's English error text to the `no-source` / `no-tradition` rules by regex. An Ajv upgrade that rewords them would turn those rules into `schema`. | **Accepted.** The fixtures would fail loudly: `no-source.json` expects `no-source`. Dependencies are pinned (D11). |
| 7 | Correctness | `stripComments` treats `//` inside a string as a comment, so `"a // therapy"` would be missed by `lint:copy`. | **Deferred.** A real tokenizer is not worth it while copy is one line. Revisit when `copy/` grows. |
| 8 | Privacy | Source maps are built (`sourcemap: true`) and would be published with the site. They are not precached. | **Deferred** to G0.23: depends on whether the repository is public. |
| 9 | Technical | `engine-strict` is off and Node 22.11 is below what `eslint-visitor-keys@5` declares. A package could use an API this Node lacks. | **Accepted for now**: every gate ran green on 22.11. Upgrade Node, G0.20. |
| 10 | Soul | The shell says *The garden is being prepared.* A first-time visitor finds nothing to do and might feel turned away, or feel asked to come back. | **Accepted.** The line asks nothing and promises no date, and the build is not deployed (D8), so no player sees it. It is replaced by the first real screen. |
Looked for and found none:
- **Soul.** No guilt, comparison, rejection or dependence. There is no mechanic, no
count, no notification and no streak.
- **Reachability.** There is no network feature. The care-event schema refuses free
text in `messageId` (a test), and refuses any extra field, so nothing can ride along.
- **Offline.** The whole shell works with the server closed (offline suite).
- **Privacy.** Every request goes to the serving origin (e2e records all of them).
There are no cookies and no Web Storage (e2e), and the CSP is `'self'` only. The
only bytes that leave the device are the requests for the app's own files.
Correctness cases from §5.3: second run, clock change, DST, partial write, tab closed
mid-action and two tabs do not apply to a shell with no state. DST is covered for
`localDay`, on both 2026 Prague transition days. The rest return with
`packages/storage`.
## What was NOT verified
- **Real GitHub Pages.** The sub-path is tested against a local server only.
- **A phone.** No install, no airplane mode, no iOS Safari. The suites use desktop
Chromium only.
- **Firefox and WebKit.** Not run.
- **Screen reader.** axe passes. No one has listened to the page.
- **A fresh clone.** `pnpm install --frozen-lockfile` passed on the merged `main`
(`d11d242`), but in the existing checkout, not a new one.
## After merge
Merged with `--no-ff` as `d11d242` and pushed. Local `HEAD`, `origin/main` and
`git ls-remote origin main` print one hash. Every gate ran again on the merged tree,
with the same counts as above: 117 unit, 6 e2e, 1 offline, 13 of 13 fixtures.
There is no GitHub remote yet, so no mirror to check (§5.2, G0.13).
- **The setOffline lesson** is imported from Ludus and was not re-measured here.
- **The rename-in-one-commit property.** Nobody has tried renaming. The name lives
in `constants.ts` and `index.html`, the manifest is built from the constants, and
the `@rosea/*` scope and database name are as listed in CLAUDE.md.
+8
View File
@@ -0,0 +1,8 @@
# This machine has core.autocrlf=true. Without this, every text file is
# rewritten with CRLF on checkout and diffs fill with line-ending noise.
* text=auto eol=lf
*.webp binary
*.avif binary
*.png binary
*.ico binary
+3
View File
@@ -28,3 +28,6 @@ art/exports/
.DS_Store
Thumbs.db
*.log
# Generated from JSON Schema by packages/schema build
packages/schema/src/generated/
+5
View File
@@ -0,0 +1,5 @@
# As in Ludus. `engine-strict` is deliberately OFF: it fails the install on any
# transitive package's declared Node range, and eslint-visitor-keys@5 declares
# ^22.13 while running fine on 22.11 (this machine, and Ludus's).
auto-install-peers=true
strict-peer-dependencies=false
+36 -20
View File
@@ -52,12 +52,14 @@ encouraging, never ruling), never a name or a quote.
her. Care has a touch of skill: water by feel (too much is as bad as too little), shade her from wind,
pull weeds, gather fallen petals. She grows from the **total** time of care, never from a streak.
Neglect makes her **drift** — turn away, close a little — never break. Short visits hold her; real
time brings full bloom. One tap shows her real numbers (water, warmth, care hours, trend).
time — calendar days on which care helped, never minutes on screen — brings full bloom. One tap
shows her real numbers (water, warmth, days of care, trend).
- **The planets** — a journey through lonely grown-ups (the king, the vain man, the businessman, the
lamplighter, the geographer…). Each planet lets the player feel one shape of loneliness.
- **The fox** — follows at a distance from the first planet and comes closer through touch (pet,
brush) and food. The rose tells you what he wants today. His food is **berries**, gathered by tending
other players' forgotten roses (one harvest per forgotten rose per day, only when the care helped).
brush) and food. The rose tells you what he wants today. His food is **berries**: first from the wild bush
beside the player's own rose, later also from tending other players' forgotten roses — an addition,
never a requirement (one harvest per bush per day, only when the care helped).
Your own rose's growth sets berry quality: wild strawberries → blueberries → raspberries →
blackberries → rose hips. After the taming he leads the player to real people.
- **Teaching in play** — the rose and the fox explain and remind in speech bubbles, with text from the
@@ -68,7 +70,8 @@ encouraging, never ruling), never a name or a quote.
footprints, then a trail, then a road.
- **The bridge to Amicitia** (promoted openly) — once a path is a road, either player may light a
**lantern**. A one-sided lantern is invisible; when both are lit, the game says so and the two apps
swap anonymous keys device to device. Players are known only by their rose's name. Free conversation
swap anonymous keys device to device. The lantern never passes through `lucerna`. Before a match,
sentences carry the Amicitia icon and *a taste of Amicitia* — never "sent through Amicitia". Players are known only by their rose's name. Free conversation
happens only in Amicitia, never in Rosea. Rosea has no doors: paths only grow, a lit lantern stays lit.
- **The shared sky** — every act of care toward someone else adds light to one night sky that all
players share. The sky is the **real** sky: real constellations. Every day at local sunset a wave of
@@ -110,7 +113,11 @@ feed of anything.
---
## 2. Repository layout (proposed — confirmed when Phase 0 scaffolds it)
## 2. Repository layout
Phase 0 scaffolded `schema`, `engine`, `content`, `ui` and `apps/rosea`. `storage`, `identity`,
`sync`, `services/lucerna`, `tools/art-prep` and `art/` arrive with their first feature, because an
empty package has a test suite that runs nothing ([`phase0-workspace.md`](.agents/features/phase0-workspace.md) D1).
```
pnpm-workspace.yaml
@@ -157,7 +164,8 @@ content/
docs/ # ROADMAP.md, ART.md, numbered milestone feature docs
```
`lucerna` — *lantern*: it only ever shows that someone was there.
`lucerna` — *lantern*: it only ever shows that someone was there. The lantern gesture (§1) shares the
name and never passes through it.
**Dependency direction (never violate):**
@@ -192,27 +200,32 @@ Web first is the decision: the game must run from a link, on any phone, with no
---
## 3. Commands (proposed until Phase 0 scaffolds them)
## 3. Commands
```bash
pnpm install --frozen-lockfile
pnpm --filter @rosea/schema build # schema first, always
pnpm install --frozen-lockfile # also installs the git hooks (§5.2)
pnpm --filter @rosea/schema build # schema first, always (generates the contract types)
pnpm --filter @rosea/app dev # 127.0.0.1:5173 — never --host (§5.7)
pnpm build # turbo: schema -> engine -> content -> ui -> app
pnpm build # turbo: schema -> engine/content/ui -> app
pnpm lint # ESLint, incl. the engine-purity rule (§7)
pnpm typecheck # tsc + svelte-check, every package plus e2e/ and scripts/
pnpm test # vitest, all packages — quote counts per package
pnpm --filter @rosea/engine test # incl. fast-check property tests and sun golden tests
pnpm test:e2e # Playwright against the BUILT app
pnpm test:offline # Playwright, network cut after first load
pnpm --filter @rosea/engine test # incl. fast-check property tests (sun golden tests: later)
pnpm test:e2e # builds, then Playwright against the BUILT app under /Rosea/
pnpm test:offline # builds, loads once, CLOSES the server, reloads
pnpm validate:library # every hope sentence; fixtures must FAIL
pnpm lint:copy # forbidden words and names (§5.6)
# Not yet — they arrive with their first feature:
pnpm art:prep # opens tools/art-prep on 127.0.0.1
cargo test --manifest-path services/lucerna/Cargo.toml # Phase 4 onward
```
The build's base path is `/Rosea/` (GitHub Pages' project sub-path); `ROSEA_BASE=/x/` overrides it
for the build and for both Playwright suites together.
> **The `pnpm test` trap, imported from Aeterna.** Exit code 0 says the command succeeded, not that
> tests ran. A filter that matched nothing and a green run look identical. **Quote the counts per
> package, or do not claim green.**
@@ -354,7 +367,7 @@ happened twice.)*
- **The engine gets property tests.** `fast-check`: growth is monotonic in total care and never
decreases; fox distance never jumps more than one step per day; replaying the same log twice gives
byte-identical `derived` state; a missed sunset never changes the rose's stage; an unopened
sentence is never lost; at most one harvest per forgotten rose per local day, and none when the care
sentence is never lost; at most one harvest per bush per local day, and none when the care
did not help; drift never lowers the stage earned.
- **Sun maths gets golden tests** against published sunrise/sunset tables for a spread of cities:
Prague, Reykjavík, Tromsø (polar day and polar night), Quito, Sydney, Anchorage — including both DST
@@ -421,9 +434,11 @@ player can send another player, and the sender picks one.
```jsonc
{ "kind": "care", "ts": 1761500000000, "localDay": "2026-10-24",
"from": "<pubkey>", "to": "<pubkey>", "act": "water" | "shade" | "wind" | "light",
"from": "<pubkey>", "to": "<pubkey>", "act": "water" | "shade" | "weed" | "petals",
"trace": "petal:<colour>", "messageId": "ps-23-4" | null, "clientVersion": "0.1.0" }
// act: "water" | "shade" | "weed" | "petals" (own rose or another player's)
// act applies to the player's own rose or another player's. (This example once
// listed "wind" | "light"; §1's weeds and fallen petals won — phase0-workspace.md D5.)
// Only "care" is in packages/schema so far; each other kind arrives with the feature doc that uses it.
// other kinds: "sentence-opened", "sunset" (seen), "planet-step", "fox" (pet | brush | feed),
// "harvest" (berry kind), "thanks", "lantern" (lit — never unlit)
```
@@ -452,7 +467,8 @@ No timestamp finer than a day, no precise location, no free text, no link to the
- **Svelte 5 runes, no state library.** A component that decides growth, taming or anything in the sky
is a layering violation and a review **blocker**.
- **Three taps to action, one preferred.** From a cold open, tending the rose is one tap.
- **Every string a player reads lives in `packages/ui/src/copy/`**, and passes `lint:copy`. The
- **Every string a player reads lives in `packages/ui/src/copy/`**, and passes `lint:copy` — except
the Letter, which is the author's Markdown in `docs/LETTER.md` and passes `lint:copy` too. The
interface language is plain English (Czech later). Latin is for the brand only.
- **Silence is a feature.** Sunset, the thanks visit and the end of a planet have moments with no
buttons at all. Do not fill them.
@@ -468,14 +484,14 @@ No timestamp finer than a day, no precise location, no free text, no link to the
| Trap | Why it bites |
|:--|:--|
| **A PWA cannot schedule a local notification** *(predicted — verify first)* | The sunset invitation is time-based. A web app generally cannot fire a notification at a set time while closed without a **push server** sending it, and a push server that knows when someone's sunset is knows roughly where they are. On iOS, web push works only for a site added to the home screen. Decide this in the Phase 1 feature doc: in-app sunset only for the web build, and local notifications through the Tauri shell later — or a push design whose privacy cost is written down. |
| **A PWA cannot schedule a local notification** *(predicted — verify first)* | The sunset invitation is time-based. A web app generally cannot fire a notification at a set time while closed without a **push server** sending it, and a push server that knows when someone's sunset is knows roughly where they are. On iOS, web push works only for a site added to the home screen. **Decided in Phase 0 (2026-11-01):** in-app sunset only for the web build — no push server — and local notifications through the Tauri shell later (Phase 6). |
| **Polar day and polar night** *(predicted)* | Above the Arctic Circle the sun does not set in summer or rise in winter. "Every day at sunset" has no answer there. The engine must return a defined state and the game must have a gentle alternative (e.g. the hour the light is lowest). |
| **DST and the local day** *(predicted)* | Sunset jumps an hour twice a year under a player who did nothing; a day boundary computed in UTC records Monday-evening care as Tuesday's. One module computes the day. |
| **Comfort becomes wallpaper** | The same words every day stop meaning anything. Comfort words are occasional; the real trace of a real person is constant. Track repetition in tests. |
| **Guilt sneaks in through "gentle" reminders** | "Your rose misses you" is guilt wearing a ribbon. No notification ever refers to neglect — the player's or anyone else's. |
| **Streak creep** | Someone will propose "just a small streak". Growth is from total care; a missed day never resets anything. |
| **Drift that reads as blame** | A rose turned away can feel like an accusation. Drift is shown as waiting, never as hurt caused; she brightens on the first touch, and no copy ever says *you forgot*. |
| **Berry farming** | Tending forgotten roses for food invites mindless tapping. One harvest per forgotten rose per local day, only when the care actually helped — enforced in `engine/forage`, property-tested. |
| **Berry farming** | Tending roses for food invites mindless tapping. One harvest per bush per local day — the player's own and each forgotten rose's — only when the care actually helped, enforced in `engine/forage`, property-tested. |
| **A lantern as rejection** | A lit lantern that is visibly unanswered is the rejection this game exists to avoid. One-sided lanterns are invisible to the other player, always. |
| **Location makes people findable** | Coarse cells next to a sparse population identify a house. Cell size must adapt to density, traces must be delayed and auto-deleted, and stranger contact is consent-only (§5.6). |
| **The library as a scam channel** | If any field lets a sender attach free text, a lonely recipient can be manipulated. The id-only contract (§6.1) is the defence. |
+54
View File
@@ -0,0 +1,54 @@
# Handover
Rewritten at the end of each session (CLAUDE.md §5.1).
## Last session — 2026-10-31 to 2026-11-01
**Done.**
- **Repository:** the git repo exists, and `origin` is Gitea (`mnovak/Rosea`).
`main` holds `CLAUDE.md` and `.gitignore` (`1e4c5a0`).
- **Phase 0 workspace:** merged to `main` with `--no-ff` (`d11d242`) and pushed. Local and
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: 117 (schema 15, content 47,
engine 52, ui 3). E2E: 6. Offline: 1. `lint:copy`: 9 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
`docs/roadmap-gameplay`, as the author gave them, together with a read against the
code: [`.agents/reviews/docs-roadmap-gameplay.md`](.agents/reviews/docs-roadmap-gameplay.md).
The author answered Q1–Q7, and the answers are written into both docs and CLAUDE.md.
Merged to `main`.
- **The Letter slot:** merged to `main`. `docs/LETTER.md`
holds slots as comments only. Once the author writes in it, a link to the letter
appears in the garden, and the page opens at `#letter`, offline too. Review:
[`.agents/reviews/feature-letter-slot.md`](.agents/reviews/feature-letter-slot.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). Also open: a GitHub remote (G0.13). The Letter slot is built (G0.25).
The notification decision is made: in-app only on the web (G0.26).
**Waiting on the author.**
1. **The Letter:** the words in `docs/LETTER.md`, the verified support lines for the
door to real help (G0.27), and Q9 (may the letter name the book).
2. **Sentences:** an agent may propose public-domain candidates with their sources.
Only the author can mark one verified.
3. **`docs/ART.md` and `art/STYLE.md`**, which are needed before the art pipeline.
4. **A GitHub repository** for Pages, and whether it is public (G0.13, G0.23).
5. **Upgrading Node** to ≥ 22.13 on this machine (G0.20).
**How this machine works** (not in the code):
- **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
probe other helpers: `lessons/process.md`.
- **Hooks:** `pnpm install` installs them. They block files over 5 MB and AI
attribution trailers.
**Read first next time:** [`.agents/GAP_ANALYSIS.md`](.agents/GAP_ANALYSIS.md), then
[`.agents/lessons/`](.agents/lessons/README.md).
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="referrer" content="no-referrer" />
<!-- One of the three places the product name lives (CLAUDE.md preamble). -->
<title>Rosea Domi</title>
<link rel="icon" href="./icon.svg" type="image/svg+xml" />
<link rel="apple-touch-icon" href="./icon.svg" />
</head>
<body>
<div id="app"></div>
<script type="module" src="./src/main.ts"></script>
</body>
</html>
+24
View File
@@ -0,0 +1,24 @@
{
"name": "@rosea/app",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "The PWA. Renders what the engine returns; contains no growth, taming or sky logic.",
"scripts": {
"dev": "vite --host 127.0.0.1 --port 5173 --strictPort",
"build": "vite build",
"typecheck": "svelte-check --threshold error --output human"
},
"dependencies": {
"@rosea/schema": "workspace:*",
"@rosea/ui": "workspace:*"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "5.1.1",
"svelte": "5.56.9",
"svelte-check": "4.7.6",
"typescript": "5.9.3",
"vite": "6.4.3",
"vite-plugin-pwa": "1.3.0"
}
}
+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<!-- Placeholder icon (CLAUDE.md §2 art/placeholders): form only, not art. Replaced through docs/ART.md. -->
<rect width="512" height="512" rx="96" fill="#fbf6f1"/>
<circle cx="256" cy="232" r="120" fill="#b4485e"/>
<circle cx="256" cy="232" r="64" fill="#d97a8c"/>
<rect x="246" y="340" width="20" height="112" rx="10" fill="#5f7a52"/>
</svg>

After

Width:  |  Height:  |  Size: 418 B

+7
View File
@@ -0,0 +1,7 @@
<script lang="ts">
import { Shell } from '@rosea/ui';
// Bundled at build time, so the letter is precached and opens offline (letter-slot.md L1).
import letter from '../../../docs/LETTER.md?raw';
</script>
<Shell {letter} />
+8
View File
@@ -0,0 +1,8 @@
import '@rosea/ui/tokens.css';
import { mount } from 'svelte';
import App from './App.svelte';
const target = document.getElementById('app');
if (target === null) throw new Error('index.html has no #app element');
mount(App, { target });
+2
View File
@@ -0,0 +1,2 @@
/// <reference types="svelte" />
/// <reference types="vite/client" />
+1
View File
@@ -0,0 +1 @@
export default {};
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node", "svelte", "vite/client"]
},
"include": ["src/**/*.ts", "src/**/*.svelte", "vite.config.ts"]
}
+107
View File
@@ -0,0 +1,107 @@
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { defineConfig, type Plugin } from 'vite';
import { VitePWA } from 'vite-plugin-pwa';
// A relative path, not '@rosea/schema', on purpose. Vite bundles a config's
// relative imports but externalises anything under node_modules, and Node cannot
// load a workspace package's .ts source, so `vite build` and `svelte-check` both
// failed to load this file. The constants module is pure and dependency-free.
import { PRODUCT_NAME, PRODUCT_SHORT_NAME } from '../../packages/schema/src/constants.js';
/**
* GitHub Pages serves a project site at `/<repo>/`, not `/` (CLAUDE.md §8). Vite
* `base`, the manifest's `scope`/`start_url` and the service worker's scope all
* derive from this one value, so they cannot disagree. The e2e and offline
* suites serve the build under the same prefix.
*/
const BASE = process.env['ROSEA_BASE'] ?? '/Rosea/';
if (!BASE.startsWith('/') || !BASE.endsWith('/')) {
throw new Error(`ROSEA_BASE must start and end with '/', got '${BASE}'`);
}
/**
* The content-security policy. GitHub Pages cannot send headers, so it lives in
* a <meta> tag (CLAUDE.md §8). It is injected into the BUILT page only, because
* the dev server injects inline <style> for hot reload and `style-src 'self'`
* would blank it. E2E runs against the build, where the policy is real.
*
* `'self'` everywhere and nothing else: no CDN, no font host, no analytics
* (CLAUDE.md §4). `frame-ancestors` is ignored in a meta tag and is omitted
* rather than pretended.
*/
const CSP = [
"default-src 'self'",
"script-src 'self'",
"style-src 'self'",
"img-src 'self' data:",
"font-src 'self'",
"connect-src 'self'",
"manifest-src 'self'",
"worker-src 'self'",
"object-src 'none'",
"base-uri 'self'",
"form-action 'none'"
].join('; ');
function contentSecurityPolicy(): Plugin {
return {
name: 'rosea-csp',
apply: 'build',
transformIndexHtml: {
order: 'post',
handler: () => [
{ tag: 'meta', attrs: { 'http-equiv': 'Content-Security-Policy', content: CSP }, injectTo: 'head-prepend' }
]
}
};
}
// Nothing binds to anything but 127.0.0.1 (CLAUDE.md §5.7).
export default defineConfig({
base: BASE,
plugins: [
svelte(),
contentSecurityPolicy(),
VitePWA({
strategies: 'generateSW',
// 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',
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.
name: PRODUCT_NAME,
short_name: PRODUCT_SHORT_NAME,
description: 'A rose to tend, a fox to befriend, and the time we give to people.',
id: BASE,
start_url: BASE,
scope: BASE,
display: 'standalone',
orientation: 'portrait',
background_color: '#fbf6f1',
theme_color: '#b4485e',
icons: [{ src: 'icon.svg', sizes: 'any', type: 'image/svg+xml', purpose: 'any' }]
},
workbox: {
// The cache name never contains the build hash; Workbox invalidates
// per entry from the precache manifest's revisions.
cacheId: 'rosea',
globPatterns: ['**/*.{js,css,html,svg,webmanifest}'],
navigateFallback: 'index.html',
// No runtime caching: the app makes no request it was not asked to make.
runtimeCaching: [],
cleanupOutdatedCaches: true,
// The first worker controls the page that registered it, so a player who
// opens the link once and loses signal still has the app.
clientsClaim: true,
skipWaiting: false
},
devOptions: { enabled: false }
})
],
server: { host: '127.0.0.1', strictPort: true },
preview: { host: '127.0.0.1', strictPort: true },
build: { target: 'es2022', sourcemap: true }
});
+46
View File
@@ -0,0 +1,46 @@
{
"expect": "duplicate-id",
"why": "Two entries with one id: a message between players would be ambiguous.",
"entries": [
{
"id": "fixture-entry",
"text": {
"en": "Fixture text, not a real sentence."
},
"source": {
"work": "Fixture",
"author": null,
"tradition": "biblical",
"translation": "KJV",
"publicDomain": true,
"verifiedBy": "Fixture",
"verifiedAt": "2026-11-01"
},
"use": [
"sunset"
],
"tone": "gentle",
"promisesOutcome": false
},
{
"id": "fixture-entry",
"text": {
"en": "Another fixture text."
},
"source": {
"work": "Fixture",
"author": null,
"tradition": "biblical",
"translation": "KJV",
"publicDomain": true,
"verifiedBy": "Fixture",
"verifiedAt": "2026-11-01"
},
"use": [
"sunset"
],
"tone": "gentle",
"promisesOutcome": false
}
]
}
@@ -0,0 +1,24 @@
{
"expect": "forbidden-word",
"why": "A medical-claim word, inside a hyphenated compound.",
"entry": {
"id": "fixture-entry",
"text": {
"en": "Fixture text about self-healing."
},
"source": {
"work": "Fixture",
"author": null,
"tradition": "biblical",
"translation": "KJV",
"publicDomain": true,
"verifiedBy": "Fixture",
"verifiedAt": "2026-11-01"
},
"use": [
"sunset"
],
"tone": "gentle",
"promisesOutcome": false
}
}
@@ -0,0 +1,25 @@
{
"expect": "forbidden-word",
"why": "A name from The Little Prince, in the Czech text.",
"entry": {
"id": "fixture-entry",
"text": {
"en": "Fixture text, not a real sentence.",
"cs": "Fixture text, Malý princ."
},
"source": {
"work": "Fixture",
"author": null,
"tradition": "biblical",
"translation": "KJV",
"publicDomain": true,
"verifiedBy": "Fixture",
"verifiedAt": "2026-11-01"
},
"use": [
"sunset"
],
"tone": "gentle",
"promisesOutcome": false
}
}
@@ -0,0 +1,24 @@
{
"expect": "forbidden-word",
"why": "A name from Tolkien.",
"entry": {
"id": "fixture-entry",
"text": {
"en": "Fixture text naming Gandalf."
},
"source": {
"work": "Fixture",
"author": null,
"tradition": "biblical",
"translation": "KJV",
"publicDomain": true,
"verifiedBy": "Fixture",
"verifiedAt": "2026-11-01"
},
"use": [
"sunset"
],
"tone": "gentle",
"promisesOutcome": false
}
}
@@ -0,0 +1,24 @@
{
"expect": "forbidden-word",
"why": "Names the state the game never names, capitalised to prove case is ignored.",
"entry": {
"id": "fixture-entry",
"text": {
"en": "Fixture text for the Lonely."
},
"source": {
"work": "Fixture",
"author": null,
"tradition": "biblical",
"translation": "KJV",
"publicDomain": true,
"verifiedBy": "Fixture",
"verifiedAt": "2026-11-01"
},
"use": [
"sunset"
],
"tone": "gentle",
"promisesOutcome": false
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"expect": "schema",
"why": "An id is what travels between players; it can never be a sentence.",
"entry": {
"id": "meet me at the station",
"text": {
"en": "Fixture text, not a real sentence."
},
"source": {
"work": "Fixture",
"author": null,
"tradition": "biblical",
"translation": "KJV",
"publicDomain": true,
"verifiedBy": "Fixture",
"verifiedAt": "2026-11-01"
},
"use": [
"sunset"
],
"tone": "gentle",
"promisesOutcome": false
}
}
+15
View File
@@ -0,0 +1,15 @@
{
"expect": "no-source",
"why": "Every sentence names its source.",
"entry": {
"id": "fixture-entry",
"text": {
"en": "Fixture text, not a real sentence."
},
"use": [
"sunset"
],
"tone": "gentle",
"promisesOutcome": false
}
}
+23
View File
@@ -0,0 +1,23 @@
{
"expect": "no-tradition",
"why": "Missing tradition tag.",
"entry": {
"id": "fixture-entry",
"text": {
"en": "Fixture text, not a real sentence."
},
"source": {
"work": "Fixture",
"author": null,
"translation": "KJV",
"publicDomain": true,
"verifiedBy": "Fixture",
"verifiedAt": "2026-11-01"
},
"use": [
"sunset"
],
"tone": "gentle",
"promisesOutcome": false
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"expect": "not-public-domain",
"why": "A source not verified public domain, and not written by the author for Rosea.",
"entry": {
"id": "fixture-entry",
"text": {
"en": "Fixture text, not a real sentence."
},
"source": {
"work": "Fixture",
"author": null,
"tradition": "stoic",
"translation": null,
"publicDomain": false,
"verifiedBy": "Fixture",
"verifiedAt": "2026-11-01"
},
"use": [
"sunset"
],
"tone": "gentle",
"promisesOutcome": false
}
}
@@ -0,0 +1,24 @@
{
"expect": "promises-outcome",
"why": "Honestly marked as promising an outcome.",
"entry": {
"id": "fixture-entry",
"text": {
"en": "Fixture text, not a real sentence."
},
"source": {
"work": "Fixture",
"author": null,
"tradition": "biblical",
"translation": "KJV",
"publicDomain": true,
"verifiedBy": "Fixture",
"verifiedAt": "2026-11-01"
},
"use": [
"sunset"
],
"tone": "gentle",
"promisesOutcome": true
}
}
@@ -0,0 +1,24 @@
{
"expect": "promises-outcome",
"why": "Promises an outcome while marked promisesOutcome: false. Flagged for human review.",
"entry": {
"id": "fixture-entry",
"text": {
"en": "Fixture: everything will be fine."
},
"source": {
"work": "Fixture",
"author": null,
"tradition": "biblical",
"translation": "KJV",
"publicDomain": true,
"verifiedBy": "Fixture",
"verifiedAt": "2026-11-01"
},
"use": [
"sunset"
],
"tone": "gentle",
"promisesOutcome": false
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"expect": "too-long",
"why": "Over the length cap.",
"entry": {
"id": "fixture-entry",
"text": {
"en": "Fixture text that runs on far past the cap. Fixture text that runs on far past the cap. Fixture text that runs on far past the cap. Fixture text that runs on far past the cap. Fixture text that runs on far past the cap. Fixture text that runs on far past the cap."
},
"source": {
"work": "Fixture",
"author": null,
"tradition": "biblical",
"translation": "KJV",
"publicDomain": true,
"verifiedBy": "Fixture",
"verifiedAt": "2026-11-01"
},
"use": [
"sunset"
],
"tone": "gentle",
"promisesOutcome": false
}
}
@@ -0,0 +1,24 @@
{
"expect": "translation-under-copyright",
"why": "A modern Bible translation that is still under copyright.",
"entry": {
"id": "fixture-entry",
"text": {
"en": "Fixture text, not a real sentence."
},
"source": {
"work": "Fixture",
"author": null,
"tradition": "biblical",
"translation": "NIV",
"publicDomain": true,
"verifiedBy": "Fixture",
"verifiedAt": "2026-11-01"
},
"use": [
"sunset"
],
"tone": "gentle",
"promisesOutcome": false
}
}
+17
View File
@@ -0,0 +1,17 @@
# The hope library
One JSON file per source tradition (`biblical.json`, `stoic.json`, `rosea.json`, …).
Each file is an array of entries in the shape of
[`hope-sentence.schema.json`](../../packages/schema/schemas/hope-sentence.schema.json)
(CLAUDE.md §6.1).
**It is empty on purpose.** Every entry carries `verifiedBy` and `verifiedAt`, which
record that a person checked the source and its public-domain status. An agent
cannot make that check, so agents do not add entries. They may prepare a candidate
list elsewhere for the author to verify.
Run `pnpm validate:library` after any change. The validator also runs every file
in [`../fixtures/`](../fixtures/), and **fails if any fixture passes**.
Before the first release: at least 365 entries with `"use": ["sunset", …]`, so that
no sunset sentence repeats within a year.
+107
View File
@@ -0,0 +1,107 @@
# Rosea Domi — gameplay loop (decided 2026-10-28)
Rosea is still a game: every visit has real things to do. Art serves play, never replaces it. Core
purpose: training for real relationships — the habits learned tending the rose and the fox are the
habits Amicitia Domi needs with people. Amicitia is promoted openly (§5); its door opens when the fox
starts leading to real people.
## 1. The rose
- Actions with a touch of skill (feel, not a button): water (pour slowly until the leaves lift; too
much is as bad as too little), shade from wind at the right moment, pull overnight weeds, gather
fallen petals.
- She drifts, never breaks. Neglect makes her turn away and close a little (like a friend drifting to
an outer circle in Amicitia). Nothing earned disappears.
- Short visits only hold her; real time brings full bloom (mirrors Amicitia: check-ins freeze drift,
real time climbs). *Real time* means calendar days on which the care actually helped — never minutes
on screen. A long session is worth no more than a short one with the same care (decided 2026-11-01).
- The daily sentence comes from the rose, not from the sunset clock. She waits with a folded petal;
best given at sunset, but never missed. Coming back on nearby days gives a little more (e.g. an
earlier sentence remembered). A gap is never punished; no streak counter exists.
## 2. Numbers — measured and transparent
Her face and posture are the surface. One tap opens the real numbers: water, warmth, days of care,
trend. Everything measured is visible on request; nothing is hidden, nothing is shouted.
## 3. The fox
- Taming is touch and food: pet and brush the fox; feed it.
- The rose tells you what the fox wants today.
- Food = berries. Before there are friends, a wild berry bush beside the player's own rose ripens when
their care actually helped her, so the fox is never hungry without other players (decided
2026-11-01). Later, berries also come from tending forgotten roses of other players: friends'
(Phase 3) and, with the shared sky, strangers' (Phase 4) — an addition, never a requirement. A
forgotten rose stays theirs; tending it ripens the wild berry bush beside it. Anti-farming: one
harvest per bush per day, and only when the care actually helped (e.g. water when she truly needed
it).
- Your own rose's growth decides berry quality: wild strawberries → blueberries → raspberries →
blackberries → rose hips (the rare top treat; the rose's own fruit — ties rose and fox together).
- No trees, no apples, no hunting. Keep the screen minimal.
## 4. Teaching the player
- The game is taught in play: the rose and the fox speak in speech bubbles — "this is what you need to
do" — and remind the player when something is forgotten. Never assume the player read anything.
- Bubble text comes from the curated copy library (no free text, same rules as the hope library).
- A Letter from the Gardener holds the deeper why and can be re-read any time — it is never required
to understand how to play.
## 5. From roses to real people — the bridge to Amicitia (decided)
- Amicitia Domi is promoted openly as the door to real contact.
- Players are known only by the name they give their rose (a nickname; it may be their real name if
they choose). Rosea never knows real names.
- Lantern: once the path between two roses has grown into a road, either player may light a lantern
("I'd like to talk"). A one-sided lantern is invisible to the other. When both have lit one, the
game says so. The lantern travels only device to device and never passes through Lucerna, the
discovery service, despite the shared name (decided 2026-11-01).
- No personal data exchanged: the two apps swap anonymous keys device to device; each appears in
Amicitia under their rose's name.
- Before a match, curated sentences sent from the rose carry the Amicitia icon and "a taste of
Amicitia" — a visible taste, no real contact. (Rosea's own sync carries them, so the label never
says Amicitia sent them; decided 2026-11-01.) After a match, free conversation happens only in
Amicitia, never in Rosea.
- No doors, no closing. Rosea has no "close the door" action; paths only grow. A lit lantern stays
lit. Whether a connection lives or fades is Amicitia's concern, not Rosea's.
- Safety note (Claude's judgement): Rosea needs no block because it has no free text; Amicitia, where
free text begins, must still have a quiet safety block for harassment — not promoted.
## 6. The first days, and the journey as the second pillar (decided)
- Main risk (Claude's view, agreed): lonely players are the ones who quietly drop off. The beauty is
not the hard part; the first days must be rewarding enough that players stay long enough to be
changed by the game.
- Tending the rose and the fox alone is not yet enough gameplay. The second pillar is the journey:
visiting the lonely grown-ups' planets (king, vain man, drunkard, businessman, lamplighter,
geographer), each with its own real things to do — so there is always somewhere to go and something
new to discover from day one.
- Design rule: every early session ends with visible progress and a reason to return tomorrow (a new
place glimpsed, a berry kind closer, the fox a step nearer) — never with guilt.
## 7. The first minutes — and what Rosea is (decided, corrected 2026-10-28)
- Rosea Domi is its own game, by purpose: it exists to lead players into Amicitia Domi. It is not a
Little Prince game and never presents itself as one.
- From Saint-Exupéry it takes one idea: taming/binding someone makes you responsible for them, and
tending is how that responsibility is lived. The book is complementary inspiration, nothing more.
- The planets and lonely grown-ups stay as a quiet, familiar echo that makes the first minutes feel
recognisable — never named, never explained in-game as the book.
- No text from the book; no title, names or "you may know this book" prompts in the game, its name,
logo or marketing (the estate also holds trademarks on the title).
- A Letter from the Gardener is where everything is taught: the one sentence of inspiration, the river
of life, why the art looks as it does, and how the game leads to Amicitia.
- The Letter is clear about the difference: Rosea's philosophy and many of its small things (berries
and rose hips, the lanterns, the paths between roses, the real sunset, the shared sky, Amicitia)
were never in the book. The familiarity is a doorway; what lies behind it is Rosea's own.
## 8. How much comes from the book — stated precisely (decided)
- Taken as reference: the book's structure and the shape of the gameplay loop (rose, fox, the journey
through the lonely grown-ups' planets) — almost the whole book is echoed in the game.
- Skipped: the pilot in the desert. It does not translate into play and has no place in Rosea.
- Visual style: a direction only — never, ever copying the illustrations (see `art/STYLE.md`).
- Rosea's own philosophy: the paths, and the river of life with its whirlpools, drawn from Pascal and
Nietzsche and Mark's "vortex of continuum". These are explained in A Letter from the Gardener.
- Idea, open: a companion book in which these philosophical concepts are evaluated and written out at
length — the Letter is its short form.
+34
View File
@@ -0,0 +1,34 @@
<!--
A Letter from the Gardener: the author's own words, signed by the author.
Agents scaffold this file and never write in it (CLAUDE.md preamble and §1).
How it reaches the player: the app bundles this file at build time and shows
it at #letter, offline included. While this file holds nothing but comments,
the player sees no way to the page.
Markdown that works: # and ## headings, paragraphs, lists with - or *,
*emphasis*, and links to https:// pages or tel: numbers. Anything else is
shown as plain text. `pnpm lint:copy` checks every word outside comments,
as it does for all player-facing text.
The slots below are what GAMEPLAY.md and CLAUDE.md say the letter carries.
Keep, reorder or delete them as you like: comments never reach the player.
-->
<!-- Slot: the one sentence of inspiration (GAMEPLAY §7). -->
<!-- Slot: the river of life and its whirlpools (GAMEPLAY §8, CLAUDE.md §1). -->
<!-- Slot: why the art looks as it does (GAMEPLAY §7). -->
<!-- Slot: what in Rosea was never in the book: berries and rose hips, the
lanterns, the paths, the real sunset, the shared sky, Amicitia (GAMEPLAY §7). -->
<!-- Slot: every feature and every principle, taught (CLAUDE.md §1). -->
<!-- Slot: how the game leads to Amicitia Domi (GAMEPLAY §5, §7). -->
<!-- Slot: the quiet door to real help: verified support lines, as links
(CLAUDE.md §5.6 rule 5, G0.27). Not advice, no clinical claim. -->
<!-- Slot: the signature. -->
+180
View File
@@ -0,0 +1,180 @@
# Rosea Domi — phase plan
Working document. Lives at `docs/ROADMAP.md`. Companion to [`CLAUDE.md`](../CLAUDE.md) (the operating
manual) and [`ART.md`](ART.md) (the illustration pipeline).
---
## 0. The thing to decide before anything else
Rosea joins a queue that already holds NARTOR, Memoria, Ludus, Panda Domi and others. The failure mode
is not "Rosea is a bad idea" — it is many products at 70%.
So **Phases 0–1 are a spike, not a commitment**: the rose alone, the sunset, the library, offline, on
a real phone. At the end of Phase 1 there is one honest question — *did the real sunset become part of
my day?* — and a no is a legitimate answer that leaves a reusable sentence library and a sun module
behind.
Solo evenings-and-weekends pace. Durations are calendar estimates, not effort (assumption).
---
## 1. Naming
`Rosea` — Latin *rose-coloured*: the colour of the sky at sunset and of the rose. Working name.
In public always **Rosea Domi**; *Domi* never stands alone. Final name, trademark and domain checks are
open (§6). The help section is **A Letter from the Gardener**. The discovery service is **Lucerna**
(*lantern*).
---
## 2. What makes this different
Most games for lonely people either pretend to be a friend or count everything. Rosea does neither.
Its unit of value is **time given to someone else** — and its best moments send the player *away* from
the screen: to the real sunset, the real sky, real people.
Three consequences run through every phase:
1. **Growth comes from total care, never from a streak.** Nothing earned ever disappears.
2. **No free text, no counting of people.** Comfort is chosen from a curated library; friendship is
shown as a path, never a number.
3. **Every beauty has a real twin.** Sunset, sunrise and constellations are real, computed on device.
---
## 3. Architecture in one paragraph
A pnpm/Turbo monorepo in TypeScript. `packages/schema` holds the contracts and generates the types.
`packages/engine` is pure — growth, taming, the shared sky, and the sun maths, with time as a
parameter. `packages/content` holds the hope library and its validator. `packages/storage` is the only
module that opens IndexedDB, `packages/identity` the only one that holds keys, `packages/sync` the only
one that talks to friends (WebRTC, Phase 3). `apps/rosea` is a **Svelte 5 + Vite PWA** — web first,
from a link, no store — built by GitHub Actions and hosted on **GitHub Pages**, with a Gitea mirror. **Rust** is used where it earns its place: `services/lucerna`, the optional
anonymous discovery service (Axum + SQLite, Phase 4), and later a **Tauri 2** shell for Android and iOS
that gives local notifications without a server (Phase 6). All player state is an append-only event log;
every visible thing is a pure function of it.
---
## 4. Phases
Each phase has a gate: a question with an observable answer. Failing it means the next phase does not
start.
### Phase 0 — Foundations · ~1–2 weeks
- Repo, `.gitignore`, the 5 MB pre-commit hook, remotes, `CLAUDE.md`, this roadmap, `ART.md`.
- `packages/schema` with the hope-sentence and care-event contracts; the library validator with its
**negative fixtures**; `lint:copy` with the forbidden-words list.
- The first **60 sentences** of the library, each sourced and verified public domain.
- **Art**: `art/STYLE.md` drafted with Mark, `art/manifest.json` for Phase 1 assets, Claude's SVG
placeholders, and the **art preparation page** (`tools/art-prep`) working end to end on one asset.
- A slot for *A Letter from the Gardener* — the author writes it; agents only scaffold the page.
- **Decision recorded:** how the sunset invitation reaches the player on the web (see the notification
trap in `CLAUDE.md` §8). *Decided 2026-11-01:* on the web the invitation lives inside the app only —
no push server; real local notifications come with the Tauri shell (Phase 6).
**Gate:** `validate:library` passes on the 60 sentences and **fails on every negative fixture** with a
message naming the problem; one illustration has gone through the full pipeline — prompt, paste,
automatic checks, Claude's review, Mark's approval — into `art/final/`.
### Phase 1 — The rose alone · ~3–4 weeks · the spike
- One rose with her face: care with a touch of skill (water by feel, shade, weeds, petals), moods,
thorns, growth from **total** days of care, drift instead of loss, her numbers one tap away, and
speech-bubble teaching (`docs/GAMEPLAY.md` §1–2, §4).
- **The sun**: real local sunset and sunrise, on device; polar day/night handled. Location: the player is asked *"Where do you want your sunset?"* (a city, skippable); if skipped, it is guessed from the device time zone. **Never GPS.** A finer guess (country from IP or carrier) is an open idea — it costs a network call, so it must be weighed against local-first.
- **The in-game sunset** — move the chair, watch it again — as comfort and rehearsal; it tells the
player when the real one is tonight.
- **The day's sentence comes from the rose** (`docs/GAMEPLAY.md` §1): she waits with a folded petal;
sunset is the best moment to open it, but it is never lost and no streak exists.
- Installable PWA, fully offline, `navigator.storage.persist()`, export-my-rose.
- The offline Playwright suite.
**Out of scope:** planets, fox, friends, any server.
**Gate — the spike's real question.** Mark plays it daily for two weeks on his phone. Then: *did he go
and look at the real sunset without the game nagging him, and did the rose make him want to come back?*
Yes on both is a go. Yes only on the second means a pleasant toy, not Rosea. No on both is a clean stop.
### Phase 2 — The planets and the fox · ~4–6 weeks
- The planets of lonely grown-ups, one at a time, each designed in its own feature doc (they need not
all work the same way).
- The fox follows at a distance and comes closer through **how the player acts**; short taming at the
end of the journey. His berries come from the wild bush beside the player's own rose
(`docs/GAMEPLAY.md` §3), so nothing here needs another player.
- Collections: visitors who leave mementos while the player is away; the "sheep album" of the rose's
strange requests; rare visitors with hidden conditions (sunrise-only visitors among them).
- The *Geographer's book* — optional, private numbers about the player's own time.
**Gate:** a player who has never heard of the book finishes the first three planets and can say, in
their own words, what one of them felt like.
### Phase 3 — Friends · ~4–6 weeks
- Tending a friend's rose; their fox brings them a real trace (a petal in your colour) and, now and
then, a comfort line **you chose from the library**.
- Thanks as one optional gesture — their fox visits your rose.
- Paths between roses: footprints → trail → road.
- Friend-to-friend sync over WebRTC: care travels like letters and merges when devices meet.
- Invite by link; no account.
- Forgotten friends' roses ripen berries for the fox (`docs/GAMEPLAY.md` §3).
- The bridge to Amicitia: once a path is a road, lanterns, and the device-to-device key swap
(`docs/GAMEPLAY.md` §5).
**Gate:** five friends, two weeks, no reminders from Mark. *Do they come back on their own, and does
at least one of them describe a moment of being cared for?*
### Phase 4 — The shared sky · ~4–6 weeks · opt-in, separable
- `services/lucerna` in Rust: anonymous traces only (coarse cell, day bucket, gesture, auto-delete).
- The shared night sky made of **real constellations**; acts of care light it; a completed
constellation opens a new planet for everyone.
- The lamplighter's wave: lamps following the sunset around the globe.
- Keeping an absent stranger's rose alive with light — anonymous, no contact.
- The consent ladder toward strangers: traces → a light → foxes meet only if both agree.
**Gate:** deleting `services/lucerna` leaves Phases 1–3 fully working, with no dead controls and no
errors.
### Phase 5 — Real meetings and sharing · ~3–4 weeks
- One shared daily moment for everyone, and a spoiler-free image of your sky to share.
- Group meetings in public places only (in the spirit of community days); never one-to-one.
- The yearly moment on the anniversary of the player's first day.
**Gate:** a share image leaves the device containing nothing that identifies the player or anyone
else.
### Phase 6 — Stores and money · ongoing
- Tauri 2 shell for Android and iOS: local sunset notifications without a server.
- Monetisation — **not decided** (§6). Constraints already set: tending others is always free; no
ads, no subscription-only, no sale of data.
---
## 5. Risks, stated as risks
| Risk | Why it could kill this | What reduces it |
|:--|:--|:--|
| **It makes a lonely person feel worse** | Guilt, comparison or an unanswered gesture hurts most the people this is for. | The Soul section in every review; `soul.md`; no counts, no streaks, no neglect notifications. |
| **Cold start** | Phases 3–5 need people; Mark will have few players for months. | Phases 1–2 must stand alone; the fox's path to people comes after the game is already worth playing. |
| **Content volume** | 365 sourced sentences and many planets is a lot of careful work. | Start with 60 sentences; library grows by tradition; the validator keeps quality. |
| **Web notifications** | The sunset invitation may need a push server on the web, with a privacy cost. | Decided in Phase 0; the Tauri shell later removes the server. |
| **Copyright** | The book and Tolkien are protected; a too-close image or line is a legal problem. | Forbidden-names lint; likeness check in the art pipeline; ideas only. |
| **Medical-device scope** | Wellbeing claims can pull the app under medical rules. | Forbidden words in all copy, store text included. |
| **Safety around strangers** | Lonely people are the people a scammer looks for. | No free text, ever; consent ladder; group meetings in public only. |
| **One more product** | It competes for the same evenings as everything else in Domi. | The Phase 1 gate, treated as a real decision. |
---
## 6. Open questions
- **The sunrise mechanic** beyond sunrise-only visitors.
- **The visual style.** Decided with Mark in `art/STYLE.md` before any final art is generated.
- **The final name**, trademark and domain checks for Rosea Domi.
- **Money.** Only the constraints are fixed (Phase 6).
- **The Letter from the Gardener** — written by the author; its philosophy is his and is signed by him.
+66
View File
@@ -0,0 +1,66 @@
import { expect, test } from '@playwright/test';
import { PRODUCT_NAME } from '@rosea/schema';
import { en } from '@rosea/ui/copy';
import { startStaticServer } from './static-server.js';
/**
* The offline suite. CLAUDE.md §3 describes its full shape: tend the rose, walk
* a planet, watch a sunset, close the tab, reopen, assert everything survived.
* Phase 0 has no rose, so this proves the part everything else will stand on:
* the app opens with no server anywhere, under its real base path.
*
* The server is genuinely CLOSED, not emulated: `context.setOffline` acts before
* the service worker and would test the harness instead (imported from Ludus).
*/
test('the shell opens from the service worker with the server gone', async ({ browser }) => {
const server = await startStaticServer();
const context = await browser.newContext();
let serverOpen = true;
try {
const page = await context.newPage();
await page.goto(server.url);
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
// `clientsClaim` makes the FIRST worker control the page that registered it.
// Without it, a player who opens the link once and loses signal has nothing.
await page.waitForFunction(() => navigator.serviceWorker.controller !== null, null, { timeout: 20_000 });
await page.waitForFunction(
async () => {
for (const name of await caches.keys()) {
const cache = await caches.open(name);
if ((await cache.keys()).some((r) => r.url.includes('index.html'))) return true;
}
return false;
},
null,
{ timeout: 20_000 }
);
await server.close();
serverOpen = false;
// Proof the network is really gone, from outside the browser.
await expect(fetch(server.url)).rejects.toThrow();
// 1. Reload the open tab.
await page.reload();
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
await expect(page.getByText(en.shell.preparing)).toBeVisible();
// 2. Close the tab and open a fresh one: a cold start, the shape of a player
// coming back days later with no signal.
await page.close();
const again = await context.newPage();
await again.goto(server.url);
await expect(again.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
// 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);
} finally {
// A test run leaves the machine as it found it (CLAUDE.md §5.7).
await context.close();
if (serverOpen) await server.close();
}
});
+19
View File
@@ -0,0 +1,19 @@
import { defineConfig, devices } from '@playwright/test';
/**
* The main e2e suite. Runs against the BUILT bundle (`pnpm test:e2e` builds it
* first), served by a server each spec starts on a free port, so there is no
* port table to keep and no dev server to mistake for the product (CLAUDE.md §3).
*/
export default defineConfig({
testDir: '.',
testMatch: /shell\.spec\.ts/,
fullyParallel: false,
workers: 1,
retries: 0,
reporter: [['list']],
use: {
...devices['Desktop Chrome'],
trace: 'retain-on-failure'
}
});
+19
View File
@@ -0,0 +1,19 @@
import { defineConfig, devices } from '@playwright/test';
/**
* The offline suite — the product's central claim (CLAUDE.md §3). Separate
* from the main suite because it asks a different question: not "does it
* render" but "does it render with no server in the world".
*/
export default defineConfig({
testDir: '.',
testMatch: /offline\.spec\.ts/,
fullyParallel: false,
workers: 1,
retries: 0,
reporter: [['list']],
use: {
...devices['Desktop Chrome'],
trace: 'retain-on-failure'
}
});
+129
View File
@@ -0,0 +1,129 @@
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 { parseLetter } from '@rosea/ui/letter';
import { readFileSync } from 'node:fs';
import { BASE, startStaticServer, type StaticServer } from './static-server.js';
let server: StaticServer;
test.beforeAll(async () => {
server = await startStaticServer();
});
test.afterAll(async () => {
await server.close();
});
/** Opens the app and records every request and every CSP violation on the way. */
async function open(page: Page): Promise<{ requests: string[]; cspViolations: string[] }> {
const requests: string[] = [];
const cspViolations: string[] = [];
page.on('request', (r) => requests.push(r.url()));
page.on('console', (m) => {
if (m.type() === 'error' && /Content Security Policy/i.test(m.text())) cspViolations.push(m.text());
});
await page.goto(server.url);
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
// Let the worker register and precache, so its requests are counted too.
await page.waitForFunction(() => navigator.serviceWorker.ready.then(() => true), null, { timeout: 20_000 });
return { requests, cspViolations };
}
test('the built app renders its name and its one line, under the base path', async ({ page }) => {
await open(page);
await expect(page.getByText(en.shell.preparing)).toBeVisible();
await expect(page).toHaveTitle(PRODUCT_NAME);
});
test('nothing is requested from any other origin', async ({ page }) => {
const { requests } = await open(page);
expect(requests.length, 'the page must have made requests for this to mean anything').toBeGreaterThan(0);
expect(requests.filter((url) => !url.startsWith(server.origin + '/'))).toEqual([]);
});
test('nothing is written to cookies or Web Storage', async ({ page }) => {
await open(page);
const written = await page.evaluate(() => ({
cookie: document.cookie,
localStorage: localStorage.length,
sessionStorage: sessionStorage.length
}));
expect(written).toEqual({ cookie: '', localStorage: 0, sessionStorage: 0 });
expect(await page.context().cookies()).toEqual([]);
});
test('the built page carries the CSP and no inline script, and nothing violates it', async ({ page }) => {
const { cspViolations } = await open(page);
const html = await (await fetch(server.url)).text();
// Read from the DOM, not the raw HTML: Vite escapes the quotes as &#39;.
const csp = await page.locator('meta[http-equiv="Content-Security-Policy"]').getAttribute('content');
expect(csp, 'CSP meta tag in the built index.html').toBeTruthy();
expect(csp).toContain("default-src 'self'");
expect(csp).not.toContain('unsafe-inline');
expect(csp).not.toContain('unsafe-eval');
const inline = [...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/g)].filter(
([, attrs, body]) => !/\bsrc=/.test(attrs ?? '') && (body ?? '').trim() !== ''
);
expect(inline.map(([tag]) => tag)).toEqual([]);
expect(cspViolations).toEqual([]);
// The CSP is injected FIRST in <head>, ahead of <meta charset>, so it governs
// every script. The charset must still fall in the first 1024 bytes or the
// browser may guess the encoding; a CSP that grows can push it out.
const charsetAt = Buffer.from(html).indexOf('<meta charset');
expect(charsetAt, 'meta charset present').toBeGreaterThan(-1);
expect(charsetAt, 'meta charset within the first 1024 bytes').toBeLessThan(1024);
});
test('manifest scope, start_url and the service worker scope all equal the base path', async ({ page }) => {
await open(page);
const manifestHref = await page.locator('link[rel="manifest"]').getAttribute('href');
expect(manifestHref, 'manifest link').toBeTruthy();
const manifest = (await (await fetch(new URL(manifestHref!, server.url))).json()) as Record<string, unknown>;
expect(manifest['scope']).toBe(BASE);
expect(manifest['start_url']).toBe(BASE);
expect(manifest['name']).toBe(PRODUCT_NAME);
const swScope = await page.evaluate(async () => (await navigator.serviceWorker.ready).scope);
expect(swScope).toBe(server.url);
// The icon the manifest names must exist where the manifest says it is.
const icons = manifest['icons'] as { src: string }[];
for (const icon of icons) {
const res = await fetch(new URL(icon.src, new URL(manifestHref!, server.url)));
expect(res.status, icon.src).toBe(200);
}
});
test('the shell has no accessibility violations', async ({ page }) => {
await open(page);
const results = await new AxeBuilder({ page }).analyze();
expect(results.violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
});
// Tests whichever state docs/LETTER.md is in: empty now, the author's words later.
test('the Letter: no way to it while empty, and it opens from the garden once written', async ({ page }) => {
const written = parseLetter(readFileSync(new URL('../docs/LETTER.md', import.meta.url), 'utf8')).length > 0;
await open(page);
const link = page.getByRole('link', { name: en.letter.title });
if (!written) {
await expect(link).toHaveCount(0);
await page.goto(server.url + '#letter');
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
return;
}
await link.click();
await expect(page.getByRole('heading', { level: 1 })).toHaveText(en.letter.title);
const results = await new AxeBuilder({ page }).analyze();
expect(results.violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
await page.getByRole('link', { name: en.letter.back }).click();
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
});
+99
View File
@@ -0,0 +1,99 @@
import { createReadStream, statSync } from 'node:fs';
import { createServer, type Server } from 'node:http';
import { extname, join, normalize, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
/**
* A throwaway static server for the BUILT app, under the test's control.
*
* It serves `apps/rosea/dist` under the same base path GitHub Pages will use
* (`/Rosea/` unless ROSEA_BASE says otherwise), and 404s everything outside it.
* Serving at `/` would hide every base-path bug (CLAUDE.md §8).
*
* It exists for the offline suite too. Playwright's `context.setOffline` and
* `route().abort()` both act before the service worker is consulted, so they
* test the harness and not the cache (imported from Ludus). The only honest
* "no network" is no server: start one, let the worker precache, close it.
*
* Binds 127.0.0.1 on port 0, so the OS picks a free port (CLAUDE.md §5.7).
*/
export const BASE = process.env['ROSEA_BASE'] ?? '/Rosea/';
const DIST = fileURLToPath(new URL('../apps/rosea/dist', import.meta.url));
const MIME: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.webmanifest': 'application/manifest+json; charset=utf-8',
'.svg': 'image/svg+xml',
'.map': 'application/json; charset=utf-8'
};
export interface StaticServer {
/** The app's URL, base path included, e.g. http://127.0.0.1:53211/Rosea/ */
readonly url: string;
readonly origin: string;
readonly close: () => Promise<void>;
}
export async function startStaticServer(): Promise<StaticServer> {
try {
statSync(join(DIST, 'index.html'));
} catch (error) {
throw new Error(`No built app at ${DIST}. Run \`pnpm build\` first. (${String(error)})`);
}
const server: Server = createServer((req, res) => {
const path = decodeURIComponent((req.url ?? '/').split('?')[0] ?? '/');
if (!path.startsWith(BASE)) {
res.writeHead(404, { 'content-type': 'text/plain' });
res.end(`outside ${BASE}`);
return;
}
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) {
res.writeHead(403).end();
return;
}
let target = file;
try {
if (statSync(target).isDirectory()) target = join(target, 'index.html');
statSync(target);
} catch {
// Not on disk: an honest 404, which is what Pages would send.
res.writeHead(404, { 'content-type': 'text/plain' });
res.end('not found');
return;
}
res.writeHead(200, {
'content-type': MIME[extname(target)] ?? 'application/octet-stream',
// No HTTP cache, so whatever loads after the server is gone came from the
// service worker and not from the browser's own cache.
'cache-control': 'no-store'
});
createReadStream(target).pipe(res);
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (address === null || typeof address === 'string') throw new Error('static server did not bind a port');
const origin = `http://127.0.0.1:${address.port}`;
return {
origin,
url: `${origin}${BASE}`,
close: () =>
new Promise<void>((resolve) => {
server.closeAllConnections();
server.close(() => resolve());
})
};
}
+113
View File
@@ -0,0 +1,113 @@
/**
* The linter earns its place on the rules a compiler will not give: the ones
* about intent. Types belong to `tsc --strict` and `svelte-check`; formatting
* belongs to nobody.
*
* Two house rules live here:
* - CLAUDE.md §7 "never swallow an error": `no-empty` with no empty catch.
* - CLAUDE.md §7 "the engine is pure — enforced by a lint rule": the block
* scoped to packages/engine/src below. `packages/engine/test/purity-lint.test.ts`
* proves each ban fires, because a guard only ever seen not firing is untested.
*/
import js from '@eslint/js';
import ts from 'typescript-eslint';
import svelte from 'eslint-plugin-svelte';
import svelteParser from 'svelte-eslint-parser';
import globals from 'globals';
const CLOCK = 'Time is a parameter (`now: number`). A clock in the engine makes replaying the event log non-deterministic.';
const DICE = 'Randomness is a parameter (`rng: () => number`) so a replay gives byte-identical derived state.';
const IO = 'The engine performs no I/O. It returns values; packages/storage, packages/sync and the app do the rest.';
const ZONE = 'The time zone is a parameter. The app reads the device zone; the engine never does.';
const UTC_DAY = 'That is the UTC day. Days come from engine/src/time/localDay.ts and nowhere else (CLAUDE.md §7).';
export default [
{
ignores: [
'**/dist/**',
'**/node_modules/**',
'**/.turbo/**',
'**/generated/**',
'**/playwright-report/**',
'**/test-results/**'
]
},
js.configs.recommended,
...ts.configs.recommended,
...svelte.configs['flat/recommended'],
{
languageOptions: {
ecmaVersion: 2023,
sourceType: 'module',
globals: { ...globals.browser, ...globals.node }
},
rules: {
'no-empty': ['error', { allowEmptyCatch: false }],
eqeqeq: ['error', 'always', { null: 'ignore' }],
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_', caughtErrors: 'none' }
]
}
},
{
files: ['**/*.svelte', '**/*.svelte.ts', '**/*.svelte.js'],
languageOptions: {
parser: svelteParser,
parserOptions: { parser: ts.parser }
}
},
{
// THE ENGINE IS PURE. Scoped to src/: tests may read clocks to build fixtures.
files: ['packages/engine/src/**/*.ts'],
rules: {
'no-restricted-globals': [
'error',
{ name: 'fetch', message: IO },
{ name: 'XMLHttpRequest', message: IO },
{ name: 'WebSocket', message: IO },
{ name: 'localStorage', message: IO },
{ name: 'sessionStorage', message: IO },
{ name: 'indexedDB', message: IO },
{ name: 'document', message: IO },
{ name: 'window', message: IO },
{ name: 'globalThis', message: IO },
{ name: 'navigator', message: IO },
{ name: 'crypto', message: DICE },
{ name: 'performance', message: CLOCK },
{ name: 'setTimeout', message: CLOCK },
{ name: 'setInterval', message: CLOCK },
{ name: 'requestAnimationFrame', message: CLOCK },
{ name: 'process', message: IO }
],
'no-restricted-properties': [
'error',
{ object: 'Date', property: 'now', message: CLOCK },
{ object: 'Math', property: 'random', message: DICE },
{ property: 'resolvedOptions', message: ZONE }
],
'no-restricted-syntax': [
'error',
{ selector: "NewExpression[callee.name='Date'][arguments.length=0]", message: CLOCK },
{ selector: "CallExpression[callee.name='Date']", message: CLOCK },
{
selector: "CallExpression[callee.property.name='slice'][callee.object.callee.property.name='toISOString']",
message: UTC_DAY
},
{ selector: 'ImportDeclaration[source.value=/^node:/]', message: IO },
{ selector: 'ImportExpression', message: IO }
]
}
},
{
files: ['**/test/**', '**/*.test.ts', '**/*.spec.ts', 'scripts/**', 'e2e/**'],
rules: {
'@typescript-eslint/no-unused-expressions': 'off'
}
}
];
+40
View File
@@ -0,0 +1,40 @@
{
"name": "rosea",
"private": true,
"version": "0.1.0",
"type": "module",
"packageManager": "pnpm@9.12.3",
"engines": {
"node": ">=22"
},
"scripts": {
"prepare": "node scripts/install-hooks.mjs",
"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",
"validate:library": "tsx scripts/validate-library.ts",
"lint:copy": "tsx scripts/lint-copy.ts"
},
"devDependencies": {
"@axe-core/playwright": "4.13.0",
"@eslint/js": "9.39.5",
"@playwright/test": "1.62.1",
"@rosea/content": "workspace:*",
"@rosea/schema": "workspace:*",
"@rosea/ui": "workspace:*",
"@types/node": "22.20.1",
"eslint": "9.39.5",
"eslint-plugin-svelte": "3.23.0",
"globals": "16.5.0",
"svelte": "5.56.9",
"svelte-eslint-parser": "1.8.1",
"tsx": "4.23.12",
"turbo": "2.10.10",
"typescript": "5.9.3",
"typescript-eslint": "8.69.0",
"vitest": "3.2.7"
}
}
+25
View File
@@ -0,0 +1,25 @@
{
"name": "@rosea/content",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "The hope library and planets' scripts as data, the library validator, and the one list of forbidden words.",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts",
"./validate": "./src/validator.ts"
},
"scripts": {
"build": "tsc -p tsconfig.json",
"typecheck": "tsc -p tsconfig.json",
"test": "vitest run --reporter=verbose"
},
"dependencies": {
"@rosea/schema": "workspace:*"
},
"devDependencies": {
"typescript": "5.9.3",
"vitest": "3.2.7"
}
}
+46
View File
@@ -0,0 +1,46 @@
/**
* The core of `pnpm lint:copy` (CLAUDE.md §5.6, §7): what a player could read in
* a file, and what is wrong with it. The script walks files; this decides.
*/
import { findForbidden } from './forbidden.js';
export interface CopyProblem {
readonly line: number;
readonly message: string;
}
/**
* Removes comments, keeping line numbers. Comments are where the rules are
* explained, and a rule must be nameable in the file that enforces it.
* `//` after a `:` is a URL, not a comment.
*/
export function stripComments(source: string): string {
const blank = (m: string): string => m.replace(/[^\n]/g, ' ');
return source
.replace(/<!--[\s\S]*?-->/g, blank)
.replace(/\/\*[\s\S]*?\*\//g, blank)
.replace(/(?<![:\\])\/\/[^\n]*/g, blank);
}
// *Domi* is the ecosystem's word and never stands alone (CLAUDE.md preamble).
const DOMI_ALONE = /(?<!(?:Rosea|Panda|Amicitia)[\s\u00a0])\bDomi\b/g;
/** Problems in one file's player-visible text. */
export function lintCopy(source: string): CopyProblem[] {
const text = stripComments(source);
const lineOf = (index: number): number => text.slice(0, index).split('\n').length;
const problems: CopyProblem[] = [];
for (const hit of findForbidden(text)) {
problems.push({ line: lineOf(hit.index), message: `'${hit.term}' (${hit.category}): ${hit.why}` });
}
for (const m of text.matchAll(DOMI_ALONE)) {
problems.push({
line: lineOf(m.index),
message: "'Domi' on its own: the product is always Rosea Domi, and Domi never appears alone"
});
}
return problems.sort((a, b) => a.line - b.line);
}
+86
View File
@@ -0,0 +1,86 @@
/**
* The one list of words and names that never reach a player (CLAUDE.md §5.6
* rules 3 and 4). `lint:copy` and the library validator both read it, so the two
* can never disagree.
*
* Matching is whole-word and case-insensitive, with inflections spelled out.
* A stem match (`heal*`) would also catch *health*, and a rose can be healthy.
*
* `treat` is banned outright, including the fox's food: he eats *berries*.
* `patient` is banned too. Patience is the cure Gandalf's spirit offers, so the
* product may say *patience* and *patiently* but never *patient*.
*/
export type ForbiddenCategory = 'medical' | 'unnamed-state' | 'little-prince' | 'tolkien';
export interface ForbiddenTerm {
readonly term: string;
readonly category: ForbiddenCategory;
readonly why: string;
}
const MEDICAL =
'A medical claim pulls the product toward EU medical-device rules (CLAUDE.md §5.6 rule 3). Rosea comforts; it does not treat.';
const UNNAMED =
'The game never names the state for the player (CLAUDE.md §5.6 rule 4). It lets them feel seen instead.';
const PRINCE = 'Nothing from The Little Prince by name or quote: one idea is borrowed, never its text (CLAUDE.md §5.6 rule 3).';
const TOLKIEN = "Gandalf's spirit, never a name or a quote from Tolkien's works (CLAUDE.md §5.6 rule 3).";
const terms = (category: ForbiddenCategory, why: string, list: readonly string[]): ForbiddenTerm[] =>
list.map((term) => ({ term, category, why }));
export const FORBIDDEN: readonly ForbiddenTerm[] = [
...terms('medical', MEDICAL, [
'therapy', 'therapies', 'therapist', 'therapists', 'therapeutic', 'therapeutically',
'treat', 'treats', 'treated', 'treating', 'treatment', 'treatments',
'heal', 'heals', 'healed', 'healing', 'healer', 'healers',
'cure', 'cures', 'cured', 'curing', 'curative',
'diagnose', 'diagnoses', 'diagnosed', 'diagnosing', 'diagnosis', 'diagnostic',
'symptom', 'symptoms', 'symptomatic',
'patient', 'patients',
'disorder', 'disorders'
]),
...terms('unnamed-state', UNNAMED, ['lonely', 'lonelier', 'loneliest', 'loneliness']),
...terms('little-prince', PRINCE, [
'Little Prince', 'Petit Prince', 'Malý princ', 'Saint-Exupéry', 'Saint-Exupery', 'Exupéry', 'Exupery', 'B-612', 'B612'
]),
...terms('tolkien', TOLKIEN, [
'Tolkien', 'Gandalf', 'Mithrandir', 'Frodo', 'Bilbo', 'Samwise', 'Aragorn', 'Galadriel', 'Sauron',
// 'Middle-earth' also matches 'Middle earth': spaces and hyphens are interchangeable in a term.
'Mordor', 'Rivendell', 'Middle-earth', 'hobbit', 'hobbits', 'Lothlórien', 'Lothlorien'
])
];
export interface ForbiddenHit {
readonly term: string;
readonly category: ForbiddenCategory;
readonly why: string;
/** Index into the scanned text. */
readonly index: number;
}
const escape = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/[\s-]+/g, '[\\s\\u00a0-]+');
// Letters and digits on either side mean it is part of a longer word: *treaty*
// does not contain *treat*. Hyphens and apostrophes are boundaries, so
// *self-healing* is caught.
const PATTERNS = FORBIDDEN.map((entry) => ({
entry,
regex: new RegExp(`(?<![\\p{L}\\p{N}])${escape(entry.term)}(?![\\p{L}\\p{N}])`, 'giu')
}));
/**
* Every forbidden term in `text`, in order of appearance, once per place.
* `Middle-earth` and `Middle earth` both match either spelling, so a second hit
* at the same index is the same word and is dropped.
*/
export function findForbidden(text: string): ForbiddenHit[] {
const byIndex = new Map<number, ForbiddenHit>();
for (const { entry, regex } of PATTERNS) {
regex.lastIndex = 0;
for (let m = regex.exec(text); m !== null; m = regex.exec(text)) {
if (!byIndex.has(m.index)) byIndex.set(m.index, { ...entry, index: m.index });
}
}
return [...byIndex.values()].sort((a, b) => a.index - b.index);
}
+2
View File
@@ -0,0 +1,2 @@
export { lintCopy, stripComments, type CopyProblem } from './copy-lint.js';
export { FORBIDDEN, findForbidden, type ForbiddenCategory, type ForbiddenHit, type ForbiddenTerm } from './forbidden.js';
+148
View File
@@ -0,0 +1,148 @@
/**
* The hope-library validator (CLAUDE.md §5.5, §5.6 rule 2, §6.1).
*
* The schema says what shape an entry has. This says whether it may be shown
* to a person: sourced, public domain or the author's own, short enough to
* read at sunset, free of forbidden words, and not promising anything.
*
* Its negative fixtures in `content/fixtures/` ARE the validator: a rule here
* without a fixture proving it fires is a review blocker.
*/
import type { HopeSentence } from '@rosea/schema';
import { validateHopeSentence } from '@rosea/schema/validate';
import { findForbidden } from './forbidden.js';
export type Rule =
| 'schema'
| 'no-source'
| 'not-public-domain'
| 'translation-under-copyright'
| 'too-long'
| 'promises-outcome'
| 'forbidden-word'
| 'no-tradition'
| 'duplicate-id';
export interface Problem {
readonly id: string;
readonly rule: Rule;
readonly message: string;
}
/** Characters per language. A sentence opened at sunset is read on a phone, once. */
export const LENGTH_CAP = 240;
/**
* The tradition tag for a line the author wrote for Rosea. Those are not public
* domain, and need not be: the author owns them (CLAUDE.md §5.6 rule 2).
*/
export const AUTHOR_TRADITION = 'rosea';
/**
* Translations known to be in the public domain. Anything else is assumed to
* be under copyright until someone checks and adds it here, with the source of
* that check in the commit.
*/
export const PUBLIC_DOMAIN_TRANSLATIONS: ReadonlySet<string> = new Set([
'KJV', // King James Version, 1611/1769
'Bible kralická', // 1579–1613
'ASV', // American Standard Version, 1901
'Douay-Rheims', // 1582–1610, Challoner revision 1752
'YLT', // Young's Literal Translation, 1862
'WEB' // World English Bible, dedicated to the public domain
]);
/**
* Phrasings that promise an outcome. A heuristic, so a hit means "a human must
* read this", and the entry fails until one does. An honest `promisesOutcome:
* true` fails the same way.
*/
const OUTCOME_PHRASES: readonly RegExp[] = [
/\beverything will be\b/i,
/\b(it|you|things) will (all )?(be|get) (better|fine|okay|ok|alright|all right|well)\b/i,
/\byou will (find|never|always|soon)\b/i,
/\bi promise\b/i,
/\bguarantee/i
];
const idOf = (input: unknown): string =>
typeof input === 'object' && input !== null && typeof (input as { id?: unknown }).id === 'string'
? (input as { id: string }).id
: '(no id)';
/** Every reason `input` may not be shown to a player. Empty means it may. */
export function validateEntry(input: unknown): Problem[] {
const id = idOf(input);
const problem = (rule: Rule, message: string): Problem => ({ id, rule, message });
const problems: Problem[] = [];
const schema = validateHopeSentence(input);
if (!schema.ok) {
for (const error of schema.errors) {
if (/^\(root\) .*'source'/.test(error)) {
problems.push(problem('no-source', 'has no source: every sentence names where it comes from'));
} else if (/^\/source .*'tradition'|^\/source\/tradition /.test(error)) {
problems.push(problem('no-tradition', 'has no tradition tag: the library stays mixed, so each line says which one it is from'));
} else {
problems.push(problem('schema', error));
}
}
return problems;
}
const entry: HopeSentence = schema.value;
const { source } = entry;
if (!source.publicDomain && source.tradition !== AUTHOR_TRADITION) {
problems.push(
problem('not-public-domain', `source '${source.work}' is not verified public domain, and the author did not write it for Rosea`)
);
}
if (source.translation !== null && !PUBLIC_DOMAIN_TRANSLATIONS.has(source.translation)) {
problems.push(
problem(
'translation-under-copyright',
`translation '${source.translation}' is not on the public-domain list; a modern translation is usually still under copyright`
)
);
}
for (const [lang, text] of Object.entries(entry.text)) {
if (text === undefined) continue;
const length = [...text].length;
if (length > LENGTH_CAP) {
problems.push(problem('too-long', `${lang} text is ${length} characters, over the length cap of ${LENGTH_CAP}`));
}
for (const hit of findForbidden(text)) {
problems.push(problem('forbidden-word', `${lang} text contains '${hit.term}' (${hit.category}): ${hit.why}`));
}
const phrase = OUTCOME_PHRASES.find((p) => p.test(text));
if (phrase !== undefined) {
problems.push(problem('promises-outcome', `${lang} text may promise an outcome (${phrase.source}): needs human review`));
}
}
if (entry.promisesOutcome) {
problems.push(problem('promises-outcome', 'is marked promisesOutcome: comfort never promises what will happen'));
}
return problems;
}
/** Validates a whole library: every entry, plus ids unique across all of them. */
export function validateLibrary(entries: readonly unknown[]): Problem[] {
const problems = entries.flatMap(validateEntry);
const seen = new Set<string>();
for (const entry of entries) {
const id = idOf(entry);
if (seen.has(id)) {
problems.push({ id, rule: 'duplicate-id', message: `id '${id}' is used more than once; a message between players would be ambiguous` });
}
seen.add(id);
}
return problems;
}
+41
View File
@@ -0,0 +1,41 @@
import { describe, expect, it } from 'vitest';
import { lintCopy, stripComments } from '../src/copy-lint.js';
describe('lint:copy core', () => {
it('reports a forbidden word in a string, with its line', () => {
const problems = lintCopy("export const a = 'ok';\nexport const b = 'A gentle therapy';\n");
expect(problems).toHaveLength(1);
expect(problems[0]?.line).toBe(2);
expect(problems[0]?.message).toContain('therapy');
});
it('reports a forbidden word in Svelte markup', () => {
expect(lintCopy('<p>For the lonely.</p>')).toHaveLength(1);
});
it('ignores comments, where rules are explained', () => {
expect(lintCopy('// never say therapy\n/* nor lonely */\n<!-- nor Gandalf -->\nconst ok = 1;')).toEqual([]);
});
it('keeps line numbers when it strips a multi-line comment', () => {
const problems = lintCopy("/*\n\n*/\nconst s = 'cure';");
expect(problems[0]?.line).toBe(4);
});
it('does not mistake a URL for a comment', () => {
expect(stripComments("'https://example.invalid/cure'")).toContain('cure');
});
it("reports 'Domi' standing alone", () => {
expect(lintCopy("const title = 'Domi';")).toHaveLength(1);
expect(lintCopy("const title = 'Welcome to Domi';")).toHaveLength(1);
});
it("accepts 'Domi' after its first word", () => {
expect(lintCopy("'Rosea Domi', 'Panda Domi', 'Amicitia Domi'")).toEqual([]);
});
it('accepts clean shell copy', () => {
expect(lintCopy("preparing: 'The garden is being prepared.'")).toEqual([]);
});
});
+49
View File
@@ -0,0 +1,49 @@
import { describe, expect, it } from 'vitest';
import { FORBIDDEN, findForbidden } from '../src/forbidden.js';
const terms = (text: string): string[] => findForbidden(text).map((h) => h.term);
describe('forbidden words — what is caught', () => {
it('catches every listed term on its own', () => {
const missed = FORBIDDEN.filter(({ term }) => !terms(`before ${term} after`).includes(term)).map((t) => t.term);
expect(missed).toEqual([]);
});
it.each([
['A soft THERAPY for the soul', 'therapy'],
['self-healing petals', 'healing'],
["the rose's lonely planet", 'lonely'],
['Loneliness.', 'loneliness'],
['a treat for the fox', 'treat'],
['be patient with yourself', 'patient'],
['Middle-earth', 'Middle-earth'],
['Middle earth', 'Middle-earth'],
['Malý princ', 'Malý princ'],
['Saint-Exupéry wrote', 'Saint-Exupéry']
])('"%s" contains %s', (text, term) => {
expect(terms(text)).toContain(term);
});
it('reports hits in reading order', () => {
expect(terms('cure first, then therapy')).toEqual(['cure', 'therapy']);
});
it('reports one word once, though two spellings of it match', () => {
expect(terms('Middle earth')).toHaveLength(1);
expect(terms('Middle-earth and Middle earth')).toHaveLength(2);
});
});
describe('forbidden words — what is NOT caught', () => {
it.each([
'a treaty between two roses',
'a healthy rose',
'patience, and patiently waiting',
'the lamplighter on his planet',
'the king, the vain man, the businessman',
'a fox among the berries',
'Rosea Domi'
])('"%s" is clean', (text) => {
expect(terms(text)).toEqual([]);
});
});
+85
View File
@@ -0,0 +1,85 @@
import { readFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
import { LENGTH_CAP, validateEntry, validateLibrary, type Rule } from '../src/validator.js';
const fixturesDir = fileURLToPath(new URL('../../../content/fixtures', import.meta.url));
interface Fixture {
readonly expect: Rule;
readonly why: string;
readonly entry?: unknown;
readonly entries?: readonly unknown[];
}
const fixtures = readdirSync(fixturesDir)
.filter((f) => f.endsWith('.json'))
.sort()
.map((file) => ({ file, fixture: JSON.parse(readFileSync(join(fixturesDir, file), 'utf8')) as Fixture }));
const valid = {
id: 'valid-entry',
text: { en: 'Fixture text, not a real sentence.', cs: 'Testovací text.' },
source: {
work: 'Fixture',
author: null,
tradition: 'biblical',
translation: 'KJV',
publicDomain: true,
verifiedBy: 'Fixture',
verifiedAt: '2026-11-01'
},
use: ['sunset', 'comfort'],
tone: 'gentle',
promisesOutcome: false
};
describe('library validator — negative fixtures', () => {
it('finds the fixtures', () => {
// A glob matching nothing would pass every case below.
expect(fixtures.length).toBeGreaterThanOrEqual(13);
});
it.each(fixtures)('$file fails with its named rule', ({ fixture }) => {
const problems = fixture.entries !== undefined ? validateLibrary(fixture.entries) : validateEntry(fixture.entry);
expect(problems.map((p) => p.rule), fixture.why).toContain(fixture.expect);
for (const p of problems) expect(p.message.length, 'each problem says what is wrong').toBeGreaterThan(10);
});
it('every rule the validator has is proved by at least one fixture', () => {
const proved = new Set(fixtures.map(({ fixture }) => fixture.expect));
const RULES: readonly Rule[] = [
'schema',
'no-source',
'not-public-domain',
'translation-under-copyright',
'too-long',
'promises-outcome',
'forbidden-word',
'no-tradition',
'duplicate-id'
];
expect(RULES.filter((r) => !proved.has(r))).toEqual([]);
});
});
describe('library validator — what passes', () => {
it('accepts a sourced, public-domain, short, gentle entry', () => {
expect(validateEntry(valid)).toEqual([]);
});
it('accepts a line the author wrote for Rosea, though it is not public domain', () => {
const own = { ...valid, source: { ...valid.source, tradition: 'rosea', translation: null, publicDomain: false } };
expect(validateEntry(own)).toEqual([]);
});
it('accepts text exactly at the length cap, counting characters and not UTF-16 units', () => {
const atCap = { ...valid, text: { en: 'ř'.repeat(LENGTH_CAP) } };
expect(validateEntry(atCap)).toEqual([]);
});
it('accepts an empty library, and says nothing about it', () => {
expect(validateLibrary([])).toEqual([]);
});
});
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node"]
},
"include": ["src/**/*.ts", "test/**/*.ts"]
}
+26
View File
@@ -0,0 +1,26 @@
{
"name": "@rosea/engine",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "Pure. No I/O, no DOM, no Date.now(), no Math.random(). Time and randomness are parameters.",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts"
},
"scripts": {
"build": "tsc -p tsconfig.json",
"typecheck": "tsc -p tsconfig.json",
"test": "vitest run --reporter=verbose"
},
"dependencies": {
"@rosea/schema": "workspace:*"
},
"devDependencies": {
"eslint": "9.39.5",
"fast-check": "3.23.2",
"typescript": "5.9.3",
"vitest": "3.2.7"
}
}
+1
View File
@@ -0,0 +1 @@
export { isLocalDay, localDay, type LocalDay } from './time/localDay.js';
+67
View File
@@ -0,0 +1,67 @@
/**
* The ONLY place in the repository where a day is computed (CLAUDE.md §7).
*
* A day is always local to a named IANA time zone, and the zone is always a
* parameter. The engine never asks the device which zone it is in: the app
* passes the zone of the city the player chose, or the device's own zone as the
* fallback (CLAUDE.md §4 `profile`).
*
* Never `toISOString().slice(0, 10)`: that is the UTC day, and in Prague it
* records Monday-evening care as Tuesday's.
*/
/** A calendar day, `YYYY-MM-DD`, in some player's local time. */
export type LocalDay = string;
const LOCAL_DAY = /^\d{4}-\d{2}-\d{2}$/;
// Memoised per zone. Constructing a DateTimeFormat costs far more than using one.
// This is a cache of a pure function's machinery, not state: the output depends
// only on the arguments.
const formatters = new Map<string, Intl.DateTimeFormat>();
function formatterFor(timeZone: string): Intl.DateTimeFormat {
let formatter = formatters.get(timeZone);
if (formatter === undefined) {
// Throws RangeError for an unknown zone, which is the right failure: a
// mistyped zone silently falling back to UTC is the bug this module exists
// to prevent.
formatter = new Intl.DateTimeFormat('en-CA', {
timeZone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
calendar: 'iso8601',
numberingSystem: 'latn'
});
formatters.set(timeZone, formatter);
}
return formatter;
}
/** The local calendar day of `epochMs` in `timeZone`. */
export function localDay(epochMs: number, timeZone: string): LocalDay {
if (!Number.isFinite(epochMs)) {
throw new RangeError(`localDay: epochMs must be a finite number, got ${String(epochMs)}`);
}
const parts = formatterFor(timeZone).formatToParts(epochMs);
const part = (type: Intl.DateTimeFormatPartTypes): string => {
const value = parts.find((p) => p.type === type)?.value;
if (value === undefined) throw new RangeError(`localDay: no ${type} for ${epochMs} in ${timeZone}`);
return value;
};
const day = `${part('year')}-${part('month')}-${part('day')}`;
if (!LOCAL_DAY.test(day)) {
// Years before 1000 or after 9999 would not be four digits. No player tends
// a rose then; refusing is better than writing an ambiguous day to the log.
throw new RangeError(`localDay: ${epochMs} gives an unrepresentable day '${day}'`);
}
return day;
}
/** Whether `value` has the shape of a LocalDay. Does not check that the date exists. */
export function isLocalDay(value: string): value is LocalDay {
return LOCAL_DAY.test(value);
}
+88
View File
@@ -0,0 +1,88 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import { isLocalDay, localDay } from '../src/time/localDay.js';
const at = (iso: string): number => Date.parse(iso);
describe('localDay — golden cases', () => {
it.each([
// Prague, 2026 spring-forward day (29 March, 02:00 CET -> 03:00 CEST).
['2026-03-28T23:30:00Z', 'Europe/Prague', '2026-03-29'], // 00:30 CET, first half-hour of the short day
['2026-03-29T21:59:00Z', 'Europe/Prague', '2026-03-29'], // 23:59 CEST, last minute of it
['2026-03-29T22:00:00Z', 'Europe/Prague', '2026-03-30'],
// Prague, 2026 fall-back day (25 October, 03:00 CEST -> 02:00 CET), 25 hours long.
['2026-10-24T22:00:00Z', 'Europe/Prague', '2026-10-25'],
['2026-10-25T22:59:00Z', 'Europe/Prague', '2026-10-25'], // 23:59 CET
['2026-10-25T23:00:00Z', 'Europe/Prague', '2026-10-26'],
// Southern hemisphere: Sydney is ahead of UTC, so its morning is UTC's yesterday.
['2026-11-01T21:00:00Z', 'Australia/Sydney', '2026-11-02'],
// Reykjavík has no DST and sits on UTC: the one zone where UTC days are right.
['2026-06-21T23:59:00Z', 'Atlantic/Reykjavik', '2026-06-21'],
// The edges of the clock face.
['2026-01-01T10:00:00Z', 'Pacific/Kiritimati', '2026-01-02'], // UTC+14
['2026-01-01T10:00:00Z', 'Etc/GMT+12', '2025-12-31'] // UTC-12
])('%s in %s is %s', (iso, zone, expected) => {
expect(localDay(at(iso), zone)).toBe(expected);
});
it('Monday evening in Anchorage is Monday, though UTC already says Tuesday', () => {
// 2026-10-26 is a Monday. 20:00 AKDT = 04:00 UTC on Tuesday.
const mondayEvening = at('2026-10-27T04:00:00Z');
expect(localDay(mondayEvening, 'America/Anchorage')).toBe('2026-10-26');
expect(new Date(mondayEvening).toISOString().slice(0, 10)).toBe('2026-10-27'); // the trap, measured
});
it('just after midnight on Tuesday in Prague is Tuesday, though UTC still says Monday', () => {
const tuesdayNight = at('2026-10-26T23:30:00Z'); // 00:30 CET on Tuesday 27th
expect(localDay(tuesdayNight, 'Europe/Prague')).toBe('2026-10-27');
});
});
describe('localDay — refusals', () => {
it('throws on an unknown zone instead of falling back to UTC', () => {
expect(() => localDay(0, 'Europe/Atlantis')).toThrow(RangeError);
});
it('throws on a non-finite time', () => {
expect(() => localDay(Number.NaN, 'Europe/Prague')).toThrow(RangeError);
expect(() => localDay(Number.POSITIVE_INFINITY, 'Europe/Prague')).toThrow(RangeError);
});
});
describe('localDay — properties', () => {
const ZONES = [
'Europe/Prague',
'Atlantic/Reykjavik',
'Europe/Oslo', // Tromsø's zone
'America/Guayaquil', // Quito's zone
'Australia/Sydney',
'America/Anchorage',
'Pacific/Kiritimati',
'Etc/GMT+12'
] as const;
// 2000-01-01 .. 2100-01-01: every year a player could plausibly be in.
const instant = fc.integer({ min: Date.UTC(2000, 0, 1), max: Date.UTC(2100, 0, 1) });
const zone = fc.constantFrom(...ZONES);
const HOUR = 3_600_000;
it('always returns a well-formed day', () => {
fc.assert(fc.property(instant, zone, (t, z) => isLocalDay(localDay(t, z))));
});
it('never goes backwards in time, across DST changes included', () => {
fc.assert(
fc.property(instant, fc.integer({ min: 0, max: 72 * HOUR }), zone, (t, dt, z) => {
return localDay(t, z) <= localDay(t + dt, z);
})
);
});
it('always advances within 26 hours (no local day is longer than 25)', () => {
fc.assert(fc.property(instant, zone, (t, z) => localDay(t, z) < localDay(t + 26 * HOUR, z)));
});
it('is deterministic: the same arguments give the same day', () => {
fc.assert(fc.property(instant, zone, (t, z) => localDay(t, z) === localDay(t, z)));
});
});
+66
View File
@@ -0,0 +1,66 @@
/**
* Proves the engine-purity lint rule (eslint.config.mjs, CLAUDE.md §7) fires.
*
* A guard that has only ever been seen NOT firing has not been tested. Each
* banned construct is linted as if it lived in packages/engine/src, and must be
* reported. The same snippet placed outside the engine must not be, which proves
* the rule is scoped and not a global ban someone will turn off in anger.
*/
import { ESLint } from 'eslint';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
const repoRoot = fileURLToPath(new URL('../../..', import.meta.url));
const eslint = new ESLint({ cwd: repoRoot });
const ENGINE_FILE = 'packages/engine/src/__purity_probe__.ts';
const OUTSIDE_FILE = 'packages/ui/src/__purity_probe__.ts';
async function messages(code: string, filePath: string): Promise<string[]> {
const [result] = await eslint.lintText(code, { filePath });
if (result === undefined) throw new Error('ESLint returned no result');
return result.messages.map((m) => `${m.ruleId ?? 'fatal'}: ${m.message}`);
}
const IMPURE: readonly [what: string, code: string][] = [
['Date.now()', 'export const t = Date.now();'],
['new Date() with no argument', 'export const d = new Date();'],
['Date() called as a function', 'export const s = Date();'],
['Math.random()', 'export const r = Math.random();'],
['fetch()', "export const p = fetch('/x');"],
['localStorage', "export const v = localStorage.getItem('x');"],
['indexedDB', "export const o = indexedDB.open('x');"],
['document', 'export const b = document.body;'],
['window', 'export const w = window.innerWidth;'],
['navigator', 'export const l = navigator.language;'],
['crypto', 'export const c = crypto.randomUUID();'],
['setTimeout', 'setTimeout(() => 0, 1);'],
['performance.now()', 'export const n = performance.now();'],
['the device time zone', 'export const z = Intl.DateTimeFormat().resolvedOptions().timeZone;'],
['a UTC day', 'export const day = new Date(0).toISOString().slice(0, 10);'],
['a Node built-in', "import { readFileSync } from 'node:fs'; export const f = readFileSync;"]
];
describe('engine purity lint rule', () => {
it.each(IMPURE)('reports %s inside packages/engine/src', async (_what, code) => {
const found = await messages(code, ENGINE_FILE);
expect(found.filter((m) => m.startsWith('fatal')), 'snippet must parse').toEqual([]);
expect(found.some((m) => /^no-restricted-/.test(m)), found.join('\n')).toBe(true);
});
it.each(IMPURE)('does not report %s outside the engine', async (_what, code) => {
const found = await messages(code, OUTSIDE_FILE);
expect(found.filter((m) => /^no-restricted-/.test(m))).toEqual([]);
});
it('allows a Date built from an explicit instant', async () => {
expect(await messages('export const d = new Date(1761500000000);', ENGINE_FILE)).toEqual([]);
});
it('the real engine sources are clean', async () => {
const results = await eslint.lintFiles(['packages/engine/src/**/*.ts']);
expect(results.length, 'the glob must match engine sources').toBeGreaterThan(0);
const problems = results.flatMap((r) => r.messages.map((m) => `${r.filePath}:${m.line} ${m.message}`));
expect(problems).toEqual([]);
});
});
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node"]
},
"include": ["src/**/*.ts", "test/**/*.ts"]
}
+27
View File
@@ -0,0 +1,27 @@
{
"name": "@rosea/schema",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "THE source of truth: JSON Schemas for hope sentences, care events and traces; generated types; the validator. Imports nothing from this repository.",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts",
"./validate": "./src/validate.ts",
"./schemas/*": "./schemas/*"
},
"scripts": {
"build": "node scripts/generate-types.mjs && tsc -p tsconfig.json",
"typecheck": "tsc -p tsconfig.json",
"test": "vitest run --reporter=verbose"
},
"dependencies": {
"ajv": "8.20.0"
},
"devDependencies": {
"json-schema-to-typescript": "15.0.4",
"typescript": "5.9.3",
"vitest": "3.2.7"
}
}
@@ -0,0 +1,37 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://rosea.invalid/schema/care-event.json",
"title": "CareEvent",
"description": "One act of care, append-only and never edited (CLAUDE.md §6.2). The other event kinds arrive with docs/GAMEPLAY.md.",
"type": "object",
"additionalProperties": false,
"required": ["kind", "ts", "localDay", "from", "to", "act", "trace", "messageId", "clientVersion"],
"properties": {
"kind": { "const": "care" },
"ts": { "description": "Epoch milliseconds. Stays on the device; never part of a trace.", "type": "integer", "minimum": 0 },
"localDay": {
"description": "The player's local day, from engine/src/time/localDay.ts and nowhere else.",
"type": "string",
"pattern": "^\\d{4}-\\d{2}-\\d{2}$"
},
"from": { "$ref": "#/definitions/publicKey" },
"to": { "$ref": "#/definitions/publicKey" },
"act": { "type": "string", "enum": ["water", "shade", "weed", "petals"] },
"trace": { "type": "string", "pattern": "^petal:[a-z]+(-[a-z]+)*$" },
"messageId": {
"description": "A hope-library id or null. Never text: the pattern admits no space, so no sentence fits (CLAUDE.md §5.6 rule 1).",
"oneOf": [
{ "type": "string", "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$", "maxLength": 64 },
{ "type": "null" }
]
},
"clientVersion": { "type": "string", "pattern": "^\\d+\\.\\d+\\.\\d+$" }
},
"definitions": {
"publicKey": {
"description": "An opaque base64url public key. Its exact encoding is decided with packages/identity.",
"type": "string",
"pattern": "^[A-Za-z0-9_-]{32,128}$"
}
}
}
@@ -0,0 +1,52 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://rosea.invalid/schema/hope-sentence.json",
"title": "HopeSentence",
"description": "One entry of the curated hope library (CLAUDE.md §6.1). The only words one player can send another are ids of these.",
"type": "object",
"additionalProperties": false,
"required": ["id", "text", "source", "use", "tone", "promisesOutcome"],
"properties": {
"id": {
"description": "Stable, lowercase, hyphenated. A message between players carries only this.",
"type": "string",
"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$",
"maxLength": 64
},
"text": {
"type": "object",
"additionalProperties": false,
"required": ["en"],
"properties": {
"en": { "type": "string", "minLength": 1 },
"cs": { "type": "string", "minLength": 1 }
}
},
"source": {
"type": "object",
"additionalProperties": false,
"required": ["work", "author", "tradition", "translation", "publicDomain", "verifiedBy", "verifiedAt"],
"properties": {
"work": { "type": "string", "minLength": 1 },
"author": { "type": ["string", "null"] },
"tradition": {
"description": "A lowercase tag such as `biblical` or `stoic`. `rosea` marks a line the author wrote for this game.",
"type": "string",
"pattern": "^[a-z]+(-[a-z]+)*$"
},
"translation": { "type": ["string", "null"] },
"publicDomain": { "type": "boolean" },
"verifiedBy": { "type": "string", "minLength": 1 },
"verifiedAt": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$" }
}
},
"use": {
"type": "array",
"minItems": 1,
"uniqueItems": true,
"items": { "type": "string", "enum": ["sunset", "comfort", "thanks"] }
},
"tone": { "type": "string", "pattern": "^[a-z]+(-[a-z]+)*$" },
"promisesOutcome": { "type": "boolean" }
}
}
+20
View File
@@ -0,0 +1,20 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://rosea.invalid/schema/trace.json",
"title": "Trace",
"description": "An anonymous shared-sky trace, Phase 4, opt-in only (CLAUDE.md §6.3). No timestamp finer than a day, no precise location, no free text, no link to the friend graph.",
"type": "object",
"additionalProperties": false,
"required": ["traceId", "geocell", "dayBucket", "gesture", "sig"],
"properties": {
"traceId": { "description": "Random and rotating.", "type": "string", "pattern": "^[A-Za-z0-9_-]{16,64}$" },
"geocell": {
"description": "A coarse cell id, at most ~1 km (CLAUDE.md §4). Capped at 6 characters: a 6-character geohash is ~1.2 x 0.6 km, and every character more is ~5x finer, down to centimetres. The cell system and its density-adaptive size are decided in the Phase 4 feature doc.",
"type": "string",
"pattern": "^[a-z0-9]{3,6}$"
},
"dayBucket": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$" },
"gesture": { "type": "string", "enum": ["petal", "light"] },
"sig": { "type": "string", "pattern": "^[A-Za-z0-9_-]{16,256}$" }
}
}
@@ -0,0 +1,30 @@
// Generates TypeScript types from the JSON Schemas (CLAUDE.md §7: contract types
// are generated, never hand-written). Output is git-ignored; `build` runs first
// in every turbo task that needs it.
import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
import { basename, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { compile } from 'json-schema-to-typescript';
const root = fileURLToPath(new URL('..', import.meta.url));
const schemaDir = join(root, 'schemas');
const outDir = join(root, 'src', 'generated');
mkdirSync(outDir, { recursive: true });
const banner = '/* Generated by packages/schema/scripts/generate-types.mjs. Do not edit. */';
const names = [];
for (const file of readdirSync(schemaDir).filter((f) => f.endsWith('.schema.json')).sort()) {
const schema = JSON.parse(readFileSync(join(schemaDir, file), 'utf8'));
const name = basename(file, '.schema.json');
const ts = await compile(schema, schema.title, { bannerComment: banner, additionalProperties: false });
writeFileSync(join(outDir, `${name}.ts`), ts);
names.push(name);
}
writeFileSync(
join(outDir, 'index.ts'),
`${banner}\n${names.map((n) => `export type * from './${n}.js';`).join('\n')}\n`
);
console.log(`[schema] generated types for ${names.length} schemas: ${names.join(', ')}`);
+17
View File
@@ -0,0 +1,17 @@
/**
* The product's name, in one of the three places it may appear in source
* (CLAUDE.md preamble). The other two are `apps/rosea/index.html` and the web
* manifest, which `apps/rosea/vite.config.ts` builds from these constants.
*
* `Rosea` is a working name. Renaming must stay a one-commit operation: change
* these, `index.html`, the `@rosea/*` scope and nothing else.
*/
/** What the player reads. *Domi* never appears alone. */
export const PRODUCT_NAME = 'Rosea Domi';
/** The short form, for the home-screen label. */
export const PRODUCT_SHORT_NAME = 'Rosea';
/** The IndexedDB database name (CLAUDE.md §4). Changes together with the name. */
export const DATABASE_NAME = 'rosea';
+2
View File
@@ -0,0 +1,2 @@
export * from './constants.js';
export type * from './generated/index.js';
+41
View File
@@ -0,0 +1,41 @@
/**
* Schema validation, for Node only: scripts, tests and the library validator.
*
* It is a separate entry point (`@rosea/schema/validate`) on purpose. Ajv
* compiles validators with `new Function`, which the app's CSP forbids
* (`script-src 'self'`, no `'unsafe-eval'`). Importing it from the browser bundle
* would fail at runtime, not at build time. When the app needs to validate, it
* gets standalone pre-compiled validators (GAP_ANALYSIS G0.12).
*/
import { Ajv, type ErrorObject, type ValidateFunction } from 'ajv';
import careEvent from '../schemas/care-event.schema.json' with { type: 'json' };
import hopeSentence from '../schemas/hope-sentence.schema.json' with { type: 'json' };
import trace from '../schemas/trace.schema.json' with { type: 'json' };
import type { CareEvent, HopeSentence, Trace } from './generated/index.js';
export type SchemaResult<T> =
| { readonly ok: true; readonly value: T }
| { readonly ok: false; readonly errors: readonly string[] };
const ajv = new Ajv({ allErrors: true, strict: true });
function wrap<T>(validate: ValidateFunction): (input: unknown) => SchemaResult<T> {
return (input) =>
validate(input)
? { ok: true, value: input as T }
: { ok: false, errors: (validate.errors ?? []).map(describe) };
}
function describe(error: ErrorObject): string {
const where = error.instancePath === '' ? '(root)' : error.instancePath;
// Ajv already names a missing property in its message; an extra one it does not.
const extra =
error.keyword === 'additionalProperties'
? ` '${String((error.params as { additionalProperty?: unknown }).additionalProperty)}'`
: '';
return `${where} ${error.message ?? error.keyword}${extra}`;
}
export const validateHopeSentence = wrap<HopeSentence>(ajv.compile(hopeSentence));
export const validateCareEvent = wrap<CareEvent>(ajv.compile(careEvent));
export const validateTrace = wrap<Trace>(ajv.compile(trace));
+118
View File
@@ -0,0 +1,118 @@
import { describe, expect, it } from 'vitest';
import { validateCareEvent, validateHopeSentence, validateTrace } from '../src/validate.js';
const KEY_A = 'A'.repeat(43);
const KEY_B = 'b_-'.repeat(15);
const careEvent = {
kind: 'care',
ts: 1761500000000,
localDay: '2026-10-24',
from: KEY_A,
to: KEY_B,
act: 'water',
trace: 'petal:pale-pink',
messageId: 'ps-23-4',
clientVersion: '0.1.0'
};
const sentence = {
id: 'ps-23-4',
text: { en: 'Placeholder text for a schema test.' },
source: {
work: 'Psalms 23:4',
author: null,
tradition: 'biblical',
translation: 'KJV',
publicDomain: true,
verifiedBy: 'Test',
verifiedAt: '2026-11-01'
},
use: ['sunset'],
tone: 'gentle',
promisesOutcome: false
};
const trace = {
traceId: 'r'.repeat(22),
geocell: 'u2fkb',
dayBucket: '2026-10-24',
gesture: 'petal',
sig: 's'.repeat(64)
};
describe('hope sentence', () => {
it('accepts a complete entry', () => {
expect(validateHopeSentence(sentence)).toMatchObject({ ok: true });
});
it('rejects an entry with no source', () => {
const { source: _source, ...rest } = sentence;
const result = validateHopeSentence(rest);
expect(result.ok).toBe(false);
expect(!result.ok && result.errors.join('\n')).toContain("'source'");
});
it('rejects an id with a space, because an id is what travels between players', () => {
expect(validateHopeSentence({ ...sentence, id: 'you are seen' }).ok).toBe(false);
});
it('rejects an unknown use', () => {
expect(validateHopeSentence({ ...sentence, use: ['push-notification'] }).ok).toBe(false);
});
});
describe('care event', () => {
it('accepts every act the rose has', () => {
for (const act of ['water', 'shade', 'weed', 'petals']) {
expect(validateCareEvent({ ...careEvent, act }), act).toMatchObject({ ok: true });
}
});
it('rejects the acts §6.2 used to list by mistake', () => {
for (const act of ['wind', 'light']) {
expect(validateCareEvent({ ...careEvent, act }).ok, act).toBe(false);
}
});
it('accepts a null messageId', () => {
expect(validateCareEvent({ ...careEvent, messageId: null })).toMatchObject({ ok: true });
});
it('rejects free text in messageId (CLAUDE.md §5.6 rule 1)', () => {
expect(validateCareEvent({ ...careEvent, messageId: 'meet me at the station' }).ok).toBe(false);
});
it('rejects a missing localDay', () => {
const { localDay: _day, ...rest } = careEvent;
expect(validateCareEvent(rest).ok).toBe(false);
});
it('rejects any extra field, so nothing rides along unseen', () => {
expect(validateCareEvent({ ...careEvent, note: 'hello' }).ok).toBe(false);
});
});
describe('trace', () => {
it('accepts a day-bucketed trace', () => {
expect(validateTrace(trace)).toMatchObject({ ok: true });
});
it('rejects a day bucket finer than a day', () => {
expect(validateTrace({ ...trace, dayBucket: '2026-10-24T18:42' }).ok).toBe(false);
});
it('rejects a timestamp field', () => {
expect(validateTrace({ ...trace, ts: 1761500000000 }).ok).toBe(false);
});
it('rejects a precise coordinate in place of a cell', () => {
expect(validateTrace({ ...trace, geocell: '50.0755,14.4378' }).ok).toBe(false);
});
it('rejects a cell finer than ~1 km: a long geohash is a house, not a district', () => {
expect(validateTrace({ ...trace, geocell: 'u2fkbn' }).ok, '6 chars, ~1.2 km').toBe(true);
expect(validateTrace({ ...trace, geocell: 'u2fkbnx' }).ok, '7 chars, ~150 m').toBe(false);
expect(validateTrace({ ...trace, geocell: 'u2fkbnxq9vk2' }).ok, '12 chars, ~4 cm').toBe(false);
});
});
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node"]
},
"include": ["src/**/*.ts", "test/**/*.ts"]
}
+41
View File
@@ -0,0 +1,41 @@
{
"name": "@rosea/ui",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "Svelte components, tokens and copy/. Renders what the engine returns; decides nothing.",
"main": "./src/index.ts",
"types": "./src/index.ts",
"svelte": "./src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"svelte": "./src/index.ts",
"default": "./src/index.ts"
},
"./copy": "./src/copy/en.ts",
"./letter": "./src/letter/parse.ts",
"./tokens.css": "./src/tokens.css"
},
"scripts": {
"build": "svelte-check --threshold error --output human",
"typecheck": "svelte-check --threshold error --output human",
"test": "vitest run --reporter=verbose"
},
"dependencies": {
"@rosea/schema": "workspace:*"
},
"peerDependencies": {
"svelte": "^5.56.0"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "5.1.1",
"@testing-library/svelte": "5.4.2",
"jsdom": "25.0.1",
"svelte": "5.56.9",
"svelte-check": "4.7.6",
"typescript": "5.9.3",
"vite": "6.4.3",
"vitest": "3.2.7"
}
}
+90
View File
@@ -0,0 +1,90 @@
<script lang="ts">
import { PRODUCT_NAME } from '@rosea/schema';
import { en } from './copy/en.js';
import Letter from './letter/Letter.svelte';
import { parseLetter } from './letter/parse.js';
/** The author's Markdown from docs/LETTER.md. Empty means there is no way to the page. */
let { letter = '' }: { letter?: string } = $props();
const LETTER_HASH = '#letter';
// Any hash but the letter's is the garden. A bare '#' is not a valid link target.
const GARDEN_HASH = '#garden';
const blocks = $derived(parseLetter(letter));
let hash = $state(location.hash);
const view = $derived(hash === LETTER_HASH && blocks.length > 0 ? 'letter' : 'home');
let heading = $state<HTMLHeadingElement>();
// Focus follows the view only after the player moved, never on the first load.
let moved = false;
$effect(() => {
const onChange = (): void => {
moved = true;
hash = location.hash;
};
window.addEventListener('hashchange', onChange);
return () => window.removeEventListener('hashchange', onChange);
});
$effect(() => {
// Read `heading` first: an effect tracks only what it reads, and `moved` is not state.
const target = heading;
if (moved) target?.focus();
});
</script>
{#if view === 'letter'}
<main class="shell page">
<h1 bind:this={heading} tabindex="-1">{en.letter.title}</h1>
<Letter {blocks} />
<a href={GARDEN_HASH}>{en.letter.back}</a>
</main>
{:else}
<main class="shell">
<h1 bind:this={heading} tabindex="-1">{PRODUCT_NAME}</h1>
<p>{en.shell.preparing}</p>
{#if blocks.length > 0}
<a href={LETTER_HASH}>{en.letter.title}</a>
{/if}
</main>
{/if}
<style>
.shell {
min-height: 100dvh;
display: grid;
place-content: center;
gap: var(--space-2);
padding: var(--space-4);
text-align: center;
}
.page {
place-content: start center;
text-align: start;
}
h1 {
margin: 0;
font-family: var(--font-display);
font-weight: 400;
font-size: clamp(2rem, 8vw, 3.5rem);
letter-spacing: 0.02em;
color: var(--rose);
}
h1:focus {
outline: none;
}
p {
margin: 0;
color: var(--ink-soft);
}
a {
color: var(--rose);
}
</style>
+20
View File
@@ -0,0 +1,20 @@
/**
* Every string a player reads lives under copy/ (CLAUDE.md §7) and passes
* `pnpm lint:copy`. Plain English; Czech arrives as `cs.ts` with the same shape.
*
* The product name is not repeated here: it comes from @rosea/schema, one of the
* three places it may live.
*/
export const en = {
shell: {
/** The one line on the Phase 0 page. True, calm, and asks nothing. */
preparing: 'The garden is being prepared.'
},
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',
back: 'Back to the garden'
}
} as const;
export type Copy = typeof en;
+3
View File
@@ -0,0 +1,3 @@
export { default as Shell } from './Shell.svelte';
export { en, type Copy } from './copy/en.js';
export { parseLetter, type Inline, type LetterBlock } from './letter/parse.js';
+61
View File
@@ -0,0 +1,61 @@
<script lang="ts">
import type { Inline, LetterBlock } from './parse.js';
let { blocks }: { blocks: readonly LetterBlock[] } = $props();
</script>
{#snippet inlines(parts: readonly Inline[])}
{#each parts as part, i (i)}
{#if part.kind === 'link' && part.href.startsWith('tel:')}
<a href={part.href}>{part.text}</a>
{:else if part.kind === 'link'}
<a href={part.href} target="_blank" rel="noopener noreferrer">{part.text}</a>
{:else if part.kind === 'em'}
<em>{part.text}</em>
{:else}
{part.text}
{/if}
{/each}
{/snippet}
<article class="letter">
{#each blocks as block, i (i)}
{#if block.kind === 'heading' && block.level === 2}
<h2>{@render inlines(block.inlines)}</h2>
{:else if block.kind === 'heading'}
<h3>{@render inlines(block.inlines)}</h3>
{:else if block.kind === 'paragraph'}
<p>{@render inlines(block.inlines)}</p>
{:else}
<ul>
{#each block.items as item, j (j)}
<li>{@render inlines(item)}</li>
{/each}
</ul>
{/if}
{/each}
</article>
<style>
.letter {
max-width: 38rem;
line-height: 1.65;
}
h2,
h3 {
font-family: var(--font-display);
font-weight: 400;
color: var(--rose);
margin: var(--space-4) 0 var(--space-2);
}
p,
ul {
margin: 0 0 var(--space-3);
}
a {
color: var(--rose);
}
</style>
+85
View File
@@ -0,0 +1,85 @@
/**
* The Letter from the Gardener, from the author's Markdown to blocks the page
* renders (.agents/features/letter-slot.md L3, L4).
*
* A deliberately small subset: headings, paragraphs, lists, *emphasis* and
* links. Anything else is shown as the text it is. Nothing here builds HTML,
* so nothing in the file can inject markup or script.
*/
export type Inline =
| { readonly kind: 'text'; readonly text: string }
| { readonly kind: 'em'; readonly text: string }
| { readonly kind: 'link'; readonly text: string; readonly href: string };
export type LetterBlock =
| { readonly kind: 'heading'; readonly level: 2 | 3; readonly inlines: readonly Inline[] }
| { readonly kind: 'paragraph'; readonly inlines: readonly Inline[] }
| { readonly kind: 'list'; readonly items: readonly (readonly Inline[])[] };
/** The support door needs web and phone links, and nothing else does. */
const ALLOWED_HREF = /^(?:https:\/\/\S+|tel:\+?[\d ()-]+)$/i;
// A link target may hold one level of brackets, as in tel:+420 (2) 123.
const INLINE = /\[([^\]\n]+)\]\(((?:[^()\n]|\([^()\n]*\))+)\)|\*([^*\n]+)\*|_([^_\n]+)_/g;
function inlines(source: string): Inline[] {
const parts: Inline[] = [];
const text = (t: string): void => {
if (t === '') return;
const last = parts[parts.length - 1];
if (last?.kind === 'text') parts[parts.length - 1] = { kind: 'text', text: last.text + t };
else parts.push({ kind: 'text', text: t });
};
let at = 0;
for (const m of source.matchAll(INLINE)) {
text(source.slice(at, m.index));
const [, label, href, star, underscore] = m;
if (label !== undefined && href !== undefined) {
if (ALLOWED_HREF.test(href.trim())) parts.push({ kind: 'link', text: label, href: href.trim() });
else text(label);
} else {
parts.push({ kind: 'em', text: star ?? underscore ?? '' });
}
at = m.index + m[0].length;
}
text(source.slice(at));
return parts;
}
export function parseLetter(markdown: string): LetterBlock[] {
// Comments are the author's notes and the scaffold's slots, never the letter.
const lines = markdown.replace(/\r\n?/g, '\n').replace(/<!--[\s\S]*?-->/g, '').split('\n');
const blocks: LetterBlock[] = [];
let paragraph: string[] = [];
let list: Inline[][] = [];
const flush = (): void => {
if (paragraph.length > 0) blocks.push({ kind: 'paragraph', inlines: inlines(paragraph.join(' ')) });
if (list.length > 0) blocks.push({ kind: 'list', items: list });
paragraph = [];
list = [];
};
for (const raw of lines) {
const line = raw.trim();
const heading = /^(#{1,6})\s+(.+)$/.exec(line);
const item = /^[-*]\s+(.+)$/.exec(line);
if (line === '') {
flush();
} else if (heading !== null) {
flush();
blocks.push({ kind: 'heading', level: heading[1] === '#' ? 2 : 3, inlines: inlines(heading[2] ?? '') });
} else if (item !== null) {
if (paragraph.length > 0) flush();
list.push(inlines(item[1] ?? ''));
} else {
if (list.length > 0) flush();
paragraph.push(line);
}
}
flush();
return blocks;
}
+49
View File
@@ -0,0 +1,49 @@
/*
* Design tokens. Placeholders until docs/ART.md sets the palette: they exist so
* components reference tokens from the first commit, never raw colours.
* System fonts only: nothing is fetched from a CDN (CLAUDE.md §4).
*/
:root {
color-scheme: light dark;
--paper: #fbf6f1;
--ink: #2b2324;
--ink-soft: #6b5d5e;
--rose: #b4485e;
--font-body: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
--font-display: Georgia, 'Times New Roman', serif;
--space-1: 0.25rem;
--space-2: 0.5rem;
--space-3: 1rem;
--space-4: 1.5rem;
}
@media (prefers-color-scheme: dark) {
:root {
--paper: #1d1819;
--ink: #f1e8e6;
--ink-soft: #b8a9a8;
--rose: #e8899b;
}
}
html,
body {
margin: 0;
background: var(--paper);
color: var(--ink);
font-family: var(--font-body);
line-height: 1.5;
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
+1
View File
@@ -0,0 +1 @@
export default {};
+85
View File
@@ -0,0 +1,85 @@
import { PRODUCT_NAME } from '@rosea/schema';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/svelte';
import { afterEach, describe, expect, it } from 'vitest';
import Shell from '../src/Shell.svelte';
import { en } from '../src/copy/en.js';
afterEach(() => {
cleanup();
window.location.hash = '';
});
const LETTER = [
'# Why',
'',
'A line.',
'',
'[Read](https://example.org) or [call](tel:+420123) or [not](javascript:alert(1)).'
].join('\n');
const h1 = (): HTMLElement => screen.getByRole('heading', { level: 1 });
describe('Shell', () => {
it('names the product in the page heading, from the schema constant', () => {
render(Shell);
expect(screen.getByRole('heading', { level: 1 }).textContent).toBe(PRODUCT_NAME);
});
it('shows its one line from copy/, and no control to press', () => {
render(Shell);
expect(screen.getByText(en.shell.preparing)).toBeTruthy();
expect(screen.queryAllByRole('button')).toEqual([]);
expect(screen.queryAllByRole('link')).toEqual([]);
});
it('is a landmark, so a screen reader can find it', () => {
render(Shell);
expect(screen.getByRole('main')).toBeTruthy();
});
});
describe('Shell and the Letter', () => {
it('with an empty letter offers no way to it, and #letter shows the garden', () => {
window.location.hash = '#letter';
render(Shell, { letter: '<!-- Slot: the signature. -->\n' });
expect(h1().textContent).toBe(PRODUCT_NAME);
expect(screen.queryAllByRole('link')).toEqual([]);
});
it('with a letter, a link opens it, Back returns, and focus follows each heading', async () => {
render(Shell, { letter: LETTER });
expect(document.activeElement, 'nothing is focused on first load').toBe(document.body);
await fireEvent.click(screen.getByRole('link', { name: en.letter.title }));
await waitFor(() => expect(h1().textContent).toBe(en.letter.title));
await waitFor(() => expect(document.activeElement).toBe(h1()));
expect(screen.getByRole('heading', { level: 2 }).textContent).toBe('Why');
expect(screen.getByRole('main')).toBeTruthy();
await fireEvent.click(screen.getByRole('link', { name: en.letter.back }));
await waitFor(() => expect(h1().textContent).toBe(PRODUCT_NAME));
await waitFor(() => expect(document.activeElement).toBe(h1()));
});
it('opens straight at #letter, as from a bookmark', () => {
window.location.hash = '#letter';
render(Shell, { letter: LETTER });
expect(h1().textContent).toBe(en.letter.title);
});
it('renders https links in a new tab with no referrer, tel links in place, and nothing else as a link', () => {
window.location.hash = '#letter';
render(Shell, { letter: LETTER });
const read = screen.getByRole('link', { name: 'Read' });
expect(read.getAttribute('href')).toBe('https://example.org');
expect(read.getAttribute('target')).toBe('_blank');
expect(read.getAttribute('rel')).toBe('noopener noreferrer');
const call = screen.getByRole('link', { name: 'call' });
expect(call.getAttribute('href')).toBe('tel:+420123');
expect(call.getAttribute('target')).toBeNull();
expect(screen.queryByRole('link', { name: 'not' })).toBeNull();
expect(screen.getByText(/or not\./)).toBeTruthy();
});
});
+78
View File
@@ -0,0 +1,78 @@
import { describe, expect, it } from 'vitest';
import { parseLetter } from '../src/letter/parse.js';
describe('parseLetter', () => {
it('reads a file of only comments as an empty letter', () => {
const scaffold = '<!--\n A note for the author.\n-->\n\n<!-- Slot: one -->\n<!-- Slot: two -->\n';
expect(parseLetter(scaffold)).toEqual([]);
expect(parseLetter('')).toEqual([]);
expect(parseLetter(' \n\n \r\n')).toEqual([]);
});
it('reads headings, paragraphs joined across lines, and lists', () => {
const md = '# Why\n\nOne line\nand the next.\n\n## How\n- first\n* second\n\nLast.';
expect(parseLetter(md)).toEqual([
{ kind: 'heading', level: 2, inlines: [{ kind: 'text', text: 'Why' }] },
{ kind: 'paragraph', inlines: [{ kind: 'text', text: 'One line and the next.' }] },
{ kind: 'heading', level: 3, inlines: [{ kind: 'text', text: 'How' }] },
{ kind: 'list', items: [[{ kind: 'text', text: 'first' }], [{ kind: 'text', text: 'second' }]] },
{ kind: 'paragraph', inlines: [{ kind: 'text', text: 'Last.' }] }
]);
});
it('maps every heading below the first level to h3', () => {
expect(parseLetter('### Deep\n\n###### Deeper')).toEqual([
{ kind: 'heading', level: 3, inlines: [{ kind: 'text', text: 'Deep' }] },
{ kind: 'heading', level: 3, inlines: [{ kind: 'text', text: 'Deeper' }] }
]);
});
it('reads CRLF files the same as LF', () => {
expect(parseLetter('# A\r\n\r\nB\r\nC')).toEqual(parseLetter('# A\n\nB\nC'));
});
it('reads emphasis and links inside a paragraph', () => {
expect(parseLetter('A *quiet* door: [call](tel:+420 123 456) or [read](https://example.org/x).')).toEqual([
{
kind: 'paragraph',
inlines: [
{ kind: 'text', text: 'A ' },
{ kind: 'em', text: 'quiet' },
{ kind: 'text', text: ' door: ' },
{ kind: 'link', text: 'call', href: 'tel:+420 123 456' },
{ kind: 'text', text: ' or ' },
{ kind: 'link', text: 'read', href: 'https://example.org/x' },
{ kind: 'text', text: '.' }
]
}
]);
});
it('reads a phone number with brackets as one link', () => {
expect(parseLetter('[call](tel:+420 (2) 123)')).toEqual([
{ kind: 'paragraph', inlines: [{ kind: 'link', text: 'call', href: 'tel:+420 (2) 123' }] }
]);
});
it('keeps only the label of a link whose scheme is not https: or tel:', () => {
for (const href of ['javascript:alert(1)', 'data:text/html,x', 'http://example.org', '/relative', 'JavaScript:x']) {
expect(parseLetter(`[label](${href})`), href).toEqual([
{ kind: 'paragraph', inlines: [{ kind: 'text', text: 'label' }] }
]);
}
});
it('never produces markup: raw HTML stays text', () => {
const blocks = parseLetter('<script>alert(1)</script>\n\n<b onclick="x">bold</b>');
expect(blocks).toEqual([
{ kind: 'paragraph', inlines: [{ kind: 'text', text: '<script>alert(1)</script>' }] },
{ kind: 'paragraph', inlines: [{ kind: 'text', text: '<b onclick="x">bold</b>' }] }
]);
});
it('drops a comment in the middle of a paragraph and keeps the words around it', () => {
expect(parseLetter('Before <!-- a note --> after.')).toEqual([
{ kind: 'paragraph', inlines: [{ kind: 'text', text: 'Before after.' }] }
]);
});
});
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node", "svelte"]
},
"include": ["src/**/*.ts", "src/**/*.svelte", "test/**/*.ts", "vitest.config.ts"]
}
+12
View File
@@ -0,0 +1,12 @@
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { defineConfig } from 'vitest/config';
export default defineConfig({
plugins: [svelte()],
// Svelte resolves its client build only under the `browser` condition.
resolve: { conditions: ['browser'] },
test: {
environment: 'jsdom',
include: ['test/**/*.test.ts']
}
});
+6375
View File
File diff suppressed because it is too large Load Diff
+3
View File
@@ -0,0 +1,3 @@
packages:
- 'packages/*'
- 'apps/*'
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Rosea commit-msg hook — CLAUDE.md §5.2: NO AI ATTRIBUTION IN COMMITS, EVER.
# Imported from Ludus; NoAlgoTube needed a history rewrite to remove 18 of these.
msg_file="$1"
if grep -qiE '^(Co-Authored-By:.*(Claude|Anthropic|GPT|Copilot|Codex))|Claude-Session:|Generated with \[Claude Code\]|🤖 Generated with' "$msg_file"; then
echo "BLOCKED: commit message contains an AI attribution trailer." >&2
echo " Strip the trailer and commit again (CLAUDE.md §5.2)." >&2
exit 1
fi
exit 0
+35
View File
@@ -0,0 +1,35 @@
// Installs the git hooks CLAUDE.md §5.2 relies on. Runs from `pnpm install` via
// the root `prepare` script, so a fresh clone is guarded before its first commit.
// Adapted from Ludus, including its worktree fix: in a worktree `.git` is a FILE
// pointing at the real gitdir, and hooks resolve per worktree.
import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, statSync } from 'node:fs';
import { dirname, isAbsolute, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
const gitPath = join(root, '.git');
if (!existsSync(gitPath)) {
console.log('[hooks] no .git — skipping hook install.');
process.exit(0);
}
function resolveGitDir(path) {
if (statSync(path).isDirectory()) return path;
const target = /^gitdir:\s*(.+)$/.exec(readFileSync(path, 'utf8').trim())?.[1]?.trim();
if (target === undefined) {
console.log(`[hooks] ${path} is a file but not a gitdir pointer — skipping hook install.`);
process.exit(0);
}
return isAbsolute(target) ? target : resolve(root, target);
}
const hooksDir = join(resolveGitDir(gitPath), 'hooks');
mkdirSync(hooksDir, { recursive: true });
for (const hook of ['pre-commit', 'commit-msg']) {
const dest = join(hooksDir, hook);
copyFileSync(join(root, 'scripts', hook), dest);
chmodSync(dest, 0o755);
console.log(`[hooks] installed ${hook}`);
}
+56
View File
@@ -0,0 +1,56 @@
/**
* `pnpm lint:copy` — every file a player could read text from, checked for
* forbidden words and names (CLAUDE.md §5.6). The rules live in
* @rosea/content (copy-lint.ts, forbidden.ts) and are tested there.
*
* Not scanned: .agents/ and docs/, where the forbidden words may appear because
* they are being discussed (§5.6 rule 4). The one exception is docs/LETTER.md:
* it lives with the docs but a player reads it (letter-slot.md L6).
*/
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
import { extname, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
import { lintCopy } from '@rosea/content';
const root = fileURLToPath(new URL('..', import.meta.url));
/** Directories walked, and the extensions read in them. */
const TARGETS: readonly { dir: string; ext: readonly string[] }[] = [
{ dir: 'packages/ui/src', ext: ['.ts', '.svelte', '.css'] },
{ dir: 'apps/rosea/src', ext: ['.ts', '.svelte', '.css'] },
// Store listings, once they exist, live here and are player-facing too (§8).
{ dir: 'store', ext: ['.md', '.txt', '.json'] }
];
/** Single files: the page shell, the config that builds the web manifest, and the Letter. */
const FILES: readonly string[] = ['apps/rosea/index.html', 'apps/rosea/vite.config.ts', 'docs/LETTER.md'];
function walk(dir: string, ext: readonly string[]): string[] {
if (!existsSync(dir)) return [];
return readdirSync(dir).flatMap((entry) => {
const full = join(dir, entry);
if (statSync(full).isDirectory()) return walk(full, ext);
return ext.includes(extname(entry)) ? [full] : [];
});
}
const files = [
...TARGETS.flatMap(({ dir, ext }) => walk(join(root, dir), ext)),
...FILES.map((f) => join(root, f)).filter((f) => existsSync(f))
];
if (files.length === 0) {
console.error('lint:copy found no files to check. A check that reads nothing is not a pass.');
process.exit(1);
}
let problems = 0;
for (const file of files) {
for (const p of lintCopy(readFileSync(file, 'utf8'))) {
problems += 1;
console.error(`${relative(root, file).replace(/\\/g, '/')}:${p.line} ${p.message}`);
}
}
console.log(`lint:copy: ${files.length} files checked, ${problems} problem${problems === 1 ? '' : 's'}`);
process.exit(problems === 0 ? 0 : 1);
+28
View File
@@ -0,0 +1,28 @@
#!/bin/sh
# Rosea pre-commit hook — CLAUDE.md §5.2.
# .gitignore is a reminder; this is the enforcement. Rejects any staged blob over
# 5 MB, because a raw image export cannot be removed without a history rewrite.
LIMIT=5242880
report=$(mktemp)
trap 'rm -f "$report"' EXIT
git diff --cached --name-only --diff-filter=ACM -z |
while IFS= read -r -d '' path; do
blob=$(git rev-parse ":$path" 2>/dev/null) || continue
size=$(git cat-file -s "$blob" 2>/dev/null || echo 0)
if [ "$size" -gt "$LIMIT" ]; then
awk "BEGIN{printf \" %s — %.1f MB\n\", \"$path\", $size/1048576}" >> "$report"
fi
done
if [ -s "$report" ]; then
echo "BLOCKED: staged files exceed the 5 MB limit:" >&2
cat "$report" >&2
echo "" >&2
echo "Build output and raw image exports are never committed (CLAUDE.md §5.2)." >&2
echo "Final art goes in art/final/ as optimised WebP/AVIF." >&2
exit 1
fi
exit 0
+79
View File
@@ -0,0 +1,79 @@
/**
* `pnpm validate:library` — every hope sentence in content/library/, and every
* negative fixture in content/fixtures/ (CLAUDE.md §5.5).
*
* Passes when the library has no problems AND every fixture fails with the rule
* it names. A fixture that passes means a rule has stopped firing: that fails
* the run, the same as a bad sentence.
*/
import { readFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { validateEntry, validateLibrary, type Rule } from '@rosea/content/validate';
const root = fileURLToPath(new URL('..', import.meta.url));
const libraryDir = join(root, 'content', 'library');
const fixturesDir = join(root, 'content', 'fixtures');
const jsonIn = (dir: string): string[] =>
readdirSync(dir)
.filter((f) => f.endsWith('.json'))
.sort();
let failed = false;
// ── the library ────────────────────────────────────────────────────────────
const entries: unknown[] = [];
for (const file of jsonIn(libraryDir)) {
const data: unknown = JSON.parse(readFileSync(join(libraryDir, file), 'utf8'));
if (!Array.isArray(data)) {
console.error(`content/library/${file}: must be an array of entries`);
failed = true;
continue;
}
entries.push(...data);
}
for (const p of validateLibrary(entries)) {
console.error(`library ${p.id} [${p.rule}] ${p.message}`);
failed = true;
}
const sunset = entries.filter(
(e) => typeof e === 'object' && e !== null && Array.isArray((e as { use?: unknown }).use) && (e as { use: unknown[] }).use.includes('sunset')
).length;
console.log(
`library: ${entries.length} entr${entries.length === 1 ? 'y' : 'ies'} in ${jsonIn(libraryDir).length} files, ${sunset} sunset (release needs 365)`
);
// ── the fixtures: each must FAIL, with its named rule ───────────────────────
interface Fixture {
expect: Rule;
entry?: unknown;
entries?: unknown[];
}
const fixtureFiles = jsonIn(fixturesDir);
let fixtureOk = 0;
for (const file of fixtureFiles) {
const fixture = JSON.parse(readFileSync(join(fixturesDir, file), 'utf8')) as Fixture;
const problems = fixture.entries !== undefined ? validateLibrary(fixture.entries) : validateEntry(fixture.entry);
if (problems.some((p) => p.rule === fixture.expect)) {
fixtureOk += 1;
} else {
console.error(
`fixture ${file} expected [${fixture.expect}], got ${problems.length === 0 ? 'a PASS' : problems.map((p) => `[${p.rule}]`).join(' ')}`
);
failed = true;
}
}
console.log(`fixtures: ${fixtureOk} of ${fixtureFiles.length} rejected as expected`);
if (fixtureFiles.length === 0) {
console.error('fixtures: none found. The negative fixtures ARE the validator (CLAUDE.md §5.5).');
failed = true;
}
process.exit(failed ? 1 : 0);
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noImplicitOverride": true,
"noFallthroughCasesInSwitch": true,
"verbatimModuleSyntax": true,
"isolatedModules": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"noEmit": true
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"//": "Typechecks the repository's own tools: e2e specs and scripts. Packages typecheck themselves through turbo.",
"extends": "./tsconfig.base.json",
"compilerOptions": {
"types": ["node"]
},
"include": ["e2e/**/*.ts", "scripts/**/*.ts"]
}
+31
View File
@@ -0,0 +1,31 @@
{
"$schema": "https://turbo.build/schema.json",
"ui": "stream",
// docs/LETTER.md is bundled into the app (letter-slot.md L1). Without it here a
// changed letter replays the cached build and never reaches the player.
"globalDependencies": ["content/**", "docs/LETTER.md"],
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**", "src/generated/**"]
},
// Not cacheable. A test task's only output is its log, and a replayed log
// is someone else's assertion about a tree you cannot see. Ludus measured
// a cached `51 passed` against 50 in the real tree (CLAUDE.md §3 trap).
"test": {
"dependsOn": ["^build"],
"outputs": [],
"cache": false
},
"typecheck": {
"dependsOn": ["^build", "build"],
"outputs": [],
"cache": false
},
"dev": {
"dependsOn": ["^build"],
"cache": false,
"persistent": true
}
}
}