Skip to content

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

fix: don't treat unreadable settings.json as disabled at boot (#8428)

[._.]/ Adam Eivyd7a4f19e7cb1
diff --git a/server/services/autoUpdateScheduler.js b/server/services/autoUpdateScheduler.js
index efb03290e0..767ffe75e7 100644
--- a/server/services/autoUpdateScheduler.js
+++ b/server/services/autoUpdateScheduler.js
@@ -35,7 +35,7 @@
*/
import { schedule, cancel } from './eventScheduler.js';
-import { getSettings, settingsEvents } from './settings.js';
+import { getSettings, getSettingsWithStatus, settingsEvents } from './settings.js';
import { getSystemActivity } from './activeProcessing.js';
import { startPortosSelfUpdate } from './portosSelfUpdate.js';
import { runAppUpdate } from './appUpdateRunner.js';
@@ -50,10 +50,18 @@ const EVENT_ID = 'portos-auto-update';
/** How often the scheduler looks for an idle window once it is armed. */
const AUTO_UPDATE_POLL_INTERVAL_MS = 5 * 60 * 1000;
+// How long to wait before retrying a boot-time read that came back corrupt
+// (issue #8428) — mirrors backupScheduler's retry window.
+const CORRUPT_SETTINGS_RETRY_MS = 60_000;
+
// Only confirmed enabled/disabled states are cached; the signature makes an
// unrelated settings save free, exactly as backupScheduler's does.
let registrationSignature = null;
+// Guards against stacking multiple boot-retry timers while settings.json
+// stays unreadable across several syncAutoUpdateSchedule() calls.
+let corruptRetryTimer = null;
+
// The Socket.IO server, captured at boot so the scheduler's run emits the same
// `portos:update:*` / `app:update:*` frames a click would — a user watching the
// Update page sees the automatic run stream like any other.
@@ -343,7 +351,25 @@ async function launchUpdateFor(channel, io) {
* @returns {Promise<boolean>} whether the poll is registered afterwards.
*/
export async function syncAutoUpdateSchedule(settings) {
- const current = settings || await getSettings().catch(() => null);
+ if (!settings) {
+ // No explicit snapshot: boot path (or a corrupt-read retry). Read through
+ // the strict status so an unreadable/malformed settings.json is
+ // distinguishable from "auto-update genuinely off" (issue #8428).
+ // `settings:updated` always hands this a clean parsed snapshot, so the
+ // explicit-argument path below is unaffected.
+ const { corrupt, settings: read } = await getSettingsWithStatus().catch(() => ({ corrupt: true, settings: {} }));
+ if (corrupt) {
+ console.error('❌ Automatic updates: settings unreadable — keeping current registration, will retry on next settings change');
+ const wasEnabled = registrationSignature !== null && JSON.parse(registrationSignature).enabled === true;
+ // Don't cache a signature for a failed read — the next sync
+ // (settings:invalidated, or the boot retry below) must re-evaluate.
+ registrationSignature = null;
+ scheduleCorruptRetry();
+ return wasEnabled;
+ }
+ return syncAutoUpdateSchedule(read);
+ }
+ const current = settings;
const config = resolveAutoUpdateConfig(current?.autoUpdate);
// Only the enabled flag shapes the REGISTRATION; the channel and the interval
// are re-read inside the handler, so changing either takes effect on the next
@@ -373,6 +399,22 @@ export async function syncAutoUpdateSchedule(settings) {
return true;
}
+/**
+ * Arm a single one-shot retry after a corrupt boot/re-sync read (#8428), so a
+ * transient failure self-heals without waiting for a user-driven settings
+ * save. Runs outside the request lifecycle — the process-boundary try/catch
+ * convention applies, not the route error-bubbling one.
+ */
+function scheduleCorruptRetry() {
+ if (corruptRetryTimer) return;
+ corruptRetryTimer = setTimeout(() => {
+ corruptRetryTimer = null;
+ syncAutoUpdateSchedule().catch(err =>
+ console.error(`❌ Automatic updates: corrupt-settings retry failed: ${err.message}`));
+ }, CORRUPT_SETTINGS_RETRY_MS);
+ corruptRetryTimer.unref?.();
+}
+
// Re-sync on every settings save rather than from the settings route — keeps
// the HTTP handler decoupled from the update graph (mirrors backupScheduler).
// The signature guard makes unrelated saves free.
@@ -381,6 +423,14 @@ settingsEvents.on('settings:updated', (cleaned) => {
console.error(`❌ Auto-update schedule re-sync failed: ${err.message}`));
});
+// A corrupt boot read invalidates the settings read cache (settings.js's
+// reloadSettings()); re-sync as soon as a later read clears, without waiting
+// for a settings:updated save (#8428).
+settingsEvents.on('settings:invalidated', () => {
+ syncAutoUpdateSchedule().catch(err =>
+ console.error(`❌ Auto-update schedule invalidation re-sync failed: ${err.message}`));
+});
+
/**
* Boot entry point — captures the Socket.IO server so an automatic run streams
* its progress to whoever is watching, then registers the poll if the feature
@@ -397,4 +447,8 @@ export function __resetAutoUpdateSchedulerForTests() {
lastLoggedSkip = null;
ioRef = null;
failingRuntimeWrites.clear();
+ if (corruptRetryTimer) {
+ clearTimeout(corruptRetryTimer);
+ corruptRetryTimer = null;
+ }
}
diff --git a/server/services/autoUpdateScheduler.test.js b/server/services/autoUpdateScheduler.test.js
index d7326a0a4c..da46cab5b0 100644
--- a/server/services/autoUpdateScheduler.test.js
+++ b/server/services/autoUpdateScheduler.test.js
@@ -1,7 +1,8 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const deps = vi.hoisted(() => ({
settings: vi.fn(),
+ settingsWithStatus: vi.fn(),
processing: vi.fn(),
selfUpdate: vi.fn(),
appUpdate: vi.fn(),
@@ -18,6 +19,7 @@ const deps = vi.hoisted(() => ({
vi.mock('./eventScheduler.js', () => ({ schedule: deps.schedule, cancel: deps.cancel }));
vi.mock('./settings.js', () => ({
getSettings: deps.settings,
+ getSettingsWithStatus: deps.settingsWithStatus,
settingsEvents: { on: vi.fn(), emit: vi.fn() },
}));
vi.mock('./activeProcessing.js', () => ({ getSystemActivity: deps.processing }));
@@ -47,6 +49,9 @@ beforeEach(() => {
Object.values(deps).forEach((mock) => mock.mockReset());
__resetAutoUpdateSchedulerForTests();
deps.settings.mockResolvedValue({ autoUpdate: { enabled: true, channel: 'release', minIntervalHours: 6 } });
+ // getSettingsWithStatus defaults to wrapping getSettings as a clean read
+ // (`corrupt: false`) — corrupt-read tests override it directly.
+ deps.settingsWithStatus.mockImplementation(async () => ({ corrupt: false, settings: await deps.settings() }));
deps.gateState.mockResolvedValue({
runtime: { armedAt: iso(Date.now() - 48 * HOUR), lastRunAt: null, repairQueuedAt: null },
lastUpdateResult: null,
@@ -421,6 +426,56 @@ describe('poll registration', () => {
});
});
+/**
+ * #8428: a boot-time read of settings.json that is unreadable/malformed must
+ * not be treated as "auto-update off". Before this, `getSettings()` collapsed
+ * that failure to `{}`, so `resolveAutoUpdateConfig({})` resolved `disabled`
+ * and the scheduler cached that as a confirmed signature — permanently, since
+ * nothing re-triggers a sync until the next successful settings save.
+ */
+describe('poll registration: corrupt settings read at boot (#8428)', () => {
+ let consoleErrorSpy;
+
+ beforeEach(() => {
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ consoleErrorSpy.mockRestore();
+ });
+
+ it('logs an error and registers nothing on a corrupt boot read, without logging "off"', async () => {
+ deps.settingsWithStatus.mockResolvedValueOnce({ corrupt: true, settings: {} });
+ await expect(syncAutoUpdateSchedule()).resolves.toBe(false);
+
+ expect(deps.schedule).not.toHaveBeenCalled();
+ expect(deps.cancel).not.toHaveBeenCalled();
+ expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining('❌ Automatic updates: settings unreadable'));
+ });
+
+ it('does not cancel an already-registered poll when a later read is corrupt', async () => {
+ await expect(syncAutoUpdateSchedule({ autoUpdate: { enabled: true } })).resolves.toBe(true);
+ expect(deps.schedule).toHaveBeenCalledTimes(1);
+
+ deps.settingsWithStatus.mockResolvedValueOnce({ corrupt: true, settings: {} });
+ await expect(syncAutoUpdateSchedule()).resolves.toBe(true);
+
+ expect(deps.cancel).not.toHaveBeenCalled();
+ expect(deps.schedule).toHaveBeenCalledTimes(1);
+ });
+
+ it('registers once a later clean read succeeds, without a settings:updated save', async () => {
+ deps.settingsWithStatus.mockResolvedValueOnce({ corrupt: true, settings: {} });
+ await expect(syncAutoUpdateSchedule()).resolves.toBe(false);
+ expect(deps.schedule).not.toHaveBeenCalled();
+
+ // Simulate the boot retry / settings:invalidated re-sync firing after a
+ // later clean read — the default mockImplementation resolves cleanly now.
+ await expect(syncAutoUpdateSchedule()).resolves.toBe(true);
+ expect(deps.schedule).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('interval baseline', () => {
it('prefers the most recent of the scheduler run, the manual update, and the arming point', () => {
const now = Date.parse('2026-01-02T00:00:00Z');
diff --git a/server/services/backupScheduler.js b/server/services/backupScheduler.js
index 5fda480738..a9ff2fc725 100644
--- a/server/services/backupScheduler.js
+++ b/server/services/backupScheduler.js
@@ -9,17 +9,27 @@
*/
import { schedule, cancel } from './eventScheduler.js';
-import { getSettings, settingsEvents } from './settings.js';
+import { getSettings, getSettingsWithStatus, settingsEvents } from './settings.js';
import { runBackup } from './backup.js';
import { getUserTimezone } from './userTimezone.js';
import { resolveBackupConfig } from '../lib/backupConfig.js';
const EVENT_ID = 'backup-daily';
+// How long to wait before retrying a boot-time read that came back corrupt
+// (issue #8428) — long enough to skip past a transient EIO/iCloud-dataless
+// blip without spamming retries, short enough that the schedule self-heals
+// well inside a normal session.
+const CORRUPT_SETTINGS_RETRY_MS = 60_000;
+
// Only confirmed disabled or runnable configurations are cached.
// null means stopped or failed, so identical inputs can retry.
let reconciliationState = null;
+// Guards against stacking multiple boot-retry timers while settings.json
+// stays unreadable across several syncBackupSchedule() calls.
+let corruptRetryTimer = null;
+
/**
* The registration-affecting slice of settings: `null` when backup scheduling
* should be inactive (explicitly disabled, or no destination configured).
@@ -39,7 +49,26 @@ function registrationInputs(settings) {
* @returns {Promise<boolean>} whether a cron is registered after the sync
*/
export async function syncBackupSchedule(settings) {
- const current = settings || await getSettings().catch(() => null);
+ if (!settings) {
+ // No explicit snapshot: this is the boot path (or a corrupt-read retry),
+ // so read through the strict status so an unreadable/malformed
+ // settings.json is distinguishable from "backup genuinely disabled"
+ // (issue #8428). `settings:updated` always hands syncBackupSchedule a
+ // clean parsed snapshot, so the explicit-argument path is unaffected.
+ const { corrupt, settings: read } = await getSettingsWithStatus().catch(() => ({ corrupt: true, settings: {} }));
+ if (corrupt) {
+ console.error('❌ Backup scheduler: settings unreadable — keeping current registration, will retry on next settings change');
+ const wasScheduled = reconciliationState?.kind === 'scheduled';
+ // Don't cache a signature/state for a failed read — the next sync
+ // (settings:invalidated, or the boot retry below) must re-evaluate
+ // rather than treating this as a confirmed disabled state.
+ reconciliationState = null;
+ scheduleCorruptRetry();
+ return wasScheduled;
+ }
+ return syncBackupSchedule(read);
+ }
+ const current = settings;
const inputs = registrationInputs(current);
const timezone = await getUserTimezone().catch(() => 'UTC');
@@ -115,6 +144,22 @@ function attemptRegistration(inputs, timezone, signature) {
return { kind: 'scheduled', signature };
}
+/**
+ * Arm a single one-shot retry after a corrupt boot/re-sync read (#8428), so a
+ * transient failure self-heals without waiting for a user-driven settings
+ * save. Runs outside the request lifecycle — the process-boundary try/catch
+ * convention applies, not the route error-bubbling one.
+ */
+function scheduleCorruptRetry() {
+ if (corruptRetryTimer) return;
+ corruptRetryTimer = setTimeout(() => {
+ corruptRetryTimer = null;
+ syncBackupSchedule().catch(err =>
+ console.error(`❌ Backup scheduler: corrupt-settings retry failed: ${err.message}`));
+ }, CORRUPT_SETTINGS_RETRY_MS);
+ corruptRetryTimer.unref?.();
+}
+
// Re-sync on every settings save rather than from the settings route — keeps
// the HTTP handler decoupled from the backup graph (mirrors
// seriesAutopilotScheduler.js). The signature guard makes unrelated saves free.
@@ -123,6 +168,14 @@ settingsEvents.on('settings:updated', (cleaned) => {
console.error(`❌ Backup schedule re-sync failed: ${err.message}`));
});
+// A corrupt boot read invalidates the settings read cache (settings.js's
+// reloadSettings()); re-sync as soon as a later read clears, without waiting
+// for a settings:updated save (#8428).
+settingsEvents.on('settings:invalidated', () => {
+ syncBackupSchedule().catch(err =>
+ console.error(`❌ Backup schedule invalidation re-sync failed: ${err.message}`));
+});
+
/**
* Boot entry point — registers the cron once at startup if backup is
* configured. Later enable/disable/cron edits are picked up by the
@@ -138,5 +191,9 @@ export async function startBackupScheduler() {
export function stopBackupScheduler() {
cancel(EVENT_ID);
reconciliationState = null;
+ if (corruptRetryTimer) {
+ clearTimeout(corruptRetryTimer);
+ corruptRetryTimer = null;
+ }
console.log('💾 Backup scheduler: stopped');
}
diff --git a/server/services/backupScheduler.test.js b/server/services/backupScheduler.test.js
index 1eda922bee..31fb979649 100644
--- a/server/services/backupScheduler.test.js
+++ b/server/services/backupScheduler.test.js
@@ -11,7 +11,7 @@
* destPath after boot must register the cron without a restart.
*/
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
vi.mock('./eventScheduler.js', () => ({
// The real schedule() returns the registered event; the scheduler treats a
@@ -34,10 +34,15 @@ const { settingsEvents } = vi.hoisted(() => {
}
};
});
-vi.mock('./settings.js', () => ({
- getSettings: vi.fn(),
- settingsEvents
-}));
+vi.mock('./settings.js', () => {
+ // getSettingsWithStatus defaults to wrapping getSettings as a clean read
+ // (`corrupt: false`), matching production for every test that only sets up
+ // `getSettings.mockResolvedValue(...)`. Corrupt-read tests override
+ // getSettingsWithStatus directly.
+ const getSettings = vi.fn();
+ const getSettingsWithStatus = vi.fn(async () => ({ corrupt: false, settings: await getSettings() }));
+ return { getSettings, getSettingsWithStatus, settingsEvents };
+});
vi.mock('./backup.js', () => ({
runBackup: vi.fn().mockResolvedValue({ success: true })
@@ -48,7 +53,7 @@ vi.mock('./userTimezone.js', () => ({
}));
import { schedule, cancel } from './eventScheduler.js';
-import { getSettings } from './settings.js';
+import { getSettings, getSettingsWithStatus } from './settings.js';
import { runBackup } from './backup.js';
import { startBackupScheduler, stopBackupScheduler, syncBackupSchedule } from './backupScheduler.js';
@@ -328,3 +333,58 @@ describe('confirmed backup schedule lifecycle', () => {
expect(schedule).toHaveBeenCalledTimes(3);
});
});
+
+/**
+ * #8428: a boot-time read of settings.json that is unreadable/malformed must
+ * not be treated as "backup disabled". Before this, `getSettings()` collapsed
+ * that failure to `{}`, so `registrationInputs({})` was `null` and the
+ * scheduler cached a confirmed `disabled` state — permanently, since nothing
+ * re-triggers a sync until the next successful settings save.
+ */
+describe('corrupt settings read at boot (#8428)', () => {
+ let consoleErrorSpy;
+
+ beforeEach(() => {
+ stopBackupScheduler();
+ vi.clearAllMocks();
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ consoleErrorSpy.mockRestore();
+ });
+
+ it('logs an error and registers nothing new on a corrupt boot read, without logging "disabled"', async () => {
+ getSettingsWithStatus.mockResolvedValueOnce({ corrupt: true, settings: {} });
+ await startBackupScheduler();
+
+ expect(schedule).not.toHaveBeenCalled();
+ expect(cancel).not.toHaveBeenCalled();
+ expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining('❌ Backup scheduler: settings unreadable'));
+ });
+
+ it('does not cancel an already-registered cron when a later read is corrupt', async () => {
+ getSettings.mockResolvedValue({ backup: { enabled: true, destPath: '/dest' } });
+ await startBackupScheduler();
+ expect(schedule).toHaveBeenCalledTimes(1);
+
+ getSettingsWithStatus.mockResolvedValueOnce({ corrupt: true, settings: {} });
+ expect(await syncBackupSchedule()).toBe(true);
+
+ expect(cancel).not.toHaveBeenCalled();
+ expect(schedule).toHaveBeenCalledTimes(1);
+ });
+
+ it('registers once a later clean read succeeds, via settings:invalidated rather than a save', async () => {
+ getSettingsWithStatus.mockResolvedValueOnce({ corrupt: true, settings: {} });
+ await startBackupScheduler();
+ expect(schedule).not.toHaveBeenCalled();
+
+ getSettings.mockResolvedValue({ backup: { enabled: true, destPath: '/dest', cronExpression: '0 3 * * *' } });
+ settingsEvents.emit('settings:invalidated');
+ await new Promise(resolve => setImmediate(resolve));
+
+ expect(schedule).toHaveBeenCalledTimes(1);
+ expect(schedule.mock.calls[0][0]).toMatchObject({ cron: '0 3 * * *' });
+ });
+});
diff --git a/server/services/seriesAutopilotScheduler.js b/server/services/seriesAutopilotScheduler.js
index ee591ea245..3416c8d0fc 100644
--- a/server/services/seriesAutopilotScheduler.js
+++ b/server/services/seriesAutopilotScheduler.js
@@ -26,7 +26,7 @@
*/
import { schedule, cancel, isValidCron } from './eventScheduler.js';
-import { getSettings, settingsEvents } from './settings.js';
+import { getSettings, getSettingsWithStatus, settingsEvents } from './settings.js';
import { getSeries } from './pipeline/series.js';
import { startSeriesAutopilot } from './pipeline/seriesAutopilot.js';
import { getUserTimezone } from './userTimezone.js';
@@ -34,6 +34,10 @@ import { getUserTimezone } from './userTimezone.js';
// eventScheduler id namespace for a per-series cron. One event per seriesId.
const eventId = (seriesId) => `series-autopilot-${seriesId}`;
+// How long to wait before retrying a boot-time read that came back corrupt
+// (issue #8428) — mirrors backupScheduler's retry window.
+const CORRUPT_SETTINGS_RETRY_MS = 60_000;
+
// 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();
@@ -45,6 +49,10 @@ const registered = new Set();
// deliberately: they don't affect registration (the handler re-reads them per run).
let lastSignature = null;
+// Guards against stacking multiple boot-retry timers while settings.json
+// stays unreadable across several syncSeriesAutopilotSchedules() calls.
+let corruptRetryTimer = null;
+
/**
* Pure extractor: the enabled, cron-valid schedules from a settings snapshot.
* A schedule needs `enabled === true`, a non-empty `seriesId`, and a cron
@@ -165,7 +173,24 @@ function signatureOf(active, fallbackTz) {
* @param {object} [settings] - a settings snapshot; re-read when omitted
*/
export async function syncSeriesAutopilotSchedules(settings) {
- const current = settings || await getSettings().catch(() => null);
+ if (!settings) {
+ // No explicit snapshot: boot path (or a corrupt-read retry). Read through
+ // the strict status so an unreadable/malformed settings.json is
+ // distinguishable from "no schedules configured" (issue #8428).
+ // `settings:updated` always hands this a clean parsed snapshot, so the
+ // explicit-argument path below is unaffected.
+ const { corrupt, settings: read } = await getSettingsWithStatus().catch(() => ({ corrupt: true, settings: {} }));
+ if (corrupt) {
+ console.error('❌ Series Autopilot scheduler: settings unreadable — keeping current registration, will retry on next settings change');
+ // Don't cache a signature for a failed read — the next sync
+ // (settings:invalidated, or the boot retry below) must re-evaluate.
+ lastSignature = null;
+ scheduleCorruptRetry();
+ return registered.size;
+ }
+ return syncSeriesAutopilotSchedules(read);
+ }
+ const current = settings;
const active = activeSchedules(current);
const timezone = await getUserTimezone().catch(() => 'UTC');
@@ -198,6 +223,30 @@ settingsEvents.on('settings:updated', (cleaned) => {
console.error(`❌ Series Autopilot schedule re-sync failed: ${err.message}`));
});
+/**
+ * Arm a single one-shot retry after a corrupt boot/re-sync read (#8428), so a
+ * transient failure self-heals without waiting for a user-driven settings
+ * save. Runs outside the request lifecycle — the process-boundary try/catch
+ * convention applies, not the route error-bubbling one.
+ */
+function scheduleCorruptRetry() {
+ if (corruptRetryTimer) return;
+ corruptRetryTimer = setTimeout(() => {
+ corruptRetryTimer = null;
+ syncSeriesAutopilotSchedules().catch((err) =>
+ console.error(`❌ Series Autopilot scheduler: corrupt-settings retry failed: ${err.message}`));
+ }, CORRUPT_SETTINGS_RETRY_MS);
+ corruptRetryTimer.unref?.();
+}
+
+// A corrupt boot read invalidates the settings read cache (settings.js's
+// reloadSettings()); re-sync as soon as a later read clears, without waiting
+// for a settings:updated save (#8428).
+settingsEvents.on('settings:invalidated', () => {
+ syncSeriesAutopilotSchedules().catch((err) =>
+ console.error(`❌ Series Autopilot schedule invalidation 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
@@ -217,4 +266,8 @@ export function stopSeriesAutopilotScheduler() {
registered.delete(seriesId);
}
lastSignature = null;
+ if (corruptRetryTimer) {
+ clearTimeout(corruptRetryTimer);
+ corruptRetryTimer = null;
+ }
}
diff --git a/server/services/seriesAutopilotScheduler.test.js b/server/services/seriesAutopilotScheduler.test.js
index b8934b1463..0c879e3340 100644
--- a/server/services/seriesAutopilotScheduler.test.js
+++ b/server/services/seriesAutopilotScheduler.test.js
@@ -7,7 +7,7 @@
* the pinned run options to startSeriesAutopilot.
*/
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
vi.mock('./eventScheduler.js', () => ({
schedule: vi.fn(),
@@ -17,7 +17,15 @@ vi.mock('./eventScheduler.js', () => ({
}));
// settingsEvents only needs `.on` at module load (the re-sync subscription).
-vi.mock('./settings.js', () => ({ getSettings: vi.fn(), settingsEvents: { on: vi.fn() } }));
+vi.mock('./settings.js', () => {
+ // getSettingsWithStatus defaults to wrapping getSettings as a clean read
+ // (`corrupt: false`), matching production for every test that only sets up
+ // `getSettings.mockResolvedValue(...)`. Corrupt-read tests override
+ // getSettingsWithStatus directly.
+ const getSettings = vi.fn();
+ const getSettingsWithStatus = vi.fn(async () => ({ corrupt: false, settings: await getSettings() }));
+ return { getSettings, getSettingsWithStatus, settingsEvents: { on: vi.fn() } };
+});
vi.mock('./pipeline/series.js', () => ({ getSeries: vi.fn() }));
vi.mock('./pipeline/seriesAutopilot.js', () => ({ startSeriesAutopilot: vi.fn() }));
vi.mock('./userTimezone.js', () => ({
@@ -25,7 +33,7 @@ vi.mock('./userTimezone.js', () => ({
}));
import { schedule, cancel } from './eventScheduler.js';
-import { getSettings } from './settings.js';
+import { getSettings, getSettingsWithStatus } from './settings.js';
import { getSeries } from './pipeline/series.js';
import { startSeriesAutopilot } from './pipeline/seriesAutopilot.js';
import {
@@ -213,3 +221,58 @@ describe('startSeriesAutopilotScheduler', () => {
expect(schedule).toHaveBeenCalledWith(expect.objectContaining({ id: 'series-autopilot-s1' }));
});
});
+
+/**
+ * #8428: a boot-time read of settings.json that is unreadable/malformed must
+ * not be treated as "no schedules configured". Before this, `getSettings()`
+ * collapsed that failure to `{}`, so `activeSchedules({})` was `[]` and the
+ * scheduler cached that as a confirmed signature — permanently, since nothing
+ * re-triggers a sync until the next successful settings save.
+ */
+describe('corrupt settings read at boot (#8428)', () => {
+ let consoleErrorSpy;
+
+ beforeEach(() => {
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ consoleErrorSpy.mockRestore();
+ });
+
+ it('logs an error and registers nothing on a corrupt boot read, without logging "0 schedule(s)"', async () => {
+ getSettingsWithStatus.mockResolvedValueOnce({ corrupt: true, settings: {} });
+ const count = await startSeriesAutopilotScheduler();
+
+ expect(count).toBe(0);
+ expect(schedule).not.toHaveBeenCalled();
+ expect(cancel).not.toHaveBeenCalled();
+ expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining('❌ Series Autopilot scheduler: settings unreadable'));
+ });
+
+ it('does not cancel an already-registered series cron when a later read is corrupt', async () => {
+ getSettings.mockResolvedValue(withSchedules([{ seriesId: 's1', enabled: true, cron: '0 3 * * *' }]));
+ await startSeriesAutopilotScheduler();
+ expect(schedule).toHaveBeenCalledTimes(1);
+
+ getSettingsWithStatus.mockResolvedValueOnce({ corrupt: true, settings: {} });
+ await syncSeriesAutopilotSchedules();
+
+ expect(cancel).not.toHaveBeenCalled();
+ expect(schedule).toHaveBeenCalledTimes(1);
+ });
+
+ it('registers once a later clean read succeeds, without a settings:updated save', async () => {
+ getSettingsWithStatus.mockResolvedValueOnce({ corrupt: true, settings: {} });
+ await startSeriesAutopilotScheduler();
+ expect(schedule).not.toHaveBeenCalled();
+
+ getSettings.mockResolvedValue(withSchedules([{ seriesId: 's1', enabled: true, cron: '0 3 * * *' }]));
+ // Simulate the boot retry / settings:invalidated re-sync firing after a
+ // later clean read — the default mockImplementation resolves cleanly now.
+ const count = await syncSeriesAutopilotSchedules();
+
+ expect(count).toBe(1);
+ expect(schedule).toHaveBeenCalledTimes(1);
+ });
+});