[engine] DaySentence: The folded petal waits until opened, one a day, never lost
This commit is contained in:
@@ -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';
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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));
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user