[engine] Rose: Name a rose by her current and past keys, replay each key on its own, and add each act once
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
export { addDays, daysBetween, isLocalDay, localDay, localMinutes, type LocalDay } from './time/localDay.js';
|
export { addDays, daysBetween, isLocalDay, localDay, localMinutes, type LocalDay } from './time/localDay.js';
|
||||||
export {
|
export {
|
||||||
careEvent, judgeCare, OWN_TRACE, petalsOn, pour, ROSE, roseAt, seeded, stageFor, weedsOn, windOn,
|
careEvent, careIdentity, judgeCare, newCare, OWN_TRACE, petalsOn, pour, ROSE, roseAt, seeded, stageFor, weedsOn, windOn,
|
||||||
type Judged, type Mood, type Needs, type RoseNow, type Stage, type Trend
|
type Judged, type Mood, type Needs, type RoseKeys, type RoseNow, type Stage, type Trend
|
||||||
} from './rose/rose.js';
|
} from './rose/rose.js';
|
||||||
export { invitation, nextInvitation, sunDay, type NamedPlace, type Place, type SunDay } from './sun/sun.js';
|
export { invitation, nextInvitation, sunDay, type NamedPlace, type Place, type SunDay } from './sun/sun.js';
|
||||||
|
|||||||
@@ -124,6 +124,23 @@ export function careEvent(p: {
|
|||||||
return { ...base, amount: Math.round(Math.min(1, Math.max(0, p.amount ?? 0)) * 100) / 100 };
|
return { ...base, amount: Math.round(Math.min(1, Math.max(0, p.amount ?? 0)) * 100) / 100 };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** What makes two care events the same act: the same moment, giver, rose and act. */
|
||||||
|
export const careIdentity = (e: CareEvent): string => `${e.ts}|${e.from}|${e.to}|${e.act}|${e.amount ?? ''}`;
|
||||||
|
|
||||||
|
/** The acts in `incoming` that `existing` does not hold yet: bringing a rose back twice adds nothing twice. */
|
||||||
|
export function newCare(existing: readonly CareEvent[], incoming: readonly CareEvent[]): CareEvent[] {
|
||||||
|
const seen = new Set(existing.map(careIdentity));
|
||||||
|
const out: CareEvent[] = [];
|
||||||
|
for (const e of incoming) {
|
||||||
|
const id = careIdentity(e);
|
||||||
|
if (!seen.has(id)) {
|
||||||
|
seen.add(id);
|
||||||
|
out.push(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
/** One act of the log, judged: did it meet a real need? */
|
/** One act of the log, judged: did it meet a real need? */
|
||||||
export interface Judged {
|
export interface Judged {
|
||||||
readonly event: CareEvent;
|
readonly event: CareEvent;
|
||||||
@@ -141,14 +158,26 @@ interface Replay {
|
|||||||
const fall = (level: number, from: number | null, to: number): number =>
|
const fall = (level: number, from: number | null, to: number): number =>
|
||||||
from === null ? level : Math.max(0, level - (ROSE.waterFallPerDay * Math.max(0, to - from)) / DAY_MS);
|
from === null ? level : Math.max(0, level - (ROSE.waterFallPerDay * Math.max(0, to - from)) / DAY_MS);
|
||||||
|
|
||||||
/** The log in order, each act judged. Only care given to this rose counts. */
|
/**
|
||||||
function replay(events: readonly CareEvent[], seed: string, timeZone: string): Replay {
|
* The rose's keys: the current one first, then any she was named by before, on
|
||||||
|
* another device (keep-her-safe.md K2). A single key is a rose that never moved.
|
||||||
|
*/
|
||||||
|
export type RoseKeys = string | readonly string[];
|
||||||
|
const keyList = (keys: RoseKeys): readonly string[] => (typeof keys === 'string' ? [keys] : keys);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The care given under one key, in order, each act judged with that key's own
|
||||||
|
* weeds, petals and wind. `inherited` are days of care earned under her other keys:
|
||||||
|
* they count towards her stage, so a moved rose drops petals as she did before.
|
||||||
|
*/
|
||||||
|
function replay(events: readonly CareEvent[], seed: string, timeZone: string, inherited: ReadonlySet<LocalDay> = new Set()): Replay {
|
||||||
const mine = events
|
const mine = events
|
||||||
.map((e, i) => ({ e, i }))
|
.map((e, i) => ({ e, i }))
|
||||||
.filter(({ e }) => e.kind === 'care' && e.to === seed)
|
.filter(({ e }) => e.kind === 'care' && e.to === seed)
|
||||||
.sort((a, b) => a.e.ts - b.e.ts || a.i - b.i)
|
.sort((a, b) => a.e.ts - b.e.ts || a.i - b.i)
|
||||||
.map(({ e }) => e);
|
.map(({ e }) => e);
|
||||||
|
|
||||||
|
const grownBy = (day: LocalDay): number => new Set([...days, ...[...inherited].filter((d) => d <= day)]).size;
|
||||||
const days = new Set<LocalDay>();
|
const days = new Set<LocalDay>();
|
||||||
const met = new Map<string, true>();
|
const met = new Map<string, true>();
|
||||||
const judged: Judged[] = [];
|
const judged: Judged[] = [];
|
||||||
@@ -172,7 +201,7 @@ function replay(events: readonly CareEvent[], seed: string, timeZone: string): R
|
|||||||
if (helped) met.set(`${day}|weeds`, true);
|
if (helped) met.set(`${day}|weeds`, true);
|
||||||
break;
|
break;
|
||||||
case 'petals':
|
case 'petals':
|
||||||
helped = stageFor(days.size) !== 'bud' && petalsOn(seed, day) && !met.has(`${day}|petals`);
|
helped = stageFor(grownBy(day)) !== 'bud' && petalsOn(seed, day) && !met.has(`${day}|petals`);
|
||||||
if (helped) met.set(`${day}|petals`, true);
|
if (helped) met.set(`${day}|petals`, true);
|
||||||
break;
|
break;
|
||||||
case 'shade': {
|
case 'shade': {
|
||||||
@@ -189,17 +218,36 @@ function replay(events: readonly CareEvent[], seed: string, timeZone: string): R
|
|||||||
return { judged, days, water: { level, at }, met, firstDay: mine[0]?.localDay ?? null };
|
return { judged, days, water: { level, at }, met, firstDay: mine[0]?.localDay ?? null };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Every act of the log with whether it helped, in order. */
|
/**
|
||||||
export function judgeCare(events: readonly CareEvent[], seed: string, timeZone: string): readonly Judged[] {
|
* Replays every key separately: the past keys first, then the current one, which
|
||||||
return replay(events, seed, timeZone).judged;
|
* inherits their days. Each key's judgments depend only on its own care, so adding
|
||||||
|
* another key's log can never take a day of care away (keep-her-safe.md K3).
|
||||||
|
*/
|
||||||
|
function replayAll(events: readonly CareEvent[], keys: RoseKeys, timeZone: string): { current: Replay; all: readonly Replay[]; days: ReadonlySet<LocalDay> } {
|
||||||
|
const [currentKey = '', ...past] = keyList(keys);
|
||||||
|
const pastReplays = past.map((k) => replay(events, k, timeZone));
|
||||||
|
const inherited = new Set(pastReplays.flatMap((r) => [...r.days]));
|
||||||
|
const current = replay(events, currentKey, timeZone, inherited);
|
||||||
|
return { current, all: [current, ...pastReplays], days: new Set([...inherited, ...current.days]) };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The rose at `now`: a pure replay of `events` for the rose whose key is `seed`. */
|
/** Every act given to the rose, with whether it helped, in time order. */
|
||||||
export function roseAt(events: readonly CareEvent[], seed: string, now: number, timeZone: string): RoseNow {
|
export function judgeCare(events: readonly CareEvent[], keys: RoseKeys, timeZone: string): readonly Judged[] {
|
||||||
const r = replay(events, seed, timeZone);
|
return replayAll(events, keys, timeZone).all.flatMap((r) => r.judged).sort((a, b) => a.event.ts - b.event.ts);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The rose at `now`: a pure replay of `events` for the rose named by `keys`. Her
|
||||||
|
* water and today's needs come from the current key; her days of care, stage and
|
||||||
|
* drift from all of them.
|
||||||
|
*/
|
||||||
|
export function roseAt(events: readonly CareEvent[], keys: RoseKeys, now: number, timeZone: string): RoseNow {
|
||||||
|
const { current: r, all, days } = replayAll(events, keys, timeZone);
|
||||||
|
const seed = keyList(keys)[0] ?? '';
|
||||||
const today = localDay(now, timeZone);
|
const today = localDay(now, timeZone);
|
||||||
const water = fall(r.water.level, r.water.at, now);
|
const water = fall(r.water.level, r.water.at, now);
|
||||||
const stage = stageFor(r.days.size);
|
const stage = stageFor(days.size);
|
||||||
|
const firstDay = all.map((x) => x.firstDay).filter((d): d is LocalDay => d !== null).sort()[0] ?? null;
|
||||||
|
|
||||||
const wind = windOn(seed, today);
|
const wind = windOn(seed, today);
|
||||||
const minute = localMinutes(now, timeZone);
|
const minute = localMinutes(now, timeZone);
|
||||||
@@ -210,15 +258,15 @@ export function roseAt(events: readonly CareEvent[], seed: string, now: number,
|
|||||||
wind: wind !== null && minute >= wind[0] && minute < wind[1] && !r.met.has(`${today}|wind`)
|
wind: wind !== null && minute >= wind[0] && minute < wind[1] && !r.met.has(`${today}|wind`)
|
||||||
};
|
};
|
||||||
|
|
||||||
const careDays = [...r.days].filter((d) => d <= today).sort();
|
const careDays = [...days].filter((d) => d <= today).sort();
|
||||||
const lastDayOfCare = careDays.at(-1) ?? null;
|
const lastDayOfCare = careDays.at(-1) ?? null;
|
||||||
const since = daysBetween(lastDayOfCare ?? r.firstDay ?? today, today);
|
const since = daysBetween(lastDayOfCare ?? firstDay ?? today, today);
|
||||||
const drift = since >= ROSE.driftDays[1] ? 2 : since >= ROSE.driftDays[0] ? 1 : 0;
|
const drift = since >= ROSE.driftDays[1] ? 2 : since >= ROSE.driftDays[0] ? 1 : 0;
|
||||||
const weekStart = addDays(today, -6);
|
const weekStart = addDays(today, -6);
|
||||||
const warmth = careDays.filter((d) => d >= weekStart).length;
|
const warmth = careDays.filter((d) => d >= weekStart).length;
|
||||||
const trend: Trend = drift > 0 ? 'waiting' : lastDayOfCare !== null && daysBetween(lastDayOfCare, today) <= 1 ? 'growing' : 'steady';
|
const trend: Trend = drift > 0 ? 'waiting' : lastDayOfCare !== null && daysBetween(lastDayOfCare, today) <= 1 ? 'growing' : 'steady';
|
||||||
|
|
||||||
const lastHelp = [...r.judged].reverse().find((j) => j.helped && j.event.ts <= now);
|
const lastHelp = all.flatMap((x) => x.judged).filter((j) => j.helped && j.event.ts <= now).sort((a, b) => b.event.ts - a.event.ts)[0];
|
||||||
const blushing = lastHelp !== undefined && now - lastHelp.event.ts < ROSE.blushMinutes * 60_000;
|
const blushing = lastHelp !== undefined && now - lastHelp.event.ts < ROSE.blushMinutes * 60_000;
|
||||||
const mood: Mood = blushing ? 'blushing'
|
const mood: Mood = blushing ? 'blushing'
|
||||||
: water > ROSE.tooFull ? 'too-full'
|
: water > ROSE.tooFull ? 'too-full'
|
||||||
@@ -227,5 +275,5 @@ export function roseAt(events: readonly CareEvent[], seed: string, now: number,
|
|||||||
: water < ROSE.thirsty ? 'thirsty'
|
: water < ROSE.thirsty ? 'thirsty'
|
||||||
: 'content';
|
: 'content';
|
||||||
|
|
||||||
return { stage, drift, mood, water, needs, daysOfCare: r.days.size, warmth, trend, lastDayOfCare };
|
return { stage, drift, mood, water, needs, daysOfCare: days.size, warmth, trend, lastDayOfCare };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import fc from 'fast-check';
|
import fc from 'fast-check';
|
||||||
import type { CareEvent } from '@rosea/schema';
|
import type { CareEvent } from '@rosea/schema';
|
||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { careEvent, judgeCare, OWN_TRACE, petalsOn, pour, ROSE, roseAt, stageFor, weedsOn, windOn, type Stage } from '../src/rose/rose.js';
|
import { careEvent, judgeCare, newCare, OWN_TRACE, petalsOn, pour, ROSE, roseAt, stageFor, weedsOn, windOn, type Stage } from '../src/rose/rose.js';
|
||||||
import { addDays, localDay } from '../src/time/localDay.js';
|
import { addDays, localDay } from '../src/time/localDay.js';
|
||||||
|
|
||||||
const ZONE = 'Europe/Prague';
|
const ZONE = 'Europe/Prague';
|
||||||
@@ -208,3 +208,50 @@ describe('careEvent — one act as the log keeps it', () => {
|
|||||||
expect(validateCareEvent(s)).toMatchObject({ ok: true });
|
expect(validateCareEvent(s)).toMatchObject({ ok: true });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('a rose brought back under a new key (keep-her-safe.md)', () => {
|
||||||
|
const NEW = 'N'.repeat(43);
|
||||||
|
const careAs = (to: string, ts: number, amount = 0.5): CareEvent => ({ ...care(ts, 'water', amount), from: to, to });
|
||||||
|
|
||||||
|
it('keeps every day of care given under her old key, and starts her water afresh under the new one', () => {
|
||||||
|
const old = dailyWater(12);
|
||||||
|
const now = START + 12 * DAY;
|
||||||
|
const before = roseAt(old, ME, now, ZONE);
|
||||||
|
const moved = roseAt(old, [NEW, ME], now, ZONE);
|
||||||
|
expect(moved.daysOfCare).toBe(before.daysOfCare);
|
||||||
|
expect(moved.stage).toBe(before.stage);
|
||||||
|
expect(moved.lastDayOfCare).toBe(before.lastDayOfCare);
|
||||||
|
expect(moved.water).toBe(ROSE.waterStart); // no care under the new key yet
|
||||||
|
// Care under the new key adds to the old days.
|
||||||
|
const after = roseAt([...old, careAs(NEW, now)], [NEW, ME], now + 60_000, ZONE);
|
||||||
|
expect(after.daysOfCare).toBe(before.daysOfCare + 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a moved rose that is opening drops petals, and gathering them helps', () => {
|
||||||
|
const old = dailyWater(ROSE.stageDays[0]);
|
||||||
|
const from = START + ROSE.stageDays[0] * DAY;
|
||||||
|
let day = from;
|
||||||
|
while (!petalsOn(NEW, localDay(day, ZONE))) day += DAY;
|
||||||
|
expect(roseAt(old, [NEW, ME], day, ZONE).needs.petals).toBe(true);
|
||||||
|
const gathered = { ...care(day, 'petals'), from: NEW, to: NEW };
|
||||||
|
expect(judgeCare([...old, gathered], [NEW, ME], ZONE).at(-1)?.helped).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('merging two logs never takes a day of care away from either', () => {
|
||||||
|
const act = fc.constantFrom<CareEvent['act']>('water', 'shade', 'weed', 'petals');
|
||||||
|
const logAs = (to: string) => fc.array(fc.tuple(fc.integer({ min: 0, max: 40 * 24 * 60 }), act, fc.double({ min: 0, max: 1, noNaN: true })), { maxLength: 40 })
|
||||||
|
.map((xs) => xs.map(([m, a, amount]) => ({ ...care(START + m * 60_000, a, amount), from: to, to })));
|
||||||
|
fc.assert(fc.property(logAs(ME), logAs(NEW), (a, b) => {
|
||||||
|
const end = START + 50 * DAY;
|
||||||
|
const merged = roseAt([...a, ...b], [NEW, ME], end, ZONE).daysOfCare;
|
||||||
|
return merged >= roseAt(a, ME, end, ZONE).daysOfCare && merged >= roseAt(b, NEW, end, ZONE).daysOfCare;
|
||||||
|
}), { numRuns: 150 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('newCare adds each act once, however often the same file is brought back', () => {
|
||||||
|
const log = dailyWater(3);
|
||||||
|
expect(newCare([], log)).toEqual(log);
|
||||||
|
expect(newCare(log, log)).toEqual([]);
|
||||||
|
expect(newCare(log.slice(0, 1), [...log, ...log])).toEqual(log.slice(1));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user