From ad41c587300dc547b7020c2793e20ae21bbacbeb Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 2 Nov 2026 08:55:04 +0100 Subject: [PATCH 1/8] [schema] DaySentence: The sentence-opened event, an id and never text --- .../schemas/sentence-opened.schema.json | 39 +++++++++++++++++++ packages/schema/src/validate.ts | 4 +- packages/schema/test/schemas.test.ts | 22 ++++++++++- 3 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 packages/schema/schemas/sentence-opened.schema.json diff --git a/packages/schema/schemas/sentence-opened.schema.json b/packages/schema/schemas/sentence-opened.schema.json new file mode 100644 index 0000000..64a7917 --- /dev/null +++ b/packages/schema/schemas/sentence-opened.schema.json @@ -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+$" + } + } +} diff --git a/packages/schema/src/validate.ts b/packages/schema/src/validate.ts index 7e498dc..efb35d8 100644 --- a/packages/schema/src/validate.ts +++ b/packages/schema/src/validate.ts @@ -10,8 +10,9 @@ import { Ajv, type ErrorObject, type ValidateFunction } from 'ajv'; import careEvent from '../schemas/care-event.schema.json' with { type: 'json' }; import hopeSentence from '../schemas/hope-sentence.schema.json' with { type: 'json' }; +import sentenceOpened from '../schemas/sentence-opened.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 = | { readonly ok: true; readonly value: T } @@ -38,4 +39,5 @@ function describe(error: ErrorObject): string { export const validateHopeSentence = wrap(ajv.compile(hopeSentence)); export const validateCareEvent = wrap(ajv.compile(careEvent)); +export const validateSentenceOpened = wrap(ajv.compile(sentenceOpened)); export const validateTrace = wrap(ajv.compile(trace)); diff --git a/packages/schema/test/schemas.test.ts b/packages/schema/test/schemas.test.ts index 049252a..7dde8d1 100644 --- a/packages/schema/test/schemas.test.ts +++ b/packages/schema/test/schemas.test.ts @@ -1,5 +1,5 @@ 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_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', () => { it('accepts a day-bucketed trace', () => { expect(validateTrace(trace)).toMatchObject({ ok: true }); From 636c0bcbc02bb34ad822bd9a836a4c43f26bdea7 Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 2 Nov 2026 08:55:05 +0100 Subject: [PATCH 2/8] [engine] DaySentence: The folded petal waits until opened, one a day, never lost --- packages/engine/src/index.ts | 3 + packages/engine/src/petal/petal.ts | 142 +++++++++++++++++ packages/engine/test/petal.test.ts | 244 +++++++++++++++++++++++++++++ 3 files changed, 389 insertions(+) create mode 100644 packages/engine/src/petal/petal.ts create mode 100644 packages/engine/test/petal.test.ts diff --git a/packages/engine/src/index.ts b/packages/engine/src/index.ts index f55f281..7611e95 100644 --- a/packages/engine/src/index.ts +++ b/packages/engine/src/index.ts @@ -4,3 +4,6 @@ export { type Judged, type Mood, type Needs, type RoseKeys, type RoseNow, type Stage, type Trend } from './rose/rose.js'; export { invitation, nextInvitation, sunDay, type NamedPlace, type Place, type SunDay } from './sun/sun.js'; +export { + goodMoment, newOpened, openedIdentity, PETAL, petalAt, petalOrder, sentenceOpened, type PetalNow, type PetalSentence +} from './petal/petal.js'; diff --git a/packages/engine/src/petal/petal.ts b/packages/engine/src/petal/petal.ts new file mode 100644 index 0000000..74a44bd --- /dev/null +++ b/packages/engine/src/petal/petal.ts @@ -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 => 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(); + 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(); + 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(); + 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; +} diff --git a/packages/engine/test/petal.test.ts b/packages/engine/test/petal.test.ts new file mode 100644 index 0000000..89719c3 --- /dev/null +++ b/packages/engine/test/petal.test.ts @@ -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)); + }); +}); From cdbaf5619560a87e2b3079cfa7e61af60de2ea5c Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 2 Nov 2026 08:55:05 +0100 Subject: [PATCH 3/8] [storage] DaySentence: Opened petals in the log; the rose file carries them as version 2 --- packages/storage/src/index.ts | 103 +++++++++++++++++++----- packages/storage/test/opened.test.ts | 76 +++++++++++++++++ packages/storage/test/rose-file.test.ts | 40 +++++++-- 3 files changed, 194 insertions(+), 25 deletions(-) create mode 100644 packages/storage/test/opened.test.ts diff --git a/packages/storage/src/index.ts b/packages/storage/src/index.ts index e0c368f..2bb3f9c 100644 --- a/packages/storage/src/index.ts +++ b/packages/storage/src/index.ts @@ -2,7 +2,7 @@ * 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 * 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). * 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. */ 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 { DATABASE_NAME, type CareEvent } from '@rosea/schema'; +import { DATABASE_NAME, type CareEvent, type SentenceOpened } from '@rosea/schema'; export { DATABASE_NAME }; @@ -37,14 +37,19 @@ const SUNSET_PLACE = 'sunsetPlace'; const SELF = 'self'; const PAST_KEYS = 'pastKeys'; -/** The file a rose is saved to and brought back from (keep-her-safe.md K4). Never the private key, never the town. */ +/** + * 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 interface RoseFile { 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. */ readonly keys: readonly string[]; readonly events: readonly CareEvent[]; + readonly opened: readonly SentenceOpened[]; } export interface Storage { @@ -55,6 +60,10 @@ export interface Storage { appendCare(event: CareEvent): Promise; /** The whole care log, in the order it was written. */ loadCare(): Promise; + /** Appends one opened petal (day-sentence.md P6). Never edited. */ + appendOpened(event: SentenceOpened): Promise; + /** Every opened petal, in the order written. */ + loadOpened(): Promise; /** * 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. @@ -69,7 +78,7 @@ export interface Storage { * Brings a saved rose back: her keys join the past keys and every act not already * here is appended. Nothing is edited or removed. Rejects a file that is not a rose. */ - importRose(file: unknown, currentKey: string): Promise<{ readonly added: number }>; + importRose(file: unknown, currentKey: string): Promise<{ readonly added: number; readonly petals: number }>; close(): void; } @@ -118,21 +127,52 @@ export function asCareEvent(value: unknown): CareEvent | null { 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; + 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 = 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)); -/** 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(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 { if (typeof value !== 'object' || value === null) return null; const v = value as Record; - if (v['format'] !== ROSE_FILE_FORMAT || v['version'] !== 1) return null; - if (!isKeyList(v['keys']) || v['keys'].length === 0 || !Array.isArray(v['events'])) return null; - const events: CareEvent[] = []; - for (const e of v['events'] as unknown[]) { - const plain = asCareEvent(e); - if (plain === null) return null; - events.push(plain); - } - return { format: ROSE_FILE_FORMAT, version: 1, keys: [...new Set(v['keys'])], events }; + if (v['format'] !== ROSE_FILE_FORMAT || (v['version'] !== 1 && v['version'] !== 2)) return null; + if (!isKeyList(v['keys']) || v['keys'].length === 0) return null; + const events = every(v['events'], asCareEvent); + const opened = v['version'] === 1 ? ('opened' in v ? null : []) : every(v['opened'], asSentenceOpened); + if (events === null || opened === null) return null; + return { format: ROSE_FILE_FORMAT, version: 2, keys: [...new Set(v['keys'])], events, opened }; } class RoseaDatabase extends Dexie { @@ -181,6 +221,7 @@ export function openStorage(options?: DexieOptions): Storage { const rows = await db.events.orderBy('id').toArray(); const events: CareEvent[] = []; for (const row of rows) { + if (OTHER_KINDS.has(kindOf(row.event))) continue; const e = asCareEvent(row.event); // 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); @@ -188,6 +229,22 @@ export function openStorage(options?: DexieOptions): Storage { } 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) { if (!isIdentity(fresh)) throw new TypeError('storage: refusing to keep an identity of an unknown shape'); return db.transaction('rw', db.keys, async () => { @@ -211,7 +268,10 @@ export function openStorage(options?: DexieOptions): Storage { }, async exportRose(currentKey) { 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) { const rose = asRoseFile(file); @@ -221,10 +281,13 @@ export function openStorage(options?: DexieOptions): Storage { const past = isKeyList(row?.value) ? row.value : []; const keys = [...new Set([...past, ...rose.keys])].filter((k) => k !== currentKey); await db.profile.put({ key: PAST_KEYS, value: keys }); - const existing = (await db.events.orderBy('id').toArray()).map((r) => asCareEvent(r.event)).filter((e): e is CareEvent => e !== null); + const 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); - await db.events.bulkAdd(added.map((event) => ({ event }))); - return { added: added.length }; + const petals = newOpened(existingOpened, rose.opened); + await db.events.bulkAdd([...added, ...petals].map((event) => ({ event }))); + return { added: added.length, petals: petals.length }; }); }, close() { diff --git a/packages/storage/test/opened.test.ts b/packages/storage/test/opened.test.ts new file mode 100644 index 0000000..4d5715f --- /dev/null +++ b/packages/storage/test/opened.test.ts @@ -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); + } + }); +}); diff --git a/packages/storage/test/rose-file.test.ts b/packages/storage/test/rose-file.test.ts index e362664..9b80310 100644 --- a/packages/storage/test/rose-file.test.ts +++ b/packages/storage/test/rose-file.test.ts @@ -1,5 +1,5 @@ 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 { afterEach, describe, expect, it } from 'vitest'; 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 }); +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 open = (indexedDB: IDBFactory = new IDBFactory()): Storage => { const s = openStorage({ indexedDB, IDBKeyRange }); @@ -28,14 +32,16 @@ describe('saving the rose to a file', () => { await s.keepIdentity(await createIdentity()); await s.saveSunsetPlace({ kind: 'town', town: { name: 'Brno', region: '', country: 'Czechia', lat: 49.2, lon: 16.61, timeZone: 'Europe/Prague' } }); await s.appendCare(act(OLD, 1)); + await s.appendOpened(petal(OLD, 2)); 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/); }); it('survives a trip through JSON text unchanged', async () => { const s = open(); await s.appendCare(act(OLD, 1)); + await s.appendOpened(petal(OLD, 2)); const file = await s.exportRose(OLD); 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 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.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 () => { const old = open(); await old.appendCare(act(OLD, 1)); + await old.appendOpened(petal(OLD, 2)); const file = await old.exportRose(OLD); const here = open(); await here.appendCare(act(NEW, 5)); await here.importRose(file, NEW); - expect(await here.importRose(file, NEW)).toEqual({ added: 0 }); + expect(await here.importRose(file, NEW)).toEqual({ added: 0, petals: 0 }); 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]); }); it('a file saved on this very device adds nothing and does not list its own key as past', async () => { const s = open(); await s.appendCare(act(NEW, 1)); - expect(await s.importRose(await s.exportRose(NEW), NEW)).toEqual({ added: 0 }); + 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([]); }); @@ -79,6 +106,9 @@ describe('bringing her back', () => { for (const bad of [ null, 'rose', { format: 'other', version: 1, keys: [OLD], events: [] }, { format: ROSE_FILE_FORMAT, version: 2, keys: [OLD], events: [] }, + { format: ROSE_FILE_FORMAT, version: 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: ['short'], events: [] }, { format: ROSE_FILE_FORMAT, version: 1, keys: [OLD], events: [{ ...act(OLD, 1), note: 'hello' }] } From 5934523e45ff670f77819e6939a1e2c5ad863067 Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 2 Nov 2026 08:55:06 +0100 Subject: [PATCH 4/8] [content] DaySentence: Candidates held to every rule; library:verify for the author --- package.json | 1 + packages/content/package.json | 1 + packages/content/src/candidates.ts | 102 +++++++++++++++++++++++ packages/content/test/candidates.test.ts | 87 +++++++++++++++++++ scripts/validate-library.ts | 35 ++++++-- scripts/verify-sentences.ts | 59 +++++++++++++ 6 files changed, 280 insertions(+), 5 deletions(-) create mode 100644 packages/content/src/candidates.ts create mode 100644 packages/content/test/candidates.test.ts create mode 100644 scripts/verify-sentences.ts diff --git a/package.json b/package.json index 3280588..0e06fc2 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "test:e2e": "pnpm guard:cpu && turbo run build --filter=@rosea/app && playwright test --config=e2e/playwright.config.ts", "test:offline": "pnpm guard:cpu && turbo run build --filter=@rosea/app && playwright test --config=e2e/playwright.offline.config.ts", "validate:library": "tsx scripts/validate-library.ts", + "library:verify": "tsx scripts/verify-sentences.ts", "lint:copy": "tsx scripts/lint-copy.ts", "art:board": "tsx tools/art-prep/src/cli-board.ts", "art:accept": "tsx tools/art-prep/src/cli-accept.ts", diff --git a/packages/content/package.json b/packages/content/package.json index 9074095..c339e5d 100644 --- a/packages/content/package.json +++ b/packages/content/package.json @@ -9,6 +9,7 @@ "exports": { ".": "./src/index.ts", "./validate": "./src/validator.ts", + "./candidates": "./src/candidates.ts", "./places": "./src/places/places.ts", "./guess": "./src/places/guess.ts" }, diff --git a/packages/content/src/candidates.ts b/packages/content/src/candidates.ts new file mode 100644 index 0000000..c320a55 --- /dev/null +++ b/packages/content/src/candidates.ts @@ -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 --by ` 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>; + +const isRecord = (x: unknown): x is Record => 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(); + 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 = Object.fromEntries(Object.entries(p.library).map(([f, e]) => [f, [...e]])); + const candidates: Record = {}; + 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 }; +} diff --git a/packages/content/test/candidates.test.ts b/packages/content/test/candidates.test.ts new file mode 100644 index 0000000..fa69fa4 --- /dev/null +++ b/packages/content/test/candidates.test.ts @@ -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 = {}): Record => ({ + 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; + 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/); + }); +}); diff --git a/scripts/validate-library.ts b/scripts/validate-library.ts index 908c113..847e7cf 100644 --- a/scripts/validate-library.ts +++ b/scripts/validate-library.ts @@ -5,14 +5,21 @@ * Passes when the library has no problems AND every fixture fails with the rule * it names. A fixture that passes means a rule has stopped firing: that fails * the run, the same as a bad sentence. + * + * 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 { join } from 'node:path'; +import { existsSync, readFileSync, readdirSync } from 'node:fs'; +import { join, relative, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { validateCandidates } from '@rosea/content/candidates'; import { validateEntry, validateLibrary, type Rule } from '@rosea/content/validate'; 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 jsonIn = (dir: string): string[] => @@ -27,7 +34,7 @@ const entries: unknown[] = []; for (const file of jsonIn(libraryDir)) { const data: unknown = JSON.parse(readFileSync(join(libraryDir, file), 'utf8')); if (!Array.isArray(data)) { - console.error(`content/library/${file}: must be an array of entries`); + console.error(`${relative(root, libraryDir)}/${file}: must be an array of entries`); failed = true; continue; } @@ -44,9 +51,27 @@ const sunset = entries.filter( ).length; 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 ─────────────────────── interface Fixture { expect: Rule; diff --git a/scripts/verify-sentences.ts b/scripts/verify-sentences.ts new file mode 100644 index 0000000..d884894 --- /dev/null +++ b/scripts/verify-sentences.ts @@ -0,0 +1,59 @@ +/** + * `pnpm library:verify --by ` — 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 […] --by '); + process.exit(2); +} + +const read = (dir: string): Files => { + if (!existsSync(dir)) return {}; + const files: Record = {}; + 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.`); From 03dc69702a2dfaaab2b2ef1af8031ee661173a68 Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 2 Nov 2026 08:55:06 +0100 Subject: [PATCH 5/8] [ui] DaySentence: Her folded petal, the words and their source; the library bundled after validation --- apps/rosea/package.json | 2 +- apps/rosea/src/App.svelte | 5 + apps/rosea/src/vite-env.d.ts | 7 ++ apps/rosea/vite.config.ts | 34 ++++++ e2e/fixtures/library/fixture.json | 18 +++ e2e/petal.spec.ts | 91 +++++++++++++++ e2e/playwright.config.ts | 2 +- e2e/shell.spec.ts | 2 +- packages/ui/src/Shell.svelte | 2 +- packages/ui/src/copy/en.ts | 21 +++- packages/ui/src/rose/KeepSafe.svelte | 4 +- packages/ui/src/rose/Petal.svelte | 128 ++++++++++++++++++++ packages/ui/src/rose/Rose.svelte | 45 +++++-- packages/ui/src/rose/types.ts | 8 +- packages/ui/test/petal.test.ts | 168 +++++++++++++++++++++++++++ packages/ui/test/rose.test.ts | 7 +- 16 files changed, 525 insertions(+), 19 deletions(-) create mode 100644 e2e/fixtures/library/fixture.json create mode 100644 e2e/petal.spec.ts create mode 100644 packages/ui/src/rose/Petal.svelte create mode 100644 packages/ui/test/petal.test.ts diff --git a/apps/rosea/package.json b/apps/rosea/package.json index e2c723e..0c65151 100644 --- a/apps/rosea/package.json +++ b/apps/rosea/package.json @@ -6,7 +6,7 @@ "description": "The PWA. Renders what the engine returns; contains no growth, taming or sky logic.", "scripts": { "dev": "vite --host 127.0.0.1 --port 5173 --strictPort", - "build": "vite build", + "build": "tsx ../../scripts/validate-library.ts && vite build", "typecheck": "svelte-check --threshold error --output human" }, "dependencies": { diff --git a/apps/rosea/src/App.svelte b/apps/rosea/src/App.svelte index 3887d94..cdbb75d 100644 --- a/apps/rosea/src/App.svelte +++ b/apps/rosea/src/App.svelte @@ -7,6 +7,8 @@ import { version } from '../package.json'; // Bundled at build time, so the letter is precached and opens offline (letter-slot.md L1). import letter from '../../../docs/LETTER.md?raw'; + // 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 // device anything (CLAUDE.md §2). Only the zone's name; never GPS, never a lookup. @@ -92,6 +94,9 @@ await storage.appendCare(event); keepAfterCare(); }, + sentences, + loadOpened: () => storage.loadOpened(), + appendOpened: (event) => storage.appendOpened(event), clientVersion: version, deviceZone, now: () => Date.now(), diff --git a/apps/rosea/src/vite-env.d.ts b/apps/rosea/src/vite-env.d.ts index 0cde2af..65e826c 100644 --- a/apps/rosea/src/vite-env.d.ts +++ b/apps/rosea/src/vite-env.d.ts @@ -1,3 +1,10 @@ /// /// /// + +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; +} diff --git a/apps/rosea/vite.config.ts b/apps/rosea/vite.config.ts index cc5886a..0e4aed1 100644 --- a/apps/rosea/vite.config.ts +++ b/apps/rosea/vite.config.ts @@ -1,4 +1,7 @@ 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 { VitePWA } from 'vite-plugin-pwa'; // 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). export default defineConfig({ base: BASE, plugins: [ svelte(), contentSecurityPolicy(), + hopeLibrary(), VitePWA({ strategies: 'generateSW', // Never swap a running app silently. A new worker waits until the player diff --git a/e2e/fixtures/library/fixture.json b/e2e/fixtures/library/fixture.json new file mode 100644 index 0000000..11e10f8 --- /dev/null +++ b/e2e/fixtures/library/fixture.json @@ -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 + } +] diff --git a/e2e/petal.spec.ts b/e2e/petal.spec.ts new file mode 100644 index 0000000..430185e --- /dev/null +++ b/e2e/petal.spec.ts @@ -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 { + 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([]); + }); +}); diff --git a/e2e/playwright.config.ts b/e2e/playwright.config.ts index 7632fe3..4101856 100644 --- a/e2e/playwright.config.ts +++ b/e2e/playwright.config.ts @@ -7,7 +7,7 @@ import { defineConfig, devices } from '@playwright/test'; */ export default defineConfig({ testDir: '.', - testMatch: /(shell|update)\.spec\.ts/, + testMatch: /(shell|update|petal)\.spec\.ts/, fullyParallel: false, workers: 1, retries: 0, diff --git a/e2e/shell.spec.ts b/e2e/shell.spec.ts index 2d97d3f..ce39632 100644 --- a/e2e/shell.spec.ts +++ b/e2e/shell.spec.ts @@ -253,7 +253,7 @@ test.describe('keep her safe, in Prague at 08:00 on 1 March 2026', () => { } finally { 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/); // A fresh profile: the shape of an evicted garden, or a new phone. diff --git a/packages/ui/src/Shell.svelte b/packages/ui/src/Shell.svelte index f031126..d11e73b 100644 --- a/packages/ui/src/Shell.svelte +++ b/packages/ui/src/Shell.svelte @@ -129,7 +129,7 @@

