Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

feat(triggers): schedule on weekdays at a time, not just on an interval

Chaitanya Girie1588b702049
diff --git a/src/main/config.ts b/src/main/config.ts
index 9a75f295..ba385d8b 100644
--- a/src/main/config.ts
+++ b/src/main/config.ts
@@ -28,6 +28,12 @@ export interface ScheduledMission {
id: string;
label: string;
intervalMs: number;
+ /** Day-of-week + time-of-day schedule. When present and valid this REPLACES
+ * `intervalMs` — an interval cannot say "weekday mornings", because it drifts
+ * against the clock and a 24h one started at 15:00 fires at 15:00 forever.
+ * `intervalMs` is deliberately left on the record so switching back restores
+ * the cadence the user had. See shared/weeklySchedule.ts. */
+ weekly?: { days: number[]; minute: number };
to: string;
body: string;
enabled: boolean;
diff --git a/src/main/index.ts b/src/main/index.ts
index fb7e9d54..c3a97530 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -18,6 +18,7 @@ import {
modelForRole, OPS_STANDUP_MISSION, HEARTBEAT_MISSION, COMPACT_MAINTENANCE_MISSION, type HarnessConfig, type ScheduledMission
} from './config';
import { listDir, readFileText, readFileBinary, writeFileText, statAbs, expandTilde } from './fs';
+import { normalizeWeekly, weeklyDelayMs } from '../shared/weeklySchedule';
import {
getBranch, getStatus, getLog, getBranches, getAheadBehind, isRepo, getDiff, mainRepoRoot,
addWorktree, removeWorktree, worktreeHasUnintegratedWork, worktreeIsGcSafe,
@@ -660,7 +661,12 @@ function syncMissions(): void {
clearMissionTimers();
const missions = readConfig().missions ?? [];
for (const m of missions) {
- if (!m.enabled || !(m.intervalMs > 0)) continue;
+ if (!m.enabled) continue;
+ // A weekly mission (day-of-week + time) is armed below and does NOT need an
+ // interval, so the interval guard has to come after that branch — it used to
+ // be folded into the line above and would have rejected every one of them.
+ const weekly = m.kind === 'heartbeat' ? null : normalizeWeekly(m.weekly);
+ if (!weekly && !(m.intervalMs > 0)) continue;
// Heartbeat (Lane A #1) opts out of the fixed setInterval and self-reschedules
// with an adaptive cadence. Registered into the same missionTimers map so
// clearMissionTimers() tears it down identically on quit/reset.
@@ -699,11 +705,33 @@ function syncMissions(): void {
console.error('[scheduler] mission', m.id, e);
}
};
+ const entry: MissionTimer = {};
+ if (weekly) {
+ // Weekly self-reschedules: there is no steady interval to settle into,
+ // because the gap between two slots varies (Fri to Mon is not Mon to Wed,
+ // and the week the clocks change is not 168 hours long).
+ //
+ // `justFired` is a spin guard, not a nicety. weeklyDelayMs returns 0 for a
+ // slot that was missed and not yet run, and it learns "already run" from
+ // the persisted lastFiredAt — so if fire()'s writeConfig ever failed, the
+ // next computation would return 0 again, forever. Passing `now` as the
+ // last-fired floor after a fire makes the catch-up branch unreachable, so
+ // the worst case is a lost stamp rather than a hot loop.
+ const rearm = (justFired: boolean): void => {
+ const now = Date.now();
+ const persisted = (readConfig().missions ?? []).find((x) => x.id === m.id)?.lastFiredAt ?? 0;
+ const delay = weeklyDelayMs(weekly, now, justFired ? Math.max(persisted, now) : persisted);
+ if (delay === null) return;
+ entry.timeout = setTimeout(() => { fire(); rearm(true); }, delay);
+ };
+ rearm(false);
+ missionTimers.set(m.id, entry);
+ continue;
+ }
// Honor lastFiredAt so a partially-elapsed interval is not restarted from
// zero on reboot or when an unrelated mission is edited: wait only the time
// remaining until the next due fire, then settle into a steady interval.
const remaining = Math.max(0, m.intervalMs - (Date.now() - (m.lastFiredAt ?? 0)));
- const entry: MissionTimer = {};
entry.timeout = setTimeout(() => {
fire();
entry.interval = setInterval(fire, m.intervalMs);
diff --git a/src/renderer/src/components/triggers/SchedulesSection.tsx b/src/renderer/src/components/triggers/SchedulesSection.tsx
index 9fd263e6..da750393 100644
--- a/src/renderer/src/components/triggers/SchedulesSection.tsx
+++ b/src/renderer/src/components/triggers/SchedulesSection.tsx
@@ -2,9 +2,11 @@ import { useEffect, useState } from 'react';
import { PixelButton } from '../PixelButton';
import { useStore } from '@/store/store';
import {
- Chip, Field, Hint, IntervalPicker, MiniButton, Muted, Select, SubCard, SubHeader,
- Toggle, fmtInterval, inputStyle, textareaStyle
+ Chip, Field, Hint, MiniButton, Muted, Select, SchedulePicker, SubCard, SubHeader,
+ Toggle, fmtInterval, inputStyle, textareaStyle, weeklyDraft, weeklyIsUsable,
+ type WeeklyDraft
} from './ui';
+import { formatWeekly, nextWeeklyFireMs } from '@shared/weeklySchedule';
/**
* SCHEDULES — recurring auto-dispatched missions. The oldest trigger type, and
@@ -29,6 +31,8 @@ interface ScheduledMission {
lastFiredAt?: number;
kind?: 'dispatch' | 'heartbeat' | 'compact';
quietThresholdMs?: number;
+ /** Day-of-week + time. Present ⇒ this replaces intervalMs (main/config.ts). */
+ weekly?: { days: number[]; minute: number };
}
const DEFAULT_INTERVAL_MS = 3_600_000;
@@ -48,6 +52,8 @@ export function SchedulesSection({ onSummary }: { onSummary?: (s: string) => voi
const [adding, setAdding] = useState(false);
const [mLabel, setMLabel] = useState('');
const [mInterval, setMInterval] = useState<number>(DEFAULT_INTERVAL_MS);
+ // null ⇒ the interval above is what runs. Non-null ⇒ days and a time do.
+ const [mWeekly, setMWeekly] = useState<WeeklyDraft | null>(null);
const [mTo, setMTo] = useState<string>('god');
const [mBody, setMBody] = useState('');
@@ -76,17 +82,22 @@ export function SchedulesSection({ onSummary }: { onSummary?: (s: string) => voi
const remove = (id: string) => persist(missions.filter((m) => m.id !== id));
const add = () => {
- if (!mLabel.trim() || !mBody.trim()) return;
+ if (!mLabel.trim() || !mBody.trim() || !whenIsUsable) return;
persist([...missions, {
id: `m_${Date.now().toString(36)}`,
label: mLabel.trim(),
+ // The interval rides along even in weekly mode, so flipping back to
+ // "every…" later restores the cadence rather than a default.
intervalMs: mInterval,
+ ...(mWeekly ? { weekly: mWeekly } : {}),
to: mTo,
body: mBody.trim(),
enabled: true
}]);
- setMLabel(''); setMBody(''); setAdding(false);
+ setMLabel(''); setMBody(''); setMWeekly(null); setAdding(false);
};
+ /** A weekly draft with no days picked would never fire, so it cannot be saved. */
+ const whenIsUsable = !mWeekly || weeklyIsUsable(mWeekly);
const targetName = (to: string) =>
to === 'broadcast' ? 'everyone' : to === 'god' ? 'Michael' : agents.find((a) => a.id === to)?.name ?? to;
@@ -128,8 +139,13 @@ export function SchedulesSection({ onSummary }: { onSummary?: (s: string) => voi
{agents.filter((a) => !a.isGod).map((a) => <option key={a.id} value={a.id}>{a.name}</option>)}
</Select>
</Field>
- <Field label="EVERY">
- <IntervalPicker value={mInterval} onChange={setMInterval} />
+ <Field label="WHEN">
+ <SchedulePicker
+ intervalMs={mInterval}
+ weekly={mWeekly}
+ onInterval={setMInterval}
+ onWeekly={setMWeekly}
+ />
</Field>
<Field label="PROMPT">
<textarea
@@ -141,10 +157,10 @@ export function SchedulesSection({ onSummary }: { onSummary?: (s: string) => voi
/>
</Field>
<div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
- <PixelButton variant="primary" size="sm" onClick={add} disabled={!mLabel.trim() || !mBody.trim()}>
+ <PixelButton variant="primary" size="sm" onClick={add} disabled={!mLabel.trim() || !mBody.trim() || !whenIsUsable}>
add
</PixelButton>
- <PixelButton variant="ghost" size="sm" onClick={() => { setAdding(false); setMLabel(''); setMBody(''); }}>
+ <PixelButton variant="ghost" size="sm" onClick={() => { setAdding(false); setMLabel(''); setMBody(''); setMWeekly(null); }}>
cancel
</PixelButton>
</div>
@@ -169,6 +185,7 @@ function MissionRow({ mission, targetName, agents, onPatch, onDelete }: {
const [label, setLabel] = useState(mission.label);
const [to, setTo] = useState(mission.to);
const [intervalMs, setIntervalMs] = useState(mission.intervalMs);
+ const [weekly, setWeekly] = useState<WeeklyDraft | null>(weeklyDraft(mission.weekly));
const [body, setBody] = useState(mission.body);
const [saved, setSaved] = useState(false);
@@ -179,19 +196,30 @@ function MissionRow({ mission, targetName, agents, onPatch, onDelete }: {
setLabel(mission.label);
setTo(mission.to);
setIntervalMs(mission.intervalMs);
+ setWeekly(weeklyDraft(mission.weekly));
setBody(mission.body);
setSaved(false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
const heartbeat = mission.kind === 'heartbeat';
+ const storedWeekly = weeklyDraft(mission.weekly);
+ // Compare the CANONICAL form, not the raw object: [1,3] and [3,1] mean the
+ // same schedule, and a row that reads as dirty after a no-op click is noise.
+ const weeklyKey = (w: WeeklyDraft | null) => (w ? `${[...w.days].sort((a, b) => a - b).join(',')}@${w.minute}` : '');
const dirty = label !== mission.label || to !== mission.to
- || intervalMs !== mission.intervalMs || body !== mission.body;
+ || intervalMs !== mission.intervalMs || body !== mission.body
+ || weeklyKey(weekly) !== weeklyKey(storedWeekly);
+ const whenIsUsable = !weekly || weeklyIsUsable(weekly);
const fired = mission.lastFiredAt ? `fired ${relTime(Date.now() - mission.lastFiredAt)}` : 'not yet fired';
- const next = mission.enabled && mission.lastFiredAt
- ? ` · next ${relTime(Date.now() - (mission.lastFiredAt + mission.intervalMs))}`
- : '';
+ // A weekly mission's next run comes from the calendar, not from lastFiredAt +
+ // interval — and unlike the interval case it is knowable before the first run,
+ // so a schedule that has never fired can still say when it will.
+ const nextAt = storedWeekly
+ ? nextWeeklyFireMs(storedWeekly, Date.now())
+ : mission.lastFiredAt ? mission.lastFiredAt + mission.intervalMs : null;
+ const next = mission.enabled && nextAt !== null ? ` · next ${relTime(Date.now() - nextAt)}` : '';
const save = () => {
const trimmed = label.trim();
@@ -199,7 +227,10 @@ function MissionRow({ mission, targetName, agents, onPatch, onDelete }: {
// Fold the trim back into the draft too, or the row would read as still
// dirty against a label that was only ever going to be stored trimmed.
setLabel(trimmed);
- onPatch({ label: trimmed, to, intervalMs, body });
+ // `weekly: undefined` is the switch back to interval mode. It has to be sent
+ // explicitly — the backend merges by id and spreads, so simply omitting the
+ // key would leave the old schedule in place and the row would snap back.
+ onPatch({ label: trimmed, to, intervalMs, body, weekly: weekly ?? undefined });
setSaved(true);
setTimeout(() => setSaved(false), 1300);
};
@@ -212,7 +243,7 @@ function MissionRow({ mission, targetName, agents, onPatch, onDelete }: {
title={
<span style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
<Chip tone={mission.enabled ? 'on' : 'off'}>
- {heartbeat ? '♥ beat' : fmtInterval(mission.intervalMs)}
+ {heartbeat ? '♥ beat' : storedWeekly ? formatWeekly(storedWeekly) : fmtInterval(mission.intervalMs)}
</Chip>
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{mission.label}
@@ -246,8 +277,12 @@ function MissionRow({ mission, targetName, agents, onPatch, onDelete }: {
{agents.filter((a) => !a.isGod).map((a) => <option key={a.id} value={a.id}>{a.name}</option>)}
</Select>
</Field>
- <Field label="EVERY">
- <IntervalPicker value={intervalMs} onChange={setIntervalMs} />
+ <Field label="WHEN">
+ {/* The heartbeat has no calendar: it is a cadence that adapts to how
+ busy the floor is, so pinning it to Tuesdays would be a lie. */}
+ {heartbeat
+ ? <SchedulePicker intervalMs={intervalMs} weekly={null} onInterval={setIntervalMs} onWeekly={() => { /* interval only */ }} />
+ : <SchedulePicker intervalMs={intervalMs} weekly={weekly} onInterval={setIntervalMs} onWeekly={setWeekly} />}
{heartbeat && <Hint>The beat adapts to how quiet the floor is, so this is the ceiling, not the exact gap.</Hint>}
</Field>
<Field label="PROMPT">
@@ -260,7 +295,7 @@ function MissionRow({ mission, targetName, agents, onPatch, onDelete }: {
/>
</Field>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 8 }}>
- <PixelButton variant="primary" size="sm" onClick={save} disabled={!dirty || !label.trim()}>
+ <PixelButton variant="primary" size="sm" onClick={save} disabled={!dirty || !label.trim() || !whenIsUsable}>
{saved && !dirty ? 'saved' : 'save'}
</PixelButton>
<span style={{ flex: 1 }} />
diff --git a/src/renderer/src/components/triggers/ui.tsx b/src/renderer/src/components/triggers/ui.tsx
index 2b0a70dc..78738fdc 100644
--- a/src/renderer/src/components/triggers/ui.tsx
+++ b/src/renderer/src/components/triggers/ui.tsx
@@ -1,5 +1,9 @@
import { useState, type CSSProperties, type ReactNode } from 'react';
import { TRIGGER_MODES, type TriggerMode } from '@shared/triggers';
+import {
+ WEEKDAY_INITIALS, WEEKDAY_LABELS, formatMinute, normalizeWeekly,
+ type WeeklySchedule
+} from '@shared/weeklySchedule';
/**
* Shared chrome for the Triggers tab.
@@ -387,3 +391,125 @@ export function SecretField({ value, revealed, onReveal, onCopy, copied, placeho
</div>
);
}
+
+/* ──────────────────────────── weekly schedule ────────────────────────────── */
+
+/** A weekly schedule the picker can hold mid-edit. Days may be empty while the
+ * user is deselecting, which `normalizeWeekly` would reject — so the draft type
+ * is looser than the stored one, and the SAVE is what has to be valid. */
+export type WeeklyDraft = { days: number[]; minute: number };
+
+export const DEFAULT_WEEKLY: WeeklyDraft = { days: [1, 2, 3, 4, 5], minute: 9 * 60 };
+
+/** True when this draft is safe to store. The one gate every call site shares. */
+export function weeklyIsUsable(w: WeeklyDraft): boolean {
+ return normalizeWeekly(w) !== null;
+}
+
+/**
+ * Day-of-week + time-of-day picker.
+ *
+ * Seven toggles rather than a multi-select, because picking "Mon Wed Fri" is the
+ * whole job and a native multi-select makes it a modifier-key puzzle. The order
+ * is Sunday-first to match `Date.getDay()`, so no index maths sits between what
+ * is clicked and what is stored.
+ */
+export function WeeklyPicker({ value, onChange }: {
+ value: WeeklyDraft; onChange: (w: WeeklyDraft) => void;
+}) {
+ const toggle = (d: number) => onChange({
+ ...value,
+ days: value.days.includes(d) ? value.days.filter((x) => x !== d) : [...value.days, d].sort((a, b) => a - b)
+ });
+ const setDays = (days: number[]) => onChange({ ...value, days });
+ const same = (days: number[]) =>
+ value.days.length === days.length && days.every((d) => value.days.includes(d));
+
+ return (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
+ <div style={{ display: 'flex', gap: 3, flexWrap: 'wrap' }}>
+ {WEEKDAY_INITIALS.map((initial, d) => {
+ const on = value.days.includes(d);
+ return (
+ <button
+ key={d}
+ type="button"
+ onClick={() => toggle(d)}
+ title={WEEKDAY_LABELS[d]}
+ aria-pressed={on}
+ style={{
+ width: 26, height: 24, border: 'none', cursor: 'pointer',
+ background: on ? 'var(--cth-mint)' : 'var(--cth-cream-200)',
+ boxShadow: on
+ ? 'inset 0 0 0 1.5px var(--cth-ink-500)'
+ : 'inset 0 0 0 1px var(--cth-ink-100)',
+ fontFamily: 'var(--cth-font-ui)', fontSize: 11,
+ color: on ? 'var(--cth-ink-900)' : 'var(--cth-ink-500)'
+ }}
+ >{initial}</button>
+ );
+ })}
+ </div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
+ <span style={{ fontSize: 11, color: 'var(--cth-ink-500)' }}>at</span>
+ {/* A native time field, so typing 0930 works and the value is already
+ the HH:MM the schedule stores. Minute granularity, not 5-minute
+ steps: "09:47 on Tuesdays" is a legitimate thing to want. */}
+ <input
+ type="time"
+ value={formatMinute(value.minute)}
+ onChange={(e) => {
+ const [h, m] = e.target.value.split(':').map(Number);
+ if (Number.isFinite(h) && Number.isFinite(m)) onChange({ ...value, minute: h * 60 + m });
+ }}
+ style={{ ...inputStyle, width: 108, padding: '3px 6px' }}
+ />
+ <span style={{ flex: 1 }} />
+ <MiniButton onClick={() => setDays(same([1, 2, 3, 4, 5]) ? [] : [1, 2, 3, 4, 5])}>weekdays</MiniButton>
+ <MiniButton onClick={() => setDays(same([0, 1, 2, 3, 4, 5, 6]) ? [] : [0, 1, 2, 3, 4, 5, 6])}>every day</MiniButton>
+ </div>
+ {value.days.length === 0 && <Hint>Pick at least one day, or this will never run.</Hint>}
+ </div>
+ );
+}
+
+/**
+ * The whole "when does this run" control: pick a repeating gap, or pick days and
+ * a time. Both call sites (the new-schedule form and an expanded row) use this
+ * so the two can never drift apart.
+ *
+ * `weekly === null` IS interval mode. Keeping the mode in the value rather than
+ * in local state means a row that reloads from disk cannot show the wrong tab.
+ */
+export function SchedulePicker({ intervalMs, weekly, onInterval, onWeekly }: {
+ intervalMs: number;
+ weekly: WeeklyDraft | null;
+ onInterval: (ms: number) => void;
+ onWeekly: (w: WeeklyDraft | null) => void;
+}) {
+ const tab = (active: boolean): CSSProperties => ({
+ padding: '3px 10px 2px', border: 'none', cursor: 'pointer',
+ background: active ? 'var(--cth-cream-100)' : 'transparent',
+ boxShadow: active ? 'inset 0 0 0 1.5px var(--cth-ink-500)' : 'inset 0 0 0 1px var(--cth-ink-100)',
+ fontFamily: 'var(--cth-font-ui)', fontSize: 11,
+ color: active ? 'var(--cth-ink-900)' : 'var(--cth-ink-500)'
+ });
+ return (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
+ <div style={{ display: 'flex', gap: 4 }}>
+ <button type="button" style={tab(!weekly)} onClick={() => onWeekly(null)}>every…</button>
+ <button type="button" style={tab(!!weekly)} onClick={() => onWeekly(weekly ?? DEFAULT_WEEKLY)}>on days…</button>
+ </div>
+ {weekly
+ ? <WeeklyPicker value={weekly} onChange={onWeekly} />
+ : <IntervalPicker value={intervalMs} onChange={onInterval} />}
+ </div>
+ );
+}
+
+/** Narrow a stored mission's `weekly` to a draft, or null for interval mode.
+ * One place decides what "this mission is weekly" means. */
+export function weeklyDraft(w: WeeklySchedule | { days: number[]; minute: number } | undefined): WeeklyDraft | null {
+ const n = normalizeWeekly(w);
+ return n ? { days: n.days, minute: n.minute } : null;
+}
diff --git a/src/shared/weeklySchedule.ts b/src/shared/weeklySchedule.ts
new file mode 100644
index 00000000..953992d1
--- /dev/null
+++ b/src/shared/weeklySchedule.ts
@@ -0,0 +1,143 @@
+/**
+ * WEEKLY SCHEDULES — "every Monday and Thursday at 09:00" instead of
+ * "every 86400000 ms".
+ *
+ * A `ScheduledMission` has always fired on a fixed interval, which cannot say
+ * "weekday mornings": an interval drifts relative to the clock, and a 24h one
+ * started at 15:00 fires at 15:00 forever. This module adds the other shape.
+ * When a mission carries a valid `weekly`, that REPLACES its interval; the
+ * interval is left on the record untouched so switching back restores it.
+ *
+ * Pure and import-free on purpose, so the test loader can take it directly and
+ * the scheduler's arithmetic is testable without a clock or a config file.
+ *
+ * ── Everything here is LOCAL time, deliberately ────────────────────────────
+ * "09:00 on Monday" means 09:00 where the user is sitting, which is the only
+ * reading a person expects. That is why the next occurrence is built with the
+ * Date(y, m, d, h, min) constructor rather than by adding milliseconds: adding
+ * 7 * 86400000 across a daylight-saving boundary lands an hour off, while
+ * re-constructing from calendar fields lands on the same wall clock. On a
+ * spring-forward day a time that does not exist (02:30 in most of the US) rolls
+ * forward the way the platform rolls it, which is the standard behaviour and
+ * the one every other scheduler produces too.
+ */
+
+export interface WeeklySchedule {
+ /** 0 = Sunday … 6 = Saturday. Empty means "not a weekly schedule". */
+ days: number[];
+ /** Minutes since local midnight, 0..1439. */
+ minute: number;
+}
+
+export const WEEKDAY_LABELS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
+/** Initials for the 7-button picker. Two Ts and two Ss — the position carries
+ * the meaning, and every calendar in the world does the same. */
+export const WEEKDAY_INITIALS = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
+
+/**
+ * How long after a MISSED slot the mission still fires.
+ *
+ * A laptop asleep at 09:00 and opened at 10:30 should still get its 09:00 run;
+ * one closed on Friday and opened on Monday should not get Friday's. Six hours
+ * splits those two cases about where a person would. This matches what the
+ * interval scheduler already does (it clamps a negative remaining time to zero
+ * and fires on boot), so the two kinds of schedule behave the same way after a
+ * sleep rather than one of them silently skipping.
+ */
+export const WEEKLY_CATCHUP_MS = 6 * 60 * 60 * 1000;
+
+/** Validate and canonicalise. Returns null for anything that is not a usable
+ * weekly schedule — no days, a bad day number, a minute outside the day — so
+ * every caller has exactly one check to make. Days come back sorted and
+ * de-duplicated, so two schedules that mean the same thing compare equal. */
+export function normalizeWeekly(w: unknown): WeeklySchedule | null {
+ if (!w || typeof w !== 'object') return null;
+ const raw = w as { days?: unknown; minute?: unknown };
+ if (!Array.isArray(raw.days)) return null;
+ const days = [...new Set(
+ raw.days.filter((d): d is number => typeof d === 'number' && Number.isInteger(d) && d >= 0 && d <= 6)
+ )].sort((a, b) => a - b);
+ if (days.length === 0) return null;
+ const minute = raw.minute;
+ if (typeof minute !== 'number' || !Number.isInteger(minute) || minute < 0 || minute > 1439) return null;
+ return { days, minute };
+}
+
+/** "09:00". Zero-padded 24h, because a schedule an operator is reading back
+ * should not need an am/pm second look. */
+export function formatMinute(minute: number): string {
+ const h = Math.floor(minute / 60);
+ const m = minute % 60;
+ return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
+}
+
+/** Human summary for a row: "weekdays at 09:00", "Mon, Thu at 14:30". */
+export function formatWeekly(w: unknown): string {
+ const n = normalizeWeekly(w);
+ if (!n) return 'no days picked';
+ const at = formatMinute(n.minute);
+ const key = n.days.join(',');
+ if (key === '0,1,2,3,4,5,6') return `every day at ${at}`;
+ if (key === '1,2,3,4,5') return `weekdays at ${at}`;
+ if (key === '0,6') return `weekends at ${at}`;
+ return `${n.days.map((d) => WEEKDAY_LABELS[d]).join(', ')} at ${at}`;
+}
+
+/** Build the local instant for `minute` on the day `offset` days from `from`.
+ * Calendar-field construction, not millisecond arithmetic — see the DST note. */
+function slotAt(from: Date, offset: number, minute: number): Date {
+ return new Date(
+ from.getFullYear(), from.getMonth(), from.getDate() + offset,
+ Math.floor(minute / 60), minute % 60, 0, 0
+ );
+}
+
+/** The first matching slot STRICTLY after `nowMs`, or null if there are no days.
+ * Eight candidates is always enough: the worst case is one day a week whose
+ * slot has already passed today, which lands on offset 7. */
+export function nextWeeklyFireMs(w: unknown, nowMs: number): number | null {
+ const n = normalizeWeekly(w);
+ if (!n) return null;
+ const from = new Date(nowMs);
+ for (let offset = 0; offset <= 7; offset++) {
+ const slot = slotAt(from, offset, n.minute);
+ if (!n.days.includes(slot.getDay())) continue;
+ const t = slot.getTime();
+ if (t > nowMs) return t;
+ }
+ return null;
+}
+
+/** The most recent matching slot at or before `nowMs`, or null. Used only to
+ * decide whether a slot was MISSED while the app was not running. */
+export function previousWeeklyFireMs(w: unknown, nowMs: number): number | null {
+ const n = normalizeWeekly(w);
+ if (!n) return null;
+ const from = new Date(nowMs);
+ for (let offset = 0; offset >= -7; offset--) {
+ const slot = slotAt(from, offset, n.minute);
+ if (!n.days.includes(slot.getDay())) continue;
+ const t = slot.getTime();
+ if (t <= nowMs) return t;
+ }
+ return null;
+}
+
+/**
+ * How long the scheduler should wait before firing this mission, or null when
+ * the schedule is not usable.
+ *
+ * Zero means "fire now": a slot passed while we were not watching, it is recent
+ * enough to still be worth running, and we have not already run it. That last
+ * clause is what `lastFiredAt` is for — without it, re-arming the scheduler
+ * (which happens on every save of ANY mission) would re-fire a mission that
+ * already ran minutes ago.
+ */
+export function weeklyDelayMs(w: unknown, nowMs: number, lastFiredAt = 0): number | null {
+ const n = normalizeWeekly(w);
+ if (!n) return null;
+ const prev = previousWeeklyFireMs(n, nowMs);
+ if (prev !== null && prev > lastFiredAt && nowMs - prev <= WEEKLY_CATCHUP_MS) return 0;
+ const next = nextWeeklyFireMs(n, nowMs);
+ return next === null ? null : Math.max(0, next - nowMs);
+}
diff --git a/test/weekly-schedule.test.cjs b/test/weekly-schedule.test.cjs
new file mode 100644
index 00000000..b6f5012c
--- /dev/null
+++ b/test/weekly-schedule.test.cjs
@@ -0,0 +1,120 @@
+/**
+ * Weekly trigger schedules — the arithmetic behind "every Monday at 09:00".
+ *
+ * The interesting cases are all about time NOT being uniform: a slot that has
+ * already passed today, a slot missed while the machine slept, and a week that
+ * is not 7 * 24h long because the clocks moved. The last one is why the module
+ * builds instants from calendar fields instead of adding milliseconds, and it
+ * is asserted here in a fixed zone so the test means the same thing everywhere.
+ */
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const loadTs = require('./load-ts.cjs');
+
+const {
+ normalizeWeekly, formatWeekly, formatMinute,
+ nextWeeklyFireMs, previousWeeklyFireMs, weeklyDelayMs, WEEKLY_CATCHUP_MS
+} = loadTs('src/shared/weeklySchedule.ts');
+
+/** Local-time helper: these tests run under TZ=UTC (set below), so a local
+ * construction and a UTC one agree except in the DST block, which sets its own. */
+const at = (y, m, d, h = 0, min = 0) => new Date(y, m - 1, d, h, min, 0, 0).getTime();
+
+test('normalizeWeekly sorts, de-dupes and rejects nonsense', () => {
+ assert.deepEqual(normalizeWeekly({ days: [4, 1, 1], minute: 540 }), { days: [1, 4], minute: 540 });
+ assert.equal(normalizeWeekly({ days: [], minute: 540 }), null, 'no days is not a schedule');
+ assert.equal(normalizeWeekly({ days: [7], minute: 540 }), null, 'day 7 does not exist');
+ assert.equal(normalizeWeekly({ days: [1], minute: 1440 }), null, 'minute 1440 is tomorrow');
+ assert.equal(normalizeWeekly({ days: [1], minute: -1 }), null);
+ assert.equal(normalizeWeekly({ days: [1], minute: 9.5 }), null, 'fractional minutes are a bug upstream');
+ assert.equal(normalizeWeekly(undefined), null);
+ assert.equal(normalizeWeekly({ days: [1] }), null, 'a day with no time is not a schedule');
+});
+
+test('formatWeekly names the common sets rather than listing them', () => {
+ assert.equal(formatWeekly({ days: [0, 1, 2, 3, 4, 5, 6], minute: 540 }), 'every day at 09:00');
+ assert.equal(formatWeekly({ days: [1, 2, 3, 4, 5], minute: 540 }), 'weekdays at 09:00');
+ assert.equal(formatWeekly({ days: [0, 6], minute: 630 }), 'weekends at 10:30');
+ assert.equal(formatWeekly({ days: [1, 4], minute: 870 }), 'Mon, Thu at 14:30');
+ assert.equal(formatWeekly({ days: [], minute: 0 }), 'no days picked');
+ assert.equal(formatMinute(0), '00:00');
+ assert.equal(formatMinute(1439), '23:59');
+});
+
+test('nextWeeklyFireMs skips today once the slot has passed', () => {
+ const mondays = { days: [1], minute: 540 }; // Mon 09:00
+ // 2026-08-24 is a Monday.
+ assert.equal(nextWeeklyFireMs(mondays, at(2026, 8, 24, 8, 0)), at(2026, 8, 24, 9, 0), 'later today');
+ assert.equal(nextWeeklyFireMs(mondays, at(2026, 8, 24, 9, 0)), at(2026, 8, 31, 9, 0),
+ 'exactly on the slot means it is spent — strictly after, or a re-arm double-fires');
+ assert.equal(nextWeeklyFireMs(mondays, at(2026, 8, 24, 10, 0)), at(2026, 8, 31, 9, 0), 'next week');
+ assert.equal(nextWeeklyFireMs({ days: [], minute: 540 }, Date.now()), null);
+});
+
+test('nextWeeklyFireMs picks the nearest of several days', () => {
+ const mwf = { days: [1, 3, 5], minute: 540 };
+ assert.equal(nextWeeklyFireMs(mwf, at(2026, 8, 24, 10, 0)), at(2026, 8, 26, 9, 0), 'Mon 10:00 -> Wed');
+ assert.equal(nextWeeklyFireMs(mwf, at(2026, 8, 26, 10, 0)), at(2026, 8, 28, 9, 0), 'Wed -> Fri');
+ assert.equal(nextWeeklyFireMs(mwf, at(2026, 8, 28, 10, 0)), at(2026, 8, 31, 9, 0), 'Fri -> Mon, over the weekend');
+});
+
+test('previousWeeklyFireMs finds the slot behind us', () => {
+ const mondays = { days: [1], minute: 540 };
+ assert.equal(previousWeeklyFireMs(mondays, at(2026, 8, 24, 10, 0)), at(2026, 8, 24, 9, 0));
+ assert.equal(previousWeeklyFireMs(mondays, at(2026, 8, 24, 8, 0)), at(2026, 8, 17, 9, 0), 'last week');
+});
+
+test('a slot missed while asleep fires on wake, once, and only if recent', () => {
+ const mondays = { days: [1], minute: 540 };
+ const slot = at(2026, 8, 24, 9, 0);
+
+ // Woke at 10:00 having never run it: catch up.
+ assert.equal(weeklyDelayMs(mondays, at(2026, 8, 24, 10, 0), 0), 0);
+
+ // Same wake, but it already ran at 09:00. This is the re-arm case — the
+ // scheduler rebuilds every timer whenever ANY mission is saved — and firing
+ // again here would double-dispatch every edit.
+ assert.equal(weeklyDelayMs(mondays, at(2026, 8, 24, 10, 0), slot), at(2026, 8, 31, 9, 0) - at(2026, 8, 24, 10, 0));
+
+ // Woke well past the catch-up window: the 09:00 run is gone, not deferred to
+ // an hour nobody asked for.
+ const late = slot + WEEKLY_CATCHUP_MS + 60_000;
+ assert.equal(weeklyDelayMs(mondays, late, 0), at(2026, 8, 31, 9, 0) - late);
+});
+
+test('weeklyDelayMs waits, rather than firing, when the slot is ahead', () => {
+ const mondays = { days: [1], minute: 540 };
+ const now = at(2026, 8, 24, 8, 0);
+ assert.equal(weeklyDelayMs(mondays, now, 0), 60 * 60 * 1000, 'one hour to go');
+ assert.equal(weeklyDelayMs({ days: [], minute: 540 }, now, 0), null);
+});
+
+test('every delay fits in a setTimeout', () => {
+ // Node clamps a timeout above 2^31-1 ms and fires it IMMEDIATELY, which would
+ // turn a long gap into a hot loop. One day a week is the longest possible gap.
+ const sundays = { days: [0], minute: 0 };
+ const d = weeklyDelayMs(sundays, at(2026, 8, 24, 0, 1), Date.now());
+ assert.ok(d !== null && d <= 7 * 86400000 && d < 2147483647);
+});
+
+test('the clocks moving does not move the appointment', () => {
+ // US DST ends 2026-11-01, so the week containing it is 169 hours long, not
+ // 168. A Monday 09:00 schedule must stay at 09:00 on both sides of it — which
+ // is exactly what adding 7 * 86400000 ms would fail to do.
+ const tz = process.env.TZ;
+ process.env.TZ = 'America/New_York';
+ try {
+ const slot = new Date(2026, 9, 26, 9, 0, 0, 0).getTime(); // Mon 26 Oct, 09:00 EDT
+ const fire = nextWeeklyFireMs({ days: [1], minute: 540 }, slot + 1000);
+ const landed = new Date(fire);
+ assert.equal(landed.getDate(), 2, 'lands on Monday 2 November');
+ assert.equal(landed.getMonth(), 10);
+ assert.equal(landed.getHours(), 9, 'still 09:00 local, not 08:00');
+ // The proof that this is calendar arithmetic and not millisecond arithmetic:
+ // the gap between two consecutive 09:00 Mondays across the fall-back is a
+ // week PLUS the repeated hour.
+ assert.equal(fire - slot, 7 * 86400000 + 60 * 60 * 1000);
+ } finally {
+ if (tz === undefined) delete process.env.TZ; else process.env.TZ = tz;
+ }
+});