[ui] DaySentence: Merge the rose's folded petal and the sentence candidates

This commit is contained in:
2026-11-02 09:04:13 +01:00
53 changed files with 3591 additions and 71 deletions
+1
View File
@@ -8,6 +8,7 @@ One row per feature, with its analysis document (CLAUDE.md §5.1). Gaps live in
| Workspace, contracts, gates, PWA shell | 0 | Merged to `main` 2026-11-01 (`d11d242`); built, not deployed. Phase 0 gate still open | [phase0-workspace.md](features/phase0-workspace.md) | [feature-phase0-workspace.md](reviews/feature-phase0-workspace.md) | | 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) | | Roadmap and gameplay docs, read against the code | 0 | Merged 2026-11-01; Q1–Q7 answered by the author | — | [docs-roadmap-gameplay.md](reviews/docs-roadmap-gameplay.md) |
| The Letter slot: page at `#letter`, empty `docs/LETTER.md` | 0 | Merged to `main`; built, not deployed. Invisible until the author writes | [letter-slot.md](features/letter-slot.md) | [feature-letter-slot.md](reviews/feature-letter-slot.md) | | The Letter slot: page at `#letter`, empty `docs/LETTER.md` | 0 | Merged to `main`; built, not deployed. Invisible until the author writes | [letter-slot.md](features/letter-slot.md) | [feature-letter-slot.md](reviews/feature-letter-slot.md) |
| The day's sentence: her folded petal, one a day, never lost, best at sunset; candidates and `library:verify` | 1 | Merged to `main`; built, not deployed. Invisible until the author verifies sentences | [day-sentence.md](features/day-sentence.md) | [feature-day-sentence.md](reviews/feature-day-sentence.md) |
| The in-game sunset: move the chair, half a minute of silence, then the real sunset's time | 1 | Merged to `main`; built, not deployed | [chair-sunset.md](features/chair-sunset.md) | [feature-chair-sunset.md](reviews/feature-chair-sunset.md) | | The in-game sunset: move the chair, half a minute of silence, then the real sunset's time | 1 | Merged to `main`; built, not deployed | [chair-sunset.md](features/chair-sunset.md) | [feature-chair-sunset.md](reviews/feature-chair-sunset.md) |
| A calm refresh: a waiting new version is offered in one line, never swapped in by itself | 0 | Merged to `main`; built, not deployed | [calm-refresh.md](features/calm-refresh.md) | [feature-calm-refresh.md](reviews/feature-calm-refresh.md) | | A calm refresh: a waiting new version is offered in one line, never swapped in by itself | 0 | Merged to `main`; built, not deployed | [calm-refresh.md](features/calm-refresh.md) | [feature-calm-refresh.md](reviews/feature-calm-refresh.md) |
| The CPU guard: full runs wait for, then refuse, a busy machine | 0 | Merged to `main` | — | [fix-cpu-guard.md](reviews/fix-cpu-guard.md) | | The CPU guard: full runs wait for, then refuse, a busy machine | 0 | Merged to `main` | — | [fix-cpu-guard.md](reviews/fix-cpu-guard.md) |
+3 -3
View File
@@ -28,13 +28,13 @@ board exist, and the first real picture is the author's to make.
| ~~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.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)~~ | Closed 2026-11-02 on `feature/calm-refresh`: the app registers the worker and shows *A new version of the garden is ready.* with *Refresh*. e2e publishes a real second version: offered, not swapped, then taken over on Refresh; 3 of 3 put-back bugs caught. | | ~~G0.10~~ | ~~No calm *refresh* control for a waiting service worker (CLAUDE.md §8, stale SW)~~ | Closed 2026-11-02 on `feature/calm-refresh`: the app registers the worker and shows *A new version of the garden is ready.* with *Refresh*. e2e publishes a real second version: offered, not swapped, then taken over on Refresh; 3 of 3 put-back bugs caught. |
| ~~G0.11~~ | ~~IndexedDB eviction: no `navigator.storage.persist()`, no export-my-rose (§8)~~ | Closed 2026-11-02 on `feature/keep-her-safe`: *Keep her safe* asks the browser (and an installed app asks by itself), saves her to a file without the town or the private key, and brings her back additively on any device. e2e: saved on one browser profile, restored on a fresh one, survives a reload. Not seen in Firefox or Safari. | | ~~G0.11~~ | ~~IndexedDB eviction: no `navigator.storage.persist()`, no export-my-rose (§8)~~ | Closed 2026-11-02 on `feature/keep-her-safe`: *Keep her safe* asks the browser (and an installed app asks by itself), saves her to a file without the town or the private key, and brings her back additively on any device. e2e: saved on one browser profile, restored on a fresh one, survives a reload. Not seen in Firefox or Safari. |
| G0.12 | The app cannot validate content in the browser | Open. Ajv compiles with `new Function`, which the CSP forbids. Needs standalone pre-compiled validators before the app reads the library. | | G0.12 | The app cannot validate content in the browser | Narrowed 2026-11-02 (day-sentence.md P5): the library is bundled at build time, after `validate:library` passes, so the app never validates it. Reopens only if content is ever fetched at runtime; then it needs standalone pre-compiled validators (Ajv compiles with `new Function`, which the CSP forbids). |
| G0.13 | No GitHub remote, no Pages deploy workflow, no mirror check (§5.2) | Open. Only the Gitea remote exists. | | 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.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: `sync`, `services/lucerna` | Open by design (D1). Each arrives with its first feature. `tools/art-prep` arrived with the art board; `storage` with the sunset place and the rose (`profile`, `events`, `keys`); `identity` with the rose (a keypair, nothing signed yet). | | G0.15 | Deferred packages: `sync`, `services/lucerna` | Open by design (D1). Each arrives with its first feature. `tools/art-prep` arrived with the art board; `storage` with the sunset place and the rose (`profile`, `events`, `keys`); `identity` with the rose (a keypair, nothing signed yet). |
| G0.16 | The outcome-phrase heuristic has no reviewed override | Open. A real sentence that trips it (a false positive) cannot enter the library. Design: a `reviewedBy` field on the entry, set only by a person. | | G0.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.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.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). Since 2026-11-02 candidates wait in `content/candidates/`, each with where to read it; the author verifies with `pnpm library:verify <id…> --by <name>` (day-sentence.md P8). |
| 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.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.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.21 | No PNG icons | Open (predicted trap). iOS ignores SVG for `apple-touch-icon`. Comes through the art pipeline. |
@@ -56,7 +56,7 @@ sentences). Nothing in Phase 1 is visible to the player yet.
| ~~G1.1~~ | ~~No module computes the sun (CLAUDE.md §7); polar and DST traps only predicted~~ | Closed 2026-11-01 on `feature/sun`. `engine/src/sun/sun.ts`: 26 published days in 6 cities within 2 min, polar day and night at Tromsø, 50 tests, 5 of 5 put-back bugs caught. Both traps measured (CLAUDE.md §8). | | ~~G1.1~~ | ~~No module computes the sun (CLAUDE.md §7); polar and DST traps only predicted~~ | Closed 2026-11-01 on `feature/sun`. `engine/src/sun/sun.ts`: 26 published days in 6 cities within 2 min, polar day and night at Tromsø, 50 tests, 5 of 5 put-back bugs caught. Both traps measured (CLAUDE.md §8). |
| ~~G1.2~~ | ~~The player cannot choose a city; no time-zone guess; no sunset time on screen~~ | Closed 2026-11-02 on `feature/sunset-place`. 7,342 public-domain towns searched on the device, a guess for every zone a browser reports, the town kept in IndexedDB, tonight's sunset in the garden. 299 unit, 10 e2e, offline choosing and changing a town; 6 of 6 put-back bugs caught. | | ~~G1.2~~ | ~~The player cannot choose a city; no time-zone guess; no sunset time on screen~~ | Closed 2026-11-02 on `feature/sunset-place`. 7,342 public-domain towns searched on the device, a guess for every zone a browser reports, the town kept in IndexedDB, tonight's sunset in the garden. 299 unit, 10 e2e, offline choosing and changing a town; 6 of 6 put-back bugs caught. |
| ~~G1.4~~ | ~~No rose~~ | Closed 2026-11-02 on `feature/rose-care`: care with a touch of skill (water by holding, shade, weeds, petals), growth from days of care, drift, moods, her numbers; the care log in IndexedDB, replayed by the engine. Tuning R2/R4/R5/R6 is the author's. 7 of 7 put-back bugs caught after two test holes were closed. | | ~~G1.4~~ | ~~No rose~~ | Closed 2026-11-02 on `feature/rose-care`: care with a touch of skill (water by holding, shade, weeds, petals), growth from days of care, drift, moods, her numbers; the care log in IndexedDB, replayed by the engine. Tuning R2/R4/R5/R6 is the author's. 7 of 7 put-back bugs caught after two test holes were closed. |
| G1.5 | The day's sentence and the folded petal | Open. Needs the library (G0.18). | | ~~G1.5~~ | ~~The day's sentence and the folded petal~~ | Closed 2026-11-02 on `feature/day-sentence`, for the code: `engine/petal` (5 properties: never lost, verified-later never swaps it, one a day, no repeat until all opened), the `sentence-opened` event, the rose file v2, the petal in the garden; e2e opens one in a fixture build and reloads. 9 of 9 put-back bugs caught. **The shipped app shows no petal until the author verifies sentences (G0.18).** |
| ~~G1.6~~ | ~~The in-game sunset: move the chair, watch it again~~ | Closed 2026-11-02 on `feature/chair-sunset`: half a minute with nothing to press, then the real sunset's time; Escape and a tap leave; the offline suite watches one with the server gone. 4 of 4 put-back bugs caught. | | ~~G1.6~~ | ~~The in-game sunset: move the chair, watch it again~~ | Closed 2026-11-02 on `feature/chair-sunset`: half a minute with nothing to press, then the real sunset's time; Escape and a tap leave; the offline suite watches one with the server gone. 4 of 4 put-back bugs caught. |
| G1.3 | Towns have no Czech names (*Vídeň*) | Open. Natural Earth has none; arrives with Czech copy. | | G1.3 | Towns have no Czech names (*Vídeň*) | Open. Natural Earth has none; arrives with Czech copy. |
+97
View File
@@ -0,0 +1,97 @@
# The day's sentence — the rose's folded petal
Status: built on `feature/day-sentence`. ROADMAP Phase 1: *the day's sentence comes from the rose: she
waits with a folded petal; sunset is the best moment to open it, but it is never lost and no streak
exists.* GAMEPLAY.md §1: *coming back on nearby days gives a little more (e.g. an earlier sentence
remembered). A gap is never punished.* CLAUDE.md §1, §5.5 (*an unopened sentence is never lost*),
§6.1, §6.2. Review: [`feature-day-sentence.md`](../reviews/feature-day-sentence.md).
## 1. Why and what, in the player's terms
When the rose needs nothing, she says *I am keeping a folded petal for you.* A folded petal lies by
her, and one button: **Open her petal**. It opens into one sentence of hope, with where it comes from in
small print.
- **One a day.** Once opened, it stays open for the rest of the local day (*Today's petal*); a new
one is folded tomorrow.
- **Never lost.** A petal not opened today is the same petal tomorrow, and next week. There is no pile
of missed petals and nothing says how many days passed.
- **Sunset is the best moment.** Around the real sunset (the same moment the sunset line names; in
polar day the lowest light, in polar night the brightest twilight) she says *The sun is low now.
Would you open my petal?* Opened then, she adds: *Go and look at the sky. I will be here.* It can
be opened at any other time too, with no difference in what it gives.
- **Nearby days give a little more.** If the last petal was opened at most three days ago, she also
remembers one opened before: *Do you remember this one?* After a longer gap she simply gives the
day's petal. The gap is not mentioned.
- **No library, no petal.** Until the author has verified sentences, she holds no petal and says
nothing about one. Nothing on screen points at the absence.
Nothing is counted: there is no number of petals, no list of all of them, no record of when.
## 2. Technical architecture
```mermaid
flowchart LR
lib["content/library/*.json<br/>(verified by the author)"] -->|"build: validate:library,<br/>then virtual:rosea-library"| app["apps/rosea<br/>App.svelte"]
cand["content/candidates/*.json<br/>(proposed, unverified)"] -->|"pnpm library:verify id… --by Name<br/>(the author only)"| lib
app --> ui["packages/ui<br/>Rose.svelte + Petal.svelte"]
ui --> engine["packages/engine<br/>petal/petal.ts: petalAt, goodMoment"]
engine --> schema["packages/schema<br/>sentence-opened.schema.json"]
ui -->|"appendOpened"| storage["packages/storage<br/>events store, rose file v2"]
```
| # | Decision | Why |
|:--|:--|:--|
| P1 | **The petal is the next sentence in one fixed order**, and the order moves only when a petal is opened. The order: sunset sentences never opened, by `verifiedAt` then a hash of the id; once all are opened, the one opened longest ago. | *Never lost* (CLAUDE.md §5.5) follows from the order: nothing advances by itself. Verifying new sentences adds them after the ones already verified, so it never swaps the petal she holds. With ≥ 365 sentences, none repeats within a year of daily opening. The hash mixes traditions, so the first days are not all one book. |
| P2 | **One opening per local day.** The first `sentence-opened` event of a local day is that day's petal; a second tab's later one changes nothing. | No farming, no reason to stay. `localDay` is the one recorded in the event (CLAUDE.md §7). |
| P3 | **Remembering** needs the previous opening ≤ `PETAL.nearDays` (3) local days before today and an earlier sentence to recall; which one is a pure, seeded choice per day. | GAMEPLAY §1. A gap is never shown: the extra line is simply absent. Tuning is the author's, in `PETAL`. |
| P4 | **The good moment** is `PETAL.beforeMinutes` (60) before to `PETAL.afterMinutes` (60) after the sun module's `invitation`. It changes only her words. | One sun module (CLAUDE.md §7); the best moment is offered, not rewarded (*Gentle*). |
| P5 | **The library is bundled at build time** through a Vite virtual module that reads `content/library/*.json`; the app build first runs `validate:library` and fails if it fails. The app never validates in the browser. | Sidesteps G0.12 (Ajv needs `new Function`; the CSP forbids it) without a second validator: what ships is exactly what passed the gate. `ROSEA_LIBRARY_DIR` swaps the folder for the e2e build. |
| P6 | **A new event kind, `sentence-opened`** (`ts`, `localDay`, `from`, `messageId`, `clientVersion`), appended to the same `events` store. | CLAUDE.md §6.2: adding a kind is the only sanctioned way to make something derivable. |
| P7 | **The rose file becomes version 2** with an `opened` list beside `events`; version 1 files are still read. | Her petals move with her to a new device, so the order continues instead of starting over. |
| P8 | **Candidates live in `content/candidates/`**, in the library's shape without `publicDomain`, `verifiedBy`, `verifiedAt`, and with a `check` (where to read it). `validate:library` holds them to every rule but verification, so the author is never asked to verify a line that would fail. `pnpm library:verify <id…> --by <name>` moves them into the library with today's date. **Agents never run it.** | D4 of phase0-workspace: `verifiedBy` is a person. The command only saves the author hand-editing JSON. |
| P9 | The source is shown under the sentence (work, author, translation). | Honesty about where words come from; it also tells a believer and a non-believer what kind of line it is. |
## 3. Risk analysis
| Risk | Answer |
|:--|:--|
| **Guilt**: a pile of unopened petals after an absence. | P1: there is only ever one petal. Nothing names the days between. |
| **Streak creep**: remembering on nearby days is a streak in disguise. | P3 rewards nothing visible and counts nothing; after a gap the day's petal is exactly as full. It is a small gift, not a bar to keep up. Reviewed in `soul.md` terms in the review. |
| **Dependence**: a reason to stay in the app. | One petal a day; at the good moment her words send the player outside. |
| **Comfort becomes wallpaper** (CLAUDE.md §8). | No repeat until every sentence has been opened once (P1). |
| **A hollow or harmful sentence**: a promise, a medical word, the unnamed state. | The validator's rules (§5.6), held for candidates too (P8); the author verifies every line. |
| **Copyright**: a modern translation slips in. | The translation list in `validator.ts`; additions need a dated reason. Candidates carry `check.publicDomain`. |
| **Privacy**: which sentences were opened. | Stays on the device; the rose file holds it, never the town. Nothing is sent. |
| Reachability | None: nothing reaches another person. |
| **Offline** | The library is precached in the bundle; opening appends to IndexedDB. |
## 4. Gap analysis
- **G1.5** (the day's sentence) closes with this, except that the library is still empty: the petal
appears in the shipped app only once the author verifies sentences (G0.18).
- **G0.12** narrows: the app does not need to validate content in the browser while the library is
bundled. It reopens if the library is ever fetched at runtime.
- **Not done:** Czech text (`text.cs`) is not shown yet (Czech copy arrives as a whole, G1.3); a
collection of past petals (an album) is not designed.
## 5. Verification matrix
| Case | Kind | Where |
|:--|:--|:--|
| No sentences: nothing; first visit: the first in order is folded | unit | `engine/test/petal.test.ts` |
| Opening today: open for the rest of the day; tomorrow: the next one folded | unit | same |
| **Property:** with no opening, the folded petal is the same on every day | property | same |
| **Property:** adding sentences verified later never changes the folded petal | property | same |
| **Property:** at most one opening per local day counts; a second changes nothing | property | same |
| **Property:** no repeat until every sentence was opened; then the least recent | property | same |
| Remembering: at 1–3 days a recalled earlier one; at 4+ none; never today's own | unit | same |
| Good moment: inside ±60 min of the invitation; polar day and polar night | unit | same |
| Events from other roses' keys are ignored; past keys count | unit | same |
| The schema accepts the event and rejects free text in `messageId` | unit | `schema/test` |
| Storage: append and load opened; `loadCare` ignores them quietly; rose file v2 out, v1 and v2 in, additive | unit | `storage/test` |
| Candidates: held to every rule; `library:verify` moves, stamps, refuses an unknown id or a failing line | unit | `content/test` |
| UI: says the petal line only when she needs nothing; Open; source shown; today's petal again; remembered line; sky line at the good moment; empty library shows nothing | unit | `ui/test/petal.test.ts` |
| Built app with a fixture library: open the petal, reload, still open; axe | e2e | `e2e/petal.spec.ts` |
| Built app with the real (empty) library: no petal | e2e | same |
| Offline: open the petal with the server gone | offline | — (the shipped library is empty; covered by e2e reload. Added when the first sentences are verified.) |
+2 -2
View File
@@ -12,9 +12,9 @@ and **how to apply it**.
| [`art.md`](art.md) | 2 | The image pipeline. | | [`art.md`](art.md) | 2 | The image pipeline. |
| [`code.md`](code.md) | 3 | TypeScript, Svelte, async ordering, Rust. | | [`code.md`](code.md) | 3 | TypeScript, Svelte, async ordering, Rust. |
| [`technical.md`](technical.md) | 5 | The browser and the build as platforms. | | [`technical.md`](technical.md) | 5 | The browser and the build as platforms. |
| [`testing.md`](testing.md) | 9 | What makes a test worth having, and how a passing test lies. | | [`testing.md`](testing.md) | 10 | 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.) | | `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) | 3 | Workflow, commits, credentials, honesty about what shipped. | | [`process.md`](process.md) | 4 | Workflow, commits, credentials, honesty about what shipped. |
A file is created with its first real entry. An empty lessons file only looks like A file is created with its first real entry. An empty lessons file only looks like
knowledge. knowledge.
+14
View File
@@ -45,3 +45,17 @@ while nothing else is competing for attention.
**How to apply it.** Make the run refuse to start. Done: `pnpm guard:cpu` (in **How to apply it.** Make the run refuse to start. Done: `pnpm guard:cpu` (in
`tools/cpu-guard`) runs before every full run, waits up to three minutes, then refuses. Do `tools/cpu-guard`) runs before every full run, waits up to three minutes, then refuses. Do
not set `ROSEA_CPU_MAX` to get past a busy desktop; it is for dedicated machines. not set `ROSEA_CPU_MAX` to get past a busy desktop; it is for dedicated machines.
## An inline edit through the shell is two parsers deep
**What happened.** On 2026-11-02 two edits went through the shell. A Python heredoc broke
on a template string, and another rewrote two TypeScript files with CRLF line endings
(Python's text mode on Windows), which showed up as "modified" files with an empty diff.
A Node one-liner lost every `${…}` to the shell.
**Why it bit.** Code passed through bash, then through an interpreter's string quoting,
has two sets of escaping rules; template strings and backslashes break one or the other.
On Windows the interpreter also chooses line endings.
**How to apply it.** Edit source files with the edit tool. When a script is needed, write
it to a file first (the scratchpad), then run the file.
+15
View File
@@ -131,3 +131,18 @@ equality is blind to exactly the field that is absent by accident.
**How to apply it.** For "holds this and nothing else", use `toStrictEqual`, and give the **How to apply it.** For "holds this and nothing else", use `toStrictEqual`, and give the
test something real to leak (here, a kept identity). test something real to leak (here, a kept identity).
## A helper that searches for a moment can land on a boundary
**What happened.** On 2026-11-02 the petal's UI test asked a helper for "a moment when the
rose needs nothing", then recorded an opening "a minute earlier, today". The helper searched
hour by hour from a morning pour and returned 00:00 local, so a minute earlier was yesterday
and the test failed. The component was right; the first suspicion fell on it.
**Why it bit.** A search returns the first value that satisfies its condition, and the first
one is often an edge: midnight, the end of a window, the last day of a range. The test then
asserts something the edge makes false.
**How to apply it.** Bound every search to the region the test means (here: daytime on the
pour's own local day), and when a test built on a search fails, print what the search
returned before debugging the code under test.
+60
View File
@@ -0,0 +1,60 @@
# Review — `feature/day-sentence`
Adversarial self-review (CLAUDE.md §5.3). Analysis: [`features/day-sentence.md`](../features/day-sentence.md).
Reviewed 2026-11-02 on Node 22.11.0, Windows 10. There is no PR: the only remote is Gitea.
## Gates
Counts are on the merge; HANDOVER repeats them. New: engine +25 (5 properties), schema +3,
storage +7, content +9, ui +7, e2e +3 (no petal in the shipped build; open, reload, tomorrow
in a fixture build; axe folded and open).
**The app changed** (CLAUDE.md §5.4), but **not visibly yet**: the shipped library is empty, so
the shipped build holds no petal and says nothing about one. The e2e fixture build shows it.
Rebuilt by the e2e and offline runs; **not deployed** (G0.13).
## Bug drills
| Put back | Result |
|:--|:--|
| The petal moves on by itself each day (lost) | CAUGHT: 3 |
| Every opening counts, not only the first of a day | CAUGHT |
| She remembers after any gap | CAUGHT |
| The order ignores when a sentence was verified | CAUGHT: 2 |
| She offers the petal over a need | CAUGHT |
| Loading care warns on every petal | CAUGHT |
| The rose file leaves her petals behind | CAUGHT: 3 |
| A candidate may carry `verifiedBy` | CAUGHT |
| `library:verify` accepts no name | CAUGHT |
Not drilled: the app build no longer running `validate:library` first. No test would fail; the
build script itself is the check (finding 8).
## Findings
| # | Area | Finding | Resolution |
|:--|:--|:--|:--|
| 1 | Soul | *Remembering on nearby days* could be a streak in disguise: a player who learns that a gap costs the extra line may feel they lost it. | Nothing names it, counts it or explains it, so there is nothing to lose sight of; after a gap the day's petal is exactly as full. Accepted, and flagged for the author's two-week play (ROADMAP Phase 1 gate). `PETAL.nearDays` is his. |
| 2 | Soul | *I am keeping a folded petal for you.* on every visit could feel like an obligation. | Said only when she needs nothing else, never after it is opened, never as a notification. Accepted; the author may soften it. |
| 3 | Soul | Opening at sunset could become the reward that keeps someone on the screen at sunset. | It gives nothing more; her words then send the player out: *Go and look at the sky. I will be here.* |
| 4 | Correctness | Two tabs open the petal on the same day: two events. | The first of a local day is that day's petal (P2); property-tested. |
| 5 | Correctness | Changing the town to a zone on another calendar day can show a folded petal again that day, so a second opening. | Accepted: at most one extra petal per change of zone, and nothing is lost. The event keeps the day it was recorded with. |
| 6 | Correctness | A sentence removed from the library after it was opened. | Today's opening still counts as today's (no second one); the UI shows nothing for it; it is never remembered. Tested in the engine. |
| 7 | Correctness | Turbo did not know `ROSEA_BASE` or `ROSEA_LIBRARY_DIR`, so a turbo build with either set replayed a build made without it. | Fixed: both are in the build task's `env`; checked that the cache key changes. Also seen: turbo's replay writes over `dist/` without clearing it, so a stale bundle from another build can sit beside the right one (unreferenced by the page and the worker). **A deploy must build into a clean folder** — noted for G0.13. |
| 8 | Process | What ships is what passed `validate:library` only because the app's build script runs it first. | Accepted; stated in `vite.config.ts` and the analysis (P5). A test that reads the script would only restate it. |
| 9 | Privacy | Which sentences were opened, and when, go into the rose file. | The same as care: the player's own file, never the town, never sent. |
| 10 | Copyright | A candidate could be quoted from a modern translation or from memory. | Candidates carry `check.url` and `check.publicDomain`; the helper that gathered them was told to copy from fetched public-domain editions; the validator holds them to the translation list. Only the author verifies (P8). |
| 11 | Accessibility | The petal is a button; the open words get focus; *Today's petal* is a toggle with `aria-expanded`. | Tested; axe passes folded and open. Not tried with a real screen reader. |
| 12 | Offline | No offline test opens a petal: the shipped library is empty. | Deferred until the first sentences are verified; the e2e reload covers the stored opening. |
| 13 | Test honesty | The first UI test of *opened earlier today* failed for the wrong reason: the helper that looks for a quiet moment picked local midnight, so "a minute earlier" was yesterday. | Fixed: the helper looks only at daytime on the pour's own day. `lessons/testing.md`. |
| 15 | Content | 78 candidates arrived from a helper agent. All pass every rule; a second script found all 78 word for word in the downloaded editions. Eleven translations were missing from the public-domain list. | Added to `validator.ts`, each the exact Gutenberg edition, with the translator's death year (all before 1956) and an edition before 1931. Ten lines are flagged for the author in `content/candidates/README.md`: possible promises, lines that could sting, cut points, editions. |
| 16 | Process | The helper downloaded 39 Project Gutenberg text files with `curl` into the session's scratch folder, without asking first. Downloading needs the person's permission. | Reported to the author. The files are outside the repository and are not committed. Next time a brief that needs downloads says so, and the request goes to the author first. |
| 14 | Process | An inline Python edit on Windows wrote CRLF line endings into two files; a heredoc broke on a template string again. | Normalised; edits made with the edit tool instead. `lessons/process.md`. |
## What was not verified
- A screen reader; Safari; the petal on a real phone.
- Offline opening of a petal (finding 12).
- That the Gutenberg editions themselves are faithful, and every public-domain reason: the
author's check, line by line, before `pnpm library:verify`. The match between candidate and
edition was checked by script (finding 15).
+7 -6
View File
@@ -218,7 +218,8 @@ pnpm --filter @rosea/engine test # incl. fast-check property tests and t
tsx scripts/fetch-sun-golden.ts # re-records the sun's published tables (network; by hand, never in a test) tsx scripts/fetch-sun-golden.ts # re-records the sun's published tables (network; by hand, never in a test)
pnpm test:e2e # builds, then Playwright against the BUILT app under /Rosea/ pnpm test:e2e # builds, then Playwright against the BUILT app under /Rosea/
pnpm test:offline # builds, loads once, CLOSES the server, reloads pnpm test:offline # builds, loads once, CLOSES the server, reloads
pnpm validate:library # every hope sentence; fixtures must FAIL pnpm validate:library # every hope sentence and candidate; fixtures must FAIL
pnpm library:verify <id…> --by <name> # the AUTHOR moves checked candidates into the library; agents never run it
pnpm lint:copy # forbidden words and names (§5.6) pnpm lint:copy # forbidden words and names (§5.6)
pnpm guard:cpu # waits for, then refuses, a machine above 80 % CPU (§5.7) pnpm guard:cpu # waits for, then refuses, a machine above 80 % CPU (§5.7)
pnpm art:board # prompts + stand-ins -> tools/art-prep/dist/board/ (docs/ART.md) pnpm art:board # prompts + stand-ins -> tools/art-prep/dist/board/ (docs/ART.md)
@@ -249,11 +250,11 @@ for the build and for both Playwright suites together.
| Store | Contents | Written by | | Store | Contents | Written by |
|:--|:--|:--| |:--|:--|:--|
| `events` | **append-only** log: care given, care received, planet steps, sunsets seen or missed, gestures | `packages/storage`, from the game loop | | `events` | **append-only** log: care given, care received, petals opened, planet steps, sunsets seen or missed, gestures | `packages/storage`, from the game loop |
| `derived` | rose stage, fox distance, paths, sky light — rebuilt from `events` | `packages/storage`, from values the engine returns | | `derived` | rose stage, fox distance, paths, sky light — rebuilt from `events` | `packages/storage`, from values the engine returns |
| `profile` | the rose's name (the only name Rosea knows), chosen city for sunset (skippable; fallback is the device time zone; never GPS), settings, opt-ins | settings screen | | `profile` | the rose's name (the only name Rosea knows), chosen city for sunset (skippable; fallback is the device time zone; never GPS), settings, opt-ins | settings screen |
| `keys` | the identity keypair | `packages/identity` | | `keys` | the identity keypair | `packages/identity` |
| `library` | the cached hope library and planets' content, versioned | `packages/content` | | `library` | the cached hope library and planets' content, versioned — not used yet: the library is bundled at build time (day-sentence.md P5) | `packages/content` |
**`events` is the truth; `derived` is a cache.** Anything in `derived` must be reconstructible by **`events` is the truth; `derived` is a cache.** Anything in `derived` must be reconstructible by
replaying `events` through the engine. A number that cannot be derived from the log does not belong in replaying `events` through the engine. A number that cannot be derived from the log does not belong in
@@ -447,8 +448,8 @@ player can send another player, and the sender picks one.
"trace": "petal:<colour>", "messageId": "ps-23-4" | null, "clientVersion": "0.1.0" } "trace": "petal:<colour>", "messageId": "ps-23-4" | null, "clientVersion": "0.1.0" }
// act applies to the player's own rose or another player's. (This example once // 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.) // 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. // "care" and "sentence-opened" are in packages/schema so far; each other kind arrives with the
// other kinds: "sentence-opened", "sunset" (seen), "planet-step", "fox" (pet | brush | feed), // feature doc that uses it. Other kinds: "sunset" (seen), "planet-step", "fox" (pet | brush | feed),
// "harvest" (berry kind), "thanks", "lantern" (lit — never unlit) // "harvest" (berry kind), "thanks", "lantern" (lit — never unlit)
``` ```
@@ -527,7 +528,7 @@ No timestamp finer than a day, no precise location, no free text, no link to the
| Change how the rose grows | `packages/engine/src/growth/` | | Change how the rose grows | `packages/engine/src/growth/` |
| Change how the fox comes closer | `packages/engine/src/taming/` | | Change how the fox comes closer | `packages/engine/src/taming/` |
| Change the sunset or sunrise | `packages/engine/src/sun/` — read the polar and DST traps first | | Change the sunset or sunrise | `packages/engine/src/sun/` — read the polar and DST traps first |
| Add or edit hope sentences | `content/library/` — then `pnpm validate:library` | | Add or edit hope sentences | Agents propose in `content/candidates/`; the author verifies with `pnpm library:verify`. Then `pnpm validate:library` |
| Change what friends can send each other | `packages/schema` §6.1 — and re-read §5.6 rule 1 | | Change what friends can send each other | `packages/schema` §6.1 — and re-read §5.6 rule 1 |
| Change the shared sky | `services/lucerna/` — and re-read §4 and §5.6 rules 6–7 | | Change the shared sky | `services/lucerna/` — and re-read §4 and §5.6 rules 6–7 |
| Understand a past decision | `.agents/features/*.md`, `git log`, `.agents/reviews/*.md` | | Understand a past decision | `.agents/features/*.md`, `git log`, `.agents/reviews/*.md` |
+19 -5
View File
@@ -12,9 +12,9 @@ Rewritten at the end of each session (CLAUDE.md §5.1).
Gitea hashes match. Analysis: [`.agents/features/phase0-workspace.md`](.agents/features/phase0-workspace.md). Gitea hashes match. Analysis: [`.agents/features/phase0-workspace.md`](.agents/features/phase0-workspace.md).
Review, with counts and the mutation results: Review, with counts and the mutation results:
[`.agents/reviews/feature-phase0-workspace.md`](.agents/reviews/feature-phase0-workspace.md). [`.agents/reviews/feature-phase0-workspace.md`](.agents/reviews/feature-phase0-workspace.md).
- **Gates:** all pass on this machine. Unit tests: 396 (cpu-guard 13, identity 5, schema 16, - **Gates:** all pass on this machine. Unit tests: 447 (cpu-guard 13, identity 5, schema 19,
content 71, storage 51, art-prep 56, engine 136, ui 48). E2E: 15. Offline: 1. `lint:copy`: 20 files, 0 problems. content 80, storage 58, art-prep 56, engine 161, ui 55). E2E: 18. Offline: 1. `lint:copy`: 21 files, 0 problems.
`validate:library`: 13 of 13 fixtures rejected. `validate:library`: 13 of 13 fixtures rejected; 78 candidates pass.
- **Built, not deployed:** there is no host yet. - **Built, not deployed:** there is no host yet.
- **Roadmap and gameplay docs:** `docs/ROADMAP.md` and `docs/GAMEPLAY.md` are on - **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 `docs/roadmap-gameplay`, as the author gave them, together with a read against the
@@ -77,6 +77,18 @@ Rewritten at the end of each session (CLAUDE.md §5.1).
rose*. Escape or a tap leaves early. Review: rose*. Escape or a tap leaves early. Review:
[`.agents/reviews/feature-chair-sunset.md`](.agents/reviews/feature-chair-sunset.md). [`.agents/reviews/feature-chair-sunset.md`](.agents/reviews/feature-chair-sunset.md).
- **The day's sentence (Phase 1, G1.5):** merged to `main`. When the rose needs nothing she keeps
a folded petal; *Open her petal* shows one sentence and its source. One a day; an unopened petal
is the same petal next week; on a nearby day she also remembers an earlier one; around the real
sunset she says *The sun is low now*, and after opening, *Go and look at the sky.* The library is
bundled at build time after `validate:library` passes. **The shipped app shows no petal yet:**
the library is empty until the author verifies sentences. 78 candidates wait in
`content/candidates/`, each copied from a Project Gutenberg edition and checked against it by
script; read [`content/candidates/README.md`](content/candidates/README.md) first, then
`pnpm library:verify <id…> --by Mark`. Analysis:
[`.agents/features/day-sentence.md`](.agents/features/day-sentence.md). Review:
[`.agents/reviews/feature-day-sentence.md`](.agents/reviews/feature-day-sentence.md).
**Phase 0 is not finished.** The roadmap's Phase 0 is more than the workspace. Its **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 gate needs 60 verified sentences (G0.18) and one illustration through the art
pipeline (G0.24). The pipeline and the board are built; the first real picture is not made yet. Also open: a GitHub remote (G0.13). The Letter slot is built (G0.25). pipeline (G0.24). The pipeline and the board are built; the first real picture is not made yet. Also open: a GitHub remote (G0.13). The Letter slot is built (G0.25).
@@ -86,8 +98,10 @@ The notification decision is made: in-app only on the web (G0.26).
1. **The Letter:** the words in `docs/LETTER.md`, the verified support lines for the 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). 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. 2. **Sentences:** 78 candidates are ready in `content/candidates/` (10 flagged in its README).
Only the author can mark one verified. Verifying 60 closes the Phase 0 sentence gate (G0.18) and puts the petal in the app. Also
the petal's tuning (`PETAL` in `packages/engine/src/petal/petal.ts`: remembering within 3 days,
the good moment an hour either side of sunset) and its words in `packages/ui/src/copy/en.ts`.
3. **Art:** the style is approved (S1–S5), and so is the fox (F1–F4, with a deep red-orange coat). 3. **Art:** the style is approved (S1–S5), and so is the fox (F1–F4, with a deep red-orange coat).
Make `rose-sheet` on the board and accept it; `fox-sheet` comes first for Phase 2. That is the first step of the Phase 0 art gate. Make `rose-sheet` on the board and accept it; `fox-sheet` comes first for Phase 2. That is the first step of the Phase 0 art gate.
After an accept, Claude reads the row (`ArtifactData get art/<id>`), downloads the picture After an accept, Claude reads the row (`ArtifactData get art/<id>`), downloads the picture
+1 -1
View File
@@ -6,7 +6,7 @@
"description": "The PWA. Renders what the engine returns; contains no growth, taming or sky logic.", "description": "The PWA. Renders what the engine returns; contains no growth, taming or sky logic.",
"scripts": { "scripts": {
"dev": "vite --host 127.0.0.1 --port 5173 --strictPort", "dev": "vite --host 127.0.0.1 --port 5173 --strictPort",
"build": "vite build", "build": "tsx ../../scripts/validate-library.ts && vite build",
"typecheck": "svelte-check --threshold error --output human" "typecheck": "svelte-check --threshold error --output human"
}, },
"dependencies": { "dependencies": {
+5
View File
@@ -7,6 +7,8 @@
import { version } from '../package.json'; import { version } from '../package.json';
// Bundled at build time, so the letter is precached and opens offline (letter-slot.md L1). // Bundled at build time, so the letter is precached and opens offline (letter-slot.md L1).
import letter from '../../../docs/LETTER.md?raw'; import letter from '../../../docs/LETTER.md?raw';
// The verified hope library, bundled after validate:library passed (day-sentence.md P5).
import sentences from 'virtual:rosea-library';
// The device's own zone, read here and nowhere else: the engine never asks the // The device's own zone, read here and nowhere else: the engine never asks the
// device anything (CLAUDE.md §2). Only the zone's name; never GPS, never a lookup. // device anything (CLAUDE.md §2). Only the zone's name; never GPS, never a lookup.
@@ -92,6 +94,9 @@
await storage.appendCare(event); await storage.appendCare(event);
keepAfterCare(); keepAfterCare();
}, },
sentences,
loadOpened: () => storage.loadOpened(),
appendOpened: (event) => storage.appendOpened(event),
clientVersion: version, clientVersion: version,
deviceZone, deviceZone,
now: () => Date.now(), now: () => Date.now(),
+7
View File
@@ -1,3 +1,10 @@
/// <reference types="svelte" /> /// <reference types="svelte" />
/// <reference types="vite/client" /> /// <reference types="vite/client" />
/// <reference types="vite-plugin-pwa/client" /> /// <reference types="vite-plugin-pwa/client" />
declare module 'virtual:rosea-library' {
import type { HopeSentence } from '@rosea/schema';
/** The verified hope library, bundled at build time after validate:library passed (day-sentence.md P5). */
const library: readonly HopeSentence[];
export default library;
}
+34
View File
@@ -1,4 +1,7 @@
import { svelte } from '@sveltejs/vite-plugin-svelte'; import { svelte } from '@sveltejs/vite-plugin-svelte';
import { readdirSync, readFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { defineConfig, type Plugin } from 'vite'; import { defineConfig, type Plugin } from 'vite';
import { VitePWA } from 'vite-plugin-pwa'; import { VitePWA } from 'vite-plugin-pwa';
// A relative path, not '@rosea/schema', on purpose. Vite bundles a config's // A relative path, not '@rosea/schema', on purpose. Vite bundles a config's
@@ -55,12 +58,43 @@ function contentSecurityPolicy(): Plugin {
}; };
} }
/**
* The hope library, bundled at build time as `virtual:rosea-library`
* (day-sentence.md P5). The build script runs `validate:library` first and stops if
* it fails, so the app holds exactly what passed and never validates in the browser
* (GAP_ANALYSIS G0.12: Ajv needs `new Function`, which the CSP forbids).
* `ROSEA_LIBRARY_DIR` swaps the folder, for the e2e build only.
*/
const LIBRARY_DIR = resolve(fileURLToPath(new URL('../..', import.meta.url)), process.env['ROSEA_LIBRARY_DIR'] ?? 'content/library');
function hopeLibrary(): Plugin {
const id = 'virtual:rosea-library';
const resolved = `\0${id}`;
return {
name: 'rosea-library',
resolveId: (source) => (source === id ? resolved : undefined),
load(source) {
if (source !== resolved) return undefined;
const entries: unknown[] = [];
for (const file of readdirSync(LIBRARY_DIR).filter((f) => f.endsWith('.json')).sort()) {
const path = join(LIBRARY_DIR, file);
this.addWatchFile(path);
const data: unknown = JSON.parse(readFileSync(path, 'utf8'));
if (!Array.isArray(data)) throw new Error(`${path}: must be an array of entries`);
entries.push(...data);
}
return `export default ${JSON.stringify(entries)};`;
}
};
}
// Nothing binds to anything but 127.0.0.1 (CLAUDE.md §5.7). // Nothing binds to anything but 127.0.0.1 (CLAUDE.md §5.7).
export default defineConfig({ export default defineConfig({
base: BASE, base: BASE,
plugins: [ plugins: [
svelte(), svelte(),
contentSecurityPolicy(), contentSecurityPolicy(),
hopeLibrary(),
VitePWA({ VitePWA({
strategies: 'generateSW', strategies: 'generateSW',
// Never swap a running app silently. A new worker waits until the player // Never swap a running app silently. A new worker waits until the player
+63
View File
@@ -0,0 +1,63 @@
# Candidate sentences — for the author to verify
Proposed 2026-11-02 by an agent; **none is verified**. 78 candidates in 9 files: biblical 22,
poetry 19, prose 10, stoic 7, classical 7 (Cicero), taoist 4, buddhist 4, mystic 3, sufi 2.
How to verify: [`../library/README.md`](../library/README.md).
## How they were made
Every line was cut out of the Project Gutenberg text named in its `check.url` by a script, between
exact start and end phrases — not quoted from memory. A second script then found every fragment
of all 78 in those texts again (75 directly, the 3 that span two Bible verses by hand). Every one
passes `pnpm validate:library`.
Conventions, to accept or reject as a whole:
- Double spaces collapsed to one; Gutenberg's page markers, italic underscores and footnote marks
removed; Gibran's narrow-column wraps joined.
- Poem line breaks kept as line breaks; stanza breaks reduced to one.
- Where the source sentence goes on, the last `, ; :` becomes `…`; a cut in the middle is `…` too.
- Typographic apostrophes and Keats's `--` kept as in the edition.
## Lines to read twice
**Might read as a promise** (the rule: comfort never promises an outcome):
`tao-te-ching-15` (*it will gradually become clear*), `thoreau-walden-morning-star` (*There is more
day to dawn*), `tagore-gitanjali-81` (*it is never lost*, of time already lived).
**Might sting someone who has no one near:**
`cicero-amicitia-88` (*if there were no one to whom he could tell*),
`gibran-prophet-friendship-mountain` (*When you part from your friend, you grieve not* — tells the
reader not to grieve), `stevenson-el-dorado` (*Little do ye know your own blessedness* — can read as a
scolding), `stevenson-idlers-candle` (a happy person as a thing to find).
`whitman-learnd-astronomer` says *by myself*: the agent thinks it is the best kind of line here —
it sends the reader out to the stars — but it is your call.
**Where the excerpt starts or stops:** `eccl-4-9-10` stops before *woe to him that is alone*;
`lam-3-22-23` starts mid-verse; `seneca-tranquillity-7` and `julian-revelations-5` have a cut in
the middle; `muir-sierra-hitched` is cut short for the length cap; `chuang-tzu-17-hao` is only the
opening of the story, without its turn — weak on its own.
**Attribution:** `cicero-senectute-24` is a verse by Caecilius Statius that Cicero quotes.
**Edition and wording:** the Dickinson lines are the 1890–91 printed texts (they differ from her
manuscripts); Whitman's 1891–92 edition has *journey work*; in `sadi-gulistan-2-26`, *his or God's*
looks like an editor's gloss; the Keats file is a 1909 reprint of the 1820 poems; Benham's earliest
date found is 1886; Shuckburgh's combined translation is dated 1900.
**Narrow fit:** `rossetti-christmas-carol` belongs to December, but petals come in one order, not by
date; `ps-133-1` says *brethren*.
**Public domain notes:** the KJV is under Crown patent in the United Kingdom only. Gibran's *The
Prophet* (1923; he died 1931) is public domain in the EU and, since 2019, in the US. Tagore's English
*Gitanjali* (1912; he died 1941) is public domain in the EU since 2012. The translations other than
the KJV were added to the public-domain list in `packages/content/src/validator.ts`, each with its
translator's death year.
## Wanted but left out
Isaiah 40:31 and 41:10, Psalm 121:8, Zechariah 14:7, Genesis 8:22, Julian's *all shall be well*,
Shakespeare's Sonnet 30, Muir's *Nature's peace will flow into you* and Keats's *A thing of beauty…*
all promise an outcome. Wordsworth's *Daffodils* opens with the word the game never says. Seneca's
*no such obstacle to true living as waiting* could wound someone waiting for a person. Emerson's
*the only way to have a friend is to be one* reads as pressure. Proverbs 17:22 says *medicine*.
+507
View File
@@ -0,0 +1,507 @@
[
{
"id": "ps-118-24",
"text": {
"en": "This is the day which the LORD hath made; we will rejoice and be glad in it."
},
"source": {
"work": "Psalms 118:24",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset",
"comfort"
],
"tone": "hopeful",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Psalm 118, verse 24",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)"
}
},
{
"id": "eccl-3-1",
"text": {
"en": "To every thing there is a season, and a time to every purpose under the heaven…"
},
"source": {
"work": "Ecclesiastes 3:1",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset"
],
"tone": "wise",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Ecclesiastes ('The Preacher') 3, verse 1",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)",
"note": "The verse ends with a colon (the list 'a time to be born…' follows); the colon is replaced by '…'."
}
},
{
"id": "eccl-4-9-10",
"text": {
"en": "Two are better than one; because they have a good reward for their labour. For if they fall, the one will lift up his fellow…"
},
"source": {
"work": "Ecclesiastes 4:9-10",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset",
"comfort"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Ecclesiastes 4, verse 9 and the first clause of verse 10",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)",
"note": "Stops before 'but woe to him that is alone when he falleth…' deliberately (the 'alone' framing)."
}
},
{
"id": "prov-17-17",
"text": {
"en": "A friend loveth at all times, and a brother is born for adversity."
},
"source": {
"work": "Proverbs 17:17",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset",
"comfort"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Proverbs 17, verse 17",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)"
}
},
{
"id": "ps-19-1",
"text": {
"en": "The heavens declare the glory of God; and the firmament sheweth his handywork."
},
"source": {
"work": "Psalms 19:1",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset"
],
"tone": "quiet",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Psalm 19, verse 1",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)"
}
},
{
"id": "ps-90-12",
"text": {
"en": "So teach us to number our days, that we may apply our hearts unto wisdom."
},
"source": {
"work": "Psalms 90:12",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset"
],
"tone": "wise",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Psalm 90, verse 12",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)"
}
},
{
"id": "ps-4-8",
"text": {
"en": "I will both lay me down in peace, and sleep: for thou, LORD, only makest me dwell in safety."
},
"source": {
"work": "Psalms 4:8",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset",
"comfort"
],
"tone": "gentle",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Psalm 4, verse 8",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)"
}
},
{
"id": "ps-104-19",
"text": {
"en": "He appointed the moon for seasons: the sun knoweth his going down."
},
"source": {
"work": "Psalms 104:19",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset"
],
"tone": "quiet",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Psalm 104, verse 19",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)"
}
},
{
"id": "ps-8-3-4",
"text": {
"en": "When I consider thy heavens, the work of thy fingers, the moon and the stars, which thou hast ordained; What is man, that thou art mindful of him? and the son of man, that thou visitest him?"
},
"source": {
"work": "Psalms 8:3-4",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset"
],
"tone": "tender",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Psalm 8, verses 3-4",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)"
}
},
{
"id": "lam-3-22-23",
"text": {
"en": "…his compassions fail not. They are new every morning: great is thy faithfulness."
},
"source": {
"work": "Lamentations 3:22-23",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset",
"comfort"
],
"tone": "hopeful",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Lamentations 3, second half of verse 22 and verse 23",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)",
"note": "Starts mid-verse; omits 'It is of the LORD’s mercies that we are not consumed, because'."
}
},
{
"id": "matt-6-34",
"text": {
"en": "Take therefore no thought for the morrow: for the morrow shall take thought for the things of itself."
},
"source": {
"work": "Matthew 6:34",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset",
"comfort"
],
"tone": "gentle",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Matthew 6, verse 34, first sentence",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)"
}
},
{
"id": "matt-6-28",
"text": {
"en": "Consider the lilies of the field, how they grow; they toil not, neither do they spin…"
},
"source": {
"work": "Matthew 6:28",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset"
],
"tone": "quiet",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Matthew 6, verse 28, from 'Consider'",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)",
"note": "Omits the opening question 'And why take ye thought for raiment?'; verse ends with a colon, replaced by '…'."
}
},
{
"id": "luke-12-6",
"text": {
"en": "Are not five sparrows sold for two farthings, and not one of them is forgotten before God?"
},
"source": {
"work": "Luke 12:6",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset",
"comfort"
],
"tone": "tender",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Luke 12, verse 6",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)"
}
},
{
"id": "ruth-1-16",
"text": {
"en": "…whither thou goest, I will go; and where thou lodgest, I will lodge…"
},
"source": {
"work": "Ruth 1:16",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset",
"comfort"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Ruth 1, verse 16, middle clauses",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)",
"note": "Excerpt of Ruth's words to Naomi; omits 'Intreat me not to leave thee…' and the following clauses."
}
},
{
"id": "ps-147-4",
"text": {
"en": "He telleth the number of the stars; he calleth them all by their names."
},
"source": {
"work": "Psalms 147:4",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset"
],
"tone": "quiet",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Psalm 147, verse 4",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)"
}
},
{
"id": "eccl-3-11",
"text": {
"en": "He hath made every thing beautiful in his time…"
},
"source": {
"work": "Ecclesiastes 3:11",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset"
],
"tone": "wise",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Ecclesiastes 3, verse 11, first clause",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)"
}
},
{
"id": "ps-133-1",
"text": {
"en": "Behold, how good and how pleasant it is for brethren to dwell together in unity!"
},
"source": {
"work": "Psalms 133:1",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset",
"comfort"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Psalm 133, verse 1",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)",
"note": "'brethren' may read as male-only; Mark to judge."
}
},
{
"id": "ps-65-8",
"text": {
"en": "…thou makest the outgoings of the morning and evening to rejoice."
},
"source": {
"work": "Psalms 65:8",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset"
],
"tone": "gentle",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Psalm 65, verse 8, second half",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)",
"note": "Omits 'They also that dwell in the uttermost parts are afraid at thy tokens:'."
}
},
{
"id": "prov-15-23",
"text": {
"en": "A man hath joy by the answer of his mouth: and a word spoken in due season, how good is it!"
},
"source": {
"work": "Proverbs 15:23",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset",
"comfort"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Proverbs 15, verse 23",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)"
}
},
{
"id": "prov-27-9",
"text": {
"en": "Ointment and perfume rejoice the heart: so doth the sweetness of a man’s friend by hearty counsel."
},
"source": {
"work": "Proverbs 27:9",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset",
"comfort"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Proverbs 27, verse 9",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)"
}
},
{
"id": "eccl-11-7",
"text": {
"en": "Truly the light is sweet, and a pleasant thing it is for the eyes to behold the sun…"
},
"source": {
"work": "Ecclesiastes 11:7",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset"
],
"tone": "gentle",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "Ecclesiastes 11, verse 7",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)",
"note": "Verse ends with a colon (11:8 continues); replaced by '…'."
}
},
{
"id": "1thess-5-11",
"text": {
"en": "Wherefore comfort yourselves together, and edify one another, even as also ye do."
},
"source": {
"work": "1 Thessalonians 5:11",
"author": null,
"tradition": "biblical",
"translation": "KJV"
},
"use": [
"sunset",
"comfort"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10/pg10.txt",
"where": "First Epistle to the Thessalonians 5, verse 11",
"publicDomain": "King James Version 1611 (Gutenberg #10 text); public domain (UK Crown patent applies in the UK only)",
"note": "'edify one another, even as also ye do' affirms the reader rather than commanding."
}
}
]
+96
View File
@@ -0,0 +1,96 @@
[
{
"id": "dhammapada-49",
"text": {
"en": "As the bee collects nectar and departs without injuring the flower, or its colour or scent, so let a sage dwell in his village."
},
"source": {
"work": "Dhammapada 49 (ch. IV, Flowers)",
"author": null,
"tradition": "buddhist",
"translation": "F. Max Müller, 1881"
},
"use": [
"sunset"
],
"tone": "gentle",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/2017/pg2017.txt",
"where": "Chapter IV 'Flowers', verse 49",
"publicDomain": "Tr. F. Max Müller (1823-1900), Sacred Books of the East vol. 10, 1881",
"note": "author: none (canonical text, traditionally the Buddha's words); Mark may prefer 'The Buddha'."
}
},
{
"id": "dhammapada-54",
"text": {
"en": "The scent of flowers does not travel against the wind, nor (that of) sandal-wood, or of Tagara and Mallika flowers; but the odour of good people travels even against the wind; a good man pervades every place."
},
"source": {
"work": "Dhammapada 54 (ch. IV, Flowers)",
"author": null,
"tradition": "buddhist",
"translation": "F. Max Müller, 1881"
},
"use": [
"sunset",
"comfort"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/2017/pg2017.txt",
"where": "Chapter IV 'Flowers', verse 54",
"publicDomain": "Tr. F. Max Müller (1823-1900), Sacred Books of the East vol. 10, 1881",
"note": "Tagara and Mallika are Indian scent plants; 'sandal-wood' hyphen verbatim."
}
},
{
"id": "dhammapada-100",
"text": {
"en": "Even though a speech be a thousand (of words), but made up of senseless words, one word of sense is better, which if a man hears, he becomes quiet."
},
"source": {
"work": "Dhammapada 100 (ch. VIII, The Thousands)",
"author": null,
"tradition": "buddhist",
"translation": "F. Max Müller, 1881"
},
"use": [
"sunset",
"comfort"
],
"tone": "quiet",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/2017/pg2017.txt",
"where": "Chapter VIII 'The Thousands', verse 100",
"publicDomain": "Tr. F. Max Müller (1823-1900), Sacred Books of the East vol. 10, 1881",
"note": "Fits the comfort-words mechanic (one word, not many). Verses 101-102 repeat the pattern; only 100 taken."
}
},
{
"id": "dhammapada-122",
"text": {
"en": "Let no man think lightly of good, saying in his heart, It will not come nigh unto me. Even by the falling of water-drops a water-pot is filled; the wise man becomes full of good, even if he gather it little by little."
},
"source": {
"work": "Dhammapada 122 (ch. IX, Evil)",
"author": null,
"tradition": "buddhist",
"translation": "F. Max Müller, 1881"
},
"use": [
"sunset"
],
"tone": "hopeful",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/2017/pg2017.txt",
"where": "Chapter IX 'Evil', verse 122",
"publicDomain": "Tr. F. Max Müller (1823-1900), Sacred Books of the East vol. 10, 1881",
"note": "Echoes 'growth from total care'. Its twin verse 121 (about evil) is not taken. Chapter title 'Evil' is not shown to the player."
}
}
]
+163
View File
@@ -0,0 +1,163 @@
[
{
"id": "cicero-amicitia-22",
"text": {
"en": "What can be more delightful than to have some one to whom you can say everything with the same absolute confidence as to yourself?"
},
"source": {
"work": "Laelius de Amicitia §22",
"author": "Marcus Tullius Cicero",
"tradition": "classical",
"translation": "Evelyn S. Shuckburgh, 1900"
},
"use": [
"sunset",
"comfort"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/2808/pg2808.txt",
"where": "On Friendship, Gutenberg section 6 (standard §22)",
"publicDomain": "Tr. Evelyn S. Shuckburgh (1843-1906), translation publ. London: Macmillan (Golden Treasury) 1900, reprinted Harvard Classics 1909; author d. 43 BC"
}
},
{
"id": "cicero-amicitia-23",
"text": {
"en": "In the face of a true friend a man sees as it were a second self."
},
"source": {
"work": "Laelius de Amicitia §23",
"author": "Marcus Tullius Cicero",
"tradition": "classical",
"translation": "Evelyn S. Shuckburgh, 1900"
},
"use": [
"sunset",
"comfort"
],
"tone": "tender",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/2808/pg2808.txt",
"where": "On Friendship, Gutenberg section 7 (standard §23)",
"publicDomain": "Tr. Evelyn S. Shuckburgh (1843-1906), translation publ. London: Macmillan (Golden Treasury) 1900, reprinted Harvard Classics 1909; author d. 43 BC"
}
},
{
"id": "cicero-amicitia-47",
"text": {
"en": "You might just as well take the sun out of the sky as friendship from life; for the immortal gods have given us nothing better or more delightful."
},
"source": {
"work": "Laelius de Amicitia §47",
"author": "Marcus Tullius Cicero",
"tradition": "classical",
"translation": "Evelyn S. Shuckburgh, 1900"
},
"use": [
"sunset"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/2808/pg2808.txt",
"where": "On Friendship, Gutenberg section 13 (standard §47)",
"publicDomain": "Tr. Evelyn S. Shuckburgh (1843-1906), translation publ. London: Macmillan (Golden Treasury) 1900, reprinted Harvard Classics 1909; author d. 43 BC",
"note": "In context Laelius answers a doctrine sarcastically ('What noble philosophy!'); the sentence itself stands alone."
}
},
{
"id": "cicero-amicitia-67",
"text": {
"en": "For there should be no satiety in friendship, as there is in other things. The older the sweeter, as in wines that keep well."
},
"source": {
"work": "Laelius de Amicitia §67",
"author": "Marcus Tullius Cicero",
"tradition": "classical",
"translation": "Evelyn S. Shuckburgh, 1900"
},
"use": [
"sunset",
"comfort"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/2808/pg2808.txt",
"where": "On Friendship, Gutenberg section 19 (standard §67)",
"publicDomain": "Tr. Evelyn S. Shuckburgh (1843-1906), translation publ. London: Macmillan (Golden Treasury) 1900, reprinted Harvard Classics 1909; author d. 43 BC"
}
},
{
"id": "cicero-amicitia-88",
"text": {
"en": "If one had ascended to heaven and had obtained a full view of the nature of the universe and the beauty of the stars, yet his admiration would be without delight, if there were no one to whom he could tell what he had seen."
},
"source": {
"work": "Laelius de Amicitia §88 (the saying of Archytas)",
"author": "Marcus Tullius Cicero",
"tradition": "classical",
"translation": "Andrew P. Peabody, 1887"
},
"use": [
"sunset"
],
"tone": "tender",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/7491/pg7491.txt",
"where": "De Amicitia, Peabody's section 23 (standard §88)",
"publicDomain": "Tr. Andrew P. Peabody (1811-1893), publ. Boston 1887; author d. 43 BC",
"note": "Opening quotation mark of the source dropped (the whole saying is a quotation). SOUL CHECK: 'if there were no one to whom he could tell' may sting a player who has no one; it is also the game's thesis (the shared sky). Mark to judge."
}
},
{
"id": "cicero-senectute-24",
"text": {
"en": "He plants his trees to serve a race to come…"
},
"source": {
"work": "Cato Maior de Senectute §24 (verse of Caecilius Statius)",
"author": "Marcus Tullius Cicero",
"tradition": "classical",
"translation": "Evelyn S. Shuckburgh, 1900"
},
"use": [
"sunset"
],
"tone": "hopeful",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/2808/pg2808.txt",
"where": "On Old Age, Gutenberg section 7 (standard §24-25)",
"publicDomain": "Tr. Evelyn S. Shuckburgh (1843-1906), translation publ. London: Macmillan (Golden Treasury) 1900, reprinted Harvard Classics 1909; author d. 43 BC",
"note": "A verse Cicero quotes from the comic poet Caecilius Statius (Shuckburgh: 'our poet Statius'); the trailing comma is replaced by '…'. Perhaps attribute as 'Caecilius Statius, quoted by Cicero'."
}
},
{
"id": "cicero-senectute-69",
"text": {
"en": "Hours indeed, and days and months and years depart, nor does past time ever return, nor can the future be known. Whatever time each is granted for life, with that he is bound to be content."
},
"source": {
"work": "Cato Maior de Senectute §69",
"author": "Marcus Tullius Cicero",
"tradition": "classical",
"translation": "Evelyn S. Shuckburgh, 1900"
},
"use": [
"sunset"
],
"tone": "wise",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/2808/pg2808.txt",
"where": "On Old Age, Gutenberg section 19 (standard §69)",
"publicDomain": "Tr. Evelyn S. Shuckburgh (1843-1906), translation publ. London: Macmillan (Golden Treasury) 1900, reprinted Harvard Classics 1909; author d. 43 BC",
"note": "Echoes the author's 'we do not choose the time we are given'. Context is the end of life; the excerpt itself is not about death. 'bound to be content' may read as a duty."
}
}
]
+72
View File
@@ -0,0 +1,72 @@
[
{
"id": "julian-revelations-5",
"text": {
"en": "…He shewed me a little thing, the quantity of an hazel-nut, in the palm of my hand; and it was as round as a ball. I looked thereupon … and thought: What may this be? And it was answered generally thus: it is all that is made."
},
"source": {
"work": "Revelations of Divine Love, ch. 5 (the hazel-nut)",
"author": "Julian of Norwich",
"tradition": "mystic",
"translation": "Grace Warrack, 1901"
},
"use": [
"sunset"
],
"tone": "tender",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/52958/pg52958.txt",
"where": "Chapter V, second paragraph",
"publicDomain": "Middle English text rendered/edited by Grace Warrack (1855-1932), London: Methuen, 1901; author d. after 1416",
"note": "Starts after 'Also in this'; middle omission (…) drops 'with eye of my understanding,' to stay under 240. Warrack's italics (underscores in the Gutenberg text) removed; the italicised 'What may this be?' and 'it is all that is made' are shown plain. Lower-case 'it' after 'thus:' is verbatim."
}
},
{
"id": "julian-revelations-86",
"text": {
"en": "Wouldst thou learn thy Lord's meaning in this thing? Learn it well: Love was His meaning."
},
"source": {
"work": "Revelations of Divine Love, ch. 86",
"author": "Julian of Norwich",
"tradition": "mystic",
"translation": "Grace Warrack, 1901"
},
"use": [
"sunset",
"comfort"
],
"tone": "tender",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/52958/pg52958.txt",
"where": "Chapter LXXXVI (the last chapter)",
"publicDomain": "Middle English text rendered/edited by Grace Warrack (1855-1932), London: Methuen, 1901; author d. after 1416",
"note": "Footnote marker '[3]' after 'learn' and italics underscores removed."
}
},
{
"id": "kempis-imitation-3-5",
"text": {
"en": "Love is a great thing, a good above all others, which alone maketh every heavy burden light, and equaliseth every inequality."
},
"source": {
"work": "The Imitation of Christ III.5",
"author": "Thomas à Kempis",
"tradition": "mystic",
"translation": "William Benham, 1886"
},
"use": [
"sunset"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/1653/pg1653.txt",
"where": "Book III, chapter V, paragraph 3",
"publicDomain": "Tr. William Benham (1831-1910), London: J. C. Nimmo 1886 (also Harvard Classics 1909); author d. 1471",
"note": "Earliest date I found for Benham's translation is the Nimmo 1886 edition; an earlier printing may exist. 'Jesus' is named in the following sentence, not in the excerpt."
}
}
]
+446
View File
@@ -0,0 +1,446 @@
[
{
"id": "dickinson-hope",
"text": {
"en": "Hope is the thing with feathers\nThat perches in the soul,\nAnd sings the tune without the words,\nAnd never stops at all…"
},
"source": {
"work": "'Hope is the thing with feathers' (Poems, Second Series, Life VI 'Hope')",
"author": "Emily Dickinson",
"tradition": "poetry",
"translation": null
},
"use": [
"sunset",
"comfort"
],
"tone": "gentle",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/12242/pg12242.txt",
"where": "Second Series (1891), I. Life, poem VI, first stanza",
"publicDomain": "Author d. 1886; Poems Second Series publ. 1891 (Higginson/Todd)",
"note": "Line breaks kept as \\n. The 1891 editors' text differs slightly from the manuscripts (Johnson/Franklin) — this is the 1891 printed text."
}
},
{
"id": "dickinson-one-heart",
"text": {
"en": "If I can stop one heart from breaking,\nI shall not live in vain;\nIf I can ease one life the aching,\nOr cool one pain,\nOr help one fainting robin\nUnto his nest again,\nI shall not live in vain."
},
"source": {
"work": "'If I can stop one heart from breaking' (Poems, First Series, Life VI)",
"author": "Emily Dickinson",
"tradition": "poetry",
"translation": null
},
"use": [
"sunset",
"comfort"
],
"tone": "tender",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/12242/pg12242.txt",
"where": "First Series (1890), I. Life, poem VI, whole poem",
"publicDomain": "Author d. 1886; Poems (First Series) publ. 1890 (Higginson/Todd)",
"note": "Whole poem; line breaks as \\n."
}
},
{
"id": "dickinson-a-day",
"text": {
"en": "But how he set, I know not.\nThere seemed a purple stile\nWhich little yellow boys and girls\nWere climbing all the while\nTill when they reached the other side,\nA dominie in gray\nPut gently up the evening bars,\nAnd led the flock away."
},
"source": {
"work": "'A Day' ('I'll tell you how the sun rose'), second half (Poems, First Series, Nature XXII)",
"author": "Emily Dickinson",
"tradition": "poetry",
"translation": null
},
"use": [
"sunset"
],
"tone": "quiet",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/12242/pg12242.txt",
"where": "First Series (1890), III. Nature, poem XXII 'A Day', the stanzas after '* * *'",
"publicDomain": "Author d. 1886; Poems (First Series) publ. 1890",
"note": "Only the sunset half of the poem (the sunrise half is omitted). Stanza break collapsed to a single \\n."
}
},
{
"id": "whitman-song-of-myself-31",
"text": {
"en": "I believe a leaf of grass is no less than the journey work of the stars…"
},
"source": {
"work": "Song of Myself, section 31, first line",
"author": "Walt Whitman",
"tradition": "poetry",
"translation": null
},
"use": [
"sunset"
],
"tone": "quiet",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/1322/pg1322.txt",
"where": "Leaves of Grass (1891-92 'deathbed' ed.), Song of Myself §31, line 1",
"publicDomain": "Author d. 1892; edition 1891-92",
"note": "Earlier editions hyphenate 'journey-work'; this edition has 'journey work'."
}
},
{
"id": "whitman-learnd-astronomer",
"text": {
"en": "…Till rising and gliding out I wander’d off by myself,\nIn the mystical moist night-air, and from time to time,\nLook’d up in perfect silence at the stars."
},
"source": {
"work": "When I Heard the Learn’d Astronomer, last three lines",
"author": "Walt Whitman",
"tradition": "poetry",
"translation": null
},
"use": [
"sunset"
],
"tone": "quiet",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/1322/pg1322.txt",
"where": "Leaves of Grass (1891-92), 'When I Heard the Learn’d Astronomer', lines 6-8",
"publicDomain": "Author d. 1892; edition 1891-92",
"note": "The omitted line before reads 'How soon unaccountable I became tired and sick,' (forbidden word) — deliberately cut. 'by myself' is chosen solitude; Mark to judge. Points beyond the screen."
}
},
{
"id": "wordsworth-beauteous-evening",
"text": {
"en": "It is a beauteous Evening, calm and free;\nThe holy time is quiet as a Nun\nBreathless with adoration; the broad sun\nIs sinking down in its tranquillity;\nThe gentleness of heaven is on the Sea…"
},
"source": {
"work": "'It is a beauteous Evening, calm and free', lines 1-5",
"author": "William Wordsworth",
"tradition": "poetry",
"translation": null
},
"use": [
"sunset"
],
"tone": "quiet",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/8774/pg8774.txt",
"where": "Poems in Two Volumes (1807), vol. 1, Miscellaneous Sonnets no. 19, lines 1-5",
"publicDomain": "Author d. 1850; publ. 1807",
"note": "Line 5 ends with a colon (sentence continues 'Listen! the mighty Being is awake'); replaced by '…'. 'quiet as a Nun' is a religious image."
}
},
{
"id": "wordsworth-tintern-abbey",
"text": {
"en": "…On that best portion of a good man’s life;\nHis little, nameless, unremembered acts\nOf kindness and of love."
},
"source": {
"work": "Lines written a few miles above Tintern Abbey (1798), ll. 34-36",
"author": "William Wordsworth",
"tradition": "poetry",
"translation": null
},
"use": [
"sunset",
"comfort"
],
"tone": "tender",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/9622/pg9622.txt",
"where": "Lyrical Ballads (1798), 'Lines written a few miles above Tintern Abbey', ll. 34-36",
"publicDomain": "Author d. 1850; publ. 1798",
"note": "Source line starts with capital 'On that best portion' (verse capital); the excerpt keeps 'On'."
}
},
{
"id": "keats-to-autumn-3",
"text": {
"en": "Where are the songs of Spring? Ay, where are they?\nThink not of them, thou hast thy music too,--\nWhile barred clouds bloom the soft-dying day,\nAnd touch the stubble-plains with rosy hue…"
},
"source": {
"work": "To Autumn, stanza 3, lines 1-4",
"author": "John Keats",
"tradition": "poetry",
"translation": null
},
"use": [
"sunset",
"comfort"
],
"tone": "gentle",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/23684/pg23684.txt",
"where": "Poems Published in 1820 (Clarendon reprint 1909, ed. M. Robertson), 'To Autumn', stanza 3, ll. 1-4",
"publicDomain": "Author d. 1821; publ. 1820 (the 1909 reprint follows it)",
"note": "'--' in the source stands for an em dash; kept as in the Gutenberg text. Final ';' replaced by '…'."
}
},
{
"id": "rossetti-who-has-seen-the-wind",
"text": {
"en": "Who has seen the wind?\nNeither I nor you:\nBut when the leaves hang trembling\nThe wind is passing thro’.\nWho has seen the wind?\nNeither you nor I:\nBut when the trees bow down their heads\nThe wind is passing by."
},
"source": {
"work": "'Who has seen the wind?' (Sing-Song)",
"author": "Christina Rossetti",
"tradition": "poetry",
"translation": null
},
"use": [
"sunset"
],
"tone": "gentle",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/76703/pg76703.txt",
"where": "Sing-Song (1893 ed.; first publ. 1872), whole poem",
"publicDomain": "Author d. 1894; first publ. 1872",
"note": "Whole poem, both stanzas; stanza break collapsed to \\n. Fits the rose's wind-shade care."
}
},
{
"id": "rossetti-christmas-carol",
"text": {
"en": "What can I give Him,\nPoor as I am?\nIf I were a shepherd\nI would bring a lamb,\nIf I were a wise man\nI would do my part,--\nYet what I can I give Him,\nGive my heart."
},
"source": {
"work": "A Christmas Carol ('In the bleak mid-winter'), last stanza",
"author": "Christina Rossetti",
"tradition": "poetry",
"translation": null
},
"use": [
"sunset"
],
"tone": "tender",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/19188/pg19188.txt",
"where": "Poems (Boston: Little, Brown, 1906; Author's Edition 1876), 'A Christmas Carol', final stanza",
"publicDomain": "Author d. 1894; poem first publ. 1872",
"note": "Christian; 'Him' is Christ. Seasonal (Christmas) — perhaps limit to December."
}
},
{
"id": "shakespeare-sonnet-29",
"text": {
"en": "Haply I think on thee, and then my state,\nLike to the lark at break of day arising\nFrom sullen earth, sings hymns at heaven’s gate…"
},
"source": {
"work": "Sonnet 29, lines 10-12",
"author": "William Shakespeare",
"tradition": "poetry",
"translation": null
},
"use": [
"sunset",
"comfort"
],
"tone": "tender",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/1041/pg1041.txt",
"where": "Sonnet XXIX, lines 10-12",
"publicDomain": "Author d. 1616; publ. 1609",
"note": "Gutenberg's modern-spelling text. The sonnet's opening ('I all alone beweep my outcast state') is deliberately omitted."
}
},
{
"id": "tagore-gitanjali-63",
"text": {
"en": "Thou hast made me known to friends whom I knew not. Thou hast given me seats in homes not my own. Thou hast brought the distant near and made a brother of the stranger."
},
"source": {
"work": "Gitanjali 63",
"author": "Rabindranath Tagore",
"tradition": "poetry",
"translation": "Rabindranath Tagore (his own English), 1912"
},
"use": [
"sunset",
"comfort"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/7164/pg7164.txt",
"where": "Gitanjali (1912), poem 63, first paragraph",
"publicDomain": "Author d. 1941 (EU PD since 2012); English Gitanjali publ. 1912",
"note": "Devotional: 'Thou' is God. Prose-poem; source paragraph wrap joined with spaces."
}
},
{
"id": "tagore-gitanjali-69",
"text": {
"en": "The same stream of life that runs through my veins night and day runs through the world and dances in rhythmic measures."
},
"source": {
"work": "Gitanjali 69",
"author": "Rabindranath Tagore",
"tradition": "poetry",
"translation": "Rabindranath Tagore (his own English), 1912"
},
"use": [
"sunset"
],
"tone": "hopeful",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/7164/pg7164.txt",
"where": "Gitanjali (1912), poem 69, first paragraph",
"publicDomain": "Author d. 1941; publ. 1912",
"note": "Echoes the author's river-of-life image."
}
},
{
"id": "tagore-gitanjali-81",
"text": {
"en": "On many an idle day have I grieved over lost time. But it is never lost, my lord. Thou hast taken every moment of my life in thine own hands."
},
"source": {
"work": "Gitanjali 81",
"author": "Rabindranath Tagore",
"tradition": "poetry",
"translation": "Rabindranath Tagore (his own English), 1912"
},
"use": [
"sunset",
"comfort"
],
"tone": "tender",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/7164/pg7164.txt",
"where": "Gitanjali (1912), poem 81, first paragraph",
"publicDomain": "Author d. 1941; publ. 1912",
"note": "'it is never lost' is about time already lived, not a promise of what will happen; 'my lord' is God. Echoes 'progress never disappears'."
}
},
{
"id": "gibran-prophet-friendship-silence",
"text": {
"en": "And when he is silent your heart ceases not to listen to his heart; For without words, in friendship, all thoughts, all desires, all expectations are born and shared, with joy that is unacclaimed."
},
"source": {
"work": "The Prophet, 'On Friendship'",
"author": "Kahlil Gibran",
"tradition": "poetry",
"translation": null
},
"use": [
"sunset",
"comfort"
],
"tone": "tender",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/58585/pg58585.txt",
"where": "The Prophet (Knopf, 1923), 'Friendship', stanzas 5-6",
"publicDomain": "Author d. 1931 (EU PD since 2002); publ. 1923 (US PD since 2019)",
"note": "Short-line layout of the edition joined with spaces; the capital 'For' after ';' is verbatim (new stanza)."
}
},
{
"id": "gibran-prophet-friendship-mountain",
"text": {
"en": "When you part from your friend, you grieve not; For that which you love most in him may be clearer in his absence, as the mountain to the climber is clearer from the plain."
},
"source": {
"work": "The Prophet, 'On Friendship'",
"author": "Kahlil Gibran",
"tradition": "poetry",
"translation": null
},
"use": [
"sunset",
"comfort"
],
"tone": "tender",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/58585/pg58585.txt",
"where": "The Prophet (1923), 'Friendship', stanzas 7-8",
"publicDomain": "Author d. 1931; publ. 1923",
"note": "Same chapter as the other Gibran friendship lines, distinct stanza."
}
},
{
"id": "gibran-prophet-friendship-hours",
"text": {
"en": "For what is your friend that you should seek him with hours to kill? Seek him always with hours to live."
},
"source": {
"work": "The Prophet, 'On Friendship'",
"author": "Kahlil Gibran",
"tradition": "poetry",
"translation": null
},
"use": [
"sunset"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/58585/pg58585.txt",
"where": "The Prophet (1923), 'Friendship', second part, stanzas 3-4",
"publicDomain": "Author d. 1931; publ. 1923"
}
},
{
"id": "gibran-prophet-friendship-dew",
"text": {
"en": "And in the sweetness of friendship let there be laughter, and sharing of pleasures. For in the dew of little things the heart finds its morning and is refreshed."
},
"source": {
"work": "The Prophet, 'On Friendship'",
"author": "Kahlil Gibran",
"tradition": "poetry",
"translation": null
},
"use": [
"sunset",
"comfort"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/58585/pg58585.txt",
"where": "The Prophet (1923), 'Friendship', closing stanzas",
"publicDomain": "Author d. 1931; publ. 1923"
}
},
{
"id": "gibran-prophet-giving",
"text": {
"en": "You give but little when you give of your possessions. It is when you give of yourself that you truly give."
},
"source": {
"work": "The Prophet, 'On Giving'",
"author": "Kahlil Gibran",
"tradition": "poetry",
"translation": null
},
"use": [
"sunset"
],
"tone": "wise",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/58585/pg58585.txt",
"where": "The Prophet (1923), 'Giving', opening",
"publicDomain": "Author d. 1931; publ. 1923"
}
}
]
+229
View File
@@ -0,0 +1,229 @@
[
{
"id": "emerson-friendship-sincere",
"text": {
"en": "A friend is a person with whom I may be sincere. Before him I may think aloud."
},
"source": {
"work": "Essays: First Series, 'Friendship'",
"author": "Ralph Waldo Emerson",
"tradition": "prose",
"translation": null
},
"use": [
"sunset",
"comfort"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/2944/pg2944.txt",
"where": "Essays, First Series (1841), VI 'Friendship'",
"publicDomain": "Author d. 1882; publ. 1841"
}
},
{
"id": "emerson-nature-stars",
"text": {
"en": "If the stars should appear one night in a thousand years, how would men believe and adore … But every night come out these envoys of beauty, and light the universe with their admonishing smile."
},
"source": {
"work": "Nature, ch. I",
"author": "Ralph Waldo Emerson",
"tradition": "prose",
"translation": null
},
"use": [
"sunset"
],
"tone": "quiet",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/29433/pg29433.txt",
"where": "Nature (new ed. 1849; first publ. 1836), chapter I 'Nature'",
"publicDomain": "Author d. 1882; publ. 1836/1849",
"note": "Middle omission marked …: '; and preserve for many generations the remembrance of the city of God which had been shown!'"
}
},
{
"id": "thoreau-walden-time-stream",
"text": {
"en": "Time is but the stream I go a-fishing in. I drink at it; but while I drink I see the sandy bottom and detect how shallow it is. Its thin current slides away, but eternity remains."
},
"source": {
"work": "Walden, 'Where I Lived, and What I Lived For'",
"author": "Henry David Thoreau",
"tradition": "prose",
"translation": null
},
"use": [
"sunset"
],
"tone": "quiet",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/205/pg205.txt",
"where": "Walden (1854), 'Where I Lived, and What I Lived For', closing paragraph",
"publicDomain": "Author d. 1862; publ. 1854",
"note": "Echoes the river-of-time image."
}
},
{
"id": "thoreau-walden-bloom",
"text": {
"en": "There were times when I could not afford to sacrifice the bloom of the present moment to any work, whether of the head or hands. I love a broad margin to my life."
},
"source": {
"work": "Walden, 'Sounds'",
"author": "Henry David Thoreau",
"tradition": "prose",
"translation": null
},
"use": [
"sunset"
],
"tone": "gentle",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/205/pg205.txt",
"where": "Walden (1854), 'Sounds', second paragraph",
"publicDomain": "Author d. 1862; publ. 1854"
}
},
{
"id": "thoreau-walden-morning-star",
"text": {
"en": "Only that day dawns to which we are awake. There is more day to dawn. The sun is but a morning star."
},
"source": {
"work": "Walden, 'Conclusion' (last lines)",
"author": "Henry David Thoreau",
"tradition": "prose",
"translation": null
},
"use": [
"sunset"
],
"tone": "hopeful",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/205/pg205.txt",
"where": "Walden (1854), 'Conclusion', final three sentences of the book",
"publicDomain": "Author d. 1862; publ. 1854",
"note": "'There is more day to dawn' is open hope, not a promise to the reader; Mark to judge."
}
},
{
"id": "stevenson-el-dorado",
"text": {
"en": "Little do ye know your own blessedness; for to travel hopefully is a better thing than to arrive, and the true success is to labour."
},
"source": {
"work": "Virginibus Puerisque, 'El Dorado'",
"author": "Robert Louis Stevenson",
"tradition": "prose",
"translation": null
},
"use": [
"sunset"
],
"tone": "wise",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/386/pg386.txt",
"where": "Virginibus Puerisque (1881), 'El Dorado', end of the essay",
"publicDomain": "Author d. 1894; publ. 1881"
}
},
{
"id": "stevenson-idlers-candle",
"text": {
"en": "A happy man or woman is a better thing to find than a five-pound note. He or she is a radiating focus of goodwill; and their entrance into a room is as though another candle had been lighted."
},
"source": {
"work": "Virginibus Puerisque, 'An Apology for Idlers'",
"author": "Robert Louis Stevenson",
"tradition": "prose",
"translation": null
},
"use": [
"sunset"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/386/pg386.txt",
"where": "Virginibus Puerisque (1881), 'An Apology for Idlers'",
"publicDomain": "Author d. 1894; publ. 1881",
"note": "Source has double spaces after full stops; collapsed to single spaces (typography only)."
}
},
{
"id": "muir-sierra-june-13",
"text": {
"en": "Life seems neither long nor short, and we take no more heed to save time or make haste than do the trees and stars."
},
"source": {
"work": "My First Summer in the Sierra, June 13",
"author": "John Muir",
"tradition": "prose",
"translation": null
},
"use": [
"sunset"
],
"tone": "quiet",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/32540/pg32540.txt",
"where": "My First Summer in the Sierra (1911), journal entry 'June 13'",
"publicDomain": "Author d. 1914; publ. 1911"
}
},
{
"id": "muir-sierra-sunsets",
"text": {
"en": "The sunsets, when the trees stood hushed awaiting their good-night blessings. Divine, enduring, unwastable wealth."
},
"source": {
"work": "My First Summer in the Sierra, July 7",
"author": "John Muir",
"tradition": "prose",
"translation": null
},
"use": [
"sunset"
],
"tone": "quiet",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/32540/pg32540.txt",
"where": "My First Summer in the Sierra (1911), within the entry dated 'July 7'",
"publicDomain": "Author d. 1914; publ. 1911",
"note": "Two verbless sentences from a long reminiscing list; they stand alone. The same entry opens 'Rather weak and sickish' — not in the excerpt."
}
},
{
"id": "muir-sierra-hitched",
"text": {
"en": "When we try to pick out anything by itself, we find it hitched to everything else in the universe. One fancies a heart like our own must be beating in every crystal and cell…"
},
"source": {
"work": "My First Summer in the Sierra, July 27",
"author": "John Muir",
"tradition": "prose",
"translation": null
},
"use": [
"sunset"
],
"tone": "wise",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/32540/pg32540.txt",
"where": "My First Summer in the Sierra (1911), entry 'July 27'",
"publicDomain": "Author d. 1914; publ. 1911",
"note": "Second sentence continues ', and we feel like stopping to speak to the plants and animals as friendly fellow mountaineers.' — cut for length; Mark may prefer the full sentence (would be ~250 chars, over the cap)."
}
}
]
+163
View File
@@ -0,0 +1,163 @@
[
{
"id": "marcus-aurelius-3-10",
"text": {
"en": "…bear in mind that every man lives only this present time, which is an indivisible point, and that all the rest of his life is either past or it is uncertain."
},
"source": {
"work": "Meditations III.10",
"author": "Marcus Aurelius",
"tradition": "stoic",
"translation": "George Long, 1862"
},
"use": [
"sunset"
],
"tone": "wise",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/15877/pg15877.txt",
"where": "Book III, section 10",
"publicDomain": "Tr. George Long (1800-1879), first publ. 1862; author d. 180 AD",
"note": "Starts after 'Throwing away then all things, hold to these only which are few; and besides,'."
}
},
{
"id": "marcus-aurelius-6-7",
"text": {
"en": "Take pleasure in one thing and rest in it, in passing from one social act to another social act, thinking of God."
},
"source": {
"work": "Meditations VI.7",
"author": "Marcus Aurelius",
"tradition": "stoic",
"translation": "George Long, 1862"
},
"use": [
"sunset"
],
"tone": "quiet",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/15877/pg15877.txt",
"where": "Book VI, section 7",
"publicDomain": "Tr. George Long (1800-1879), first publ. 1862; author d. 180 AD"
}
},
{
"id": "marcus-aurelius-6-48",
"text": {
"en": "When thou wishest to delight thyself, think of the virtues of those who live with thee; for instance, the activity of one, and the modesty of another, and the liberality of a third, and some other good quality of a fourth."
},
"source": {
"work": "Meditations VI.48",
"author": "Marcus Aurelius",
"tradition": "stoic",
"translation": "George Long, 1862"
},
"use": [
"sunset"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/15877/pg15877.txt",
"where": "Book VI, section 48, first sentence",
"publicDomain": "Tr. George Long (1800-1879), first publ. 1862; author d. 180 AD"
}
},
{
"id": "marcus-aurelius-7-47",
"text": {
"en": "Look round at the courses of the stars, as if thou wert going along with them…"
},
"source": {
"work": "Meditations VII.47",
"author": "Marcus Aurelius",
"tradition": "stoic",
"translation": "George Long, 1862"
},
"use": [
"sunset"
],
"tone": "quiet",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/15877/pg15877.txt",
"where": "Book VII, section 47, first clause",
"publicDomain": "Tr. George Long (1800-1879), first publ. 1862; author d. 180 AD",
"note": "Sentence continues '; and constantly consider the changes of the elements…'; cut there."
}
},
{
"id": "epictetus-discourses-1-15",
"text": {
"en": "Nothing great, said Epictetus, is produced suddenly, since not even the grape or the fig is. If you say to me now that you want a fig, I will answer to you that it requires time: let it flower first, then put forth fruit, and then ripen."
},
"source": {
"work": "Discourses I.15 (What Philosophy Promises)",
"author": "Epictetus",
"tradition": "stoic",
"translation": "George Long, 1877"
},
"use": [
"sunset",
"comfort"
],
"tone": "wise",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/10661/pg10661.txt",
"where": "Discourses Book I, ch. 15 'What Philosophy Promises' (Gutenberg #10661 is Long's selection; chapter heading present)",
"publicDomain": "Tr. George Long (1800-1879), Discourses first publ. 1877; author d. c. 135 AD",
"note": "Context: a man asks how to keep his peace while his brother is angry with him."
}
},
{
"id": "seneca-shortness-of-life-2",
"text": {
"en": "Why do we complain of Nature? she has dealt kindly with us. Life is long enough, if you know how to use it."
},
"source": {
"work": "On the Shortness of Life (De Brevitate Vitae) II",
"author": "Lucius Annaeus Seneca",
"tradition": "stoic",
"translation": "Aubrey Stewart, 1889"
},
"use": [
"sunset"
],
"tone": "wise",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/64576/pg64576.txt",
"where": "Dialogues Book X 'Of the Shortness of Life', ch. II, opening",
"publicDomain": "Tr. Aubrey Stewart (1844-1918), publ. London: G. Bell, 1889; author d. 65 AD",
"note": "Lower-case 'she' after the question mark is verbatim."
}
},
{
"id": "seneca-tranquillity-7",
"text": {
"en": "…nothing delights the mind so much as faithful and pleasant friendship: what a blessing it is when there is one … whose very sight delights you!"
},
"source": {
"work": "On Peace of Mind (De Tranquillitate Animi) VII",
"author": "Lucius Annaeus Seneca",
"tradition": "stoic",
"translation": "Aubrey Stewart, 1889"
},
"use": [
"sunset",
"comfort"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/64576/pg64576.txt",
"where": "Dialogues Book IX 'Of Peace of Mind', ch. VII",
"publicDomain": "Tr. Aubrey Stewart (1844-1918), publ. London: G. Bell, 1889; author d. 65 AD",
"note": "Starts after 'Yet'. Middle omission (marked …) drops 'whose breast is ready to receive all your secrets with safety, whose knowledge of your actions you fear less than your own conscience, whose conversation removes your anxieties, whose advice assists your plans, whose cheerfulness dispels your gloom,'. The Gutenberg page marker '{266}' inside the sentence was removed."
}
}
]
+48
View File
@@ -0,0 +1,48 @@
[
{
"id": "sadi-gulistan-1-10",
"text": {
"en": "The sons of Adam are members one of another, for in their creation they have a common origin. If the vicissitudes of fortune involve one member in pain, all the other members will feel a sympathy."
},
"source": {
"work": "Gulistan, ch. I, story 10",
"author": "Sa'di",
"tradition": "sufi",
"translation": "James Ross, 1823"
},
"use": [
"sunset"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/13060/pg13060.txt",
"where": "Gulistan, Chapter I 'Of the Customs of Kings', story X",
"publicDomain": "Tr. James Ross (1759-1831), first publ. 1823; reprinted in 'The Persian Literature' vol. 2 (Colonial Press, 1900); author d. 1291/92",
"note": "The famous 'Bani Adam' verses in Ross's prose rendering."
}
},
{
"id": "sadi-gulistan-2-26",
"text": {
"en": "It is not the nightingale that alone serenades his rose; for every thorn on the rose-bush is a tongue in his or God's praise!"
},
"source": {
"work": "Gulistan, ch. II, story 26",
"author": "Sa'di",
"tradition": "sufi",
"translation": "James Ross, 1823"
},
"use": [
"sunset"
],
"tone": "gentle",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/13060/pg13060.txt",
"where": "Gulistan, Chapter II 'Of the Morals of Dervishes', story XXVI (end of a quotation)",
"publicDomain": "Tr. James Ross (1759-1831), first publ. 1823; reprinted in 'The Persian Literature' vol. 2 (Colonial Press, 1900); author d. 1291/92",
"note": "A rose with thorns — the game's own rose. 'his or God's' looks like an editor's gloss in this reprint; the closing quotation mark of the source is dropped. Uses 'alone' in the sense of 'only'."
}
}
]
+94
View File
@@ -0,0 +1,94 @@
[
{
"id": "tao-te-ching-8",
"text": {
"en": "The highest excellence is like (that of) water. The excellence of water appears in its benefiting all things…"
},
"source": {
"work": "Tao Te Ching, ch. 8",
"author": "Laozi",
"tradition": "taoist",
"translation": "James Legge, 1891"
},
"use": [
"sunset"
],
"tone": "quiet",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/216/pg216.txt",
"where": "Chapter 8, verse 1, first two sentences",
"publicDomain": "Tr. James Legge (1815-1897), Sacred Books of the East vol. 39, 1891",
"note": "Legge's parentheses '(that of)' are his own and are kept verbatim; sentence continues ', and in its occupying… the low place which all men dislike'."
}
},
{
"id": "tao-te-ching-15",
"text": {
"en": "Who can (make) the muddy water (clear)? Let it be still, and it will gradually become clear."
},
"source": {
"work": "Tao Te Ching, ch. 15",
"author": "Laozi",
"tradition": "taoist",
"translation": "James Legge, 1891"
},
"use": [
"sunset",
"comfort"
],
"tone": "gentle",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/216/pg216.txt",
"where": "Chapter 15, verse 3, first two sentences",
"publicDomain": "Tr. James Legge (1815-1897), Sacred Books of the East vol. 39, 1891",
"note": "OUTCOME CHECK: 'it will gradually become clear' is said of water left still — a natural image, not a promise to the reader; Mark to judge."
}
},
{
"id": "tao-te-ching-64",
"text": {
"en": "The tree which fills the arms grew from the tiniest sprout; the tower of nine storeys rose from a (small) heap of earth; the journey of a thousand li commenced with a single step."
},
"source": {
"work": "Tao Te Ching, ch. 64",
"author": "Laozi",
"tradition": "taoist",
"translation": "James Legge, 1891"
},
"use": [
"sunset"
],
"tone": "hopeful",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/216/pg216.txt",
"where": "Chapter 64, verse 2",
"publicDomain": "Tr. James Legge (1815-1897), Sacred Books of the East vol. 39, 1891"
}
},
{
"id": "chuang-tzu-17-hao",
"text": {
"en": "Chuang Tzŭ and Hui Tzŭ had strolled on to the bridge over the Hao, when the former observed, \"See how the minnows are darting about! That is the pleasure of fishes.\""
},
"source": {
"work": "Chuang Tzu, ch. XVII (Autumn Floods), the bridge over the Hao",
"author": "Zhuangzi",
"tradition": "taoist",
"translation": "Herbert A. Giles, 1889"
},
"use": [
"sunset"
],
"tone": "warm",
"promisesOutcome": false,
"check": {
"url": "https://www.gutenberg.org/cache/epub/59709/pg59709.txt",
"where": "Chapter XVII, final anecdote (bridge over the Hao)",
"publicDomain": "Tr. Herbert A. Giles (1845-1935), London: Bernard Quaritch, 1889 (title page in the Gutenberg file)",
"note": "Source uses straight double quotes and the breve in 'Tzŭ'; kept."
}
}
]
+21 -3
View File
@@ -7,11 +7,29 @@ Each file is an array of entries in the shape of
**It is empty on purpose.** Every entry carries `verifiedBy` and `verifiedAt`, which **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 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 cannot make that check, so agents do not add entries here.
list elsewhere for the author to verify.
**Candidates** wait in [`../candidates/`](../candidates/), one file per tradition, in
the same shape without `publicDomain`, `verifiedBy` and `verifiedAt`, and with a
`check`: the page to read the sentence on, where in the work it is, and why it is in
the public domain. `pnpm validate:library` holds every candidate to every library
rule, so none would fail once verified.
**To verify** (the author only): read each sentence at its `check.url`, confirm the
words and the public-domain reason, then
```bash
pnpm library:verify ps-118-24 cicero-amicitia-22 --by Mark
```
It moves those candidates into the library file of the same name, with your name and
today's date, and refuses (moving nothing) if the library would then fail. Commit the
result. A line the author writes for Rosea goes straight into `rosea.json`, with
`"tradition": "rosea"`.
Run `pnpm validate:library` after any change. The validator also runs every file Run `pnpm validate:library` after any change. The validator also runs every file
in [`../fixtures/`](../fixtures/), and **fails if any fixture passes**. in [`../fixtures/`](../fixtures/), and **fails if any fixture passes**. The app's
build runs it first, so the app only ever ships what passed.
Before the first release: at least 365 entries with `"use": ["sunset", …]`, so that Before the first release: at least 365 entries with `"use": ["sunset", …]`, so that
no sunset sentence repeats within a year. no sunset sentence repeats within a year.
+18
View File
@@ -0,0 +1,18 @@
[
{
"id": "e2e-first",
"text": { "en": "An e2e fixture sentence, not a real one." },
"source": { "work": "Fixture 1", "author": null, "tradition": "fixture", "translation": null, "publicDomain": true, "verifiedBy": "e2e", "verifiedAt": "2026-11-01" },
"use": ["sunset"],
"tone": "gentle",
"promisesOutcome": false
},
{
"id": "e2e-second",
"text": { "en": "A second e2e fixture sentence." },
"source": { "work": "Fixture 2", "author": "A Writer", "tradition": "fixture", "translation": null, "publicDomain": true, "verifiedBy": "e2e", "verifiedAt": "2026-11-01" },
"use": ["sunset"],
"tone": "gentle",
"promisesOutcome": false
}
]
+91
View File
@@ -0,0 +1,91 @@
import AxeBuilder from '@axe-core/playwright';
import { expect, test, type Page } from '@playwright/test';
import { en } from '@rosea/ui/copy';
import { execSync } from 'node:child_process';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { startStaticServer, type StaticServer } from './static-server.js';
import { storedCare } from './stored.js';
import fixture from './fixtures/library/fixture.json' with { type: 'json' };
/**
* The rose's folded petal (.agents/features/day-sentence.md), in the BUILT app.
*
* The shipped library is empty until the author verifies sentences, so the main
* build can only show that there is no petal. This spec also builds the app a second
* time, with a fixture library (ROSEA_LIBRARY_DIR, P5), into a folder of its own, and
* serves that. The second build passes through the same validate:library step.
*/
const ROOT = fileURLToPath(new URL('..', import.meta.url));
const MORNING = Date.parse('2026-03-01T10:00:00+01:00');
const texts = fixture.map((s) => s.text.en);
test.use({ timezoneId: 'Europe/Prague', locale: 'en-US' });
let server: StaticServer;
test.beforeEach(async () => {
server = await startStaticServer();
});
test.afterEach(async () => {
await server.close();
});
async function open(page: Page): Promise<void> {
await page.clock.setFixedTime(MORNING);
await page.goto(server.url);
await expect(page.getByRole('button', { name: en.rose.water })).toBeVisible();
}
test('with the shipped library still empty, she holds no petal and says nothing about one', async ({ page }) => {
await open(page);
await expect(page.getByRole('button', { name: en.rose.petal.open })).toHaveCount(0);
await expect(page.getByText(en.rose.petal.waiting)).toHaveCount(0);
});
test.describe('with a fixture library', () => {
let dist: string;
test.beforeAll(() => {
dist = mkdtempSync(join(tmpdir(), 'rosea-petal-'));
// The same build the player gets, with the fixture library in place of the real one.
execSync(`pnpm --filter @rosea/app run build --outDir "${dist}" --emptyOutDir`, {
cwd: ROOT,
env: { ...process.env, ROSEA_LIBRARY_DIR: 'e2e/fixtures/library' },
stdio: 'pipe'
});
});
test.afterAll(() => {
rmSync(dist, { recursive: true, force: true });
});
test.beforeEach(() => server.serveFrom(dist));
test('open her petal: the words and their source; a reload keeps it open, and no second one today', async ({ page }) => {
await open(page);
await page.getByRole('button', { name: en.rose.petal.open }).click();
const words = page.locator('blockquote');
await expect(words).toHaveCount(1);
const said = (await words.textContent()) ?? '';
expect(texts).toContain(said);
await storedCare(page, 1);
await page.reload();
await expect(page.getByRole('button', { name: en.rose.petal.today })).toHaveAttribute('aria-expanded', 'true');
await expect(page.locator('blockquote')).toHaveText(said);
await expect(page.getByRole('button', { name: en.rose.petal.open })).toHaveCount(0);
// Tomorrow, the next one is folded.
await page.clock.setFixedTime(MORNING + 24 * 3_600_000);
await page.reload();
await expect(page.getByRole('button', { name: en.rose.petal.open })).toBeVisible();
});
test('the folded and the open petal have no accessibility violations', async ({ page }) => {
await open(page);
await expect(page.getByRole('button', { name: en.rose.petal.open })).toBeVisible();
expect((await new AxeBuilder({ page }).analyze()).violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
await page.getByRole('button', { name: en.rose.petal.open }).click();
await expect(page.locator('blockquote')).toBeVisible();
expect((await new AxeBuilder({ page }).analyze()).violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
});
});
+1 -1
View File
@@ -7,7 +7,7 @@ import { defineConfig, devices } from '@playwright/test';
*/ */
export default defineConfig({ export default defineConfig({
testDir: '.', testDir: '.',
testMatch: /(shell|update)\.spec\.ts/, testMatch: /(shell|update|petal)\.spec\.ts/,
fullyParallel: false, fullyParallel: false,
workers: 1, workers: 1,
retries: 0, retries: 0,
+1 -1
View File
@@ -253,7 +253,7 @@ test.describe('keep her safe, in Prague at 08:00 on 1 March 2026', () => {
} finally { } finally {
await first.close(); await first.close();
} }
expect(JSON.parse(saved)).toMatchObject({ format: 'rosea-rose', version: 1 }); expect(JSON.parse(saved)).toMatchObject({ format: 'rosea-rose', version: 2 });
expect(saved).not.toMatch(/Brno|privateKey/); expect(saved).not.toMatch(/Brno|privateKey/);
// A fresh profile: the shape of an evicted garden, or a new phone. // A fresh profile: the shape of an evicted garden, or a new phone.
+1
View File
@@ -16,6 +16,7 @@
"test:e2e": "pnpm guard:cpu && turbo run build --filter=@rosea/app && playwright test --config=e2e/playwright.config.ts", "test:e2e": "pnpm guard:cpu && turbo run build --filter=@rosea/app && playwright test --config=e2e/playwright.config.ts",
"test:offline": "pnpm guard:cpu && turbo run build --filter=@rosea/app && playwright test --config=e2e/playwright.offline.config.ts", "test:offline": "pnpm guard:cpu && turbo run build --filter=@rosea/app && playwright test --config=e2e/playwright.offline.config.ts",
"validate:library": "tsx scripts/validate-library.ts", "validate:library": "tsx scripts/validate-library.ts",
"library:verify": "tsx scripts/verify-sentences.ts",
"lint:copy": "tsx scripts/lint-copy.ts", "lint:copy": "tsx scripts/lint-copy.ts",
"art:board": "tsx tools/art-prep/src/cli-board.ts", "art:board": "tsx tools/art-prep/src/cli-board.ts",
"art:accept": "tsx tools/art-prep/src/cli-accept.ts", "art:accept": "tsx tools/art-prep/src/cli-accept.ts",
+1
View File
@@ -9,6 +9,7 @@
"exports": { "exports": {
".": "./src/index.ts", ".": "./src/index.ts",
"./validate": "./src/validator.ts", "./validate": "./src/validator.ts",
"./candidates": "./src/candidates.ts",
"./places": "./src/places/places.ts", "./places": "./src/places/places.ts",
"./guess": "./src/places/guess.ts" "./guess": "./src/places/guess.ts"
}, },
+102
View File
@@ -0,0 +1,102 @@
/**
* Candidate sentences and their verification (.agents/features/day-sentence.md P8).
*
* An agent may propose a sentence; only a person may say it was checked
* (phase0-workspace.md D4). A candidate is a library entry without `publicDomain`,
* `verifiedBy` and `verifiedAt`, and with a `check`: where to read it. It is held to
* every library rule but verification, so the author is never asked to verify a
* line that would fail anyway.
*
* `verifyCandidates` is what `pnpm library:verify <id…> --by <name>` does. It is the
* author's command. **Agents never run it.**
*/
import { validateEntry, validateLibrary, type Problem } from './validator.js';
/** A file's worth of entries: its name (`biblical.json`) and what it holds. */
export type Files = Readonly<Record<string, readonly unknown[]>>;
const isRecord = (x: unknown): x is Record<string, unknown> => typeof x === 'object' && x !== null && !Array.isArray(x);
const idOf = (x: unknown): string => (isRecord(x) && typeof x['id'] === 'string' ? x['id'] : '(no id)');
/** The library entry a candidate becomes once a person has checked it. */
export function asVerified(candidate: unknown, by: string, day: string): unknown {
if (!isRecord(candidate) || !isRecord(candidate['source'])) return candidate;
const { check: _check, ...entry } = candidate;
return { ...entry, source: { ...candidate['source'], publicDomain: true, verifiedBy: by, verifiedAt: day } };
}
/** Every reason a candidate could not become a library entry, even once verified. */
export function validateCandidate(candidate: unknown): Problem[] {
const id = idOf(candidate);
const problems: Problem[] = [];
const check = isRecord(candidate) ? candidate['check'] : undefined;
if (!isRecord(check) || typeof check['url'] !== 'string' || !/^https:\/\//.test(check['url']) || typeof check['where'] !== 'string' || typeof check['publicDomain'] !== 'string') {
problems.push({ id, rule: 'schema', message: 'a candidate needs check.url (https), check.where and check.publicDomain, so the person verifying knows where to read it' });
}
const source = isRecord(candidate) ? candidate['source'] : undefined;
for (const field of ['publicDomain', 'verifiedBy', 'verifiedAt']) {
if (isRecord(source) && field in source) {
problems.push({ id, rule: 'schema', message: `a candidate must not carry source.${field}: only the person who verifies it adds that` });
}
}
return [...problems, ...validateEntry(asVerified(candidate, 'candidate', '2000-01-01'))];
}
/** Every candidate, and ids unique across the candidates and the library together. */
export function validateCandidates(candidates: readonly unknown[], library: readonly unknown[]): Problem[] {
const problems = candidates.flatMap(validateCandidate);
const inLibrary = new Set(library.map(idOf));
const seen = new Set<string>();
for (const c of candidates) {
const id = idOf(c);
if (inLibrary.has(id)) problems.push({ id, rule: 'duplicate-id', message: `id '${id}' is already in the library` });
else if (seen.has(id)) problems.push({ id, rule: 'duplicate-id', message: `id '${id}' is proposed more than once` });
seen.add(id);
}
return problems;
}
export type VerifyResult =
| { readonly ok: true; readonly library: Files; readonly candidates: Files; readonly moved: readonly string[] }
| { readonly ok: false; readonly problems: readonly string[] };
/**
* Moves the candidates named by `ids` into the library, as checked by `by` on `day`.
* Each lands in the library file named like its candidate file. Refuses, and moves
* nothing, if an id is unknown, the name is empty, or the library would fail.
*/
export function verifyCandidates(p: {
readonly candidates: Files;
readonly library: Files;
readonly ids: readonly string[];
readonly by: string;
readonly day: string;
}): VerifyResult {
const by = p.by.trim();
if (by === '' || by.toLowerCase() === 'candidate') return { ok: false, problems: ['--by needs the name of the person who checked the sentences'] };
if (!/^\d{4}-\d{2}-\d{2}$/.test(p.day)) return { ok: false, problems: [`not a day: '${p.day}'`] };
if (p.ids.length === 0) return { ok: false, problems: ['name at least one candidate id'] };
const wanted = new Set(p.ids);
const library: Record<string, unknown[]> = Object.fromEntries(Object.entries(p.library).map(([f, e]) => [f, [...e]]));
const candidates: Record<string, unknown[]> = {};
const moved: string[] = [];
for (const [file, entries] of Object.entries(p.candidates)) {
candidates[file] = [];
for (const c of entries) {
const id = idOf(c);
if (wanted.has(id) && !moved.includes(id)) {
(library[file] ??= []).push(asVerified(c, by, p.day));
moved.push(id);
} else {
candidates[file].push(c);
}
}
}
const unknown = p.ids.filter((id) => !moved.includes(id));
if (unknown.length > 0) return { ok: false, problems: unknown.map((id) => `no candidate '${id}'`) };
const problems = validateLibrary(Object.values(library).flat()).map((x) => `${x.id} [${x.rule}] ${x.message}`);
if (problems.length > 0) return { ok: false, problems };
return { ok: true, library, candidates, moved };
}
+17 -1
View File
@@ -49,7 +49,23 @@ export const PUBLIC_DOMAIN_TRANSLATIONS: ReadonlySet<string> = new Set([
'ASV', // American Standard Version, 1901 'ASV', // American Standard Version, 1901
'Douay-Rheims', // 1582–1610, Challoner revision 1752 'Douay-Rheims', // 1582–1610, Challoner revision 1752
'YLT', // Young's Literal Translation, 1862 'YLT', // Young's Literal Translation, 1862
'WEB' // World English Bible, dedicated to the public domain 'WEB', // World English Bible, dedicated to the public domain
// Added 2026-11-02 with the first candidates (day-sentence.md P8). Each is the edition
// on Project Gutenberg; translator dead before 1956 (EU life + 70) and the edition
// first published before 1931 (US). Death years from the Gutenberg catalogue,
// cross-checked by web search. The author still checks each sentence.
'George Long, 1862', // Marcus Aurelius; d. 1879
'George Long, 1877', // Epictetus; d. 1879
'Evelyn S. Shuckburgh, 1900', // Cicero; d. 1906
'Andrew P. Peabody, 1887', // Cicero, De Amicitia; d. 1893
'Aubrey Stewart, 1889', // Seneca, Minor Dialogues; d. 1918
'James Legge, 1891', // Tao Te Ching; d. 1897
'Herbert A. Giles, 1889', // Chuang Tzu; d. 1935
'F. Max Müller, 1881', // Dhammapada; d. 1900
'James Ross, 1823', // Sa'di, Gulistan; d. 1831
'William Benham, 1886', // Imitation of Christ; d. 1910
'Grace Warrack, 1901', // Julian of Norwich; d. 1932
'Rabindranath Tagore (his own English), 1912' // Gitanjali; d. 1941
]); ]);
/** /**
+87
View File
@@ -0,0 +1,87 @@
import { describe, expect, it } from 'vitest';
import { asVerified, validateCandidate, validateCandidates, verifyCandidates } from '../src/candidates.js';
import { validateEntry } from '../src/validator.js';
const candidate = (id: string, over: Record<string, unknown> = {}): Record<string, unknown> => ({
id,
text: { en: 'Fixture text for a candidate, not a real sentence.' },
source: { work: 'Fixture 1:1', author: null, tradition: 'biblical', translation: 'KJV' },
use: ['sunset'],
tone: 'gentle',
promisesOutcome: false,
check: { url: 'https://example.org/fixture', where: 'chapter 1, verse 1', publicDomain: 'KJV, 1611/1769' },
...over
});
describe('a candidate (day-sentence.md P8)', () => {
it('becomes a valid library entry once a person has checked it, with no check field left', () => {
const entry = asVerified(candidate('fx-1'), 'Mark', '2026-11-02') as Record<string, unknown>;
expect(validateEntry(entry)).toEqual([]);
expect(entry).not.toHaveProperty('check');
expect(entry['source']).toMatchObject({ publicDomain: true, verifiedBy: 'Mark', verifiedAt: '2026-11-02' });
});
it('passes when it would pass the library', () => {
expect(validateCandidate(candidate('fx-1'))).toEqual([]);
});
it('is held to every library rule: length, forbidden words, promises, translations', () => {
expect(validateCandidate(candidate('fx-long', { text: { en: 'x'.repeat(241) } })).map((p) => p.rule)).toContain('too-long');
expect(validateCandidate(candidate('fx-word', { text: { en: 'A lonely road.' } })).map((p) => p.rule)).toContain('forbidden-word');
expect(validateCandidate(candidate('fx-promise', { text: { en: 'Everything will be well.' } })).map((p) => p.rule)).toContain('promises-outcome');
expect(
validateCandidate(candidate('fx-niv', { source: { work: 'Fixture', author: null, tradition: 'biblical', translation: 'NIV' } })).map((p) => p.rule)
).toContain('translation-under-copyright');
});
it('needs a check that says where to read it', () => {
const { check: _, ...noCheck } = candidate('fx-1');
expect(validateCandidate(noCheck)[0]?.message).toMatch(/check\.url/);
expect(validateCandidate(candidate('fx-1', { check: { url: 'http://example.org', where: 'x', publicDomain: 'x' } }))[0]?.message).toMatch(/https/);
});
it('may not say it was verified: only the person who verifies adds that', () => {
for (const field of ['publicDomain', 'verifiedBy', 'verifiedAt']) {
const c = candidate('fx-1', { source: { work: 'F', author: null, tradition: 'biblical', translation: 'KJV', [field]: field === 'publicDomain' ? true : 'x' } });
expect(validateCandidate(c).map((p) => p.message).join(' '), field).toMatch(new RegExp(`source\\.${field}`));
}
});
it('may not reuse an id the library or another candidate has', () => {
const library = [asVerified(candidate('fx-1'), 'Mark', '2026-11-01')];
const problems = validateCandidates([candidate('fx-1'), candidate('fx-2'), candidate('fx-2')], library);
expect(problems.map((p) => `${p.id} ${p.rule}`)).toEqual(['fx-1 duplicate-id', 'fx-2 duplicate-id']);
});
});
describe('library:verify — the author’s command', () => {
const files = { candidates: { 'biblical.json': [candidate('fx-1'), candidate('fx-2')], 'poetry.json': [candidate('fx-3', { source: { work: 'P', author: 'A Poet', tradition: 'poetry', translation: null } })] }, library: {} };
it('moves the named candidates into the library file of the same name, stamped with the name and the day', () => {
const result = verifyCandidates({ ...files, ids: ['fx-1', 'fx-3'], by: 'Mark', day: '2026-11-02' });
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.moved).toEqual(['fx-1', 'fx-3']);
expect(Object.keys(result.library).sort()).toEqual(['biblical.json', 'poetry.json']);
expect(result.library['biblical.json']).toEqual([asVerified(candidate('fx-1'), 'Mark', '2026-11-02')]);
expect(result.candidates['biblical.json']).toEqual([candidate('fx-2')]);
expect(result.candidates['poetry.json']).toEqual([]);
});
it('adds to what the library already holds, never replaces it', () => {
const kept = asVerified(candidate('old-1'), 'Mark', '2026-11-01');
const result = verifyCandidates({ ...files, library: { 'biblical.json': [kept] }, ids: ['fx-2'], by: 'Mark', day: '2026-11-02' });
expect(result.ok && result.library['biblical.json']).toEqual([kept, asVerified(candidate('fx-2'), 'Mark', '2026-11-02')]);
});
it('refuses, moving nothing, without a person’s name, with an unknown id, or with a line the library would refuse', () => {
expect(verifyCandidates({ ...files, ids: ['fx-1'], by: ' ', day: '2026-11-02' })).toMatchObject({ ok: false });
expect(verifyCandidates({ ...files, ids: ['fx-1'], by: 'candidate', day: '2026-11-02' })).toMatchObject({ ok: false });
expect(verifyCandidates({ ...files, ids: [], by: 'Mark', day: '2026-11-02' })).toMatchObject({ ok: false });
expect(verifyCandidates({ ...files, ids: ['fx-1', 'nope'], by: 'Mark', day: '2026-11-02' })).toEqual({ ok: false, problems: ["no candidate 'nope'"] });
const bad = { candidates: { 'biblical.json': [candidate('fx-bad', { text: { en: 'A lonely road.' } })] }, library: {} };
const result = verifyCandidates({ ...bad, ids: ['fx-bad'], by: 'Mark', day: '2026-11-02' });
expect(result.ok).toBe(false);
expect(!result.ok && result.problems.join(' ')).toMatch(/forbidden-word/);
});
});
+3
View File
@@ -4,3 +4,6 @@ export {
type Judged, type Mood, type Needs, type RoseKeys, type RoseNow, type Stage, type Trend type Judged, type Mood, type Needs, type RoseKeys, type RoseNow, type Stage, type Trend
} from './rose/rose.js'; } from './rose/rose.js';
export { invitation, nextInvitation, sunDay, type NamedPlace, type Place, type SunDay } from './sun/sun.js'; export { invitation, nextInvitation, sunDay, type NamedPlace, type Place, type SunDay } from './sun/sun.js';
export {
goodMoment, newOpened, openedIdentity, PETAL, petalAt, petalOrder, sentenceOpened, type PetalNow, type PetalSentence
} from './petal/petal.js';
+142
View File
@@ -0,0 +1,142 @@
/**
* The rose's folded petal: the day's sentence (.agents/features/day-sentence.md).
*
* Pure: the log, the library, the clock and the place are parameters. Which sentence
* waits is a function of what was opened, never of the days that passed, so a
* petal not opened is never lost (CLAUDE.md §5.5) and a gap is never shown.
*/
import type { HopeSentence, SentenceOpened } from '@rosea/schema';
import { seeded, type RoseKeys } from '../rose/rose.js';
import { nextInvitation, type Place } from '../sun/sun.js';
import { daysBetween, localDay, type LocalDay } from '../time/localDay.js';
/** The petal's tuning. The author's to change (day-sentence.md P3, P4). */
export const PETAL = {
/** The last petal opened at most this many local days ago: she also remembers an earlier one. */
nearDays: 3,
/** The good moment: this long before the sun module's invitation… */
beforeMinutes: 60,
/** …until this long after it. */
afterMinutes: 60
} as const;
const MINUTE = 60_000;
/** What the petal needs to know of a library sentence. */
export interface PetalSentence {
readonly id: HopeSentence['id'];
readonly use: HopeSentence['use'];
readonly source: { readonly verifiedAt: HopeSentence['source']['verifiedAt'] };
}
export type PetalNow =
/** No sunset sentence in the library: no petal, and nothing said about one. */
| { readonly kind: 'none' }
| { readonly kind: 'folded'; readonly id: string }
/** Opened today. `remembered` is an earlier one she recalls, on a nearby day (P3). */
| { readonly kind: 'open'; readonly id: string; readonly remembered: string | null };
const byKeys = (keys: RoseKeys): ReadonlySet<string> => new Set(typeof keys === 'string' ? [keys] : keys);
/**
* The one order the petals come in (P1): sunset sentences by the day they were
* verified, then by a hash of the id, so the first days are not all one book and a
* sentence verified later always comes after the ones already there.
*/
export function petalOrder(sentences: readonly PetalSentence[]): string[] {
const seen = new Set<string>();
const sunset: { id: string; day: LocalDay; mix: number }[] = [];
for (const s of sentences) {
if (!s.use.includes('sunset') || seen.has(s.id)) continue;
seen.add(s.id);
sunset.push({ id: s.id, day: s.source.verifiedAt, mix: seeded(s.id, s.source.verifiedAt, 'petal') });
}
sunset.sort((a, b) => (a.day < b.day ? -1 : a.day > b.day ? 1 : a.mix - b.mix || (a.id < b.id ? -1 : 1)));
return sunset.map((s) => s.id);
}
/** The first opening of each local day, in the order they happened (P2). Later ones that day changed nothing. */
function dayOpenings(opened: readonly SentenceOpened[], keys: RoseKeys): SentenceOpened[] {
const mine = byKeys(keys);
const sorted = opened.filter((e) => mine.has(e.from)).sort((a, b) => a.ts - b.ts);
const firstOfDay = new Map<LocalDay, SentenceOpened>();
for (const e of sorted) if (!firstOfDay.has(e.localDay)) firstOfDay.set(e.localDay, e);
return [...firstOfDay.values()];
}
/** The rose's petal at `now`, for the rose named by `keys`. */
export function petalAt(
sentences: readonly PetalSentence[],
opened: readonly SentenceOpened[],
keys: RoseKeys,
now: number,
timeZone: string
): PetalNow {
const today = localDay(now, timeZone);
const days = dayOpenings(opened, keys);
const order = petalOrder(sentences);
const todays = days.find((e) => e.localDay === today);
if (todays !== undefined) {
const before = days.filter((e) => e.localDay < today);
const previous = before.at(-1);
let remembered: string | null = null;
if (previous !== undefined && daysBetween(previous.localDay, today) <= PETAL.nearDays) {
const known = new Set(order);
const earlier = [...new Set(before.map((e) => e.messageId))].filter((id) => id !== todays.messageId && known.has(id));
if (earlier.length > 0) remembered = earlier[Math.floor(seeded(todays.from, today, 'remember') * earlier.length)] ?? null;
}
return { kind: 'open', id: todays.messageId, remembered };
}
if (order.length === 0) return { kind: 'none' };
const lastOpened = new Map<string, number>();
for (const e of days) lastOpened.set(e.messageId, e.ts);
const never = order.find((id) => !lastOpened.has(id));
if (never !== undefined) return { kind: 'folded', id: never };
// Every one has been opened: the one opened longest ago comes round again.
let oldest = order[0]!;
for (const id of order) if (lastOpened.get(id)! < lastOpened.get(oldest)!) oldest = id;
return { kind: 'folded', id: oldest };
}
/**
* The best moment to open the petal (P4): around the sun module's invitation, the
* sunset, or in polar day the lowest light, in polar night the brightest twilight.
* It changes only what she says.
*/
export function goodMoment(now: number, place: Place): boolean {
const { at } = nextInvitation(now - PETAL.afterMinutes * MINUTE, place);
return now >= at - PETAL.beforeMinutes * MINUTE;
}
/** The event the log keeps when the petal is opened. The day comes from the one module that computes days. */
export function sentenceOpened(p: {
readonly now: number;
readonly timeZone: string;
readonly from: string;
readonly messageId: string;
readonly clientVersion: string;
}): SentenceOpened {
return {
kind: 'sentence-opened', ts: Math.round(p.now), localDay: localDay(p.now, p.timeZone),
from: p.from, messageId: p.messageId, clientVersion: p.clientVersion
};
}
/** What makes two openings the same: the same moment, rose and sentence. */
export const openedIdentity = (e: SentenceOpened): string => `${e.ts}|${e.from}|${e.messageId}`;
/** The openings in `incoming` that `existing` does not hold yet (bringing a rose back twice adds nothing twice). */
export function newOpened(existing: readonly SentenceOpened[], incoming: readonly SentenceOpened[]): SentenceOpened[] {
const seen = new Set(existing.map(openedIdentity));
const out: SentenceOpened[] = [];
for (const e of incoming) {
const id = openedIdentity(e);
if (!seen.has(id)) {
seen.add(id);
out.push(e);
}
}
return out;
}
+244
View File
@@ -0,0 +1,244 @@
import fc from 'fast-check';
import type { SentenceOpened } from '@rosea/schema';
import { describe, expect, it } from 'vitest';
import { goodMoment, newOpened, PETAL, petalAt, petalOrder, sentenceOpened, type PetalNow, type PetalSentence } from '../src/petal/petal.js';
import { invitation, sunDay, type Place } from '../src/sun/sun.js';
import { addDays, localDay } from '../src/time/localDay.js';
const ZONE = 'Europe/Prague';
const ME = 'M'.repeat(43);
const BEFORE = 'B'.repeat(43);
const SOMEONE = 'S'.repeat(43);
const HOUR = 3_600_000;
const DAY = 24 * HOUR;
const MINUTE = 60_000;
/** 10:00 in Prague on 1 March 2026. */
const START = Date.parse('2026-03-01T10:00:00+01:00');
const sentence = (id: string, verifiedAt = '2026-11-01', use: PetalSentence['use'] = ['sunset']): PetalSentence => ({ id, use, source: { verifiedAt } });
const LIBRARY: PetalSentence[] = ['a', 'b', 'c', 'd', 'e'].map((id) => sentence(`line-${id}`));
const open = (ts: number, messageId: string, from = ME): SentenceOpened =>
sentenceOpened({ now: ts, timeZone: ZONE, from, messageId, clientVersion: '0.1.0' });
const at = (opened: SentenceOpened[], now: number, library = LIBRARY, keys: string | string[] = ME): PetalNow =>
petalAt(library, opened, keys, now, ZONE);
/** Opens whatever is folded, once a day at 10:00, for `n` days from `from`. */
function openDaily(n: number, from = START, library = LIBRARY): SentenceOpened[] {
const log: SentenceOpened[] = [];
for (let i = 0; i < n; i++) {
const now = from + i * DAY;
const p = at(log, now, library);
if (p.kind !== 'folded') throw new Error(`day ${i}: expected a folded petal, got ${p.kind}`);
log.push(open(now, p.id));
}
return log;
}
describe('the order (P1)', () => {
it('holds only sunset sentences, each once', () => {
const order = petalOrder([...LIBRARY, sentence('thanks-only', '2026-11-01', ['thanks']), sentence('line-a')]);
expect(order).toHaveLength(5);
expect(order).not.toContain('thanks-only');
});
it('puts a sentence verified later after every one verified before it', () => {
const order = petalOrder([sentence('late', '2026-12-01'), ...LIBRARY, sentence('early', '2026-10-01')]);
expect(order[0]).toBe('early');
expect(order.at(-1)).toBe('late');
});
it('mixes sentences verified on the same day, rather than keeping file order', () => {
const ids = Array.from({ length: 20 }, (_, i) => `x-${String(i).padStart(2, '0')}`);
expect(petalOrder(ids.map((id) => sentence(id)))).not.toEqual(ids);
});
});
describe('the folded petal', () => {
it('is absent when the library holds no sunset sentence', () => {
expect(at([], START, [])).toEqual({ kind: 'none' });
expect(at([], START, [sentence('t', '2026-11-01', ['thanks'])])).toEqual({ kind: 'none' });
});
it('on a first visit is the first in the order', () => {
expect(at([], START)).toEqual({ kind: 'folded', id: petalOrder(LIBRARY)[0] });
});
it('once opened stays open for the rest of the local day, and tomorrow the next one is folded', () => {
const first = petalOrder(LIBRARY)[0]!;
const log = [open(START, first)];
expect(at(log, START + 13 * HOUR)).toMatchObject({ kind: 'open', id: first });
expect(at(log, START + 14 * HOUR - 1)).toMatchObject({ kind: 'open', id: first }); // 23:59:59.999
expect(at(log, START + 14 * HOUR)).toEqual({ kind: 'folded', id: petalOrder(LIBRARY)[1] }); // midnight
});
it('comes round again only when every sentence has been opened, the one opened longest ago first', () => {
const log = openDaily(5);
expect(new Set(log.map((e) => e.messageId)).size).toBe(5);
expect(at(log, START + 5 * DAY)).toEqual({ kind: 'folded', id: log[0]!.messageId });
const more = [...log, open(START + 5 * DAY, log[0]!.messageId)];
expect(at(more, START + 6 * DAY)).toEqual({ kind: 'folded', id: log[1]!.messageId });
});
it("counts the rose's own keys, past keys too, and nobody else's", () => {
const first = petalOrder(LIBRARY)[0]!;
expect(at([open(START, first, SOMEONE)], START + DAY)).toEqual({ kind: 'folded', id: first });
expect(at([open(START, first, BEFORE)], START + DAY, LIBRARY, [ME, BEFORE])).toEqual({ kind: 'folded', id: petalOrder(LIBRARY)[1] });
});
it('keeps an opening whose sentence has left the library as that day’s petal', () => {
expect(at([open(START, 'gone-now')], START + HOUR)).toMatchObject({ kind: 'open', id: 'gone-now' });
});
it('reads the log in the order things happened, whatever order it is stored in', () => {
const log = openDaily(4);
expect(at([...log].reverse(), START + 4 * DAY)).toEqual(at(log, START + 4 * DAY));
});
});
describe('never lost (CLAUDE.md §5.5)', () => {
it('property: with no opening, the folded petal is the same on every day', () => {
fc.assert(
fc.property(fc.integer({ min: 0, max: 30 }), fc.integer({ min: 1, max: 2000 }), (n, later) => {
const log = openDaily(n);
const tomorrow = START + n * DAY;
expect(at(log, tomorrow + later * DAY)).toEqual(at(log, tomorrow));
}),
{ numRuns: 60 }
);
});
it('property: sentences verified later never change the folded petal while one already there is unopened', () => {
fc.assert(
fc.property(fc.integer({ min: 0, max: 4 }), fc.array(fc.stringMatching(/^[a-z]{1,8}$/), { maxLength: 10 }), (n, extra) => {
const log = openDaily(n);
const grown = [...LIBRARY, ...extra.map((id) => sentence(`new-${id}`, '2026-11-20'))];
expect(at(log, START + n * DAY, grown)).toEqual(at(log, START + n * DAY));
}),
{ numRuns: 60 }
);
});
it('property: at most one opening counts per local day; a second one that day changes nothing', () => {
fc.assert(
fc.property(fc.integer({ min: 1, max: 10 }), fc.integer({ min: 1, max: 13 * 60 }), (n, minutesLater) => {
const log = openDaily(n);
const last = log.at(-1)!;
const second = open(last.ts + minutesLater * MINUTE, 'line-e' === last.messageId ? 'line-a' : 'line-e');
expect(second.localDay).toBe(last.localDay);
const withSecond = [...log, second];
expect(at(withSecond, second.ts)).toMatchObject({ kind: 'open', id: last.messageId });
expect(at(withSecond, START + n * DAY)).toEqual(at(log, START + n * DAY));
}),
{ numRuns: 60 }
);
});
it('property: no sentence repeats until every one has been opened', () => {
fc.assert(
fc.property(fc.integer({ min: 1, max: 40 }), fc.array(fc.integer({ min: 0, max: 9 }), { minLength: 1, maxLength: 25 }), (size, gaps) => {
const library = Array.from({ length: size }, (_, i) => sentence(`s-${i}`));
const log: SentenceOpened[] = [];
let now = START;
for (const gap of gaps) {
now += (1 + gap) * DAY;
const p = at(log, now, library);
if (p.kind !== 'folded') throw new Error('expected folded');
log.push(open(now, p.id));
}
const ids = log.map((e) => e.messageId);
// Opened in rounds of `size`: within a round, every one is different.
for (let i = 0; i < ids.length; i += size) {
const round = ids.slice(i, i + size);
expect(new Set(round).size).toBe(round.length);
}
}),
{ numRuns: 60 }
);
});
});
describe('remembering on nearby days (P3)', () => {
const openedOn = (dayOffsets: number[]): SentenceOpened[] => {
const log: SentenceOpened[] = [];
for (const d of dayOffsets) {
const p = at(log, START + d * DAY);
if (p.kind !== 'folded') throw new Error('expected folded');
log.push(open(START + d * DAY, p.id));
}
return log;
};
it.each([1, 2, 3])('the last petal %i day(s) before: she remembers an earlier one, never today’s own', (gap) => {
const log = openedOn([0, 1, 1 + gap]);
const today = at(log, START + (1 + gap) * DAY);
expect(today.kind).toBe('open');
if (today.kind !== 'open') return;
expect(today.remembered).not.toBeNull();
expect(today.remembered).not.toBe(today.id);
expect(log.slice(0, 2).map((e) => e.messageId)).toContain(today.remembered);
});
it(`after a gap of more than ${PETAL.nearDays} days, the day's petal and nothing about the gap`, () => {
const log = openedOn([0, 1, 1 + PETAL.nearDays + 1]);
expect(at(log, START + (2 + PETAL.nearDays) * DAY)).toMatchObject({ kind: 'open', remembered: null });
});
it('on the very first petal there is nothing to remember', () => {
expect(at(openedOn([0]), START)).toMatchObject({ kind: 'open', remembered: null });
});
it('remembers only sentences still in the library', () => {
const log = [open(START, 'gone-now'), open(START + DAY, 'line-a')];
expect(at(log, START + DAY)).toMatchObject({ kind: 'open', id: 'line-a', remembered: null });
});
it('is the same choice on every replay of the same day', () => {
const log = openedOn([0, 1, 2, 3, 4]);
expect(at(log, START + 4 * DAY)).toEqual(at(log, START + 4 * DAY + 5 * HOUR));
});
});
describe('the good moment (P4)', () => {
const prague: Place = { lat: 50.0755, lon: 14.4378, timeZone: 'Europe/Prague' };
const tromso: Place = { lat: 69.6492, lon: 18.9553, timeZone: 'Europe/Oslo' };
const sunsetOn = (day: string, place: Place): number => invitation(sunDay(day, place));
it('is the hour either side of the sunset, and not the minute outside it', () => {
const sunset = sunsetOn('2026-03-01', prague);
expect(goodMoment(sunset, prague)).toBe(true);
expect(goodMoment(sunset - PETAL.beforeMinutes * MINUTE, prague)).toBe(true);
expect(goodMoment(sunset + PETAL.afterMinutes * MINUTE, prague)).toBe(true);
expect(goodMoment(sunset - PETAL.beforeMinutes * MINUTE - MINUTE, prague)).toBe(false);
expect(goodMoment(sunset + PETAL.afterMinutes * MINUTE + MINUTE, prague)).toBe(false);
expect(goodMoment(Date.parse('2026-03-01T10:00:00+01:00'), prague)).toBe(false);
});
it('in polar day is the lowest light, and in polar night the brightest twilight', () => {
const lowest = sunsetOn('2026-06-21', tromso);
expect(sunDay('2026-06-21', tromso).kind).toBe('polar-day');
expect(goodMoment(lowest, tromso)).toBe(true);
expect(goodMoment(lowest + 3 * HOUR, tromso)).toBe(false);
const noon = sunsetOn('2026-12-21', tromso);
expect(sunDay('2026-12-21', tromso).kind).toBe('polar-night');
expect(goodMoment(noon, tromso)).toBe(true);
expect(goodMoment(noon - 3 * HOUR, tromso)).toBe(false);
});
});
describe('the event and bringing it back', () => {
it('records the local day in the given zone', () => {
const lateEvening = Date.parse('2026-03-01T23:30:00+01:00');
expect(sentenceOpened({ now: lateEvening, timeZone: ZONE, from: ME, messageId: 'line-a', clientVersion: '0.1.0' })).toEqual({
kind: 'sentence-opened', ts: lateEvening, localDay: '2026-03-01', from: ME, messageId: 'line-a', clientVersion: '0.1.0'
});
expect(localDay(lateEvening, 'UTC')).toBe('2026-03-01');
expect(sentenceOpened({ now: lateEvening, timeZone: 'Asia/Tokyo', from: ME, messageId: 'line-a', clientVersion: '0.1.0' }).localDay).toBe(addDays('2026-03-01', 1));
});
it('newOpened adds only what is not there yet', () => {
const log = openDaily(3);
expect(newOpened(log, log)).toEqual([]);
expect(newOpened(log.slice(0, 1), [...log, ...log])).toEqual(log.slice(1));
});
});
@@ -0,0 +1,39 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://rosea.invalid/schema/sentence-opened.json",
"title": "SentenceOpened",
"description": "The rose's folded petal was opened (CLAUDE.md §6.2, .agents/features/day-sentence.md). Append-only, never edited. The first one of a local day is that day's petal.",
"type": "object",
"additionalProperties": false,
"required": ["kind", "ts", "localDay", "from", "messageId", "clientVersion"],
"properties": {
"kind": {
"const": "sentence-opened"
},
"ts": {
"description": "Epoch milliseconds. Stays on the device.",
"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": {
"description": "The key of the rose whose petal it was.",
"type": "string",
"pattern": "^[A-Za-z0-9_-]{32,128}$"
},
"messageId": {
"description": "The hope-library id that was in the petal. Never text: the pattern admits no space (CLAUDE.md §5.6 rule 1).",
"type": "string",
"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$",
"maxLength": 64
},
"clientVersion": {
"type": "string",
"pattern": "^\\d+\\.\\d+\\.\\d+$"
}
}
}
+3 -1
View File
@@ -10,8 +10,9 @@
import { Ajv, type ErrorObject, type ValidateFunction } from 'ajv'; import { Ajv, type ErrorObject, type ValidateFunction } from 'ajv';
import careEvent from '../schemas/care-event.schema.json' with { type: 'json' }; import careEvent from '../schemas/care-event.schema.json' with { type: 'json' };
import hopeSentence from '../schemas/hope-sentence.schema.json' with { type: 'json' }; import hopeSentence from '../schemas/hope-sentence.schema.json' with { type: 'json' };
import sentenceOpened from '../schemas/sentence-opened.schema.json' with { type: 'json' };
import trace from '../schemas/trace.schema.json' with { type: 'json' }; import trace from '../schemas/trace.schema.json' with { type: 'json' };
import type { CareEvent, HopeSentence, Trace } from './generated/index.js'; import type { CareEvent, HopeSentence, SentenceOpened, Trace } from './generated/index.js';
export type SchemaResult<T> = export type SchemaResult<T> =
| { readonly ok: true; readonly value: T } | { readonly ok: true; readonly value: T }
@@ -38,4 +39,5 @@ function describe(error: ErrorObject): string {
export const validateHopeSentence = wrap<HopeSentence>(ajv.compile(hopeSentence)); export const validateHopeSentence = wrap<HopeSentence>(ajv.compile(hopeSentence));
export const validateCareEvent = wrap<CareEvent>(ajv.compile(careEvent)); export const validateCareEvent = wrap<CareEvent>(ajv.compile(careEvent));
export const validateSentenceOpened = wrap<SentenceOpened>(ajv.compile(sentenceOpened));
export const validateTrace = wrap<Trace>(ajv.compile(trace)); export const validateTrace = wrap<Trace>(ajv.compile(trace));
+21 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { validateCareEvent, validateHopeSentence, validateTrace } from '../src/validate.js'; import { validateCareEvent, validateHopeSentence, validateSentenceOpened, validateTrace } from '../src/validate.js';
const KEY_A = 'A'.repeat(43); const KEY_A = 'A'.repeat(43);
const KEY_B = 'b_-'.repeat(15); const KEY_B = 'b_-'.repeat(15);
@@ -103,6 +103,26 @@ describe('care event', () => {
}); });
}); });
describe('sentence opened (day-sentence.md P6)', () => {
const opened = { kind: 'sentence-opened', ts: 1761500000000, localDay: '2026-10-24', from: KEY_A, messageId: 'ps-23-4', clientVersion: '0.1.0' };
it('accepts an opened petal', () => {
expect(validateSentenceOpened(opened)).toMatchObject({ ok: true });
});
it('rejects text in place of an id, so no words can ride in the log', () => {
expect(validateSentenceOpened({ ...opened, messageId: 'The LORD is my shepherd' }).ok).toBe(false);
expect(validateSentenceOpened({ ...opened, messageId: null }).ok).toBe(false);
});
it('rejects a missing day, an extra field, or another kind', () => {
const { localDay: _, ...noDay } = opened;
expect(validateSentenceOpened(noDay).ok).toBe(false);
expect(validateSentenceOpened({ ...opened, atSunset: true }).ok).toBe(false);
expect(validateSentenceOpened({ ...opened, kind: 'care' }).ok).toBe(false);
});
});
describe('trace', () => { describe('trace', () => {
it('accepts a day-bucketed trace', () => { it('accepts a day-bucketed trace', () => {
expect(validateTrace(trace)).toMatchObject({ ok: true }); expect(validateTrace(trace)).toMatchObject({ ok: true });
+83 -20
View File
@@ -2,7 +2,7 @@
* The ONLY module that touches IndexedDB (CLAUDE.md §2). The database `rosea` and its * The ONLY module that touches IndexedDB (CLAUDE.md §2). The database `rosea` and its
* stores are listed in CLAUDE.md §4; each store arrives with the feature that writes * stores are listed in CLAUDE.md §4; each store arrives with the feature that writes
* it. So far: `profile` (the sunset place, sunset-place.md), `events` (the rose's care * it. So far: `profile` (the sunset place, sunset-place.md), `events` (the rose's care
* log, rose.md) and `keys` (the identity, rose.md). * log, rose.md, and her opened petals, day-sentence.md) and `keys` (the identity, rose.md).
* *
* The database name changes together with the product name (CLAUDE.md preamble). * The database name changes together with the product name (CLAUDE.md preamble).
* Everything written is a fresh plain copy that passed a shape check: a Svelte 5 * Everything written is a fresh plain copy that passed a shape check: a Svelte 5
@@ -10,9 +10,9 @@
* may enter a log that is never edited. * may enter a log that is never edited.
*/ */
import Dexie, { type DexieOptions, type Table } from 'dexie'; import Dexie, { type DexieOptions, type Table } from 'dexie';
import { newCare, type NamedPlace } from '@rosea/engine'; import { newCare, newOpened, type NamedPlace } from '@rosea/engine';
import { isIdentity, type Identity } from '@rosea/identity'; import { isIdentity, type Identity } from '@rosea/identity';
import { DATABASE_NAME, type CareEvent } from '@rosea/schema'; import { DATABASE_NAME, type CareEvent, type SentenceOpened } from '@rosea/schema';
export { DATABASE_NAME }; export { DATABASE_NAME };
@@ -37,14 +37,19 @@ const SUNSET_PLACE = 'sunsetPlace';
const SELF = 'self'; const SELF = 'self';
const PAST_KEYS = 'pastKeys'; const PAST_KEYS = 'pastKeys';
/** The file a rose is saved to and brought back from (keep-her-safe.md K4). Never the private key, never the town. */ /**
* The file a rose is saved to and brought back from (keep-her-safe.md K4). Never the
* private key, never the town. Version 2 adds her opened petals (day-sentence.md P7);
* a version 1 file is still read, as one with none.
*/
export const ROSE_FILE_FORMAT = 'rosea-rose'; export const ROSE_FILE_FORMAT = 'rosea-rose';
export interface RoseFile { export interface RoseFile {
readonly format: typeof ROSE_FILE_FORMAT; readonly format: typeof ROSE_FILE_FORMAT;
readonly version: 1; readonly version: 2;
/** The keys that have named her, the one she had when saved first. Public keys only. */ /** The keys that have named her, the one she had when saved first. Public keys only. */
readonly keys: readonly string[]; readonly keys: readonly string[];
readonly events: readonly CareEvent[]; readonly events: readonly CareEvent[];
readonly opened: readonly SentenceOpened[];
} }
export interface Storage { export interface Storage {
@@ -55,6 +60,10 @@ export interface Storage {
appendCare(event: CareEvent): Promise<void>; appendCare(event: CareEvent): Promise<void>;
/** The whole care log, in the order it was written. */ /** The whole care log, in the order it was written. */
loadCare(): Promise<CareEvent[]>; loadCare(): Promise<CareEvent[]>;
/** Appends one opened petal (day-sentence.md P6). Never edited. */
appendOpened(event: SentenceOpened): Promise<void>;
/** Every opened petal, in the order written. */
loadOpened(): Promise<SentenceOpened[]>;
/** /**
* The player's identity: the one already kept, or `fresh` kept now. With two tabs * The player's identity: the one already kept, or `fresh` kept now. With two tabs
* racing, both get the same one: the first write wins and the other is dropped. * racing, both get the same one: the first write wins and the other is dropped.
@@ -69,7 +78,7 @@ export interface Storage {
* Brings a saved rose back: her keys join the past keys and every act not already * Brings a saved rose back: her keys join the past keys and every act not already
* here is appended. Nothing is edited or removed. Rejects a file that is not a rose. * here is appended. Nothing is edited or removed. Rejects a file that is not a rose.
*/ */
importRose(file: unknown, currentKey: string): Promise<{ readonly added: number }>; importRose(file: unknown, currentKey: string): Promise<{ readonly added: number; readonly petals: number }>;
close(): void; close(): void;
} }
@@ -118,21 +127,52 @@ export function asCareEvent(value: unknown): CareEvent | null {
return isWater ? { ...base, amount: v['amount'] as number } : base; return isWater ? { ...base, amount: v['amount'] as number } : base;
} }
const OPENED_KEYS = new Set(['kind', 'ts', 'localDay', 'from', 'messageId', 'clientVersion']);
/** The sentence-opened contract (sentence-opened.schema.json), checked by hand for the same reason as care. */
export function asSentenceOpened(value: unknown): SentenceOpened | null {
if (typeof value !== 'object' || value === null) return null;
const v = value as Record<string, unknown>;
if (Object.keys(v).some((k) => !OPENED_KEYS.has(k))) return null;
if (v['kind'] !== 'sentence-opened' || !Number.isSafeInteger(v['ts']) || (v['ts'] as number) < 0) return null;
if (!matches(v['localDay'], /^\d{4}-\d{2}-\d{2}$/) || !matches(v['from'], KEY)) return null;
const messageId = v['messageId'];
if (!(matches(messageId, /^[a-z0-9]+(-[a-z0-9]+)*$/) && messageId.length <= 64)) return null;
if (!matches(v['clientVersion'], /^\d+\.\d+\.\d+$/)) return null;
return { kind: 'sentence-opened', ts: v['ts'] as number, localDay: v['localDay'], from: v['from'], messageId, clientVersion: v['clientVersion'] };
}
/** Kinds the log holds besides care, each read by its own loader: not broken entries. */
const OTHER_KINDS: ReadonlySet<unknown> = new Set(['sentence-opened']);
const kindOf = (event: unknown): unknown => (typeof event === 'object' && event !== null ? (event as { kind?: unknown }).kind : undefined);
const isKeyList = (x: unknown): x is string[] => Array.isArray(x) && x.every((k) => matches(k, KEY)); const isKeyList = (x: unknown): x is string[] => Array.isArray(x) && x.every((k) => matches(k, KEY));
/** The shape check for a saved rose. Every act must pass the care event contract. */ /** Every item through `check`, or null if any one fails it. */
function every<T>(items: unknown, check: (x: unknown) => T | null): T[] | null {
if (!Array.isArray(items)) return null;
const out: T[] = [];
for (const item of items as unknown[]) {
const plain = check(item);
if (plain === null) return null;
out.push(plain);
}
return out;
}
/**
* The shape check for a saved rose, version 1 or 2. Every act must pass the care
* event contract and every petal the sentence-opened one. It answers as version 2.
*/
export function asRoseFile(value: unknown): RoseFile | null { export function asRoseFile(value: unknown): RoseFile | null {
if (typeof value !== 'object' || value === null) return null; if (typeof value !== 'object' || value === null) return null;
const v = value as Record<string, unknown>; const v = value as Record<string, unknown>;
if (v['format'] !== ROSE_FILE_FORMAT || v['version'] !== 1) return null; if (v['format'] !== ROSE_FILE_FORMAT || (v['version'] !== 1 && v['version'] !== 2)) return null;
if (!isKeyList(v['keys']) || v['keys'].length === 0 || !Array.isArray(v['events'])) return null; if (!isKeyList(v['keys']) || v['keys'].length === 0) return null;
const events: CareEvent[] = []; const events = every(v['events'], asCareEvent);
for (const e of v['events'] as unknown[]) { const opened = v['version'] === 1 ? ('opened' in v ? null : []) : every(v['opened'], asSentenceOpened);
const plain = asCareEvent(e); if (events === null || opened === null) return null;
if (plain === null) return null; return { format: ROSE_FILE_FORMAT, version: 2, keys: [...new Set(v['keys'])], events, opened };
events.push(plain);
}
return { format: ROSE_FILE_FORMAT, version: 1, keys: [...new Set(v['keys'])], events };
} }
class RoseaDatabase extends Dexie { class RoseaDatabase extends Dexie {
@@ -181,6 +221,7 @@ export function openStorage(options?: DexieOptions): Storage {
const rows = await db.events.orderBy('id').toArray(); const rows = await db.events.orderBy('id').toArray();
const events: CareEvent[] = []; const events: CareEvent[] = [];
for (const row of rows) { for (const row of rows) {
if (OTHER_KINDS.has(kindOf(row.event))) continue;
const e = asCareEvent(row.event); const e = asCareEvent(row.event);
// A broken entry is said out loud and left in place: the log is never edited. // A broken entry is said out loud and left in place: the log is never edited.
if (e === null) console.warn('storage: a care event has an unknown shape; it is skipped, not removed', row); if (e === null) console.warn('storage: a care event has an unknown shape; it is skipped, not removed', row);
@@ -188,6 +229,22 @@ export function openStorage(options?: DexieOptions): Storage {
} }
return events; return events;
}, },
async appendOpened(event) {
const plain = asSentenceOpened(event);
if (plain === null) throw new TypeError('storage: refusing to append an opened petal of an unknown shape');
await db.events.add({ event: plain });
},
async loadOpened() {
const rows = await db.events.orderBy('id').toArray();
const opened: SentenceOpened[] = [];
for (const row of rows) {
if (kindOf(row.event) !== 'sentence-opened') continue;
const e = asSentenceOpened(row.event);
if (e === null) console.warn('storage: an opened petal has an unknown shape; it is skipped, not removed', row);
else opened.push(e);
}
return opened;
},
async keepIdentity(fresh) { async keepIdentity(fresh) {
if (!isIdentity(fresh)) throw new TypeError('storage: refusing to keep an identity of an unknown shape'); if (!isIdentity(fresh)) throw new TypeError('storage: refusing to keep an identity of an unknown shape');
return db.transaction('rw', db.keys, async () => { return db.transaction('rw', db.keys, async () => {
@@ -211,7 +268,10 @@ export function openStorage(options?: DexieOptions): Storage {
}, },
async exportRose(currentKey) { async exportRose(currentKey) {
const past = await api.loadPastKeys(); const past = await api.loadPastKeys();
return { format: ROSE_FILE_FORMAT, version: 1, keys: [...new Set([currentKey, ...past])], events: await api.loadCare() }; return {
format: ROSE_FILE_FORMAT, version: 2, keys: [...new Set([currentKey, ...past])],
events: await api.loadCare(), opened: await api.loadOpened()
};
}, },
async importRose(file, currentKey) { async importRose(file, currentKey) {
const rose = asRoseFile(file); const rose = asRoseFile(file);
@@ -221,10 +281,13 @@ export function openStorage(options?: DexieOptions): Storage {
const past = isKeyList(row?.value) ? row.value : []; const past = isKeyList(row?.value) ? row.value : [];
const keys = [...new Set([...past, ...rose.keys])].filter((k) => k !== currentKey); const keys = [...new Set([...past, ...rose.keys])].filter((k) => k !== currentKey);
await db.profile.put({ key: PAST_KEYS, value: keys }); await db.profile.put({ key: PAST_KEYS, value: keys });
const existing = (await db.events.orderBy('id').toArray()).map((r) => asCareEvent(r.event)).filter((e): e is CareEvent => e !== null); const rows = (await db.events.orderBy('id').toArray()).map((r) => r.event);
const existing = rows.map(asCareEvent).filter((e): e is CareEvent => e !== null);
const existingOpened = rows.map(asSentenceOpened).filter((e): e is SentenceOpened => e !== null);
const added = newCare(existing, rose.events); const added = newCare(existing, rose.events);
await db.events.bulkAdd(added.map((event) => ({ event }))); const petals = newOpened(existingOpened, rose.opened);
return { added: added.length }; await db.events.bulkAdd([...added, ...petals].map((event) => ({ event })));
return { added: added.length, petals: petals.length };
}); });
}, },
close() { close() {
+76
View File
@@ -0,0 +1,76 @@
import type { CareEvent, SentenceOpened } from '@rosea/schema';
import { validateSentenceOpened } from '@rosea/schema/validate';
import Dexie from 'dexie';
import { IDBFactory, IDBKeyRange } from 'fake-indexeddb';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { asSentenceOpened, openStorage, type Storage } from '../src/index.js';
const KEY = 'K'.repeat(87);
const petal: SentenceOpened = { kind: 'sentence-opened', ts: 1774944000000, localDay: '2026-03-31', from: KEY, messageId: 'ps-118-24', clientVersion: '0.1.0' };
const weed: CareEvent = { kind: 'care', ts: 1774944060000, localDay: '2026-03-31', from: KEY, to: KEY, act: 'weed', trace: 'petal:rose', messageId: null, clientVersion: '0.1.0' };
const opened: Storage[] = [];
const open = (indexedDB: IDBFactory = new IDBFactory()): Storage => {
const s = openStorage({ indexedDB, IDBKeyRange });
opened.push(s);
return s;
};
afterEach(() => {
for (const s of opened.splice(0)) s.close();
vi.restoreAllMocks();
});
describe('opened petals (day-sentence.md P6)', () => {
it('are appended to the same log and come back in order, across a reopen', async () => {
const factory = new IDBFactory();
const s = open(factory);
await s.appendOpened(petal);
await s.appendCare(weed);
await s.appendOpened(new Proxy({ ...petal, ts: petal.ts + 86_400_000, localDay: '2026-04-01' }, {}));
s.close();
const again = open(factory);
expect(await again.loadOpened()).toEqual([petal, { ...petal, ts: petal.ts + 86_400_000, localDay: '2026-04-01' }]);
expect(await again.loadCare()).toEqual([weed]);
});
it('loading care passes over them quietly: they are not broken entries', async () => {
const s = open();
await s.appendOpened(petal);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
expect(await s.loadCare()).toEqual([]);
expect(warn).not.toHaveBeenCalled();
});
it('refuses text in place of an id, or anything else the contract refuses', async () => {
const s = open();
for (const bad of [
{ ...petal, messageId: 'The LORD is my shepherd' },
{ ...petal, note: 'hello' },
{ ...petal, kind: 'care' },
{ ...petal, from: 'short' }
]) {
await expect(s.appendOpened(bad as SentenceOpened)).rejects.toThrow(/unknown shape/);
}
expect(await s.loadOpened()).toEqual([]);
});
it('a broken one already in the log is skipped and said, never removed', async () => {
const factory = new IDBFactory();
const s = open(factory);
await s.appendOpened(petal);
s.close();
const raw = new Dexie('rosea', { indexedDB: factory, IDBKeyRange });
raw.version(2).stores({ profile: 'key', events: '++id', keys: 'id' });
await raw.table('events').add({ event: { kind: 'sentence-opened', messageId: 'Free words' } });
raw.close();
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
expect(await open(factory).loadOpened()).toEqual([petal]);
expect(warn).toHaveBeenCalledOnce();
});
it('the hand check agrees with the schema on every case above', () => {
for (const value of [petal, { ...petal, messageId: 'A sentence' }, { ...petal, note: 'x' }, { ...petal, ts: -1 }, { ...petal, ts: 1.5 }, { ...petal, localDay: '31.3.2026' }]) {
expect(asSentenceOpened(value) !== null, JSON.stringify(value)).toBe(validateSentenceOpened(value).ok);
}
});
});
+35 -5
View File
@@ -1,5 +1,5 @@
import { createIdentity } from '@rosea/identity'; import { createIdentity } from '@rosea/identity';
import type { CareEvent } from '@rosea/schema'; import type { CareEvent, SentenceOpened } from '@rosea/schema';
import { IDBFactory, IDBKeyRange } from 'fake-indexeddb'; import { IDBFactory, IDBKeyRange } from 'fake-indexeddb';
import { afterEach, describe, expect, it } from 'vitest'; import { afterEach, describe, expect, it } from 'vitest';
import { asRoseFile, openStorage, ROSE_FILE_FORMAT, type Storage } from '../src/index.js'; import { asRoseFile, openStorage, ROSE_FILE_FORMAT, type Storage } from '../src/index.js';
@@ -11,6 +11,10 @@ const act = (to: string, ts: number): CareEvent => ({
trace: 'petal:rose', messageId: null, clientVersion: '0.1.0', amount: 0.5 trace: 'petal:rose', messageId: null, clientVersion: '0.1.0', amount: 0.5
}); });
const petal = (from: string, ts: number): SentenceOpened => ({
kind: 'sentence-opened', ts, localDay: '2026-03-01', from, messageId: 'ps-118-24', clientVersion: '0.1.0'
});
const opened: Storage[] = []; const opened: Storage[] = [];
const open = (indexedDB: IDBFactory = new IDBFactory()): Storage => { const open = (indexedDB: IDBFactory = new IDBFactory()): Storage => {
const s = openStorage({ indexedDB, IDBKeyRange }); const s = openStorage({ indexedDB, IDBKeyRange });
@@ -28,14 +32,16 @@ describe('saving the rose to a file', () => {
await s.keepIdentity(await createIdentity()); await s.keepIdentity(await createIdentity());
await s.saveSunsetPlace({ kind: 'town', town: { name: 'Brno', region: '', country: 'Czechia', lat: 49.2, lon: 16.61, timeZone: 'Europe/Prague' } }); await s.saveSunsetPlace({ kind: 'town', town: { name: 'Brno', region: '', country: 'Czechia', lat: 49.2, lon: 16.61, timeZone: 'Europe/Prague' } });
await s.appendCare(act(OLD, 1)); await s.appendCare(act(OLD, 1));
await s.appendOpened(petal(OLD, 2));
const file = await s.exportRose(OLD); const file = await s.exportRose(OLD);
expect(file).toStrictEqual({ format: ROSE_FILE_FORMAT, version: 1, keys: [OLD], events: [act(OLD, 1)] }); expect(file).toStrictEqual({ format: ROSE_FILE_FORMAT, version: 2, keys: [OLD], events: [act(OLD, 1)], opened: [petal(OLD, 2)] });
expect(JSON.stringify(file)).not.toMatch(/Brno|privateKey|CryptoKey/); expect(JSON.stringify(file)).not.toMatch(/Brno|privateKey|CryptoKey/);
}); });
it('survives a trip through JSON text unchanged', async () => { it('survives a trip through JSON text unchanged', async () => {
const s = open(); const s = open();
await s.appendCare(act(OLD, 1)); await s.appendCare(act(OLD, 1));
await s.appendOpened(petal(OLD, 2));
const file = await s.exportRose(OLD); const file = await s.exportRose(OLD);
expect(asRoseFile(JSON.parse(JSON.stringify(file)))).toEqual(file); expect(asRoseFile(JSON.parse(JSON.stringify(file)))).toEqual(file);
}); });
@@ -49,27 +55,48 @@ describe('bringing her back', () => {
const file = JSON.parse(JSON.stringify(await old.exportRose(OLD))); const file = JSON.parse(JSON.stringify(await old.exportRose(OLD)));
const fresh = open(); const fresh = open();
expect(await fresh.importRose(file, NEW)).toEqual({ added: 2 }); expect(await fresh.importRose(file, NEW)).toEqual({ added: 2, petals: 0 });
expect(await fresh.loadPastKeys()).toEqual([OLD]); expect(await fresh.loadPastKeys()).toEqual([OLD]);
expect(await fresh.loadCare()).toEqual([act(OLD, 1), act(OLD, 2)]); expect(await fresh.loadCare()).toEqual([act(OLD, 1), act(OLD, 2)]);
}); });
it('her opened petals come with her, so the next petal is the one she would have held (day-sentence.md P7)', async () => {
const old = open();
await old.appendCare(act(OLD, 1));
await old.appendOpened(petal(OLD, 2));
const file = JSON.parse(JSON.stringify(await old.exportRose(OLD)));
const fresh = open();
await fresh.appendOpened(petal(NEW, 9));
expect(await fresh.importRose(file, NEW)).toEqual({ added: 1, petals: 1 });
expect(await fresh.loadOpened()).toEqual([petal(NEW, 9), petal(OLD, 2)]);
});
it('a version 1 file, saved before petals existed, is still brought back', async () => {
const v1 = { format: ROSE_FILE_FORMAT, version: 1, keys: [OLD], events: [act(OLD, 1)] };
const fresh = open();
expect(await fresh.importRose(v1, NEW)).toEqual({ added: 1, petals: 0 });
expect(await fresh.loadCare()).toEqual([act(OLD, 1)]);
});
it('twice is the same as once, and the care given here meanwhile stays', async () => { it('twice is the same as once, and the care given here meanwhile stays', async () => {
const old = open(); const old = open();
await old.appendCare(act(OLD, 1)); await old.appendCare(act(OLD, 1));
await old.appendOpened(petal(OLD, 2));
const file = await old.exportRose(OLD); const file = await old.exportRose(OLD);
const here = open(); const here = open();
await here.appendCare(act(NEW, 5)); await here.appendCare(act(NEW, 5));
await here.importRose(file, NEW); await here.importRose(file, NEW);
expect(await here.importRose(file, NEW)).toEqual({ added: 0 }); expect(await here.importRose(file, NEW)).toEqual({ added: 0, petals: 0 });
expect(await here.loadCare()).toEqual([act(NEW, 5), act(OLD, 1)]); expect(await here.loadCare()).toEqual([act(NEW, 5), act(OLD, 1)]);
expect(await here.loadOpened()).toEqual([petal(OLD, 2)]);
expect(await here.loadPastKeys()).toEqual([OLD]); expect(await here.loadPastKeys()).toEqual([OLD]);
}); });
it('a file saved on this very device adds nothing and does not list its own key as past', async () => { it('a file saved on this very device adds nothing and does not list its own key as past', async () => {
const s = open(); const s = open();
await s.appendCare(act(NEW, 1)); await s.appendCare(act(NEW, 1));
expect(await s.importRose(await s.exportRose(NEW), NEW)).toEqual({ added: 0 }); await s.appendOpened(petal(NEW, 2));
expect(await s.importRose(await s.exportRose(NEW), NEW)).toEqual({ added: 0, petals: 0 });
expect(await s.loadPastKeys()).toEqual([]); expect(await s.loadPastKeys()).toEqual([]);
}); });
@@ -79,6 +106,9 @@ describe('bringing her back', () => {
for (const bad of [ for (const bad of [
null, 'rose', { format: 'other', version: 1, keys: [OLD], events: [] }, null, 'rose', { format: 'other', version: 1, keys: [OLD], events: [] },
{ format: ROSE_FILE_FORMAT, version: 2, keys: [OLD], events: [] }, { format: ROSE_FILE_FORMAT, version: 2, keys: [OLD], events: [] },
{ format: ROSE_FILE_FORMAT, version: 3, keys: [OLD], events: [], opened: [] },
{ format: ROSE_FILE_FORMAT, version: 2, keys: [OLD], events: [], opened: [{ ...petal(OLD, 1), messageId: 'Free words' }] },
{ format: ROSE_FILE_FORMAT, version: 1, keys: [OLD], events: [], opened: [petal(OLD, 1)] },
{ format: ROSE_FILE_FORMAT, version: 1, keys: [], events: [] }, { format: ROSE_FILE_FORMAT, version: 1, keys: [], events: [] },
{ format: ROSE_FILE_FORMAT, version: 1, keys: ['short'], events: [] }, { format: ROSE_FILE_FORMAT, version: 1, keys: ['short'], events: [] },
{ format: ROSE_FILE_FORMAT, version: 1, keys: [OLD], events: [{ ...act(OLD, 1), note: 'hello' }] } { format: ROSE_FILE_FORMAT, version: 1, keys: [OLD], events: [{ ...act(OLD, 1), note: 'hello' }] }
+1 -1
View File
@@ -129,7 +129,7 @@
<h1 bind:this={heading} tabindex="-1">{PRODUCT_NAME}</h1> <h1 bind:this={heading} tabindex="-1">{PRODUCT_NAME}</h1>
<p>{en.shell.preparing}</p> <p>{en.shell.preparing}</p>
{#if rose} {#if rose}
<Rose wiring={rose} timeZone={roseZone} /> <Rose wiring={rose} timeZone={roseZone} {place} />
{/if} {/if}
{#if sunset && (status === 'asking' || changing)} {#if sunset && (status === 'asking' || changing)}
<SunsetPlace <SunsetPlace
+20 -1
View File
@@ -50,6 +50,24 @@ export const en = {
tooFull: 'That was a lot of water. I will be fine by tomorrow.' tooFull: 'That was a lot of water. I will be fine by tomorrow.'
}, },
notKept: 'This device could not keep today’s care, so it lasts only until the garden closes.', notKept: 'This device could not keep today’s care, so it lasts only until the garden closes.',
/**
* The day's sentence (day-sentence.md). She offers; she never counts, and never
* mentions a day the petal was not opened.
*/
petal: {
/** Said when she needs nothing else. */
waiting: 'I am keeping a folded petal for you.',
/** Around the real sunset (P4); in polar day and night the same words still hold. */
goodMoment: 'The sun is low now. Would you open my petal?',
/** After opening it at the good moment: the best moments send the player outside. */
lookUp: 'Go and look at the sky. I will be here.',
open: 'Open her petal',
folded: 'A folded petal.',
today: 'Today’s petal',
remember: 'Do you remember this one?',
source: (work: string, author: string | null, translation: string | null): string =>
`${author ? `${author}, ` : ''}${work}${translation ? ` (${translation})` : ''}`
},
/** Keeping her (keep-her-safe.md). True and calm: a browser can clear a site's data. */ /** Keeping her (keep-her-safe.md). True and calm: a browser can clear a site's data. */
safe: { safe: {
title: 'Keep her safe', title: 'Keep her safe',
@@ -62,7 +80,8 @@ export const en = {
save: 'Save her to a file', save: 'Save her to a file',
fileNote: 'The file holds her care and when it was given. It never holds your town.', fileNote: 'The file holds her care and when it was given. It never holds your town.',
bringBack: 'Bring her back from a file', bringBack: 'Bring her back from a file',
broughtBack: (n: number): string => (n === 1 ? 'She is back, with 1 act of care.' : `She is back, with ${n} acts of care.`), broughtBack: (n: number): string =>
n === 0 ? 'She is back.' : n === 1 ? 'She is back, with 1 act of care.' : `She is back, with ${n} acts of care.`,
alreadyHere: 'Everything in that file is already here.', alreadyHere: 'Everything in that file is already here.',
notARose: 'That file does not hold a rose.' notARose: 'That file does not hold a rose.'
} }
+2 -2
View File
@@ -49,8 +49,8 @@
const file = input.files?.[0]; const file = input.files?.[0];
if (!file) return; if (!file) return;
try { try {
const { added } = await wiring.importRose(JSON.parse(await file.text()), currentKey); const { added, petals } = await wiring.importRose(JSON.parse(await file.text()), currentKey);
said = added === 0 ? en.rose.safe.alreadyHere : en.rose.safe.broughtBack(added); said = added === 0 && petals === 0 ? en.rose.safe.alreadyHere : en.rose.safe.broughtBack(added);
onrestored(); onrestored();
} catch (error) { } catch (error) {
// A wrong file is an ordinary thing to choose; the player is told calmly, the console fully. // A wrong file is an ordinary thing to choose; the player is told calmly, the console fully.
+128
View File
@@ -0,0 +1,128 @@
<script lang="ts">
import type { PetalNow } from '@rosea/engine';
import type { HopeSentence } from '@rosea/schema';
import { tick } from 'svelte';
import { en } from '../copy/en.js';
// The art board's stand-in until real art is accepted (docs/ART.md).
import folded from '../../../../art/placeholders/petal-folded.svg?url';
/**
* The rose's folded petal (day-sentence.md). The engine decides which sentence and
* whether it is open; this shows it and hands the player's tap back.
*/
let { petal, sentences, onopen }: { petal: PetalNow; sentences: readonly HopeSentence[]; onopen: () => void } = $props();
const uid = $props.id();
/** Today's open petal is shown; the player can fold it away and back for the rest of the day. */
let showing = $state(true);
let words = $state<HTMLElement>();
const find = (id: string | null): HopeSentence | undefined => (id === null ? undefined : sentences.find((s) => s.id === id));
const today = $derived(petal.kind === 'open' ? find(petal.id) : undefined);
const remembered = $derived(petal.kind === 'open' ? find(petal.remembered) : undefined);
const source = (s: HopeSentence): string => en.rose.petal.source(s.source.work, s.source.author, s.source.translation);
async function open(): Promise<void> {
onopen();
showing = true;
// The player acted, so focus follows them to the words.
await tick();
words?.focus();
}
</script>
{#if petal.kind === 'folded'}
<div class="petal">
<img src={folded} alt={en.rose.petal.folded} width="56" height="56" />
<button type="button" onclick={open}>{en.rose.petal.open}</button>
</div>
{:else if petal.kind === 'open' && today}
<div class="petal">
<button type="button" class="quiet" aria-expanded={showing} aria-controls="{uid}-words" onclick={() => (showing = !showing)}>{en.rose.petal.today}</button>
{#if showing}
<div id="{uid}-words" class="words" tabindex="-1" bind:this={words}>
<figure>
<blockquote>{today.text.en}</blockquote>
<figcaption>{source(today)}</figcaption>
</figure>
{#if remembered}
<p class="remember">{en.rose.petal.remember}</p>
<figure>
<blockquote>{remembered.text.en}</blockquote>
<figcaption>{source(remembered)}</figcaption>
</figure>
{/if}
</div>
{/if}
</div>
{/if}
<style>
.petal {
display: grid;
justify-items: center;
gap: var(--space-2);
}
img {
width: 3.5rem;
height: auto;
}
.words {
display: grid;
gap: var(--space-3);
max-width: 24rem;
padding: var(--space-3);
border-radius: 1.25rem;
background: color-mix(in srgb, var(--rose) 10%, var(--paper));
}
.words:focus {
outline: none;
}
figure {
margin: 0;
display: grid;
gap: var(--space-1);
}
blockquote {
margin: 0;
font-family: var(--font-display);
font-size: 1.15rem;
line-height: 1.45;
color: var(--ink);
}
figcaption,
.remember {
margin: 0;
font-size: 0.85rem;
color: var(--ink-soft);
}
button {
font: inherit;
padding: var(--space-2) var(--space-3);
border-radius: 999px;
border: 1px solid var(--rose);
background: var(--paper);
color: var(--ink);
cursor: pointer;
}
.quiet {
border: none;
background: none;
padding: var(--space-1) 0;
color: var(--rose);
text-decoration: underline;
}
button:focus-visible {
outline: 2px solid var(--rose);
outline-offset: 2px;
}
</style>
+37 -8
View File
@@ -1,8 +1,12 @@
<script lang="ts"> <script lang="ts">
import { careEvent, localDay, pour, roseAt, ROSE, type Mood, type RoseNow, type Stage } from '@rosea/engine'; import {
import type { CareEvent } from '@rosea/schema'; careEvent, goodMoment, localDay, petalAt, pour, roseAt, ROSE, sentenceOpened,
type Mood, type PetalNow, type Place, type RoseNow, type Stage
} from '@rosea/engine';
import type { CareEvent, SentenceOpened } from '@rosea/schema';
import { en } from '../copy/en.js'; import { en } from '../copy/en.js';
import KeepSafe from './KeepSafe.svelte'; import KeepSafe from './KeepSafe.svelte';
import Petal from './Petal.svelte';
import type { RoseWiring } from './types.js'; import type { RoseWiring } from './types.js';
// The art board's stand-ins until real art is accepted (rose.md R10, docs/ART.md). // The art board's stand-ins until real art is accepted (rose.md R10, docs/ART.md).
import bud from '../../../../art/placeholders/rose-bud.svg?url'; import bud from '../../../../art/placeholders/rose-bud.svg?url';
@@ -19,7 +23,7 @@
* The rose. Everything she is comes from the engine's replay of her care log * The rose. Everything she is comes from the engine's replay of her care log
* (rose.md); this renders it and turns the player's hands into care events. * (rose.md); this renders it and turns the player's hands into care events.
*/ */
let { wiring, timeZone }: { wiring: RoseWiring; timeZone: string } = $props(); let { wiring, timeZone, place = null }: { wiring: RoseWiring; timeZone: string; place?: Place | null } = $props();
const STAGE_PICTURE: Record<Stage, string> = { bud, opening, 'half-bloom': halfBloom, 'full-bloom': fullBloom }; const STAGE_PICTURE: Record<Stage, string> = { bud, opening, 'half-bloom': halfBloom, 'full-bloom': fullBloom };
const MOOD_PICTURE: Record<Mood, string> = { content: fullBloom, thirsty, 'too-full': overwatered, windblown, blushing, waiting }; const MOOD_PICTURE: Record<Mood, string> = { content: fullBloom, thirsty, 'too-full': overwatered, windblown, blushing, waiting };
@@ -29,18 +33,23 @@
let pastKeys = $state.raw<readonly string[]>([]); let pastKeys = $state.raw<readonly string[]>([]);
let showSafe = $state(false); let showSafe = $state(false);
let events = $state.raw<readonly CareEvent[]>([]); let events = $state.raw<readonly CareEvent[]>([]);
/** Her opened petals (day-sentence.md). */
let opened = $state.raw<readonly SentenceOpened[]>([]);
let now = $state(0); let now = $state(0);
let kept = $state(true); let kept = $state(true);
let showNumbers = $state(false); let showNumbers = $state(false);
/** The petal was opened at the good moment in this visit: she sends the player out to the sky. */
let lookUp = $state(false);
$effect(() => { $effect(() => {
const w = wiring; const w = wiring;
now = w.now(); now = w.now();
Promise.all([w.identity(), w.loadCare(), w.pastKeys()]).then( Promise.all([w.identity(), w.loadCare(), w.pastKeys(), w.loadOpened()]).then(
([id, log, past]) => { ([id, log, past, petals]) => {
seed = id.publicKey; seed = id.publicKey;
events = log; events = log;
pastKeys = past; pastKeys = past;
opened = petals;
if (!id.kept) kept = false; if (!id.kept) kept = false;
}, },
(error: unknown) => { (error: unknown) => {
@@ -54,13 +63,28 @@
}); });
const rose = $derived<RoseNow | null>(seed === null ? null : roseAt(events, [seed, ...pastKeys], now, timeZone)); const rose = $derived<RoseNow | null>(seed === null ? null : roseAt(events, [seed, ...pastKeys], now, timeZone));
const petal = $derived<PetalNow>(seed === null ? { kind: 'none' } : petalAt(wiring.sentences, opened, [seed, ...pastKeys], now, timeZone));
const sunIsLow = $derived(place !== null && now > 0 && goodMoment(now, place));
function openPetal(): void {
if (seed === null || petal.kind !== 'folded') return;
now = wiring.now();
const event = sentenceOpened({ now, timeZone, from: seed, messageId: petal.id, clientVersion: wiring.clientVersion });
lookUp = place !== null && goodMoment(now, place);
opened = [...opened, event];
wiring.appendOpened(event).catch((error: unknown) => {
console.error('rose: the device could not keep the opened petal', error);
kept = false;
});
}
/** After she is brought back from a file: read her log and keys again. */ /** After she is brought back from a file: read her log and keys again. */
function restored(): void { function restored(): void {
Promise.all([wiring.loadCare(), wiring.pastKeys()]).then( Promise.all([wiring.loadCare(), wiring.pastKeys(), wiring.loadOpened()]).then(
([log, past]) => { ([log, past, petals]) => {
events = log; events = log;
pastKeys = past; pastKeys = past;
opened = petals;
now = wiring.now(); now = wiring.now();
}, },
(error: unknown) => console.error('rose: could not read her back after restoring', error) (error: unknown) => console.error('rose: could not read her back after restoring', error)
@@ -116,7 +140,10 @@
: rose.needs.weeds ? s.weeds : rose.needs.weeds ? s.weeds
: rose.needs.petals ? s.petals : rose.needs.petals ? s.petals
: ''; : '';
return [rose.drift > 0 ? s.back : '', need].filter(Boolean).join(' '); // The petal only when she needs nothing else: one line at a time (day-sentence.md §1).
const p = en.rose.petal;
const offer = need !== '' ? '' : petal.kind === 'folded' ? (sunIsLow ? p.goodMoment : p.waiting) : petal.kind === 'open' && lookUp ? p.lookUp : '';
return [rose.drift > 0 ? s.back : '', need || offer].filter(Boolean).join(' ');
}); });
const picture = $derived(rose ? (rose.stage === 'full-bloom' ? MOOD_PICTURE[rose.mood] : STAGE_PICTURE[rose.stage]) : bud); const picture = $derived(rose ? (rose.stage === 'full-bloom' ? MOOD_PICTURE[rose.mood] : STAGE_PICTURE[rose.stage]) : bud);
@@ -175,6 +202,8 @@
{/if} {/if}
<p class="said" role="status" aria-live="assertive">{pouring && can ? (can.tooFull ? en.rose.plenty : can.leavesLift ? en.rose.leavesLift : '') : ''}</p> <p class="said" role="status" aria-live="assertive">{pouring && can ? (can.tooFull ? en.rose.plenty : can.leavesLift ? en.rose.leavesLift : '') : ''}</p>
<Petal {petal} sentences={wiring.sentences} onopen={openPetal} />
{#if !kept} {#if !kept}
<p class="hint">{en.rose.notKept}</p> <p class="hint">{en.rose.notKept}</p>
{/if} {/if}
+6 -2
View File
@@ -1,4 +1,4 @@
import type { CareEvent } from '@rosea/schema'; import type { CareEvent, HopeSentence, SentenceOpened } from '@rosea/schema';
/** /**
* What the rose needs from the app: her care log, her key, and the clock. The app * What the rose needs from the app: her care log, her key, and the clock. The app
@@ -9,6 +9,10 @@ export interface RoseWiring {
readonly identity: () => Promise<{ readonly publicKey: string; readonly kept: boolean }>; readonly identity: () => Promise<{ readonly publicKey: string; readonly kept: boolean }>;
readonly loadCare: () => Promise<CareEvent[]>; readonly loadCare: () => Promise<CareEvent[]>;
readonly appendCare: (event: CareEvent) => Promise<void>; readonly appendCare: (event: CareEvent) => Promise<void>;
/** The verified library, as bundled. Empty: she holds no petal (day-sentence.md). */
readonly sentences: readonly HopeSentence[];
readonly loadOpened: () => Promise<SentenceOpened[]>;
readonly appendOpened: (event: SentenceOpened) => Promise<void>;
readonly clientVersion: string; readonly clientVersion: string;
/** The device's own zone: the rose's day when no sunset town is chosen (rose.md R8). */ /** The device's own zone: the rose's day when no sunset town is chosen (rose.md R8). */
readonly deviceZone: string; readonly deviceZone: string;
@@ -18,7 +22,7 @@ export interface RoseWiring {
readonly pastKeys: () => Promise<string[]>; readonly pastKeys: () => Promise<string[]>;
/** The rose as a file's contents, and bringing one back. */ /** The rose as a file's contents, and bringing one back. */
readonly exportRose: (currentKey: string) => Promise<unknown>; readonly exportRose: (currentKey: string) => Promise<unknown>;
readonly importRose: (file: unknown, currentKey: string) => Promise<{ readonly added: number }>; readonly importRose: (file: unknown, currentKey: string) => Promise<{ readonly added: number; readonly petals: number }>;
/** Hands the player a file to keep. */ /** Hands the player a file to keep. */
readonly saveFile: (name: string, text: string) => void; readonly saveFile: (name: string, text: string) => void;
/** The browser's promise to keep the garden: true, false, or null when it cannot say. */ /** The browser's promise to keep the garden: true, false, or null when it cannot say. */
+168
View File
@@ -0,0 +1,168 @@
import { addDays, careEvent, invitation, petalOrder, roseAt, sentenceOpened, sunDay, type Place } from '@rosea/engine';
import type { CareEvent, HopeSentence, SentenceOpened } from '@rosea/schema';
import { cleanup, fireEvent, render, screen, within } from '@testing-library/svelte';
import { tick } from 'svelte';
import { afterEach, describe, expect, it } from 'vitest';
import { en } from '../src/copy/en.js';
import Rose from '../src/rose/Rose.svelte';
import type { RoseWiring } from '../src/rose/types.js';
const ZONE = 'Europe/Prague';
const ME = 'M'.repeat(87);
const HOUR = 3_600_000;
const DAY = 24 * HOUR;
const prague: Place = { lat: 50.0755, lon: 14.4378, timeZone: ZONE };
const line = (id: string, text: string, over: Partial<HopeSentence['source']> = {}): HopeSentence => ({
id,
text: { en: text },
source: { work: `Fixture ${id}`, author: null, tradition: 'fixture', translation: null, publicDomain: true, verifiedBy: 'Test', verifiedAt: '2026-11-01', ...over },
use: ['sunset'],
tone: 'gentle',
promisesOutcome: false
});
const LIBRARY: HopeSentence[] = [
line('fx-one', 'The first fixture line.', { author: 'A Writer', translation: 'A Translator, 1900' }),
line('fx-two', 'The second fixture line.'),
line('fx-three', 'The third fixture line.')
];
const order = petalOrder(LIBRARY);
const textOf = (id: string): string => LIBRARY.find((s) => s.id === id)!.text.en;
const water = (now: number): CareEvent => careEvent({ now, timeZone: ZONE, from: ME, to: ME, act: 'water', amount: 0.5, clientVersion: '0.1.0' });
const opening = (now: number, messageId: string): SentenceOpened => sentenceOpened({ now, timeZone: ZONE, from: ME, messageId, clientVersion: '0.1.0' });
const quiet = (log: CareEvent[], now: number): boolean => {
const r = roseAt(log, ME, now, ZONE);
return !r.needs.water && !r.needs.wind && !r.needs.weeds && !r.needs.petals && r.mood === 'content';
};
/**
* A daytime moment, an hour or more after a helpful 08:00 pour on the same local day,
* at which she needs nothing and is not blushing: then the petal is hers to offer.
* Found with the engine, so the test does not guess the day's weeds and wind.
*/
function quietMoment(from: number): { log: CareEvent[]; now: number } {
for (let day = 0; day < 30; day++) {
const pour = from + day * DAY;
const log = [water(pour)];
for (let later = pour + HOUR; later <= pour + 10 * HOUR; later += 10 * 60_000) {
if (quiet(log, later)) return { log, now: later };
}
}
throw new Error('no quiet moment in 30 days');
}
/** A day's sunset at which she needs nothing, after a pour that afternoon. */
function quietSunset(): { log: CareEvent[]; now: number } {
for (let day = 0; day < 60; day++) {
const sunset = invitation(sunDay(addDays('2026-03-02', day), prague));
for (let hours = 2; hours <= 6; hours++) {
const log = [water(sunset - hours * HOUR)];
if (quiet(log, sunset)) return { log, now: sunset };
}
}
throw new Error('no quiet sunset in 60 days');
}
function wiring(p: { log?: CareEvent[]; opened?: SentenceOpened[]; at: number; sentences?: HopeSentence[] }): RoseWiring & { appendedOpened: SentenceOpened[] } {
const appendedOpened: SentenceOpened[] = [];
return {
identity: async () => ({ publicKey: ME, kept: true }),
loadCare: async () => p.log ?? [],
appendCare: async () => undefined,
sentences: p.sentences ?? LIBRARY,
loadOpened: async () => p.opened ?? [],
appendOpened: async (e) => {
appendedOpened.push(e);
},
clientVersion: '0.1.0',
deviceZone: ZONE,
now: () => p.at,
pastKeys: async () => [],
exportRose: async () => ({}),
importRose: async () => ({ added: 0, petals: 0 }),
saveFile: () => undefined,
keeping: { persisted: async () => false, persist: async () => true },
installHint: false,
appendedOpened
};
}
const MORNING = Date.parse('2026-03-02T08:00:00+01:00');
const bubble = (): string => document.querySelector('.bubble')?.textContent ?? '';
afterEach(() => cleanup());
describe('the folded petal (day-sentence.md)', () => {
it('with an empty library: no petal, and she says nothing about one', async () => {
const q = quietMoment(MORNING);
render(Rose, { wiring: wiring({ log: q.log, at: q.now, sentences: [] }), timeZone: ZONE });
await screen.findByRole('button', { name: en.rose.water });
expect(screen.queryByRole('button', { name: en.rose.petal.open })).toBeNull();
expect(bubble()).not.toContain('petal');
});
it('when she needs nothing, she says she keeps it, and offers it', async () => {
const q = quietMoment(MORNING);
render(Rose, { wiring: wiring({ log: q.log, at: q.now }), timeZone: ZONE, place: prague });
expect(await screen.findByRole('button', { name: en.rose.petal.open })).toBeTruthy();
expect(screen.getByRole('img', { name: en.rose.petal.folded })).toBeTruthy();
expect(bubble()).toBe(en.rose.petal.waiting);
});
it('when she needs something, the need is what she says, and the petal still waits', async () => {
render(Rose, { wiring: wiring({ at: MORNING }), timeZone: ZONE });
expect(await screen.findByRole('button', { name: en.rose.petal.open })).toBeTruthy();
// A new rose's soil is dry.
expect(bubble()).toBe(en.rose.says.dry);
});
it('opening it keeps one event, shows the words and where they come from, and moves focus to them', async () => {
const q = quietMoment(MORNING);
const w = wiring({ log: q.log, at: q.now });
render(Rose, { wiring: w, timeZone: ZONE, place: prague });
await fireEvent.click(await screen.findByRole('button', { name: en.rose.petal.open }));
await tick();
expect(w.appendedOpened).toEqual([opening(q.now, order[0]!)]);
expect(screen.queryByRole('button', { name: en.rose.petal.open })).toBeNull();
const words = document.getElementById(screen.getByRole('button', { name: en.rose.petal.today }).getAttribute('aria-controls')!)!;
expect(within(words).getByText(textOf(order[0]!))).toBeTruthy();
const s = LIBRARY.find((x) => x.id === order[0])!.source;
expect(within(words).getByText(en.rose.petal.source(s.work, s.author, s.translation))).toBeTruthy();
expect(document.activeElement).toBe(words);
// Away from sunset, opening it changes nothing in what she says.
expect(bubble()).toBe('');
});
it('opened earlier today: the same words come back, and can be folded away and back', async () => {
const q = quietMoment(MORNING);
render(Rose, { wiring: wiring({ log: q.log, at: q.now, opened: [opening(q.now - 60_000, 'fx-two')] }), timeZone: ZONE });
const today = await screen.findByRole('button', { name: en.rose.petal.today });
expect(today.getAttribute('aria-expanded')).toBe('true');
expect(screen.getByText(textOf('fx-two'))).toBeTruthy();
expect(screen.queryByRole('button', { name: en.rose.petal.open })).toBeNull();
await fireEvent.click(today);
expect(today.getAttribute('aria-expanded')).toBe('false');
expect(screen.queryByText(textOf('fx-two'))).toBeNull();
});
it('on a nearby day she also remembers an earlier one', async () => {
const q = quietMoment(MORNING);
const opened = [opening(q.now - DAY, order[0]!), opening(q.now - 60_000, order[1]!)];
render(Rose, { wiring: wiring({ log: q.log, at: q.now, opened }), timeZone: ZONE });
expect(await screen.findByText(en.rose.petal.remember)).toBeTruthy();
expect(screen.getByText(textOf(order[0]!))).toBeTruthy();
expect(screen.getByText(textOf(order[1]!))).toBeTruthy();
});
it('at sunset she says the sun is low, and once it is opened, sends the player to the sky', async () => {
const q = quietSunset();
render(Rose, { wiring: wiring({ log: q.log, at: q.now }), timeZone: ZONE, place: prague });
await screen.findByRole('button', { name: en.rose.petal.open });
expect(bubble()).toBe(en.rose.petal.goodMoment);
await fireEvent.click(screen.getByRole('button', { name: en.rose.petal.open }));
await tick();
expect(bubble()).toBe(en.rose.petal.lookUp);
});
});
+5 -2
View File
@@ -28,7 +28,10 @@ function wiring(over: Partial<RoseWiring> & { log?: CareEvent[]; at?: number } =
now: () => at, now: () => at,
pastKeys: async () => [], pastKeys: async () => [],
exportRose: async (key) => ({ format: 'rosea-rose', version: 1, keys: [key], events: [...(over.log ?? []), ...appended] }), exportRose: async (key) => ({ format: 'rosea-rose', version: 1, keys: [key], events: [...(over.log ?? []), ...appended] }),
importRose: async () => ({ added: 0 }), importRose: async () => ({ added: 0, petals: 0 }),
sentences: [],
loadOpened: async () => [],
appendOpened: async () => undefined,
saveFile: (name, text) => { saveFile: (name, text) => {
saved.push({ name, text }); saved.push({ name, text });
}, },
@@ -203,7 +206,7 @@ describe('keep her safe (keep-her-safe.md)', () => {
importRose: async (file) => { importRose: async (file) => {
expect(file).toMatchObject({ keys: [OLD] }); expect(file).toMatchObject({ keys: [OLD] });
restored = true; restored = true;
return { added: 1 }; return { added: 1, petals: 0 };
} }
}); });
render(Rose, { wiring: w, timeZone: ZONE }); render(Rose, { wiring: w, timeZone: ZONE });
+30 -5
View File
@@ -5,14 +5,21 @@
* Passes when the library has no problems AND every fixture fails with the rule * 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 * it names. A fixture that passes means a rule has stopped firing: that fails
* the run, the same as a bad sentence. * the run, the same as a bad sentence.
*
* It also holds the candidates in content/candidates/ to every rule but
* verification (day-sentence.md P8), and the app's build runs it first, so what
* ships is what passed (P5). ROSEA_LIBRARY_DIR swaps the library folder, for the
* e2e build only; the app's Vite config reads the same variable.
*/ */
import { readFileSync, readdirSync } from 'node:fs'; import { existsSync, readFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path'; import { join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { validateCandidates } from '@rosea/content/candidates';
import { validateEntry, validateLibrary, type Rule } from '@rosea/content/validate'; import { validateEntry, validateLibrary, type Rule } from '@rosea/content/validate';
const root = fileURLToPath(new URL('..', import.meta.url)); const root = fileURLToPath(new URL('..', import.meta.url));
const libraryDir = join(root, 'content', 'library'); const libraryDir = resolve(root, process.env['ROSEA_LIBRARY_DIR'] ?? join('content', 'library'));
const candidatesDir = join(root, 'content', 'candidates');
const fixturesDir = join(root, 'content', 'fixtures'); const fixturesDir = join(root, 'content', 'fixtures');
const jsonIn = (dir: string): string[] => const jsonIn = (dir: string): string[] =>
@@ -27,7 +34,7 @@ const entries: unknown[] = [];
for (const file of jsonIn(libraryDir)) { for (const file of jsonIn(libraryDir)) {
const data: unknown = JSON.parse(readFileSync(join(libraryDir, file), 'utf8')); const data: unknown = JSON.parse(readFileSync(join(libraryDir, file), 'utf8'));
if (!Array.isArray(data)) { if (!Array.isArray(data)) {
console.error(`content/library/${file}: must be an array of entries`); console.error(`${relative(root, libraryDir)}/${file}: must be an array of entries`);
failed = true; failed = true;
continue; continue;
} }
@@ -44,9 +51,27 @@ const sunset = entries.filter(
).length; ).length;
console.log( console.log(
`library: ${entries.length} entr${entries.length === 1 ? 'y' : 'ies'} in ${jsonIn(libraryDir).length} files, ${sunset} sunset (release needs 365)` `library (${relative(root, libraryDir).replaceAll('\\', '/')}): ${entries.length} entr${entries.length === 1 ? 'y' : 'ies'} in ${jsonIn(libraryDir).length} files, ${sunset} sunset (release needs 365)`
); );
// ── the candidates: proposed, not verified ─────────────────────────────────
const candidates: unknown[] = [];
const candidateFiles = existsSync(candidatesDir) ? jsonIn(candidatesDir) : [];
for (const file of candidateFiles) {
const data: unknown = JSON.parse(readFileSync(join(candidatesDir, file), 'utf8'));
if (!Array.isArray(data)) {
console.error(`content/candidates/${file}: must be an array of candidates`);
failed = true;
continue;
}
candidates.push(...data);
}
for (const p of validateCandidates(candidates, entries)) {
console.error(`candidate ${p.id} [${p.rule}] ${p.message}`);
failed = true;
}
console.log(`candidates: ${candidates.length} in ${candidateFiles.length} files, waiting for a person to verify them`);
// ── the fixtures: each must FAIL, with its named rule ─────────────────────── // ── the fixtures: each must FAIL, with its named rule ───────────────────────
interface Fixture { interface Fixture {
expect: Rule; expect: Rule;
+59
View File
@@ -0,0 +1,59 @@
/**
* `pnpm library:verify <id…> --by <name>` — the author's command (day-sentence.md P8).
*
* Run it only after reading each sentence at its `check.url` and confirming the words
* and their public-domain status yourself. It moves those candidates from
* content/candidates/ into content/library/, stamped with your name and today's
* date, and refuses (changing nothing) if the library would then fail
* `validate:library`.
*
* **Agents never run this.** `verifiedBy` records that a person checked the source
* (phase0-workspace.md D4); an agent that runs it makes that record false.
*/
import { readFileSync, readdirSync, writeFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { verifyCandidates, type Files } from '@rosea/content/candidates';
import { localDay } from '@rosea/engine';
const root = fileURLToPath(new URL('..', import.meta.url));
const libraryDir = join(root, 'content', 'library');
const candidatesDir = join(root, 'content', 'candidates');
const args = process.argv.slice(2);
const byAt = args.indexOf('--by');
const by = byAt >= 0 ? (args[byAt + 1] ?? '') : '';
const ids = args.filter((a, i) => a !== '--by' && i !== byAt + 1 && !a.startsWith('--'));
if (byAt < 0 || ids.length === 0) {
console.error('usage: pnpm library:verify <id> [<id>…] --by <your name>');
process.exit(2);
}
const read = (dir: string): Files => {
if (!existsSync(dir)) return {};
const files: Record<string, unknown[]> = {};
for (const f of readdirSync(dir).filter((f) => f.endsWith('.json')).sort()) {
const data: unknown = JSON.parse(readFileSync(join(dir, f), 'utf8'));
if (!Array.isArray(data)) throw new Error(`${dir}/${f}: must be an array`);
files[f] = data;
}
return files;
};
// The day on this machine's own clock and zone, as a person would write it.
const day = localDay(Date.now(), Intl.DateTimeFormat().resolvedOptions().timeZone);
const result = verifyCandidates({ candidates: read(candidatesDir), library: read(libraryDir), ids, by, day });
if (!result.ok) {
for (const p of result.problems) console.error(p);
console.error('Nothing was moved.');
process.exit(1);
}
const write = (dir: string, files: Files): void => {
for (const [f, entries] of Object.entries(files)) writeFileSync(join(dir, f), `${JSON.stringify(entries, null, 2)}\n`);
};
write(libraryDir, result.library);
write(candidatesDir, result.candidates);
console.log(`Verified by ${by.trim()} on ${day}: ${result.moved.join(', ')}. Run pnpm validate:library, then commit.`);
+3
View File
@@ -7,6 +7,9 @@
"tasks": { "tasks": {
"build": { "build": {
"dependsOn": ["^build"], "dependsOn": ["^build"],
// Both change what the app's build holds. Undeclared, turbo would replay a
// build made without them as if they did not matter (day-sentence.md review).
"env": ["ROSEA_BASE", "ROSEA_LIBRARY_DIR"],
"outputs": ["dist/**", "src/generated/**"] "outputs": ["dist/**", "src/generated/**"]
}, },
// Not cacheable. A test task's only output is its log, and a replayed log // Not cacheable. A test task's only output is its log, and a replayed log