Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: stop scheduled tasks from replaying missed cron slots

[._.]/ Adam Eivy2a145908ab46
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index b81d54fe71..6074b495ae 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -6,7 +6,7 @@
*
* Cadence model (two variants + one orthogonal flag):
* - type 'on-demand': never auto-queued; only a manual trigger runs it.
- * - type 'cron': clock-scheduled from `cronExpression` (5-field), with catch-up.
+ * - type 'cron': clock-scheduled from `cronExpression` (5-field), without replaying missed slots.
* - `perpetual: true` (independent of type): drain actionable work back-to-back
* (re-queue on completion) until a programmatic work-detector reports nothing
* actionable, then PARK on a recheck cadence. An on-demand+perpetual task
@@ -25,7 +25,7 @@ import { isTaskTypeEnabledForApp, getAppTaskTypeInterval, getAppTaskTypeInterval
import { loadState, isImprovementEnabled } from './cosState.js';
import { getLocalParts } from '../lib/timezone.js';
import { getUserTimezone } from './userTimezone.js';
-import { parseCronToNextRun, parseCronToPrevRun } from './eventScheduler.js';
+import { parseCronToNextRun } from './eventScheduler.js';
import { isAuditTaskType, defaultFileIssuesFor, auditDoWorkRequiresWorktree, getAuditScheduleMetadata, AUDIT_RUN_GUIDANCE, AUDIT_SUGGESTED_AFTER } from '../lib/auditCatalog.js';
import { DEFAULT_TASK_PROMPTS } from './taskPromptDefaults.js';
import {
@@ -940,44 +940,12 @@ export async function shouldRunTask(taskType, appId = null, { featureEnabled = c
break;
}
- // Catch-up: if a cron slot has already elapsed since the last successful run
- // (or, for never-run tasks, within the last cron period), fire it now instead
- // of waiting another full period. This recovers from daemon downtime, restarts,
- // and the hourly-check window missing the 60-second cron match.
- const prevRun = parseCronToPrevRun(cronExpr, new Date(now), timezone);
- if (prevRun) {
- const prevRunMs = prevRun.getTime();
- let lookbackBound;
- if (lastRun) {
- lookbackBound = lastRun;
- } else {
- // Never-run: only catch up to a slot that elapsed AFTER the task was
- // configured. Without this bound a never-run task always fires its most
- // recent past slot, so a weekly "Sunday 09:00" task enabled on a Friday
- // immediately reads as "due now (catch-up)" for last Sunday — a slot that
- // predates the task and was never actually missed. `createdAt` is stamped
- // when the task is first seen (loadSchedule backfills it for existing
- // installs), so catch-up only recovers slots the task was around for. An
- // un-backfilled task (createdAt absent) yields bound 0 → the legacy
- // always-catch-up behavior.
- lookbackBound = safeDate(interval.createdAt);
- }
- if (prevRunMs > lookbackBound && prevRunMs <= now) {
- // Compute nextRun for telemetry/reporting
- const nextRunAfterCatch = parseCronToNextRun(cronExpr, new Date(now), timezone);
- result = {
- shouldRun: true,
- reason: 'cron-catch-up',
- cronExpression: cronExpr,
- missedSlot: prevRun.toISOString(),
- nextRunAt: nextRunAfterCatch ? nextRunAfterCatch.toISOString() : null
- };
- break;
- }
- }
-
- // For never-run tasks, use 1 minute ago so the first scheduled occurrence can match
- const fromDate = lastRun ? new Date(lastRun) : new Date(now - 60_000);
+ // Only the current scheduled minute is eligible. Replaying from lastRun
+ // makes a schedule edit retroactively create missed work and lets hourly
+ // improvement checks launch tasks before their next configured occurrence.
+ // Keep lastRun as a lower bound to prevent a second run in the same minute.
+ const minuteStart = Math.floor(now / 60_000) * 60_000;
+ const fromDate = new Date(Math.max(lastRun || 0, minuteStart - 1));
const nextRun = parseCronToNextRun(cronExpr, fromDate, timezone);
if (!nextRun) {
result = { shouldRun: false, reason: 'invalid-cron', cronExpression: cronExpr };
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index 5ba12cac14..b19670c2ba 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -87,8 +87,7 @@ vi.mock('./userTimezone.js', () => ({
}))
vi.mock('./eventScheduler.js', () => ({
- parseCronToNextRun: vi.fn(),
- parseCronToPrevRun: vi.fn()
+ parseCronToNextRun: vi.fn()
}))
// Failure-park auto-notification (#2616): recordTaskTypeFailure lazy-imports
@@ -191,7 +190,7 @@ import { writeFile } from 'fs/promises'
import { isTaskTypeEnabledForApp, getAppTaskTypeInterval, clearAllPrWatcherState, clearAllIssueWatcherState } from './apps.js'
import { getLocalParts } from '../lib/timezone.js'
import { getAdaptiveCooldownMultiplier } from './taskLearning.js'
-import { parseCronToNextRun, parseCronToPrevRun } from './eventScheduler.js'
+import { parseCronToNextRun } from './eventScheduler.js'
import { addNotification, exists as notificationExists, removeByMetadata } from './notifications.js'
import { isInstanceFeatureEnabled } from './instanceFeatures.js'
@@ -210,23 +209,18 @@ const PAUSED_SHIPPED_DRAINS = {
// The cron parser is mocked module-wide, so a case that wants a cron task
// simply due (or simply on cooldown) states it here rather than hand-picking
-// wall-clock instants: no catch-up slot, and a next slot already past / still
-// ahead. Callers needing catch-up semantics still stub prevRun themselves.
+// wall-clock instants: a slot in the current minute, or one still ahead.
const cronDueNow = () => {
- parseCronToPrevRun.mockReturnValue(null)
- parseCronToNextRun.mockReturnValue(new Date(Date.now() - 60_000))
+ parseCronToNextRun.mockReturnValue(new Date(Math.floor(Date.now() / 60_000) * 60_000))
}
const cronNotDueYet = () => {
- parseCronToPrevRun.mockReturnValue(null)
parseCronToNextRun.mockReturnValue(new Date(Date.now() + 60 * 60 * 1000))
}
// Resolve "the most recent 9 AM in the past, local time." Bare
// `setHours(9, 0, 0, 0)` flakes in CI when the runner's wall-clock is
// before 9 AM local (UTC CI fires at ~04:00 UTC daily) — today's 9 AM
-// would be in the future and shouldRunTask's `prevRunMs <= now` guard
-// correctly rejects a slot that hasn't happened yet, breaking these
-// tests' premise. Subtract a day when needed.
+// would be in the future. Subtract a day when needed.
const recentNineAm = () => {
const d = new Date()
d.setHours(9, 0, 0, 0)
@@ -1333,96 +1327,58 @@ describe('taskSchedule', () => {
expect(result.reason).toBe('cron-due')
})
- describe('cron catch-up', () => {
- it('catches up a never-run cron when the missed slot elapsed after the task was created', async () => {
- // Cron: 0 9 * * * (daily 9 AM). The task was configured yesterday and the
- // daemon missed today's 9 AM slot — so the elapsed slot is genuinely missed
- // and should fire now. The catch-up bound is the task's createdAt.
- const todayNineAm = recentNineAm()
- const twoDaysAgo = new Date(todayNineAm.getTime() - 2 * 24 * 60 * 60 * 1000)
-
- parseCronToPrevRun.mockReturnValueOnce(todayNineAm) // most-recent past occurrence
- parseCronToNextRun.mockReturnValueOnce(new Date(todayNineAm.getTime() + 24 * 60 * 60 * 1000))
-
- mockSchedule({
- tasks: {
- 'plan-task': { type: 'cron', enabled: true, cronExpression: '0 9 * * *', providerId: null, model: null, prompt: null, createdAt: twoDaysAgo.toISOString() }
- }
- })
-
- const result = await shouldRunTask('plan-task')
- expect(result.shouldRun).toBe(true)
- expect(result.reason).toBe('cron-catch-up')
- expect(result.missedSlot).toBe(todayNineAm.toISOString())
+ describe('cron slots without catch-up', () => {
+ let savedImplementations
+ beforeEach(async () => {
+ const mocks = [parseCronToNextRun, getLocalParts, getAppTaskTypeInterval, isTaskTypeEnabledForApp]
+ savedImplementations = mocks.map(mock => [mock, mock.getMockImplementation()])
+ const actual = await vi.importActual('../lib/timezone.js')
+ getLocalParts.mockImplementation(actual.getLocalParts)
+ isTaskTypeEnabledForApp.mockResolvedValue(true)
})
-
- it('does NOT catch up a never-run cron whose most-recent slot predates the task', async () => {
- // The reported bug: a weekly "Sunday 09:00" task enabled mid-week must NOT
- // immediately fire for last Sunday's slot — that slot elapsed before the
- // task existed, so there was nothing to miss. It waits for the next Sunday.
- const now = Date.now()
- const lastSunday = new Date(now - 3 * 24 * 60 * 60 * 1000) // slot before creation
- const nextSunday = new Date(now + 4 * 24 * 60 * 60 * 1000)
- const createdYesterday = new Date(now - 1 * 24 * 60 * 60 * 1000) // task created after last Sunday
-
- parseCronToPrevRun.mockReturnValueOnce(lastSunday)
- parseCronToNextRun.mockReturnValue(nextSunday)
-
- mockSchedule({
- tasks: {
- 'branch-cleanup': { type: 'cron', enabled: true, cronExpression: '0 9 * * 0', providerId: null, model: null, prompt: null, createdAt: createdYesterday.toISOString() }
- }
- })
-
- const result = await shouldRunTask('branch-cleanup')
- expect(result.shouldRun).toBe(false)
- expect(result.reason).toBe('cron-cooldown')
+ afterEach(() => {
+ for (const [mock, implementation] of savedImplementations) mock.mockImplementation(implementation)
})
- it('catches up after the recorded lastRun even if the daemon missed the slot', async () => {
- // Cron fired yesterday, then daemon was down across today's 9 AM.
- // Catch-up bound is the recorded lastRun (yesterday), so today's 9 AM counts as missed.
- const todayNineAm = recentNineAm()
- const yesterdayNineAm = new Date(todayNineAm.getTime() - 24 * 60 * 60 * 1000)
-
- parseCronToPrevRun.mockReturnValueOnce(todayNineAm)
- parseCronToNextRun.mockReturnValueOnce(new Date(todayNineAm.getTime() + 24 * 60 * 60 * 1000))
+ it('waits after an inherited schedule edit, fires in the new slot, and does not repeat it', async () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-09-09T05:57:22Z'))
+ const actual = await vi.importActual('./eventScheduler.js')
+ parseCronToNextRun.mockImplementation(actual.parseCronToNextRun)
+ getAppTaskTypeInterval.mockResolvedValue(null)
+ const lastRun = '2026-09-08T05:01:00Z'
+ const schedule = {
+ tasks: { 'release-check': { type: 'cron', enabled: true, cronExpression: '30 4 * * *', runAfter: [] } },
+ executions: { 'task:release-check': { perApp: { 'app-1': { lastRun, count: 1 } } } }
+ }
+ mockSchedule(schedule)
- mockSchedule({
- tasks: {
- 'plan-task': { type: 'cron', enabled: true, cronExpression: '0 9 * * *', providerId: null, model: null, prompt: null }
- },
- executions: {
- 'task:plan-task': { lastRun: yesterdayNineAm.toISOString(), count: 1, perApp: {} }
- }
+ expect(await shouldRunTask('release-check', 'app-1')).toMatchObject({
+ shouldRun: false, reason: 'cron-cooldown', nextRunAt: '2026-09-09T11:30:00.000Z'
})
+ vi.setSystemTime(new Date('2026-09-09T11:30:20Z'))
+ expect(await shouldRunTask('release-check', 'app-1')).toMatchObject({ shouldRun: true, reason: 'cron-due' })
- const result = await shouldRunTask('plan-task')
- expect(result.shouldRun).toBe(true)
- expect(result.reason).toBe('cron-catch-up')
+ schedule.executions['task:release-check'].perApp['app-1'].lastRun = '2026-09-09T11:30:20Z'
+ mockSchedule(schedule)
+ expect(await shouldRunTask('release-check', 'app-1')).toMatchObject({
+ shouldRun: false, nextRunAt: '2026-09-10T11:30:00.000Z'
+ })
})
- it('does NOT catch up when lastRun already covers the most-recent slot', async () => {
- // Cron fired this morning at 9 AM; lastRun is at the same 9 AM.
- // prevRun == lastRun → not strictly greater → no catch-up.
- const todayNineAm = recentNineAm()
- const tomorrowNineAm = new Date(todayNineAm.getTime() + 24 * 60 * 60 * 1000)
-
- parseCronToPrevRun.mockReturnValueOnce(todayNineAm)
- parseCronToNextRun.mockReturnValueOnce(tomorrowNineAm)
-
+ it('waits for the next per-app slot after downtime, including never-run tasks', async () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-09-09T12:00:00Z'))
+ const actual = await vi.importActual('./eventScheduler.js')
+ parseCronToNextRun.mockImplementation(actual.parseCronToNextRun)
+ getAppTaskTypeInterval.mockResolvedValue('30 4 * * *')
mockSchedule({
- tasks: {
- 'plan-task': { type: 'cron', enabled: true, cronExpression: '0 9 * * *', providerId: null, model: null, prompt: null }
- },
- executions: {
- 'task:plan-task': { lastRun: todayNineAm.toISOString(), count: 1, perApp: {} }
- }
+ tasks: { 'release-check': { type: 'cron', enabled: true, cronExpression: '0 8 * * *', createdAt: '2026-09-01T00:00:00Z', runAfter: [] } }
})
-
- const result = await shouldRunTask('plan-task')
- expect(result.shouldRun).toBe(false)
- expect(result.reason).toBe('cron-cooldown')
+ expect(await shouldRunTask('release-check', 'app-1')).toMatchObject({
+ shouldRun: false, nextRunAt: '2026-09-10T11:30:00.000Z'
+ })
+ getAppTaskTypeInterval.mockResolvedValue(null)
})
})
})
@@ -1437,7 +1393,6 @@ describe('taskSchedule', () => {
})
it('returns a due cron task and skips a disabled one', async () => {
- parseCronToPrevRun.mockReturnValue(null)
parseCronToNextRun.mockReturnValue(new Date(Date.now() - 60_000))
mockSchedule({
tasks: {
@@ -1476,7 +1431,6 @@ describe('taskSchedule', () => {
it('does not select a feature-disabled task', async () => {
isInstanceFeatureEnabled.mockResolvedValue(false)
- parseCronToPrevRun.mockReturnValue(null)
parseCronToNextRun.mockReturnValue(new Date(Date.now() - 60_000))
mockSchedule({ tasks: {
...PAUSED_SHIPPED_DRAINS,
@@ -1490,13 +1444,9 @@ describe('taskSchedule', () => {
// A user-pinned wall-clock schedule must fire at its slot even while a
// perpetual task is perpetually 'ready' (draining a backlog).
const todayNineAm = recentNineAm()
- const tomorrowNineAm = new Date(todayNineAm.getTime() + 24 * 60 * 60 * 1000)
const yesterdayNineAm = new Date(todayNineAm.getTime() - 24 * 60 * 60 * 1000)
- // shouldRunTask iterates both tasks. plan-task was created before its missed
- // slot (createdAt bound), so its elapsed 9 AM counts as a genuine catch-up.
- parseCronToPrevRun.mockReturnValueOnce(todayNineAm) // plan-task prevRun
- parseCronToNextRun.mockReturnValue(tomorrowNineAm)
+ cronDueNow()
mockSchedule({
tasks: {
@@ -1518,10 +1468,8 @@ describe('taskSchedule', () => {
// perpetual drain is eligible, so the caller passes perpetualOnly to get
// the drain instead of being stranded behind the cooled-down cron pick.
const todayNineAm = recentNineAm()
- const tomorrowNineAm = new Date(todayNineAm.getTime() + 24 * 60 * 60 * 1000)
const yesterdayNineAm = new Date(todayNineAm.getTime() - 24 * 60 * 60 * 1000)
- parseCronToPrevRun.mockReturnValueOnce(todayNineAm)
- parseCronToNextRun.mockReturnValue(tomorrowNineAm)
+ cronDueNow()
mockSchedule({
tasks: {
@@ -1543,7 +1491,6 @@ describe('taskSchedule', () => {
})
it('perpetualOnly returns null when no perpetual task is due (app stays throttled)', async () => {
- parseCronToPrevRun.mockReturnValue(null)
parseCronToNextRun.mockReturnValue(new Date(Date.now() - 60_000))
mockSchedule({
tasks: {