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

Add scheduled Series Autopilot runs (per-series cron, consent-gated)

[._.]/ Adam Eivyd0d4b82d13f1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c1896419d3..f8512e39ce 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -36,6 +36,10 @@
- The standalone `/layered-intelligence` page has been removed — with the loop now a per-app scheduled task, its status is seen and managed in CoS → Schedule like every other task, and per-app behavior stays on Edit App → Intelligence. (The dedicated cross-app overview/proposals page and its endpoints are gone; nothing else surfaced there.)
- **[issue-2326] The app Automation page now edits per-task provider/model overrides inline.** Each task row on Edit App → Automation gained a "⚙ Configure" disclosure that expands a per-app provider + model override (with "Use default provider" to inherit the global/task default) — previously reachable only from CoS → Schedule → Configure. The `layered-intelligence` row additionally links straight to its behavior config (telemetry sources, allowed scopes, guidance rules) on the Edit App → Intelligence tab, so an app's full self-improvement setup is configurable without leaving the app.
+## Series Autopilot
+
+- **[issue-2174] A series can now run its autopilot on a schedule — progress overnight, unattended.** Series Autopilot used to be button-only ("Run Autonomously to Completion"); each series can now register a cron schedule (via the day/time picker on the Autopilot panel) so its draft advances on a timer, autonovel-style. Setup is explicit and consent-gated per the AI Provider Usage Policy: the panel names the exact provider/model each run will call (with an override picker that otherwise falls back to the series' own configured provider) and the CoS autonomy mode + daily action-budget cap the run is gated by, and the enable toggle is **off by default** — no schedule fires until you turn it on. Every existing autonomy gate still applies: a run is skipped when CoS autonomy is off, it spends against the CoS daily action budget, and it pauses to notify you (rather than retrying forever) on a convergence stall. Schedules are stored per machine, so a series synced to another peer doesn't double-run there, and editing a schedule (time, provider, enable) takes effect on the next run without a server restart.
+
## Changed
- **The Shell page's quick-launch shortcuts are simpler.** The one-click `codex` launcher now runs `codex --dangerously-bypass-approvals-and-sandbox`, so an interactive Codex session started from the Shell page can edit files and run commands without stopping to approve each one — matching how the `claude` shortcut already runs with `--dangerously-skip-permissions`. The `claude` shortcut no longer appends `--system-prompt .` (it launches with Claude's full default prompt), and the redundant `claude (full)` shortcut has been removed.
diff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsx
index fa58343398..20357f4edb 100644
--- a/client/src/components/pipeline/AutopilotPanel.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.jsx
@@ -17,6 +17,7 @@ import {
getSettings,
patchSettingsSlice,
} from '../../services/api';
+import SeriesAutopilotSchedule from './SeriesAutopilotSchedule';
// Convergence-round bounds — mirror the server (seriesAutopilot.js + the
// pipelineEditorialChecks settings schema). 0 = skip that gate entirely.
@@ -785,6 +786,9 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
);
})() : null}
+ {/* Scheduled unattended runs (#2174) — hidden while a run is active. */}
+ {!active ? <SeriesAutopilotSchedule series={series} /> : null}
+
{/* Production readiness (canon descriptive integrity) */}
<div className="px-3 pb-3 border-t border-port-border pt-2">
<div className="flex items-center gap-2">
diff --git a/client/src/components/pipeline/SeriesAutopilotSchedule.jsx b/client/src/components/pipeline/SeriesAutopilotSchedule.jsx
new file mode 100644
index 0000000000..d774ddf8e7
--- /dev/null
+++ b/client/src/components/pipeline/SeriesAutopilotSchedule.jsx
@@ -0,0 +1,238 @@
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { CalendarClock, Loader2, AlertTriangle, Trash2 } from 'lucide-react';
+import { getSettings, patchSettingsSlice } from '../../services/apiSystem';
+import { getProviders } from '../../services/apiProviders';
+import { getCosConfig } from '../../services/apiAgents';
+import { describeCron } from '../../utils/cronHelpers';
+import { providerDisplayName, assignmentModelOptions } from '../../utils/providers';
+import CronInput from '../CronInput';
+import ProviderModelSelector from '../ProviderModelSelector';
+import toast from '../ui/Toast';
+
+/**
+ * Scheduled Series Autopilot setup (#2174).
+ *
+ * Lets the user register a cron schedule so this series runs its autopilot
+ * unattended (overnight, autonovel-style). This is the AI Provider Usage
+ * Policy's sanctioned "scheduled automation" exception, so the UI is an
+ * explicit, consent-gated setup that:
+ * - names the provider/model the scheduled run will use (with a picker to
+ * change it — falls back to the series' own configured provider),
+ * - names the CoS autonomy mode + daily action-budget cap the run is gated by,
+ * - keeps the enable toggle OFF by default (no schedule until the user opts in).
+ *
+ * Schedules are stored MACHINE-LOCALLY in `settings.seriesAutopilot.schedules`
+ * (settings.json doesn't federate) — a schedule on the federated series record
+ * would double-run the same series across sync peers.
+ */
+export default function SeriesAutopilotSchedule({ series }) {
+ const seriesId = series?.id;
+ const [loaded, setLoaded] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [editingCron, setEditingCron] = useState(false);
+
+ // The persisted schedule entry for THIS series (null when none configured).
+ const [entry, setEntry] = useState(null);
+ // Context for the consent copy.
+ const [providers, setProviders] = useState([]);
+ const [activeProviderId, setActiveProviderId] = useState(null);
+ const [cosMode, setCosMode] = useState(null);
+ const [cosBudget, setCosBudget] = useState(null); // maxActionsPerDay or null (unlimited)
+
+ // Global, series-independent context (providers + CoS autonomy/budget) — fetch
+ // once, not on every series switch.
+ useEffect(() => {
+ let canceled = false;
+ Promise.all([
+ getProviders({ silent: true }).catch(() => null),
+ getCosConfig({ silent: true }).catch(() => null),
+ ]).then(([provData, cos]) => {
+ if (canceled) return;
+ setProviders(provData?.providers || []);
+ setActiveProviderId(provData?.activeProvider || null);
+ setCosMode(cos?.domainAutonomy?.cos ?? 'execute');
+ const cap = cos?.domainBudgets?.cos?.maxActionsPerDay;
+ setCosBudget(Number.isFinite(cap) && cap > 0 ? cap : null);
+ });
+ return () => { canceled = true; };
+ }, []);
+
+ // This series' persisted schedule entry — reloads when the series changes.
+ // Reset first so a switch can't briefly show (and let the user save) the
+ // previous series' schedule under the new seriesId before the fetch resolves.
+ useEffect(() => {
+ let canceled = false;
+ setLoaded(false);
+ setEntry(null);
+ getSettings({ silent: true }).catch(() => null).then((settings) => {
+ if (canceled) return;
+ const schedules = settings?.seriesAutopilot?.schedules;
+ setEntry(Array.isArray(schedules) ? schedules.find((s) => s?.seriesId === seriesId) || null : null);
+ setLoaded(true);
+ });
+ return () => { canceled = true; };
+ }, [seriesId]);
+
+ // Effective provider/model the scheduled run will use: schedule override →
+ // series' own llm → the active provider. Mirrors startSeriesAutopilot's
+ // provider resolution so the consent copy names what will actually run. Only
+ // inherit the series' MODEL when the effective provider IS the series provider
+ // — an override to a different provider uses that provider's default model, so
+ // showing the series' model would misname what runs.
+ const effProviderId = entry?.provider || series?.llm?.provider || activeProviderId || '';
+ const inheritsSeriesLlm = !entry?.provider || entry.provider === series?.llm?.provider;
+ const effModel = entry?.model || (inheritsSeriesLlm ? series?.llm?.model || '' : '');
+ const providerLabel = (id) => providerDisplayName(providers, id, '—');
+ const providerModels = useMemo(
+ () => assignmentModelOptions(null, providers, effProviderId),
+ [providers, effProviderId],
+ );
+
+ // Persist a mutated entry for this series, preserving every OTHER series'
+ // schedule. Re-reads the freshest schedules array so a sibling series edited
+ // elsewhere isn't clobbered, then replaces/removes just this series' element.
+ const persist = useCallback(async (nextEntry) => {
+ setSaving(true);
+ const stamped = nextEntry ? { ...nextEntry, seriesId } : null;
+ const settings = await getSettings({ silent: true }).catch(() => null);
+ const others = Array.isArray(settings?.seriesAutopilot?.schedules)
+ ? settings.seriesAutopilot.schedules.filter((s) => s?.seriesId !== seriesId)
+ : [];
+ const next = stamped ? [...others, stamped] : others;
+ const ok = await patchSettingsSlice('seriesAutopilot', { schedules: next }, { silent: true })
+ .then(() => true)
+ .catch((err) => { toast.error(err.message || 'Failed to save schedule'); return false; });
+ if (ok) setEntry(stamped);
+ setSaving(false);
+ return ok;
+ }, [seriesId]);
+
+ // patch-merge helpers — the provider/model/enable controls render only inside
+ // the `hasCron` block, so `entry` is a full object there; `saveCron`'s spread
+ // of a possibly-null entry is a spec-safe no-op.
+ const saveCron = async (cron) => {
+ setEditingCron(false);
+ // Setting a cron never auto-enables — the user still flips the toggle (consent).
+ await persist({ ...entry, cron });
+ };
+ const toggleEnabled = async (enabled) => {
+ if (enabled && !entry?.cron) {
+ toast.error('Set a schedule time first');
+ return;
+ }
+ await persist({ ...entry, enabled });
+ };
+ const setProvider = async (provider) => persist({ ...entry, provider: provider || undefined, model: undefined });
+ const setModel = async (model) => persist({ ...entry, model: model || undefined });
+
+ const removeSchedule = async () => {
+ await persist(null);
+ setEditingCron(false);
+ };
+
+ if (!seriesId) return null;
+
+ const enabled = !!entry?.enabled;
+ const hasCron = !!entry?.cron;
+
+ return (
+ <div className="border-t border-port-border px-3 py-3 flex flex-col gap-2.5">
+ <div className="flex items-center gap-2 flex-wrap">
+ <CalendarClock size={14} className="text-port-accent" />
+ <span className="text-sm font-medium text-white">Scheduled runs</span>
+ <span className="text-xs text-gray-500">progress this series unattended on a timer</span>
+ {saving ? <Loader2 size={12} className="animate-spin text-gray-500 ml-auto" /> : null}
+ </div>
+
+ {!loaded ? (
+ <p className="text-xs text-gray-500">Loading…</p>
+ ) : (
+ <>
+ {/* Schedule time */}
+ <div className="flex items-center gap-2 flex-wrap text-xs">
+ <span className="text-gray-400">When:</span>
+ {editingCron ? (
+ <CronInput
+ value={entry?.cron || '0 3 * * *'}
+ onSave={saveCron}
+ onCancel={() => setEditingCron(false)}
+ />
+ ) : (
+ <>
+ <span className="text-gray-200">{hasCron ? describeCron(entry.cron) : 'not set'}</span>
+ <button
+ type="button"
+ onClick={() => setEditingCron(true)}
+ className="px-2 py-0.5 rounded border border-port-border bg-port-bg text-gray-300 hover:border-port-accent/40 hover:text-white"
+ >
+ {hasCron ? 'Change' : 'Set schedule'}
+ </button>
+ {hasCron ? (
+ <button
+ type="button"
+ onClick={removeSchedule}
+ disabled={saving}
+ className="inline-flex items-center gap-1 px-2 py-0.5 rounded border border-port-border bg-port-bg text-gray-400 hover:text-port-error hover:border-port-error/40 disabled:opacity-40"
+ title="Remove schedule"
+ >
+ <Trash2 size={11} /> Remove
+ </button>
+ ) : null}
+ </>
+ )}
+ </div>
+
+ {/* Consent context: names the provider/model + the budget/autonomy gate. */}
+ {hasCron ? (
+ <div className="rounded-lg border border-port-border bg-port-bg/60 p-2.5 flex flex-col gap-2">
+ <p className="text-[11px] text-gray-400 leading-relaxed">
+ Each scheduled run calls your AI provider automatically. It runs as{' '}
+ <span className="text-gray-200 font-medium">{providerLabel(effProviderId)}</span>
+ {effModel ? <> / <span className="text-gray-200 font-medium">{effModel}</span></> : <> (provider default model)</>}
+ , and is gated by the CoS autonomy mode{' '}
+ <span className={`font-medium ${cosMode === 'off' ? 'text-port-error' : 'text-gray-200'}`}>{cosMode || 'execute'}</span>
+ {' '}and the CoS daily action budget{' '}
+ <span className="text-gray-200 font-medium">{cosBudget ? `(${cosBudget} actions/day)` : '(no cap set)'}</span>.
+ {' '}Runs pause and notify you instead of retrying forever.
+ </p>
+
+ <div className="max-w-md">
+ <ProviderModelSelector
+ providers={providers}
+ selectedProviderId={entry?.provider ?? ''}
+ selectedModel={entry?.model || ''}
+ availableModels={providerModels}
+ onProviderChange={setProvider}
+ onModelChange={setModel}
+ label="Override provider for scheduled runs"
+ compact
+ alwaysShowModel
+ emptyProviderOption={`Use series default (${providerLabel(series?.llm?.provider || activeProviderId)})`}
+ emptyModelOption="Default model"
+ />
+ </div>
+
+ {cosMode === 'off' ? (
+ <p className="text-[11px] text-port-warning flex items-start gap-1">
+ <AlertTriangle size={12} className="mt-0.5 shrink-0" />
+ CoS autonomy is off — scheduled runs will be skipped until you set it to dry-run or execute in CoS settings.
+ </p>
+ ) : null}
+
+ {/* Enable toggle — OFF by default; turning it ON is the consent. */}
+ <label className="flex items-center gap-2 text-xs text-gray-200 pt-0.5">
+ <input
+ type="checkbox"
+ checked={enabled}
+ disabled={saving || !hasCron}
+ onChange={(e) => toggleEnabled(e.target.checked)}
+ />
+ <span className="font-medium">Enable scheduled autopilot for this series</span>
+ </label>
+ </div>
+ ) : null}
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/pipeline/SeriesAutopilotSchedule.test.jsx b/client/src/components/pipeline/SeriesAutopilotSchedule.test.jsx
new file mode 100644
index 0000000000..016805b680
--- /dev/null
+++ b/client/src/components/pipeline/SeriesAutopilotSchedule.test.jsx
@@ -0,0 +1,112 @@
+import { it, expect, vi, beforeEach } from 'vitest';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+
+vi.mock('../../services/apiSystem', () => ({
+ getSettings: vi.fn(),
+ patchSettingsSlice: vi.fn(),
+}));
+vi.mock('../../services/apiProviders', () => ({ getProviders: vi.fn() }));
+vi.mock('../../services/apiAgents', () => ({ getCosConfig: vi.fn() }));
+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), warning: vi.fn() } }));
+
+import { getSettings, patchSettingsSlice } from '../../services/apiSystem';
+import { getProviders } from '../../services/apiProviders';
+import { getCosConfig } from '../../services/apiAgents';
+import SeriesAutopilotSchedule from './SeriesAutopilotSchedule';
+
+const SERIES = { id: 's1', name: 'Test', llm: { provider: 'anthropic', model: 'claude-opus-4-8' } };
+
+const settingsWith = (schedules = []) => ({ seriesAutopilot: { schedules } });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getSettings.mockResolvedValue(settingsWith([]));
+ getProviders.mockResolvedValue({
+ providers: [{ id: 'anthropic', name: 'Anthropic', models: ['claude-opus-4-8'] }],
+ activeProvider: 'anthropic',
+ });
+ getCosConfig.mockResolvedValue({
+ domainAutonomy: { cos: 'execute' },
+ domainBudgets: { cos: { maxActionsPerDay: 40 } },
+ });
+ patchSettingsSlice.mockResolvedValue({});
+});
+
+it('shows "Set schedule" and no consent card when nothing is configured', async () => {
+ render(<SeriesAutopilotSchedule series={SERIES} />);
+ expect(await screen.findByText('Set schedule')).toBeInTheDocument();
+ // No cron → no consent/enable UI yet.
+ expect(screen.queryByText(/Enable scheduled autopilot/)).not.toBeInTheDocument();
+});
+
+it('names the effective provider/model and the cos budget cap in the consent copy', async () => {
+ getSettings.mockResolvedValue(settingsWith([{ seriesId: 's1', enabled: false, cron: '0 3 * * *' }]));
+ render(<SeriesAutopilotSchedule series={SERIES} />);
+ // The daily budget cap is unique to the consent copy; provider/model also
+ // appear in the override <select> options, so allow multiple matches there.
+ expect(await screen.findByText(/40 actions\/day/)).toBeInTheDocument();
+ expect(screen.getAllByText('Anthropic').length).toBeGreaterThan(0);
+ expect(screen.getAllByText('claude-opus-4-8').length).toBeGreaterThan(0);
+});
+
+it('enable toggle is OFF by default and enabling persists enabled:true', async () => {
+ getSettings.mockResolvedValue(settingsWith([{ seriesId: 's1', enabled: false, cron: '0 3 * * *' }]));
+ render(<SeriesAutopilotSchedule series={SERIES} />);
+ const toggle = await screen.findByRole('checkbox');
+ expect(toggle).not.toBeChecked();
+ fireEvent.click(toggle);
+ await waitFor(() => expect(patchSettingsSlice).toHaveBeenCalled());
+ const [slice, payload] = patchSettingsSlice.mock.calls[0];
+ expect(slice).toBe('seriesAutopilot');
+ expect(payload.schedules).toEqual([
+ expect.objectContaining({ seriesId: 's1', cron: '0 3 * * *', enabled: true }),
+ ]);
+});
+
+it('preserves OTHER series schedules when saving this one', async () => {
+ getSettings.mockResolvedValue(settingsWith([
+ { seriesId: 'other', enabled: true, cron: '0 5 * * *' },
+ { seriesId: 's1', enabled: false, cron: '0 3 * * *' },
+ ]));
+ render(<SeriesAutopilotSchedule series={SERIES} />);
+ const toggle = await screen.findByRole('checkbox');
+ fireEvent.click(toggle);
+ await waitFor(() => expect(patchSettingsSlice).toHaveBeenCalled());
+ const ids = patchSettingsSlice.mock.calls[0][1].schedules.map((s) => s.seriesId);
+ expect(ids).toContain('other');
+ expect(ids).toContain('s1');
+});
+
+it('does not name the series model when the override provider differs from the series provider', async () => {
+ // Override to openai; the series is on anthropic. The run will use openai's
+ // DEFAULT model, so the consent copy must not show the series' anthropic model.
+ getProviders.mockResolvedValue({
+ providers: [
+ { id: 'anthropic', name: 'Anthropic', models: ['claude-opus-4-8'] },
+ { id: 'openai', name: 'OpenAI', models: ['gpt-5.6'] },
+ ],
+ activeProvider: 'anthropic',
+ });
+ getSettings.mockResolvedValue(settingsWith([{ seriesId: 's1', enabled: false, cron: '0 3 * * *', provider: 'openai' }]));
+ render(<SeriesAutopilotSchedule series={SERIES} />);
+ expect(await screen.findByText(/provider default model/)).toBeInTheDocument();
+ expect(screen.queryByText('claude-opus-4-8')).not.toBeInTheDocument();
+});
+
+it('clears the prior series schedule when switching series so it is not shown/saved under the new id', async () => {
+ // settings only holds s1's schedule; s2 has none.
+ getSettings.mockResolvedValue(settingsWith([{ seriesId: 's1', enabled: true, cron: '0 3 * * *' }]));
+ const { rerender } = render(<SeriesAutopilotSchedule series={SERIES} />);
+ await screen.findByText('Change'); // s1's configured schedule renders
+ // Switch to s2 (different id, no schedule) — must not keep showing s1's cron/consent.
+ rerender(<SeriesAutopilotSchedule series={{ id: 's2', name: 'Other', llm: {} }} />);
+ expect(await screen.findByText('Set schedule')).toBeInTheDocument();
+ expect(screen.queryByText(/Enable scheduled autopilot/)).not.toBeInTheDocument();
+});
+
+it('warns when CoS autonomy is off', async () => {
+ getSettings.mockResolvedValue(settingsWith([{ seriesId: 's1', enabled: false, cron: '0 3 * * *' }]));
+ getCosConfig.mockResolvedValue({ domainAutonomy: { cos: 'off' }, domainBudgets: {} });
+ render(<SeriesAutopilotSchedule series={SERIES} />);
+ expect(await screen.findByText(/CoS autonomy is off/)).toBeInTheDocument();
+});
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index 67dd5188ae..1769f15c34 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -44,7 +44,7 @@ export const pauseCos = (reason) => request('/cos/pause', {
body: JSON.stringify({ reason })
});
export const resumeCos = (options = {}) => request('/cos/resume', { method: 'POST', ...options });
-export const getCosConfig = () => request('/cos/config');
+export const getCosConfig = (options) => request('/cos/config', options);
export const updateCosConfig = (config, options = {}) => request('/cos/config', {
method: 'PUT',
body: JSON.stringify(config),
diff --git a/server/index.js b/server/index.js
index 69ba0da4d5..55495393a1 100644
--- a/server/index.js
+++ b/server/index.js
@@ -173,6 +173,7 @@ import * as agentActionExecutor from './services/agentActionExecutor.js';
import * as cos from './services/cos.js';
import { startBackupScheduler } from './services/backupScheduler.js';
import { startPrivacyRecheckScheduler } from './services/privacyRecheckScheduler.js';
+import { startSeriesAutopilotScheduler } from './services/seriesAutopilotScheduler.js';
import { startCitySnapshotScheduler } from './services/citySnapshotScheduler.js';
import { startImessageScheduler } from './services/imessageScheduler.js';
import { startSignalScheduler } from './services/signalScheduler.js';
@@ -624,6 +625,11 @@ startBackupScheduler().catch(err => console.error(`❌ Backup scheduler init fai
// re-runs the broker scan + opt-out pass when the user opts in via
// Settings → Privacy (sanctioned scheduled-automation exception) (#2145).
startPrivacyRecheckScheduler().catch(err => console.error(`❌ Privacy recheck scheduler init failed: ${err.message}`));
+// Initialize Series Autopilot scheduler — OFF by default; registers a cron per
+// series only when the user configured + enabled one via Settings → Series
+// Autopilot. Each scheduled run still passes through the cos autonomy gate +
+// daily budget (sanctioned scheduled-automation exception) (#2174).
+startSeriesAutopilotScheduler().catch(err => console.error(`❌ Series Autopilot scheduler init failed: ${err.message}`));
// Initialize CyberCity snapshot scheduler — records periodic city-state frames
// for the historical timeline scrubber (issue #877).
startCitySnapshotScheduler().catch(err => console.error(`❌ City snapshot scheduler init failed: ${err.message}`));
diff --git a/server/lib/validation.js b/server/lib/validation.js
index df3d209ea2..7a617a10c3 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -400,6 +400,65 @@ export const backupConfigSchema = z.object({
disabledDefaultExcludes: z.array(z.string()).optional().default([])
});
+// Scheduled Series Autopilot (#2174). Machine-local per-series cron schedules
+// that fire `startSeriesAutopilot` unattended — the AI Provider Usage Policy's
+// sanctioned "scheduled automation" exception. Stored under the top-level
+// `seriesAutopilot` settings key (NOT on the federated series record — a
+// schedule that synced to a peer would double-run the same series). Each entry
+// is OFF by default (`enabled` defaults false); the run itself still passes
+// through the cos-domain autonomy gate + daily budget inside startSeriesAutopilot.
+// provider/model are OPTIONAL overrides — when absent the run uses the series'
+// own `series.llm` (or the active provider); the scheduler maps them to the
+// pipeline's providerOverride/modelOverride. A blank provider/model (UI sentinel
+// for "use the series default") is coerced to undefined so it doesn't pin an
+// 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])));
+};
+
+export const seriesAutopilotScheduleSchema = z.object({
+ seriesId: z.string().min(1).max(64),
+ enabled: z.boolean().optional().default(false),
+ cron: z.string().min(1).max(120).refine(isValidCronExpression, 'invalid cron expression'),
+ timezone: z.string().min(1).max(64).optional(),
+ provider: z.preprocess((v) => (v === '' ? undefined : v), z.string().min(1).max(120).optional()),
+ model: z.preprocess((v) => (v === '' ? undefined : v), z.string().min(1).max(200).optional()),
+}).strict();
+
+export const seriesAutopilotSettingsSchema = z.object({
+ schedules: z.array(seriesAutopilotScheduleSchema).optional().default([]),
+}).strict();
+
// Per-API external-access flags (issue: public API surface). Stored under the
// top-level `apiAccess` settings key (client-readable — NOT under `secrets`).
// Drives `server/lib/apiRegistry.js`: an entry that is `exposed && !requireAuth`
diff --git a/server/lib/validation.test.js b/server/lib/validation.test.js
index d266576f66..5268d3802b 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -26,6 +26,7 @@ import {
subdirFilterSchema,
isPaginationRequested,
paginateArray,
+ seriesAutopilotSettingsSchema,
} from './validation.js';
describe('validation.js', () => {
@@ -1081,3 +1082,34 @@ describe('validation.js', () => {
});
});
});
+
+describe('seriesAutopilotSettingsSchema (#2174)', () => {
+ const rejects = (cron) => expect(seriesAutopilotSettingsSchema.safeParse({
+ schedules: [{ seriesId: 's1', cron }],
+ }).success).toBe(false);
+ const accepts = (cron) => expect(seriesAutopilotSettingsSchema.safeParse({
+ schedules: [{ seriesId: 's1', cron }],
+ }).success).toBe(true);
+
+ it('rejects out-of-range / malformed crons so an enabled schedule cannot silently never fire', () => {
+ rejects('99 99 * * *'); // minute/hour out of range
+ rejects('0 3 * *'); // only 4 fields
+ rejects('0 3 * * * *'); // 6 fields
+ rejects('not a cron');
+ rejects('60 * * * *'); // minute 60 (max 59)
+ });
+
+ it('accepts common valid crons (ranges, lists, steps)', () => {
+ accepts('0 3 * * *');
+ accepts('*/15 * * * *');
+ accepts('0 9 * * 1-5');
+ accepts('0 0,12 1 */2 *');
+ });
+
+ it('defaults enabled to false and coerces blank provider/model to undefined', () => {
+ const parsed = seriesAutopilotSettingsSchema.parse({
+ schedules: [{ seriesId: 's1', cron: '0 3 * * *', provider: '', model: '' }],
+ });
+ expect(parsed.schedules[0]).toEqual({ seriesId: 's1', cron: '0 3 * * *', enabled: false });
+ });
+});
diff --git a/server/routes/settings.js b/server/routes/settings.js
index a68fdd9063..46c5327189 100644
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@ -10,7 +10,7 @@ import {
} from '../services/mediaJobQueue/index.js';
import { asyncHandler } from '../lib/errorHandler.js';
import { isPlainObject } from '../lib/objects.js';
-import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, privacySettingsSchema, validateRequest } from '../lib/validation.js';
+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, validateRequest } from '../lib/validation.js';
const router = Router();
@@ -198,6 +198,13 @@ router.put('/', asyncHandler(async (req, res) => {
if (req.body?.privacy !== undefined) {
validateRequest(privacySettingsSchema.partial(), req.body.privacy);
}
+ // Scheduled Series Autopilot config (#2174) — validate the slice when present
+ // so an invalid cron (rejected by the schema's isValidCronExpression refine) or
+ // bad seriesId can't reach disk and leave an "enabled" schedule that never fires.
+ // `.partial()` so a PUT that only carries { schedules } still validates.
+ if (req.body?.seriesAutopilot !== undefined) {
+ validateRequest(seriesAutopilotSettingsSchema.partial(), req.body.seriesAutopilot);
+ }
// User-defined catalog types moved out of settings.json into PostgreSQL
// (`catalog_user_types`, #1001). The `/api/catalog/types` routes are the only
// write path; a `catalogUserTypes` key in a PUT /api/settings body (legacy
@@ -220,6 +227,11 @@ router.put('/', asyncHandler(async (req, res) => {
// merged value so a save takes effect without a restart and without
// re-reading the file.
setCodexParallelLimit(merged.imageGen?.codex?.parallelLimit ?? CODEX_PARALLEL_DEFAULT);
+ // Series Autopilot crons re-register themselves off settings.js's
+ // `settings:updated` event (see seriesAutopilotScheduler.js) — the save above
+ // already emitted it — so an added/removed/edited schedule takes effect
+ // immediately without a restart, and this route stays decoupled from the
+ // autopilot pipeline graph.
res.json(sanitizeSettingsForResponse(merged));
}));
diff --git a/server/services/seriesAutopilotScheduler.js b/server/services/seriesAutopilotScheduler.js
new file mode 100644
index 0000000000..e6d1187a16
--- /dev/null
+++ b/server/services/seriesAutopilotScheduler.js
@@ -0,0 +1,215 @@
+/**
+ * Scheduled Series Autopilot (#2174)
+ *
+ * Registers a cron job per user-configured series so a series can progress
+ * unattended (autonovel-style overnight runs). This is the AI Provider Usage
+ * Policy's sanctioned "scheduled automations" exception — the user explicitly
+ * configured each schedule via Settings, naming the provider/model and enabling
+ * it (OFF by default), so it may call an AI provider on its own cadence.
+ *
+ * Design decisions:
+ * - **Machine-local, not federated.** Schedules live in `settings.seriesAutopilot`
+ * (settings.json is per-machine and does NOT sync between peers). A schedule on
+ * the federated *series record* would double-run the same series across two sync
+ * peers; storing it in settings keeps execution to the machine that configured it.
+ * - **Re-read settings every invocation** (backupScheduler.js pattern): the handler
+ * re-reads `settings.seriesAutopilot`, so `enabled`, provider/model, and the run
+ * options all take effect on the next scheduled run without a restart. The cron
+ * expression itself is captured at registration — so an edited cron needs a
+ * re-sync, which `syncSeriesAutopilotSchedules()` performs (wired into the
+ * settings PUT route) so even a cron change applies without a restart.
+ * - **Every autonomy gate still applies.** The handler delegates to
+ * `startSeriesAutopilot`, which rejects when the cos domain is `off`, runs
+ * under the cos daily action budget, and (when `notifyOnPause`) notifies rather
+ * than retrying forever on a convergence pause — the scheduler adds no new
+ * autonomy surface, it only *triggers* the existing one on a timer.
+ */
+
+import { schedule, cancel, isValidCron } from './eventScheduler.js';
+import { getSettings, settingsEvents } from './settings.js';
+import { getSeries } from './pipeline/series.js';
+import { startSeriesAutopilot } from './pipeline/seriesAutopilot.js';
+import { getUserTimezone } from '../lib/timezone.js';
+
+// eventScheduler id namespace for a per-series cron. One event per seriesId.
+const eventId = (seriesId) => `series-autopilot-${seriesId}`;
+
+// seriesIds we currently hold a registered cron for — so a re-sync can cancel
+// events whose schedule was removed or disabled since the last registration.
+const registered = new Set();
+
+// Signature of the last-synced registration inputs (which series, at what cron
+// + timezone). The `settings:updated` subscription fires on EVERY settings save;
+// this lets an unrelated save short-circuit instead of re-registering — and
+// re-computing next-run for — every series cron. provider/model are excluded
+// deliberately: they don't affect registration (the handler re-reads them per run).
+let lastSignature = null;
+
+/**
+ * Pure extractor: the enabled, cron-valid schedules from a settings snapshot.
+ * A schedule needs `enabled === true`, a non-empty `seriesId`, and a cron
+ * expression the eventScheduler accepts — anything else is skipped (a disabled
+ * or malformed entry simply doesn't register). Deduplicates by seriesId,
+ * last-wins, so a hand-edited settings.json with two entries for one series
+ * can't register two competing crons.
+ * @param {object} settings - a full settings object
+ * @returns {Array<object>} the runnable schedule entries
+ */
+export function activeSchedules(settings) {
+ const raw = settings?.seriesAutopilot?.schedules;
+ if (!Array.isArray(raw)) return [];
+ const byId = new Map();
+ for (const s of raw) {
+ if (!s || typeof s !== 'object') continue;
+ if (s.enabled !== true) continue;
+ if (typeof s.seriesId !== 'string' || !s.seriesId) continue;
+ if (typeof s.cron !== 'string' || !isValidCron(s.cron)) continue;
+ byId.set(s.seriesId, s);
+ }
+ return [...byId.values()];
+}
+
+/**
+ * Map a schedule entry to the options object passed to startSeriesAutopilot.
+ * Only forwards the honored subset, dropping absent fields so the autopilot's
+ * own per-run → persisted → default resolution still applies to everything the
+ * schedule doesn't pin. The schedule stores user-facing `provider`/`model`; the
+ * autopilot LLM calls read `providerOverride`/`modelOverride` (the pipeline's
+ * provider-override convention), so map them here.
+ */
+export function runOptionsFor(entry) {
+ const opts = {};
+ if (entry.provider) opts.providerOverride = entry.provider;
+ if (entry.model) opts.modelOverride = entry.model;
+ return opts;
+}
+
+/**
+ * The cron handler for one series. Re-reads settings so a toggle/edit since
+ * registration takes effect, re-checks the series still exists, then delegates
+ * to startSeriesAutopilot — which owns the autonomy gate (it returns
+ * `{ rejected: true }` when the cos domain is `off`), the cos daily action
+ * budget, and the notify-on-pause behavior. The scheduler adds no new autonomy
+ * surface, so it delegates rather than re-deriving the cos mode (which lives in
+ * the cos state, not settings). Runs outside the Express request lifecycle, so
+ * it must never throw — a throw here would crash the process (no `next(err)` to
+ * bubble to).
+ */
+async function runScheduledAutopilot(seriesId) {
+ try {
+ const settings = await getSettings().catch(() => null);
+ const entry = activeSchedules(settings).find((s) => s.seriesId === seriesId);
+ if (!entry) {
+ console.log(`🎬 Series Autopilot scheduler: #${seriesId} disabled/removed since registration — skipping run`);
+ return;
+ }
+ const series = await getSeries(seriesId).catch(() => null);
+ if (!series) {
+ console.log(`🎬 Series Autopilot scheduler: series ${seriesId} not found — skipping run`);
+ return;
+ }
+ console.log(`🎬 Series Autopilot scheduler: starting scheduled run for ${seriesId}`);
+ const result = await startSeriesAutopilot(seriesId, runOptionsFor(entry));
+ if (result?.rejected) {
+ // cos autonomy is off — the sanctioned gate refused the run. Expected, not an error.
+ console.log(`🎬 Series Autopilot scheduler: run for ${seriesId} rejected (cos autonomy ${result.mode})`);
+ } else if (result?.alreadyRunning) {
+ console.log(`🎬 Series Autopilot scheduler: ${seriesId} already running — scheduled tick is a no-op`);
+ }
+ } catch (err) {
+ console.error(`❌ Series Autopilot scheduler: run for ${seriesId} failed: ${err.message}`);
+ }
+}
+
+/**
+ * Register (or re-register) the cron for one schedule entry. eventScheduler's
+ * `schedule()` cancels an existing event with the same id, so calling this for
+ * a series that already has a cron cleanly replaces it (picking up an edited
+ * cron/timezone).
+ */
+function registerSchedule(entry, timezone) {
+ const sid = entry.seriesId; // capture only the id — the handler re-reads the entry per run
+ schedule({
+ id: eventId(sid),
+ type: 'cron',
+ cron: entry.cron,
+ timezone: entry.timezone || timezone,
+ handler: () => runScheduledAutopilot(sid),
+ metadata: { source: 'seriesAutopilotScheduler', seriesId: sid },
+ });
+ registered.add(sid);
+}
+
+// Registration-affecting fingerprint of the active schedules (+ the fallback
+// timezone). Two snapshots with the same fingerprint register identical crons,
+// so a save that didn't touch scheduling can skip the whole re-sync.
+function signatureOf(active, fallbackTz) {
+ return JSON.stringify({
+ tz: fallbackTz ?? null,
+ s: active.map((e) => [e.seriesId, e.cron, e.timezone ?? null]),
+ });
+}
+
+/**
+ * (Re)synchronize the registered crons to match the given settings snapshot:
+ * register/replace every active schedule and cancel any previously-registered
+ * series that is no longer active (removed or disabled). Idempotent — safe to
+ * call at boot and after every settings save. Short-circuits when the
+ * registration inputs are unchanged since the last sync (the `settings:updated`
+ * bus fires on every save, most of which don't touch scheduling).
+ * @param {object} [settings] - a settings snapshot; re-read when omitted
+ */
+export async function syncSeriesAutopilotSchedules(settings) {
+ const current = settings || await getSettings().catch(() => null);
+ const active = activeSchedules(current);
+ const timezone = await getUserTimezone().catch(() => 'UTC');
+
+ const signature = signatureOf(active, current?.timezone);
+ if (signature === lastSignature) return active.length; // nothing registration-affecting changed
+ lastSignature = signature;
+
+ const activeIds = new Set(active.map((s) => s.seriesId));
+ // Cancel crons whose schedule is gone/disabled.
+ for (const seriesId of [...registered]) {
+ if (!activeIds.has(seriesId)) {
+ cancel(eventId(seriesId));
+ registered.delete(seriesId);
+ }
+ }
+ // Register/replace the active ones.
+ for (const entry of active) {
+ registerSchedule(entry, timezone);
+ }
+ console.log(`🎬 Series Autopilot scheduler: ${active.length} schedule(s) active`);
+ return active.length;
+}
+
+// Re-sync when settings change, rather than being called from the settings
+// route — keeps the HTTP handler decoupled from the autopilot pipeline graph
+// (mirrors meatspacePostReminder.js). The signature guard above makes an
+// unrelated save a cheap no-op.
+settingsEvents.on('settings:updated', (cleaned) => {
+ syncSeriesAutopilotSchedules(cleaned).catch((err) =>
+ console.error(`❌ Series Autopilot schedule re-sync failed: ${err.message}`));
+});
+
+/**
+ * Boot entry point — registers the configured schedules once at startup.
+ * No-ops cleanly when nothing is configured (no cold LLM calls: registering a
+ * timer fires nothing until its cron elapses, and even then only if enabled +
+ * cos autonomy is on).
+ */
+export async function startSeriesAutopilotScheduler() {
+ return syncSeriesAutopilotSchedules();
+}
+
+/**
+ * Cancel every registered series-autopilot cron (test teardown / shutdown).
+ */
+export function stopSeriesAutopilotScheduler() {
+ for (const seriesId of [...registered]) {
+ cancel(eventId(seriesId));
+ registered.delete(seriesId);
+ }
+ lastSignature = null;
+}
diff --git a/server/services/seriesAutopilotScheduler.test.js b/server/services/seriesAutopilotScheduler.test.js
new file mode 100644
index 0000000000..1796a47785
--- /dev/null
+++ b/server/services/seriesAutopilotScheduler.test.js
@@ -0,0 +1,185 @@
+/**
+ * Tests for seriesAutopilotScheduler (#2174) — the machine-local per-series cron
+ * that fires startSeriesAutopilot unattended. Covers:
+ * - activeSchedules() pure filter (enabled + valid cron + dedup by seriesId)
+ * - registration/cancellation on sync (added, removed, disabled, edited cron)
+ * - the handler re-reads settings, honors the cos-off gate, and forwards only
+ * the pinned run options to startSeriesAutopilot.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./eventScheduler.js', () => ({
+ schedule: vi.fn(),
+ cancel: vi.fn(),
+ // Accept the standard 5-field crons the tests use; reject the sentinel bad one.
+ isValidCron: vi.fn((expr) => typeof expr === 'string' && expr !== 'not a cron' && expr.trim().split(/\s+/).length === 5),
+}));
+
+// settingsEvents only needs `.on` at module load (the re-sync subscription).
+vi.mock('./settings.js', () => ({ getSettings: vi.fn(), settingsEvents: { on: vi.fn() } }));
+vi.mock('./pipeline/series.js', () => ({ getSeries: vi.fn() }));
+vi.mock('./pipeline/seriesAutopilot.js', () => ({ startSeriesAutopilot: vi.fn() }));
+vi.mock('../lib/timezone.js', () => ({ getUserTimezone: vi.fn().mockResolvedValue('America/Los_Angeles') }));
+
+import { schedule, cancel } from './eventScheduler.js';
+import { getSettings } from './settings.js';
+import { getSeries } from './pipeline/series.js';
+import { startSeriesAutopilot } from './pipeline/seriesAutopilot.js';
+import {
+ activeSchedules,
+ syncSeriesAutopilotSchedules,
+ startSeriesAutopilotScheduler,
+ stopSeriesAutopilotScheduler,
+} from './seriesAutopilotScheduler.js';
+
+const withSchedules = (schedules) => ({ seriesAutopilot: { schedules } });
+
+beforeEach(() => {
+ // Clear the module-level registered Set BEFORE clearing mocks, so the teardown
+ // cancel() calls for a prior test's leftover registrations aren't recorded
+ // against this test's cancel mock.
+ stopSeriesAutopilotScheduler();
+ vi.clearAllMocks();
+ getSeries.mockResolvedValue({ id: 's1', name: 'Test Series' });
+ startSeriesAutopilot.mockResolvedValue({ runId: 'r1' });
+});
+
+describe('activeSchedules', () => {
+ it('keeps only enabled entries with a valid cron and a seriesId', () => {
+ const out = activeSchedules(withSchedules([
+ { seriesId: 's1', enabled: true, cron: '0 3 * * *' },
+ { seriesId: 's2', enabled: false, cron: '0 3 * * *' }, // disabled
+ { seriesId: 's3', enabled: true, cron: 'not a cron' }, // bad cron
+ { seriesId: '', enabled: true, cron: '0 3 * * *' }, // no id
+ { enabled: true, cron: '0 3 * * *' }, // no id key
+ ]));
+ expect(out.map((s) => s.seriesId)).toEqual(['s1']);
+ });
+
+ it('deduplicates by seriesId (last-wins)', () => {
+ const out = activeSchedules(withSchedules([
+ { seriesId: 's1', enabled: true, cron: '0 3 * * *' },
+ { seriesId: 's1', enabled: true, cron: '0 9 * * *' },
+ ]));
+ expect(out).toHaveLength(1);
+ expect(out[0].cron).toBe('0 9 * * *');
+ });
+
+ it('returns [] for missing/malformed settings', () => {
+ expect(activeSchedules(undefined)).toEqual([]);
+ expect(activeSchedules({})).toEqual([]);
+ expect(activeSchedules({ seriesAutopilot: { schedules: 'nope' } })).toEqual([]);
+ });
+});
+
+describe('syncSeriesAutopilotSchedules', () => {
+ it('registers a cron per active schedule, honoring per-entry then user timezone', async () => {
+ const count = await syncSeriesAutopilotSchedules(withSchedules([
+ { seriesId: 's1', enabled: true, cron: '0 3 * * *', timezone: 'Europe/Paris' },
+ { seriesId: 's2', enabled: true, cron: '30 2 * * *' },
+ ]));
+ expect(count).toBe(2);
+ expect(schedule).toHaveBeenCalledTimes(2);
+ expect(schedule.mock.calls[0][0]).toMatchObject({
+ id: 'series-autopilot-s1', type: 'cron', cron: '0 3 * * *', timezone: 'Europe/Paris',
+ });
+ // Falls back to the user timezone when the entry has none.
+ expect(schedule.mock.calls[1][0]).toMatchObject({
+ id: 'series-autopilot-s2', timezone: 'America/Los_Angeles',
+ });
+ });
+
+ it('cancels a cron whose schedule was removed or disabled on a later sync', async () => {
+ await syncSeriesAutopilotSchedules(withSchedules([
+ { seriesId: 's1', enabled: true, cron: '0 3 * * *' },
+ { seriesId: 's2', enabled: true, cron: '0 3 * * *' },
+ ]));
+ schedule.mockClear();
+
+ // s2 disabled, s1 kept.
+ await syncSeriesAutopilotSchedules(withSchedules([
+ { seriesId: 's1', enabled: true, cron: '0 3 * * *' },
+ { seriesId: 's2', enabled: false, cron: '0 3 * * *' },
+ ]));
+ expect(cancel).toHaveBeenCalledWith('series-autopilot-s2');
+ expect(cancel).not.toHaveBeenCalledWith('series-autopilot-s1');
+ });
+
+ it('re-reads settings when none passed', async () => {
+ getSettings.mockResolvedValue(withSchedules([{ seriesId: 's1', enabled: true, cron: '0 3 * * *' }]));
+ const count = await syncSeriesAutopilotSchedules();
+ expect(getSettings).toHaveBeenCalled();
+ expect(count).toBe(1);
+ });
+
+ it('short-circuits a re-sync when nothing registration-affecting changed', async () => {
+ const snap = withSchedules([{ seriesId: 's1', enabled: true, cron: '0 3 * * *' }]);
+ await syncSeriesAutopilotSchedules(snap);
+ schedule.mockClear();
+ // Same schedules → no re-registration (an unrelated settings save shouldn't churn crons).
+ await syncSeriesAutopilotSchedules(snap);
+ expect(schedule).not.toHaveBeenCalled();
+ // A changed cron DOES re-register.
+ await syncSeriesAutopilotSchedules(withSchedules([{ seriesId: 's1', enabled: true, cron: '0 9 * * *' }]));
+ expect(schedule).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('scheduled handler', () => {
+ async function registerAndGetHandler(entry) {
+ await syncSeriesAutopilotSchedules(withSchedules([entry]));
+ return schedule.mock.calls.at(-1)[0].handler;
+ }
+
+ it('starts the autopilot, mapping provider/model to the override keys', async () => {
+ const entry = { seriesId: 's1', enabled: true, cron: '0 3 * * *', provider: 'anthropic', model: 'claude-opus-4-8' };
+ const handler = await registerAndGetHandler(entry);
+ getSettings.mockResolvedValue(withSchedules([entry]));
+ await handler();
+ // provider/model are mapped to the pipeline's providerOverride/modelOverride keys.
+ expect(startSeriesAutopilot).toHaveBeenCalledWith('s1', {
+ providerOverride: 'anthropic', modelOverride: 'claude-opus-4-8',
+ });
+ });
+
+ it('skips when the schedule was disabled since registration', async () => {
+ const handler = await registerAndGetHandler({ seriesId: 's1', enabled: true, cron: '0 3 * * *' });
+ getSettings.mockResolvedValue(withSchedules([{ seriesId: 's1', enabled: false, cron: '0 3 * * *' }]));
+ await handler();
+ expect(startSeriesAutopilot).not.toHaveBeenCalled();
+ });
+
+ it('delegates the cos-off gate to startSeriesAutopilot and handles its rejection', async () => {
+ // The scheduler no longer pre-checks the cos domain (it lives in cos state,
+ // not settings) — startSeriesAutopilot owns the gate and returns rejected.
+ const handler = await registerAndGetHandler({ seriesId: 's1', enabled: true, cron: '0 3 * * *' });
+ getSettings.mockResolvedValue(withSchedules([{ seriesId: 's1', enabled: true, cron: '0 3 * * *' }]));
+ startSeriesAutopilot.mockResolvedValue({ rejected: true, mode: 'off' });
+ await expect(handler()).resolves.toBeUndefined();
+ expect(startSeriesAutopilot).toHaveBeenCalledWith('s1', {});
+ });
+
+ it('skips when the series no longer exists', async () => {
+ const handler = await registerAndGetHandler({ seriesId: 's1', enabled: true, cron: '0 3 * * *' });
+ getSettings.mockResolvedValue(withSchedules([{ seriesId: 's1', enabled: true, cron: '0 3 * * *' }]));
+ getSeries.mockResolvedValue(null);
+ await handler();
+ expect(startSeriesAutopilot).not.toHaveBeenCalled();
+ });
+
+ it('never throws even if startSeriesAutopilot rejects (runs outside the request lifecycle)', async () => {
+ const handler = await registerAndGetHandler({ seriesId: 's1', enabled: true, cron: '0 3 * * *' });
+ getSettings.mockResolvedValue(withSchedules([{ seriesId: 's1', enabled: true, cron: '0 3 * * *' }]));
+ startSeriesAutopilot.mockRejectedValue(new Error('boom'));
+ await expect(handler()).resolves.toBeUndefined();
+ });
+});
+
+describe('startSeriesAutopilotScheduler', () => {
+ it('is a thin boot wrapper over the settings-reading sync', async () => {
+ getSettings.mockResolvedValue(withSchedules([{ seriesId: 's1', enabled: true, cron: '0 3 * * *' }]));
+ await startSeriesAutopilotScheduler();
+ expect(schedule).toHaveBeenCalledWith(expect.objectContaining({ id: 'series-autopilot-s1' }));
+ });
+});