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(cos): scheduled cron tasks now actually fire on their schedule

[._.]/ Adam Eivy6e3b23d20621
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 6513d92c19..920fdd427e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -21,6 +21,35 @@
## Fixed
+- **Scheduled cron tasks (e.g. `plan-task` at 9 AM) silently never fired.**
+ Four overlapping bugs in the CoS scheduler combined to make user-pinned
+ cron schedules guaranteed misses: (1) `shouldRunTask` had no catch-up
+ branch — when the daemon was down across a cron boundary, the first run
+ after restart computed `nextRun = TOMORROW` and waited a full period;
+ (2) `scheduleNextImprovementCheck` peeked only `getUpcomingTasks(1)`, so
+ a perpetually-ready weekly task (`status='ready'`) masked any
+ `status='scheduled'` cron task behind it and the next check defaulted
+ to a flat 1h interval that never aligned to cron boundaries; (3)
+ `getNextTaskType` filtered daily → weekly → once → cron, so a ready
+ weekly always outranked a cron task firing right now; (4) stale
+ `activeAgentId` pointers in `app-activity.json` (from idle-review
+ agents that died across long-ago restarts) made `isAppOnCooldown`
+ return `true` indefinitely for affected apps, so
+ `queueEligibleImprovementTasks` silently skipped them every cycle.
+ Fix: added `parseCronToPrevRun` + a `cron-catch-up` branch in
+ `shouldRunTask` (catches up the most-recent past slot within one cron
+ period), widened the upcoming-tasks scan to find the soonest scheduled
+ task across the full list, reordered `getNextTaskType` to put cron /
+ custom ahead of daily / weekly / once, and added
+ `clearStaleActiveAgents()` wired into daemon startup to drop pointers
+ that don't resolve to live agents in `state.agents`. Touches
+ `server/services/eventScheduler.js` (new `parseCronToPrevRun`),
+ `server/services/taskSchedule.js` (catch-up + priority reorder),
+ `server/services/cos.js` (alignment + startup cleanup),
+ `server/services/appActivity.js` (`clearStaleActiveAgents`), plus
+ catch-up + priority regression tests in
+ `server/services/taskSchedule.test.js`.
+
- **Universe canon writes silently dropped at the Zod layer.** The
`patchSchema` in `server/routes/universeBuilder.js` didn't list
`characters` / `settings` / `objects` / `origin`, so Zod's default-strip
diff --git a/server/services/appActivity.js b/server/services/appActivity.js
index b19dd163f0..c641165421 100644
--- a/server/services/appActivity.js
+++ b/server/services/appActivity.js
@@ -123,6 +123,34 @@ export async function clearAppCooldown(appId) {
return updateAppActivity(appId, { cooldownUntil: null });
}
+/**
+ * Clear `activeAgentId` entries that reference agents no longer in the live agent set.
+ *
+ * Called at daemon startup. Without this, an idle-review agent that died across a
+ * server restart (or a Feb-vintage state file that never finished cleanly) leaves a
+ * stale activeAgentId pointing at a dead PID. `isAppOnCooldown` treats any non-null
+ * activeAgentId as "still working" → the app is stuck on cooldown forever, and
+ * `queueEligibleImprovementTasks` silently skips it every cycle.
+ *
+ * @param {Set<string>|Array<string>} liveAgentIds - The currently-running agent IDs from cosState
+ * @returns {Promise<{cleared: string[]}>} - List of app IDs whose activeAgentId was cleared
+ */
+export async function clearStaleActiveAgents(liveAgentIds) {
+ const live = liveAgentIds instanceof Set ? liveAgentIds : new Set(liveAgentIds || []);
+ const activity = await loadAppActivity();
+ const cleared = [];
+ for (const [appId, app] of Object.entries(activity.apps || {})) {
+ if (app.activeAgentId && !live.has(app.activeAgentId)) {
+ cleared.push(appId);
+ app.activeAgentId = null;
+ }
+ }
+ if (cleared.length > 0) {
+ await saveAppActivity(activity);
+ }
+ return { cleared };
+}
+
/**
* Check if an app is on cooldown
*/
diff --git a/server/services/cos.js b/server/services/cos.js
index fda1e6e641..716aaaef35 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -20,7 +20,7 @@ import { promisify } from 'util';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { getActiveProvider } from './providers.js';
import { parseTasksMarkdown, groupTasksByStatus, getNextTask, getAutoApprovedTasks, getAwaitingApprovalTasks, updateTaskStatus, generateTasksMarkdown, hasKnownPrefix, isInternalTaskId } from '../lib/taskParser.js';
-import { isAppOnCooldown, getNextAppForReview, markAppReviewStarted, markIdleReviewStarted } from './appActivity.js';
+import { isAppOnCooldown, getNextAppForReview, markAppReviewStarted, markIdleReviewStarted, clearStaleActiveAgents } from './appActivity.js';
import { getActiveApps, getAppTaskTypeOverrides } from './apps.js';
import { getAdaptiveCooldownMultiplier, getSkippedTaskTypes, getPerformanceSummary, checkAndRehabilitateSkippedTasks, getLearningInsights, getTaskTypeConfidence } from './taskLearning.js';
import { schedule as scheduleEvent, cancel as cancelEvent, getStats as getSchedulerStats, parseCronToNextRun } from './eventScheduler.js';
@@ -182,6 +182,19 @@ export async function start() {
// Then reset any orphaned in_progress tasks (no running agent)
await resetOrphanedTasks();
+ // Clear stale activeAgentId pointers in app-activity.json. Without this, an
+ // idle-review agent that died across a restart (or a long-stale Feb-era state
+ // file) leaves activeAgentId set forever — isAppOnCooldown treats that as
+ // "agent still working" and queueEligibleImprovementTasks silently skips the
+ // app every cycle. Re-load state since the orphan-cleanup steps above have
+ // already mutated the on-disk agents map.
+ const freshState = await loadState();
+ const liveAgentIds = new Set(Object.keys(freshState.agents || {}));
+ const { cleared: clearedActiveAgents } = await clearStaleActiveAgents(liveAgentIds).catch(() => ({ cleared: [] }));
+ if (clearedActiveAgents.length > 0) {
+ emitLog('info', `🧹 Cleared ${clearedActiveAgents.length} stale activeAgentId pointer(s) from app-activity`);
+ }
+
// Archive stale completed agents from state.json on startup
const { archived } = await _archiveStaleAgents().catch(() => ({ archived: 0 }));
if (archived > 0) {
@@ -2965,7 +2978,10 @@ async function scheduleNextImprovementCheck() {
if (!isDaemonRunning()) return;
const taskSchedule = await import('./taskSchedule.js');
- const upcoming = await taskSchedule.getUpcomingTasks(1);
+ // Pull a wider list so a perpetually-"ready" weekly task can't mask an upcoming
+ // cron boundary. We sort by status (ready first), so 1-element peeks always miss
+ // the cron slot when anything else is ready.
+ const upcoming = await taskSchedule.getUpcomingTasks(50);
// Default: check again in 1 hour if nothing scheduled
// Cap at 1 hour so per-app cron tasks (e.g. feature-ideas at 1am) are always checked
@@ -2974,13 +2990,19 @@ async function scheduleNextImprovementCheck() {
let delayMs = MAX_CHECK_INTERVAL;
let description = 'Periodic improvement check (1h)';
- if (upcoming.length > 0 && upcoming[0].status === 'scheduled' && upcoming[0].eligibleIn > 0) {
- delayMs = Math.min(upcoming[0].eligibleIn, MAX_CHECK_INTERVAL);
- const effectiveFormatted = formatDuration(delayMs);
- const capNote = upcoming[0].eligibleIn > MAX_CHECK_INTERVAL
- ? ` (capped from ${upcoming[0].eligibleInFormatted})`
- : '';
- description = `Next improvement: ${upcoming[0].taskType} in ${effectiveFormatted}${capNote}`;
+ // Pick the soonest *scheduled* task (status='scheduled' with positive eligibleIn).
+ // Ready tasks don't gate the delay — they'll be queued on whatever the next check
+ // ends up being. Cron tasks DO gate the delay, because their firing window is a
+ // single minute; missing it pushes the next attempt out by a full period.
+ const nextScheduled = upcoming
+ .filter(t => t.status === 'scheduled' && t.eligibleIn > 0)
+ .sort((a, b) => a.eligibleIn - b.eligibleIn)[0];
+
+ if (nextScheduled && nextScheduled.eligibleIn < MAX_CHECK_INTERVAL) {
+ delayMs = nextScheduled.eligibleIn;
+ description = `Next improvement: ${nextScheduled.taskType} in ${formatDuration(delayMs)}`;
+ } else if (nextScheduled) {
+ description = `Next improvement: ${nextScheduled.taskType} in ${nextScheduled.eligibleInFormatted} (capped at 1h)`;
}
scheduleEvent({
diff --git a/server/services/eventScheduler.js b/server/services/eventScheduler.js
index 0b78509bce..671ccc4780 100644
--- a/server/services/eventScheduler.js
+++ b/server/services/eventScheduler.js
@@ -135,6 +135,80 @@ function parseCronToNextRun(cronExpr, from = new Date(), timezone = 'UTC') {
return null // No match found within 2 years
}
+/**
+ * Parse cron expression to most-recent past execution time (at or before `from`).
+ *
+ * Mirrors parseCronToNextRun but walks backwards. Used to detect missed cron slots
+ * for catch-up logic when the daemon was down across a scheduled time.
+ *
+ * @param {string} cronExpr - Cron expression
+ * @param {Date} from - Reference point; result will be <= from
+ * @param {string} timezone - IANA timezone for matching
+ * @returns {Date|null} - Previous execution time (UTC), or null if invalid/no match within 2 years
+ */
+function parseCronToPrevRun(cronExpr, from = new Date(), timezone = 'UTC') {
+ const parts = cronExpr.trim().split(/\s+/)
+ if (parts.length !== 5) {
+ throw new Error(`Invalid cron expression: ${cronExpr}`)
+ }
+
+ const [minuteExpr, hourExpr, dayOfMonthExpr, monthExpr, dayOfWeekExpr] = parts
+
+ const fieldRanges = [
+ [minuteExpr, 0, 59, 'minute'],
+ [hourExpr, 0, 23, 'hour'],
+ [dayOfMonthExpr, 1, 31, 'dayOfMonth'],
+ [monthExpr, 1, 12, 'month'],
+ [dayOfWeekExpr, 0, 7, 'dayOfWeek']
+ ]
+ for (const [expr, min, max, name] of fieldRanges) {
+ if (!validateCronFieldRange(expr, min, max)) {
+ console.error(`❌ Invalid cron ${name} field "${expr}" in expression: ${cronExpr}`)
+ return null
+ }
+ }
+
+ // Start at the current minute (zero seconds) and walk backwards minute-by-minute
+ const prev = new Date(from)
+ prev.setSeconds(0, 0)
+
+ const minDate = new Date(from)
+ minDate.setFullYear(minDate.getFullYear() - 2)
+
+ const useLocal = timezone !== 'UTC'
+
+ let iterations = 0
+ while (prev > minDate) {
+ if (++iterations > MAX_CRON_ITERATIONS) {
+ console.error(`❌ Cron prev-run search exceeded ${MAX_CRON_ITERATIONS} iterations for: ${cronExpr}`)
+ return null
+ }
+
+ let month, day, dow, hour, minute
+ if (useLocal) {
+ const lp = getLocalParts(prev, timezone)
+ month = lp.month; day = lp.day; dow = lp.dayOfWeek; hour = lp.hour; minute = lp.minute
+ } else {
+ month = prev.getMonth() + 1; day = prev.getDate(); dow = prev.getDay()
+ hour = prev.getHours(); minute = prev.getMinutes()
+ }
+
+ const dowMatches = matchesCronField(dow, dayOfWeekExpr, 0) ||
+ (dow === 0 && matchesCronField(7, dayOfWeekExpr, 0))
+
+ if (matchesCronField(month, monthExpr, 1) &&
+ matchesCronField(day, dayOfMonthExpr, 1) &&
+ dowMatches &&
+ matchesCronField(hour, hourExpr, 0) &&
+ matchesCronField(minute, minuteExpr, 0)) {
+ return prev
+ }
+ prev.setMinutes(prev.getMinutes() - 1)
+ }
+
+ return null
+}
+
/**
* Check if a value matches a cron field expression
* @param {number} value - Current value
@@ -561,5 +635,6 @@ export {
cancelAll,
triggerNow,
parseCronToNextRun,
+ parseCronToPrevRun,
MAX_TIMEOUT
}
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 922ded7a2b..cf4ac9d58d 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -23,7 +23,7 @@ import { isTaskTypeEnabledForApp, getAppTaskTypeInterval, getActiveApps, getAppT
import { loadState, isImprovementEnabled } from './cosState.js';
import { PORTOS_UI_URL, PORTOS_API_URL } from '../lib/ports.js';
import { getUserTimezone, getLocalParts } from '../lib/timezone.js';
-import { parseCronToNextRun } from './eventScheduler.js';
+import { parseCronToNextRun, parseCronToPrevRun } from './eventScheduler.js';
const DATA_DIR = PATHS.cos;
const SCHEDULE_FILE = join(DATA_DIR, 'task-schedule.json');
@@ -1963,6 +1963,39 @@ export async function shouldRunTask(taskType, appId = null) {
result = { shouldRun: false, reason: 'invalid-cron' };
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 if the most-recent occurrence is within ONE cron
+ // period of now (e.g. daily cron catches up to ~24h, hourly to ~1h). The bound
+ // is "the occurrence before prevRun" — anything older has already been missed
+ // by more than one period and shouldn't be replayed.
+ const beforePrev = parseCronToPrevRun(cronExpr, new Date(prevRunMs - 60_000), timezone);
+ lookbackBound = beforePrev ? beforePrev.getTime() : 0;
+ }
+ 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);
const nextRun = parseCronToNextRun(cronExpr, fromDate, timezone);
@@ -2021,9 +2054,16 @@ export async function getNextTaskType(appId = null, lastType = '') {
const schedule = await loadSchedule();
const taskTypes = Object.keys(schedule.tasks);
- // First, check for daily/weekly/once tasks that are due
const dueTasks = await getDueTasks(appId);
+ // Explicit time-based schedules (cron, custom interval) outrank loose interval-based
+ // ones (daily/weekly/once). A user-pinned 9 AM cron should fire at 9 AM even if a
+ // weekly task is perpetually "ready" — the loose tasks will pick up the next slot.
+ const cronDue = dueTasks.filter(t => t.interval.type === INTERVAL_TYPES.CRON || t.interval.type === INTERVAL_TYPES.CUSTOM);
+ if (cronDue.length > 0) {
+ return { taskType: cronDue[0].taskType, reason: `${cronDue[0].interval.type}-due` };
+ }
+
const dailyDue = dueTasks.filter(t => t.interval.type === INTERVAL_TYPES.DAILY);
if (dailyDue.length > 0) {
return { taskType: dailyDue[0].taskType, reason: 'daily-priority' };
@@ -2039,11 +2079,6 @@ export async function getNextTaskType(appId = null, lastType = '') {
return { taskType: onceDue[0].taskType, reason: 'once-first-run' };
}
- const cronDue = dueTasks.filter(t => t.interval.type === INTERVAL_TYPES.CRON || t.interval.type === INTERVAL_TYPES.CUSTOM);
- if (cronDue.length > 0) {
- return { taskType: cronDue[0].taskType, reason: `${cronDue[0].interval.type}-due` };
- }
-
// Fall back to rotation among enabled rotation tasks
const rotationTasks = taskTypes.filter(t =>
schedule.tasks[t].enabled &&
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index 50bc008f67..20928ca01a 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -59,7 +59,8 @@ vi.mock('../lib/timezone.js', () => ({
}))
vi.mock('./eventScheduler.js', () => ({
- parseCronToNextRun: vi.fn()
+ parseCronToNextRun: vi.fn(),
+ parseCronToPrevRun: vi.fn()
}))
// Use the real isImprovementEnabled implementation; only stub loadState.
@@ -99,6 +100,7 @@ import { readJSONFile } from '../lib/fileUtils.js'
import { isTaskTypeEnabledForApp, getAppTaskTypeInterval } from './apps.js'
import { getLocalParts } from '../lib/timezone.js'
import { getAdaptiveCooldownMultiplier } from './taskLearning.js'
+import { parseCronToNextRun, parseCronToPrevRun } from './eventScheduler.js'
const mockSchedule = ({ tasks = {}, executions = {}, templates = [] } = {}) => {
readJSONFile.mockResolvedValue({ version: 2, tasks, executions, templates })
@@ -482,6 +484,81 @@ describe('taskSchedule', () => {
expect(result.shouldRun).toBe(true)
expect(result.reason).toContain('daily-due')
})
+
+ describe('cron catch-up', () => {
+ it('catches up a never-run cron when the most-recent slot is within one period', async () => {
+ // Cron: 0 9 * * * (daily 9 AM). It's now 10:30 AM — today's 9 AM slot already elapsed.
+ // First call (from=now): most-recent past 9 AM is today.
+ // Second call (from=prev-60s): one occurrence earlier = yesterday's 9 AM (the lookback bound).
+ const todayNineAm = new Date()
+ todayNineAm.setHours(9, 0, 0, 0)
+ const yesterdayNineAm = new Date(todayNineAm.getTime() - 24 * 60 * 60 * 1000)
+
+ parseCronToPrevRun
+ .mockReturnValueOnce(todayNineAm) // most-recent past occurrence
+ .mockReturnValueOnce(yesterdayNineAm) // one period earlier (the bound)
+ 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 }
+ }
+ })
+
+ const result = await shouldRunTask('plan-task')
+ expect(result.shouldRun).toBe(true)
+ expect(result.reason).toBe('cron-catch-up')
+ expect(result.missedSlot).toBe(todayNineAm.toISOString())
+ })
+
+ 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. Now it's 11 AM.
+ // Catch-up bound is the recorded lastRun (yesterday), so today's 9 AM counts as missed.
+ const todayNineAm = new Date()
+ todayNineAm.setHours(9, 0, 0, 0)
+ const yesterdayNineAm = new Date(todayNineAm.getTime() - 24 * 60 * 60 * 1000)
+
+ parseCronToPrevRun.mockReturnValueOnce(todayNineAm)
+ 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 }
+ },
+ executions: {
+ 'task:plan-task': { lastRun: yesterdayNineAm.toISOString(), count: 1, perApp: {} }
+ }
+ })
+
+ const result = await shouldRunTask('plan-task')
+ expect(result.shouldRun).toBe(true)
+ expect(result.reason).toBe('cron-catch-up')
+ })
+
+ it('does NOT catch up when lastRun already covers the most-recent slot', async () => {
+ // Cron fired this morning at 9 AM; it's now 10 AM. lastRun is at the same 9 AM.
+ // prevRun == lastRun → not strictly greater → no catch-up.
+ const todayNineAm = new Date()
+ todayNineAm.setHours(9, 0, 0, 0)
+ const tomorrowNineAm = new Date(todayNineAm.getTime() + 24 * 60 * 60 * 1000)
+
+ parseCronToPrevRun.mockReturnValueOnce(todayNineAm)
+ parseCronToNextRun.mockReturnValueOnce(tomorrowNineAm)
+
+ 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: {} }
+ }
+ })
+
+ const result = await shouldRunTask('plan-task')
+ expect(result.shouldRun).toBe(false)
+ expect(result.reason).toBe('cron-cooldown')
+ })
+ })
})
describe('getDueTasks', () => {
@@ -540,6 +617,34 @@ describe('taskSchedule', () => {
const result = await getNextTaskType(null, 'code-quality')
expect(result.taskType).toBe('error-handling')
})
+
+ it('prefers a due cron task over a perpetually-ready weekly task', async () => {
+ // A weekly task with no execution record is perpetually 'ready' (weekly-due).
+ // A cron task firing right now should still win — explicit time-based schedules
+ // shouldn't get masked by loose interval-based ones.
+ const todayNineAm = new Date()
+ todayNineAm.setHours(9, 0, 0, 0)
+ const tomorrowNineAm = new Date(todayNineAm.getTime() + 24 * 60 * 60 * 1000)
+ const yesterdayNineAm = new Date(todayNineAm.getTime() - 24 * 60 * 60 * 1000)
+
+ // shouldRunTask iterates both tasks. For plan-task it calls prev twice (catch-up
+ // path); for code-quality it doesn't call cron helpers at all.
+ parseCronToPrevRun
+ .mockReturnValueOnce(todayNineAm) // plan-task prevRun
+ .mockReturnValueOnce(yesterdayNineAm) // plan-task beforePrev (bound)
+ parseCronToNextRun.mockReturnValue(tomorrowNineAm)
+
+ mockSchedule({
+ tasks: {
+ 'code-quality': { type: 'weekly', enabled: true, providerId: null, model: null, prompt: null, runAfter: [] },
+ 'plan-task': { type: 'cron', enabled: true, cronExpression: '0 9 * * *', providerId: null, model: null, prompt: null }
+ }
+ })
+
+ const result = await getNextTaskType()
+ expect(result.taskType).toBe('plan-task')
+ expect(result.reason).toBe('cron-due')
+ })
})
describe('templates', () => {