{PRODUCT_NAME}

{en.shell.preparing}

{#if rose} - + {/if} {#if sunset && (status === 'asking' || changing)} + `${author ? `${author}, ` : ''}${work}${translation ? ` (${translation})` : ''}` + }, /** Keeping her (keep-her-safe.md). True and calm: a browser can clear a site's data. */ safe: { title: 'Keep her safe', @@ -62,7 +80,8 @@ export const en = { save: 'Save her to a file', fileNote: 'The file holds her care and when it was given. It never holds your town.', bringBack: 'Bring her back from a file', - broughtBack: (n: number): string => (n === 1 ? 'She is back, with 1 act of care.' : `She is back, with ${n} acts of care.`), + 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.', notARose: 'That file does not hold a rose.' } diff --git a/packages/ui/src/rose/KeepSafe.svelte b/packages/ui/src/rose/KeepSafe.svelte index 87a885f..4b3366c 100644 --- a/packages/ui/src/rose/KeepSafe.svelte +++ b/packages/ui/src/rose/KeepSafe.svelte @@ -49,8 +49,8 @@ const file = input.files?.[0]; if (!file) return; try { - const { added } = await wiring.importRose(JSON.parse(await file.text()), currentKey); - said = added === 0 ? en.rose.safe.alreadyHere : en.rose.safe.broughtBack(added); + const { added, petals } = await wiring.importRose(JSON.parse(await file.text()), currentKey); + said = added === 0 && petals === 0 ? en.rose.safe.alreadyHere : en.rose.safe.broughtBack(added); onrestored(); } catch (error) { // A wrong file is an ordinary thing to choose; the player is told calmly, the console fully. diff --git a/packages/ui/src/rose/Petal.svelte b/packages/ui/src/rose/Petal.svelte new file mode 100644 index 0000000..6c12538 --- /dev/null +++ b/packages/ui/src/rose/Petal.svelte @@ -0,0 +1,128 @@ + + +{#if petal.kind === 'folded'} +
+ {en.rose.petal.folded} + +
+{:else if petal.kind === 'open' && today} +
+ + {#if showing} +
+
+
{today.text.en}
+
{source(today)}
+
+ {#if remembered} +

{en.rose.petal.remember}

+
+
{remembered.text.en}
+
{source(remembered)}
+
+ {/if} +
+ {/if} +
+{/if} + + diff --git a/packages/ui/src/rose/Rose.svelte b/packages/ui/src/rose/Rose.svelte index b022a16..40a86d8 100644 --- a/packages/ui/src/rose/Rose.svelte +++ b/packages/ui/src/rose/Rose.svelte @@ -1,8 +1,12 @@