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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: reject out-of-range cron expressions at every schedule save boundary (#6634)
[._.]/ Adam Eivye2bcc531e6c5
diff --git a/client/src/components/CronInput.jsx b/client/src/components/CronInput.jsxindex c1aabe80ee..73fbf53aac 100644--- a/client/src/components/CronInput.jsx+++ b/client/src/components/CronInput.jsx@@ -1,5 +1,5 @@import { useEffect, useState } from 'react';-import { DEFAULT_CRON } from '../utils/cronHelpers';+import { DEFAULT_CRON, findCronExpressionError } from '../utils/cronHelpers';import CronSchedulePicker from './CronSchedulePicker';import InlineConfirmRow from './ui/InlineConfirmRow';@@ -24,7 +24,10 @@ export default function CronInput({ value, onSave, onCancel, className = '' }) {const trimmed = expr.trim();const isDirty = trimmed !== savedExpression.trim();- const isValid = trimmed.split(/\s+/).length === 5;+ // Field ranges too, not just the 5-token shape: the save routes reject an+ // out-of-range expression with a 400, and the scheduler would never fire it.+ const validationError = findCronExpressionError(trimmed);+ const isValid = validationError === null;const handleSave = () => {if (!isValid) return;@@ -68,13 +71,13 @@ export default function CronInput({ value, onSave, onCancel, className = '' }) {aria-live="polite"className={`mr-auto text-xs ${isDirty ? 'font-medium text-port-warning' : 'text-gray-500'}`}>- {isDirty ? (isValid ? 'Unsaved changes — save before closing' : 'Enter a valid 5-field cron expression') : null}+ {isDirty ? (isValid ? 'Unsaved changes — save before closing' : validationError) : null}</span><buttontype="button"onClick={handleSave}disabled={!isValid}- title={isValid ? 'Save schedule changes' : 'Enter a valid 5-field cron expression before saving'}+ title={isValid ? 'Save schedule changes' : validationError}className={`inline-flex min-h-[40px] items-center justify-center rounded px-4 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${isDirty? 'bg-port-accent text-white shadow-sm ring-2 ring-port-accent/50 hover:bg-port-accent/80': 'bg-port-accent/20 text-port-accent hover:bg-port-accent/30'}`}diff --git a/client/src/components/CronInput.test.jsx b/client/src/components/CronInput.test.jsxindex 5c809a5907..ad786b2d9e 100644--- a/client/src/components/CronInput.test.jsx+++ b/client/src/components/CronInput.test.jsx@@ -43,6 +43,30 @@ describe('CronInput', () => {expect(screen.queryByText(/Unsaved changes/i)).toBeNull();});+ it('blocks saving an out-of-range expression and says which field is wrong', () => {+ // #6634: the editor used to enable Save on any 5-token expression, so the+ // user could save a schedule the server now 400s and the scheduler could+ // never fire.+ const onSave = vi.fn();+ render(<CronInput value="0 7 * * *" onSave={onSave} onCancel={vi.fn()} />);++ const expression = screen.getByLabelText('Cron expression');+ fireEvent.change(expression, { target: { value: '99 9 * * *' } });++ const save = screen.getByRole('button', { name: 'Save schedule' });+ expect(save).toBeDisabled();+ expect(screen.getByRole('status')).toHaveTextContent('Invalid minute field');+ fireEvent.click(save);+ expect(onSave).not.toHaveBeenCalled();++ // A leap-day cron has no occurrence in the scheduler's search window but is+ // valid syntax, so the editor must not block it.+ fireEvent.change(expression, { target: { value: '0 0 29 2 *' } });+ expect(screen.getByRole('button', { name: 'Save schedule' })).toBeEnabled();+ fireEvent.click(screen.getByRole('button', { name: 'Save schedule' }));+ expect(onSave).toHaveBeenCalledWith('0 0 29 2 *');+ });+it('closes immediately when there are no edits', () => {const onCancel = vi.fn();render(<CronInput value="0 7 * * *" onSave={vi.fn()} onCancel={onCancel} />);diff --git a/client/src/utils/cronHelpers.js b/client/src/utils/cronHelpers.jsindex bab8fa2881..ba0bc80cbd 100644--- a/client/src/utils/cronHelpers.js+++ b/client/src/utils/cronHelpers.js@@ -1,5 +1,9 @@import { INTERVAL_OPTIONS } from '../../../server/lib/autonomousJobIntervals.js';export { ON_DEMAND_INTERVAL } from '../../../server/lib/autonomousJobIntervals.js';+// Syntax/range validation shared with the scheduler and every save route, so+// the editor cannot enable Save on an expression the server will 400 (#6634).+// cronValidation.js is a pure leaf — importing it pulls in no service graph.+export { isValidCronExpression, findCronExpressionError } from '../../../server/lib/cronValidation.js';export const CRON_PRESETS = [{ value: '*/15 * * * *', label: 'Every 15 min' },@@ -14,9 +18,9 @@ export const CRON_PRESETS = [{ value: '0 0 1 * *', label: 'Monthly 1st at midnight' }];-export function isCronExpression(val) {- return typeof val === 'string' && val.trim().split(/\s+/).length === 5;-}+// SHAPE only (mirrors the server's `isCronShaped`) — it separates a cron from a+// named cadence. Gate a SAVE on `isValidCronExpression` instead.+export { isCronShaped as isCronExpression } from '../../../server/lib/cronValidation.js';const DOW_MAP = { '0': 'Sun', '1': 'Mon', '2': 'Tue', '3': 'Wed', '4': 'Thu', '5': 'Fri', '6': 'Sat', '7': 'Sun' };diff --git a/server/lib/README.md b/server/lib/README.mdindex 52a3163637..cfebb693a3 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -78,6 +78,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `quotaBurnValidation.js` | Zod schemas for the Quota Burn routes (partial config PUT, manual-run body, `run once` re-arm body). || `quotaReset.js` | `parseHumanReset` turns a provider CLI's human reset string into ISO 8601 (call it from the adapter); `normalizeResetAt`/`hoursUntilReset` compute time remaining without treating unknown values as imminent resets; `parseObservedReset` pulls the reset a provider stated in its own refusal text, and `isObservedBlockActive` is the shared "is that refusal still holding?" predicate every observed-refusal ledger uses. || `quotaWindows.js` | Classifies a quota window by PERIOD (`windowPeriodHours`); `classifyWindows` splits one card's windows into the weekly allowance that expires unused and the 5-hour one that refuses first, in one pass. `windowLabelOf` names a window. Pure. |+| `cronValidation.js` | Cron syntax + field-range validation (pure, import-free, browser-safe). `isValidCronExpression` / `findCronExpressionError` (a user-facing reason string) / `isValidCronField` / `isCronShaped` (5-token SHAPE only — the named-cadence detector, never a stand-in for validity), plus `CRON_FIELD_NAMES` / `CRON_FIELD_BOUNDS`. ONE implementation shared by `services/eventScheduler.js`, the CoS schedule + per-app task-type save routes, the app-override schema in `validation.js`, and the browser cron editor via `client/src/utils/cronHelpers.js` (#6634). Syntax validity is deliberately separate from whether an occurrence exists in the scheduler bounded search window — a leap-day cron is valid. || `recurrenceValidation.js` | Shared Zod shape and vocabulary for anchored calendar recurrences that cannot be represented faithfully by five-field cron. || `appleHealthValidation.js` | Apple Health import payloads. || `brainValidation.js` | Brain/memory route schemas (search, ingest, edit). |diff --git a/server/lib/cronValidation.js b/server/lib/cronValidation.jsnew file mode 100644index 0000000000..ef19f5e635--- /dev/null+++ b/server/lib/cronValidation.js@@ -0,0 +1,116 @@+/**+ * Cron syntax + field-range validation (pure, dependency-free).+ *+ * ONE implementation of "is this a valid 5-field cron expression", shared by+ * the runtime walker (`services/eventScheduler.js`), every save boundary that+ * persists a cron string (CoS global schedule routes, per-app task-type+ * overrides, the generic app-update schema), and the browser cron editor.+ *+ * Before this module those four surfaces disagreed: the walker rejected+ * out-of-range fields by returning `null`, while the save routes only counted+ * five whitespace-separated tokens — so `99 9 * * *` could be saved on an+ * ENABLED schedule that then never fired (#6634).+ *+ * SYNTAX VALIDITY IS NOT "HAS A NEXT OCCURRENCE". `0 0 29 2 *` (leap day) is+ * syntactically valid even though the scheduler's bounded two-year search+ * window may find no match; a save boundary must never use a null next-run+ * result as its invalidity signal. Next-occurrence search stays in the+ * scheduler; this module answers syntax and range only.+ *+ * Kept free of imports (Zod included) so the browser can import it directly,+ * the way `client/src/utils/cronHelpers.js` already imports pure scheduling+ * vocabulary out of `server/lib/`.+ */++/** Field order of a 5-field cron expression. */+export const CRON_FIELD_NAMES = ['minute', 'hour', 'dayOfMonth', 'month', 'dayOfWeek'];++/**+ * Inclusive [min, max] bounds per field. `dayOfWeek` allows 7 as a second+ * spelling of Sunday (the walker matches both 0 and 7).+ */+export const CRON_FIELD_BOUNDS = [[0, 59], [0, 23], [1, 31], [1, 12], [0, 7]];++export const CRON_FIELD_COUNT = 5;++/**+ * Whether a value has the 5-token SHAPE of a cron expression — the detector+ * that distinguishes a cron string from a named cadence like `on-demand`. It+ * says nothing about syntax validity; use `isValidCronExpression` for that.+ * @param {unknown} value+ * @returns {boolean}+ */+export function isCronShaped(value) {+ return typeof value === 'string' && value.trim().split(/\s+/).length === CRON_FIELD_COUNT;+}++/**+ * Validate one comma-separated part of a field (`5`, `1-5`, `*`, `*\/15`,+ * `1-5/2`, `0/10`).+ */+function isCronPartValid(part, min, max) {+ const [range, step] = part.split('/');+ // Only ONE `/` is legal — `1/2/3` splits into 3 and must not pass.+ if (part.split('/').length > 2) return false;+ if (step !== undefined && !(/^\d+$/.test(step) && Number(step) >= 1)) return false;+ if (range === '*') return true;+ const bounds = range.split('-');+ if (bounds.length > 2) return false;+ const [a, b] = bounds;+ if (!/^\d+$/.test(a)) return false;+ const av = Number(a);+ if (av < min || av > max) return false;+ if (b !== undefined) {+ if (!/^\d+$/.test(b)) return false;+ const bv = Number(b);+ if (bv < min || bv > max || bv < av) return false;+ }+ return true;+}++/**+ * Validate a single cron field against its bounds.+ * @param {string} expr - One field of a cron expression (e.g. `*\/15`, `1-5`)+ * @param {number} min - Minimum allowed value+ * @param {number} max - Maximum allowed value+ * @returns {boolean}+ */+export function isValidCronField(expr, min, max) {+ if (typeof expr !== 'string' || expr === '') return false;+ return expr.split(',').every((part) => isCronPartValid(part, min, max));+}++/**+ * Describe why an expression is not a valid cron, or `null` when it is valid.+ * Returned as a user-facing string so the editor can explain the rejection+ * rather than only disabling Save.+ * @param {unknown} expr+ * @returns {string|null}+ */+export function findCronExpressionError(expr) {+ if (typeof expr !== 'string' || expr.trim() === '') {+ return 'Enter a 5-field cron expression (minute hour dayOfMonth month dayOfWeek)';+ }+ const fields = expr.trim().split(/\s+/);+ if (fields.length !== CRON_FIELD_COUNT) {+ return 'Enter a 5-field cron expression (minute hour dayOfMonth month dayOfWeek)';+ }+ for (let i = 0; i < CRON_FIELD_COUNT; i += 1) {+ const [min, max] = CRON_FIELD_BOUNDS[i];+ if (!isValidCronField(fields[i], min, max)) {+ return `Invalid ${CRON_FIELD_NAMES[i]} field "${fields[i]}" — allowed range is ${min}-${max}`;+ }+ }+ return null;+}++/**+ * Whether a value is a syntactically valid 5-field cron expression with every+ * field inside its range. Does NOT consider whether an occurrence exists in any+ * particular search window.+ * @param {unknown} expr+ * @returns {boolean}+ */+export function isValidCronExpression(expr) {+ return findCronExpressionError(expr) === null;+}diff --git a/server/lib/cronValidation.test.js b/server/lib/cronValidation.test.jsnew file mode 100644index 0000000000..c76a2876ac--- /dev/null+++ b/server/lib/cronValidation.test.js@@ -0,0 +1,107 @@+import { describe, it, expect } from 'vitest';+import {+ isValidCronExpression,+ findCronExpressionError,+ isValidCronField,+ isCronShaped,+ CRON_FIELD_BOUNDS,+} from './cronValidation.js';+import { parseCronToNextRun } from '../services/eventScheduler.js';++// Syntax/range only. Route-boundary behavior (which HTTP status, which store+// write) lives with the routes; these cases pin the vocabulary itself.+describe('cronValidation', () => {+ it('accepts wildcards, ranges, lists, and steps in every field', () => {+ for (const expr of [+ '* * * * *',+ '0 7 * * *',+ '*/15 * * * *',+ '0 9-17 * * 1-5',+ '0 9,12,15,18 * * *',+ '5-55/10 */2 1-28/7 1,6,12 1-5',+ '59 23 31 12 6',+ ]) {+ expect(findCronExpressionError(expr), expr).toBeNull();+ }+ });++ it('accepts both 0 and 7 as Sunday', () => {+ expect(isValidCronExpression('0 0 * * 0')).toBe(true);+ expect(isValidCronExpression('0 0 * * 7')).toBe(true);+ expect(isValidCronExpression('0 0 * * 0-7')).toBe(true);+ expect(isValidCronExpression('0 0 * * 8')).toBe(false);+ });++ it('rejects out-of-range values per field and names the offending field', () => {+ // One out-of-range case per field, using that field's own upper bound + 1.+ const overflow = [+ ['60 0 * * *', 'minute'],+ ['0 24 * * *', 'hour'],+ ['0 0 32 * *', 'dayOfMonth'],+ ['0 0 * 13 *', 'month'],+ ['0 0 * * 8', 'dayOfWeek'],+ ];+ for (const [expr, field] of overflow) {+ expect(findCronExpressionError(expr), expr).toContain(field);+ }+ // Below-minimum values, where the floor is 1 rather than 0.+ expect(isValidCronExpression('0 0 0 * *')).toBe(false);+ expect(isValidCronExpression('0 0 * 0 *')).toBe(false);+ });++ it('rejects the reported real-world regressions from #6634', () => {+ // Both were accepted by the old five-token save check and then silently+ // dropped by the scheduler, leaving an "enabled" schedule that never fired.+ expect(isValidCronExpression('99 9 * * *')).toBe(false);+ expect(isValidCronExpression('0 25 * * *')).toBe(false);+ expect(parseCronToNextRun('99 9 * * *', new Date('2026-01-01T00:00:00Z'), 'UTC')).toBeNull();+ expect(parseCronToNextRun('0 25 * * *', new Date('2026-01-01T00:00:00Z'), 'UTC')).toBeNull();+ });++ it('rejects malformed syntax that is still five tokens', () => {+ for (const expr of [+ 'a * * * *', // non-numeric+ '*/0 * * * *', // zero step+ '*/x * * * *', // non-numeric step+ '1/2/3 * * * *', // two step separators+ '5-1 * * * *', // inverted range+ '1-2-3 * * * *', // two range separators+ '-5 * * * *', // missing range start+ '1, * * * *', // empty list entry+ '1.5 * * * *', // non-integer+ ]) {+ expect(isValidCronExpression(expr), expr).toBe(false);+ }+ });++ it('rejects anything that is not a five-field string', () => {+ for (const value of ['* * * *', '* * * * * *', '', ' ', 'on-demand', null, undefined, 5, ['0 7 * * *']]) {+ expect(isValidCronExpression(value), String(value)).toBe(false);+ }+ });++ it('treats an expression with no occurrence in the search window as VALID syntax', () => {+ // A leap-day cron is syntactically valid, but the scheduler's bounded+ // two-year search finds nothing from 2024-03-01 (the next leap day is 2028). A+ // save boundary must not use that null as its invalidity signal — that+ // conflation is exactly what #6634 forbids.+ expect(isValidCronExpression('0 0 29 2 *')).toBe(true);+ expect(parseCronToNextRun('0 0 29 2 *', new Date('2024-03-01T00:00:00Z'), 'UTC')).toBeNull();+ // ...and the same expression DOES resolve when a leap day is in window.+ expect(parseCronToNextRun('0 0 29 2 *', new Date('2027-06-01T00:00:00Z'), 'UTC')).toBeInstanceOf(Date);+ });++ it('isCronShaped detects the five-token shape without judging validity', () => {+ expect(isCronShaped('99 9 * * *')).toBe(true);+ expect(isValidCronExpression('99 9 * * *')).toBe(false);+ expect(isCronShaped('on-demand')).toBe(false);+ expect(isCronShaped(null)).toBe(false);+ });++ it('isValidCronField enforces the bounds it is given', () => {+ const [minuteMin, minuteMax] = CRON_FIELD_BOUNDS[0];+ expect(isValidCronField('0-59', minuteMin, minuteMax)).toBe(true);+ expect(isValidCronField('0-60', minuteMin, minuteMax)).toBe(false);+ expect(isValidCronField('', minuteMin, minuteMax)).toBe(false);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 06e103bbc3..d8ae8d04d2 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -30,6 +30,9 @@ export * as catalogValidation from './catalogValidation.js';export * as characterAugmentValidation from './characterAugmentValidation.js';export * as characterEvolutionValidation from './characterEvolutionValidation.js';export * as cosValidation from './cosValidation.js';+// Flat: validation.js re-exports these same bindings, and the barrel's collision+// check treats an identical identity as a re-export rather than a clash.+export * from './cronValidation.js';export * from './cosToolContracts.js';export * as creativeCommissionValidation from './creativeCommissionValidation.js';export * as creativeDirectorValidation from './creativeDirectorValidation.js';diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 91ae169a40..0c39ba5f34 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -23,6 +23,7 @@ import {isFederatedMediaAudioPrompt,} from './federatedMediaWire.js';import { isPlainObject } from './objects.js';+import { isValidCronExpression, isCronShaped } from './cronValidation.js';import { USER_ACTION_ACTORS, USER_ACTION_TYPES } from './userActionTypes.js';// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total@@ -260,7 +261,14 @@ export const appSchema = z.object({disabledTaskTypes: z.array(z.string()).optional(), // Legacy: migrated to taskTypeOverridestaskTypeOverrides: z.record(z.object({enabled: z.boolean().optional(),- interval: z.string().nullable().optional(),+ // A cron-SHAPED override must also be in range, or this generic PUT would+ // persist an enabled schedule the walker can never match (#6634). A+ // non-cron-shaped string is a named/legacy cadence the route decodes, and+ // null clears the override back to inherit — both pass through untouched.+ interval: z.string().refine(+ (v) => !isCronShaped(v) || isValidCronExpression(v),+ 'interval must be a valid 5-field cron expression'+ ).nullable().optional(),// Per-app scheduling fields for handler-backed tasks (e.g. layered-intelligence);// persisted by updateAppTaskTypeOverride. Nullable = "clear back to inherit/default".// Declared here so a generic PUT /api/apps/:id can't silently strip them (Zod drops@@ -892,37 +900,15 @@ export const backupConfigSchema = z.object({// empty string. Other autopilot run options are intentionally NOT accepted here:// there's no UI producing them, so a scheduled run uses the series' persisted// defaults for those (add a field only when a control exists to set it).-// Structural cron validator, self-contained so validation.js stays a leaf lib-// (importing the scheduler's isValidCron would pull the eventScheduler graph into-// every suite that mocks validation's deps). Rejects a 5-token-but-out-of-range-// cron like `99 99 * * *` at the PUT boundary (a 400 the UI surfaces) instead of-// letting it be saved+enabled and then silently dropped by activeSchedules —-// which would leave the user with an "enabled" schedule that never fires (#2174).-// Deliberately no less permissive than the scheduler's parser (`*`, ranges,-// lists, steps) so a cron it accepts is never rejected here.-const CRON_FIELD_BOUNDS = [[0, 59], [0, 23], [1, 31], [1, 12], [0, 7]];-const isCronPartValid = (part, min, max) => {- const [range, step] = part.split('/');- if (step !== undefined && !(/^\d+$/.test(step) && Number(step) >= 1)) return false;- if (range === '*') return true;- const [a, b] = range.split('-');- if (!/^\d+$/.test(a)) return false;- const av = Number(a);- if (av < min || av > max) return false;- if (b !== undefined) {- if (!/^\d+$/.test(b)) return false;- const bv = Number(b);- if (bv < min || bv > max || bv < av) return false;- }- return true;-};-export const isValidCronExpression = (expr) => {- if (typeof expr !== 'string') return false;- const fields = expr.trim().split(/\s+/);- if (fields.length !== 5) return false;- return fields.every((field, i) =>- field.split(',').every((part) => isCronPartValid(part, CRON_FIELD_BOUNDS[i][0], CRON_FIELD_BOUNDS[i][1])));-};+// Cron syntax/range validation lives in the pure leaf `cronValidation.js` so the+// scheduler, every save boundary, and the browser cron editor share ONE+// implementation (#6634). Re-exported here because callers already reach for+// `isValidCronExpression` through validation.js. Rejects a 5-token-but-out-of-+// range cron like `99 99 * * *` at the PUT boundary (a 400 the UI surfaces)+// instead of letting it be saved+enabled and then silently dropped by+// activeSchedules — which would leave the user with an "enabled" schedule that+// never fires (#2174).+export { isValidCronExpression, isCronShaped, findCronExpressionError } from './cronValidation.js';export const seriesAutopilotScheduleSchema = z.object({seriesId: z.string().min(1).max(64),diff --git a/server/lib/validation.test.js b/server/lib/validation.test.jsindex 06e0ae9368..9563ca53fb 100644--- a/server/lib/validation.test.js+++ b/server/lib/validation.test.js@@ -669,6 +669,25 @@ describe('validation.js', () => {expect(result.success).toBe(true);});+ it('rejects a cron-shaped taskTypeOverrides interval that is out of range', () => {+ // #6634: this generic entry point accepted any string, so an out-of-range+ // cron could be persisted here even after the dedicated per-app route+ // learned to reject it. A non-cron-shaped cadence name and a null clear+ // still pass through untouched.+ for (const interval of ['99 9 * * *', '0 25 * * *']) {+ const result = appUpdateSchema.safeParse({+ taskTypeOverrides: { 'layered-intelligence': { interval } }+ });+ expect(result.success, interval).toBe(false);+ }+ for (const interval of ['0 7 * * *', '0 0 29 2 *', '6h', 'on-demand', null]) {+ const result = appUpdateSchema.safeParse({+ taskTypeOverrides: { 'layered-intelligence': { interval } }+ });+ expect(result.success, String(interval)).toBe(true);+ }+ });+it('accepts partial managed-app feature overrides', () => {expect(appUpdateSchema.safeParse({ featureOverrides: { jira: false } }).success).toBe(true);expect(appUpdateSchema.safeParse({ featureOverrides: { gsd: null } }).success).toBe(true);diff --git a/server/routes/apps/taskTypes.js b/server/routes/apps/taskTypes.jsindex 64a7099a0e..31b6ddd032 100644--- a/server/routes/apps/taskTypes.js+++ b/server/routes/apps/taskTypes.js@@ -23,8 +23,8 @@ import { PORTOS_APP_ID } from '../../services/apps.js';import { sanitizeTaskMetadata, ISSUE_AUTHOR_FILTERS } from '../../lib/validation.js';import { listWorkItems } from '../../services/workItems.js';import { resolveClaimWorkMetadata, resolveClaimAuthorFilter, resolveAppClaimReviewers } from '../../services/cosTaskGenerator.js';-import { parseCronToNextRun } from '../../services/eventScheduler.js';import { INTERVAL_TYPES, decodeIntervalType, isCronExpression, isKnownIntervalType } from '../../services/taskScheduleConstants.js';+import { findCronExpressionError } from '../../lib/cronValidation.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';@@ -298,9 +298,14 @@ router.put('/:id/task-types/:taskType', asyncHandler(async (req, res) => {}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.trim(), new Date(), 'UTC');+ // Syntax + field ranges only. The walker returns null (never throws) for+ // an out-of-range field, so the old `parseCronToNextRun` call could not+ // reject one; and a null result also means 'no occurrence in the bounded+ // search window' (a leap-day cron), which is still valid syntax (#6634).+ const cronError = findCronExpressionError(interval);+ if (cronError) {+ throw new ServerError(`interval is invalid: ${cronError}`, { status: 400, code: 'VALIDATION_ERROR' });+ }interval = interval.trim();} else {// An unrecognized string is rejected rather than decoded — silentlydiff --git a/server/routes/apps/taskTypes.test.js b/server/routes/apps/taskTypes.test.jsindex 1f43156303..eb4015af82 100644--- a/server/routes/apps/taskTypes.test.js+++ b/server/routes/apps/taskTypes.test.js@@ -4,8 +4,8 @@ import { request } from '../../lib/testHelper.js';import taskTypeRoutes from './taskTypes.js';// Only the apps service is mocked; SELF_IMPROVEMENT_TASK_TYPES (taskScheduleRegistry) and-// parseCronToNextRun (eventScheduler) run for real, as do the sanitizeTaskMetadata-// validators.+// the shared cron validator (lib/cronValidation.js) run for real, as do the+// sanitizeTaskMetadata validators.const recordUserAction = vi.hoisted(() => vi.fn(async () => ({ id: 'evt' })));vi.mock('../../services/userActions.js', () => ({ recordUserAction }));@@ -390,6 +390,59 @@ describe('Apps Task-Type Routes', () => {expect(response.status).toBe(400);expect(response.body.code).toBe('INVALID_TASK_TYPE');});++ // #6634: this route used to call parseCronToNextRun and discard its result,+ // on the belief that it throws for an out-of-range field. It returns null,+ // so these were saved as enabled per-app cadences that never fire.+ it('rejects an out-of-range cron interval before persisting it', async () => {+ for (const interval of ['99 9 * * *', '0 25 * * *']) {+ appsService.updateAppTaskTypeOverride.mockClear();+ const response = await request(app)+ .put('/api/apps/app-001/task-types/feature-ideas')+ .send({ interval });+ expect(response.status, interval).toBe(400);+ expect(appsService.updateAppTaskTypeOverride).not.toHaveBeenCalled();+ }+ });++ it('accepts a valid cron interval, a leap-day cron, a legacy cadence name, and null', async () => {+ appsService.updateAppTaskTypeOverride.mockResolvedValue({+ id: 'app-001', name: 'Test App', taskTypeOverrides: {}+ });++ // A leap-day cron has no occurrence in the scheduler's bounded two-year+ // search window, but is syntactically valid and must still save.+ for (const interval of [' 0 */6 * * * ', '0 0 29 2 *']) {+ appsService.updateAppTaskTypeOverride.mockClear();+ const ok = await request(app)+ .put('/api/apps/app-001/task-types/feature-ideas')+ .send({ interval });+ expect(ok.status, interval).toBe(200);+ expect(appsService.updateAppTaskTypeOverride).toHaveBeenCalledWith(+ 'app-001', 'feature-ideas', expect.objectContaining({ interval: interval.trim() })+ );+ }++ // A retired cadence name from an older client is still decoded, not rejected.+ appsService.updateAppTaskTypeOverride.mockClear();+ const legacy = await request(app)+ .put('/api/apps/app-001/task-types/feature-ideas')+ .send({ interval: 'weekly' });+ expect(legacy.status).toBe(200);+ expect(appsService.updateAppTaskTypeOverride).toHaveBeenCalledWith(+ 'app-001', 'feature-ideas', expect.objectContaining({ interval: '0 7 * * 1' })+ );++ // null clears the override back to inheriting the global cadence.+ appsService.updateAppTaskTypeOverride.mockClear();+ const cleared = await request(app)+ .put('/api/apps/app-001/task-types/feature-ideas')+ .send({ interval: null });+ expect(cleared.status).toBe(200);+ expect(appsService.updateAppTaskTypeOverride).toHaveBeenCalledWith(+ 'app-001', 'feature-ideas', expect.objectContaining({ interval: null })+ );+ });});describe('PUT /api/apps/bulk-task-type/:taskType', () => {diff --git a/server/routes/cosScheduleRoutes.js b/server/routes/cosScheduleRoutes.jsindex 5b71c5a627..47650ad9cb 100644--- a/server/routes/cosScheduleRoutes.js+++ b/server/routes/cosScheduleRoutes.js@@ -12,6 +12,7 @@ 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';import { normalizeSuggestedAfter, SUGGESTED_AFTER_MAX } from '../lib/scheduleRunOrder.js';+import { findCronExpressionError } from '../lib/cronValidation.js';const templateTaskSchema = z.object({name: z.string().min(1),@@ -76,8 +77,14 @@ function pickScheduleSettings(body, taskType) {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' });+ // Field RANGES, not just the 5-token shape: an out-of-range expression saved+ // on an enabled schedule would be silently dropped by the walker and never+ // fire (#6634).+ if (settings.cronExpression !== undefined && settings.cronExpression !== null) {+ const cronError = findCronExpressionError(settings.cronExpression);+ if (cronError) {+ throw new ServerError(`cronExpression is invalid: ${cronError}`, { status: 400, code: 'VALIDATION_ERROR' });+ }}if (settings.labels !== undefined) {const parsed = scheduleLabelsSchema.safeParse(settings.labels);@@ -110,9 +117,14 @@ function pickScheduleSettings(body, taskType) {// Empty string clears it; otherwise require a 5-field cron expression.if (trimmed === '') {settings.recheckCron = null;- } else if (trimmed.split(/\s+/).length !== 5) {- throw new ServerError('recheckCron must be a 5-field cron expression (minute hour dayOfMonth month dayOfWeek)', { status: 400, code: 'VALIDATION_ERROR' });} else {+ // An invalid recheck cron does not merely 'not fire' —+ // computePerpetualRecheckAt silently falls back to another cadence — so+ // reject it here with the same shared validator (#6634).+ const recheckError = findCronExpressionError(trimmed);+ if (recheckError) {+ throw new ServerError(`recheckCron is invalid: ${recheckError}`, { status: 400, code: 'VALIDATION_ERROR' });+ }settings.recheckCron = trimmed;}}diff --git a/server/routes/cosScheduleRoutes.test.js b/server/routes/cosScheduleRoutes.test.jsindex 256e02a9d8..2ffd927ccf 100644--- a/server/routes/cosScheduleRoutes.test.js+++ b/server/routes/cosScheduleRoutes.test.js@@ -506,6 +506,57 @@ describe('CoS Schedule Routes', () => {.send({ type: 'cron', cronExpression: '0 9 * *' });expect(response.status).toBe(400);});++ // #6634: a 5-token expression with an out-of-range field used to be saved+ // and enabled, then silently dropped by the scheduler — an 'enabled'+ // schedule that never fires. The store must not be written at all.+ it('rejects an out-of-range cronExpression before persisting it', async () => {+ for (const cronExpression of ['99 9 * * *', '0 25 * * *']) {+ taskSchedule.updateTaskInterval.mockClear();+ const response = await request(app)+ .put('/api/cos/schedule/task/security')+ .send({ type: 'cron', cronExpression });+ expect(response.status, cronExpression).toBe(400);+ expect(taskSchedule.updateTaskInterval).not.toHaveBeenCalled();+ }+ });++ it('rejects an out-of-range recheckCron before persisting it, and still clears on empty', async () => {+ taskSchedule.updateTaskInterval.mockClear();+ const bad = await request(app)+ .put('/api/cos/schedule/task/security')+ .send({ recheckCron: '99 9 * * *' });+ expect(bad.status).toBe(400);+ expect(taskSchedule.updateTaskInterval).not.toHaveBeenCalled();++ taskSchedule.updateTaskInterval.mockClear();+ const cleared = await request(app)+ .put('/api/cos/schedule/task/security')+ .send({ recheckCron: ' ' });+ expect(cleared.status).toBe(200);+ expect(taskSchedule.updateTaskInterval).toHaveBeenCalledWith('security', { recheckCron: null });++ taskSchedule.updateTaskInterval.mockClear();+ const ok = await request(app)+ .put('/api/cos/schedule/task/security')+ .send({ recheckCron: ' 0 */6 * * * ' });+ expect(ok.status).toBe(200);+ expect(taskSchedule.updateTaskInterval).toHaveBeenCalledWith('security', { recheckCron: '0 */6 * * *' });+ });++ // Syntax validity is not 'has an occurrence in the search window' — the+ // scheduler's bounded walk finds no leap day within two years of this+ // reference, but the expression is still savable.+ it('accepts a leap-day cron that has no occurrence in the search window', async () => {+ taskSchedule.updateTaskInterval.mockClear();+ const response = await request(app)+ .put('/api/cos/schedule/task/security')+ .send({ type: 'cron', cronExpression: '0 0 29 2 *' });+ expect(response.status).toBe(200);+ expect(taskSchedule.updateTaskInterval).toHaveBeenCalledWith('security', expect.objectContaining({+ type: 'cron', cronExpression: '0 0 29 2 *'+ }));+ });});it('normalizes labels, supports clearing, and rejects invalid labels before writing', async () => {diff --git a/server/services/eventScheduler.js b/server/services/eventScheduler.jsindex fa6a79ec38..adb437c627 100644--- a/server/services/eventScheduler.js+++ b/server/services/eventScheduler.js@@ -8,6 +8,10 @@import { cosEvents } from './cosEvents.js'import { getLocalParts } from '../lib/timezone.js'import { recurrenceRuleSchema } from '../lib/recurrenceValidation.js'+// Syntax/range validation is shared with every save boundary and the browser+// cron editor, so an expression the routes accept is exactly the set this+// walker can search (#6634).+import { isValidCronField, CRON_FIELD_BOUNDS, CRON_FIELD_NAMES } from '../lib/cronValidation.js'// Maximum safe setTimeout value (2^31 - 1 ms, ~24.8 days)const MAX_TIMEOUT = 2147483647@@ -22,35 +26,6 @@ const activeTimers = new Map()const eventHistory = []const MAX_HISTORY = 500-/**- * Validate that all numeric values in a cron field fall within the allowed range- * @param {string} expr - Cron field expression- * @param {number} min - Minimum allowed value- * @param {number} max - Maximum allowed value- * @returns {boolean} - True if all values are within range- */-function validateCronFieldRange(expr, min, max) {- if (expr === '*') return true-- // Parse each comma-separated part, handling range (a-b) and step (*/n or a-b/n) syntax- for (const part of expr.split(',')) {- const [rangeExpr, stepStr] = part.split('/')- // Validate step value if present- if (stepStr !== undefined) {- const step = Number(stepStr)- if (isNaN(step) || step < 1) return false- }- // Skip wildcard base (e.g. */5)- if (rangeExpr === '*') continue- // Handle range (a-b) or single value- const bounds = rangeExpr.split('-').map(Number)- if (bounds.some(n => isNaN(n) || n < min || n > max)) return false- // Validate range order- if (bounds.length === 2 && bounds[0] > bounds[1]) return false- }- return true-}-// Maximum iterations for cron search loop (2 years in minutes, matches maxDate window)const MAX_CRON_ITERATIONS = 1051920@@ -78,17 +53,13 @@ function walkCron(cronExpr, from = new Date(), timezone = 'UTC', { stepMs, untilconst [minuteExpr, hourExpr, dayOfMonthExpr, monthExpr, dayOfWeekExpr] = parts- // Validate cron field ranges before entering the search loop- const fieldRanges = [- [minuteExpr, 0, 59, 'minute'],- [hourExpr, 0, 23, 'hour'],- [dayOfMonthExpr, 1, 31, 'dayOfMonth'],- [monthExpr, 1, 12, 'month'],- [dayOfWeekExpr, 0, 7, 'dayOfWeek']- ]- for (const [expr, min, max, name] of fieldRanges) {- if (!validateCronFieldRange(expr, min, max)) {- console.error(`❌ Invalid cron ${name} field "${expr}" in expression: ${cronExpr}`)+ // Validate cron field ranges before entering the search loop. Out-of-range+ // fields return null (not throw) — callers rely on that; the save boundaries+ // reject such expressions up front with the same shared validator.+ for (let i = 0; i < parts.length; i += 1) {+ const [min, max] = CRON_FIELD_BOUNDS[i]+ if (!isValidCronField(parts[i], min, max)) {+ console.error(`❌ Invalid cron ${CRON_FIELD_NAMES[i]} field "${parts[i]}" in expression: ${cronExpr}`)return null}}diff --git a/server/services/taskScheduleConstants.js b/server/services/taskScheduleConstants.jsindex 62056a4383..505c6eb5c9 100644--- a/server/services/taskScheduleConstants.js+++ b/server/services/taskScheduleConstants.js@@ -1,6 +1,7 @@/** Dependency-free task scheduling constants shared by registry and runtime modules. */import { QUOTA_BURN_REQUEST_ORIGIN } from '../lib/quotaBurnOrigin.js';+import { isCronShaped } from '../lib/cronValidation.js';const MINUTE_MS = 60 * 1000;const HOUR_MS = 60 * MINUTE_MS;@@ -67,10 +68,12 @@ export const isUserOriginRequest = (request) =>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;-}+/**+ * A 5-field cron expression (the only string cadence the scheduler accepts).+ * SHAPE only — it distinguishes a cron from a named cadence and says nothing+ * about validity; `isValidCronExpression` is what save boundaries gate on.+ */+export const isCronExpression = isCronShaped;/*** Approximate a numeric interval as a 5-field cron expression. Used by the