Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

fix(calendar): a monthly series must not be moved by a date that does not exist (#157)

Xialie Zhuang21ea3260cf29
diff --git a/server/src/__tests__/calendar-recurrence.test.ts b/server/src/__tests__/calendar-recurrence.test.ts
new file mode 100644
index 0000000..c689e0a
--- /dev/null
+++ b/server/src/__tests__/calendar-recurrence.test.ts
@@ -0,0 +1,187 @@
+/**
+ * Recurrence math for calendar events.
+ *
+ * The old implementation stepped forward from the PREVIOUS occurrence. That is
+ * fine until a step lands on a date that does not exist — `setUTCMonth` turns
+ * "Jan 31 plus a month" into March 3 — because the overflowed value was then
+ * fed back in as the next seed. So the error did not skip one occurrence, it
+ * moved the entire series permanently: "monthly on the 31st" silently became
+ * "the 3rd of every month, starting in March", and "yearly on Feb 29" became
+ * Mar 1 forever, never returning at the next leap year.
+ *
+ * Every occurrence is now computed from the seed by index, which cannot drift.
+ *
+ * Run: node --import tsx --test server/src/__tests__/calendar-recurrence.test.ts
+ */
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { nextOccurrenceOnOrAfter, type RecurrenceRule } from '../recurrence.js'
+
+const DOW = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
+
+/** The first `n` occurrences, walked the way the dispatcher walks them: ask for
+ * the next slot at or after just past the previous one. */
+function series(seedIso: string, rule: RecurrenceRule | null, n: number): string[] {
+ const seed = new Date(seedIso)
+ const out: string[] = []
+ let after = seed
+ for (let i = 0; i < n; i++) {
+ const next = nextOccurrenceOnOrAfter(seed, rule, after)
+ if (!next) break
+ out.push(next.toISOString().slice(0, 10))
+ after = new Date(next.getTime() + 1000)
+ }
+ return out
+}
+
+function weekdays(seedIso: string, rule: RecurrenceRule, n: number): string[] {
+ return series(seedIso, rule, n).map((d) => `${d} ${DOW[new Date(`${d}T00:00:00Z`).getUTCDay()]}`)
+}
+
+// ── the month-end case that used to corrupt the whole series ────────────────
+
+test('monthly on the 31st clamps into short months and comes back', () => {
+ // Was: Jan 31 → Mar 3 → Apr 3 → May 3 … February skipped and the
+ // day-of-month permanently changed.
+ assert.deepEqual(
+ series('2026-01-31T09:00:00Z', { freq: 'monthly', interval: 1 }, 7),
+ ['2026-01-31', '2026-02-28', '2026-03-31', '2026-04-30', '2026-05-31', '2026-06-30', '2026-07-31'],
+ )
+})
+
+test('monthly on the 30th clamps only where it must', () => {
+ assert.deepEqual(
+ series('2026-01-30T09:00:00Z', { freq: 'monthly', interval: 1 }, 4),
+ ['2026-01-30', '2026-02-28', '2026-03-30', '2026-04-30'],
+ )
+})
+
+test('February clamping follows the leap year, not a fixed 28', () => {
+ // 2028 is a leap year; the same rule must reach the 29th there.
+ assert.deepEqual(
+ series('2027-12-31T09:00:00Z', { freq: 'monthly', interval: 2 }, 4),
+ ['2027-12-31', '2028-02-29', '2028-04-30', '2028-06-30'],
+ )
+})
+
+test('yearly on Feb 29 returns at the next leap year', () => {
+ // Was: Mar 1 from 2029 onward, forever — the date the user picked was gone.
+ assert.deepEqual(
+ series('2028-02-29T09:00:00Z', { freq: 'yearly', interval: 1 }, 6),
+ ['2028-02-29', '2029-02-28', '2030-02-28', '2031-02-28', '2032-02-29', '2033-02-28'],
+ )
+})
+
+test('a mid-month monthly series is untouched', () => {
+ // The common case has to be exactly as before; nothing here is clamped.
+ assert.deepEqual(
+ series('2026-01-15T09:00:00Z', { freq: 'monthly', interval: 1 }, 4),
+ ['2026-01-15', '2026-02-15', '2026-03-15', '2026-04-15'],
+ )
+})
+
+// ── weekly ─────────────────────────────────────────────────────────────────
+
+test('every-2-weeks on Mon and Wed keeps both days in the same week', () => {
+ // Was: Mon → Wed of the NEXT week → Mon of the week after, a 9/12/9 day
+ // pattern that is neither "every two weeks" nor "Mon and Wed".
+ assert.deepEqual(
+ weekdays('2026-01-05T09:00:00Z', { freq: 'weekly', interval: 2, byweekday: [1, 3] }, 6),
+ [
+ '2026-01-05 Mon', '2026-01-07 Wed',
+ '2026-01-19 Mon', '2026-01-21 Wed',
+ '2026-02-02 Mon', '2026-02-04 Wed',
+ ],
+ )
+})
+
+test('weekly on Mon and Wed is unchanged', () => {
+ assert.deepEqual(
+ weekdays('2026-01-05T09:00:00Z', { freq: 'weekly', interval: 1, byweekday: [1, 3] }, 5),
+ ['2026-01-05 Mon', '2026-01-07 Wed', '2026-01-12 Mon', '2026-01-14 Wed', '2026-01-19 Mon'],
+ )
+})
+
+test('the seed week only offers days at or after the seed', () => {
+ // Seeded on a Wednesday with Mon+Wed selected: the Monday before the seed is
+ // in the past and must not be back-filled.
+ assert.deepEqual(
+ weekdays('2026-01-07T09:00:00Z', { freq: 'weekly', interval: 1, byweekday: [1, 3] }, 4),
+ ['2026-01-07 Wed', '2026-01-12 Mon', '2026-01-14 Wed', '2026-01-19 Mon'],
+ )
+})
+
+test('weekly with no byweekday follows the seed weekday', () => {
+ assert.deepEqual(
+ weekdays('2026-01-05T09:00:00Z', { freq: 'weekly', interval: 2 }, 3),
+ ['2026-01-05 Mon', '2026-01-19 Mon', '2026-02-02 Mon'],
+ )
+})
+
+test('a duplicated or unsorted byweekday is normalised, not obeyed literally', () => {
+ // The rule comes from JSON, so it can arrive in any order and with repeats.
+ assert.deepEqual(
+ weekdays('2026-01-05T09:00:00Z', { freq: 'weekly', interval: 1, byweekday: [3, 1, 3] }, 4),
+ ['2026-01-05 Mon', '2026-01-07 Wed', '2026-01-12 Mon', '2026-01-14 Wed'],
+ )
+})
+
+test('an empty byweekday falls back to the seed weekday instead of hanging', () => {
+ // The old loop guarded against this with an iteration cap; the rule should
+ // simply behave as a plain weekly.
+ assert.deepEqual(
+ weekdays('2026-01-05T09:00:00Z', { freq: 'weekly', interval: 1, byweekday: [] }, 3),
+ ['2026-01-05 Mon', '2026-01-12 Mon', '2026-01-19 Mon'],
+ )
+})
+
+// ── daily, and the series terminators ──────────────────────────────────────
+
+test('daily with an interval is unchanged', () => {
+ assert.deepEqual(
+ series('2026-01-05T09:00:00Z', { freq: 'daily', interval: 3 }, 4),
+ ['2026-01-05', '2026-01-08', '2026-01-11', '2026-01-14'],
+ )
+})
+
+test('count includes the seed', () => {
+ // The seed is occurrence #1, so count:3 yields three dates and stops.
+ assert.deepEqual(
+ series('2026-01-05T09:00:00Z', { freq: 'daily', interval: 1, count: 3 }, 10),
+ ['2026-01-05', '2026-01-06', '2026-01-07'],
+ )
+})
+
+test('until is inclusive', () => {
+ assert.deepEqual(
+ series('2026-01-05T09:00:00Z', { freq: 'daily', interval: 1, until: '2026-01-07T09:00:00Z' }, 10),
+ ['2026-01-05', '2026-01-06', '2026-01-07'],
+ )
+})
+
+test('until still terminates a clamped monthly series', () => {
+ // The terminators are checked against the computed occurrence, so clamping
+ // must not let a series run past its end.
+ assert.deepEqual(
+ series('2026-01-31T09:00:00Z', { freq: 'monthly', interval: 1, until: '2026-03-31T09:00:00Z' }, 10),
+ ['2026-01-31', '2026-02-28', '2026-03-31'],
+ )
+})
+
+test('a one-shot event fires once and never again', () => {
+ const seed = new Date('2026-01-05T09:00:00Z')
+ assert.deepEqual(nextOccurrenceOnOrAfter(seed, null, seed), seed)
+ assert.equal(nextOccurrenceOnOrAfter(seed, null, new Date(seed.getTime() + 1)), null)
+})
+
+test('asking from far in the future skips ahead without drifting', () => {
+ // The dispatcher asks for the next slot at or after "now", which may be many
+ // occurrences in. Index-based lookup has to land on the same dates the walk
+ // above produces — that equivalence is what stepping used to break.
+ const next = nextOccurrenceOnOrAfter(
+ new Date('2026-01-31T09:00:00Z'),
+ { freq: 'monthly', interval: 1 },
+ new Date('2026-06-15T00:00:00Z'),
+ )
+ assert.equal(next?.toISOString().slice(0, 10), '2026-06-30')
+})
diff --git a/server/src/calendar.ts b/server/src/calendar.ts
index 1cdc844..3be0ec6 100644
--- a/server/src/calendar.ts
+++ b/server/src/calendar.ts
@@ -20,6 +20,10 @@ import { pool } from './db/pool.js'
import { CH_MESSAGE_NEW, CH_CALENDAR_REMINDER, publish } from './redis.js'
import { env } from './env.js'
import { formatAddress, sendViaProvider, mintMessageId } from './email.js'
+// The pure half lives apart so it can be tested without a database, Redis or an
+// email transport. Re-exported here so every existing importer is unaffected.
+export { nextOccurrenceOnOrAfter, type RecurrenceRule } from './recurrence.js'
+import { nextOccurrenceOnOrAfter, type RecurrenceRule } from './recurrence.js'
const TICK_INTERVAL_MS = 60_000
const CALENDAR_SYSTEM_AUTHOR_ID = 'calendar'
@@ -30,19 +34,6 @@ const CALENDAR_SYSTEM_AUTHOR_ID = 'calendar'
* the next future slot without firing. */
const MAX_CATCHUP_MS = 60 * 60_000
-export interface RecurrenceRule {
- freq: 'daily' | 'weekly' | 'monthly' | 'yearly'
- interval: number
- /** 0=Sun … 6=Sat. Only honored when freq='weekly'. Empty/undefined = use
- * the weekday of the seed start_at. */
- byweekday?: number[]
- /** Inclusive end of the series — no occurrences after this ISO timestamp. */
- until?: string | null
- /** Hard cap on total firings (including the seed). Once reached, the
- * series is marked 'done'. */
- count?: number | null
-}
-
export interface CalendarEventRow {
id: string
company_id: string
@@ -66,94 +57,6 @@ export interface CalendarEventRow {
updated_at: Date
}
-/* ─────────────────────────── recurrence math ─────────────────────────── */
-
-/** Add N days to a Date without mutating the input. */
-function addDays(d: Date, n: number): Date {
- const out = new Date(d.getTime())
- out.setUTCDate(out.getUTCDate() + n)
- return out
-}
-
-function addMonths(d: Date, n: number): Date {
- const out = new Date(d.getTime())
- out.setUTCMonth(out.getUTCMonth() + n)
- return out
-}
-
-function addYears(d: Date, n: number): Date {
- const out = new Date(d.getTime())
- out.setUTCFullYear(out.getUTCFullYear() + n)
- return out
-}
-
-/** Step one rrule "interval" forward from `from`. For weekly with
- * byweekday this scans day-by-day (cheap — bounded at 7 iterations). */
-function stepOnce(from: Date, rule: RecurrenceRule): Date {
- const interval = Math.max(1, Math.floor(rule.interval || 1))
- switch (rule.freq) {
- case 'daily':
- return addDays(from, interval)
- case 'weekly': {
- // No explicit byweekday → just hop intervals*7 days at a time.
- const days = rule.byweekday && rule.byweekday.length > 0 ? rule.byweekday : null
- if (!days) return addDays(from, interval * 7)
- // Walk forward one day at a time until we hit a permitted weekday.
- // Skip the first interval-1 full weeks first, then resume scanning.
- // For interval=1 this is "next allowed day after `from`".
- let candidate = addDays(from, 1)
- const sorted = [...days].sort((a, b) => a - b)
- // For interval>1 we need: same DOW family, just N weeks later. The
- // simplest correct behavior — scan forward N*7 days, then pick the
- // next allowed weekday within the week of that target.
- if (interval > 1) {
- candidate = addDays(from, (interval - 1) * 7 + 1)
- }
- for (let i = 0; i < 14; i++) {
- if (sorted.includes(candidate.getUTCDay())) return candidate
- candidate = addDays(candidate, 1)
- }
- return candidate
- }
- case 'monthly':
- return addMonths(from, interval)
- case 'yearly':
- return addYears(from, interval)
- }
-}
-
-/**
- * Compute the next firing time strictly >= `after`, walking forward from
- * the event's seed `start_at`. Returns null if:
- * - the series has no recurrence and start_at < after (already fired)
- * - rule.until is earlier than the next computed slot
- * - rule.count is exhausted
- */
-export function nextOccurrenceOnOrAfter(
- startAt: Date,
- recurrence: RecurrenceRule | null,
- after: Date,
-): Date | null {
- // One-shot: the only possible slot is start_at itself.
- if (!recurrence) {
- return startAt.getTime() >= after.getTime() ? startAt : null
- }
- const untilTs = recurrence.until ? new Date(recurrence.until).getTime() : Infinity
- const maxCount = recurrence.count ?? Infinity
- let current = startAt
- let fired = 1 // start_at counts as occurrence #1
- // Cap iterations defensively so a misconfigured rule (e.g. byweekday=[])
- // can't tie up the tick loop forever.
- for (let i = 0; i < 5000; i++) {
- if (current.getTime() > untilTs) return null
- if (fired > maxCount) return null
- if (current.getTime() >= after.getTime()) return current
- current = stepOnce(current, recurrence)
- fired += 1
- }
- return null
-}
-
/* ─────────────────────────── dispatcher ─────────────────────────── */
/** Render the body of the system message posted on dispatch. Keep this as a
diff --git a/server/src/recurrence.ts b/server/src/recurrence.ts
new file mode 100644
index 0000000..e4dce44
--- /dev/null
+++ b/server/src/recurrence.ts
@@ -0,0 +1,141 @@
+/**
+ * Recurrence math — the pure half of the calendar.
+ *
+ * `calendar.ts` describes itself as two halves: this math, and the dispatcher
+ * that opens a database, Redis and an email transport. Split out so the math
+ * can be tested without any of that — the same reason cli-parse.ts is separate
+ * from cli.ts.
+ *
+ * Deliberately minimal: daily / weekly (with byweekday) / monthly / yearly,
+ * plus interval, until and count. No EXDATEs, no BYMONTHDAY, no BYSETPOS.
+ *
+ * Every occurrence is computed FROM THE SEED by index. The previous version
+ * stepped forward from the last occurrence, which is fine until a step lands on
+ * a date that does not exist: `setUTCMonth` turns "Jan 31 plus a month" into
+ * March 3, and that overflowed value then became the seed for the next step. So
+ * one impossible date did not skip one occurrence — it moved the whole series
+ * permanently. "Monthly on the 31st" became "the 3rd of every month, from
+ * March"; "yearly on Feb 29" became Mar 1 and never came back at the next leap
+ * year. An index cannot drift.
+ */
+
+export interface RecurrenceRule {
+ freq: 'daily' | 'weekly' | 'monthly' | 'yearly'
+ interval: number
+ /** 0=Sun … 6=Sat. Only honored when freq='weekly'. Empty/undefined = use
+ * the weekday of the seed start_at. */
+ byweekday?: number[]
+ /** Inclusive end of the series — no occurrences after this ISO timestamp. */
+ until?: string | null
+ /** Hard cap on total firings (including the seed). Once reached, the
+ * series is marked 'done'. */
+ count?: number | null
+}
+
+/** Add N days to a Date without mutating the input. */
+function addDays(d: Date, n: number): Date {
+ const out = new Date(d.getTime())
+ out.setUTCDate(out.getUTCDate() + n)
+ return out
+}
+
+/** `seed` shifted by N months, with the day-of-month CLAMPED into the target
+ * month rather than overflowing into the next one.
+ *
+ * `setUTCMonth` overflows: a Jan 31 date asked for February becomes March 3.
+ * That alone would only skip a month, but the old code then stepped from the
+ * overflowed value, so the drift was fed back in and the whole series moved
+ * permanently — "monthly on the 31st" became "the 3rd of every month, from
+ * March". Anchoring on the seed and clamping keeps Jan 31 → Feb 28 → Mar 31,
+ * which is also what a person scheduling month-end work means. */
+function addMonthsClamped(seed: Date, n: number): Date {
+ const day = seed.getUTCDate()
+ // Build on day 1 so the month arithmetic cannot overflow, then clamp.
+ const target = new Date(Date.UTC(
+ seed.getUTCFullYear(), seed.getUTCMonth() + n, 1,
+ seed.getUTCHours(), seed.getUTCMinutes(), seed.getUTCSeconds(), seed.getUTCMilliseconds(),
+ ))
+ // Day 0 of the following month is the last day of this one.
+ const lastDay = new Date(Date.UTC(target.getUTCFullYear(), target.getUTCMonth() + 1, 0)).getUTCDate()
+ target.setUTCDate(Math.min(day, lastDay))
+ return target
+}
+
+/** The weekdays a weekly rule fires on, or null when it should just use the
+ * seed's own weekday. Sorted and de-duplicated so the ordering below is
+ * stable regardless of how the caller wrote the rule. */
+function weeklyDays(rule: RecurrenceRule): number[] | null {
+ const raw = rule.byweekday
+ if (!raw || raw.length === 0) return null
+ const days = [...new Set(raw.filter((d) => Number.isInteger(d) && d >= 0 && d <= 6))].sort((a, b) => a - b)
+ return days.length > 0 ? days : null
+}
+
+/**
+ * The `index`-th occurrence of a rule, counted from the seed (index 0 IS the
+ * seed). Every case is computed FROM THE SEED rather than from the previous
+ * occurrence, which is what keeps an unrepresentable date — Feb 31, Feb 29 in
+ * a common year — from permanently displacing the whole series.
+ */
+function occurrenceAt(seed: Date, rule: RecurrenceRule, index: number): Date {
+ const interval = Math.max(1, Math.floor(rule.interval || 1))
+ switch (rule.freq) {
+ case 'daily':
+ return addDays(seed, index * interval)
+ case 'weekly': {
+ const days = weeklyDays(rule)
+ if (!days) return addDays(seed, index * interval * 7)
+ // Occurrences are grouped into ACTIVE weeks — the seed's week, then every
+ // `interval`-th week after it — and within each one they run through the
+ // allowed weekdays in order. The seed's own week only offers the days at
+ // or after the seed itself, so a Wednesday seed never back-fills Monday.
+ const seedDow = seed.getUTCDay()
+ const firstWeek = days.filter((d) => d >= seedDow)
+ if (index < firstWeek.length) return addDays(seed, firstWeek[index] - seedDow)
+ const rest = index - firstWeek.length
+ const week = Math.floor(rest / days.length) + 1
+ const dow = days[rest % days.length]
+ const weekStart = addDays(seed, -seedDow)
+ return addDays(weekStart, week * interval * 7 + dow)
+ }
+ case 'monthly':
+ return addMonthsClamped(seed, index * interval)
+ case 'yearly':
+ // Years through the same clamp so Feb 29 becomes Feb 28 in a common year
+ // and returns to Feb 29 at the next leap year, instead of sliding to
+ // Mar 1 and staying there.
+ return addMonthsClamped(seed, index * interval * 12)
+ }
+}
+
+/**
+ * Compute the next firing time strictly >= `after`, walking forward from
+ * the event's seed `start_at`. Returns null if:
+ * - the series has no recurrence and start_at < after (already fired)
+ * - rule.until is earlier than the next computed slot
+ * - rule.count is exhausted
+ */
+export function nextOccurrenceOnOrAfter(
+ startAt: Date,
+ recurrence: RecurrenceRule | null,
+ after: Date,
+): Date | null {
+ // One-shot: the only possible slot is start_at itself.
+ if (!recurrence) {
+ return startAt.getTime() >= after.getTime() ? startAt : null
+ }
+ const untilTs = recurrence.until ? new Date(recurrence.until).getTime() : Infinity
+ const maxCount = recurrence.count ?? Infinity
+ // Walk the series by INDEX from the seed rather than stepping off the last
+ // value. Stepping is what let one unrepresentable date (Feb 31) move every
+ // later occurrence with it; an index cannot drift.
+ // Cap iterations defensively so a misconfigured rule can't tie up the tick.
+ for (let index = 0; index < 5000; index++) {
+ if (index + 1 > maxCount) return null // start_at counts as #1
+ const current = occurrenceAt(startAt, recurrence, index)
+ if (current.getTime() > untilTs) return null
+ if (current.getTime() >= after.getTime()) return current
+ }
+ return null
+}
+