[engine] DaySentence: The folded petal waits until opened, one a day, never lost

This commit is contained in:
2026-11-02 08:55:05 +01:00
parent ad41c58730
commit 636c0bcbc0
3 changed files with 389 additions and 0 deletions
+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));
});
});