evOo-local/packages/adapters/src/coach-rhythm.ts
Claude 68f9dfb34b
fix(coach): move check-ins when the user's time zone changes
The coach check-ins are main-bot routines scheduled in the profile time zone, but a later
zone change (About you, onboarding, the main bot's update_user_profile tool, or forgetting
the whole profile) left them in the old zone until the rhythm was saved again, so they fired
at the wrong local time.

syncCoachTimeZone, next to the rhythm code, moves the main bot's coach routines that are not
in the current profile zone into it, recomputes the next run of armed ones and re-arms their
wakeup. Paused check-ins move but stay paused, routines the user made are never touched, users
without check-ins get none, and a save that leaves the zone as it is changes nothing. The
profile update and forget RPCs and the profile tool call it whenever they write the zone.

Quiet hours, the daily nudge cap and coach dates are evaluated in the profile zone when they
are used, so they need no migration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u
2026-10-04 04:08:05 +00:00

178 lines
7.5 KiB
TypeScript

import type { JobPublisher } from "@rakazo/adapter-kit";
import { routineJobKey, routineWakeupJob } from "@rakazo/adapter-kit";
import type { CoachRhythm, CoachRoutineKey } from "@rakazo/contracts";
import {
COACH_RHYTHM_OFF,
COACH_ROUTINE_KEYS,
COACH_ROUTINE_NAMES,
clockTimeToMinutes,
minutesToClockTime,
} from "@rakazo/contracts";
import { nextCronDate, nextCronDateAcross } from "@rakazo/core";
import type { PrismaClient } from "@rakazo/db";
import { coachTimeZone, ensureMainConversation, findMainBotId } from "@rakazo/db";
export const COACH_KEYS = COACH_ROUTINE_KEYS;
export type CoachKey = CoachRoutineKey;
/**
* The main bot's check-ins. Names show in the main bot's routine list; prompts are its task when
* a check-in fires. Product text in English: the main bot answers in the user's language, and
* its instructions name the coach tools it has.
*/
export const COACH_ROUTINES: Record<CoachKey, { name: string; prompt: string }> = {
morning: {
name: COACH_ROUTINE_NAMES.morning,
prompt:
"Morning check-in. Review the user's active goals and habits, and today's calendar if a calendar app is connected. Write today's brief: two to five short lines on what matters most today, and save it. Then post one short, friendly message with the gist. Leave out what is not relevant today.",
},
evening: {
name: COACH_ROUTINE_NAMES.evening,
prompt:
"Evening check-in. Log as check-ins what the user already told you about today. Then ask in one or two sentences how the day went and about habits not yet checked off. Keep it light, and do not ask when everything is already logged.",
},
weekly: {
name: COACH_ROUTINE_NAMES.weekly,
prompt:
"Weekly review. Look at the past week's check-ins and the progress on the user's active goals. Post a short summary: what moved, what stalled, and one concrete suggestion for next week. Offer to adjust, complete or drop goals, and change them only when the user agrees.",
},
};
export interface CoachRhythmDeps {
prisma: PrismaClient;
jobs: Pick<JobPublisher, "enqueue" | "cancel">;
}
/** The cron for one check-in, or null when it is off. */
export function coachCron(key: CoachKey, rhythm: CoachRhythm): string | null {
const slot = key === "weekly" ? rhythm.weekly : rhythm[key];
if (!slot) return null;
const minutes = clockTimeToMinutes(typeof slot === "string" ? slot : slot.time);
return `${minutes % 60} ${Math.floor(minutes / 60)} * * ${typeof slot === "string" ? "*" : slot.day}`;
}
/** Reads a check-in back from its routine; a schedule edited into another shape reads as off. */
function rhythmSlot(key: CoachKey, crons: readonly string[]) {
const match =
crons.length === 1 ? /^(\d{1,2}) (\d{1,2}) \* \* (\*|[0-6])$/.exec(crons[0]!) : null;
if (!match || Number(match[1]) > 59 || Number(match[2]) > 23) return null;
const time = minutesToClockTime(Number(match[2]) * 60 + Number(match[1]));
if (key === "weekly") return match[3] === "*" ? null : { day: Number(match[3]), time };
return match[3] === "*" ? time : null;
}
function isCoachKey(value: string | null): value is CoachKey {
return (COACH_KEYS as readonly string[]).includes(value ?? "");
}
/** The user's check-in times, read from the main bot's active coach routines. */
export async function getCoachRhythm(prisma: PrismaClient, userId: string): Promise<CoachRhythm> {
const botId = await findMainBotId(prisma, userId);
if (!botId) return { ...COACH_RHYTHM_OFF };
const routines = await prisma.routine.findMany({
where: { botId, userId, active: true, coachKey: { not: null } },
select: { coachKey: true, crons: true },
});
const rhythm: CoachRhythm = { ...COACH_RHYTHM_OFF };
for (const routine of routines) {
if (!isCoachKey(routine.coachKey)) continue;
const slot = rhythmSlot(routine.coachKey, routine.crons);
if (routine.coachKey === "weekly") rhythm.weekly = slot as CoachRhythm["weekly"];
else rhythm[routine.coachKey] = slot as string | null;
}
return rhythm;
}
/**
* Makes the main bot's coach routines match `rhythm`: one routine per check-in that is on,
* waking in the main conversation in the user's time zone. Check-ins that are off are deleted.
* Calling it again with the same rhythm changes nothing.
*/
export async function setCoachRhythm(
deps: CoachRhythmDeps,
input: { userId: string; rhythm: CoachRhythm },
): Promise<CoachRhythm> {
const { prisma, jobs } = deps;
const { userId, rhythm } = input;
const anyOn = COACH_KEYS.some((key) => coachCron(key, rhythm) !== null);
const conversation = anyOn ? await ensureMainConversation(prisma, userId) : null;
const botId = conversation?.leadBotId ?? (await findMainBotId(prisma, userId));
if (!botId) return { ...COACH_RHYTHM_OFF };
const existing = await prisma.routine.findMany({
where: { botId, userId, coachKey: { not: null } },
});
const timezone = anyOn ? await coachTimeZone(prisma, userId) : "UTC";
for (const key of COACH_KEYS) {
const cron = coachCron(key, rhythm);
const current = existing.find((routine) => routine.coachKey === key);
if (!cron || !conversation) {
if (current) {
await prisma.routine.deleteMany({ where: { id: current.id } });
await jobs.cancel(routineJobKey(current.id));
}
continue;
}
const { name, prompt } = COACH_ROUTINES[key];
const unchanged =
current?.active &&
current.nextRunAt &&
current.crons.length === 1 &&
current.crons[0] === cron &&
current.timezone === timezone &&
current.threadId === conversation.threadId &&
current.spaceId === conversation.spaceId &&
current.name === name &&
current.prompt === prompt;
if (unchanged) continue;
const nextRunAt = nextCronDate(cron, new Date(), timezone);
const fields = {
spaceId: conversation.spaceId,
threadId: conversation.threadId,
name,
prompt,
crons: [cron],
timezone,
active: true,
notify: true,
nextRunAt,
};
const saved = await prisma.routine.upsert({
where: { botId_coachKey: { botId, coachKey: key } },
create: { ...fields, botId, userId, coachKey: key },
update: fields,
});
// The job reconciler re-arms an active routine whose wakeup could not be enqueued.
await jobs.enqueue(routineWakeupJob(saved.id, nextRunAt));
}
return getCoachRhythm(prisma, userId);
}
/**
* Moves the main bot's check-ins into the user's current profile time zone and re-arms each
* armed one for its next local run. Check-ins already in that zone and routines the user made
* stay as they are, so calling it after every time zone save is safe.
*/
export async function syncCoachTimeZone(deps: CoachRhythmDeps, userId: string): Promise<void> {
const { prisma, jobs } = deps;
const botId = await findMainBotId(prisma, userId);
if (!botId) return;
const timezone = await coachTimeZone(prisma, userId);
const moved = await prisma.routine.findMany({
where: { botId, userId, coachKey: { not: null }, timezone: { not: timezone } },
});
for (const routine of moved) {
const armed = routine.active && routine.nextRunAt !== null;
const nextRunAt = armed
? (nextCronDateAcross(routine.crons, new Date(), timezone) ?? routine.nextRunAt)
: routine.nextRunAt;
// Skipped when another save moved it meanwhile.
const { count } = await prisma.routine.updateMany({
where: { id: routine.id, timezone: routine.timezone },
data: { timezone, nextRunAt },
});
if (count === 1 && armed && nextRunAt) {
await jobs.enqueue(routineWakeupJob(routine.id, nextRunAt));
}
}
}