Files
Rosea/packages/engine/src/rose/rose.ts
T

280 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* The rose (GAMEPLAY.md §1–2, .agents/features/rose.md). Pure: the rose at any
* moment is a replay of her care log. Time is `now`; the only "randomness" is a
* hash of her key and the day, so every replay on every device agrees.
*
* She grows from the number of local days on which care helped, never from a
* streak and never from minutes. She drifts when left, and drift never lowers
* what was grown.
*/
import type { CareEvent } from '@rosea/schema';
import { addDays, daysBetween, localDay, localMinutes, type LocalDay } from '../time/localDay.js';
/** Every tuning number in one place. Assumptions for the author: rose.md R2, R4, R5, R6. */
export const ROSE = {
/** A new rose's water: a little low, so the first pour helps and teaches. */
waterStart: 0.3,
waterFallPerDay: 0.3,
/** What a full can (amount 1) adds. */
fullPour: 0.6,
thirsty: 0.25,
/** Below this she needs water; at or above it her leaves lift. */
enough: 0.4,
tooFull: 0.95,
weedChance: 0.4,
petalChance: 0.3,
windChance: 0.25,
windEarliest: 9 * 60,
windLatest: 18 * 60,
windMinutes: 90,
/** Days of care to reach opening, half bloom, full bloom. */
stageDays: [3, 10, 25],
/** Days since the last day of care when she turns a little away, then closes a little. */
driftDays: [3, 7],
/** How long she blushes after a helpful act. */
blushMinutes: 20
} as const;
const DAY_MS = 86_400_000;
export type Stage = 'bud' | 'opening' | 'half-bloom' | 'full-bloom';
export type Mood = 'content' | 'blushing' | 'too-full' | 'windblown' | 'waiting' | 'thirsty';
export type Trend = 'growing' | 'steady' | 'waiting';
export interface Needs {
readonly water: boolean;
readonly weeds: boolean;
readonly petals: boolean;
readonly wind: boolean;
}
export interface RoseNow {
readonly stage: Stage;
/** 0: facing you; 1: turned a little away; 2: closed a little, waiting. Never lowers the stage. */
readonly drift: 0 | 1 | 2;
readonly mood: Mood;
/** Water level now: 0 is dry, from `ROSE.enough` her leaves lift, above `ROSE.tooFull` too full. */
readonly water: number;
readonly needs: Needs;
/** Local days on which care helped, in all. */
readonly daysOfCare: number;
/** Days of care in the last seven local days, today included. */
readonly warmth: number;
readonly trend: Trend;
readonly lastDayOfCare: LocalDay | null;
}
/** A number in [0, 1) from the rose's key, a day and a topic: the same on every replay. FNV-1a. */
export function seeded(seed: string, day: LocalDay, topic: string): number {
let h = 0x811c9dc5;
for (const ch of `${seed}|${day}|${topic}`) {
h ^= ch.codePointAt(0)!;
h = Math.imul(h, 0x01000193) >>> 0;
}
return h / 0x1_0000_0000;
}
export const weedsOn = (seed: string, day: LocalDay): boolean => seeded(seed, day, 'weeds') < ROSE.weedChance;
export const petalsOn = (seed: string, day: LocalDay): boolean => seeded(seed, day, 'petals') < ROSE.petalChance;
/** The day's wind, as [first, last) minutes on the local clock, or null on a still day. */
export function windOn(seed: string, day: LocalDay): readonly [number, number] | null {
if (seeded(seed, day, 'wind') >= ROSE.windChance) return null;
const start = ROSE.windEarliest + Math.floor(seeded(seed, day, 'wind-start') * (ROSE.windLatest - ROSE.windEarliest));
return [start, start + ROSE.windMinutes];
}
export function stageFor(daysOfCare: number): Stage {
const [opening, half, full] = ROSE.stageDays;
return daysOfCare >= full ? 'full-bloom' : daysOfCare >= half ? 'half-bloom' : daysOfCare >= opening ? 'opening' : 'bud';
}
/** What a pour of `amount` (0–1) would do, for the can in the player's hand. */
export function pour(waterNow: number, amount: number): { readonly after: number; readonly leavesLift: boolean; readonly tooFull: boolean; readonly helps: boolean } {
const after = waterNow + Math.min(1, Math.max(0, amount)) * ROSE.fullPour;
const tooFull = after > ROSE.tooFull;
return { after, leavesLift: after >= ROSE.enough, tooFull, helps: waterNow < ROSE.enough && after >= ROSE.enough && !tooFull };
}
/**
* The petal a player's care leaves behind (CLAUDE.md §6.2, `trace`). Every player's
* is rose-coloured until friends can tell them apart (Phase 3).
*/
export const OWN_TRACE = 'petal:rose';
/**
* One act of care as the log keeps it. The day is computed here, by the one module
* that computes days, in the rose's zone (rose.md R8). `amount` only for water.
*/
export function careEvent(p: {
readonly now: number;
readonly timeZone: string;
readonly from: string;
readonly to: string;
readonly act: CareEvent['act'];
readonly amount?: number;
readonly clientVersion: string;
}): CareEvent {
const base = {
kind: 'care' as const, ts: Math.round(p.now), localDay: localDay(p.now, p.timeZone), from: p.from, to: p.to,
act: p.act, trace: OWN_TRACE, messageId: null, clientVersion: p.clientVersion
};
if (p.act !== 'water') return base;
// Two decimals are feel enough, and keep the log free of float noise.
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? */
export interface Judged {
readonly event: CareEvent;
readonly helped: boolean;
}
interface Replay {
readonly judged: readonly Judged[];
readonly days: ReadonlySet<LocalDay>;
readonly water: { readonly level: number; readonly at: number | null };
readonly met: ReadonlyMap<string, true>;
readonly firstDay: LocalDay | null;
}
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);
/**
* 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
.map((e, i) => ({ e, i }))
.filter(({ e }) => e.kind === 'care' && e.to === seed)
.sort((a, b) => a.e.ts - b.e.ts || a.i - b.i)
.map(({ e }) => e);
const grownBy = (day: LocalDay): number => new Set([...days, ...[...inherited].filter((d) => d <= day)]).size;
const days = new Set<LocalDay>();
const met = new Map<string, true>();
const judged: Judged[] = [];
let level: number = ROSE.waterStart;
let at: number | null = null;
for (const e of mine) {
const day = e.localDay; // the day recorded when it happened is the day that counts
let helped = false;
level = fall(level, at, e.ts);
at = e.ts;
switch (e.act) {
case 'water': {
const p = pour(level, e.amount ?? 0);
helped = p.helps;
level = p.after;
break;
}
case 'weed':
helped = weedsOn(seed, day) && !met.has(`${day}|weeds`);
if (helped) met.set(`${day}|weeds`, true);
break;
case 'petals':
helped = stageFor(grownBy(day)) !== 'bud' && petalsOn(seed, day) && !met.has(`${day}|petals`);
if (helped) met.set(`${day}|petals`, true);
break;
case 'shade': {
const wind = windOn(seed, day);
const minute = localMinutes(e.ts, timeZone);
helped = wind !== null && minute >= wind[0] && minute < wind[1] && !met.has(`${day}|wind`);
if (helped) met.set(`${day}|wind`, true);
break;
}
}
if (helped) days.add(day);
judged.push({ event: e, helped });
}
return { judged, days, water: { level, at }, met, firstDay: mine[0]?.localDay ?? null };
}
/**
* Replays every key separately: the past keys first, then the current one, which
* 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]) };
}
/** Every act given to the rose, with whether it helped, in time order. */
export function judgeCare(events: readonly CareEvent[], keys: RoseKeys, timeZone: string): readonly Judged[] {
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 water = fall(r.water.level, r.water.at, now);
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 minute = localMinutes(now, timeZone);
const needs: Needs = {
water: water < ROSE.enough,
weeds: weedsOn(seed, today) && !r.met.has(`${today}|weeds`),
petals: stage !== 'bud' && petalsOn(seed, today) && !r.met.has(`${today}|petals`),
wind: wind !== null && minute >= wind[0] && minute < wind[1] && !r.met.has(`${today}|wind`)
};
const careDays = [...days].filter((d) => d <= today).sort();
const lastDayOfCare = careDays.at(-1) ?? null;
const since = daysBetween(lastDayOfCare ?? firstDay ?? today, today);
const drift = since >= ROSE.driftDays[1] ? 2 : since >= ROSE.driftDays[0] ? 1 : 0;
const weekStart = addDays(today, -6);
const warmth = careDays.filter((d) => d >= weekStart).length;
const trend: Trend = drift > 0 ? 'waiting' : lastDayOfCare !== null && daysBetween(lastDayOfCare, today) <= 1 ? 'growing' : 'steady';
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 mood: Mood = blushing ? 'blushing'
: water > ROSE.tooFull ? 'too-full'
: needs.wind ? 'windblown'
: drift > 0 ? 'waiting'
: water < ROSE.thirsty ? 'thirsty'
: 'content';
return { stage, drift, mood, water, needs, daysOfCare: days.size, warmth, trend, lastDayOfCare };
}