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

feat: collapse scheduled-task cadences to On-Demand or Scheduled (#5829)

Adam Eivy52127c4334ca
diff --git a/client/src/components/UpcomingTasksWidget.jsx b/client/src/components/UpcomingTasksWidget.jsx
index 6ef66cdd35..65697f88d6 100644
--- a/client/src/components/UpcomingTasksWidget.jsx
+++ b/client/src/components/UpcomingTasksWidget.jsx
@@ -34,11 +34,8 @@ const UpcomingTasksWidget = memo(function UpcomingTasksWidget() {
// Get interval type label
const getIntervalLabel = (intervalType) => {
const labels = {
- daily: 'Daily',
- weekly: 'Weekly',
- rotation: 'Rotation',
- once: 'One-time',
- custom: 'Custom'
+ 'on-demand': 'On Demand',
+ cron: 'Scheduled'
};
return labels[intervalType] || intervalType;
};
diff --git a/client/src/components/apps/LayeredIntelligenceTab.jsx b/client/src/components/apps/LayeredIntelligenceTab.jsx
index 4651afc1fe..4c1a609db2 100644
--- a/client/src/components/apps/LayeredIntelligenceTab.jsx
+++ b/client/src/components/apps/LayeredIntelligenceTab.jsx
@@ -6,6 +6,7 @@ import LayeredIntelligenceOutcomes from './LayeredIntelligenceOutcomes';
import { timeAgo } from '../../utils/formatters';
import { formatLiReason, liReasonTone } from '../../utils/layeredIntelligenceReasons';
import { INPUT_CLASS } from './constants';
+import { cronFromIntervalMs } from '../../utils/cronHelpers';
// The self-improvement loop's per-app config surface. Field set mirrors the
// server schema (server/lib/validation.js `layeredIntelligenceConfigSchema`)
@@ -171,18 +172,17 @@ export function buildLayeredIntelligenceUpdate(baseline, current) {
return Object.keys(update).length > 0 ? update : null;
}
+// Map a chosen intervalMs to the per-app override's { interval, intervalMs }
+// pair the scheduler understands. The per-app cadence is a 5-field cron string
+// (a space-containing `interval` is read directly as the expression), so the
+// numeric picker writes the derived expression — NOT the UI's 'cron' sentinel,
+// which only opens the editor and saves no cadence. `intervalMs` rides along so
+// the picker can re-select the slot the user chose.
const DAY_MS = 24 * 60 * 60 * 1000;
-const WEEK_MS = 7 * DAY_MS;
-// Map a chosen intervalMs to the per-app override's { interval, intervalMs } pair
-// the scheduler understands: 'daily'/'weekly' for the standard cadences, else
-// 'custom' (the scheduler's CUSTOM branch reads the numeric intervalMs). Mirrors
-// the server migration's intervalFieldsFromMs.
export function intervalFieldsFromMs(intervalMs) {
const ms = typeof intervalMs === 'number' && intervalMs > 0 ? intervalMs : DAY_MS;
- if (ms === DAY_MS) return { interval: 'daily', intervalMs: ms };
- if (ms === WEEK_MS) return { interval: 'weekly', intervalMs: ms };
- return { interval: 'custom', intervalMs: ms };
+ return { interval: cronFromIntervalMs(ms), intervalMs: ms };
}
/**
diff --git a/client/src/components/apps/LayeredIntelligenceTab.test.jsx b/client/src/components/apps/LayeredIntelligenceTab.test.jsx
index 134888cdaf..c9434740ef 100644
--- a/client/src/components/apps/LayeredIntelligenceTab.test.jsx
+++ b/client/src/components/apps/LayeredIntelligenceTab.test.jsx
@@ -184,11 +184,14 @@ describe('buildLayeredIntelligenceScheduleUpdate (per-app task override, #2322)'
expect(buildLayeredIntelligenceScheduleUpdate(baseline, { ...baseline, enabled: true })).toEqual({ enabled: true });
});
- it('emits interval + intervalMs together, mapping to daily/weekly/custom', () => {
+ it('emits interval as a 5-field cron string alongside intervalMs', () => {
+ // The per-app override reads a space-containing `interval` as the cron
+ // expression, so the numeric picker must write the expression itself — never
+ // a retired cadence name, and never the UI's 'cron' editor sentinel.
expect(buildLayeredIntelligenceScheduleUpdate(baseline, { ...baseline, intervalMs: 3600000 }))
- .toEqual({ interval: 'custom', intervalMs: 3600000 });
+ .toEqual({ interval: '0 * * * *', intervalMs: 3600000 });
expect(buildLayeredIntelligenceScheduleUpdate({ ...baseline, intervalMs: 3600000 }, { ...baseline, intervalMs: 7 * 86400000 }))
- .toEqual({ interval: 'weekly', intervalMs: 7 * 86400000 });
+ .toEqual({ interval: '0 7 * * 1', intervalMs: 7 * 86400000 });
});
it('normalizes empty provider/model to null and only emits when changed', () => {
@@ -206,11 +209,12 @@ describe('buildLayeredIntelligenceScheduleUpdate (per-app task override, #2322)'
.toEqual({ providerId: null, model: null });
});
- it('intervalFieldsFromMs maps standard cadences + falls back to daily', () => {
- expect(intervalFieldsFromMs(86400000)).toEqual({ interval: 'daily', intervalMs: 86400000 });
- expect(intervalFieldsFromMs(7 * 86400000)).toEqual({ interval: 'weekly', intervalMs: 7 * 86400000 });
- expect(intervalFieldsFromMs(6 * 3600000)).toEqual({ interval: 'custom', intervalMs: 6 * 3600000 });
- expect(intervalFieldsFromMs(0)).toEqual({ interval: 'daily', intervalMs: 86400000 });
+ it('intervalFieldsFromMs derives a cron expression + falls back to daily', () => {
+ expect(intervalFieldsFromMs(86400000)).toEqual({ interval: '0 7 * * *', intervalMs: 86400000 });
+ expect(intervalFieldsFromMs(7 * 86400000)).toEqual({ interval: '0 7 * * 1', intervalMs: 7 * 86400000 });
+ expect(intervalFieldsFromMs(6 * 3600000)).toEqual({ interval: '0 */6 * * *', intervalMs: 6 * 3600000 });
+ expect(intervalFieldsFromMs(900000)).toEqual({ interval: '*/15 * * * *', intervalMs: 900000 });
+ expect(intervalFieldsFromMs(0)).toEqual({ interval: '0 7 * * *', intervalMs: 86400000 });
});
});
diff --git a/client/src/components/apps/tabs/AutomationTab.jsx b/client/src/components/apps/tabs/AutomationTab.jsx
index ab2a850165..82d73be830 100644
--- a/client/src/components/apps/tabs/AutomationTab.jsx
+++ b/client/src/components/apps/tabs/AutomationTab.jsx
@@ -16,12 +16,8 @@ const RUNNABLE_PROVIDER_TYPES = Object.values(PROVIDER_TYPES);
const INTERVAL_OPTIONS = [
{ value: null, label: 'Inherit Global' },
- { value: 'rotation', label: 'Rotation' },
- { value: 'daily', label: 'Daily' },
- { value: 'weekly', label: 'Weekly' },
- { value: 'once', label: 'Once' },
- { value: 'on-demand', label: 'On-demand' },
- { value: 'cron', label: 'Cron' }
+ { value: 'on-demand', label: 'On Demand' },
+ { value: 'cron', label: 'Scheduled' }
];
export default function AutomationTab({ appId, appName }) {
diff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsx
index 70b2fb4bf7..0796500f47 100644
--- a/client/src/components/cos/tabs/ScheduleTab.jsx
+++ b/client/src/components/cos/tabs/ScheduleTab.jsx
@@ -114,17 +114,6 @@ export default function ScheduleTab({ apps, providers, activeProviderId }) {
return result.request || true;
}, [apps, fetchSchedule]);
- const handleResetTask = async (taskType) => {
- const result = await api.resetCosTaskHistory(taskType, null, { silent: true }).catch(err => {
- toast.error(err.message);
- return null;
- });
- if (result?.success) {
- toast.success(`Reset execution history for ${taskType}`);
- fetchSchedule();
- }
- };
-
const handleTriggerAppImprovement = handleTriggerTask;
const { handleUpdateOverride, handleBulkToggleOverride } = useAppOverrideActions(apps, fetchSchedule);
@@ -218,7 +207,6 @@ export default function ScheduleTab({ apps, providers, activeProviderId }) {
onClose={() => setSelectedTask(null)}
onUpdate={handleUpdateTask}
onTrigger={handleTriggerAppImprovement}
- onReset={handleResetTask}
providers={providers}
activeProviderId={activeProviderId}
apps={apps}
diff --git a/client/src/components/cos/tabs/WorkflowTab.jsx b/client/src/components/cos/tabs/WorkflowTab.jsx
index c057cb8a80..274b76b338 100644
--- a/client/src/components/cos/tabs/WorkflowTab.jsx
+++ b/client/src/components/cos/tabs/WorkflowTab.jsx
@@ -16,16 +16,18 @@ const TRACK_COLORS = {
};
function trackPalette(node) {
- if (node.schedule?.type === 'perpetual') return TRACK_COLORS.perpetual;
+ if (node.schedule?.perpetual) return TRACK_COLORS.perpetual;
if (node.schedule?.cronSchedule || node.schedule?.cronExpression) return TRACK_COLORS.cron;
return TRACK_COLORS[node.kind] || TRACK_COLORS.task;
}
function describeSchedule(node) {
const schedule = node.schedule || {};
- if (schedule.type === 'perpetual') {
- const reset = schedule.recheckCron ? describeCron(schedule.recheckCron) : 'daily reset';
- return `perpetual · ${reset}`;
+ // A perpetual task's cadence line names its recheck: a scheduled one rechecks
+ // on its own cron expression, an on-demand one on `recheckCron`.
+ if (schedule.perpetual) {
+ const recheck = schedule.cronExpression || schedule.recheckCron;
+ return `perpetual · ${recheck ? describeCron(recheck) || recheck : 'daily reset'}`;
}
if (schedule.cronSchedule) return describeRecurrence(schedule.cronSchedule);
if (schedule.cronExpression) return describeCron(schedule.cronExpression) || schedule.cronExpression;
diff --git a/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx b/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx
index c78222e5f4..1b168aeb84 100644
--- a/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx
+++ b/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx
@@ -131,12 +131,8 @@ const AppOverrideRow = memo(function AppOverrideRow({ app, taskType, globalInter
className="bg-port-card border border-port-border rounded px-2 py-1.5 text-xs text-white min-w-[120px] min-h-[40px]"
>
<option value="">Inherit ({INTERVAL_LABELS[globalIntervalType] || globalIntervalType})</option>
- <option value="rotation">Rotation</option>
- <option value="daily">Daily</option>
- <option value="weekly">Weekly</option>
- <option value="once">Once</option>
<option value="on-demand">On Demand</option>
- <option value="cron">Cron</option>
+ <option value="cron">Scheduled</option>
</select>
{cronEditing ? (
<CronInput
diff --git a/client/src/components/cos/tabs/schedule/AppTaskCard.test.jsx b/client/src/components/cos/tabs/schedule/AppTaskCard.test.jsx
index ce1e25753f..28332f0cbf 100644
--- a/client/src/components/cos/tabs/schedule/AppTaskCard.test.jsx
+++ b/client/src/components/cos/tabs/schedule/AppTaskCard.test.jsx
@@ -69,9 +69,11 @@ describe('AppTaskCard', () => {
expect(screen.getByText(/^in /)).toBeTruthy();
});
- it('renders a clean Cron badge and next-run schedule description for cron tasks', () => {
+ it('renders a clean Scheduled badge and next-run schedule description for cron tasks', () => {
renderCard({ type: 'cron', cronExpression: '0 6 * * 1-5' }, {}, 'layered-intelligence');
- expect(screen.getByText('Cron')).toBeTruthy();
+ expect(screen.getByText('Scheduled')).toBeTruthy();
+ // Perpetual is an ORTHOGONAL badge, so a plain cron task never shows one.
+ expect(screen.queryByText('Perpetual')).toBeNull();
expect(screen.getAllByTitle('Weekdays at 06:00 (0 6 * * 1-5)').length).toBeGreaterThanOrEqual(1);
expect(screen.getByText(/^in .* · Weekdays at 06:00/)).toBeTruthy();
expect(screen.getByText('layered-intelligence')).toBeTruthy();
@@ -82,6 +84,12 @@ describe('AppTaskCard', () => {
expect(screen.getByText('Manual trigger only')).toBeTruthy();
});
+ it('renders BOTH badges for a scheduled task that also drains perpetually', () => {
+ renderCard({ type: 'cron', cronExpression: '0 6 * * 1-5', perpetual: true });
+ expect(screen.getByText('Scheduled')).toBeTruthy();
+ expect(screen.getByText('Perpetual')).toBeTruthy();
+ });
+
it('shows "Paused" for disabled tasks', () => {
renderCard({ enabled: false });
expect(screen.getByText('Paused')).toBeTruthy();
diff --git a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
index ef1631f95d..7e756a76a9 100644
--- a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
+++ b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
@@ -18,7 +18,7 @@ import EffortSelect from '../../EffortSelect';
import PromptEditor from './PromptEditor';
import RunTaskButton from './RunTaskButton';
import TaskDataInputs from '../../TaskDataInputs';
-import { INTERVAL_DESCRIPTIONS, toggleMetadataField, pipelineStages, IMPROVEMENT_DISABLED_TITLE, SAVING_TITLE, fileIssuesEffective, managedAgentOptionsFor, toggleFileIssuesMetadata } from './scheduleConstants';
+import { INTERVAL_DESCRIPTIONS, PERPETUAL_DESCRIPTION, toggleMetadataField, pipelineStages, IMPROVEMENT_DISABLED_TITLE, SAVING_TITLE, fileIssuesEffective, managedAgentOptionsFor, toggleFileIssuesMetadata } from './scheduleConstants';
// Shown for the unpinned ('' → inherit) choice: the task type is global, so the
// policy is whatever each target app configured, and PortOS's own self-improvement
@@ -40,7 +40,7 @@ const REVIEW_CONFIG_KEYS = [
'reviewerApplies',
];
-export default function GlobalConfigControls({ taskType, config, onUpdate, onTrigger, onReset, category: _category, providers, activeProviderId, apps, updating, setUpdating, allTaskTypes, improvementDisabled, dataInputCatalog }) {
+export default function GlobalConfigControls({ taskType, config, onUpdate, onTrigger, category: _category, providers, activeProviderId, apps, updating, setUpdating, allTaskTypes, improvementDisabled, dataInputCatalog }) {
const reviewDefaults = useCodeReviewDefaults();
// Resolved model lists for the reviewer table's Model column (the picker itself
// never fetches — see its `modelOptions` prop).
@@ -107,21 +107,12 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
const handleTypeChange = async (newType) => {
if (newType === 'cron') {
+ // Open the editor rather than saving: the cadence isn't chosen until an
+ // expression is committed (handleCronSave writes both fields together).
setCronEditing(true);
setSelectedType('cron');
return;
}
- if (newType === 'perpetual') {
- // Don't null recheckCron — switching to perpetual keeps any prior cadence.
- setCronEditing(false);
- setUpdating(true);
- setSelectedType('perpetual');
- await onUpdate(taskType, { type: 'perpetual' }).catch(() => {
- setSelectedType(config.type);
- });
- setUpdating(false);
- return;
- }
setCronEditing(false);
setUpdating(true);
setSelectedType(newType);
@@ -131,6 +122,14 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
setUpdating(false);
};
+ // Perpetual is orthogonal to the cadence — toggling it never touches `type`,
+ // so a Scheduled task keeps its expression and an On-Demand one stays manual.
+ const handlePerpetualToggle = async () => {
+ setUpdating(true);
+ await onUpdate(taskType, { perpetual: !config.perpetual }).catch(() => {});
+ setUpdating(false);
+ };
+
const handleCronSave = async (expr) => {
setUpdating(true);
await onUpdate(taskType, { type: 'cron', cronExpression: expr }).catch(() => {
@@ -142,11 +141,7 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
const handleRecheckCronSave = async (expr) => {
setUpdating(true);
- // Switching to perpetual together with its recheck cadence in one PUT so a
- // freshly-picked perpetual type lands with the cadence already set.
- await onUpdate(taskType, { type: 'perpetual', recheckCron: expr }).catch(() => {
- setSelectedType(config.type);
- });
+ await onUpdate(taskType, { recheckCron: expr }).catch(() => {});
setRecheckEditing(false);
setUpdating(false);
};
@@ -289,13 +284,8 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
disabled={updating}
className="w-full bg-port-card border border-port-border rounded px-3 py-2 text-white text-sm"
>
- <option value="rotation">Rotation (runs in task queue)</option>
- <option value="daily">Daily (once per day)</option>
- <option value="weekly">Weekly (once per week)</option>
- <option value="once">Once (run once then stop)</option>
<option value="on-demand">On Demand (manual trigger only)</option>
- <option value="cron">Cron (custom schedule)</option>
- <option value="perpetual">Perpetual (drain until done, then recheck)</option>
+ <option value="cron">Scheduled (cron)</option>
</select>
{(selectedType === 'cron' && (cronEditing || config.type === 'cron')) ? (
<CronInput
@@ -309,7 +299,31 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
)}
</FormField>
- {selectedType === 'perpetual' && (
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-1.5">
+ <span className="text-sm text-gray-400">Perpetual</span>
+ <InfoTooltip label="What does Perpetual do?">
+ {PERPETUAL_DESCRIPTION}. It applies to either cadence: an On-Demand
+ perpetual task drains whenever it isn&apos;t parked, and a Scheduled
+ one starts its drain on the cron slot and rechecks on the same schedule.
+ </InfoTooltip>
+ </div>
+ <ToggleSwitch
+ enabled={!!config.perpetual}
+ onChange={handlePerpetualToggle}
+ disabled={updating}
+ ariaLabel={config.perpetual ? 'Disable perpetual drain' : 'Enable perpetual drain'}
+ />
+ </div>
+
+ {config.perpetual && selectedType === 'cron' && (
+ <p className="text-xs text-gray-500">
+ Each cron slot starts a drain that runs back-to-back while actionable work remains;
+ once it parks, the same schedule gates the next attempt.
+ </p>
+ )}
+
+ {config.perpetual && selectedType === 'on-demand' && (
<div>
<span className="text-sm text-gray-400 block mb-2">Recheck Cadence</span>
{(recheckEditing || config.recheckCron) ? (
@@ -335,9 +349,9 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
</p>
{(() => {
// claim-issue/claim-work park PER-APP, so prefer the per-app aggregate
- // (config.perpetual) over the global status.reason — which always reads
- // 'perpetual-drain' for app-scoped tasks even when every app is parked.
- const p = config.perpetual;
+ // (config.perpetualStatus) over the global status.reason — which always
+ // reads 'perpetual-drain' for app-scoped tasks even when every app is parked.
+ const p = config.perpetualStatus;
if (p && (p.trackedAppCount > 0 || p.globalParked)) {
const allParked = p.globalParked || (p.trackedAppCount > 0 && p.parkedAppCount === p.trackedAppCount);
if (allParked) {
@@ -714,16 +728,6 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
{config.invocation?.label || 'Automation-only'} — runs from its parent automation
</div>
)}
- {config.type === 'once' && status.reason === 'once-completed' && (
- <button
- onClick={() => onReset(taskType)}
- className="flex items-center gap-1 px-3 py-1.5 text-sm bg-port-warning/20 hover:bg-port-warning/30 text-port-warning rounded transition-colors"
- title="Reset execution history to run this task again"
- >
- <RotateCcw size={14} />
- Reset
- </button>
- )}
</div>
{status.completedAt && (
diff --git a/client/src/components/cos/tabs/schedule/GlobalConfigControls.test.jsx b/client/src/components/cos/tabs/schedule/GlobalConfigControls.test.jsx
index cede4747c3..2f26b557b9 100644
--- a/client/src/components/cos/tabs/schedule/GlobalConfigControls.test.jsx
+++ b/client/src/components/cos/tabs/schedule/GlobalConfigControls.test.jsx
@@ -23,7 +23,8 @@ vi.mock('../../ReviewerPicker', () => ({
import GlobalConfigControls from './GlobalConfigControls';
const BASE_CONFIG = {
- type: 'daily',
+ type: 'cron',
+ cronExpression: '0 7 * * *',
enabled: true,
providerId: null,
model: null,
@@ -39,7 +40,6 @@ function renderControls({ taskMetadata, onUpdate = vi.fn(), taskType = 'feature-
config={{ ...BASE_CONFIG, taskMetadata, ...extraConfig }}
onUpdate={onUpdate}
onTrigger={() => {}}
- onReset={() => {}}
providers={[]}
apps={[]}
updating={false}
@@ -265,3 +265,30 @@ describe('GlobalConfigControls — file issues only', () => {
});
});
});
+
+describe('GlobalConfigControls — cadence + perpetual', () => {
+ const cadenceSelect = () => screen.getByLabelText('Interval Type');
+
+ it('offers exactly the two cadence variants', () => {
+ renderControls();
+ expect([...cadenceSelect().options].map((o) => o.value)).toEqual(['on-demand', 'cron']);
+ });
+
+ it('toggling Perpetual writes only the flag, leaving the cron cadence intact', async () => {
+ const onUpdate = renderControls({ config: { perpetual: false } });
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText('Enable perpetual drain'));
+ });
+ expect(onUpdate).toHaveBeenCalledWith('feature-ideas', { perpetual: true });
+ });
+
+ it('shows a recheck-cadence control only for an ON-DEMAND perpetual task', () => {
+ renderControls({ config: { type: 'on-demand', cronExpression: null, perpetual: true } });
+ expect(screen.getByText('Recheck Cadence')).toBeInTheDocument();
+
+ cleanup();
+ // A cron+perpetual task rechecks on its OWN expression, so it needs none.
+ renderControls({ config: { type: 'cron', cronExpression: '0 7 * * *', perpetual: true } });
+ expect(screen.queryByText('Recheck Cadence')).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/cos/tabs/schedule/IntervalBadge.jsx b/client/src/components/cos/tabs/schedule/IntervalBadge.jsx
index b684a75fff..4d6704f3ba 100644
--- a/client/src/components/cos/tabs/schedule/IntervalBadge.jsx
+++ b/client/src/components/cos/tabs/schedule/IntervalBadge.jsx
@@ -1,7 +1,11 @@
import { describeCron } from '../../../../utils/cronHelpers';
-import { badge, INTERVAL_LABELS, INTERVAL_BADGE_VARIANT } from './scheduleConstants';
+import { badge, INTERVAL_LABELS, INTERVAL_BADGE_VARIANT, PERPETUAL_BADGE_VARIANT, PERPETUAL_LABEL, PERPETUAL_DESCRIPTION } from './scheduleConstants';
-export default function IntervalBadge({ type, cronExpression }) {
+/**
+ * The cadence chip, plus a separate Perpetual chip when the task carries the
+ * drain flag — the two are orthogonal, so a Scheduled + Perpetual task shows both.
+ */
+export default function IntervalBadge({ type, cronExpression, perpetual }) {
const label = INTERVAL_LABELS[type] || type;
const cronDesc = type === 'cron' && cronExpression ? describeCron(cronExpression) : null;
const title = type === 'cron' && cronExpression
@@ -9,11 +13,21 @@ export default function IntervalBadge({ type, cronExpression }) {
: undefined;
return (
- <span
- className={`${badge(INTERVAL_BADGE_VARIANT[type] || 'success')} whitespace-nowrap shrink-0`}
- title={title}
- >
- {label}
- </span>
+ <>
+ <span
+ className={`${badge(INTERVAL_BADGE_VARIANT[type] || 'gray')} whitespace-nowrap shrink-0`}
+ title={title}
+ >
+ {label}
+ </span>
+ {perpetual && (
+ <span
+ className={`${badge(PERPETUAL_BADGE_VARIANT)} whitespace-nowrap shrink-0`}
+ title={PERPETUAL_DESCRIPTION}
+ >
+ {PERPETUAL_LABEL}
+ </span>
+ )}
+ </>
);
}
diff --git a/client/src/components/cos/tabs/schedule/TaskConfigDrawer.jsx b/client/src/components/cos/tabs/schedule/TaskConfigDrawer.jsx
index b827ef78ac..3ff076578f 100644
--- a/client/src/components/cos/tabs/schedule/TaskConfigDrawer.jsx
+++ b/client/src/components/cos/tabs/schedule/TaskConfigDrawer.jsx
@@ -27,7 +27,6 @@ export default function TaskConfigDrawer({
onClose,
onUpdate,
onTrigger,
- onReset,
providers,
activeProviderId,
apps,
@@ -88,7 +87,6 @@ export default function TaskConfigDrawer({
config={config}
onUpdate={onUpdate}
onTrigger={onTrigger}
- onReset={onReset}
category="appImprovement"
providers={providers}
activeProviderId={activeProviderId}
diff --git a/client/src/components/cos/tabs/schedule/TaskHeader.jsx b/client/src/components/cos/tabs/schedule/TaskHeader.jsx
index 8320e2b0ad..37d8652bf0 100644
--- a/client/src/components/cos/tabs/schedule/TaskHeader.jsx
+++ b/client/src/components/cos/tabs/schedule/TaskHeader.jsx
@@ -51,7 +51,7 @@ export default function TaskHeader({ taskType, config }) {
{stages.length}
</span>
)}
- <IntervalBadge type={config.type} cronExpression={config.cronExpression} />
+ <IntervalBadge type={config.type} cronExpression={config.cronExpression} perpetual={config.perpetual} />
</div>
</div>
{config.description && (
diff --git a/client/src/components/cos/tabs/schedule/scheduleConstants.js b/client/src/components/cos/tabs/schedule/scheduleConstants.js
index e7d8454c58..ec09e069b9 100644
--- a/client/src/components/cos/tabs/schedule/scheduleConstants.js
+++ b/client/src/components/cos/tabs/schedule/scheduleConstants.js
@@ -6,34 +6,28 @@ import {
import { timeUntil } from '../../../../utils/formatters';
import { describeCron } from '../../../../utils/cronHelpers';
+// The cadence model is two variants; `perpetual` is an orthogonal flag that
+// renders as its own badge alongside whichever one is selected.
export const INTERVAL_LABELS = {
- rotation: 'Rotation',
- daily: 'Daily',
- weekly: 'Weekly',
- once: 'Once',
'on-demand': 'On Demand',
- custom: 'Custom',
- cron: 'Cron',
- perpetual: 'Perpetual'
+ cron: 'Scheduled'
};
export const INTERVAL_DESCRIPTIONS = {
- rotation: 'Runs as part of normal task rotation',
- daily: 'Runs once per day',
- weekly: 'Runs once per week',
- once: 'Runs once then stops',
'on-demand': 'Only runs when manually triggered',
- custom: 'Custom interval',
- cron: 'Cron expression schedule',
- perpetual: 'Drains actionable work back-to-back until none remains, then rechecks on a cadence'
+ cron: 'Runs on a cron schedule'
};
-// `cyan` is kept as a raw Tailwind hue (not a port-* token) on purpose: this is
-// a fixed 7-tone badge palette differentiating mutually-exclusive interval
-// variants (INTERVAL_BADGE_VARIANT below); every other tone here already maps
-// onto a port-* token ('accent' covers the blue/info role), so collapsing
-// cyan onto 'accent' too would make 'cron' badges visually indistinguishable
-// from 'daily' badges. See the #1909/#1924 category-color-enum caution.
+export const PERPETUAL_LABEL = 'Perpetual';
+export const PERPETUAL_DESCRIPTION =
+ 'Drains actionable work back-to-back until none remains, then rechecks on a cadence';
+
+// `cyan` is kept as a raw Tailwind hue (not a port-* token) on purpose: it is
+// the 'cron' cadence tone in INTERVAL_BADGE_VARIANT below, and every other tone
+// here already maps onto a port-* token ('accent' covers the blue/info role),
+// so collapsing cyan onto 'accent' would make a Scheduled badge visually
+// indistinguishable from the other accent-toned chips on the same card. See the
+// #1909/#1924 category-color-enum caution.
const BADGE_COLORS = {
accent: 'bg-port-accent/15 text-port-accent border-port-accent/30',
purple: 'bg-port-accent-2/15 text-port-accent-2 border-port-accent-2/30',
@@ -125,14 +119,13 @@ export const triggerButtonClass = (disabled) =>
`flex items-center gap-1 px-3 py-1.5 text-sm rounded transition-colors ${disabled ? 'bg-port-border/30 text-gray-500 cursor-not-allowed' : 'bg-port-accent/20 hover:bg-port-accent/30 text-port-accent'}`;
export const INTERVAL_BADGE_VARIANT = {
- daily: 'accent',
- weekly: 'purple',
- once: 'warning',
'on-demand': 'gray',
cron: 'cyan',
- perpetual: 'success',
};
+// Perpetual is a separate badge, not a cadence variant.
+export const PERPETUAL_BADGE_VARIANT = 'success';
+
// --- Status grouping -------------------------------------------------------
// A task falls into exactly one status group, used for the status dot, grid
// ordering, and the status filters. Order here is the grid sort order.
@@ -140,18 +133,16 @@ export const STATUS_GROUPS = {
active: { label: 'Active', dot: 'bg-port-success', order: 0 },
'on-demand': { label: 'On-Demand', dot: 'bg-gray-400', order: 1 },
waiting: { label: 'Waiting', dot: 'bg-port-warning', order: 2 },
- completed: { label: 'Completed', dot: 'bg-port-accent', order: 3 },
- disabled: { label: 'Disabled', dot: 'bg-gray-600', order: 4 },
+ disabled: { label: 'Disabled', dot: 'bg-gray-600', order: 3 },
};
// Classify a task config into one status group (mutually exclusive).
-// Disabled wins over everything; then dependency-wait; then a one-shot that
-// already ran (won't run again until reset — not "active"); then on-demand type.
+// Disabled wins over everything; then dependency-wait; then on-demand type — a
+// perpetual on-demand task is "active" because its drain runs unattended.
export function getTaskStatusGroup(config) {
if (!config?.enabled) return 'disabled';
if (config.status?.reason === 'waiting-on-dependencies') return 'waiting';
- if (config.type === 'once' && config.status?.reason === 'once-completed') return 'completed';
- if (config.type === 'on-demand') return 'on-demand';
+ if (config.type === 'on-demand' && !config.perpetual) return 'on-demand';
return 'active';
}
@@ -177,7 +168,6 @@ export function coverageTone(enabled, total) {
export function describeNextRun(config) {
const group = getTaskStatusGroup(config);
if (group === 'disabled') return { text: 'Paused', tone: 'text-gray-500' };
- if (group === 'completed') return { text: 'Completed — reset to run again', tone: 'text-gray-400' };
if (group === 'waiting') {
const deps = config.status?.pendingDeps?.join(', ');
return {
@@ -188,10 +178,10 @@ export function describeNextRun(config) {
};
}
if (group === 'on-demand') return { text: 'Manual trigger only', tone: 'text-gray-400' };
- if (config.type === 'perpetual') {
+ if (config.perpetual) {
// Prefer the per-app park aggregate — claim-issue/claim-work park per-app, so
// the global status.reason reads 'perpetual-drain' even when all apps are parked.
- const p = config.perpetual;
+ const p = config.perpetualStatus;
if (p && (p.trackedAppCount > 0 || p.globalParked)) {
// "Parked" only when there's nothing left draining: a global park, or every
// tracked app parked. A partial park (some apps still have work) is draining.
@@ -236,7 +226,6 @@ export const TASK_FILTERS = [
{ id: 'active', label: 'Active', emptyMessage: 'No active tasks.', match: ([, config]) => getTaskStatusGroup(config) === 'active' },
{ id: 'on-demand', label: 'On-Demand', emptyMessage: 'No on-demand tasks.', match: ([, config]) => getTaskStatusGroup(config) === 'on-demand' },
{ id: 'waiting', label: 'Waiting', emptyMessage: 'No tasks waiting on dependencies.', match: ([, config]) => getTaskStatusGroup(config) === 'waiting' },
- { id: 'completed', label: 'Completed', emptyMessage: 'No completed tasks.', match: ([, config]) => getTaskStatusGroup(config) === 'completed' },
{ id: 'disabled', label: 'Disabled', emptyMessage: 'No disabled tasks.', match: ([, config]) => getTaskStatusGroup(config) === 'disabled' },
];
export const DEFAULT_FILTER_ID = TASK_FILTERS[0].id;
diff --git a/client/src/components/cos/tabs/schedule/scheduleConstants.test.js b/client/src/components/cos/tabs/schedule/scheduleConstants.test.js
index 90a84ac6c1..1a8f801559 100644
--- a/client/src/components/cos/tabs/schedule/scheduleConstants.test.js
+++ b/client/src/components/cos/tabs/schedule/scheduleConstants.test.js
@@ -138,16 +138,17 @@ describe('getTaskStatusGroup', () => {
expect(getTaskStatusGroup({ enabled: true, type: 'daily' })).toBe('active');
});
- it('classifies a completed one-shot task as completed, not active', () => {
- expect(getTaskStatusGroup({ enabled: true, type: 'once', status: { reason: 'once-completed' } })).toBe('completed');
+ it('keeps a scheduled task active', () => {
+ expect(getTaskStatusGroup({ enabled: true, type: 'cron', status: { nextRunAt: '2999-01-01T00:00:00Z' } })).toBe('active');
});
- it('keeps a not-yet-run one-shot task active', () => {
- expect(getTaskStatusGroup({ enabled: true, type: 'once', status: { nextRunAt: '2999-01-01T00:00:00Z' } })).toBe('active');
+ it('classifies a perpetual on-demand task as active — its drain runs unattended', () => {
+ expect(getTaskStatusGroup({ enabled: true, type: 'on-demand', perpetual: true })).toBe('active');
+ expect(getTaskStatusGroup({ enabled: true, type: 'on-demand' })).toBe('on-demand');
});
- it('disabled wins over a completed one-shot', () => {
- expect(getTaskStatusGroup({ enabled: false, type: 'once', status: { reason: 'once-completed' } })).toBe('disabled');
+ it('disabled wins over a perpetual drain', () => {
+ expect(getTaskStatusGroup({ enabled: false, type: 'on-demand', perpetual: true })).toBe('disabled');
});
it('disabled wins over waiting', () => {
@@ -157,9 +158,9 @@ describe('getTaskStatusGroup', () => {
describe('taskSortKey', () => {
it('orders active before on-demand before waiting before disabled', () => {
- const active = taskSortKey('a', { enabled: true, type: 'daily' });
+ const active = taskSortKey('a', { enabled: true, type: 'cron' });
const onDemand = taskSortKey('b', { enabled: true, type: 'on-demand' });
- const waiting = taskSortKey('c', { enabled: true, type: 'daily', status: { reason: 'waiting-on-dependencies' } });
+ const waiting = taskSortKey('c', { enabled: true, type: 'cron', status: { reason: 'waiting-on-dependencies' } });
const disabled = taskSortKey('d', { enabled: false });
expect(active.order).toBeLessThan(onDemand.order);
expect(onDemand.order).toBeLessThan(waiting.order);
@@ -167,8 +168,8 @@ describe('taskSortKey', () => {
});
it('sorts active tasks by soonest next run, missing runs last', () => {
- const soon = taskSortKey('a', { enabled: true, type: 'daily', status: { nextRunAt: '2999-01-01T00:00:00Z' } });
- const later = taskSortKey('b', { enabled: true, type: 'daily', status: { nextRunAt: '2999-06-01T00:00:00Z' } });
+ const soon = taskSortKey('a', { enabled: true, type: 'cron', status: { nextRunAt: '2999-01-01T00:00:00Z' } });
+ const later = taskSortKey('b', { enabled: true, type: 'cron', status: { nextRunAt: '2999-06-01T00:00:00Z' } });
const none = taskSortKey('c', { enabled: true, type: 'daily' });
expect(soon.next).toBeLessThan(later.next);
expect(later.next).toBeLessThan(none.next);
@@ -199,11 +200,6 @@ describe('describeNextRun', () => {
expect(describeNextRun({ enabled: true, type: 'on-demand' }).text).toBe('Manual trigger only');
});
- it('reports a completed one-shot as completed with a reset hint', () => {
- const out = describeNextRun({ enabled: true, type: 'once', status: { reason: 'once-completed' } });
- expect(out.text).toMatch(/completed/i);
- });
-
it('reports the dependency list with a warn flag when waiting', () => {
const out = describeNextRun({ enabled: true, status: { reason: 'waiting-on-dependencies', pendingDeps: ['build', 'lint'] } });
expect(out.text).toBe('waiting on build, lint');
@@ -212,7 +208,7 @@ describe('describeNextRun', () => {
});
it('reports a relative countdown for a scheduled task with a next run', () => {
- expect(describeNextRun({ enabled: true, type: 'daily', status: { nextRunAt: '2999-01-01T00:00:00Z' } }).text).toMatch(/^in /);
+ expect(describeNextRun({ enabled: true, type: 'cron', status: { nextRunAt: '2999-01-01T00:00:00Z' } }).text).toMatch(/^in /);
});
it('reports a relative countdown with cron description for a scheduled cron task with next run', () => {
@@ -222,12 +218,12 @@ describe('describeNextRun', () => {
});
it('falls back to an interval-label pending string when no next run is known', () => {
- expect(describeNextRun({ enabled: true, type: 'daily' }).text).toBe('Daily — pending');
+ expect(describeNextRun({ enabled: true, type: 'cron' }).text).toBe('Scheduled — pending');
expect(describeNextRun({ enabled: true, type: 'cron', cronExpression: '0 6 * * 1-5' }).text).toBe('Weekdays at 06:00 — pending');
});
it('reports a draining perpetual task', () => {
- const out = describeNextRun({ enabled: true, type: 'perpetual', status: { reason: 'perpetual-drain' } });
+ const out = describeNextRun({ enabled: true, type: 'on-demand', perpetual: true, status: { reason: 'perpetual-drain' } });
expect(out.text).toMatch(/draining/i);
expect(out.tone).toBe('text-port-success');
});
@@ -235,7 +231,9 @@ describe('describeNextRun', () => {
it('reports a parked perpetual task with its recheck countdown and reason', () => {
const out = describeNextRun({
enabled: true,
- type: 'perpetual',
+ type: 'cron',
+ perpetual: true,
+ cronExpression: '0 3 * * *',
status: { reason: 'perpetual-parked', nextRunAt: '2999-01-01T00:00:00Z', parkReason: 'no-actionable-issues' }
});
expect(out.text).toMatch(/parked · rechecks/);
@@ -246,9 +244,10 @@ describe('describeNextRun', () => {
// Global status reads drain, but all tracked apps are parked — aggregate wins.
const out = describeNextRun({
enabled: true,
- type: 'perpetual',
+ type: 'on-demand',
+ perpetual: true,
status: { reason: 'perpetual-drain' },
- perpetual: { parkedAppCount: 2, trackedAppCount: 2, globalParked: false, nextRecheckAt: '2999-01-01T00:00:00Z', parkReason: 'no-actionable-issues' }
+ perpetualStatus: { parkedAppCount: 2, trackedAppCount: 2, globalParked: false, nextRecheckAt: '2999-01-01T00:00:00Z', parkReason: 'no-actionable-issues' }
});
expect(out.text).toMatch(/2 app\(s\) parked · rechecks/);
expect(out.title).toContain('no-actionable-issues');
@@ -257,9 +256,10 @@ describe('describeNextRun', () => {
it('shows draining when some apps still have work in the aggregate', () => {
const out = describeNextRun({
enabled: true,
- type: 'perpetual',
+ type: 'on-demand',
+ perpetual: true,
status: { reason: 'perpetual-drain' },
- perpetual: { parkedAppCount: 1, trackedAppCount: 3, globalParked: false, nextRecheckAt: null, parkReason: null }
+ perpetualStatus: { parkedAppCount: 1, trackedAppCount: 3, globalParked: false, nextRecheckAt: null, parkReason: null }
});
expect(out.text).toMatch(/draining/);
});
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index 044d691282..f2d62f247a 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -293,11 +293,6 @@ export const triggerCosOnDemandTask = (taskType, appId = null, options = {}) =>
body: JSON.stringify({ taskType, appId }),
...options
});
-export const resetCosTaskHistory = (taskType, appId = null, options = {}) => request('/cos/schedule/reset', {
- method: 'POST',
- body: JSON.stringify({ taskType, appId }),
- ...options
-});
// Autonomous Jobs
export const getCosJobs = (options = {}) => request('/cos/jobs', options);
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 21a067fe00..ce7293514e 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -23,7 +23,7 @@ grep -i "what you want to do" client/src/utils/README.md
| Module | Purpose |
|---|---|
| `formatters` | Date/time/duration/byte/word formatters (`clamp`, `formatBytes`, `formatDownloadGb` (decimal-GB model download size, "~29 GB"), `formatCompactCount`, `formatCompactCountOrDash` (same, but an ABSENT count renders "—" rather than "0"), `timeAgo`, `formatAgeDays` (age in whole DAYS — "412 days ago" — where `timeAgo` would collapse to "1y ago"; model-download lists), `localDateKey` (browser-local `YYYY-MM-DD`), `shiftISODate` (DST-safe calendar-day shifts), `formatTimecode`, `formatDurationMs`, `formatDateShort`, `formatContextTokens` (suffix-less context length, "4K"), `throughputLabel` (a measured model's speed as one label — tok/s where the runtime reported token counts, `~` prefixed when frame-counted, else chars/s; never both), `parseTimeoutMs`, `formatCooldown`, `recommendedRamGb`, `nameFromImageFilename`, `formatUsd` — one USD renderer (`signed` puts the minus outside the `$`; `trimWhole` drops `.00` on a typed round price) — `formatWeight` / `formatPercent` — round unit-converted floats (`170.35000000000002` → `170.4 lbs`) so raw binary precision never reaches a tile — `middleTruncate` — clip a long string from the MIDDLE so its distinguishing tail survives, where CSS `line-clamp`/`text-overflow` always eats the end — …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. **Never write `new Date(x).toLocaleDateString()` inline** — pick the helper for the shape you want: `formatDateNumeric` ("3/5/2026", compact cells), `formatDateShort` ("Mar 5, 2026"), `formatDate` ("March 5, 2026"), `formatDateFull` ("Saturday, March 5, 2026"), `formatWeekdayDate` ("Monday, Mar 5", `{ weekday, year }`), `formatMonthDay` ("Mar 5"), `formatMonthYear` ("March 2026"), `formatWeekdayShort` ("Mon"), `formatWeekdayTime` ("Mon, 7:00 AM"), `formatTimeOfDay` ("1:30 PM"), `formatTimeOfDaySeconds` ("1:30:45 PM", log/queue rows), `formatClockTime` ("02:30:45 PM"; `{ seconds, hour12, timeZone }`), `formatDateTime`. `formatHourOfDay` renders a bare hour-of-day number (0-23) as a 12-hour label in one of four styles (`long` "3 PM", `compact` "3PM", `tiny` "3p", `lower` "3pm") — the canonical home for what five components each hand-rolled, so the same 3pm no longer renders four ways across screens. Date display helpers anchor a bare `YYYY-MM-DD` at LOCAL midnight (a naive `new Date('2026-03-05')` is UTC midnight and renders as the previous day west of Greenwich) and take a fallback instead of rendering the literal "Invalid Date". |
-| `cronHelpers` | Cron preset list, friendly cron parsing/building, anchored recurrence parsing/building/description, `isCronExpression` detection, `describeCron` human-readable rendering, and `JOB_INTERVAL_OPTIONS` — the interval-mode cadences for autonomous jobs, mirroring the server's `INTERVAL_OPTIONS`. Import it rather than re-declaring the list in a scheduling component. |
+| `cronHelpers` | Cron preset list, friendly cron parsing/building, anchored recurrence parsing/building/description, `isCronExpression` detection, `describeCron` human-readable rendering, `cronFromIntervalMs` numeric-interval → expression conversion (mirrors the server helper), and `JOB_INTERVAL_OPTIONS` — the interval-mode cadences for autonomous jobs, mirroring the server's `INTERVAL_OPTIONS`. Import it rather than re-declaring the list in a scheduling component. |
| `markdownText` | `markdownToPlainText(md)` — flatten markdown source to one plain-text string for a clamped preview: strips heading/list/blockquote/fence markers, unwraps emphasis, inline code and links, images → `[alt]`, collapses blank-line runs. Use whenever a card previews arbitrary agent-authored markdown — `line-clamp-N` does not clamp a subtree of block elements, and foreign `##` headings would otherwise join the page's heading outline. Underscore emphasis is word-boundary gated and `__…__` needs interior whitespace, so stack frames and user-agent strings (`10_15_7`, `__init__`) are never silently rewritten. `dropsMarkupWhenFlattened(md)` — did the flatten lose actual markup, as opposed to only normalizing whitespace? Gates a "Show more" disclosure so a short-but-lossy body stays reachable without putting a toggle on every body that merely lost a trailing newline. |
| `timeWindow` | Time-of-day window math (`isInTimeWindow`, `timeStringToMinutes`) and morning-layout auto-switch helpers (`pickActiveLayoutId`, `recordManualLayoutPick`). |
| `timezone` | Timezone day-key helpers (`dayKeyInTimezone`, `todayKeyInTimezone`) — browser mirror of the server's `todayInTimezone`, so date-scoped POST surfaces derive "today" in the user's configured timezone and agree with the server (#2681). |
diff --git a/client/src/utils/cronHelpers.js b/client/src/utils/cronHelpers.js
index f1ba4b6866..1acee43a01 100644
--- a/client/src/utils/cronHelpers.js
+++ b/client/src/utils/cronHelpers.js
@@ -22,6 +22,38 @@ const DOW_MAP = { '0': 'Sun', '1': 'Mon', '2': 'Tue', '3': 'Wed', '4': 'Thu', '5
export const DEFAULT_TIME = '07:00';
export const DEFAULT_CRON = '0 7 * * *';
+// Weekly default for a Monday-morning cadence (mirrors the server's
+// DEFAULT_WEEKLY_CRON), so a task converted from a weekly cadence never lands
+// on a weekend.
+export const DEFAULT_WEEKLY_CRON = '0 7 * * 1';
+
+const MINUTE_MS = 60 * 1000;
+const HOUR_MS = 60 * MINUTE_MS;
+const DAY_MS = 24 * HOUR_MS;
+const WEEK_MS = 7 * DAY_MS;
+
+/**
+ * Approximate a numeric interval as a 5-field cron expression. Mirrors the
+ * server's `cronFromIntervalMs` (server/services/taskScheduleConstants.js) so a
+ * numeric cadence picker and the server-side migration derive the SAME
+ * expression — keep the two in lockstep.
+ */
+export function cronFromIntervalMs(intervalMs) {
+ const ms = Number(intervalMs);
+ if (!Number.isFinite(ms) || ms <= 0) return DEFAULT_CRON;
+ if (ms === WEEK_MS) return DEFAULT_WEEKLY_CRON;
+ if (ms >= DAY_MS) return DEFAULT_CRON;
+ if (ms >= HOUR_MS) {
+ const hours = Math.round(ms / HOUR_MS);
+ if (hours <= 1) return '0 * * * *';
+ // Only an even divisor of 24 lays out evenly across a day.
+ const step = [2, 3, 4, 6, 8, 12].find((h) => h >= hours) || 12;
+ return `0 */${step} * * *`;
+ }
+ const minutes = Math.min(59, Math.max(1, Math.round(ms / MINUTE_MS)));
+ return `*/${minutes} * * * *`;
+}
+
// Sunday-first, matching cron's day-of-week numbering (0 = Sunday).
export const WEEKDAYS = [
{ value: 0, short: 'S', label: 'Sun' },
diff --git a/docs/API.md b/docs/API.md
index 9ee52528cf..73dfef6915 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -252,11 +252,11 @@ Context tools remain read-only. Semantic reads and writes are independent, defau
|--------|----------|-------------|
| GET | `/cos/schedule` | Get full task schedule status |
| GET | `/cos/upcoming` | Get upcoming scheduled tasks preview |
-| GET | `/cos/schedule/interval-types` | Get available interval types and descriptions |
+| GET | `/cos/schedule/interval-types` | Get the two cadence types (`on-demand`, `cron`) and their descriptions, plus the `perpetual` flag description |
| GET | `/cos/schedule/due` | List all tasks due to run |
| GET | `/cos/schedule/due/:appId` | List tasks due for specific app |
| GET | `/cos/schedule/task/:taskType` | Get interval and schedule settings for a task type |
-| PUT | `/cos/schedule/task/:taskType` | Update schedule settings for a task type |
+| PUT | `/cos/schedule/task/:taskType` | Update schedule settings for a task type (`type`: `on-demand` \| `cron`; `cronExpression`: 5-field or null; `perpetual`: boolean drain flag, orthogonal to `type`) |
| POST | `/cos/schedule/trigger` | Trigger an on-demand task run |
| GET | `/cos/schedule/on-demand` | List pending on-demand task requests |
| DELETE | `/cos/schedule/on-demand/:requestId` | Clear a pending on-demand request |
diff --git a/scripts/migrations/335-schedule-interval-types.js b/scripts/migrations/335-schedule-interval-types.js
new file mode 100644
index 0000000000..2c92b16073
--- /dev/null
+++ b/scripts/migrations/335-schedule-interval-types.js
@@ -0,0 +1,120 @@
+/**
+ * Collapse the seven scheduled-task interval types onto the two-variant cadence
+ * model, with `perpetual` as an orthogonal boolean flag.
+ *
+ * once → on-demand (manual trigger only; no auto-run, no reset loop)
+ * rotation → cron '0 7 * * *' (un-shipped in defaults; a conservative
+ * daily slot, never an unbounded drain)
+ * daily → cron '0 7 * * *'
+ * weekly → cron '0 7 * * 1' (Monday, so work never lands on a weekend)
+ * custom → cron derived from intervalMs
+ * perpetual → on-demand + perpetual: true (recheck cadence retained)
+ * on-demand → on-demand (branch-reconcile / issue-reconcile gain perpetual)
+ *
+ * Applies to both schedule-file locations and to the per-app cadence overrides
+ * in apps.json. Idempotent: a record already on the new model is left alone,
+ * and a raw 5-field cron override passes through untouched. `enabled`,
+ * `weekdaysOnly`, and every other field are preserved.
+ */
+
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import {
+ INTERVAL_TYPES,
+ decodeIntervalType,
+ isCronExpression,
+ isReconcileDrainTaskType,
+ normalizeIntervalConfig,
+} from '../../server/services/taskScheduleConstants.js';
+
+const SCHEDULE_PATHS = [
+ join('data', 'cos', 'task-schedule.json'),
+ join('data', 'task-schedule.json'),
+];
+const APPS_PATH = join('data', 'apps.json');
+
+async function readJson(path) {
+ const raw = await readFile(path, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) return null;
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return null;
+ }
+}
+
+const writeJson = (path, value) => writeFile(path, `${JSON.stringify(value, null, 2)}\n`);
+
+/** Migrate one task config in place. Returns true when it changed. */
+export function migrateTaskConfig(taskType, config) {
+ if (!config || typeof config !== 'object') return false;
+ let changed = normalizeIntervalConfig(config);
+ // The reconcile drains shipped as on-demand while their drain behavior was
+ // hardcoded by task name. That special case is gone, so the flag has to be
+ // written onto the record for them to keep draining.
+ if (isReconcileDrainTaskType(taskType) && config.perpetual !== true) {
+ config.perpetual = true;
+ changed = true;
+ }
+ return changed;
+}
+
+/**
+ * Migrate one per-app override in place. Per-app rows carry the cadence as a
+ * bare string (`interval`), so a retired name becomes either 'on-demand' or a
+ * cron expression. Returns true when it changed.
+ */
+export function migrateAppOverride(override) {
+ if (!override || typeof override !== 'object') return false;
+ const { interval } = override;
+ if (typeof interval !== 'string' || isCronExpression(interval)) return false;
+ const decoded = decodeIntervalType(interval, { intervalMs: override.intervalMs });
+ const next = decoded.type === INTERVAL_TYPES.CRON ? decoded.cronExpression : INTERVAL_TYPES.ON_DEMAND;
+ if (next === interval) return false;
+ override.interval = next;
+ return true;
+}
+
+export default {
+ async up({ rootDir }) {
+ let updated = 0;
+
+ for (const relPath of SCHEDULE_PATHS) {
+ const fullPath = join(rootDir, relPath);
+ const schedule = await readJson(fullPath);
+ const tasks = schedule?.tasks;
+ if (!tasks || typeof tasks !== 'object') continue;
+
+ let migrated = 0;
+ for (const [taskType, config] of Object.entries(tasks)) {
+ if (migrateTaskConfig(taskType, config)) migrated += 1;
+ }
+ if (!migrated) continue;
+ await writeJson(fullPath, schedule);
+ updated += migrated;
+ console.log(`📅 ${relPath}: migrated ${migrated} task cadence(s) to on-demand/cron + perpetual flag`);
+ }
+
+ // apps.json stores `apps` as an object keyed by app id.
+ const appsPath = join(rootDir, APPS_PATH);
+ const apps = await readJson(appsPath);
+ if (apps?.apps && typeof apps.apps === 'object') {
+ let migrated = 0;
+ for (const app of Object.values(apps.apps)) {
+ for (const override of Object.values(app?.taskTypeOverrides || {})) {
+ if (migrateAppOverride(override)) migrated += 1;
+ }
+ }
+ if (migrated) {
+ await writeJson(appsPath, apps);
+ updated += migrated;
+ console.log(`📅 ${APPS_PATH}: migrated ${migrated} per-app cadence override(s)`);
+ }
+ }
+
+ return { updated };
+ },
+};
diff --git a/scripts/migrations/335-schedule-interval-types.test.js b/scripts/migrations/335-schedule-interval-types.test.js
new file mode 100644
index 0000000000..80f501b313
--- /dev/null
+++ b/scripts/migrations/335-schedule-interval-types.test.js
@@ -0,0 +1,124 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import migration from './335-schedule-interval-types.js';
+
+describe('migration 335 — collapse interval types to on-demand/cron + perpetual flag', () => {
+ let rootDir;
+ let schedulePath;
+ let appsPath;
+
+ const writeSchedule = (tasks) => {
+ mkdirSync(join(rootDir, 'data', 'cos'), { recursive: true });
+ writeFileSync(schedulePath, `${JSON.stringify({ version: 2, tasks, executions: {} }, null, 2)}\n`);
+ };
+ const readTasks = () => JSON.parse(readFileSync(schedulePath, 'utf8')).tasks;
+
+ const writeApps = (apps) => {
+ mkdirSync(join(rootDir, 'data'), { recursive: true });
+ writeFileSync(appsPath, `${JSON.stringify({ apps }, null, 2)}\n`);
+ };
+ const readApps = () => JSON.parse(readFileSync(appsPath, 'utf8')).apps;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-335-'));
+ schedulePath = join(rootDir, 'data', 'cos', 'task-schedule.json');
+ appsPath = join(rootDir, 'data', 'apps.json');
+ });
+
+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+
+ it('is a no-op on a fresh install with no schedule or apps file', async () => {
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0 });
+ });
+
+ it('maps every retired cadence onto the two-variant model', async () => {
+ writeSchedule({
+ 'a-once': { type: 'once', enabled: true },
+ 'a-rotation': { type: 'rotation', enabled: true },
+ 'a-daily': { type: 'daily', enabled: true },
+ 'a-weekly': { type: 'weekly', enabled: true },
+ 'a-custom': { type: 'custom', intervalMs: 1_800_000, enabled: true },
+ 'a-perpetual': { type: 'perpetual', recheckCron: '0 3 * * *', enabled: true },
+ });
+
+ await migration.up({ rootDir });
+ const tasks = readTasks();
+
+ expect(tasks['a-once']).toMatchObject({ type: 'on-demand', perpetual: false, enabled: true });
+ expect(tasks['a-rotation']).toMatchObject({ type: 'cron', cronExpression: '0 7 * * *' });
+ expect(tasks['a-daily']).toMatchObject({ type: 'cron', cronExpression: '0 7 * * *' });
+ expect(tasks['a-weekly']).toMatchObject({ type: 'cron', cronExpression: '0 7 * * 1' });
+ expect(tasks['a-custom']).toMatchObject({ type: 'cron', cronExpression: '*/30 * * * *' });
+ // The recheck cadence survives the type collapse.
+ expect(tasks['a-perpetual']).toMatchObject({ type: 'on-demand', perpetual: true, recheckCron: '0 3 * * *' });
+ });
+
+ it('preserves enabled/weekdaysOnly and an already-cron expression', async () => {
+ writeSchedule({
+ paused: { type: 'weekly', enabled: false, weekdaysOnly: true },
+ pinned: { type: 'cron', cronExpression: '30 8 * * 2', enabled: true, weekdaysOnly: true },
+ });
+
+ await migration.up({ rootDir });
+ const tasks = readTasks();
+
+ expect(tasks.paused).toMatchObject({ enabled: false, weekdaysOnly: true, type: 'cron', cronExpression: '0 7 * * 1' });
+ expect(tasks.pinned).toMatchObject({ enabled: true, weekdaysOnly: true, type: 'cron', cronExpression: '30 8 * * 2' });
+ });
+
+ it('gives the reconcile drains the perpetual flag their hardcoded behavior relied on', async () => {
+ writeSchedule({
+ 'branch-reconcile': { type: 'on-demand', enabled: true, recheckCron: '0 3 * * *' },
+ 'issue-reconcile': { type: 'on-demand', enabled: true },
+ 'claim-issue': { type: 'on-demand', enabled: true },
+ });
+
+ await migration.up({ rootDir });
+ const tasks = readTasks();
+
+ expect(tasks['branch-reconcile']).toMatchObject({ type: 'on-demand', perpetual: true });
+ expect(tasks['issue-reconcile']).toMatchObject({ type: 'on-demand', perpetual: true });
+ // Every OTHER on-demand task stays a single-run manual action.
+ expect(tasks['claim-issue']).toMatchObject({ type: 'on-demand', perpetual: false });
+ });
+
+ it('rewrites per-app cadence overrides and leaves a raw cron string alone', async () => {
+ writeApps({
+ 'app-1': {
+ id: 'app-1',
+ taskTypeOverrides: {
+ security: { enabled: true, interval: 'weekly' },
+ 'layered-intelligence': { enabled: true, interval: 'custom', intervalMs: 900_000 },
+ 'ui-bugs': { enabled: true, interval: 'once' },
+ typing: { enabled: true, interval: '15 6 * * 3' },
+ inherited: { enabled: true, interval: null },
+ },
+ },
+ });
+
+ await migration.up({ rootDir });
+ const overrides = readApps()['app-1'].taskTypeOverrides;
+
+ expect(overrides.security.interval).toBe('0 7 * * 1');
+ expect(overrides['layered-intelligence'].interval).toBe('*/15 * * * *');
+ expect(overrides['ui-bugs'].interval).toBe('on-demand');
+ expect(overrides.typing.interval).toBe('15 6 * * 3');
+ expect(overrides.inherited.interval).toBeNull();
+ });
+
+ it('is idempotent — a second run changes nothing', async () => {
+ writeSchedule({ 'a-weekly': { type: 'weekly', enabled: true }, 'branch-reconcile': { type: 'on-demand', enabled: true } });
+ writeApps({ 'app-1': { id: 'app-1', taskTypeOverrides: { security: { enabled: true, interval: 'daily' } } } });
+
+ const first = await migration.up({ rootDir });
+ expect(first.updated).toBeGreaterThan(0);
+ const afterFirst = readFileSync(schedulePath, 'utf8');
+ const appsAfterFirst = readFileSync(appsPath, 'utf8');
+
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0 });
+ expect(readFileSync(schedulePath, 'utf8')).toBe(afterFirst);
+ expect(readFileSync(appsPath, 'utf8')).toBe(appsAfterFirst);
+ });
+});
diff --git a/server/routes/apps/taskTypes.js b/server/routes/apps/taskTypes.js
index e3604189f1..5e9b5aa8f4 100644
--- a/server/routes/apps/taskTypes.js
+++ b/server/routes/apps/taskTypes.js
@@ -23,6 +23,7 @@ import { sanitizeTaskMetadata, ISSUE_AUTHOR_FILTERS } from '../../lib/validation
import { listWorkItems } from '../../services/workItems.js';
import { resolveClaimWorkMetadata, resolveClaimAuthorFilter } from '../../services/cosTaskGenerator.js';
import { parseCronToNextRun } from '../../services/eventScheduler.js';
+import { INTERVAL_TYPES, decodeIntervalType, isCronExpression, isKnownIntervalType } from '../../services/taskScheduleConstants.js';
import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
import { SELF_IMPROVEMENT_TASK_TYPES } from '../../services/taskScheduleRegistry.js';
import { summarizeOutcomeStats, computePostApprovalCompletion, computeProposalOutcomeMetrics, computeApprovalFunnel } from '../../services/layeredIntelligence.js';
@@ -208,7 +209,8 @@ router.put('/:id/task-types/all', loadApp, asyncHandler(async (req, res) => {
// PUT /api/apps/:id/task-types/:taskType - Update a task type override for an app
router.put('/:id/task-types/:taskType', asyncHandler(async (req, res) => {
- const { enabled, interval, intervalMs, providerId, model, taskMetadata } = req.body;
+ const { enabled, intervalMs, providerId, model, taskMetadata } = req.body;
+ let { interval } = req.body;
if (!SELF_IMPROVEMENT_TASK_TYPES.includes(req.params.taskType)) {
throw new ServerError(`Unknown task type '${req.params.taskType}'`, { status: 400, code: 'INVALID_TASK_TYPE' });
}
@@ -251,23 +253,31 @@ router.put('/:id/task-types/:taskType', asyncHandler(async (req, res) => {
}
}
- // Validate interval against allowed values (also accepts 5-field cron expressions)
+ // A per-app cadence override is 'on-demand', a 5-field cron expression, or
+ // null (inherit the global). A retired name (rotation/daily/weekly/once/
+ // custom) from an older client is rewritten onto that model rather than
+ // rejected, so an install upgrading mid-session keeps working.
if (interval !== undefined) {
- // 'custom' pairs with a numeric intervalMs (handler-backed tasks with a
- // sub-daily per-app cadence); the scheduler's CUSTOM branch reads intervalMs.
- const allowedIntervals = ['rotation', 'daily', 'weekly', 'once', 'on-demand', 'custom'];
- if (interval !== null && typeof interval === 'string') {
- const isCron = interval.trim().split(/\s+/).length === 5;
- if (!isCron && !allowedIntervals.includes(interval)) {
- throw new ServerError('interval must be one of rotation|daily|weekly|once|on-demand|custom, a cron expression, or null', { status: 400, code: 'VALIDATION_ERROR' });
- }
- if (isCron) {
+ if (interval !== null && typeof interval !== 'string') {
+ throw new ServerError('interval must be a string or null', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (typeof interval === 'string') {
+ if (isCronExpression(interval)) {
// Validate syntax and field ranges (parseCronToNextRun throws on invalid expressions)
// Note: null return means no match within search window (e.g. leap day) -- not invalid
- parseCronToNextRun(interval, new Date(), 'UTC');
+ parseCronToNextRun(interval.trim(), new Date(), 'UTC');
+ interval = interval.trim();
+ } else {
+ // An unrecognized string is rejected rather than decoded — silently
+ // reading it as 'on-demand' would stop the task running for this app.
+ if (!isKnownIntervalType(interval)) {
+ throw new ServerError(`interval must be '${INTERVAL_TYPES.ON_DEMAND}', a 5-field cron expression, or null`, { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const decoded = decodeIntervalType(interval, { intervalMs });
+ interval = decoded.type === INTERVAL_TYPES.CRON
+ ? decoded.cronExpression
+ : INTERVAL_TYPES.ON_DEMAND;
}
- } else if (interval !== null) {
- throw new ServerError('interval must be a string or null', { status: 400, code: 'VALIDATION_ERROR' });
}
}
diff --git a/server/routes/cosScheduleRoutes.js b/server/routes/cosScheduleRoutes.js
index 7018064aea..e3075e2ada 100644
--- a/server/routes/cosScheduleRoutes.js
+++ b/server/routes/cosScheduleRoutes.js
@@ -10,6 +10,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { sanitizeTaskMetadata, taskDataInputsSchema, validateRequest, parsePagination } from '../lib/validation.js';
import { promptSourceSchema, PROMPT_SOURCES } from '../lib/cosValidation.js';
import { EFFORT_LEVELS } from '../lib/providerModels.js';
+import { INTERVAL_TYPES, decodeIntervalType, isCronExpression, isKnownIntervalType } from '../services/taskScheduleConstants.js';
const templateTaskSchema = z.object({
name: z.string().min(1),
@@ -22,7 +23,7 @@ const templateTaskSchema = z.object({
const router = Router();
-const SCHEDULE_FIELDS = ['type', 'enabled', 'intervalMs', 'cronExpression', 'providerId', 'model', 'effort', 'prompt', 'description', 'dataInputs', 'taskMetadata', 'runAfter',
+const SCHEDULE_FIELDS = ['type', 'perpetual', 'enabled', 'intervalMs', 'cronExpression', 'providerId', 'model', 'effort', 'prompt', 'description', 'dataInputs', 'taskMetadata', 'runAfter',
// Perpetual (drain-until-done) recheck cadence: after a perpetual task drains
// its backlog and parks, it re-probes its work-detector on this cadence.
// `recheckCron` (5-field) takes precedence over `recheckIntervalMs`.
@@ -43,6 +44,28 @@ function pickScheduleSettings(body) {
if (settings.enabled !== undefined && typeof settings.enabled !== 'boolean') {
throw new ServerError('enabled must be a boolean', { status: 400, code: 'VALIDATION_ERROR' });
}
+ if (settings.perpetual !== undefined && typeof settings.perpetual !== 'boolean') {
+ throw new ServerError('perpetual must be a boolean', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (settings.type !== undefined) {
+ // Reject an unrecognized string outright — decoding it would silently make
+ // an unreadable cadence 'on-demand', i.e. quietly stop the task running.
+ if (!isKnownIntervalType(settings.type)) {
+ throw new ServerError(`type must be one of ${Object.values(INTERVAL_TYPES).join(', ')}`, { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ // A client still on the previous release (or a peer machine mid-upgrade)
+ // may send a retired cadence name. Rewrite it onto the two-variant model
+ // rather than 400-ing, so an older UI keeps working through the upgrade.
+ const decoded = decodeIntervalType(settings.type, { intervalMs: settings.intervalMs });
+ settings.type = decoded.type;
+ if (decoded.perpetual && settings.perpetual === undefined) settings.perpetual = true;
+ if (decoded.type === INTERVAL_TYPES.CRON && !isCronExpression(settings.cronExpression) && decoded.cronExpression) {
+ settings.cronExpression = decoded.cronExpression;
+ }
+ }
+ if (settings.cronExpression !== undefined && settings.cronExpression !== null && !isCronExpression(settings.cronExpression)) {
+ throw new ServerError('cronExpression must be a 5-field cron expression (minute hour dayOfMonth month dayOfWeek) or null', { status: 400, code: 'VALIDATION_ERROR' });
+ }
if (settings.description !== undefined) {
if (settings.description !== null && typeof settings.description !== 'string') {
throw new ServerError('description must be a string or null', { status: 400, code: 'VALIDATION_ERROR' });
@@ -248,15 +271,11 @@ router.get('/schedule/interval-types', (req, res) => {
res.json({
types: taskSchedule.INTERVAL_TYPES,
descriptions: {
- rotation: 'Runs as part of normal task rotation (default)',
- daily: 'Runs once per day',
- weekly: 'Runs once per week',
- once: 'Runs once per app or globally, then stops',
'on-demand': 'Only runs when manually triggered',
- custom: 'Custom interval in milliseconds',
- cron: 'Cron expression schedule (minute hour dayOfMonth month dayOfWeek)',
- perpetual: 'Drains actionable work back-to-back until none remains, then rechecks on a cadence (recheckCron / recheckIntervalMs, default daily)'
- }
+ cron: 'Scheduled on a cron expression (minute hour dayOfMonth month dayOfWeek)'
+ },
+ // `perpetual` is an orthogonal flag, not a type — it applies to either.
+ perpetual: 'Drains actionable work back-to-back until none remains, then rechecks on a cadence (its own cron expression when scheduled, else recheckCron / recheckIntervalMs, default daily)'
});
});
diff --git a/server/routes/cosScheduleRoutes.test.js b/server/routes/cosScheduleRoutes.test.js
index 34ad5c6df6..1056a63d07 100644
--- a/server/routes/cosScheduleRoutes.test.js
+++ b/server/routes/cosScheduleRoutes.test.js
@@ -20,7 +20,7 @@ vi.mock('../services/taskSchedule.js', () => ({
getTemplateTasks: vi.fn(),
addTemplateTask: vi.fn(),
deleteTemplateTask: vi.fn(),
- INTERVAL_TYPES: ['rotation', 'daily', 'weekly', 'once', 'on-demand', 'custom', 'cron']
+ INTERVAL_TYPES: { ON_DEMAND: 'on-demand', CRON: 'cron' }
}));
vi.mock('../lib/validation.js', () => ({
@@ -94,7 +94,7 @@ describe('CoS Schedule Routes', () => {
describe('GET /api/cos/schedule/task/:taskType', () => {
it('should return interval and shouldRun for task type', async () => {
- taskSchedule.getTaskInterval.mockResolvedValue({ type: 'daily', intervalMs: 86400000 });
+ taskSchedule.getTaskInterval.mockResolvedValue({ type: 'cron', cronExpression: '0 7 * * *' });
taskSchedule.shouldRunTask.mockResolvedValue(true);
const response = await request(app).get('/api/cos/schedule/task/review');
@@ -420,12 +420,57 @@ describe('CoS Schedule Routes', () => {
});
describe('GET /api/cos/schedule/interval-types', () => {
- it('should return available interval types', async () => {
+ it('returns exactly the two cadence variants, with perpetual described apart', async () => {
const response = await request(app).get('/api/cos/schedule/interval-types');
expect(response.status).toBe(200);
- expect(response.body.types).toContain('daily');
- expect(response.body.descriptions).toHaveProperty('daily');
+ expect(response.body.types).toEqual({ ON_DEMAND: 'on-demand', CRON: 'cron' });
+ expect(Object.keys(response.body.descriptions).sort()).toEqual(['cron', 'on-demand']);
+ // `perpetual` is an orthogonal flag, so it must NOT appear as a type.
+ expect(typeof response.body.perpetual).toBe('string');
+ });
+ });
+
+ describe('PUT /api/cos/schedule/task/:taskType — cadence validation', () => {
+ it('accepts the perpetual flag on either cadence and rejects a non-boolean', async () => {
+ const ok = await request(app)
+ .put('/api/cos/schedule/task/security')
+ .send({ type: 'cron', cronExpression: '0 9 * * *', perpetual: true });
+ expect(ok.status).toBe(200);
+ expect(taskSchedule.updateTaskInterval).toHaveBeenCalledWith('security', expect.objectContaining({
+ type: 'cron', cronExpression: '0 9 * * *', perpetual: true
+ }));
+
+ const bad = await request(app).put('/api/cos/schedule/task/security').send({ perpetual: 'yes' });
+ expect(bad.status).toBe(400);
+ });
+
+ it('rewrites a legacy cadence name from an older client instead of rejecting it', async () => {
+ taskSchedule.updateTaskInterval.mockClear();
+ const weekly = await request(app).put('/api/cos/schedule/task/security').send({ type: 'weekly' });
+ expect(weekly.status).toBe(200);
+ expect(taskSchedule.updateTaskInterval).toHaveBeenCalledWith('security', expect.objectContaining({
+ type: 'cron', cronExpression: '0 7 * * 1'
+ }));
+
+ taskSchedule.updateTaskInterval.mockClear();
+ const perpetual = await request(app).put('/api/cos/schedule/task/security').send({ type: 'perpetual' });
+ expect(perpetual.status).toBe(200);
+ expect(taskSchedule.updateTaskInterval).toHaveBeenCalledWith('security', expect.objectContaining({
+ type: 'on-demand', perpetual: true
+ }));
+ });
+
+ it('rejects an unrecognized cadence name rather than silently making it manual-only', async () => {
+ const response = await request(app).put('/api/cos/schedule/task/security').send({ type: 'hourly-ish' });
+ expect(response.status).toBe(400);
+ });
+
+ it('rejects a cronExpression that is not 5 fields', async () => {
+ const response = await request(app)
+ .put('/api/cos/schedule/task/security')
+ .send({ type: 'cron', cronExpression: '0 9 * *' });
+ expect(response.status).toBe(400);
});
});
diff --git a/server/services/cos.js b/server/services/cos.js
index 243cd9ad3b..4563e0896d 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -21,7 +21,6 @@ import { join } from 'path';
import { getActiveProvider } from './providers.js';
import { isInternalTaskId } from '../lib/taskParser.js';
import { isAutoApprovableInvestigation } from '../lib/investigationTasks.js';
-import { INTERVAL_TYPES, isReconcileDrainTaskType } from './taskScheduleConstants.js';
import { isRetryHeld, isStaleRetryHold } from '../lib/taskRetryHold.js';
import { isAppOnCooldown, markAppReviewCooldown, bindAppReviewAgent, clearStaleActiveAgents } from './appActivity.js';
import { getActiveApps } from './apps.js';
@@ -1477,12 +1476,10 @@ export function isPerpetualRefillCandidate(agent, schedule) {
const analysisType = agentScheduledType(agent);
if (!analysisType) return false;
const taskDef = schedule?.tasks?.[analysisType];
- const isPerpetual = taskDef?.type === INTERVAL_TYPES.PERPETUAL;
- const isOnDemandReconcile = taskDef?.type === INTERVAL_TYPES.ON_DEMAND
- && isReconcileDrainTaskType(analysisType);
- // Reconciliation keeps its drain semantics even though its fresh-install
- // interval is on-demand; all other on-demand tasks remain single-run actions.
- return Boolean(taskDef?.enabled) && (isPerpetual || isOnDemandReconcile);
+ // `perpetual` is the single drain signal, orthogonal to the cadence type: an
+ // on-demand or cron task carrying the flag re-queues on completion, and one
+ // without it stays a single-run action.
+ return Boolean(taskDef?.enabled) && taskDef?.perpetual === true;
}
/**
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index 211909fcb2..a1042cf1fb 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -1759,16 +1759,6 @@ describe('cos.js source — priority + capacity invariants', () => {
'queue path must collapse description to a single line via firstLine()'
).toMatch(/\.description\s*=\s*firstLine\(/);
- // `getNextTaskType` falls back to ROTATION when nothing is time-due, and
- // the rotation pointer is derived from the `lastType` argument. The queue
- // path MUST thread the per-app `lastImprovementType` through, otherwise
- // every tick restarts the rotation at index 0 and starves every other
- // rotation type for the app. Mirrors the legacy direct-spawn caller.
- expect(
- fnBody,
- 'queue path must pass the loaded lastType through to getNextTaskType so rotation advances'
- ).toMatch(/getNextTaskType\(app\.id,\s*\w+\s*(?:,|\))/);
-
// appActivity helpers must come from the file-level static import (line ~23),
// NOT a dynamic `await import('./appActivity.js')` *inside* the per-app
// loop. Dynamic imports are cached but still add an extra microtask + a
@@ -2182,10 +2172,12 @@ describe('addTask — first-line dedup', () => {
describe('isPerpetualRefillCandidate — perpetual drain on completion', () => {
const schedule = {
tasks: {
- 'claim-issue': { type: 'perpetual', enabled: true },
- 'claim-issue-disabled': { type: 'perpetual', enabled: false },
- 'branch-reconcile': { type: 'on-demand', enabled: true },
- 'plan-task': { type: 'daily', enabled: true },
+ 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true },
+ 'claim-issue-disabled': { type: 'on-demand', perpetual: true, enabled: false },
+ // A cron cadence carrying the same flag drains identically — the lane is
+ // chosen by `perpetual`, never by the cadence type or the task's name.
+ 'branch-reconcile': { type: 'cron', cronExpression: '0 3 * * *', perpetual: true, enabled: true },
+ 'plan-task': { type: 'cron', cronExpression: '0 7 * * *', enabled: true },
},
};
const agentFor = (analysisType, key = 'taskAnalysisType') => ({
@@ -2204,7 +2196,7 @@ describe('isPerpetualRefillCandidate — perpetual drain on completion', () => {
expect(isPerpetualRefillCandidate(agentFor('plan-task'), schedule)).toBe(false);
});
- it('is true for an enabled on-demand reconciliation drain', () => {
+ it('is true for an enabled cron-scheduled perpetual drain', () => {
expect(isPerpetualRefillCandidate(agentFor('branch-reconcile'), schedule)).toBe(true);
});
@@ -2235,10 +2227,12 @@ describe('isPerpetualRefillCandidate — perpetual drain on completion', () => {
describe('perpetualRefillPlan — manual vs scheduled drain lane', () => {
const schedule = {
tasks: {
- 'claim-issue': { type: 'perpetual', enabled: true },
- 'claim-issue-disabled': { type: 'perpetual', enabled: false },
- 'branch-reconcile': { type: 'on-demand', enabled: true },
- 'plan-task': { type: 'daily', enabled: true },
+ 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true },
+ 'claim-issue-disabled': { type: 'on-demand', perpetual: true, enabled: false },
+ // A cron cadence carrying the same flag drains identically — the lane is
+ // chosen by `perpetual`, never by the cadence type or the task's name.
+ 'branch-reconcile': { type: 'cron', cronExpression: '0 3 * * *', perpetual: true, enabled: true },
+ 'plan-task': { type: 'cron', cronExpression: '0 7 * * *', enabled: true },
},
};
const agent = (metadata) => ({ metadata });
@@ -2255,7 +2249,7 @@ describe('perpetualRefillPlan — manual vs scheduled drain lane', () => {
)).toEqual({ lane: 'onDemand', taskType: 'claim-issue', appId: 'app-42' });
});
- it('routes an on-demand reconciliation drain to the on-demand lane', () => {
+ it('routes a cron-scheduled perpetual drain to the on-demand lane when the run was manual', () => {
expect(perpetualRefillPlan(
agent({ taskAnalysisType: 'branch-reconcile', taskOnDemand: true, taskApp: 'app-1' }),
schedule,
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 7e7b1a6bde..544df54f86 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -1509,16 +1509,13 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, { ignore
blockedTaskTypes, ignoreTaskId, wakeAfterRecord
});
- // Load the activity snapshot ONCE before the per-app loop. Both the
- // cooldown gate and the rotation `lastType` lookup are derived from
- // `data/app-activity.json`; before this hoist, each app paid two
- // separate disk reads (one via `isAppOnCooldown` + one via
- // `getAppActivityById`), so a 10-app deployment did 20 reads of the
- // same file per scheduler tick. With the snapshot pinned, the cost
- // is O(1) read per `queueEligibleImprovementTasks` invocation. Falls
- // back to an empty `apps` map on disk error so the loop's per-app
- // lookups uniformly return `undefined` (both gates treat that as
- // "no activity yet — not on cooldown, no last type").
+ // Load the activity snapshot ONCE before the per-app loop. The cooldown gate
+ // is derived from `data/app-activity.json`; before this hoist, each app paid a
+ // separate disk read (via `isAppOnCooldown`), so a 10-app deployment re-read
+ // the same file once per app per scheduler tick. With the snapshot pinned, the
+ // cost is O(1) read per `queueEligibleImprovementTasks` invocation. Falls back
+ // to an empty `apps` map on disk error so the loop's per-app lookups uniformly
+ // return `undefined` (read as "no activity yet — not on cooldown").
const activitySnapshot = await loadAppActivity().catch(() => ({ apps: {} }));
// Queue eligible improvement tasks for all managed apps (including PortOS)
@@ -1565,13 +1562,7 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, { ignore
// alone). When NOT on cooldown, the normal full-priority pick runs.
const onCooldown = isAppActivityOnCooldown(appActivity, state.config.appReviewCooldownMs);
- // `getNextTaskType` falls back to ROTATION when nothing is time-due, and the
- // rotation pointer is derived from `lastType` — without it the rotation
- // always restarts from index 0 and starves every other rotation type for the
- // app. Mirror `generateManagedAppTask` (the legacy direct-spawn caller) which
- // threads the per-app `lastImprovementType` in.
- const lastType = appActivity?.lastImprovementType || '';
- const nextTypeResult = await getNextTaskType(app.id, lastType, { perpetualOnly: onCooldown }).catch(() => null);
+ const nextTypeResult = await getNextTaskType(app.id, { perpetualOnly: onCooldown }).catch(() => null);
if (!nextTypeResult) continue;
const nextType = nextTypeResult.taskType;
@@ -2285,7 +2276,7 @@ export function applyAppWorktreeDefault(metadata, app) {
}
async function generateManagedAppImprovementTask(app, state, { ignoreTaskId = null } = {}) {
- const { getAppActivityById, updateAppActivity } = await import('./appActivity.js');
+ const { updateAppActivity } = await import('./appActivity.js');
const taskSchedule = await import('./taskSchedule.js');
// First, check for any on-demand task requests for this app
@@ -2315,12 +2306,8 @@ async function generateManagedAppImprovementTask(app, state, { ignoreTaskId = nu
selectionReason = 'on-demand';
emitLog('info', `Processing on-demand app task request: ${nextType} for ${app.name}`, { requestId: request.id });
} else {
- // Get last improvement type for this app
- const appActivity = await getAppActivityById(app.id);
- const lastType = appActivity?.lastImprovementType || '';
-
// Use the schedule service to determine the next task type
- const nextTypeResult = await taskSchedule.getNextTaskType(app.id, lastType);
+ const nextTypeResult = await taskSchedule.getNextTaskType(app.id);
if (!nextTypeResult) {
emitLog('info', `No app improvement tasks are eligible for ${app.name} based on schedule`);
@@ -2429,8 +2416,7 @@ function takePerpetualTransient(taskType, appId) {
export async function emitOnDemandEmpty({ taskScheduleMod, request, targetApp, taskConfig }) {
const appId = targetApp?.id || null;
const parkInfo = await taskScheduleMod.getPerpetualParkInfo(request.taskType, appId).catch(() => null);
- const isDetectorDriven = taskConfig?.type === taskScheduleMod.INTERVAL_TYPES.PERPETUAL
- || isReconcileDrainTaskType(request.taskType);
+ const isDetectorDriven = taskConfig?.perpetual === true;
const outcome = parkInfo ? 'parked' : (isDetectorDriven ? 'transient' : 'idle');
// Layered Intelligence skips (e.g. a provider that can't drive an agent) record
@@ -2606,8 +2592,9 @@ async function resolveClaimWorkRouting(app, taskType, metadata, taskSchedule) {
* evaluations alone, parking it for `drain-cap` without a single dispatch.
*/
async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, interval, taskSchedule, { ignoreTaskId = null } = {}) {
- if (interval.type !== taskSchedule.INTERVAL_TYPES.PERPETUAL
- || taskType === 'branch-reconcile' || taskType === 'issue-reconcile') {
+ // The reconcile drains run their own scan-driven gate (the blocks in
+ // cosTaskPreStepBlocks), so they opt out of the generic work detector.
+ if (interval.perpetual !== true || isReconcileDrainTaskType(taskType)) {
return { skip: false };
}
const { detectActionableWork } = await import('./perpetualWork.js');
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index ce10bd0fbf..6ec29228e7 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -967,7 +967,7 @@ describe('emitOnDemandEmpty', () => {
// and the INTERVAL_TYPES enum the perpetual check reads.
const stubMod = {
getPerpetualParkInfo: async () => null,
- INTERVAL_TYPES: { ON_DEMAND: 'on-demand', PERPETUAL: 'perpetual' }
+ INTERVAL_TYPES: { ON_DEMAND: 'on-demand', CRON: 'cron' }
};
it("emits an 'idle' event with reason null for a non-LI task type", async () => {
@@ -979,7 +979,7 @@ describe('emitOnDemandEmpty', () => {
taskScheduleMod: stubMod,
request: { id: 'req-1', taskType: 'pr-watcher' },
targetApp: { id: 'app-1', name: 'App One' },
- taskConfig: { type: 'custom' }
+ taskConfig: { type: 'cron', cronExpression: '0 7 * * *' }
});
} finally {
cosEvents.off('schedule:on-demand-empty', handler);
@@ -1004,7 +1004,7 @@ describe('emitOnDemandEmpty', () => {
taskScheduleMod: stubMod,
request: { id: 'req-2', taskType },
targetApp: { id: 'app-1', name: 'App One' },
- taskConfig: { type: 'perpetual' }
+ taskConfig: { type: 'on-demand', perpetual: true }
});
} finally {
cosEvents.off('schedule:on-demand-empty', handler);
@@ -1018,7 +1018,7 @@ describe('emitOnDemandEmpty', () => {
expect(await emitTransient('claim-issue')).toMatchObject({ outcome: 'transient', forge: null });
});
- it('treats on-demand reconciliation as detector-driven for transient feedback', async () => {
+ it('treats a perpetual on-demand drain as detector-driven for transient feedback', async () => {
recordPerpetualTransient('branch-reconcile', 'app-1', { cli: null, reason: 'probe-failed' });
const events = [];
const handler = (data) => events.push(data);
@@ -1028,7 +1028,7 @@ describe('emitOnDemandEmpty', () => {
taskScheduleMod: stubMod,
request: { id: 'req-reconcile', taskType: 'branch-reconcile' },
targetApp: { id: 'app-1', name: 'App One' },
- taskConfig: { type: 'on-demand' }
+ taskConfig: { type: 'on-demand', perpetual: true }
});
} finally {
cosEvents.off('schedule:on-demand-empty', handler);
diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.js
index ec2fd5cd5e..673cb9fdf4 100644
--- a/server/services/cosTaskPreStepBlocks.js
+++ b/server/services/cosTaskPreStepBlocks.js
@@ -29,7 +29,6 @@ import { emitLog } from './cosEvents.js';
import { getActiveApps } from './apps.js';
import { getCodeReviewDefaults } from './codeReview.js';
import { NON_ACTIONABLE_ISSUE_LABELS } from './perpetualWork.js';
-import { isReconcileDrainTaskType } from './taskScheduleConstants.js';
import {
appendReviewerEffortBlock,
buildLocalReviewerInstructions,
@@ -248,10 +247,7 @@ export function buildPlanConstraintBlock(planId) {
* @returns {Promise<{skip:boolean}>}
*/
export async function applyPerpetualDrainCap(app, taskType, interval, taskSchedule) {
- const isPerpetual = interval.type === taskSchedule.INTERVAL_TYPES.PERPETUAL;
- const isOnDemandReconcile = interval.type === taskSchedule.INTERVAL_TYPES.ON_DEMAND
- && isReconcileDrainTaskType(taskType);
- if (!isPerpetual && !isOnDemandReconcile) return { skip: false };
+ if (interval.perpetual !== true) return { skip: false };
// Coerce before validating: this key is not on the schedule route's allowlist, so
// the only way it arrives non-numeric is a hand-edited schedule.json, where `"5"`
// is the likeliest shape and reading it as "no cap" would silently unbound the
diff --git a/server/services/cosTaskPreStepBlocks.test.js b/server/services/cosTaskPreStepBlocks.test.js
index ef21fd8eaa..106a7e5ac6 100644
--- a/server/services/cosTaskPreStepBlocks.test.js
+++ b/server/services/cosTaskPreStepBlocks.test.js
@@ -291,12 +291,13 @@ describe('resolveReconcileDrainGate', () => {
*/
describe('applyPerpetualDrainCap', () => {
const fakeSchedule = (dispatchCount = 0) => ({
- INTERVAL_TYPES: { ON_DEMAND: 'on-demand', PERPETUAL: 'perpetual' },
+ INTERVAL_TYPES: { ON_DEMAND: 'on-demand', CRON: 'cron' },
getPerpetualDrainState: vi.fn(async () => ({ signature: null, dispatchCount })),
parkPerpetual: vi.fn(async () => {})
});
const app = { id: 'app-1', name: 'App One' };
- const perpetual = (over = {}) => ({ type: 'perpetual', ...over });
+ // The drain signal is the orthogonal `perpetual` flag, not the cadence type.
+ const perpetual = (over = {}) => ({ type: 'on-demand', perpetual: true, ...over });
it('parks drain-cap once the budget is spent, clearing the signature in the park write', async () => {
const ts = fakeSchedule(5);
@@ -333,12 +334,15 @@ describe('applyPerpetualDrainCap', () => {
it('ignores non-perpetual intervals entirely', async () => {
const ts = fakeSchedule(500);
- expect(await applyPerpetualDrainCap(app, 'security', { type: 'daily', drainDispatchCap: 5 }, ts)).toEqual({ skip: false });
+ expect(await applyPerpetualDrainCap(app, 'security', { type: 'cron', cronExpression: '0 7 * * *', drainDispatchCap: 5 }, ts)).toEqual({ skip: false });
expect(ts.getPerpetualDrainState).not.toHaveBeenCalled();
+ // A reconcile task WITHOUT the flag is no longer special-cased by name.
+ expect(await applyPerpetualDrainCap(app, 'branch-reconcile', { type: 'on-demand', drainDispatchCap: 5 }, ts)).toEqual({ skip: false });
});
- it('applies the cap to the on-demand reconciliation drain', async () => {
+ it('applies the cap to a cron-scheduled perpetual drain, not just an on-demand one', async () => {
const ts = fakeSchedule(5);
- expect(await applyPerpetualDrainCap(app, 'branch-reconcile', { type: 'on-demand', drainDispatchCap: 5 }, ts)).toEqual({ skip: true });
+ const cronDrain = { type: 'cron', cronExpression: '0 7 * * *', perpetual: true, drainDispatchCap: 5 };
+ expect(await applyPerpetualDrainCap(app, 'branch-reconcile', cronDrain, ts)).toEqual({ skip: true });
});
});
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 55d2b77869..6553932881 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -4,17 +4,15 @@
* Manages configurable intervals for improvement tasks across all apps (including PortOS).
* All task types live in a single `tasks` object — no more selfImprovement/appImprovement split.
*
- * Interval types:
- * - 'rotation': Run as part of normal rotation (default)
- * - 'daily': Run once per day
- * - 'weekly': Run once per week
- * - 'once': Run once per app/globally then stop
- * - 'on-demand': Only run when manually triggered
- * - 'custom': Custom interval in milliseconds
- * - 'cron': Cron expression schedule
- * - 'perpetual': Drain actionable work back-to-back (re-queue on completion)
- * until a programmatic work-detector reports nothing actionable, then PARK
- * on a recheck cadence (`recheckCron` / `recheckIntervalMs`, default daily).
+ * 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.
+ * - `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
+ * rechecks on `recheckCron` / `recheckIntervalMs` (default daily); a
+ * cron+perpetual task's cron slot INITIATES the drain and the same expression
+ * gates the next attempt once it parks.
* See server/services/perpetualWork.js for the detector registry and the
* perpetual gate in cosTaskGenerator.generateManagedAppImprovementTaskForType.
*/
@@ -34,7 +32,8 @@ import {
DEFAULT_PERPETUAL_RECHECK_MS,
INTERVAL_TYPES,
ON_DEMAND_ORIGINS,
- WEEK,
+ decodeIntervalType,
+ isCronExpression,
isRefillRequest
} from './taskScheduleConstants.js';
import {
@@ -168,7 +167,8 @@ async function getPerformanceAdjustedInterval(taskType, baseIntervalMs) {
export async function getTaskInterval(taskType) {
const schedule = await loadSchedule();
return schedule.tasks[taskType] || {
- type: INTERVAL_TYPES.ROTATION,
+ type: INTERVAL_TYPES.ON_DEMAND,
+ perpetual: false,
enabled: false,
providerId: null,
model: null,
@@ -179,7 +179,7 @@ export async function getTaskInterval(taskType) {
export async function updateTaskInterval(taskType, settings) {
const { task, unparkedScopes } = await updateSchedule(async (schedule) => {
if (!schedule.tasks[taskType]) {
- schedule.tasks[taskType] = { type: INTERVAL_TYPES.ROTATION, enabled: false, providerId: null, model: null, createdAt: new Date().toISOString() };
+ schedule.tasks[taskType] = { type: INTERVAL_TYPES.ON_DEMAND, perpetual: false, enabled: false, providerId: null, model: null, createdAt: new Date().toISOString() };
}
// Normalize empty/whitespace prompts to null (treated as "use default")
@@ -260,7 +260,7 @@ export async function updateTaskInterval(taskType, settings) {
// clears it — so it is a record that is DUE RIGHT NOW. Restamping it from a
// lengthened cadence would silently push already-due work back into the future.
const merged = schedule.tasks[taskType];
- if (merged.type === INTERVAL_TYPES.PERPETUAL && ('recheckCron' in settings || 'recheckIntervalMs' in settings)) {
+ if (merged.perpetual && ('recheckCron' in settings || 'recheckIntervalMs' in settings || 'cronExpression' in settings)) {
const exec = schedule.executions[`task:${taskType}`];
if (exec) {
const nowMs = Date.now();
@@ -349,13 +349,19 @@ export async function getExecutionHistory(taskType) {
/**
* Compute when a parked perpetual task should next re-probe its work-detector.
- * Prefers `recheckCron` (a 5-field cron string, evaluated in the user's
- * timezone) over `recheckIntervalMs`; falls back to DEFAULT_PERPETUAL_RECHECK_MS.
+ * A cron-scheduled perpetual task rechecks on its own `cronExpression`;
+ * otherwise this prefers `recheckCron` (a 5-field cron string, evaluated in the
+ * user's timezone) over `recheckIntervalMs`, falling back to
+ * DEFAULT_PERPETUAL_RECHECK_MS.
* Returns an ISO timestamp string.
*/
export async function computePerpetualRecheckAt(interval, fromMs = Date.now()) {
- const cron = interval?.recheckCron;
- if (typeof cron === 'string' && cron.trim().split(/\s+/).length === 5) {
+ // A cron+perpetual task needs no separate recheck cadence: its own schedule
+ // both initiates the drain and gates the next attempt after it parks.
+ const cron = (interval?.type === INTERVAL_TYPES.CRON && isCronExpression(interval?.cronExpression))
+ ? interval.cronExpression
+ : interval?.recheckCron;
+ if (isCronExpression(cron)) {
const timezone = await getUserTimezone();
const next = parseCronToNextRun(cron, new Date(fromMs), timezone);
if (next) return next.toISOString();
@@ -782,26 +788,6 @@ async function checkRunAfterDeps(schedule, taskType, appId = null, featureEnable
return { satisfied: pending.length === 0, pending };
}
-/**
- * Shared due/cooldown evaluation for the fixed-cadence interval types
- * (DAILY, WEEKLY, CUSTOM), which differ only in their base interval and the
- * reason-string prefix (`label`). Reason strings are persisted and compared
- * elsewhere, so they must come out byte-identical to what each case produced
- * before this was extracted (e.g. `'daily-due'`, `'weekly-cooldown-adjusted'`).
- */
-async function evaluateFixedInterval(taskType, baseIntervalMs, label, timeSinceLastRun, lastRun, buildResult) {
- const learningAdjustment = await getPerformanceAdjustedInterval(taskType, baseIntervalMs);
- const adjustedInterval = learningAdjustment.adjustedIntervalMs;
- if (timeSinceLastRun >= adjustedInterval) {
- return buildResult(true, learningAdjustment.adjusted ? `${label}-due-adjusted` : `${label}-due`, baseIntervalMs, { learningAdjustment });
- }
- return buildResult(false, learningAdjustment.adjusted ? `${label}-cooldown-adjusted` : `${label}-cooldown`, baseIntervalMs, {
- learningAdjustment, nextRunIn: adjustedInterval - timeSinceLastRun,
- nextRunAt: new Date(lastRun + adjustedInterval).toISOString(),
- baseIntervalMs, adjustedIntervalMs: adjustedInterval
- });
-}
-
/**
* Check if a task type should run for a specific app (or globally)
*/
@@ -837,14 +823,22 @@ export async function shouldRunTask(taskType, appId = null, { featureEnabled = c
// Determine effective interval type: per-app override takes precedence
const perAppInterval = appId ? await getAppTaskTypeInterval(appId, taskType) : null;
// A per-app numeric intervalMs override (used by handler-backed tasks like
- // layered-intelligence, whose Intelligence-tab UI offers sub-daily cadences the
- // string enum can't express). When set alongside interval:'custom', the CUSTOM
- // branch below uses THIS value as the base interval instead of the global one.
+ // layered-intelligence, whose Intelligence-tab UI offers sub-daily cadences a
+ // named cadence never expressed). A legacy `interval: 'custom'` override
+ // decodes THIS value into the per-app cron expression below.
const perAppIntervalMs = appId ? await getAppTaskTypeIntervalMs(appId, taskType) : null;
- const hasCustomIntervalMs = Number.isFinite(perAppIntervalMs) && perAppIntervalMs > 0;
- // Cron expressions (contain spaces) are stored directly as the interval value
- const isCronOverride = perAppInterval && perAppInterval.includes(' ');
- const effectiveType = isCronOverride ? INTERVAL_TYPES.CRON : (perAppInterval || interval.type);
+ // A per-app override may be a raw cron expression or a retired named cadence
+ // written by an older install; decode both onto the two-variant model.
+ const perAppDecoded = perAppInterval
+ ? decodeIntervalType(perAppInterval, { intervalMs: perAppIntervalMs })
+ : null;
+ const effectiveType = perAppDecoded ? perAppDecoded.type : interval.type;
+ const effectiveCron = perAppDecoded
+ ? perAppDecoded.cronExpression
+ : (interval.cronExpression || null);
+ // `perpetual` is a task-level global property — per-app rows override the
+ // cadence only (see the issue's Out of Scope), so the global flag always wins.
+ const isPerpetual = interval.perpetual === true;
const key = `task:${taskType}`;
const execution = schedule.executions[key] || { lastRun: null, count: 0, perApp: {} };
@@ -870,56 +864,51 @@ export async function shouldRunTask(taskType, appId = null, { featureEnabled = c
const now = Date.now();
const lastRun = appExecution.lastRun ? new Date(appExecution.lastRun).getTime() : 0;
- const timeSinceLastRun = now - lastRun;
-
- const buildResult = (shouldRun, reason, baseIntervalMs, extra = {}) => {
- const result = { shouldRun, reason, ...extra };
- if (extra.learningAdjustment?.adjusted) {
- result.learningApplied = true;
- result.successRate = extra.learningAdjustment.successRate;
- result.adjustmentMultiplier = extra.learningAdjustment.multiplier;
- result.dataPoints = extra.learningAdjustment.dataPoints;
- }
- return result;
- };
let result;
- switch (effectiveType) {
- case INTERVAL_TYPES.ROTATION:
- result = { shouldRun: true, reason: 'rotation' };
- break;
-
- case INTERVAL_TYPES.DAILY:
- result = await evaluateFixedInterval(taskType, DAY, 'daily', timeSinceLastRun, lastRun, buildResult);
- break;
-
- case INTERVAL_TYPES.WEEKLY:
- result = await evaluateFixedInterval(taskType, WEEK, 'weekly', timeSinceLastRun, lastRun, buildResult);
- break;
-
- case INTERVAL_TYPES.ONCE:
- result = appExecution.count === 0
- ? { shouldRun: true, reason: 'once-first-run' }
- : { shouldRun: false, reason: 'once-completed', completedAt: appExecution.lastRun };
- break;
+ // A perpetual task's park record is the drain's brake: the work-detector at
+ // DISPATCH time writes `parkedUntil` when nothing is actionable, and this only
+ // READS it (so shouldRunTask never does network I/O). Shared by both cadence
+ // variants — an on-demand+perpetual task is due whenever it isn't parked, a
+ // cron+perpetual task additionally needs a cron slot to initiate a drain.
+ const perpetualParkResult = () => {
+ const parkUntil = parkedUntilMs(appExecution);
+ if (parkUntil && now < parkUntil) {
+ return {
+ shouldRun: false,
+ reason: 'perpetual-parked',
+ nextRunAt: new Date(parkUntil).toISOString(),
+ parkReason: appExecution.parkReason || null,
+ parkActionableCount: appExecution.parkActionableCount ?? null
+ };
+ }
+ return parkUntil ? { shouldRun: true, reason: 'perpetual-recheck' } : null;
+ };
+ switch (effectiveType) {
case INTERVAL_TYPES.ON_DEMAND:
- result = { shouldRun: false, reason: 'on-demand-only' };
- break;
-
- case INTERVAL_TYPES.CUSTOM: {
- // A per-app numeric intervalMs override wins over the global custom interval
- // (handler-backed tasks store their per-app cadence there).
- const baseInterval = (hasCustomIntervalMs ? perAppIntervalMs : interval.intervalMs) || DAY;
- result = await evaluateFixedInterval(taskType, baseInterval, 'custom', timeSinceLastRun, lastRun, buildResult);
+ // Drain-until-done when perpetual; otherwise a manual trigger is the only
+ // way this ever runs.
+ result = isPerpetual
+ ? (perpetualParkResult() || { shouldRun: true, reason: 'perpetual-drain' })
+ : { shouldRun: false, reason: 'on-demand-only' };
break;
- }
case INTERVAL_TYPES.CRON: {
+ // A parked perpetual drain is gated by its park, not by the cron slot —
+ // and once the park elapses it is due immediately (computePerpetualRecheckAt
+ // already derived that instant from this very expression).
+ if (isPerpetual) {
+ const parked = perpetualParkResult();
+ if (parked) { result = parked; break; }
+ // Unparked: the cron evaluation below decides whether to INITIATE a
+ // drain. Once one is running, the completion-refill lane keeps it going
+ // back-to-back regardless of subsequent ticks.
+ }
// Cron expression: per-app override (stored as the interval string) or global config
- const cronExpr = isCronOverride ? perAppInterval : interval.cronExpression;
- if (!cronExpr || typeof cronExpr !== 'string' || cronExpr.trim().split(/\s+/).length !== 5) {
+ const cronExpr = effectiveCron;
+ if (!isCronExpression(cronExpr)) {
result = { shouldRun: false, reason: 'invalid-cron' };
break;
}
@@ -976,32 +965,9 @@ export async function shouldRunTask(taskType, appId = null, { featureEnabled = c
break;
}
- case INTERVAL_TYPES.PERPETUAL: {
- // Drain-until-done: a perpetual task is "due" whenever it isn't parked.
- // The actual programmatic work-detector runs at DISPATCH time (the gate in
- // generateManagedAppImprovementTaskForType) and PARKS the task — writing
- // `parkedUntil` onto the execution record — when nothing is actionable.
- // shouldRunTask only reads that persisted park, so it never does network
- // I/O even though it's called several times per evaluation cycle. While
- // parked, the recheck cadence (parkedUntil) gates re-probing; once it
- // elapses the task becomes due again and the gate re-runs the detector.
- const parkUntil = parkedUntilMs(appExecution);
- if (parkUntil && now < parkUntil) {
- result = {
- shouldRun: false,
- reason: 'perpetual-parked',
- nextRunAt: new Date(parkUntil).toISOString(),
- parkReason: appExecution.parkReason || null,
- parkActionableCount: appExecution.parkActionableCount ?? null
- };
- } else {
- result = { shouldRun: true, reason: parkUntil ? 'perpetual-recheck' : 'perpetual-drain' };
- }
- break;
- }
-
default:
- result = { shouldRun: true, reason: 'unknown-default-rotation' };
+ // Unreachable once normalized — an unreadable cadence must never auto-run.
+ result = { shouldRun: false, reason: 'on-demand-only' };
}
// Escalating failure backoff (#2616): a type with recent consecutive failures
@@ -1065,76 +1031,40 @@ export async function getDueTasks(appId = null) {
/**
* Get the next task type to run (optionally for a specific app)
*/
-export async function getNextTaskType(appId = null, lastType = '', { perpetualOnly = false } = {}) {
- const schedule = await loadSchedule();
+export async function getNextTaskType(appId = null, { perpetualOnly = false } = {}) {
const dueTasks = await getDueTasks(appId);
// `perpetualOnly` constrains the pick to a due perpetual (drain-until-done)
// task, skipping every other schedule type. Callers set this when the app is
// on its review cooldown: only perpetual drains bypass that cooldown (their
- // work-detector park is the throttle), so a higher-priority cron/custom/daily
- // type that's also due must NOT be returned — it would mask the perpetual
- // drain and the caller, seeing a non-exempt pick, would skip the whole app for
- // the cooldown window (the mixed-schedule stall). Returns null when nothing
- // perpetual is due, so the caller leaves the cooled-down app alone.
+ // work-detector park is the throttle), so a higher-priority cron type that's
+ // also due must NOT be returned — it would mask the perpetual drain and the
+ // caller, seeing a non-exempt pick, would skip the whole app for the cooldown
+ // window (the mixed-schedule stall). Returns null when nothing perpetual is
+ // due, so the caller leaves the cooled-down app alone.
+ const perpetualDue = dueTasks.filter(t => t.interval.perpetual === true);
if (perpetualOnly) {
- const perpetualDue = dueTasks.filter(t => t.interval.type === INTERVAL_TYPES.PERPETUAL);
return perpetualDue.length > 0
? { taskType: perpetualDue[0].taskType, reason: 'perpetual-drain' }
: null;
}
- // 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);
+ // A user-pinned wall-clock schedule outranks a drain: a 9 AM cron must fire at
+ // 9 AM even while a perpetual task is mid-backlog. A cron+perpetual task is
+ // already gated by its own park, so it can sit in either bucket safely.
+ const cronDue = dueTasks.filter(t => t.interval.type === INTERVAL_TYPES.CRON);
if (cronDue.length > 0) {
- return { taskType: cronDue[0].taskType, reason: `${cronDue[0].interval.type}-due` };
+ return { taskType: cronDue[0].taskType, reason: 'cron-due' };
}
- // Perpetual tasks actively draining a backlog outrank the loose interval
- // tasks (daily/weekly/once/rotation) so the drain keeps the app's single
- // improvement slot until its work-detector idles and it parks — at which
- // point the loose tasks below get their turn. (Explicit time-pinned cron/
- // custom schedules above still win, so a perpetual drain can't starve a
- // user-pinned 9 AM job.)
- const perpetualDue = dueTasks.filter(t => t.interval.type === INTERVAL_TYPES.PERPETUAL);
+ // Perpetual tasks actively draining a backlog keep the app's single
+ // improvement slot until their work-detector idles and they park.
if (perpetualDue.length > 0) {
return { taskType: perpetualDue[0].taskType, reason: 'perpetual-drain' };
}
- const dailyDue = dueTasks.filter(t => t.interval.type === INTERVAL_TYPES.DAILY);
- if (dailyDue.length > 0) {
- return { taskType: dailyDue[0].taskType, reason: 'daily-priority' };
- }
-
- const weeklyDue = dueTasks.filter(t => t.interval.type === INTERVAL_TYPES.WEEKLY);
- if (weeklyDue.length > 0) {
- return { taskType: weeklyDue[0].taskType, reason: 'weekly-priority' };
- }
-
- const onceDue = dueTasks.filter(t => t.interval.type === INTERVAL_TYPES.ONCE);
- if (onceDue.length > 0) {
- return { taskType: onceDue[0].taskType, reason: 'once-first-run' };
- }
-
- // Fall back to rotation among enabled rotation tasks
- const featureEnabled = createFeatureGate();
- const rotationTasks = [];
- for (const [taskType, interval] of Object.entries(schedule.tasks)) {
- if (interval.enabled && interval.type === INTERVAL_TYPES.ROTATION && await featureEnabled(interval)) {
- rotationTasks.push(taskType);
- }
- }
-
- if (rotationTasks.length === 0) {
- return null;
- }
-
- const currentIndex = rotationTasks.indexOf(lastType);
- const nextIndex = (currentIndex + 1) % rotationTasks.length;
-
- return { taskType: rotationTasks[nextIndex], reason: 'rotation' };
+ // Everything else is on-demand: it runs only from an explicit trigger.
+ return null;
}
// ============================================================
@@ -1289,7 +1219,7 @@ export async function getScheduleStatus() {
const promptInfo = getTaskTypePromptInfo(taskType);
// Get learning adjustment info
- const baseInterval = interval.type === 'daily' ? DAY : interval.type === 'weekly' ? WEEK : (interval.intervalMs || DAY);
+ const baseInterval = interval.intervalMs || DAY;
const learningInfo = await getPerformanceAdjustedInterval(taskType, baseInterval);
// Check global shouldRun status
@@ -1381,9 +1311,11 @@ export async function getScheduleStatus() {
// so the UI can show the true parked/draining state and the soonest recheck.
// Projects the shared aggregatePerpetualParks rollup (same park semantics as
// the getUpcomingTasks eligibility derivation below).
- if (interval.type === INTERVAL_TYPES.PERPETUAL) {
+ if (interval.perpetual) {
const parks = aggregatePerpetualParks(execution, Date.now());
- taskStatus.perpetual = {
+ // Named apart from the `perpetual` BOOLEAN this config carries: the flag
+ // says the task drains, this says what its drain is doing right now.
+ taskStatus.perpetualStatus = {
globalParked: parks.globalParked,
parkedAppCount: parks.parkedAppCount,
trackedAppCount: parks.trackedAppCount,
@@ -1474,7 +1406,9 @@ export async function getUpcomingTasks(limit = 10) {
if (!interval.enabled) continue;
if (!(await featureEnabled(interval))) continue;
if (getTaskTypeInvocation(taskType).visibility === 'hidden') continue;
- if (interval.type === INTERVAL_TYPES.ON_DEMAND) continue;
+ // On-demand tasks have no wall-clock position — unless they are perpetual,
+ // whose park/recheck boundary IS the schedule the daemon must wake on.
+ if (interval.type === INTERVAL_TYPES.ON_DEMAND && !interval.perpetual) continue;
const check = await shouldRunTask(taskType, null, { featureEnabled });
const execution = schedule.executions[`task:${taskType}`] || { lastRun: null, count: 0 };
@@ -1488,16 +1422,13 @@ export async function getUpcomingTasks(limit = 10) {
} else if (check.nextRunAt) {
eligibleAt = new Date(check.nextRunAt).getTime();
taskStatus = 'scheduled';
- } else if (interval.type === INTERVAL_TYPES.ONCE && execution.count > 0) {
- taskStatus = 'completed';
- eligibleAt = Infinity;
}
// Perpetual tasks park per-app, so the global `check` above can't see the
// recheck boundary — re-derive status/eligibility from the park records so
// scheduleNextImprovementCheck wakes the daemon AT the next recheck (e.g. 9am)
// instead of only on the ≤1h fallback poll. See perpetualUpcomingEligibility.
- if (interval.type === INTERVAL_TYPES.PERPETUAL) {
+ if (interval.perpetual) {
const perpetual = perpetualUpcomingEligibility(execution, now);
if (perpetual) {
taskStatus = perpetual.status;
@@ -1505,8 +1436,6 @@ export async function getUpcomingTasks(limit = 10) {
}
}
- if (taskStatus === 'completed') continue;
-
upcoming.push({
taskType,
intervalType: interval.type,
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index a7a435e18a..4cac13fc65 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -194,6 +194,28 @@ const mockSchedule = ({ tasks = {}, executions = {}, templates = [], onDemandReq
readJSONFile.mockResolvedValue({ version: 2, tasks, executions, templates, onDemandRequests })
}
+// loadSchedule merges DEFAULT_TASK_INTERVALS over whatever a fixture supplies,
+// and the shipped reconcile drains are enabled + perpetual — so they are due on
+// every tick. A case asserting on "which tasks are due" has to pause them
+// explicitly or its expectation reads them as noise.
+const PAUSED_SHIPPED_DRAINS = {
+ 'branch-reconcile': { enabled: false },
+ 'issue-reconcile': { enabled: false },
+}
+
+// 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.
+const cronDueNow = () => {
+ parseCronToPrevRun.mockReturnValue(null)
+ parseCronToNextRun.mockReturnValue(new Date(Date.now() - 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
@@ -222,15 +244,8 @@ describe('taskSchedule', () => {
})
describe('INTERVAL_TYPES', () => {
- it('should define all expected interval types', () => {
- expect(INTERVAL_TYPES.ROTATION).toBe('rotation')
- expect(INTERVAL_TYPES.DAILY).toBe('daily')
- expect(INTERVAL_TYPES.WEEKLY).toBe('weekly')
- expect(INTERVAL_TYPES.ONCE).toBe('once')
- expect(INTERVAL_TYPES.ON_DEMAND).toBe('on-demand')
- expect(INTERVAL_TYPES.CUSTOM).toBe('custom')
- expect(INTERVAL_TYPES.CRON).toBe('cron')
- expect(INTERVAL_TYPES.PERPETUAL).toBe('perpetual')
+ it('is exactly the two cadence variants — perpetual is a flag, not a type', () => {
+ expect(INTERVAL_TYPES).toEqual({ ON_DEMAND: 'on-demand', CRON: 'cron' })
})
})
@@ -378,19 +393,32 @@ describe('taskSchedule', () => {
});
});
- it('honors a per-app numeric intervalMs override via the CUSTOM branch', async () => {
+ it('decodes a legacy per-app custom+intervalMs override into an hourly cron', async () => {
const { getAppTaskTypeInterval, getAppTaskTypeIntervalMs } = await import('./apps.js');
+ cronDueNow();
mockSchedule({
- tasks: { 'layered-intelligence': { type: 'daily', enabled: true, providerId: null, model: null, prompt: null } },
+ tasks: { 'layered-intelligence': { type: 'on-demand', enabled: true, providerId: null, model: null, prompt: null } },
executions: { 'task:layered-intelligence': { lastRun: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(), count: 1, perApp: { 'app-1': { lastRun: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(), count: 1 } } } }
});
getAppTaskTypeInterval.mockResolvedValue('custom');
- getAppTaskTypeIntervalMs.mockResolvedValue(60 * 60 * 1000); // hourly → 2h since last run ⇒ due
+ getAppTaskTypeIntervalMs.mockResolvedValue(60 * 60 * 1000);
const res = await shouldRunTask('layered-intelligence', 'app-1');
- expect(res.shouldRun).toBe(true);
+ expect(res).toMatchObject({ shouldRun: true, reason: 'cron-due', cronExpression: '0 * * * *' });
getAppTaskTypeInterval.mockResolvedValue(null);
getAppTaskTypeIntervalMs.mockResolvedValue(null);
});
+
+ it('reads a per-app cron override string directly, overriding the global cadence', async () => {
+ const { getAppTaskTypeInterval } = await import('./apps.js');
+ cronDueNow();
+ mockSchedule({
+ tasks: { 'layered-intelligence': { type: 'on-demand', enabled: true, providerId: null, model: null, prompt: null } }
+ });
+ getAppTaskTypeInterval.mockResolvedValue('*/30 * * * *');
+ const res = await shouldRunTask('layered-intelligence', 'app-1');
+ expect(res).toMatchObject({ shouldRun: true, cronExpression: '*/30 * * * *' });
+ getAppTaskTypeInterval.mockResolvedValue(null);
+ });
});
describe('issue-watcher (programmatic-I/O agent task)', () => {
@@ -478,14 +506,38 @@ describe('taskSchedule', () => {
expect(schedule.tasks['security'].providerId).toBe('p1')
})
- it('preserves an existing paused cadence when loading new defaults', async () => {
+ it('normalizes a legacy cadence on read while preserving the paused state', async () => {
mockSchedule({
- tasks: { security: { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null } }
+ tasks: { security: { type: 'weekly', enabled: false, providerId: null, model: null, prompt: null } }
})
const schedule = await loadSchedule()
- expect(schedule.tasks.security).toMatchObject({ type: INTERVAL_TYPES.WEEKLY, enabled: false })
+ // 'weekly' collapses to a Monday-07:00 cron; `enabled: false` is untouched.
+ expect(schedule.tasks.security).toMatchObject({
+ type: INTERVAL_TYPES.CRON, cronExpression: '0 7 * * 1', perpetual: false, enabled: false
+ })
+ })
+
+ it('collapses every retired cadence and keeps the perpetual flag orthogonal', async () => {
+ mockSchedule({
+ tasks: {
+ security: { type: 'rotation', enabled: true },
+ 'code-quality': { type: 'once', enabled: true },
+ 'test-coverage': { type: 'custom', intervalMs: 15 * 60 * 1000, enabled: true },
+ documentation: { type: 'perpetual', recheckCron: '0 3 * * *', enabled: true },
+ typing: { type: 'cron', cronExpression: '30 8 * * 2', perpetual: true, enabled: true },
+ }
+ })
+
+ const { tasks } = await loadSchedule()
+ expect(tasks.security).toMatchObject({ type: 'cron', cronExpression: '0 7 * * *', perpetual: false })
+ expect(tasks['code-quality']).toMatchObject({ type: 'on-demand', perpetual: false })
+ expect(tasks['code-quality'].cronExpression).toBeFalsy()
+ expect(tasks['test-coverage']).toMatchObject({ type: 'cron', cronExpression: '*/15 * * * *' })
+ expect(tasks.documentation).toMatchObject({ type: 'on-demand', perpetual: true, recheckCron: '0 3 * * *' })
+ // Already on the new model: left exactly as stored.
+ expect(tasks.typing).toMatchObject({ type: 'cron', cronExpression: '30 8 * * 2', perpetual: true })
})
it('should merge defaults for missing task types', async () => {
@@ -1060,7 +1112,7 @@ describe('taskSchedule', () => {
expect(result.reason).toBe('disabled')
})
- it('should run rotation tasks immediately', async () => {
+ it('normalizes a retired rotation cadence to a daily cron on read', async () => {
readJSONFile.mockResolvedValue({
version: 2,
tasks: {
@@ -1069,32 +1121,33 @@ describe('taskSchedule', () => {
executions: {}
})
- const result = await shouldRunTask('code-quality')
- expect(result.shouldRun).toBe(true)
- expect(result.reason).toBe('rotation')
+ const interval = await getTaskInterval('code-quality')
+ expect(interval).toMatchObject({ type: 'cron', cronExpression: '0 7 * * *', perpetual: false })
})
- it('should not run on-demand tasks automatically', async () => {
+ it('never auto-runs a plain on-demand task, but drains one carrying the perpetual flag', async () => {
mockSchedule({
- tasks: { 'ui-bugs': { type: 'on-demand', enabled: true, providerId: null, model: null, prompt: null } }
+ tasks: {
+ 'ui-bugs': { type: 'on-demand', enabled: true, providerId: null, model: null, prompt: null },
+ 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true, providerId: null, model: null, prompt: null }
+ }
})
- const result = await shouldRunTask('ui-bugs')
- expect(result.shouldRun).toBe(false)
- expect(result.reason).toBe('on-demand-only')
+ expect(await shouldRunTask('ui-bugs')).toMatchObject({ shouldRun: false, reason: 'on-demand-only' })
+ expect(await shouldRunTask('claim-issue')).toMatchObject({ shouldRun: true, reason: 'perpetual-drain' })
})
- it('should run once-type task on first run', async () => {
+ it('should not run on-demand tasks automatically', async () => {
mockSchedule({
- tasks: { 'accessibility': { type: 'once', enabled: true, providerId: null, model: null, prompt: null } }
+ tasks: { 'ui-bugs': { type: 'on-demand', enabled: true, providerId: null, model: null, prompt: null } }
})
- const result = await shouldRunTask('accessibility')
- expect(result.shouldRun).toBe(true)
- expect(result.reason).toBe('once-first-run')
+ const result = await shouldRunTask('ui-bugs')
+ expect(result.shouldRun).toBe(false)
+ expect(result.reason).toBe('on-demand-only')
})
- it('should not run once-type task after completion', async () => {
+ it('collapses a retired once cadence to a manual-only on-demand task, run count or not', async () => {
mockSchedule({
tasks: { 'accessibility': { type: 'once', enabled: true, providerId: null, model: null, prompt: null } },
executions: { 'task:accessibility': { lastRun: '2025-01-01T00:00:00Z', count: 1, perApp: {} } }
@@ -1102,14 +1155,15 @@ describe('taskSchedule', () => {
const result = await shouldRunTask('accessibility')
expect(result.shouldRun).toBe(false)
- expect(result.reason).toBe('once-completed')
+ // No 'once-completed' dead end — a manual trigger runs it again.
+ expect(result.reason).toBe('on-demand-only')
})
it('should skip weekday-only tasks on weekends', async () => {
getLocalParts.mockReturnValue({ dayOfWeek: 0 }) // Sunday
mockSchedule({
- tasks: { 'pr-reviewer': { type: 'custom', intervalMs: 7200000, enabled: true, weekdaysOnly: true, providerId: null, model: null, prompt: null } }
+ tasks: { 'pr-reviewer': { type: 'cron', cronExpression: '0 */2 * * *', enabled: true, weekdaysOnly: true, providerId: null, model: null, prompt: null } }
})
const result = await shouldRunTask('pr-reviewer')
@@ -1129,41 +1183,44 @@ describe('taskSchedule', () => {
expect(result.reason).toBe('disabled-for-app')
})
- it('should run daily task when enough time has passed', async () => {
+ it('runs a cron task once its slot has elapsed', async () => {
+ cronDueNow()
const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()
// Explicit runAfter: [] overrides the feature-ideas default that depends on do-replan
mockSchedule({
- tasks: { 'feature-ideas': { type: 'daily', enabled: true, providerId: null, model: null, prompt: null, runAfter: [] } },
+ tasks: { 'feature-ideas': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, providerId: null, model: null, prompt: null, runAfter: [] } },
executions: { 'task:feature-ideas': { lastRun: twoDaysAgo, count: 1, perApp: {} } }
})
const result = await shouldRunTask('feature-ideas')
expect(result.shouldRun).toBe(true)
- expect(result.reason).toContain('daily-due')
+ expect(result.reason).toBe('cron-due')
})
- it('should not run daily task when in cooldown', async () => {
+ it('holds a cron task until its next slot', async () => {
+ cronNotDueYet()
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'feature-ideas': { type: 'daily', enabled: true, providerId: null, model: null, prompt: null, runAfter: [] } },
+ tasks: { 'feature-ideas': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, providerId: null, model: null, prompt: null, runAfter: [] } },
executions: { 'task:feature-ideas': { lastRun: oneHourAgo, count: 5, perApp: {} } }
})
const result = await shouldRunTask('feature-ideas')
expect(result.shouldRun).toBe(false)
- expect(result.reason).toContain('daily-cooldown')
+ expect(result.reason).toBe('cron-cooldown')
})
it('feature-ideas waits on do-replan when do-replan is enabled', async () => {
+ cronDueNow()
const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()
// Default runAfter:['do-replan'] kicks in since the test doesn't override it
mockSchedule({
tasks: {
- 'feature-ideas': { type: 'daily', enabled: true, providerId: null, model: null, prompt: null },
- 'do-replan': { type: 'weekly', enabled: true, providerId: null, model: null, prompt: null }
+ 'feature-ideas': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, providerId: null, model: null, prompt: null },
+ 'do-replan': { type: 'cron', cronExpression: '0 7 * * 1', enabled: true, providerId: null, model: null, prompt: null }
},
executions: { 'task:feature-ideas': { lastRun: twoDaysAgo, count: 1, perApp: {} } }
})
@@ -1175,29 +1232,31 @@ describe('taskSchedule', () => {
})
it('feature-ideas runs when do-replan dependency is globally disabled', async () => {
+ cronDueNow()
const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()
// do-replan is disabled — feature-ideas would otherwise wait forever, so the dep is skipped
mockSchedule({
tasks: {
- 'feature-ideas': { type: 'daily', enabled: true, providerId: null, model: null, prompt: null },
- 'do-replan': { type: 'weekly', enabled: false, providerId: null, model: null, prompt: null }
+ 'feature-ideas': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, providerId: null, model: null, prompt: null },
+ 'do-replan': { type: 'cron', cronExpression: '0 7 * * 1', enabled: false, providerId: null, model: null, prompt: null }
},
executions: { 'task:feature-ideas': { lastRun: twoDaysAgo, count: 1, perApp: {} } }
})
const result = await shouldRunTask('feature-ideas')
expect(result.shouldRun).toBe(true)
- expect(result.reason).toContain('daily-due')
+ expect(result.reason).toBe('cron-due')
})
it('feature-ideas runs when do-replan dependency is disabled for the app', async () => {
+ cronDueNow()
const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()
mockSchedule({
tasks: {
- 'feature-ideas': { type: 'daily', enabled: true, providerId: null, model: null, prompt: null },
- 'do-replan': { type: 'weekly', enabled: true, providerId: null, model: null, prompt: null }
+ 'feature-ideas': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, providerId: null, model: null, prompt: null },
+ 'do-replan': { type: 'cron', cronExpression: '0 7 * * 1', enabled: true, providerId: null, model: null, prompt: null }
},
executions: {
'task:feature-ideas': { lastRun: twoDaysAgo, count: 1, perApp: { 'app-1': { lastRun: twoDaysAgo, count: 1 } } }
@@ -1210,7 +1269,7 @@ describe('taskSchedule', () => {
try {
const result = await shouldRunTask('feature-ideas', 'app-1')
expect(result.shouldRun).toBe(true)
- expect(result.reason).toContain('daily-due')
+ expect(result.reason).toBe('cron-due')
} finally {
if (originalIsTaskTypeEnabledForApp) {
isTaskTypeEnabledForApp.mockImplementation(originalIsTaskTypeEnabledForApp)
@@ -1221,11 +1280,12 @@ describe('taskSchedule', () => {
})
it('feature-ideas ignores an enabled on-demand do-replan dependency', async () => {
+ cronDueNow()
const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()
mockSchedule({
tasks: {
- 'feature-ideas': { type: 'daily', enabled: true, providerId: null, model: null, prompt: null },
+ 'feature-ideas': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, providerId: null, model: null, prompt: null },
'do-replan': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null }
},
executions: { 'task:feature-ideas': { lastRun: twoDaysAgo, count: 1, perApp: {} } }
@@ -1233,17 +1293,18 @@ describe('taskSchedule', () => {
const result = await shouldRunTask('feature-ideas')
expect(result.shouldRun).toBe(true)
- expect(result.reason).toContain('daily-due')
+ expect(result.reason).toBe('cron-due')
})
it('feature-ideas runs when do-replan has run since its last run', async () => {
+ cronDueNow()
const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()
const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString()
mockSchedule({
tasks: {
- 'feature-ideas': { type: 'daily', enabled: true, providerId: null, model: null, prompt: null },
- 'do-replan': { type: 'weekly', enabled: true, providerId: null, model: null, prompt: null }
+ 'feature-ideas': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, providerId: null, model: null, prompt: null },
+ 'do-replan': { type: 'cron', cronExpression: '0 7 * * 1', enabled: true, providerId: null, model: null, prompt: null }
},
executions: {
'task:feature-ideas': { lastRun: twoDaysAgo, count: 1, perApp: {} },
@@ -1253,7 +1314,7 @@ describe('taskSchedule', () => {
const result = await shouldRunTask('feature-ideas')
expect(result.shouldRun).toBe(true)
- expect(result.reason).toContain('daily-due')
+ expect(result.reason).toBe('cron-due')
})
describe('cron catch-up', () => {
@@ -1353,17 +1414,20 @@ describe('taskSchedule', () => {
describe('getDueTasks', () => {
it('should return empty array when no tasks are enabled', async () => {
mockSchedule({
- tasks: { 'security': { type: 'weekly', enabled: false, providerId: null, model: null, prompt: null } }
+ tasks: { ...PAUSED_SHIPPED_DRAINS, 'security': { type: 'cron', cronExpression: '0 7 * * 1', enabled: false, providerId: null, model: null, prompt: null } }
})
const due = await getDueTasks()
expect(due).toEqual([])
})
- it('should return enabled rotation tasks', async () => {
+ 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: {
- 'code-quality': { type: 'rotation', enabled: true, providerId: null, model: null, prompt: null },
- 'security': { type: 'weekly', enabled: false, providerId: null, model: null, prompt: null }
+ ...PAUSED_SHIPPED_DRAINS,
+ 'code-quality': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, providerId: null, model: null, prompt: null },
+ 'security': { type: 'cron', cronExpression: '0 7 * * 1', enabled: false, providerId: null, model: null, prompt: null }
}
})
@@ -1376,50 +1440,39 @@ describe('taskSchedule', () => {
describe('getNextTaskType', () => {
it('should return null when no tasks are enabled', async () => {
mockSchedule({
- tasks: { 'security': { type: 'weekly', enabled: false, providerId: null, model: null, prompt: null } }
+ tasks: { ...PAUSED_SHIPPED_DRAINS, 'security': { type: 'cron', cronExpression: '0 7 * * 1', enabled: false, providerId: null, model: null, prompt: null } }
})
const result = await getNextTaskType()
expect(result).toBeNull()
})
- it('should return rotation task', async () => {
+ it('returns null when only on-demand tasks are enabled — nothing is auto-queued', async () => {
mockSchedule({
tasks: {
- 'code-quality': { type: 'rotation', enabled: true, providerId: null, model: null, prompt: null },
- 'error-handling': { type: 'rotation', enabled: true, providerId: null, model: null, prompt: null }
+ ...PAUSED_SHIPPED_DRAINS,
+ 'code-quality': { type: 'on-demand', enabled: true, providerId: null, model: null, prompt: null },
+ 'error-handling': { type: 'on-demand', enabled: true, providerId: null, model: null, prompt: null }
}
})
- const result = await getNextTaskType()
- expect(result).toBeDefined()
- expect(result.reason).toBe('rotation')
- })
-
- it('should rotate to next task after last type', async () => {
- mockSchedule({
- tasks: {
- 'code-quality': { type: 'rotation', enabled: true, providerId: null, model: null, prompt: null },
- 'error-handling': { type: 'rotation', enabled: true, providerId: null, model: null, prompt: null }
- }
- })
-
- const result = await getNextTaskType(null, 'code-quality')
- expect(result.taskType).toBe('error-handling')
+ expect(await getNextTaskType()).toBeNull()
})
- it('does not select a feature-disabled rotation task', async () => {
+ 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: {
- 'jira-sprint-manager': { type: INTERVAL_TYPES.ROTATION, enabled: true },
+ ...PAUSED_SHIPPED_DRAINS,
+ 'jira-sprint-manager': { type: INTERVAL_TYPES.CRON, cronExpression: '0 7 * * *', enabled: true },
} })
expect(await getNextTaskType()).toBeNull()
})
- 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.
+ it('prefers a due cron task over an always-ready perpetual drain', async () => {
+ // 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)
@@ -1431,7 +1484,8 @@ describe('taskSchedule', () => {
mockSchedule({
tasks: {
- 'code-quality': { type: 'weekly', enabled: true, providerId: null, model: null, prompt: null, runAfter: [] },
+ ...PAUSED_SHIPPED_DRAINS,
+ 'code-quality': { type: 'on-demand', perpetual: true, enabled: true, providerId: null, model: null, prompt: null, runAfter: [] },
'plan-task': { type: 'cron', enabled: true, cronExpression: '0 9 * * *', providerId: null, model: null, prompt: null, createdAt: yesterdayNineAm.toISOString() }
}
})
@@ -1455,8 +1509,9 @@ describe('taskSchedule', () => {
mockSchedule({
tasks: {
+ ...PAUSED_SHIPPED_DRAINS,
'pr-watcher': { type: 'cron', enabled: true, cronExpression: '0 9 * * *', providerId: null, model: null, prompt: null, createdAt: yesterdayNineAm.toISOString() },
- 'claim-issue': { type: 'perpetual', enabled: true, providerId: null, model: null, prompt: null }
+ 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true, providerId: null, model: null, prompt: null }
}
})
@@ -1465,20 +1520,23 @@ describe('taskSchedule', () => {
expect(unconstrained.taskType).toBe('pr-watcher')
// perpetualOnly: the perpetual drain is returned instead.
- const constrained = await getNextTaskType(null, '', { perpetualOnly: true })
+ const constrained = await getNextTaskType(null, { perpetualOnly: true })
expect(constrained).not.toBeNull()
expect(constrained.taskType).toBe('claim-issue')
expect(constrained.reason).toBe('perpetual-drain')
})
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: {
- 'code-quality': { type: 'rotation', enabled: true, providerId: null, model: null, prompt: null },
- 'error-handling': { type: 'rotation', enabled: true, providerId: null, model: null, prompt: null }
+ ...PAUSED_SHIPPED_DRAINS,
+ 'code-quality': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, providerId: null, model: null, prompt: null },
+ 'error-handling': { type: 'on-demand', enabled: true, providerId: null, model: null, prompt: null }
}
})
- const result = await getNextTaskType(null, '', { perpetualOnly: true })
+ const result = await getNextTaskType(null, { perpetualOnly: true })
expect(result).toBeNull()
})
})
@@ -2039,10 +2097,10 @@ describe('taskSchedule', () => {
// park + convergence signature + dispatch counter for a human and MUST NOT for
// a refill — that reset is what let branch-reconcile re-dispatch all night.
it('stamps origin: user by default and refill when the drain re-issues itself', async () => {
- mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } } })
+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true } } })
expect((await triggerOnDemandTask('branch-reconcile', 'app-1')).origin).toBe(ON_DEMAND_ORIGINS.USER)
- mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } } })
+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true } } })
const refill = await triggerOnDemandTask('branch-reconcile', 'app-1', { emit: false, origin: ON_DEMAND_ORIGINS.REFILL })
expect(refill.origin).toBe(ON_DEMAND_ORIGINS.REFILL)
})
@@ -2051,7 +2109,7 @@ describe('taskSchedule', () => {
// operator action; the perpetual drain re-issues itself through this same
// lane, and logging that would fill the ledger with events nobody performed.
it('records a cos.schedule.trigger row for a human Run Now, and none for a refill', async () => {
- mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } } })
+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true } } })
const request = await triggerOnDemandTask('branch-reconcile', 'app-1')
expect(recordUserAction).toHaveBeenCalledTimes(1)
@@ -2066,13 +2124,13 @@ describe('taskSchedule', () => {
expect(recordUserAction.mock.calls[0][0].actor).toBeUndefined()
recordUserAction.mockClear()
- mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } } })
+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true } } })
await triggerOnDemandTask('branch-reconcile', 'app-1', { emit: false, origin: ON_DEMAND_ORIGINS.REFILL })
expect(recordUserAction).not.toHaveBeenCalled()
})
it('records nothing when the trigger is refused', async () => {
- mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: false } } })
+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: false } } })
expect((await triggerOnDemandTask('branch-reconcile', 'app-1')).error).toMatch(/disabled/i)
expect(recordUserAction).not.toHaveBeenCalled()
})
@@ -2081,7 +2139,7 @@ describe('taskSchedule', () => {
// loop got in. One home, so the three queue consumers can't drift on it.
describe('applyOnDemandRunResets', () => {
const parked = (extra = {}) => ({
- tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } },
+ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: {
'app-1': {
lastRun: null, count: 0,
@@ -2211,7 +2269,7 @@ describe('taskSchedule', () => {
describe('shouldRunTask', () => {
it('is due (drain) when enabled and not parked', async () => {
- mockSchedule({ tasks: { 'claim-issue': { type: 'perpetual', enabled: true } } })
+ mockSchedule({ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } } })
const result = await shouldRunTask('claim-issue')
expect(result.shouldRun).toBe(true)
expect(result.reason).toBe('perpetual-drain')
@@ -2220,7 +2278,7 @@ describe('taskSchedule', () => {
it('is NOT due while parked in the future', async () => {
const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {}, parkedUntil: future, parkReason: 'no-actionable-issues', parkActionableCount: 0 } }
})
const result = await shouldRunTask('claim-issue')
@@ -2233,7 +2291,7 @@ describe('taskSchedule', () => {
it('becomes due again (recheck) once the park elapses', async () => {
const past = new Date(Date.now() - 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {}, parkedUntil: past } }
})
const result = await shouldRunTask('claim-issue')
@@ -2245,7 +2303,7 @@ describe('taskSchedule', () => {
isTaskTypeEnabledForApp.mockResolvedValue(true)
const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, parkedUntil: future } } } }
})
const result = await shouldRunTask('claim-issue', 'app-1')
@@ -2255,11 +2313,13 @@ describe('taskSchedule', () => {
})
describe('getNextTaskType', () => {
- it('prioritizes a draining perpetual task over a due daily task', async () => {
+ it('picks a draining perpetual task when no cron task is due', async () => {
+ cronNotDueYet()
mockSchedule({
tasks: {
- 'claim-issue': { type: 'perpetual', enabled: true },
- 'security': { type: 'daily', enabled: true }
+ ...PAUSED_SHIPPED_DRAINS,
+ 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true },
+ 'security': { type: 'cron', cronExpression: '0 7 * * *', enabled: true }
}
})
const next = await getNextTaskType()
@@ -2267,18 +2327,48 @@ describe('taskSchedule', () => {
expect(next.reason).toBe('perpetual-drain')
})
- it('does not pick a parked perpetual task — yields to the daily', async () => {
+ it('does not pick a parked perpetual task — yields to the due cron task', async () => {
+ cronDueNow()
const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
mockSchedule({
tasks: {
- 'claim-issue': { type: 'perpetual', enabled: true },
- 'security': { type: 'daily', enabled: true }
+ ...PAUSED_SHIPPED_DRAINS,
+ 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true },
+ 'security': { type: 'cron', cronExpression: '0 7 * * *', enabled: true }
},
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {}, parkedUntil: future } }
})
const next = await getNextTaskType()
expect(next.taskType).toBe('security')
})
+
+ it('a cron+perpetual task parks on its own expression and stays out of the pick', async () => {
+ cronDueNow()
+ const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
+ mockSchedule({
+ tasks: {
+ ...PAUSED_SHIPPED_DRAINS,
+ 'claim-issue': { type: 'cron', cronExpression: '0 7 * * *', perpetual: true, enabled: true }
+ },
+ executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {}, parkedUntil: future } }
+ })
+ // The cron slot is due, but the park outranks it — the drain is idle.
+ expect(await shouldRunTask('claim-issue')).toMatchObject({ shouldRun: false, reason: 'perpetual-parked' })
+ expect(await getNextTaskType()).toBeNull()
+ })
+
+ it('an ELAPSED park makes a cron+perpetual task due immediately, without waiting for the next slot', async () => {
+ cronNotDueYet()
+ const past = new Date(Date.now() - 60 * 1000).toISOString()
+ mockSchedule({
+ tasks: {
+ ...PAUSED_SHIPPED_DRAINS,
+ 'claim-issue': { type: 'cron', cronExpression: '0 7 * * *', perpetual: true, enabled: true }
+ },
+ executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {}, parkedUntil: past } }
+ })
+ expect(await shouldRunTask('claim-issue')).toMatchObject({ shouldRun: true, reason: 'perpetual-recheck' })
+ })
})
// Perpetual tasks park PER-APP, so the global shouldRunTask always reads
@@ -2298,7 +2388,7 @@ describe('taskSchedule', () => {
const nineAm = new Date('2026-01-02T09:00:00Z') // next 9am (future, well past `soon`)
const soon = new Date(Date.now() + 30 * 60 * 1000).toISOString() // 30m out
mockSchedule({
- tasks: { 'claim-issue': { type: 'perpetual', enabled: true, recheckCron: '0 9 * * *' } },
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true, recheckCron: '0 9 * * *' } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
'app-1': { lastRun: null, count: 0, parkedUntil: nineAm.toISOString() },
'app-2': { lastRun: null, count: 0, parkedUntil: soon }
@@ -2317,7 +2407,7 @@ describe('taskSchedule', () => {
const past = new Date(Date.now() - 60 * 1000).toISOString()
const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'claim-issue': { type: 'perpetual', enabled: true, recheckCron: '0 9 * * *' } },
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true, recheckCron: '0 9 * * *' } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
'app-1': { lastRun: null, count: 0, parkedUntil: past }, // recheck due now
'app-2': { lastRun: null, count: 0, parkedUntil: future }
@@ -2332,7 +2422,7 @@ describe('taskSchedule', () => {
it('treats an app mid-drain (park cleared) as ready even if a sibling app is parked', async () => {
const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
'app-1': { lastRun: null, count: 0 }, // no park → draining
'app-2': { lastRun: null, count: 0, parkedUntil: future }
@@ -2344,7 +2434,7 @@ describe('taskSchedule', () => {
})
it('keeps the global ready default for a never-run perpetual task (no per-app records)', async () => {
- mockSchedule({ tasks: { 'claim-issue': { type: 'perpetual', enabled: true } } })
+ mockSchedule({ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } } })
const upcoming = await getUpcomingTasks(50)
const claim = upcoming.find(t => t.taskType === 'claim-issue')
expect(claim.status).toBe('ready')
@@ -2353,7 +2443,7 @@ describe('taskSchedule', () => {
describe('parkPerpetual / perpetual park state', () => {
it('parkPerpetual stamps parkedUntil + reason on the per-app record', async () => {
- mockSchedule({ tasks: { 'claim-issue': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } } })
+ mockSchedule({ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } } })
const record = await parkPerpetual('claim-issue', 'app-1', { reason: 'no-actionable-issues', actionableCount: 0, counts: { open: 40, inFlight: 2, filtered: 38 } })
expect(record.parkedUntil).toBeTruthy()
expect(record.parkReason).toBe('no-actionable-issues')
@@ -2364,7 +2454,7 @@ describe('taskSchedule', () => {
it('getPerpetualParkInfo reads back the park record (and null when not parked)', async () => {
const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
'app-1': { lastRun: null, count: 0, parkedUntil: future, parkReason: 'no-actionable-issues', parkActionableCount: 0, parkCounts: { open: 40, inFlight: 2, filtered: 38 } },
'app-2': { lastRun: null, count: 0 }
@@ -2384,7 +2474,7 @@ describe('taskSchedule', () => {
const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
const past = new Date(Date.now() - 60 * 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
'app-parked': { lastRun: null, count: 0, parkedUntil: future },
'app-elapsed': { lastRun: null, count: 0, parkedUntil: past },
@@ -2406,7 +2496,7 @@ describe('taskSchedule', () => {
// sibling test leaves it returning a year-2999 date.)
it('parkPerpetual honours notLaterThan when the hold lifts before the recheck', async () => {
parseCronToNextRun.mockReturnValue(null)
- mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 7 * 24 * 3600000 } } })
+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 7 * 24 * 3600000 } } })
const soon = new Date(Date.now() + 60 * 60 * 1000).toISOString()
const record = await parkPerpetual('branch-reconcile', 'app-1', {
reason: 'merged-branches-held-back', actionableCount: 0, signature: null,
@@ -2423,7 +2513,7 @@ describe('taskSchedule', () => {
it('parkPerpetual publishes the SHORTENED time on the parked event, not the raw cadence', async () => {
parseCronToNextRun.mockReturnValue(null)
cosEvents.emit.mockClear()
- mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 7 * 24 * 3600000 } } })
+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 7 * 24 * 3600000 } } })
const soon = new Date(Date.now() + 60 * 60 * 1000).toISOString()
const record = await parkPerpetual('branch-reconcile', 'app-1', {
reason: 'merged-branches-held-back', actionableCount: 0, signature: null, notLaterThan: soon
@@ -2441,7 +2531,7 @@ describe('taskSchedule', () => {
parseCronToNextRun.mockReturnValue(null)
const soon = new Date(Date.now() + 60 * 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } },
+ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } },
executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: {
'app-1': { lastRun: null, count: 0, parkedUntil: soon, parkNotLaterThan: soon, parkReason: 'merged-branches-held-back' }
} } }
@@ -2453,14 +2543,14 @@ describe('taskSchedule', () => {
it('parkPerpetual drops parkNotLaterThan when no bound is given', async () => {
parseCronToNextRun.mockReturnValue(null)
- mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } } })
+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } } })
const record = await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-in-flight-branches', actionableCount: 0, signature: null })
expect(record.parkNotLaterThan).toBeUndefined()
})
it('parkPerpetual ignores a notLaterThan that is later than the recheck', async () => {
parseCronToNextRun.mockReturnValue(null)
- mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } } })
+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } } })
const far = new Date(Date.now() + 30 * 24 * 3600000).toISOString()
const record = await parkPerpetual('branch-reconcile', 'app-1', {
reason: 'merged-branches-held-back', actionableCount: 0, signature: null, notLaterThan: far
@@ -2471,7 +2561,7 @@ describe('taskSchedule', () => {
})
it('parkPerpetual omits parkCounts when no breakdown is provided', async () => {
- mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } } })
+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } } })
const record = await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-in-flight-branches', actionableCount: 0, signature: null })
expect(record.parkCounts).toBeUndefined()
})
@@ -2483,7 +2573,7 @@ describe('taskSchedule', () => {
it('recordPerpetualDispatch clears an existing park as it spends a dispatch', async () => {
const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
'app-1': { lastRun: null, count: 0, parkedUntil: future, parkReason: 'no-actionable-issues', perpetualDispatchCount: 2 }
} } }
@@ -2496,7 +2586,7 @@ describe('taskSchedule', () => {
it('resetPerpetualForManualRun drops the park, the convergence signature, AND the dispatch count', async () => {
const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } },
+ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: {
'app-1': { lastRun: null, count: 0, parkedUntil: future, parkReason: 'no-progress', lastActionableSignature: 'a:NEEDS_PR:none', perpetualDispatchCount: 4 }
} } }
@@ -2515,7 +2605,7 @@ describe('taskSchedule', () => {
it('getPerpetualDrainState reads both brakes in one pass (and defaults them)', async () => {
mockSchedule({
- tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } },
+ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: {
'app-1': { lastRun: null, count: 0, lastActionableSignature: 'sig-1', perpetualDispatchCount: 3 }
} } }
@@ -2528,7 +2618,7 @@ describe('taskSchedule', () => {
it('recordPerpetualDispatch drops the park, records the signature, and spends one dispatch in ONE write', async () => {
const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } },
+ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: {
'app-1': { lastRun: null, count: 0, parkedUntil: future, parkReason: 'no-progress', perpetualDispatchCount: 2 }
} } }
@@ -2556,7 +2646,7 @@ describe('taskSchedule', () => {
// CHANGED set, so it resets to 1.
it('recordPerpetualDispatch resets signatureRepeatCount for the new signature', async () => {
mockSchedule({
- tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } },
+ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: {
'app-1': { lastRun: null, count: 0, lastActionableSignature: 'old-sig', signatureRepeatCount: 4 }
} } }
@@ -2571,7 +2661,7 @@ describe('taskSchedule', () => {
// future park path can forget, and a stale count caps the NEXT drain early.
it('parkPerpetual clears the dispatch budget when handed dispatchCount: 0', async () => {
mockSchedule({
- tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } },
+ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } },
executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, perpetualDispatchCount: 4 } } } }
})
await parkPerpetual('branch-reconcile', 'app-1', { reason: 'drain-cap', actionableCount: 2, signature: null, dispatchCount: 0 })
@@ -2588,7 +2678,7 @@ describe('taskSchedule', () => {
// the next window to cap early on a spend it never made.
it('parkPerpetual zeroes the dispatch budget even when the caller omits dispatchCount', async () => {
mockSchedule({
- tasks: { 'claim-issue': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } },
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, perpetualDispatchCount: 4 } } } }
})
await parkPerpetual('claim-issue', 'app-1', { reason: 'churn-detected', actionableCount: 12 })
@@ -2598,14 +2688,14 @@ describe('taskSchedule', () => {
it('resetPerpetualForManualRun is a no-op (false) when nothing is cached', async () => {
mockSchedule({
- tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0 } } } }
})
expect(await resetPerpetualForManualRun('claim-issue', 'app-1')).toBe(false)
})
it('parkPerpetual stores the actionable signature it parked on', async () => {
- mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } } })
+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } } })
await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-progress', actionableCount: 2, signature: 'a:NEEDS_PR:none|b:IN_REVIEW:5' })
const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
expect(saved.executions['task:branch-reconcile'].perApp['app-1'].lastActionableSignature).toBe('a:NEEDS_PR:none|b:IN_REVIEW:5')
@@ -2613,7 +2703,7 @@ describe('taskSchedule', () => {
it('parkPerpetual with signature:null clears a prior signature (idle park)', async () => {
mockSchedule({
- tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } },
+ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } },
executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, lastActionableSignature: 'old-sig' } } } }
})
await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-in-flight-branches', actionableCount: 0, signature: null })
@@ -2623,7 +2713,7 @@ describe('taskSchedule', () => {
it('parkPerpetual increments signatureRepeatCount when the same finding is parked again', async () => {
mockSchedule({
- tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } },
+ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } },
executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, lastActionableSignature: 'a:NEEDS_PR:none' } } } }
})
await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-progress', actionableCount: 1, signature: 'a:NEEDS_PR:none' })
@@ -2634,7 +2724,7 @@ describe('taskSchedule', () => {
it('parkPerpetual resets signatureRepeatCount when the finding changes', async () => {
mockSchedule({
- tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } },
+ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } },
executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, lastActionableSignature: 'old', signatureRepeatCount: 6 } } } }
})
await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-progress', actionableCount: 1, signature: 'new' })
@@ -2772,9 +2862,9 @@ describe('taskSchedule', () => {
expect(removeByMetadata).toHaveBeenCalledWith('failureParkKey', 'security:app-1')
})
- it('shouldRunTask returns failure-parked for a parked ROTATION type', async () => {
+ it('shouldRunTask returns failure-parked for a parked type', async () => {
mockSchedule({
- tasks: { security: { type: 'rotation', enabled: true } },
+ tasks: { security: { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:security': { lastRun: null, count: 0, perApp: {
'app-1': { lastRun: null, count: 0, consecutiveFailures: FAILURE_PARK_THRESHOLD, failureParkedAt: new Date().toISOString(), failureParkReason: 'auth-error' }
} } }
@@ -2785,10 +2875,10 @@ describe('taskSchedule', () => {
expect(res.failureParkReason).toBe('auth-error')
})
- it('shouldRunTask applies escalating failure-cooldown to ROTATION (otherwise always-run)', async () => {
+ it('shouldRunTask applies escalating failure-cooldown to an otherwise always-run perpetual drain', async () => {
// 2 consecutive failures → backoff = base*4; last failure just now → in cooldown.
mockSchedule({
- tasks: { security: { type: 'rotation', enabled: true } },
+ tasks: { security: { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:security': { lastRun: null, count: 0, perApp: {
'app-1': { lastRun: null, count: 0, consecutiveFailures: 2, lastFailureAt: new Date().toISOString(), lastErrorCategory: 'timeout' }
} } }
@@ -2800,18 +2890,18 @@ describe('taskSchedule', () => {
expect(res.failureBackoffMs).toBe(FAILURE_BACKOFF_BASE_MS * 4)
})
- it('shouldRunTask lets ROTATION run once the failure-cooldown has elapsed', async () => {
+ it('shouldRunTask lets a perpetual drain run once the failure-cooldown has elapsed', async () => {
// 1 failure → backoff = base*2; last failure long ago → cooldown elapsed.
const longAgo = new Date(Date.now() - (FAILURE_BACKOFF_CAP_MS + 60_000)).toISOString()
mockSchedule({
- tasks: { security: { type: 'rotation', enabled: true } },
+ tasks: { security: { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:security': { lastRun: null, count: 0, perApp: {
'app-1': { lastRun: null, count: 0, consecutiveFailures: 1, lastFailureAt: longAgo }
} } }
})
const res = await shouldRunTask('security', 'app-1')
expect(res.shouldRun).toBe(true)
- expect(res.reason).toBe('rotation')
+ expect(res.reason).toBe('perpetual-drain')
})
it('updateTaskInterval clears the failure ledger (config-change unpark)', async () => {
@@ -2835,7 +2925,7 @@ describe('taskSchedule', () => {
it('re-derives an existing park when the recheck cadence changes', async () => {
const farFuture = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'claim-issue': { type: 'perpetual', enabled: true, recheckIntervalMs: 30 * 24 * 60 * 60 * 1000 } },
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 30 * 24 * 60 * 60 * 1000 } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, parkedUntil: farFuture } } } }
})
await updateTaskInterval('claim-issue', { recheckIntervalMs: 1000 })
@@ -2848,7 +2938,7 @@ describe('taskSchedule', () => {
it('does not create a park when none exists', async () => {
mockSchedule({
- tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0 } } } }
})
await updateTaskInterval('claim-issue', { recheckIntervalMs: 1000 })
@@ -2865,7 +2955,7 @@ describe('taskSchedule', () => {
const soon = new Date(Date.now() + 60 * 1000).toISOString()
const elapsed = new Date(Date.now() - 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'claim-issue': { type: 'perpetual', enabled: true, recheckIntervalMs: 60 * 1000 } },
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 60 * 1000 } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
'app-future': { lastRun: null, count: 0, parkedUntil: soon },
'app-elapsed': { lastRun: null, count: 0, parkedUntil: elapsed }
@@ -2889,17 +2979,17 @@ describe('taskSchedule', () => {
})
describe('getScheduleStatus per-app park aggregate', () => {
- it('aggregates per-app parks into taskStatus.perpetual', async () => {
+ it('aggregates per-app parks into taskStatus.perpetualStatus', async () => {
const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
'app-1': { lastRun: null, count: 0, parkedUntil: future, parkReason: 'no-actionable-issues' },
'app-2': { lastRun: null, count: 0 }
} } }
})
const status = await getScheduleStatus()
- const p = status.tasks['claim-issue'].perpetual
+ const p = status.tasks['claim-issue'].perpetualStatus
expect(p).toMatchObject({ parkedAppCount: 1, trackedAppCount: 2, globalParked: false, nextRecheckAt: future, parkReason: 'no-actionable-issues' })
})
})
@@ -2911,7 +3001,7 @@ describe('taskSchedule', () => {
// hadn't elapsed; eligibility folded in any global record carrying a park).
describe('perpetual park aggregate — getScheduleStatus and getUpcomingTasks agree', () => {
const perpetualOf = async (taskType = 'claim-issue') =>
- (await getScheduleStatus()).tasks[taskType].perpetual
+ (await getScheduleStatus()).tasks[taskType].perpetualStatus
const upcomingOf = async (taskType = 'claim-issue') =>
(await getUpcomingTasks(50)).find(t => t.taskType === taskType)
@@ -2919,7 +3009,7 @@ describe('taskSchedule', () => {
const soon = new Date(Date.now() + 30 * 60 * 1000).toISOString()
const later = new Date(Date.now() + 6 * 60 * 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
'app-1': { lastRun: null, count: 0, parkedUntil: later, parkReason: 'no-actionable-issues' },
'app-2': { lastRun: null, count: 0, parkedUntil: soon, parkReason: 'no-progress' }
@@ -2936,7 +3026,7 @@ describe('taskSchedule', () => {
const past = new Date(Date.now() - 60 * 1000).toISOString()
const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
'app-1': { lastRun: null, count: 0, parkedUntil: past, parkReason: 'stale' },
'app-2': { lastRun: null, count: 0, parkedUntil: future, parkReason: 'no-actionable-issues' }
@@ -2951,7 +3041,7 @@ describe('taskSchedule', () => {
it('an own-parked GLOBAL record (no per-app) is a tracked scope for both', async () => {
const future = new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {}, parkedUntil: future, parkReason: 'no-actionable-issues' } }
})
const p = await perpetualOf()
@@ -2964,7 +3054,7 @@ describe('taskSchedule', () => {
it('an ELAPSED global park is due now for both (no lingering nextRecheckAt)', async () => {
const past = new Date(Date.now() - 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {}, parkedUntil: past, parkReason: 'no-actionable-issues' } }
})
const p = await perpetualOf()
@@ -2977,7 +3067,7 @@ describe('taskSchedule', () => {
const globalPark = new Date(Date.now() + 10 * 60 * 1000).toISOString()
const appPark = new Date(Date.now() + 60 * 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, parkedUntil: globalPark, parkReason: 'global-idle', perApp: {
'app-1': { lastRun: null, count: 0, parkedUntil: appPark, parkReason: 'no-actionable-issues' }
} } }
@@ -2991,7 +3081,7 @@ describe('taskSchedule', () => {
})
it('no tracked scope at all: status reports nothing parked and upcoming stays ready', async () => {
- mockSchedule({ tasks: { 'claim-issue': { type: 'perpetual', enabled: true } } })
+ mockSchedule({ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } } })
const p = await perpetualOf()
const claim = await upcomingOf()
expect(p).toMatchObject({ globalParked: false, parkedAppCount: 0, trackedAppCount: 0, nextRecheckAt: null, parkReason: null })
diff --git a/server/services/taskScheduleConstants.js b/server/services/taskScheduleConstants.js
index 5c60f9d2c5..c30aab0824 100644
--- a/server/services/taskScheduleConstants.js
+++ b/server/services/taskScheduleConstants.js
@@ -1,19 +1,38 @@
/** Dependency-free task scheduling constants shared by registry and runtime modules. */
-const HOUR_MS = 60 * 60 * 1000;
+const MINUTE_MS = 60 * 1000;
+const HOUR_MS = 60 * MINUTE_MS;
const DAY_MS = 24 * HOUR_MS;
+/**
+ * The cadence model is exactly two variants. `perpetual` is an ORTHOGONAL
+ * boolean on the same record, not a type — so a task can be on-demand+perpetual
+ * (drain whenever unparked) or cron+perpetual (a cron slot INITIATES a drain,
+ * and the same expression gates the next attempt once it parks).
+ */
export const INTERVAL_TYPES = {
+ ON_DEMAND: 'on-demand',
+ CRON: 'cron'
+};
+
+/**
+ * Retired cadence types. Kept for the legacy decoder below (and migration 335)
+ * so a schedule written by an older install — or by a peer machine still on the
+ * previous release — normalizes instead of falling through as "unknown".
+ */
+export const LEGACY_INTERVAL_TYPES = {
ROTATION: 'rotation',
DAILY: 'daily',
WEEKLY: 'weekly',
ONCE: 'once',
- ON_DEMAND: 'on-demand',
CUSTOM: 'custom',
- CRON: 'cron',
PERPETUAL: 'perpetual'
};
+/** Conservative daily/weekly replacements for the retired named cadences. */
+export const DEFAULT_DAILY_CRON = '0 7 * * *';
+export const DEFAULT_WEEKLY_CRON = '0 7 * * 1';
+
export const WEEK = 7 * DAY_MS;
export const DEFAULT_PERPETUAL_RECHECK_MS = DAY_MS;
export const FAILURE_BACKOFF_BASE_MS = HOUR_MS;
@@ -23,3 +42,94 @@ export const ON_DEMAND_ORIGINS = { USER: 'user', REFILL: 'refill' };
export const isRefillRequest = (request) => request?.origin === ON_DEMAND_ORIGINS.REFILL;
const RECONCILE_DRAIN_TASK_TYPES = new Set(['branch-reconcile', 'issue-reconcile']);
export const isReconcileDrainTaskType = (taskType) => RECONCILE_DRAIN_TASK_TYPES.has(taskType);
+
+/** A 5-field cron expression (the only string cadence the scheduler accepts). */
+export function isCronExpression(value) {
+ return typeof value === 'string' && value.trim().split(/\s+/).length === 5;
+}
+
+/**
+ * Approximate a numeric interval as a 5-field cron expression. Used by the
+ * `custom` → `cron` conversion (migration + runtime normalization) and by the
+ * Layered Intelligence per-app cadence picker, which offers sub-daily slots the
+ * named cadences never expressed.
+ */
+export function cronFromIntervalMs(intervalMs) {
+ const ms = Number(intervalMs);
+ if (!Number.isFinite(ms) || ms <= 0) return DEFAULT_DAILY_CRON;
+ if (ms === WEEK) return DEFAULT_WEEKLY_CRON;
+ if (ms >= DAY_MS) return DEFAULT_DAILY_CRON;
+ if (ms >= HOUR_MS) {
+ const hours = Math.round(ms / HOUR_MS);
+ if (hours <= 1) return '0 * * * *';
+ // Only an even divisor of 24 lays out evenly across a day; anything else
+ // would fire twice around midnight, so clamp to the nearest usable step.
+ const step = [2, 3, 4, 6, 8, 12].find((h) => h >= hours) || 12;
+ return `0 */${step} * * *`;
+ }
+ const minutes = Math.min(59, Math.max(1, Math.round(ms / MINUTE_MS)));
+ return `*/${minutes} * * * *`;
+}
+
+/** Every cadence value the system has ever accepted as a type name. */
+export const isKnownIntervalType = (value) =>
+ Object.values(INTERVAL_TYPES).includes(value) || Object.values(LEGACY_INTERVAL_TYPES).includes(value);
+
+/**
+ * Decode ANY historical cadence value into the two-variant model.
+ *
+ * Accepts a legacy type name, a raw cron expression, or a current type, and
+ * returns `{ type, cronExpression, perpetual }` — `cronExpression` is null when
+ * the decoded type is on-demand. `intervalMs` feeds the `custom` conversion.
+ * Unknown/absent values decode to on-demand (never auto-running), which is the
+ * safe default for a cadence we cannot read.
+ */
+export function decodeIntervalType(value, { intervalMs = null } = {}) {
+ if (isCronExpression(value)) {
+ return { type: INTERVAL_TYPES.CRON, cronExpression: value.trim(), perpetual: false };
+ }
+ switch (value) {
+ case INTERVAL_TYPES.CRON:
+ return { type: INTERVAL_TYPES.CRON, cronExpression: null, perpetual: false };
+ case LEGACY_INTERVAL_TYPES.DAILY:
+ case LEGACY_INTERVAL_TYPES.ROTATION:
+ return { type: INTERVAL_TYPES.CRON, cronExpression: DEFAULT_DAILY_CRON, perpetual: false };
+ case LEGACY_INTERVAL_TYPES.WEEKLY:
+ return { type: INTERVAL_TYPES.CRON, cronExpression: DEFAULT_WEEKLY_CRON, perpetual: false };
+ case LEGACY_INTERVAL_TYPES.CUSTOM:
+ return { type: INTERVAL_TYPES.CRON, cronExpression: cronFromIntervalMs(intervalMs), perpetual: false };
+ case LEGACY_INTERVAL_TYPES.PERPETUAL:
+ return { type: INTERVAL_TYPES.ON_DEMAND, cronExpression: null, perpetual: true };
+ default:
+ // 'once', 'on-demand', and anything unrecognized.
+ return { type: INTERVAL_TYPES.ON_DEMAND, cronExpression: null, perpetual: false };
+ }
+}
+
+/**
+ * Normalize a persisted task config IN PLACE onto the two-variant model.
+ * Returns true when something changed, so callers (loadSchedule, the migration)
+ * can decide whether the normalized shape needs persisting.
+ *
+ * A `perpetual: true` already on the record is preserved — the flag is
+ * orthogonal, so it survives whatever the type decodes to.
+ */
+export function normalizeIntervalConfig(config) {
+ if (!config || typeof config !== 'object') return false;
+ const decoded = decodeIntervalType(config.type, { intervalMs: config.intervalMs });
+ const perpetual = config.perpetual === true || decoded.perpetual;
+ // Keep an already-valid cron expression; only supply one when the decode had
+ // to invent the cadence (a retired named type) or the stored one is unusable.
+ const cronExpression = decoded.type === INTERVAL_TYPES.CRON
+ ? (isCronExpression(config.cronExpression) ? config.cronExpression.trim() : decoded.cronExpression)
+ : null;
+
+ let changed = false;
+ if (config.type !== decoded.type) { config.type = decoded.type; changed = true; }
+ if (config.perpetual !== perpetual) { config.perpetual = perpetual; changed = true; }
+ if ((config.cronExpression ?? null) !== (cronExpression ?? null)) {
+ config.cronExpression = cronExpression;
+ changed = true;
+ }
+ return changed;
+}
diff --git a/server/services/taskScheduleRegistry.js b/server/services/taskScheduleRegistry.js
index c2b361bcd8..84cb90f1cf 100644
--- a/server/services/taskScheduleRegistry.js
+++ b/server/services/taskScheduleRegistry.js
@@ -293,7 +293,7 @@ export const DEFAULT_TASK_INTERVALS = {
// SIBLING worktrees, never in its own cwd — hence the shared non-committing
// -coordinator posture above. On-demand by default — a manual Run is the
// explicit consent to drive PRs; choosing a cadence enables scheduled runs.
- 'branch-reconcile': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, recheckCron: '0 3 * * *', drainDispatchCap: PERPETUAL_DRAIN_DISPATCH_CAP, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA, cleanupMerged: true, openPr: true, resolveConflicts: true, autoMerge: true, finishAbandoned: true, branchesPerAgent: DEFAULT_BRANCHES_PER_AGENT } },
+ 'branch-reconcile': { type: INTERVAL_TYPES.ON_DEMAND, perpetual: true, enabled: true, providerId: null, model: null, prompt: null, recheckCron: '0 3 * * *', drainDispatchCap: PERPETUAL_DRAIN_DISPATCH_CAP, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA, cleanupMerged: true, openPr: true, resolveConflicts: true, autoMerge: true, finishAbandoned: true, branchesPerAgent: DEFAULT_BRANCHES_PER_AGENT } },
// issue-reconcile heals ZOMBIE issues: open + `in-progress` (claimed) yet with
// their PR already MERGED and no live claim anywhere — a partial ship left the
// claim marker on, so the queue (which skips `in-progress`) never re-picks the
@@ -310,7 +310,7 @@ export const DEFAULT_TASK_INTERVALS = {
// issue-state mutation is its whole deliverable — hence the shared
// non-committing-coordinator posture above. On-demand by default — a manual
// Run is the explicit consent to mutate issue state; a cadence is opt-in.
- 'issue-reconcile': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, recheckCron: '0 4 * * *', drainDispatchCap: PERPETUAL_DRAIN_DISPATCH_CAP, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA, autoClose: true } },
+ 'issue-reconcile': { type: INTERVAL_TYPES.ON_DEMAND, perpetual: true, enabled: true, providerId: null, model: null, prompt: null, recheckCron: '0 4 * * *', drainDispatchCap: PERPETUAL_DRAIN_DISPATCH_CAP, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA, autoClose: true } },
'console-errors': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
'dependency-updates': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null },
'documentation': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
diff --git a/server/services/taskScheduleStore.js b/server/services/taskScheduleStore.js
index c6c83188de..592b9d2452 100644
--- a/server/services/taskScheduleStore.js
+++ b/server/services/taskScheduleStore.js
@@ -6,7 +6,7 @@ import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { isPlainObject } from '../lib/objects.js';
import { emitLog } from './cosEvents.js';
-import { INTERVAL_TYPES } from './taskScheduleConstants.js';
+import { LEGACY_INTERVAL_TYPES, normalizeIntervalConfig } from './taskScheduleConstants.js';
import {
DEFAULT_TASK_INTERVALS,
createPrReviewerDefaultStages,
@@ -85,7 +85,7 @@ function migrateScheduleV1toV2(schedule) {
const existing = migrated.tasks[unifiedType];
const isExistingDefault = existing.type === DEFAULT_TASK_INTERVALS[unifiedType]?.type;
const isNewDifferent = config.type !== (taskType === 'security-audit'
- ? INTERVAL_TYPES.WEEKLY : DEFAULT_TASK_INTERVALS[unifiedType]?.type);
+ ? LEGACY_INTERVAL_TYPES.WEEKLY : DEFAULT_TASK_INTERVALS[unifiedType]?.type);
if (isExistingDefault || isNewDifferent) {
migrated.tasks[unifiedType] = { ...existing, ...config };
}
@@ -239,6 +239,11 @@ async function readSchedule() {
}
if (enforceManagedAgentOptions(taskType, config)) needsSave = true;
if (enforceBranchReconcileBatch(taskType, config)) needsSave = true;
+ // Collapse a retired cadence type (rotation/daily/weekly/once/custom/
+ // perpetual) onto the two-variant model + orthogonal `perpetual` flag, so an
+ // un-migrated schedule file — or one written by an older peer — is valid in
+ // memory and rewritten on the next save.
+ if (normalizeIntervalConfig(config)) needsSave = true;
// Stamp a creation timestamp the first time we see a task so the cron
// catch-up bound (shouldRunTask) never replays a slot that predates the
// task. Backfilling to "now" is conservative: it only suppresses catch-up
diff --git a/server/services/workflow.js b/server/services/workflow.js
index 295d88cb10..06000dfcb2 100644
--- a/server/services/workflow.js
+++ b/server/services/workflow.js
@@ -171,6 +171,7 @@ export async function getWorkflowGraph({ horizonHours = 24, from = new Date() }
enabled: !!info.enabled,
schedule: {
type: info.type,
+ perpetual: info.perpetual === true,
intervalMs: info.intervalMs ?? null,
effectiveIntervalMs: info.adjustedIntervalMs ?? info.intervalMs ?? null,
cronExpression: info.cronExpression ?? null,
@@ -197,8 +198,8 @@ export async function getWorkflowGraph({ horizonHours = 24, from = new Date() }
runReason: info.status?.shouldRun === true ? (info.status.reason || null) : null,
missedSlot: info.status?.missedSlot || null,
pendingDeps: info.status?.pendingDeps || [],
- nextRunAt: info.status?.nextRunAt || info.perpetual?.nextRecheckAt || null,
- perpetual: info.perpetual || null,
+ nextRunAt: info.status?.nextRunAt || info.perpetualStatus?.nextRecheckAt || null,
+ perpetualStatus: info.perpetualStatus || null,
// Per-app overrides so the timeline can expand a task row to show/edit
// which apps run it (mirrors the Schedule tab's PerAppOverrideList).
// `taskMetadata`/`managedAgentOptions` are the global defaults the
@@ -308,7 +309,7 @@ export function projectWorkflowTimeline(nodes, { start, end, timezone = 'UTC' })
for (const node of nodes.filter(item => item.enabled)) {
const schedule = node.schedule || {};
- if (node.kind === 'task' && schedule.type === 'perpetual') {
+ if (node.kind === 'task' && schedule.perpetual) {
projectPerpetual(node, startMs, endMs, timezone, occurrences, windows);
continue;
}
@@ -357,7 +358,9 @@ export function projectWorkflowTimeline(nodes, { start, end, timezone = 'UTC' })
continue;
}
- projectIntervalTask(node, startMs, endMs, timezone, occurrences);
+ // Anything left is an on-demand task (or a cron task with an unusable
+ // expression): the scheduler promises it no wall-clock position, so it gets
+ // neither an occurrence nor a window.
}
occurrences.sort((a, b) => new Date(a.at) - new Date(b.at) || a.nodeId.localeCompare(b.nodeId));
@@ -412,7 +415,7 @@ function appendCronOccurrences({ node, expression, startMs, endMs, timezone, tar
}
function projectPerpetual(node, startMs, endMs, timezone, occurrences, windows) {
- const perpetual = node.perpetual;
+ const perpetual = node.perpetualStatus;
const allTrackedAppsParked = perpetual?.trackedAppCount > 0 && perpetual.parkedAppCount === perpetual.trackedAppCount;
const draining = node.shouldRun && !perpetual?.globalParked && !allTrackedAppsParked && node.statusReason !== 'perpetual-parked';
if (draining) {
@@ -426,7 +429,9 @@ function projectPerpetual(node, startMs, endMs, timezone, occurrences, windows)
});
}
- const recheckCron = node.schedule?.recheckCron;
+ // A cron+perpetual task rechecks on its own expression (computePerpetualRecheckAt
+ // derives the park from it); an on-demand one uses `recheckCron`.
+ const recheckCron = node.schedule?.cronExpression || node.schedule?.recheckCron;
if (recheckCron) {
appendCronOccurrences({
node,
@@ -456,44 +461,6 @@ function projectPerpetual(node, startMs, endMs, timezone, occurrences, windows)
}
}
-function projectIntervalTask(node, startMs, endMs, timezone, occurrences) {
- const type = node.schedule?.type;
- if (type === 'rotation' || type === 'on-demand') return;
- if (type === 'once') {
- if (node.shouldRun) occurrences.push(makeOccurrence(node, startMs, 'launch', dueNowExtra(node)));
- return;
- }
-
- const cadence = node.schedule?.effectiveIntervalMs
- || (type === 'weekly' ? 7 * DAY : type === 'daily' ? DAY : node.schedule?.intervalMs);
- if (!cadence) return;
-
- let nextMs;
- if (node.shouldRun) {
- // Emit the due-now marker explicitly (tagged) and project subsequent cadence
- // slots strictly after now so the recurring slots aren't mislabelled due-now.
- occurrences.push(makeOccurrence(node, startMs, 'launch', dueNowExtra(node)));
- const anchor = node.nextRunAt ? new Date(node.nextRunAt).getTime() : NaN;
- nextMs = Number.isFinite(anchor) && anchor > startMs ? anchor : startMs + cadence;
- } else {
- nextMs = node.nextRunAt ? new Date(node.nextRunAt).getTime() : NaN;
- if (!Number.isFinite(nextMs)) {
- const lastRunMs = node.lastRun ? new Date(node.lastRun).getTime() : NaN;
- nextMs = Number.isFinite(lastRunMs) ? lastRunMs + cadence : startMs;
- }
- }
- appendIntervalOccurrences({
- node,
- firstMs: nextMs,
- cadence,
- startMs,
- endMs,
- timezone,
- target: occurrences,
- kind: 'launch'
- });
-}
-
function projectIntervalJob(node, startMs, endMs, timezone, occurrences) {
const cadence = node.schedule?.intervalMs;
if (!cadence) return;
diff --git a/server/services/workflow.test.js b/server/services/workflow.test.js
index 447c7b9222..5b0a42170c 100644
--- a/server/services/workflow.test.js
+++ b/server/services/workflow.test.js
@@ -85,8 +85,8 @@ describe('getWorkflowGraph', () => {
it('returns nodes for tasks with their stage classification', async () => {
getScheduleStatus.mockResolvedValue({
tasks: {
- 'do-replan': { type: 'weekly', enabled: true, runAfter: ['pr-reviewer'], lastRun: null, runCount: 0, status: { shouldRun: true, reason: 'weekly-due' } },
- 'feature-ideas': { type: 'daily', enabled: true, runAfter: ['do-replan'], lastRun: null, runCount: 0, status: { shouldRun: false, reason: 'waiting-on-dependencies', pendingDeps: ['do-replan'] } }
+ 'do-replan': { type: 'cron', cronExpression: '0 7 * * 1', enabled: true, runAfter: ['pr-reviewer'], lastRun: null, runCount: 0, status: { shouldRun: true, reason: 'weekly-due' } },
+ 'feature-ideas': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, runAfter: ['do-replan'], lastRun: null, runCount: 0, status: { shouldRun: false, reason: 'waiting-on-dependencies', pendingDeps: ['do-replan'] } }
}
});
getAllJobs.mockResolvedValue([]);
@@ -110,7 +110,7 @@ describe('getWorkflowGraph', () => {
getScheduleStatus.mockResolvedValue({
tasks: {
'do-replan': {
- type: 'weekly', enabled: true, runAfter: [], lastRun: null, runCount: 0,
+ type: 'cron', cronExpression: '0 7 * * 1', enabled: true, runAfter: [], lastRun: null, runCount: 0,
status: { shouldRun: true },
appOverrides: { 'app-1': { enabled: true, interval: 'daily' } },
enabledAppCount: 1,
@@ -134,7 +134,7 @@ describe('getWorkflowGraph', () => {
it('defaults per-app override fields when absent', async () => {
getScheduleStatus.mockResolvedValue({
tasks: {
- 'feature-ideas': { type: 'daily', enabled: true, runAfter: [], lastRun: null, runCount: 0, status: { shouldRun: true } }
+ 'feature-ideas': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, runAfter: [], lastRun: null, runCount: 0, status: { shouldRun: true } }
}
});
getAllJobs.mockResolvedValue([]);
@@ -151,7 +151,7 @@ describe('getWorkflowGraph', () => {
it('emits a depends-on edge for every runAfter entry', async () => {
getScheduleStatus.mockResolvedValue({
tasks: {
- 'feature-ideas': { type: 'daily', enabled: true, runAfter: ['do-replan'], lastRun: null, runCount: 0, status: { shouldRun: true } }
+ 'feature-ideas': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, runAfter: ['do-replan'], lastRun: null, runCount: 0, status: { shouldRun: true } }
}
});
getAllJobs.mockResolvedValue([]);
@@ -190,7 +190,7 @@ describe('getWorkflowGraph', () => {
it('falls back to ambient stage for unknown task types and jobs', async () => {
getScheduleStatus.mockResolvedValue({
tasks: {
- 'custom-thing': { type: 'daily', enabled: true, runAfter: [], lastRun: null, runCount: 0, status: { shouldRun: true } }
+ 'custom-thing': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, runAfter: [], lastRun: null, runCount: 0, status: { shouldRun: true } }
}
});
getAllJobs.mockResolvedValue([
@@ -206,8 +206,8 @@ describe('getWorkflowGraph', () => {
// Only plan and build populated — flow edge should connect plan → build directly
getScheduleStatus.mockResolvedValue({
tasks: {
- 'do-replan': { type: 'weekly', enabled: true, runAfter: [], lastRun: null, runCount: 0, status: { shouldRun: true } },
- 'feature-ideas': { type: 'daily', enabled: true, runAfter: [], lastRun: null, runCount: 0, status: { shouldRun: true } }
+ 'do-replan': { type: 'cron', cronExpression: '0 7 * * 1', enabled: true, runAfter: [], lastRun: null, runCount: 0, status: { shouldRun: true } },
+ 'feature-ideas': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, runAfter: [], lastRun: null, runCount: 0, status: { shouldRun: true } }
}
});
getAllJobs.mockResolvedValue([]);
@@ -251,8 +251,8 @@ describe('getWorkflowGraph', () => {
it('reports per-stage enabled/total counts', async () => {
getScheduleStatus.mockResolvedValue({
tasks: {
- 'do-replan': { type: 'weekly', enabled: true, runAfter: [], lastRun: null, runCount: 0, status: { shouldRun: true } },
- 'feature-ideas': { type: 'daily', enabled: false, runAfter: [], lastRun: null, runCount: 0, status: { shouldRun: false, reason: 'disabled' } }
+ 'do-replan': { type: 'cron', cronExpression: '0 7 * * 1', enabled: true, runAfter: [], lastRun: null, runCount: 0, status: { shouldRun: true } },
+ 'feature-ideas': { type: 'cron', cronExpression: '0 7 * * *', enabled: false, runAfter: [], lastRun: null, runCount: 0, status: { shouldRun: false, reason: 'disabled' } }
}
});
getAllJobs.mockResolvedValue([]);
@@ -323,7 +323,7 @@ describe('projectWorkflowTimeline', () => {
it('renders an active perpetual task as an open-ended drain window and its reset', () => {
const timeline = projectWorkflowTimeline([{
id: 'task:drain', kind: 'task', enabled: true, shouldRun: true,
- schedule: { type: 'perpetual', recheckCron: '0 9 * * *' }
+ schedule: { type: 'on-demand', perpetual: true, recheckCron: '0 9 * * *' }
}], range);
expect(timeline.windows[0]).toMatchObject({ nodeId: 'task:drain', state: 'draining' });
@@ -333,50 +333,28 @@ describe('projectWorkflowTimeline', () => {
it('does not show an app-scoped perpetual task draining when every tracked app is parked', () => {
const timeline = projectWorkflowTimeline([{
id: 'task:drain', kind: 'task', enabled: true, shouldRun: true,
- perpetual: { globalParked: false, trackedAppCount: 2, parkedAppCount: 2 },
- schedule: { type: 'perpetual', recheckCron: '0 9 * * *' }
+ perpetualStatus: { globalParked: false, trackedAppCount: 2, parkedAppCount: 2 },
+ schedule: { type: 'on-demand', perpetual: true, recheckCron: '0 9 * * *' }
}], range);
expect(timeline.windows).toEqual([]);
expect(timeline.occurrences[0]).toMatchObject({ nodeId: 'task:drain', kind: 'recheck' });
});
- it('places an already-due interval task at the start of the timeline', () => {
- const timeline = projectWorkflowTimeline([{
- id: 'task:due', kind: 'task', enabled: true, shouldRun: true,
- lastRun: '2026-07-07T00:00:00.000Z',
- schedule: { type: 'daily', effectiveIntervalMs: 86_400_000 }
- }], range);
-
- expect(timeline.occurrences[0]).toMatchObject({ nodeId: 'task:due', at: range.start.toISOString(), kind: 'launch' });
- });
-
- it('tags an overdue interval task launch as due-now and carries its reason', () => {
+ it('tags an overdue cron task launch as due-now and carries its reason', () => {
const timeline = projectWorkflowTimeline([{
id: 'task:weekly', kind: 'task', enabled: true, shouldRun: true,
- runReason: 'weekly-due', lastRun: null,
- schedule: { type: 'weekly', effectiveIntervalMs: 7 * 86_400_000 }
+ runReason: 'cron-due', lastRun: null,
+ schedule: { type: 'cron', cronExpression: '0 7 * * 1' }
}], range);
// The NOW marker is flagged; subsequent cadence slots (out of the 24h
// window) are not, so only the tagged launch is present.
expect(timeline.occurrences).toEqual([
- expect.objectContaining({ nodeId: 'task:weekly', at: range.start.toISOString(), dueNow: true, reason: 'weekly-due' })
+ expect.objectContaining({ nodeId: 'task:weekly', at: range.start.toISOString(), dueNow: true, reason: 'cron-due' })
]);
});
- it('does not tag a future on-cadence interval slot as due-now', () => {
- const timeline = projectWorkflowTimeline([{
- id: 'task:soon', kind: 'task', enabled: true, shouldRun: false,
- lastRun: '2026-07-08T18:00:00.000Z', nextRunAt: '2026-07-09T18:00:00.000Z',
- schedule: { type: 'daily', effectiveIntervalMs: 86_400_000 }
- }], range);
-
- expect(timeline.occurrences).toHaveLength(1);
- expect(timeline.occurrences[0]).toMatchObject({ nodeId: 'task:soon', at: '2026-07-09T18:00:00.000Z' });
- expect(timeline.occurrences[0].dueNow).toBeUndefined();
- });
-
it('tags a cron catch-up launch as due-now with the missed slot', () => {
const timeline = projectWorkflowTimeline([{
id: 'task:sunday', kind: 'task', enabled: true, shouldRun: true,
@@ -391,25 +369,6 @@ describe('projectWorkflowTimeline', () => {
});
});
- it('omits weekend occurrences for weekday-only interval tasks', () => {
- const timeline = projectWorkflowTimeline([{
- id: 'task:weekdays', kind: 'task', enabled: true, shouldRun: false,
- lastRun: '2026-07-10T09:00:00.000Z',
- nextRunAt: '2026-07-11T09:00:00.000Z',
- schedule: { type: 'daily', effectiveIntervalMs: 86_400_000, weekdaysOnly: true }
- }], {
- start: new Date('2026-07-10T10:00:00.000Z'),
- end: new Date('2026-07-13T10:00:00.000Z'),
- timezone: 'Etc/UTC'
- });
-
- // Sat 7/11 and Sun 7/12 slots are skipped — shouldRunTask refuses
- // weekday-only tasks on weekends regardless of schedule type.
- expect(timeline.occurrences).toEqual([
- expect.objectContaining({ nodeId: 'task:weekdays', at: '2026-07-13T09:00:00.000Z' })
- ]);
- });
-
it('omits weekend slots for weekday-only cron tasks', () => {
const timeline = projectWorkflowTimeline([{
id: 'task:cron-weekdays', kind: 'task', enabled: true, shouldRun: false,
@@ -468,9 +427,9 @@ describe('projectWorkflowTimeline', () => {
expect(timeline.occurrences.every(item => item.collision)).toBe(true);
});
- it('leaves rotation and on-demand tasks unpinned', () => {
+ it('leaves on-demand tasks — and a cron task with no usable expression — unpinned', () => {
const timeline = projectWorkflowTimeline([
- { id: 'task:rotation', kind: 'task', enabled: true, schedule: { type: 'rotation' } },
+ { id: 'task:broken-cron', kind: 'task', enabled: true, schedule: { type: 'cron', cronExpression: null } },
{ id: 'task:demand', kind: 'task', enabled: true, schedule: { type: 'on-demand' } }
], range);