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

222 KB
Raw Blame
vi.mock('../lib/retirementCheckoutObservation.js', () => ({ isCurrentRetirementCheckout: vi.fn(async () => false) }));
import { isCurrentRetirementCheckout } from '../lib/retirementCheckoutObservation.js';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'

vi.mock('./cosEvents.js', () => ({
  cosEvents: { emit: vi.fn() },
  emitLog: vi.fn()
}))

// fileUtils mock: include every named export consumed by ./cosState.js too,
// so vi.importActual('./cosState.js') below resolves cleanly.
vi.mock('../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
  ensureDir: vi.fn().mockResolvedValue(),
  ensureDirs: vi.fn().mockResolvedValue(),
  readJSONFile: vi.fn(),
  safeJSONParse: (content, fallback) => { try { return JSON.parse(content); } catch { return fallback; } },
  // atomicWrite replaced the raw writeFile(JSON.stringify) schedule-save site (#1837);
  // route it through the mocked fs/promises.writeFile so the tests that read
  // writeFile.mock.calls.at(-1)[1] still observe the persisted schedule JSON.
  atomicWrite: vi.fn(async (filePath, data) => {
    const payload = (typeof data === 'string' || Buffer.isBuffer(data)) ? data : JSON.stringify(data, null, 2);
    const { writeFile } = await import('fs/promises');
    return writeFile(filePath, payload);
  }),
  PATHS: { cos: '/mock/data/cos', root: '/mock', reports: '/mock/reports', scripts: '/mock/scripts' },
  HOUR: 60 * 60 * 1000,
  DAY: 24 * 60 * 60 * 1000,
  safeDate: (d) => d ? new Date(d).getTime() : 0
}))

// slashdoLoader mock: taskPromptService.js reads the bundled command body
// through loadSlashdoFile — stub it the same way the prior fileUtils mock did,
// now that the slashdo loaders live in their own module (#3110's home moved).
// Operator-action ledger (#5594). Stubbed so the origin gate in
// triggerOnDemandTask can be asserted directly (recorded vs not recorded)
// without this suite's minimal fileUtils stub having to grow a data root.
vi.mock('./userActions.js', () => ({ recordUserAction: vi.fn() }));

vi.mock('../lib/slashdoLoader.js', () => ({
  loadSlashdoFile: vi.fn().mockResolvedValue(''),
}))

vi.mock('fs/promises', () => ({
  writeFile: vi.fn().mockResolvedValue(),
  readFile: vi.fn().mockRejectedValue(new Error('readFile not mocked')),
  readdir: vi.fn().mockResolvedValue([]),
  rm: vi.fn().mockResolvedValue()
}))

vi.mock('fs', () => ({
  existsSync: vi.fn(() => true)
}))

vi.mock('./taskLearning.js', () => ({
  getAdaptiveCooldownMultiplier: vi.fn().mockResolvedValue({
    multiplier: 1.0,
    reason: 'insufficient-data',
    skip: false,
    successRate: null,
    completed: 0
  })
}))

vi.mock('./apps.js', () => ({
  isTaskTypeEnabledForApp: vi.fn().mockResolvedValue(true),
  getAppTaskTypeInterval: vi.fn().mockResolvedValue(null),
  getAppTaskTypeIntervalMs: vi.fn().mockResolvedValue(null),
  getActiveApps: vi.fn().mockResolvedValue([]),
  getAppById: vi.fn().mockResolvedValue(null),
  getAppTaskTypeOverrides: vi.fn().mockResolvedValue({}),
  clearAllPrWatcherState: vi.fn().mockResolvedValue({ changed: false }),
  clearAllIssueWatcherState: vi.fn().mockResolvedValue({ changed: false })
}))

vi.mock('./taskInputGate.js', () => ({ inputsUnchangedSince: vi.fn().mockResolvedValue(false), readHead: vi.fn() }))

vi.mock('./branchReconcileInventoryPrune.js', async importOriginal => ({ ...await importOriginal(), findGoneInventoryRows: vi.fn().mockResolvedValue([]) }))

vi.mock('./instanceFeatures.js', () => ({
  isInstanceFeatureEnabled: vi.fn().mockResolvedValue(true),
}))

vi.mock('../lib/portosUrls.js', () => ({
  PORTOS_UI_URL: 'http://localhost:5554',
  PORTOS_API_URL: 'http://localhost:5555'
}))

vi.mock('../lib/timezone.js', () => ({
  getLocalParts: vi.fn(() => ({ dayOfWeek: 3 })),
}))
vi.mock('./userTimezone.js', () => ({
  getUserTimezone: vi.fn().mockResolvedValue('America/Los_Angeles'),
}))

vi.mock('./eventScheduler.js', () => ({
  parseCronToNextRun: vi.fn()
}))

// Failure-park auto-notification (#2616): recordTaskTypeFailure lazy-imports
// notifications.js and fires an AGENT_WARNING when a type auto-parks. Mock it so
// the ledger tests can assert the notification without touching the real store.
vi.mock('./notifications.js', () => ({
  addNotification: vi.fn().mockResolvedValue({}),
  exists: vi.fn().mockResolvedValue(false),
  removeByMetadata: vi.fn().mockResolvedValue({ success: true, removedIds: [] }),
  NOTIFICATION_TYPES: { AGENT_WARNING: 'agent_warning' },
  PRIORITY_LEVELS: { HIGH: 'high' }
}))

// Use the real isImprovementEnabled implementation; only stub loadState.
// Mocking the helper would let regressions in production logic slip through.
vi.mock('./cosState.js', async () => {
  const actual = await vi.importActual('./cosState.js')
  return {
    ...actual,
    loadState: vi.fn().mockResolvedValue({ config: { improvementEnabled: true } })
  }
})

import {
  INTERVAL_TYPES,
  INSTALL_WIDE_TASK_TYPES,
  SELF_IMPROVEMENT_TASK_TYPES,
  loadSchedule,
  getTaskInterval,
  updateTaskInterval,
  recordExecution,
  recordRecommendedAudits,
  getExecutionHistory,
  shouldRunTask,
  shouldContinuePerpetualDrain,
  getDueTasks,
  getNextTaskType,
  getUpcomingTasks,
  addTemplateTask,
  getTemplateTasks,
  deleteTemplateTask,
  resetExecutionHistory,
  triggerOnDemandTask,
  getOnDemandRequests,
  clearOnDemandRequest,
  getScheduleStatus,
  computePerpetualRecheckAt,
  parkPerpetual,
  resetPerpetualForManualRun,
  getPerpetualParkInfo,
  recordPerpetualStall,
  isPerpetualParkActive,
  getPerpetualDrainState,
  recordPerpetualDispatch,
  recordBranchReconcileOutcome,
  recordLegacyRetirementResolutions,
  getBranchReconcileOutcome,
  recordInitializedRetirementRecovery,
  recordHeldCheckoutRetirement,
  recordWorkspaceCheckoutRetirement,
  applyOnDemandRunResets,
  queuePerpetualRefill,
  isRefillRequest,
  ON_DEMAND_ORIGINS,
  recordTaskTypeFailure,
  recordTaskTypeSuccess,
  clearTaskTypeFailurePark,
  computeFailureBackoffMs,
  FAILURE_BACKOFF_BASE_MS,
  FAILURE_BACKOFF_CAP_MS,
  FAILURE_PARK_THRESHOLD,
  PROMPT_VERSIONS,
  DEFAULT_TASK_INTERVALS,
  MANAGED_APP_TARGET_TASK_TYPES,
  MANAGED_AGENT_OPTIONS,
  stripManagedAgentOptionsFromOverride,
  TASK_TYPE_DESCRIPTIONS,
  TASK_TYPE_INVOCATION,
  TASK_TYPE_PROMPT_INFO,
  getTaskTypeInvocation,
  requiresManagedAppTarget,
  requiresInstallWideTarget,
  getTaskTypePromptInfo,
  PROGRAMMATIC_SCHEDULED_TASK_TYPES,
  REFERENCE_WATCH_AUDITED_VERSION,
  boundParkedUntil
} from './taskSchedule.js'
import { cosEvents, emitLog } from './cosEvents.js'
import { recordUserAction } from './userActions.js'

// Prompt getters moved to taskPromptService.js (issue #744 split, #1083 cycle
// break). taskSchedule.js re-exports the version constants but not the getters.
import {
  getDefaultPrompt,
  getTaskPrompt
} from './taskPromptService.js'

import { DEFAULT_TASK_PROMPTS } from './taskPromptDefaults.js'
import { RETIRED_CONSOLE_ERRORS_PROMPT } from './taskPromptDefaults/retiredPromptFixtures.js'

// The source of truth for "this type's deliverable is a side effect, not a commit"
// — the posture guard below iterates it so the two can't drift apart.
import { NON_COMMITTING_COORDINATOR_TASK_TYPES } from './taskTypeHooks.js'
import { enforceManagedAgentOptions } from './taskScheduleRegistry.js'
import { modeContractFor, auditDoWorkRequiresWorktree, AUDIT_TASK_TYPES, isAuditTaskType } from '../lib/auditCatalog.js'
import { NO_CHANGE_SCHEDULED_TYPES } from '../lib/noChangeCompletion.js'

import { loadState } from './cosState.js'

import { readJSONFile } from '../lib/fileUtils.js'
import { writeFile } from 'fs/promises'
import { isTaskTypeEnabledForApp, getAppById, getAppTaskTypeInterval, getAppTaskTypeOverrides, getActiveApps, clearAllPrWatcherState, clearAllIssueWatcherState } from './apps.js'
import { findGoneInventoryRows } from './branchReconcileInventoryPrune.js'
import { getLocalParts } from '../lib/timezone.js'
import { getAdaptiveCooldownMultiplier } from './taskLearning.js'
import { parseCronToNextRun } from './eventScheduler.js'
import { addNotification, exists as notificationExists, removeByMetadata } from './notifications.js'
import { isInstanceFeatureEnabled } from './instanceFeatures.js'
import { inputsUnchangedSince } from './taskInputGate.js'

const mockSchedule = ({ tasks = {}, executions = {}, templates = [], onDemandRequests = [] } = {}) => {
  readJSONFile.mockResolvedValue({ version: 2, tasks, executions, templates, onDemandRequests })
}

// loadSchedule merges DEFAULT_TASK_INTERVALS over whatever a fixture supplies,
// and the shipped reconcile drains are enabled + perpetual — so they are due on
// every tick. A case asserting on "which tasks are due" has to pause them
// explicitly or its expectation reads them as noise.
const PAUSED_SHIPPED_DRAINS = {
  'branch-reconcile': { enabled: false },
  'issue-reconcile': { enabled: false },
}

// The cron parser is mocked module-wide, so a case that wants a cron task
// simply due (or simply on cooldown) states it here rather than hand-picking
// wall-clock instants: a slot in the current minute, or one still ahead.
const cronDueNow = () => {
  parseCronToNextRun.mockReturnValue(new Date(Math.floor(Date.now() / 60_000) * 60_000))
}
const cronNotDueYet = () => {
  parseCronToNextRun.mockReturnValue(new Date(Date.now() + 60 * 60 * 1000))
}

// Resolve "the most recent 9 AM in the past, local time." Bare
// `setHours(9, 0, 0, 0)` flakes in CI when the runner's wall-clock is
// before 9 AM local (UTC CI fires at ~04:00 UTC daily) — today's 9 AM
// would be in the future. Subtract a day when needed.
const recentNineAm = () => {
  const d = new Date()
  d.setHours(9, 0, 0, 0)
  if (d.getTime() > Date.now()) d.setDate(d.getDate() - 1)
  return d
}

describe('taskSchedule', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    isInstanceFeatureEnabled.mockResolvedValue(true)
    // Default: no saved schedule → use defaults
    readJSONFile.mockResolvedValue(null)
    writeFile.mockResolvedValue(undefined)
  })

  // Cases that freeze the clock restore it here, so a failed assertion inside a
  // faked-timer block can't leak fake time into every case that follows.
  afterEach(() => {
    vi.useRealTimers()
  })

  describe('INTERVAL_TYPES', () => {
    it('is exactly the two cadence variants — perpetual is a flag, not a type', () => {
      expect(INTERVAL_TYPES).toEqual({ ON_DEMAND: 'on-demand', CRON: 'cron' })
    })
  })

  describe('SELF_IMPROVEMENT_TASK_TYPES', () => {
    it('should be an array of strings', () => {
      expect(Array.isArray(SELF_IMPROVEMENT_TASK_TYPES)).toBe(true)
      expect(SELF_IMPROVEMENT_TASK_TYPES.length).toBeGreaterThan(0)
      for (const t of SELF_IMPROVEMENT_TASK_TYPES) {
        expect(typeof t).toBe('string')
      }
    })

    it('should include core task types', () => {
      expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('security')
      expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('code-quality')
      expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('test-coverage')
      expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('performance')
      expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('dependency-updates')
      expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('do-replan')
    })
  })

  describe('feature-gated shipped tasks', () => {
    it('associates both shipped JIRA tasks with the JIRA instance feature', () => {
      expect(DEFAULT_TASK_INTERVALS['jira-sprint-manager'].feature).toBe('jira')
      expect(DEFAULT_TASK_INTERVALS['jira-status-report'].feature).toBe('jira')
    })

    it('keeps the shipped feature association authoritative over persisted state', async () => {
      mockSchedule({ tasks: {
        'jira-sprint-manager': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, feature: 'post' },
        security: { type: INTERVAL_TYPES.WEEKLY, enabled: true, feature: 'jira' },
      } })

      const schedule = await loadSchedule()

      expect(schedule.tasks['jira-sprint-manager'].feature).toBe('jira')
      expect(schedule.tasks.security).not.toHaveProperty('feature')
    })
  })

  describe('INSTALL_WIDE_TASK_TYPES', () => {
    it('names only task types that really sweep the whole install', () => {
      // repo-sync sweeps every managed checkout; user-action-review reads the
      // install-wide operator-action ledger; error-log-triage reads PortOS's own
      // PM2 logs — none is a per-app run.
      expect([...INSTALL_WIDE_TASK_TYPES]).toEqual(['repo-sync', 'user-action-review', 'model-comparison-refresh', 'error-log-triage'])
    })

    it('every install-wide type is a registered task type', () => {
      for (const t of INSTALL_WIDE_TASK_TYPES) {
        expect(SELF_IMPROVEMENT_TASK_TYPES).toContain(t)
      }
    })
  })

  describe('managed-app target task types', () => {
    it('keeps app-required scope explicit and separate from install-wide scope', () => {
      expect([...MANAGED_APP_TARGET_TASK_TYPES]).toEqual(['private-security-assessment', 'pr-reviewer', 'issue-watcher', 'pr-watcher', 'issue-reconcile', 'branch-reconcile'])
      expect(requiresManagedAppTarget('pr-reviewer')).toBe(true)
      expect(requiresManagedAppTarget('security')).toBe(false)
      expect(requiresManagedAppTarget('repo-sync')).toBe(false)
    })

    it('only names registered task types', () => {
      for (const taskType of MANAGED_APP_TARGET_TASK_TYPES) {
        expect(SELF_IMPROVEMENT_TASK_TYPES).toContain(taskType)
      }
    })
  })

  describe('TASK_TYPE_DESCRIPTIONS', () => {
    // Guards against the "orphaned task" bug: a task type with no description
    // entry falls back to a dasherized label ("claim work") in the schedule UI,
    // which reads as a legacy leftover. Every scheduled task type must carry an
    // explicit, human-readable blurb.
    it('has an explicit description for every SELF_IMPROVEMENT_TASK_TYPES entry', () => {
      const missing = SELF_IMPROVEMENT_TASK_TYPES.filter(
        (t) => !Object.prototype.hasOwnProperty.call(TASK_TYPE_DESCRIPTIONS, t)
      )
      expect(missing).toEqual([])
    })

    it('has no description keys that are not real task types', () => {
      const orphaned = Object.keys(TASK_TYPE_DESCRIPTIONS).filter(
        (t) => !SELF_IMPROVEMENT_TASK_TYPES.includes(t)
      )
      expect(orphaned).toEqual([])
    })

    it('every description is a non-empty string', () => {
      for (const [taskType, desc] of Object.entries(TASK_TYPE_DESCRIPTIONS)) {
        expect(typeof desc, taskType).toBe('string')
        expect(desc.trim().length, taskType).toBeGreaterThan(0)
      }
    })
  })

  describe('user-action-review (operator-ledger automation proposals)', () => {
    it('is registered install-wide with an on-demand + enabled default and a v2 prompt', () => {
      expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('user-action-review');
      expect(INSTALL_WIDE_TASK_TYPES.has('user-action-review')).toBe(true);
      expect(TASK_TYPE_DESCRIPTIONS['user-action-review']).toContain('propose automations');
      expect(DEFAULT_TASK_INTERVALS['user-action-review']).toMatchObject({ type: INTERVAL_TYPES.ON_DEMAND, enabled: true });
      expect(PROMPT_VERSIONS['user-action-review']).toBe(3);
      expect(DEFAULT_TASK_PROMPTS['user-action-review']).toContain('{userActionDelivery}');
      expect(DEFAULT_TASK_PROMPTS['user-action-review']).toContain('{userActionDetectors}');
      // The prompt proposes; it must never instruct the agent to enact.
      expect(DEFAULT_TASK_PROMPTS['user-action-review']).toContain('NEVER change settings');
    });

    it('defaults to file-issues with the no-code posture', () => {
      expect(DEFAULT_TASK_INTERVALS['user-action-review'].taskMetadata).toMatchObject({
        fileIssues: true, useWorktree: false, openPR: false
      });
    });

    it('surfaces the fileIssues toggle on schedule status without joining the audit catalog', async () => {
      mockSchedule({ tasks: {}, executions: {} });
      const status = await getScheduleStatus();
      expect(status.tasks['user-action-review']).toMatchObject({
        installWide: true, fileIssuesCapable: true, defaultFileIssues: true
      });
    });
  });

  describe('programmatic scheduled handlers (universe bible)', () => {
    it('ships both as enabled ON_DEMAND tasks with no interval and no cron', () => {
      for (const taskType of PROGRAMMATIC_SCHEDULED_TASK_TYPES) {
        expect(SELF_IMPROVEMENT_TASK_TYPES, taskType).toContain(taskType);
        expect(TASK_TYPE_DESCRIPTIONS[taskType], taskType).toBeTruthy();
        const shipped = DEFAULT_TASK_INTERVALS[taskType];
        expect(shipped, taskType).toMatchObject({ type: INTERVAL_TYPES.ON_DEMAND, enabled: true });
        // No cadence of any kind: a clock-due default would spend the user's
        // provider quota on a fresh install before they ever asked for it.
        expect(shipped, taskType).not.toHaveProperty('intervalMs');
        expect(shipped, taskType).not.toHaveProperty('cronExpression');
        expect(shipped, taskType).not.toHaveProperty('recheckCron');
        expect(shipped.perpetual, taskType).toBeUndefined();
      }
    });

    it('never becomes due on the clock, however much time has passed', async () => {
      // The acceptance guarantee for #6376: enabled + runnable from Run Now, yet
      // never picked up by the scheduler. `cronDueNow` puts the clock where a
      // cron task WOULD fire, so a passing assertion here is about the cadence,
      // not about the time of day.
      cronDueNow();
      mockSchedule({
        tasks: {
          ...PAUSED_SHIPPED_DRAINS,
          ...Object.fromEntries(PROGRAMMATIC_SCHEDULED_TASK_TYPES.map((t) => [t, { type: 'on-demand', enabled: true }])),
        },
        executions: Object.fromEntries(PROGRAMMATIC_SCHEDULED_TASK_TYPES.map((t) => [
          `task:${t}`, { lastRun: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000).toISOString(), count: 1 }
        ])),
      });

      for (const taskType of PROGRAMMATIC_SCHEDULED_TASK_TYPES) {
        expect(await shouldRunTask(taskType), taskType).toMatchObject({ shouldRun: false, reason: 'on-demand-only' });
      }
      const due = await getDueTasks();
      expect(due.map((t) => t.taskType)).not.toEqual(expect.arrayContaining([...PROGRAMMATIC_SCHEDULED_TASK_TYPES]));
    });

    it('refuses a managed-app target — a universe is not a repo', async () => {
      for (const taskType of PROGRAMMATIC_SCHEDULED_TASK_TYPES) {
        expect(requiresInstallWideTarget(taskType), taskType).toBe(true);
        expect(await shouldRunTask(taskType, 'app-1'), taskType)
          .toMatchObject({ shouldRun: false, reason: 'requires-install-wide-target' });
      }
      // The gate is per type, not "everything install-wide" — repo-sync's
      // whole point is that it CAN be pointed at one app.
      expect(requiresInstallWideTarget('repo-sync')).toBe(false);
    });

    it('has no prompt template and is surfaced as programmatic, not runtime-generated', () => {
      for (const taskType of PROGRAMMATIC_SCHEDULED_TASK_TYPES) {
        // PortOS performs the work itself: there is no prompt for a hook to
        // render, so the prompt-version machinery must find nothing to migrate.
        expect(DEFAULT_TASK_PROMPTS[taskType], taskType).toBeUndefined();
        expect(getTaskTypePromptInfo(taskType).mode, taskType).toBe('programmatic');
      }
    });
  });

  describe('layered-intelligence (programmatic-I/O agent task)', () => {
    it('is registered as a self-improvement task with a description and an on-demand default', () => {
      expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('layered-intelligence');
      expect(TASK_TYPE_DESCRIPTIONS['layered-intelligence']).toContain('performance metrics');
      expect(TASK_TYPE_DESCRIPTIONS['layered-intelligence']).toContain('visibility gap');
      expect(DEFAULT_TASK_INTERVALS['layered-intelligence']).toMatchObject({ type: INTERVAL_TYPES.ON_DEMAND, enabled: true });
    });

    it('has NO default prompt — the buildTaskInput hook renders it', () => {
      // LI runs as a normal reasoning agent with buildTaskInput/processTaskOutput
      // hooks (taskTypeHooks.js); the handler-backed dispatch was removed entirely.
      // The buildTaskInput hook renders the prompt, so there is no
      // DEFAULT_TASK_PROMPTS entry.
      expect(DEFAULT_TASK_PROMPTS['layered-intelligence']).toBeUndefined();
    });

    it('pins the throwaway-worktree posture so the reasoning agent can not land code', () => {
      expect(DEFAULT_TASK_INTERVALS['layered-intelligence'].taskMetadata).toMatchObject({
        useWorktree: true, openPR: false, discardWorktree: true
      });
    });

    it('decodes a legacy per-app custom+intervalMs override into an hourly cron', async () => {
      const { getAppTaskTypeInterval, getAppTaskTypeIntervalMs } = await import('./apps.js');
      cronDueNow();
      mockSchedule({
        tasks: { 'layered-intelligence': { type: 'on-demand', enabled: true, providerId: null, model: null, prompt: null } },
        executions: { 'task:layered-intelligence': { lastRun: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(), count: 1, perApp: { 'app-1': { lastRun: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(), count: 1 } } } }
      });
      getAppTaskTypeInterval.mockResolvedValue('custom');
      getAppTaskTypeIntervalMs.mockResolvedValue(60 * 60 * 1000);
      const res = await shouldRunTask('layered-intelligence', 'app-1');
      expect(res).toMatchObject({ shouldRun: true, reason: 'cron-due', cronExpression: '0 * * * *' });
      getAppTaskTypeInterval.mockResolvedValue(null);
      getAppTaskTypeIntervalMs.mockResolvedValue(null);
    });

    it('reads a per-app cron override string directly, overriding the global cadence', async () => {
      const { getAppTaskTypeInterval } = await import('./apps.js');
      cronDueNow();
      mockSchedule({
        tasks: { 'layered-intelligence': { type: 'on-demand', enabled: true, providerId: null, model: null, prompt: null } }
      });
      getAppTaskTypeInterval.mockResolvedValue('*/30 * * * *');
      const res = await shouldRunTask('layered-intelligence', 'app-1');
      expect(res).toMatchObject({ shouldRun: true, cronExpression: '*/30 * * * *' });
      getAppTaskTypeInterval.mockResolvedValue(null);
    });
  });

  describe('issue-watcher (programmatic-I/O agent task)', () => {
    it('ships as an enabled on-demand task with a 30-minute fallback and a runtime-generated prompt', () => {
      expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('issue-watcher');
      expect(DEFAULT_TASK_INTERVALS['issue-watcher']).toMatchObject({
        type: INTERVAL_TYPES.ON_DEMAND, intervalMs: 30 * 60 * 1000, enabled: true, prompt: null
      });
      expect(DEFAULT_TASK_PROMPTS['issue-watcher']).toBeUndefined();
      expect(TASK_TYPE_PROMPT_INFO['issue-watcher']).toMatchObject({ mode: 'runtime-generated' });
    });

    it('locks the direct no-checkout reasoning posture', () => {
      expect(MANAGED_AGENT_OPTIONS['issue-watcher']).toEqual(['useWorktree', 'openPR', 'readOnly', 'worktreeChangesExpected']);
      const config = { taskMetadata: { useWorktree: false, openPR: true, discardWorktree: false } };
      expect(enforceManagedAgentOptions('issue-watcher', config)).toBe(true);
      expect(config.taskMetadata).toMatchObject({ useWorktree: false, openPR: false, readOnly: true, worktreeChangesExpected: false });
    });
  });

  describe('dependency-updates isolation posture', () => {
    // Rationale lives on the registry entry: installs are never safe in the live checkout.
    it('ships worktree + PR delivery with the no-change marker and locks only useWorktree', () => {
      expect(DEFAULT_TASK_INTERVALS['dependency-updates'].taskMetadata).toEqual({ useWorktree: true, openPR: true, noChangeSuccess: true });
      expect(MANAGED_AGENT_OPTIONS['dependency-updates']).toEqual(['useWorktree']);
    });

    it('loadSchedule re-isolates an install whose stored config predates the lock', async () => {
      mockSchedule({
        tasks: {
          'dependency-updates': { type: 'cron', cronExpression: '0 6 * * 1', enabled: true, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: false } }
        }
      })
      const meta = (await loadSchedule()).tasks['dependency-updates'].taskMetadata
      expect(meta.useWorktree).toBe(true)
      // Backfilled from the defaults by the taskMetadata deep-merge.
      expect(meta.openPR).toBe(true)
      expect(meta.noChangeSuccess).toBe(true)
    })

    // The finalizer admits a non-audit scheduled type to the no-change exemption by
    // name (lib/noChangeCompletion.js), while the schedule default is what tells the
    // agent a clean exit is allowed. Keep the two in parity so a type cannot carry
    // the marker without the exemption, or the exemption without the marker.
    it('keeps the no-change allowlist in parity with the shipped noChangeSuccess defaults', () => {
      const marked = Object.entries(DEFAULT_TASK_INTERVALS)
        .filter(([type, interval]) => !isAuditTaskType(type) && interval.taskMetadata?.noChangeSuccess === true)
        .map(([type]) => type)
      expect(new Set(marked)).toEqual(NO_CHANGE_SCHEDULED_TYPES)
    })
  });

  describe('pr-reviewer (layered public-content review task)', () => {
    it('describes the preflight-owned prompt and ships the optional three-stage pipeline read-only', () => {
      expect(TASK_TYPE_PROMPT_INFO['pr-reviewer']).toMatchObject({ mode: 'runtime-generated' });
      expect(TASK_TYPE_PROMPT_INFO['pr-reviewer'].description).toContain('tool-free eligibility gate');
      expect(DEFAULT_TASK_INTERVALS['pr-reviewer'].taskMetadata.pipeline.stages).toEqual([
        expect.objectContaining({ name: 'Security Scan', role: 'security', readOnly: true, managed: true }),
        expect.objectContaining({ name: 'Eligibility Gate', role: 'eligibility', readOnly: true, executionProfile: 'public-review-gate' }),
        expect.objectContaining({ name: 'Code Review & Validated Actions', role: 'actions', readOnly: true, executionProfile: 'public-review-gate' }),
      ]);
      expect(MANAGED_AGENT_OPTIONS['pr-reviewer']).toEqual(['useWorktree', 'openPR', 'worktreeChangesExpected']);
    });
  });

  describe('do-replan task type', () => {
    it('should default to on-demand and enabled, with worktree+PR metadata', async () => {
      const interval = await getTaskInterval('do-replan')
      expect(interval.type).toBe(INTERVAL_TYPES.ON_DEMAND)
      expect(interval.enabled).toBe(true)
      expect(interval.taskMetadata?.useWorktree).toBe(true)
      expect(interval.taskMetadata?.openPR).toBe(true)
    })

    it('should expose a default prompt that delegates to the slashdo command', () => {
      const prompt = getDefaultPrompt('do-replan')
      expect(prompt).toBeDefined()
      expect(prompt).toContain('Replan')
      expect(prompt).toContain('{appName}')
      expect(prompt).toContain('{repoPath}')
      expect(prompt).toContain('{slashdoReplan}')
      expect(prompt).toContain('Issue-quality gate')
      expect(prompt).toContain('useful to do now')
      expect(prompt).toContain('let a later audit rediscover it')
      expect(prompt).toContain('A refactor is valid when current evidence shows it pays off now')
    })
  })

  describe('loadSchedule', () => {
    it('should return default schedule when no file exists', async () => {
      readJSONFile.mockResolvedValue(null)
      const schedule = await loadSchedule()
      expect(schedule.version).toBe(2)
      expect(schedule.tasks).toBeDefined()
      expect(schedule.executions).toBeDefined()
    })

    it('returns independent schedule instances on consecutive no-file reads without polluting defaults', async () => {
      readJSONFile.mockResolvedValue(null)
      const first = await loadSchedule()
      first.executions['task:security'] = { lastRun: '2026-10-18T00:00:00.000Z', count: 1 }
      first.templates.push({ name: 'polluted' })
      first.tasks['security'].enabled = false

      const second = await loadSchedule()
      expect(second.executions['task:security']).toBeUndefined()
      expect(second.templates).toEqual([])
      expect(second.tasks['security'].enabled).toBe(true)
      expect(DEFAULT_TASK_INTERVALS['security'].enabled).toBe(true)
    })

    it('does not mutate DEFAULT_TASK_INTERVALS during v1 to v2 migration', async () => {
      const originalSecurityPrompt = DEFAULT_TASK_INTERVALS['security'].prompt
      const originalSecurityMeta = DEFAULT_TASK_INTERVALS['security'].taskMetadata

      readJSONFile.mockResolvedValue({
        version: 1,
        selfImprovement: {
          security: {
            prompt: 'custom v1 prompt',
            taskMetadata: { fileIssues: true }
          }
        }
      })

      const migrated = await loadSchedule()
      expect(migrated.tasks['security'].prompt).toBe('custom v1 prompt')
      expect(DEFAULT_TASK_INTERVALS['security'].prompt).toBe(originalSecurityPrompt)
      expect(DEFAULT_TASK_INTERVALS['security'].taskMetadata).toEqual(originalSecurityMeta)
    })

    it('installs tasks on demand and keeps model research disabled until configured', async () => {
      const schedule = await loadSchedule()

      for (const taskType of SELF_IMPROVEMENT_TASK_TYPES) {
        expect(schedule.tasks[taskType], taskType).toMatchObject({
          type: INTERVAL_TYPES.ON_DEMAND,
          enabled: taskType !== 'model-comparison-refresh'
        })
      }
    })

    it('carries pre-rename v1 task config onto the renamed task', async () => {
      readJSONFile.mockResolvedValue({
        selfImprovement: { 'release-check': { enabled: false, prompt: 'custom release prompt' } },
        executions: { 'self-improve:release-check': { count: 2, lastRun: '2026-09-01T00:00:00.000Z' } },
      })
      const schedule = await loadSchedule()
      expect(schedule.tasks['do-release']).toMatchObject({ enabled: false, prompt: 'custom release prompt' })
      expect(schedule.tasks).not.toHaveProperty('release-check')
      expect(schedule.executions['task:do-release']).toMatchObject({ count: 2 })
    })

    it('turns the stall nudge off for a stored do-release schedule that never set it, and keeps an explicit choice', async () => {
      mockSchedule({
        tasks: { 'do-release': { type: 'on-demand', enabled: true, taskMetadata: { slashdoCommand: 'release', finishInFlight: true } } }
      })
      expect((await loadSchedule()).tasks['do-release'].taskMetadata).toMatchObject({ stallNudge: false, finishInFlight: true })

      mockSchedule({
        tasks: { 'do-release': { type: 'on-demand', enabled: true, taskMetadata: { slashdoCommand: 'release', stallNudge: true } } }
      })
      expect((await loadSchedule()).tasks['do-release'].taskMetadata.stallNudge).toBe(true)
    })

    it('should load and return existing v2 schedule', async () => {
      mockSchedule({
        tasks: { 'security': { type: 'weekly', enabled: true, providerId: 'p1', model: 'm1', prompt: null } }
      })

      const schedule = await loadSchedule()
      expect(schedule.version).toBe(2)
      expect(schedule.tasks['security'].enabled).toBe(true)
      expect(schedule.tasks['security'].providerId).toBe('p1')
    })

    it('normalizes a legacy cadence on read while preserving the paused state', async () => {
      mockSchedule({
        tasks: { security: { type: 'weekly', enabled: false, providerId: null, model: null, prompt: null } }
      })

      const schedule = await loadSchedule()

      // 'weekly' collapses to a Monday-07:00 cron; `enabled: false` is untouched.
      expect(schedule.tasks.security).toMatchObject({
        type: INTERVAL_TYPES.CRON, cronExpression: '0 7 * * 1', perpetual: false, enabled: false
      })
    })

    it('collapses every retired cadence and keeps the perpetual flag orthogonal', async () => {
      mockSchedule({
        tasks: {
          security: { type: 'rotation', enabled: true },
          'code-quality': { type: 'once', enabled: true },
          'test-coverage': { type: 'custom', intervalMs: 15 * 60 * 1000, enabled: true },
          documentation: { type: 'perpetual', recheckCron: '0 3 * * *', enabled: true },
          typing: { type: 'cron', cronExpression: '30 8 * * 2', perpetual: true, enabled: true },
        }
      })

      const { tasks } = await loadSchedule()
      expect(tasks.security).toMatchObject({ type: 'cron', cronExpression: '0 7 * * *', perpetual: false })
      expect(tasks['code-quality']).toMatchObject({ type: 'on-demand', perpetual: false })
      expect(tasks['code-quality'].cronExpression).toBeFalsy()
      expect(tasks['test-coverage']).toMatchObject({ type: 'cron', cronExpression: '*/15 * * * *' })
      expect(tasks.documentation).toMatchObject({ type: 'on-demand', perpetual: true, recheckCron: '0 3 * * *' })
      // Already on the new model: left exactly as stored.
      expect(tasks.typing).toMatchObject({ type: 'cron', cronExpression: '30 8 * * 2', perpetual: true })
    })

    it('should merge defaults for missing task types', async () => {
      mockSchedule({
        tasks: { 'security': { type: 'weekly', enabled: true, providerId: null, model: null, prompt: null } }
      })

      const schedule = await loadSchedule()
      // Should have all default task types even though only security was saved
      expect(schedule.tasks['code-quality']).toBeDefined()
      expect(schedule.tasks['test-coverage']).toBeDefined()
    })
  })

  describe('basic-task prompt genericization (PortOS → {appName})', () => {
    // Installs created before the Jan→Feb 2026 genericization stored a default that
    // hardcoded "PortOS" as the target app. These tasks were never versioned, so
    // they never auto-upgraded — and worse, an install that upgraded past the
    // promptVersion introduction got the old PortOS default mis-flagged
    // promptCustomized:true. The fix: version the basic tasks, keep the retired
    // defaults recognizable (by hash, in integrity.snapshot.json), and self-heal
    // the mis-flag in loadSchedule so every install converges on the generic
    // {appName} body. RETIRED_CONSOLE_ERRORS_PROMPT is one such retired default
    // — see taskPromptDefaults/retiredPromptFixtures.js.

    it('versions the basic self-improvement tasks so deployed installs can auto-upgrade', () => {
      for (const t of ['security', 'code-quality', 'test-coverage', 'performance', 'accessibility',
        'dependency-updates', 'documentation', 'ui-bugs', 'mobile-responsive', 'do-release']) {
        expect(PROMPT_VERSIONS[t], `PROMPT_VERSIONS['${t}']`).toBeGreaterThanOrEqual(2)
      }
    })

    it('the current documentation default no longer hardcodes PortOS', () => {
      expect(DEFAULT_TASK_PROMPTS['documentation']).not.toContain('PortOS')
      expect(DEFAULT_TASK_PROMPTS['documentation']).toContain('{appName}')
    })

    it('upgrades a stale, non-customized retired default (promptVersion: 1) to the current body', async () => {
      mockSchedule({
        tasks: { 'console-errors': { type: 'once', enabled: false, providerId: null, model: null, prompt: RETIRED_CONSOLE_ERRORS_PROMPT, promptVersion: 1 } }
      })
      const schedule = await loadSchedule()
      const task = schedule.tasks['console-errors']
      expect(task.prompt).toBe(DEFAULT_TASK_PROMPTS['console-errors'])
      expect(task.promptVersion).toBe(PROMPT_VERSIONS['console-errors'])
    })

    it('upgrades a pre-versioning retired default (promptVersion undefined) via the legacy-migration path', async () => {
      mockSchedule({
        tasks: { 'console-errors': { type: 'once', enabled: false, providerId: null, model: null, prompt: RETIRED_CONSOLE_ERRORS_PROMPT } }
      })
      const schedule = await loadSchedule()
      expect(schedule.tasks['console-errors'].prompt).toBe(DEFAULT_TASK_PROMPTS['console-errors'])
      expect(schedule.tasks['console-errors'].promptCustomized).not.toBe(true)
    })

    it('self-heals a mis-flagged promptCustomized that actually matches a retired default, then upgrades', async () => {
      mockSchedule({
        tasks: { 'console-errors': { type: 'once', enabled: false, providerId: null, model: null, prompt: RETIRED_CONSOLE_ERRORS_PROMPT, promptVersion: 1, promptCustomized: true } }
      })
      const schedule = await loadSchedule()
      const task = schedule.tasks['console-errors']
      expect(task.promptCustomized).toBe(false)
      expect(task.prompt).toBe(DEFAULT_TASK_PROMPTS['console-errors'])
      expect(task.promptVersion).toBe(PROMPT_VERSIONS['console-errors'])
    })

    it('preserves a genuine user customization even when it mentions PortOS', async () => {
      const custom = 'My own documentation prompt that happens to mention PortOS but matches no shipped default.'
      mockSchedule({
        tasks: { 'documentation': { type: 'once', enabled: false, providerId: null, model: null, prompt: custom, promptCustomized: true } }
      })
      const schedule = await loadSchedule()
      expect(schedule.tasks['documentation'].prompt).toBe(custom)
      expect(schedule.tasks['documentation'].promptCustomized).toBe(true)
    })
  })

  describe('promptSource provenance (issue #5432)', () => {
    // The self-heal above clears promptCustomized whenever the stored prompt
    // matches ANY shipped default (current or retired). That is right for a
    // flag the legacy migration guessed at, but it cannot tell that apart from a
    // user who deliberately pasted an older SHIPPED body into Settings →
    // Scheduled Tasks — that pin was cleared on the next load and the next
    // PROMPT_VERSIONS bump silently overwrote their chosen text. promptSource
    // records which of the two wrote the flag.
    const loadStored = async (config) => {
      mockSchedule({
        tasks: { 'console-errors': { type: 'once', enabled: false, providerId: null, model: null, ...config } }
      })
      return (await loadSchedule()).tasks['console-errors']
    }

    it('keeps a user-pinned retired default pinned instead of self-healing it', async () => {
      const task = await loadStored({
        prompt: RETIRED_CONSOLE_ERRORS_PROMPT,
        promptVersion: 1,
        promptCustomized: true,
        promptSource: 'user'
      })
      expect(task.promptCustomized).toBe(true)
      expect(task.prompt).toBe(RETIRED_CONSOLE_ERRORS_PROMPT)
    })

    it('still self-heals a legacy-inferred flag on a retired default', async () => {
      const task = await loadStored({
        prompt: RETIRED_CONSOLE_ERRORS_PROMPT,
        promptVersion: 1,
        promptCustomized: true,
        promptSource: 'legacy-inferred'
      })
      expect(task.promptCustomized).toBe(false)
      expect(task.prompt).toBe(DEFAULT_TASK_PROMPTS['console-errors'])
    })

    // Every install that upgrades into this field carries no promptSource at all.
    // Absent must keep behaving exactly as it does today, or the upgrade itself
    // would freeze thousands of mis-flagged prompts on their retired bodies.
    it('treats an absent promptSource as legacy-inferred (self-heals, as today)', async () => {
      const task = await loadStored({
        prompt: RETIRED_CONSOLE_ERRORS_PROMPT,
        promptVersion: 1,
        promptCustomized: true
      })
      expect(task.promptSource).toBeUndefined()
      expect(task.promptCustomized).toBe(false)
      expect(task.prompt).toBe(DEFAULT_TASK_PROMPTS['console-errors'])
    })

    it('stamps legacy-inferred when the legacy migration flags an unrecognized body', async () => {
      const custom = 'A console-errors prompt that matches no shipped default at all.'
      // No promptVersion → the legacy-migration branch runs.
      const task = await loadStored({ prompt: custom })
      expect(task.promptCustomized).toBe(true)
      expect(task.promptSource).toBe('legacy-inferred')
    })

    it('drops a stale promptSource when the config has no prompt to pin', async () => {
      const task = await loadStored({ prompt: null, promptSource: 'user' })
      expect(task.prompt).toBe(DEFAULT_TASK_PROMPTS['console-errors'])
      expect(task.promptSource).toBeNull()
    })

    it('survives a PROMPT_VERSIONS bump when the pin is user-sourced', async () => {
      const original = PROMPT_VERSIONS['console-errors']
      PROMPT_VERSIONS['console-errors'] = original + 1
      try {
        const task = await loadStored({
          prompt: RETIRED_CONSOLE_ERRORS_PROMPT,
          promptVersion: original,
          promptCustomized: true,
          promptSource: 'user'
        })
        expect(task.prompt).toBe(RETIRED_CONSOLE_ERRORS_PROMPT)
        expect(task.promptVersion).toBe(original)
      } finally {
        PROMPT_VERSIONS['console-errors'] = original
      }
    })

    it('upgrades the same body across a bump when the pin is legacy-inferred', async () => {
      const original = PROMPT_VERSIONS['console-errors']
      PROMPT_VERSIONS['console-errors'] = original + 1
      try {
        const task = await loadStored({
          prompt: RETIRED_CONSOLE_ERRORS_PROMPT,
          promptVersion: original,
          promptCustomized: true,
          promptSource: 'legacy-inferred'
        })
        expect(task.prompt).toBe(DEFAULT_TASK_PROMPTS['console-errors'])
        expect(task.promptVersion).toBe(original + 1)
      } finally {
        PROMPT_VERSIONS['console-errors'] = original
      }
    })
  })

  describe('pre-unification prompt generations (self- + app-improvement split)', () => {
    // Before the two improvement schedules were unified, every basic task
    // shipped up to two bodies with different headers — `[Self-Improvement] …`
    // and `[App Improvement: {appName}] …`. Unification replaced both with a
    // single `[Improvement: {appName}] …` body but preserved neither, so an
    // install carrying either generation stopped matching any shipped default,
    // was stamped promptCustomized by the legacy migration, and has been frozen
    // out of every prompt upgrade since — nine task types on a real install.
    // Their hashes are in the snapshot's history now; the fixture is the
    // `[Self-Improvement]` console-errors body.
    const loadOne = async (taskType, prompt, promptVersion) => {
      mockSchedule({
        tasks: { [taskType]: { type: 'once', enabled: false, providerId: null, model: null, prompt, promptVersion, promptCustomized: true } }
      })
      return (await loadSchedule()).tasks[taskType]
    }

    // Runs under BOTH version stamps a frozen install can carry. The legacy
    // migration wrote `promptVersion = PROMPT_VERSIONS[taskType]` alongside the
    // customized flag, so an install flagged after its type was versioned holds
    // the CURRENT version with a RETIRED body — and clearing the flag alone
    // leaves `storedVersion < current` false, so the upgrade never fires.
    // Testing only the version-1 stamp misses that entirely.
    it.each([
      ['pre-versioning', 1],
      ['current-version', PROMPT_VERSIONS['console-errors']],
    ])('self-heals and upgrades a stored pre-unification prompt (%s stamp)', async (_label, storedVersion) => {
      const task = await loadOne('console-errors', RETIRED_CONSOLE_ERRORS_PROMPT, storedVersion)
      expect(task.promptCustomized).toBe(false)
      expect(task.prompt).toBe(DEFAULT_TASK_PROMPTS['console-errors'])
      expect(task.promptVersion).toBe(PROMPT_VERSIONS['console-errors'])
    })

    it('preserves a genuine user customization that merely mimics a retired header', async () => {
      const custom = '[App Improvement: {appName}] My own audit that matches no shipped default.'
      const task = await loadOne('console-errors', custom, 1)
      expect(task.prompt).toBe(custom)
      expect(task.promptCustomized).toBe(true)
    })
  })

  describe('router-reached prompt types ride the same auto-upgrade walk (issue #3998)', () => {
    // Router-reached prompts (claim-issue-gitlab, claim-issue-jira) have no
    // DEFAULT_TASK_INTERVALS entry, but loadSchedule still walks them once an
    // install has STORED one: the merge loop preserves task types absent from the
    // defaults, and the upgrade loop iterates every stored key. Whether a stored
    // RETIRED body of theirs is recognized is the predicate's own contract
    // (taskPromptDefaults.test.js) — the bodies are no longer in the tree — so
    // this pins only that the walk reaches a stored-only key.
    it.each([
      'claim-issue-gitlab',
      'claim-issue-jira',
    ])('%s: a stored, behind-version default is walked and upgraded', async (taskType) => {
      mockSchedule({
        tasks: { [taskType]: { type: 'once', enabled: false, providerId: null, model: null, prompt: DEFAULT_TASK_PROMPTS[taskType], promptVersion: 1 } }
      })
      const task = (await loadSchedule()).tasks[taskType]
      expect(task.promptCustomized).not.toBe(true)
      expect(task.prompt).toBe(DEFAULT_TASK_PROMPTS[taskType])
      expect(task.promptVersion).toBe(PROMPT_VERSIONS[taskType])
    })
  })

  describe('getTaskInterval', () => {
    it('should return interval for known task type', async () => {
      const interval = await getTaskInterval('security')
      expect(interval.type).toBe(INTERVAL_TYPES.ON_DEMAND)
      expect(interval.enabled).toBe(true)
    })

    it('should return disabled defaults for unknown task type', async () => {
      const interval = await getTaskInterval('unknown-task')
      expect(interval.enabled).toBe(false)
    })

    it('reference-watch default is writable so the v4 prompt can record proposals (PLAN.md commit or gh/glab issue create)', async () => {
      // The v4 reference-watch prompt records proposals in the app's resolved
      // work tracker: PLAN.md commits its checklist items; GitHub/GitLab use
      // the shared `gh`/`glab` issue instructions. Both need a writable agent —
      // if `readOnly` flips back to true,
      // agentPromptBuilder injects the "## Read-Only Task" guard and the agent
      // refuses to write/commit/shell, silently breaking the flow. Pin the
      // contract so a future "default to read-only" refactor surfaces here.
      const interval = await getTaskInterval('reference-watch')
      expect(interval.taskMetadata?.readOnly).toBe(false)
    })

    // Tripwire for issue #734: the reference-watch `readOnly` default is derived from
    // what the prompt VERSION does. When PROMPT_VERSIONS['reference-watch'] is bumped,
    // this test fails until someone re-audits the default and advances
    // REFERENCE_WATCH_AUDITED_VERSION to match — so a prompt change can't silently
    // leave the schedule default stale.
    it('reference-watch readOnly default has been audited against the current prompt version (issue #734)', () => {
      expect(PROMPT_VERSIONS['reference-watch']).toBe(REFERENCE_WATCH_AUDITED_VERSION)
    })

    it('reference-watch v5 prompt requires a writable default so it can record proposals (PLAN.md commit or gh/glab issue create) (issue #734)', () => {
      // The coupling the audit anchor protects: at the audited version (v5), the prompt
      // writes to the resolved tracker (PLAN.md commit, or `gh`/`glab issue create`), so the
      // raw default must be writable. If a future re-audit flips
      // REFERENCE_WATCH_AUDITED_VERSION to a propose-only version, update this expectation
      // alongside the default and the anchor.
      if (REFERENCE_WATCH_AUDITED_VERSION === 5) {
        expect(DEFAULT_TASK_INTERVALS['reference-watch'].taskMetadata.readOnly).toBe(false)
      }
    })
  })

  describe('updateTaskInterval', () => {
    it('should update and persist task interval settings', async () => {
      const result = await updateTaskInterval('security', {
        enabled: true,
        providerId: 'provider-1',
        model: 'claude-3'
      })

      expect(result.enabled).toBe(true)
      expect(result.providerId).toBe('provider-1')
      expect(result.model).toBe('claude-3')
    })

    it('should normalize empty prompt to null', async () => {
      const result = await updateTaskInterval('security', {
        prompt: '   '
      })
      expect(result.prompt).toBeNull()
    })

    it('should set promptCustomized when custom prompt provided', async () => {
      const result = await updateTaskInterval('security', {
        prompt: 'Custom security audit prompt'
      })
      expect(result.promptCustomized).toBe(true)
    })

    it('should clear promptCustomized when prompt set to null', async () => {
      const result = await updateTaskInterval('security', {
        prompt: null
      })
      expect(result.promptCustomized).toBe(false)
    })

    // An explicit prompt write is the ONE source of a 'user' pin (#5432) — it is
    // what makes the store's self-heal leave a retired-but-deliberate body alone.
    it('should stamp promptSource "user" when a custom prompt is written', async () => {
      const result = await updateTaskInterval('security', {
        prompt: 'Custom security audit prompt'
      })
      expect(result.promptSource).toBe('user')
    })

    // The prompt editor prefills from the stored body, so "open, click Save" sends
    // back the CURRENT default verbatim. That must not pin — a pin is checked by
    // the self-heal only when its provenance is inferred, so a 'user' stamp here
    // would freeze the type off every future prompt upgrade with no way back.
    it('should not pin a prompt that is byte-identical to the current default', async () => {
      const result = await updateTaskInterval('security', {
        prompt: DEFAULT_TASK_PROMPTS['security']
      })
      expect(result.promptCustomized).toBe(false)
      expect(result.promptSource).toBeNull()
    })

    // A RETIRED shipped body IS a deliberate choice — the #5432 case.
    it('should pin a retired shipped default written by the user', async () => {
      const result = await updateTaskInterval('console-errors', { prompt: RETIRED_CONSOLE_ERRORS_PROMPT })
      expect(result.promptCustomized).toBe(true)
      expect(result.promptSource).toBe('user')
    })

    it('should clear promptSource when the prompt is set to null', async () => {
      const result = await updateTaskInterval('security', {
        prompt: null
      })
      expect(result.promptSource).toBeNull()
    })

    it('should preserve an existing pin when the write does not touch the prompt', async () => {
      mockSchedule({
        tasks: {
          'security': {
            type: 'weekly', enabled: false, providerId: null, model: null,
            prompt: 'A pinned body that matches no shipped default.',
            promptVersion: 2, promptCustomized: true, promptSource: 'user'
          }
        }
      })
      const result = await updateTaskInterval('security', { enabled: true })
      expect(result.promptSource).toBe('user')
      expect(result.promptCustomized).toBe(true)
    })

    it('should create new task entry for unknown type', async () => {
      const result = await updateTaskInterval('custom-type', {
        type: 'daily',
        enabled: true
      })
      expect(result.type).toBe('daily')
      expect(result.enabled).toBe(true)
    })

    it('clears all pr-watcher state when pr-watcher is globally disabled', async () => {
      clearAllPrWatcherState.mockClear()
      await updateTaskInterval('pr-watcher', { enabled: false })
      expect(clearAllPrWatcherState).toHaveBeenCalledTimes(1)
    })

    it('does not clear pr-watcher state on enable or on other task disables', async () => {
      clearAllPrWatcherState.mockClear()
      await updateTaskInterval('pr-watcher', { enabled: true })
      await updateTaskInterval('security', { enabled: false })
      expect(clearAllPrWatcherState).not.toHaveBeenCalled()
    })

    it('clears all issue-watcher state when issue-watcher is globally disabled', async () => {
      clearAllIssueWatcherState.mockClear()
      await updateTaskInterval('issue-watcher', { enabled: false })
      expect(clearAllIssueWatcherState).toHaveBeenCalledTimes(1)
    })
  })

  describe('managed agent options', () => {
    it('forces plan-task useWorktree/openPR back to false when stored true (loadSchedule)', async () => {
      mockSchedule({
        tasks: {
          'plan-task': {
            type: 'cron',
            enabled: true,
            providerId: null,
            model: null,
            prompt: null,
            taskMetadata: { useWorktree: true, openPR: true, simplify: true }
          }
        }
      })

      const schedule = await loadSchedule()
      expect(schedule.tasks['plan-task'].taskMetadata.useWorktree).toBe(false)
      expect(schedule.tasks['plan-task'].taskMetadata.openPR).toBe(false)
      expect(schedule.tasks['plan-task'].taskMetadata.claimFlow).toBe(true)
      // Non-managed flags pass through untouched
      expect(schedule.tasks['plan-task'].taskMetadata.simplify).toBe(true)
    })

    it('exposes managedAgentOptions in getScheduleStatus for plan-task', async () => {
      mockSchedule()
      const status = await getScheduleStatus()
      expect(status.tasks['plan-task'].managedAgentOptions).toEqual(['useWorktree', 'openPR', 'claimFlow'])
      // Other tasks should not carry the field
      expect(status.tasks['security'].managedAgentOptions).toBeUndefined()
    })

    it('rejects PUT attempts to flip a managed flag — response echoes the locked value', async () => {
      mockSchedule()
      const result = await updateTaskInterval('plan-task', {
        taskMetadata: { useWorktree: true, openPR: true, simplify: true }
      })
      expect(result.taskMetadata.useWorktree).toBe(false)
      expect(result.taskMetadata.openPR).toBe(false)
      expect(result.taskMetadata.claimFlow).toBe(true)
      expect(result.taskMetadata.simplify).toBe(true)
    })

    it('repopulates managed flags when stored taskMetadata was cleared to null', async () => {
      mockSchedule({
        tasks: {
          'plan-task': {
            type: 'cron',
            enabled: true,
            providerId: null,
            model: null,
            prompt: null,
            taskMetadata: null
          }
        }
      })

      const schedule = await loadSchedule()
      expect(schedule.tasks['plan-task'].taskMetadata.useWorktree).toBe(false)
      expect(schedule.tasks['plan-task'].taskMetadata.openPR).toBe(false)
      expect(schedule.tasks['plan-task'].taskMetadata.claimFlow).toBe(true)
    })
  })

  describe('recordExecution', () => {
    it('should record global execution', async () => {
      mockSchedule()
      const result = await recordExecution('test-record-global')
      expect(result.lastRun).toBeDefined()
      expect(result.count).toBe(1)
    })

    it('should record per-app execution', async () => {
      mockSchedule()
      const result = await recordExecution('test-record-app', 'app-1')
      expect(result.perApp['app-1']).toBeDefined()
      expect(result.perApp['app-1'].count).toBe(1)
      expect(result.perApp['app-1'].lastRun).toBeDefined()
    })

    it('should increment count on repeated execution', async () => {
      mockSchedule({
        executions: { 'task:test-incr': { lastRun: '2025-01-01T00:00:00Z', count: 5, perApp: {} } }
      })
      const result = await recordExecution('test-incr')
      expect(result.count).toBe(6)
    })
  })

  describe('getExecutionHistory', () => {
    it('should return empty history for unexecuted task', async () => {
      mockSchedule()
      const history = await getExecutionHistory('never-ran-task')
      expect(history.lastRun).toBeNull()
      expect(history.count).toBe(0)
      expect(history.perApp).toEqual({})
    })

    it('should return existing execution data', async () => {
      mockSchedule({
        executions: { 'task:my-task': { lastRun: '2025-06-01T00:00:00Z', count: 3, perApp: {} } }
      })
      const history = await getExecutionHistory('my-task')
      expect(history.lastRun).toBe('2025-06-01T00:00:00Z')
      expect(history.count).toBe(3)
    })
  })

  describe('shouldRunTask', () => {
    it('keeps invalid cron verdicts one shape before and after cron parsing', async () => {
      mockSchedule({ tasks: { 'ui-bugs': { type: 'cron', enabled: true, cronExpression: 'not a cron' } } })
      const malformed = await shouldRunTask('ui-bugs')
      mockSchedule({ tasks: { 'ui-bugs': { type: 'cron', enabled: true, cronExpression: '0 7 * * *' } } })
      parseCronToNextRun.mockReturnValue(null)
      const unresolvable = await shouldRunTask('ui-bugs')
      expect(malformed).toEqual({ shouldRun: false, reason: 'invalid-cron', cronExpression: null })
      expect(unresolvable).toEqual({ shouldRun: false, reason: 'invalid-cron', cronExpression: '0 7 * * *' })
    })

    it('does not run a task whose required instance feature is disabled', async () => {
      isInstanceFeatureEnabled.mockResolvedValue(false)
      mockSchedule({ tasks: { 'jira-sprint-manager': { type: 'rotation', enabled: true } } })

      const result = await shouldRunTask('jira-sprint-manager')

      expect(result).toEqual({ shouldRun: false, reason: 'feature-disabled', feature: 'jira' })
    })

    it('should not run disabled task', async () => {
      mockSchedule({
        tasks: { 'disabled-task': { type: 'weekly', enabled: false, providerId: null, model: null, prompt: null } }
      })
      const result = await shouldRunTask('disabled-task')
      expect(result.shouldRun).toBe(false)
      expect(result.reason).toBe('disabled')
    })

    it('normalizes a retired rotation cadence to a daily cron on read', async () => {
      readJSONFile.mockResolvedValue({
        version: 2,
        tasks: {
          'code-quality': { type: 'rotation', enabled: true, providerId: null, model: null, prompt: null }
        },
        executions: {}
      })

      const interval = await getTaskInterval('code-quality')
      expect(interval).toMatchObject({ type: 'cron', cronExpression: '0 7 * * *', perpetual: false })
    })

    it('never auto-runs a plain on-demand task, but drains one carrying the perpetual flag', async () => {
      mockSchedule({
        tasks: {
          'ui-bugs': { type: 'on-demand', enabled: true, providerId: null, model: null, prompt: null },
          'claim-issue': { type: 'on-demand', perpetual: true, enabled: true, providerId: null, model: null, prompt: null }
        }
      })

      expect(await shouldRunTask('ui-bugs')).toMatchObject({ shouldRun: false, reason: 'on-demand-only' })
      expect(await shouldRunTask('claim-issue')).toMatchObject({ shouldRun: true, reason: 'perpetual-drain' })
    })

    it('should not run on-demand tasks automatically', async () => {
      mockSchedule({
        tasks: { 'ui-bugs': { type: 'on-demand', enabled: true, providerId: null, model: null, prompt: null } }
      })

      const result = await shouldRunTask('ui-bugs')
      expect(result.shouldRun).toBe(false)
      expect(result.reason).toBe('on-demand-only')
    })

    it('collapses a retired once cadence to a manual-only on-demand task, run count or not', async () => {
      mockSchedule({
        tasks: { 'accessibility': { type: 'once', enabled: true, providerId: null, model: null, prompt: null } },
        executions: { 'task:accessibility': { lastRun: '2025-01-01T00:00:00Z', count: 1, perApp: {} } }
      })

      const result = await shouldRunTask('accessibility')
      expect(result.shouldRun).toBe(false)
      // No 'once-completed' dead end — a manual trigger runs it again.
      expect(result.reason).toBe('on-demand-only')
    })

    it('should skip weekday-only tasks on weekends', async () => {
      getLocalParts.mockReturnValue({ dayOfWeek: 0 }) // Sunday

      mockSchedule({
        tasks: { 'pr-reviewer': { type: 'cron', cronExpression: '0 */2 * * *', enabled: true, weekdaysOnly: true, providerId: null, model: null, prompt: null } }
      })

      const result = await shouldRunTask('pr-reviewer')
      expect(result.shouldRun).toBe(false)
      expect(result.reason).toBe('weekday-only')
    })

    it('should not run when disabled for specific app', async () => {
      isTaskTypeEnabledForApp.mockResolvedValue(false)

      mockSchedule({
        tasks: { 'security': { type: 'weekly', enabled: true, providerId: null, model: null, prompt: null } }
      })

      const result = await shouldRunTask('security', 'app-1')
      expect(result.shouldRun).toBe(false)
      expect(result.reason).toBe('disabled-for-app')
    })

    it('runs a cron task once its slot has elapsed', async () => {
      cronDueNow()
      const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()

      // Explicit runAfter: [] overrides the feature-ideas default that depends on do-replan
      mockSchedule({
        tasks: { 'feature-ideas': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, providerId: null, model: null, prompt: null, runAfter: [] } },
        executions: { 'task:feature-ideas': { lastRun: twoDaysAgo, count: 1, perApp: {} } }
      })

      const result = await shouldRunTask('feature-ideas')
      expect(result.shouldRun).toBe(true)
      expect(result.reason).toBe('cron-due')
    })

    it('holds a cron task until its next slot', async () => {
      cronNotDueYet()
      const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000).toISOString()

      mockSchedule({
        tasks: { 'feature-ideas': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, providerId: null, model: null, prompt: null, runAfter: [] } },
        executions: { 'task:feature-ideas': { lastRun: oneHourAgo, count: 5, perApp: {} } }
      })

      const result = await shouldRunTask('feature-ideas')
      expect(result.shouldRun).toBe(false)
      expect(result.reason).toBe('cron-cooldown')
    })

    it('feature-ideas waits on do-replan when do-replan is enabled', async () => {
      cronDueNow()
      const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()

      // Default runAfter:['do-replan'] kicks in since the test doesn't override it
      mockSchedule({
        tasks: {
          'feature-ideas': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, providerId: null, model: null, prompt: null },
          'do-replan':     { type: 'cron', cronExpression: '0 7 * * 1', enabled: true, providerId: null, model: null, prompt: null }
        },
        executions: { 'task:feature-ideas': { lastRun: twoDaysAgo, count: 1, perApp: {} } }
      })

      const result = await shouldRunTask('feature-ideas')
      expect(result.shouldRun).toBe(false)
      expect(result.reason).toBe('waiting-on-dependencies')
      expect(result.pendingDeps).toContain('do-replan')
    })

    it('feature-ideas runs when do-replan dependency is globally disabled', async () => {
      cronDueNow()
      const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()

      // do-replan is disabled — feature-ideas would otherwise wait forever, so the dep is skipped
      mockSchedule({
        tasks: {
          'feature-ideas': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, providerId: null, model: null, prompt: null },
          'do-replan':     { type: 'cron', cronExpression: '0 7 * * 1', enabled: false, providerId: null, model: null, prompt: null }
        },
        executions: { 'task:feature-ideas': { lastRun: twoDaysAgo, count: 1, perApp: {} } }
      })

      const result = await shouldRunTask('feature-ideas')
      expect(result.shouldRun).toBe(true)
      expect(result.reason).toBe('cron-due')
    })

    it('feature-ideas runs when do-replan dependency is disabled for the app', async () => {
      cronDueNow()
      const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()

      mockSchedule({
        tasks: {
          'feature-ideas': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, providerId: null, model: null, prompt: null },
          'do-replan':     { type: 'cron', cronExpression: '0 7 * * 1', enabled: true, providerId: null, model: null, prompt: null }
        },
        executions: {
          'task:feature-ideas': { lastRun: twoDaysAgo, count: 1, perApp: { 'app-1': { lastRun: twoDaysAgo, count: 1 } } }
        }
      })
      // do-replan is enabled globally but disabled for app-1; feature-ideas is enabled for app-1
      const originalIsTaskTypeEnabledForApp = isTaskTypeEnabledForApp.getMockImplementation()
      isTaskTypeEnabledForApp.mockImplementation(async (_appId, taskType) => taskType !== 'do-replan')

      try {
        const result = await shouldRunTask('feature-ideas', 'app-1')
        expect(result.shouldRun).toBe(true)
        expect(result.reason).toBe('cron-due')
      } finally {
        if (originalIsTaskTypeEnabledForApp) {
          isTaskTypeEnabledForApp.mockImplementation(originalIsTaskTypeEnabledForApp)
        } else {
          isTaskTypeEnabledForApp.mockReset()
        }
      }
    })

    it('feature-ideas ignores an enabled on-demand do-replan dependency', async () => {
      cronDueNow()
      const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()

      mockSchedule({
        tasks: {
          'feature-ideas': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, providerId: null, model: null, prompt: null },
          'do-replan': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null }
        },
        executions: { 'task:feature-ideas': { lastRun: twoDaysAgo, count: 1, perApp: {} } }
      })

      const result = await shouldRunTask('feature-ideas')
      expect(result.shouldRun).toBe(true)
      expect(result.reason).toBe('cron-due')
    })

    it('feature-ideas runs when do-replan has run since its last run', async () => {
      cronDueNow()
      const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()
      const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString()

      mockSchedule({
        tasks: {
          'feature-ideas': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, providerId: null, model: null, prompt: null },
          'do-replan':     { type: 'cron', cronExpression: '0 7 * * 1', enabled: true, providerId: null, model: null, prompt: null }
        },
        executions: {
          'task:feature-ideas': { lastRun: twoDaysAgo, count: 1, perApp: {} },
          'task:do-replan':     { lastRun: oneDayAgo, count: 1, perApp: {} }
        }
      })

      const result = await shouldRunTask('feature-ideas')
      expect(result.shouldRun).toBe(true)
      expect(result.reason).toBe('cron-due')
    })

    describe('cron slots without catch-up', () => {
      let savedImplementations
      beforeEach(async () => {
        const mocks = [parseCronToNextRun, getLocalParts, getAppTaskTypeInterval, isTaskTypeEnabledForApp]
        savedImplementations = mocks.map(mock => [mock, mock.getMockImplementation()])
        const actual = await vi.importActual('../lib/timezone.js')
        getLocalParts.mockImplementation(actual.getLocalParts)
        isTaskTypeEnabledForApp.mockResolvedValue(true)
      })
      afterEach(() => {
        for (const [mock, implementation] of savedImplementations) mock.mockImplementation(implementation)
      })

      it('waits after an inherited schedule edit, fires in the new slot, and does not repeat it', async () => {
        vi.useFakeTimers()
        vi.setSystemTime(new Date('2026-09-09T05:57:22Z'))
        const actual = await vi.importActual('./eventScheduler.js')
        parseCronToNextRun.mockImplementation(actual.parseCronToNextRun)
        getAppTaskTypeInterval.mockResolvedValue(null)
        const lastRun = '2026-09-08T05:01:00Z'
        const schedule = {
          tasks: { 'do-release': { type: 'cron', enabled: true, cronExpression: '30 4 * * *', runAfter: [] } },
          executions: { 'task:do-release': { perApp: { 'app-1': { lastRun, count: 1 } } } }
        }
        mockSchedule(schedule)

        expect(await shouldRunTask('do-release', 'app-1')).toMatchObject({
          shouldRun: false, reason: 'cron-cooldown', nextRunAt: '2026-09-09T11:30:00.000Z'
        })
        vi.setSystemTime(new Date('2026-09-09T11:30:20Z'))
        expect(await shouldRunTask('do-release', 'app-1')).toMatchObject({ shouldRun: true, reason: 'cron-due' })

        schedule.executions['task:do-release'].perApp['app-1'].lastRun = '2026-09-09T11:30:20Z'
        mockSchedule(schedule)
        expect(await shouldRunTask('do-release', 'app-1')).toMatchObject({
          shouldRun: false, nextRunAt: '2026-09-10T11:30:00.000Z'
        })
      })

      it('judges readiness against a pinned `now` instead of the wall clock', async () => {
        vi.useFakeTimers()
        vi.setSystemTime(new Date('2026-09-09T11:31:30Z'))
        const actual = await vi.importActual('./eventScheduler.js')
        parseCronToNextRun.mockImplementation(actual.parseCronToNextRun)
        getAppTaskTypeInterval.mockResolvedValue(null)
        mockSchedule({
          tasks: { 'do-release': { type: 'cron', enabled: true, cronExpression: '30 4 * * *', runAfter: [] } },
          executions: { 'task:do-release': { perApp: { 'app-1': { lastRun: '2026-09-08T05:01:00Z', count: 1 } } } }
        })
        const pinned = new Date('2026-09-09T11:30:20Z').getTime()
        expect(await shouldRunTask('do-release', 'app-1')).toMatchObject({ shouldRun: false, reason: 'cron-cooldown' })
        expect(await shouldRunTask('do-release', 'app-1', { now: pinned })).toMatchObject({ shouldRun: true, reason: 'cron-due' })
        expect((await getDueTasks('app-1', { now: pinned })).map(t => t.taskType)).toContain('do-release')
        expect((await getDueTasks('app-1')).map(t => t.taskType)).not.toContain('do-release')
      })

      it('waits for the next per-app slot after downtime, including never-run tasks', async () => {
        vi.useFakeTimers()
        vi.setSystemTime(new Date('2026-09-09T12:00:00Z'))
        const actual = await vi.importActual('./eventScheduler.js')
        parseCronToNextRun.mockImplementation(actual.parseCronToNextRun)
        getAppTaskTypeInterval.mockResolvedValue('30 4 * * *')
        mockSchedule({
          tasks: { 'do-release': { type: 'cron', enabled: true, cronExpression: '0 8 * * *', createdAt: '2026-09-01T00:00:00Z', runAfter: [] } }
        })
        expect(await shouldRunTask('do-release', 'app-1')).toMatchObject({
          shouldRun: false, nextRunAt: '2026-09-10T11:30:00.000Z'
        })
        getAppTaskTypeInterval.mockResolvedValue(null)
      })
    })
  })

  describe('getDueTasks', () => {
    it('should return empty array when no tasks are enabled', async () => {
      mockSchedule({
        tasks: { ...PAUSED_SHIPPED_DRAINS, 'security': { type: 'cron', cronExpression: '0 7 * * 1', enabled: false, providerId: null, model: null, prompt: null } }
      })
      const due = await getDueTasks()
      expect(due).toEqual([])
    })

    it('returns a due cron task and skips a disabled one', async () => {
      parseCronToNextRun.mockReturnValue(new Date(Date.now() - 60_000))
      mockSchedule({
        tasks: {
          ...PAUSED_SHIPPED_DRAINS,
          'code-quality': { type: 'cron', cronExpression: '0 7 * * *', enabled: true, providerId: null, model: null, prompt: null },
          'security': { type: 'cron', cronExpression: '0 7 * * 1', enabled: false, providerId: null, model: null, prompt: null }
        }
      })

      const due = await getDueTasks()
      expect(due.length).toBe(1)
      expect(due[0].taskType).toBe('code-quality')
    })
  })

  describe('getNextTaskType', () => {
    it('should return null when no tasks are enabled', async () => {
      mockSchedule({
        tasks: { ...PAUSED_SHIPPED_DRAINS, 'security': { type: 'cron', cronExpression: '0 7 * * 1', enabled: false, providerId: null, model: null, prompt: null } }
      })
      const result = await getNextTaskType()
      expect(result).toBeNull()
    })

    it('returns null when only on-demand tasks are enabled — nothing is auto-queued', async () => {
      mockSchedule({
        tasks: {
          ...PAUSED_SHIPPED_DRAINS,
          'code-quality': { type: 'on-demand', enabled: true, providerId: null, model: null, prompt: null },
          'error-handling': { type: 'on-demand', enabled: true, providerId: null, model: null, prompt: null }
        }
      })

      expect(await getNextTaskType()).toBeNull()
    })

    it('does not select a feature-disabled task', async () => {
      isInstanceFeatureEnabled.mockResolvedValue(false)
      parseCronToNextRun.mockReturnValue(new Date(Date.now() - 60_000))
      mockSchedule({ tasks: {
        ...PAUSED_SHIPPED_DRAINS,
        'jira-sprint-manager': { type: INTERVAL_TYPES.CRON, cronExpression: '0 7 * * *', enabled: true },
      } })

      expect(await getNextTaskType()).toBeNull()
    })

    it('prefers a due cron task over an always-ready perpetual drain', async () => {
      // A user-pinned wall-clock schedule must fire at its slot even while a
      // perpetual task is perpetually 'ready' (draining a backlog).
      const todayNineAm = recentNineAm()
      const yesterdayNineAm = new Date(todayNineAm.getTime() - 24 * 60 * 60 * 1000)

      cronDueNow()

      mockSchedule({
        tasks: {
          ...PAUSED_SHIPPED_DRAINS,
          'code-quality': { type: 'on-demand', perpetual: true, enabled: true, providerId: null, model: null, prompt: null, runAfter: [] },
          'plan-task':    { type: 'cron',   enabled: true, cronExpression: '0 9 * * *', providerId: null, model: null, prompt: null, createdAt: yesterdayNineAm.toISOString() }
        }
      })

      const result = await getNextTaskType()
      expect(result.taskType).toBe('plan-task')
      expect(result.reason).toBe('cron-due')
    })

    it('perpetualOnly returns the due perpetual task even when a higher-priority cron task is also due', async () => {
      // The mixed-schedule stall: an app on review cooldown has BOTH a due cron
      // task and a due perpetual drain. Unconstrained, getNextTaskType returns
      // the cron task (cron outranks perpetual) — but on cooldown only the
      // perpetual drain is eligible, so the caller passes perpetualOnly to get
      // the drain instead of being stranded behind the cooled-down cron pick.
      const todayNineAm = recentNineAm()
      const yesterdayNineAm = new Date(todayNineAm.getTime() - 24 * 60 * 60 * 1000)
      cronDueNow()

      mockSchedule({
        tasks: {
          ...PAUSED_SHIPPED_DRAINS,
          'pr-watcher':  { type: 'cron', enabled: true, cronExpression: '0 9 * * *', providerId: null, model: null, prompt: null, createdAt: yesterdayNineAm.toISOString() },
          'claim-issue': { type: 'on-demand', perpetual: true, enabled: true, providerId: null, model: null, prompt: null }
        }
      })

      // Unconstrained: cron wins.
      const unconstrained = await getNextTaskType()
      expect(unconstrained.taskType).toBe('pr-watcher')

      // perpetualOnly: the perpetual drain is returned instead.
      const constrained = await getNextTaskType(null, { perpetualOnly: true })
      expect(constrained).not.toBeNull()
      expect(constrained.taskType).toBe('claim-issue')
      expect(constrained.reason).toBe('perpetual-drain')
    })

    it('perpetualOnly returns null when no perpetual task is due (app stays throttled)', async () => {
      parseCronToNextRun.mockReturnValue(new Date(Date.now() - 60_000))
      mockSchedule({
        tasks: {
          ...PAUSED_SHIPPED_DRAINS,
          'code-quality':  { type: 'cron', cronExpression: '0 7 * * *', enabled: true, providerId: null, model: null, prompt: null },
          'error-handling': { type: 'on-demand', enabled: true, providerId: null, model: null, prompt: null }
        }
      })
      const result = await getNextTaskType(null, { perpetualOnly: true })
      expect(result).toBeNull()
    })
  })

  describe('templates', () => {
    it('should add a template task', async () => {
      const template = {
        name: 'Custom audit',
        prompt: 'Run custom audit',
        priority: 'HIGH'
      }

      const result = await addTemplateTask(template)
      expect(result.id).toBeDefined()
      expect(result.name).toBe('Custom audit')
    })

    it('round-trips a template through listing, the persisted payload, and delete', async () => {
      // Store reads the file on every call, so each write is fed back as the next read.
      mockSchedule()
      const template = await addTemplateTask({ name: 'Round trip', prompt: 'test' })
      const afterAdd = JSON.parse(writeFile.mock.calls.at(-1)[1])
      expect(afterAdd.templates.map(t => t.id)).toContain(template.id)
      readJSONFile.mockResolvedValue(afterAdd)
      expect((await getTemplateTasks()).map(t => t.id)).toContain(template.id)

      const result = await deleteTemplateTask(template.id)
      expect(result.success).toBe(true)
      const afterDelete = JSON.parse(writeFile.mock.calls.at(-1)[1])
      expect(afterDelete.templates.map(t => t.id)).not.toContain(template.id)
      readJSONFile.mockResolvedValue(afterDelete)
      expect((await getTemplateTasks()).map(t => t.id)).not.toContain(template.id)

      expect(await deleteTemplateTask(template.id)).toMatchObject({ error: expect.any(String) })
    })
  })

  describe('getDefaultPrompt', () => {
    it('should return prompt for known task type', () => {
      const prompt = getDefaultPrompt('security')
      expect(prompt).toBeDefined()
      expect(prompt).toContain('Security')
    })

    it('should return null for unknown task type', () => {
      const prompt = getDefaultPrompt('nonexistent')
      expect(prompt).toBeNull()
    })
  })

  describe('execution field write safety', () => {
    it('keeps a persisted custom prompt readable after rejecting malformed updates', async () => {
      mockSchedule();
      await updateTaskInterval('documentation', { prompt: 'Example custom prompt', providerId: 'example-provider', model: 'example-model' });
      const saved = JSON.parse(writeFile.mock.calls.at(-1)[1]);
      const original = saved.tasks.documentation;
      readJSONFile.mockResolvedValue(saved);
      writeFile.mockClear();
      for (const field of ['prompt', 'providerId', 'model']) {
        for (const value of [{ text: 'Example malformed prompt' }, ['example'], true, 42]) {
          await expect(updateTaskInterval('documentation', { [field]: value })).rejects.toMatchObject({ status: 400, code: 'VALIDATION_ERROR' });
        }
      }
      expect(writeFile).not.toHaveBeenCalled();
      expect(saved.tasks.documentation).toEqual(original);
      expect(await getTaskPrompt('documentation')).toBe('Example custom prompt');
      expect(original).toMatchObject({ promptSource: 'user', providerId: 'example-provider', model: 'example-model' });
    });
  });

  describe('getTaskPrompt', () => {
    it('should return default prompt when no custom prompt set', async () => {
      const prompt = await getTaskPrompt('security')
      expect(prompt).toBeDefined()
      expect(prompt).toContain('Security')
    })

    it('should return fallback prompt for unknown task type', async () => {
      const prompt = await getTaskPrompt('unknown-type')
      expect(prompt).toContain('unknown-type')
      expect(prompt).toContain('{repoPath}')
    })

    it('should substitute {slashdoReplan} with the bundled replan command body', async () => {
      const { loadSlashdoFile } = await import('../lib/slashdoLoader.js')
      loadSlashdoFile.mockResolvedValueOnce('# Replan Command\n\nSentinel body for substitution test.')
      const prompt = await getTaskPrompt('do-replan')
      expect(prompt).not.toContain('{slashdoReplan}')
      expect(prompt).toContain('Sentinel body for substitution test.')
      expect(loadSlashdoFile).toHaveBeenCalledWith('replan', { stripFrontmatter: true })
    })

    it('plan-task default self-picks like /claim — no scheduler pre-pick / Item Constraint', async () => {
      // The agent picks its own slug at execution time (Phase 1) rather than
      // accepting a slug the scheduler pre-reserved. Pin the absence of the
      // pre-pick scaffolding so a future edit can't quietly reintroduce the
      // dispatch-time reservation race (see cos.js PLAN_SELF_CLAIM_TASK_TYPES).
      const prompt = await getTaskPrompt('plan-task')
      expect(prompt).not.toContain('{planConstraint}')
      expect(prompt).not.toContain('Item Constraint')
      expect(prompt).not.toContain('scheduler pre-reserved')
      // It still drives the /claim flow: in-flight scan + claim/<slug> branch.
      expect(prompt).toContain('claim/<slug>')
      expect(prompt).toContain('in-flight set')
    })

    it('claim-issue drives the /claim --issues flow against GitHub issues', async () => {
      const prompt = await getTaskPrompt('claim-issue')
      // Work source is the GitHub issue tracker, not PLAN.md.
      expect(prompt).toContain('claim/issue-')
      expect(prompt).toContain('gh issue list')
      expect(prompt).toContain('Closes #')
      // The author-filter placeholder is substituted at dispatch time
      // (cosTaskGenerator), so it stays literal in the raw stored prompt.
      expect(prompt).toContain('{issueAuthorFilter}')
      // Issues mode ships GitHub issues only — it explicitly does not touch PLAN.md.
      expect(prompt).toContain('does NOT touch PLAN.md')
    })

    it('do-release delegates to slashdo release and requires a named release heading', async () => {
      const prompt = await getTaskPrompt('do-release')
      expect(prompt).toContain('/do:release')
      expect(prompt).toContain('{reviewers}')
      expect(prompt).toContain('# Release vX.Y.Z - <Fun Name>')
      expect(prompt).toContain('one or two biggest user-visible wins')
      expect(prompt).toContain('GitHub release title')
      expect(prompt.toLowerCase()).not.toContain('copilot')
      expect(prompt).not.toContain('reviewThreads')
    })
  })

  // The gh/git coordinator types deliver their work as a SIDE EFFECT (a deleted
  // branch, a merged PR, a relabeled issue, a posted report) in the app's live
  // checkout — never as a commit in a CoS-managed worktree. Two code-shipping
  // criteria have to be switched off for them or every successful run is recorded
  // as a failure: `openPR` (→ `pr-missing` at finalization, since there is no code
  // to open a PR for) and `worktreeChangesExpected` (→ `idle-no-changes` at the TUI
  // idle-complete gate, since a clean tree IS the success shape).
  describe('non-committing coordinator posture', () => {
    // Driven off NON_COMMITTING_COORDINATOR_TASK_TYPES — the same set that grants
    // these types their commit-criterion exemption — rather than a hand-typed list,
    // so a FUTURE coordinator type added there can't silently ship without the
    // posture. That drift is exactly how `branch-cleanup` shipped with no
    // taskMetadata at all, letting an app-level `defaultOpenPR: true` attach a
    // worktree + PR expectation to a task that only runs `git branch -d`.
    // branch-cleanup remains in the coordinator exemption only for archived
    // tasks from before migration 274; it is no longer a shipped schedule type.
    it.each([...NON_COMMITTING_COORDINATOR_TASK_TYPES].filter((type) => DEFAULT_TASK_INTERVALS[type]))(
      '%s declares no worktree/PR, expects a clean tree, and locks both flags',
      (taskType) => {
        const meta = DEFAULT_TASK_INTERVALS[taskType].taskMetadata
        // Explicitly false, NOT merely absent — applyAppWorktreeDefault fills these
        // from the app's defaults on an `=== undefined` check, so an absent key is
        // the bug, not a pass.
        expect(meta.openPR).toBe(false)
        expect(meta.useWorktree).toBe(false)
        expect(meta.worktreeChangesExpected).toBe(false)
        // Locked, so a per-app override can't re-attach what the defaults cleared.
        // worktreeChangesExpected is managed too — see MANAGED_AGENT_OPTIONS.
        const managed = ['useWorktree', 'openPR', 'worktreeChangesExpected']
        if (taskType === 'do-release') {
          managed.push('slashdoCommand')
          expect(meta.slashdoCommand).toBe('release')
        }
        expect(MANAGED_AGENT_OPTIONS[taskType]).toEqual(managed)
      }
    )

    // An explicit `taskMetadata: null` (accepted by PUT /api/cos/schedule as "clear
    // it") makes loadSchedule SKIP the defaults deep-merge, so enforceManagedAgentOptions
    // is the only thing that rebuilds the bag — and it rebuilds MANAGED fields only.
    // Before worktreeChangesExpected was managed, it went absent here and a successful
    // clean-tree run was scored `idle-no-changes` all over again.
    it.each([...NON_COMMITTING_COORDINATOR_TASK_TYPES].filter((type) => DEFAULT_TASK_INTERVALS[type]))(
      '%s keeps the full posture when stored taskMetadata was cleared to null',
      async (taskType) => {
        mockSchedule({
          tasks: {
            [taskType]: { type: 'cron', enabled: true, providerId: null, model: null, prompt: null, taskMetadata: null }
          }
        })

        const meta = (await loadSchedule()).tasks[taskType].taskMetadata
        expect(meta.useWorktree).toBe(false)
        expect(meta.openPR).toBe(false)
        expect(meta.worktreeChangesExpected).toBe(false)
        if (taskType === 'do-release') expect(meta.slashdoCommand).toBe('release')
        if (taskType === 'branch-reconcile') expect(meta.branchesPerAgent).toBe(3)
      }
    )

    it('forces branch-reconcile useWorktree/openPR back off when stored true (loadSchedule)', async () => {
      mockSchedule({
        tasks: {
          'branch-reconcile': {
            type: 'cron',
            enabled: true,
            providerId: null,
            model: null,
            prompt: null,
            taskMetadata: { useWorktree: true, openPR: true }
          }
        }
      })

      const schedule = await loadSchedule()
      expect(schedule.tasks['branch-reconcile'].taskMetadata.useWorktree).toBe(false)
      expect(schedule.tasks['branch-reconcile'].taskMetadata.openPR).toBe(false)
      // Backfilled from the defaults for installs whose stored config predates it.
      expect(schedule.tasks['branch-reconcile'].taskMetadata.worktreeChangesExpected).toBe(false)
      expect(schedule.tasks['branch-reconcile'].taskMetadata.branchesPerAgent).toBe(3)
    })

    it('keeps the legacy branch-cleanup safety posture until migration 274 runs', async () => {
      mockSchedule({
        tasks: {
          'branch-cleanup': {
            type: 'weekly',
            enabled: true,
            providerId: null,
            model: null,
            prompt: null,
            taskMetadata: { useWorktree: true, openPR: true, worktreeChangesExpected: true }
          }
        }
      })

      const meta = (await loadSchedule()).tasks['branch-cleanup'].taskMetadata
      expect(meta.useWorktree).toBe(false)
      expect(meta.openPR).toBe(false)
      expect(meta.worktreeChangesExpected).toBe(false)
    })

    it('strips a per-app branch-reconcile worktree/PR override', () => {
      expect(stripManagedAgentOptionsFromOverride('branch-reconcile', { useWorktree: true, openPR: true })).toBeNull()
    })
  })

  describe('claim-issue defaults', () => {
    it('is registered as a self-improvement task type', () => {
      expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('claim-issue')
    })

    it('defaults to self-filed issues with worktree/PR managed by the agent', () => {
      const cfg = DEFAULT_TASK_INTERVALS['claim-issue']
      expect(cfg.type).toBe(INTERVAL_TYPES.ON_DEMAND)
      expect(cfg.enabled).toBe(true)
      // Default is the slashdo /do:next --self security boundary.
      expect(cfg.taskMetadata.issueAuthorFilter).toBe('self')
      // Mirrors plan-task: the agent creates its own worktree + opens the PR,
      // so CoS must keep both off (and lock them).
      expect(cfg.taskMetadata.useWorktree).toBe(false)
      expect(cfg.taskMetadata.openPR).toBe(false)
      expect(cfg.taskMetadata.claimFlow).toBe(true)
      expect(MANAGED_AGENT_OPTIONS['claim-issue']).toEqual(['useWorktree', 'openPR', 'claimFlow'])
    })
  })

  describe('branch-reconcile defaults', () => {
    it('is the single hygiene task and defaults to a three-branch coordinator batch', () => {
      expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('branch-reconcile')
      expect(SELF_IMPROVEMENT_TASK_TYPES).not.toContain('branch-cleanup')
      expect(DEFAULT_TASK_INTERVALS['branch-reconcile'].taskMetadata.branchesPerAgent).toBe(3)
      expect(DEFAULT_TASK_INTERVALS['do-replan'].runAfter).toContain('branch-reconcile')
    })
  })

  describe('ux defaults (#3273)', () => {
    it('is registered as a self-improvement task type with a description', () => {
      expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('ux')
      expect(TASK_TYPE_DESCRIPTIONS['ux']).toBe('UX/design audit — file issues (default) or implement fixes')
    })

    it('defaults to on-demand + enabled with file-issues on (worktree/PR off)', () => {
      const cfg = DEFAULT_TASK_INTERVALS['ux']
      expect(cfg.type).toBe(INTERVAL_TYPES.ON_DEMAND)
      // Manual Run is explicit consent; choosing a cadence opts into scheduling.
      expect(cfg.enabled).toBe(true)
      expect(cfg.taskMetadata.fileIssues).toBe(true)
      expect(cfg.taskMetadata.useWorktree).toBe(false)
      expect(cfg.taskMetadata.openPR).toBe(false)
      // File-issues posture is enforced at dispatch, not via a static lock, so
      // the user can flip fileIssues off and implement.
      expect(MANAGED_AGENT_OPTIONS['ux']).toBeUndefined()
      expect(cfg.taskMetadata.readOnly).toBe(false)
    })

    it('ships a prompt that files findings to the tracker and honors the injected mode', async () => {
      const prompt = await getTaskPrompt('ux')
      // The tracker block is injected at dispatch, so the token must survive here.
      expect(prompt).toContain('{trackerInstructions}')
      expect(prompt).toContain('short, human-readable title')
      expect(prompt).not.toContain('[ux-…]')
      // Read-only-on-source is carried by the injected mode banner, not restated
      // in the body. ux is a file-issues-CAPABLE audit that merely DEFAULTS to
      // filing, so a body that hardcoded "no branches, no PRs" contradicted the
      // do-work banner the catalog prepends when the user flips the toggle.
      // Pin the seam instead of the sentence, and assert the contract it
      // resolves to actually forbids the edits.
      expect(prompt).toContain('{modeInstructions}')
      expect(prompt).not.toMatch(/do NOT (edit|create branches)/)
      expect(modeContractFor(true)).toContain('deliverable is tracker items, not code')
      expect(modeContractFor(true)).toContain('open a PR, create a branch')
      // Named checklist, not vibes.
      expect(prompt).toContain('above the fold')
      expect(prompt).toContain('1440x900')
      expect(prompt).toContain('375x812')
      // Explicitly defers to the sibling task types it would otherwise duplicate.
      expect(prompt).toContain('ui-bugs')
      expect(prompt).toContain('mobile-responsive')
      expect(prompt).toContain('accessibility')
    })
  })

  describe('media-render-research defaults', () => {
    it('is an on-demand tracker-filing research task that files labelled media issues', async () => {
      expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('media-render-research')
      expect(DEFAULT_TASK_INTERVALS['media-render-research']).toMatchObject({
        type: INTERVAL_TYPES.ON_DEMAND,
        enabled: true,
        taskMetadata: { useWorktree: false, openPR: false, readOnly: false },
      })
      const { resolveTrackerFilingBlock } = await import('../lib/workTracker.js')
      const block = await resolveTrackerFilingBlock({ repoPath: '/tmp/example-repo', workTracker: 'github' }, 'media-render-research')
      expect(block.trackerInstructions).toContain('--label media-research --label area:media --label plan')
    })
  })

  describe('plan-feature defaults', () => {
    it('is registered as a self-improvement task type with a description', () => {
      expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('plan-feature')
      expect(TASK_TYPE_DESCRIPTIONS['plan-feature']).toBeTruthy()
    })

    it('defaults to on-demand + enabled, grounded on do-replan, with no worktree/PR', () => {
      const cfg = DEFAULT_TASK_INTERVALS['plan-feature']
      expect(cfg.type).toBe(INTERVAL_TYPES.ON_DEMAND)
      // Manual Run is explicit consent; choosing a cadence opts into scheduling.
      expect(cfg.enabled).toBe(true)
      // Refresh the configured work tracker before filing a new proposal.
      expect(cfg.runAfter).toEqual(['do-replan'])
      expect(cfg.dataInputs).toEqual([
        'product-requirements',
        'project-goals',
        'open-issues',
        'open-pull-requests',
        'closed-unmerged-pull-requests',
      ])
      expect(cfg.taskMetadata.useWorktree).toBe(false)
      expect(cfg.taskMetadata.openPR).toBe(false)
      // Writable: a file-based tracker path commits checklist items.
      expect(cfg.taskMetadata.readOnly).toBe(false)
      // Filing posture comes from TRACKER_FILING_PRESETS membership at dispatch,
      // not a static lock.
      expect(MANAGED_AGENT_OPTIONS['plan-feature']).toBeUndefined()
    })

    it('always files its plan via the tracker-filing machinery', async () => {
      const { resolveTrackerFilingBlock } = await import('../lib/workTracker.js')
      const app = { repoPath: '/tmp/example-repo', workTracker: 'github' }
      const block = await resolveTrackerFilingBlock(app, 'plan-feature')
      expect(block.workTracker).toBe('github')
      expect(block.trackerInstructions).toContain('The issue number is its ID')
      expect(block.trackerInstructions).not.toContain('ID beginning with `plan-feature-`')
    })

    it('ships a prompt that plans without implementing', async () => {
      const prompt = await getTaskPrompt('plan-feature')
      expect(prompt).toContain('{appName}')
      expect(prompt).toContain('{repoPath}')
      // The tracker block is injected at dispatch, so the token must survive here.
      expect(prompt).toContain('{trackerInstructions}')
      // Product intent is specific-first, with repository documentation as the
      // fallback when a project has neither a PRD nor goals document.
      expect(prompt).toContain('PRD.md')
      expect(prompt).toContain('GOALS.md')
      expect(prompt).toContain('README.md')
      expect(prompt).toContain('docs/README.md')
      expect(prompt).not.toContain('PLAN.md')
      expect(prompt).not.toContain('REJECTED.md')
      expect(prompt).toContain('Closed unmerged pull requests')
      // Never implements — the plan IS the deliverable.
      expect(prompt).toContain('no branches, no PRs')
      expect(prompt).toContain('Acceptance criteria')
      expect(prompt).toContain('Non-goals')
    })
  })

  describe('audit file-issues types', () => {
    // Every file-issues-by-default lane, in ONE table: the posture is a single
    // product decision ("an unattended scheduled run must not land code"), so
    // asserting it in two places 20 lines apart just means a future flag gets
    // added to one of them. Every audit includes open issues; some also preload
    // PRs to dedup against work in flight without spending forge calls. Every
    // audit also preloads its recent slices so runs rotate coverage (#12090)
    // and its lane health so it does not re-file a rejected finding (#12088).
    const OPEN_ISSUES_ONLY = ['open-issues', 'audit-slice-history', 'lane-health']
    const DEDUP_PRELOAD = ['open-issues', 'open-pull-requests', 'audit-slice-history', 'lane-health']
    const FILE_ISSUES_LANES = [
      ['data-safety', OPEN_ISSUES_ONLY],
      ['simplify', OPEN_ISSUES_ONLY],
      ['ui-lifecycle', OPEN_ISSUES_ONLY],
      ['module-hygiene', DEDUP_PRELOAD],
      ['upgrade-rehearsal', DEDUP_PRELOAD],
      // Derived, so a seventh better-* lane cannot be added without landing here.
      ...[...AUDIT_TASK_TYPES]
        .filter((taskType) => taskType.startsWith('better-'))
        .map((taskType) => [taskType, DEDUP_PRELOAD]),
    ]

    it('covers every better-* lane, derived from the catalog rather than hand-listed', () => {
      const lanes = FILE_ISSUES_LANES.map(([taskType]) => taskType).filter((t) => t.startsWith('better-'))
      expect(lanes).toEqual([
        'better-complexity',
        'better-cognitive-load',
        'better-structural-drift',
        'better-runtime-safety',
        'better-dependency-freedom',
        'better-test-quality',
        'better-dev-environment',
      ])
    })

    it('ships open issues, the slice rotation record and lane health for every scheduled quality audit', () => {
      for (const taskType of AUDIT_TASK_TYPES) {
        expect(DEFAULT_TASK_INTERVALS[taskType]?.dataInputs, taskType).toContain('open-issues')
        expect(DEFAULT_TASK_INTERVALS[taskType]?.dataInputs, taskType).toContain('audit-slice-history')
        expect(DEFAULT_TASK_INTERVALS[taskType]?.dataInputs, taskType).toContain('lane-health')
      }
    })

    it.each(FILE_ISSUES_LANES)('registers %s as an enabled on-demand file-issues audit', (taskType, dataInputs) => {
      expect(SELF_IMPROVEMENT_TASK_TYPES).toContain(taskType)
      expect(TASK_TYPE_DESCRIPTIONS[taskType]).toBeTruthy()
      expect(DEFAULT_TASK_PROMPTS[taskType]).toBeTruthy()
      const cfg = DEFAULT_TASK_INTERVALS[taskType]
      expect(cfg.type).toBe(INTERVAL_TYPES.ON_DEMAND)
      expect(cfg.enabled).toBe(true)
      expect(cfg.taskMetadata.fileIssues).toBe(true)
      expect(cfg.taskMetadata.useWorktree).toBe(false)
      expect(cfg.taskMetadata.openPR).toBe(false)
      expect(cfg.dataInputs).toEqual(dataInputs)
      // The file-issues posture is enforced at dispatch, so the user can still
      // flip the toggle and implement.
      expect(MANAGED_AGENT_OPTIONS[taskType]).toBeUndefined()
    })

    it('requires worktree isolation for the lanes whose remediation restructures code', () => {
      const isolated = [...AUDIT_TASK_TYPES]
        .filter((t) => t.startsWith('better-') && auditDoWorkRequiresWorktree(t))
      expect(isolated).toEqual([
        'better-complexity',
        'better-cognitive-load',
        'better-structural-drift',
        'better-dependency-freedom',
      ])
    })

    it('surfaces fileIssuesCapable on audit types in getScheduleStatus', async () => {
      mockSchedule()
      const status = await getScheduleStatus()
      expect(status.tasks['security'].fileIssuesCapable).toBe(true)
      expect(status.tasks['security'].defaultFileIssues).toBe(false)
      expect(status.tasks['ux'].fileIssuesCapable).toBe(true)
      expect(status.tasks['ux'].defaultFileIssues).toBe(true)
      expect(status.tasks['data-safety'].fileIssuesCapable).toBe(true)
      expect(status.tasks['module-hygiene'].fileIssuesCapable).toBe(true)
      expect(status.tasks['module-hygiene'].defaultFileIssues).toBe(true)
      expect(status.tasks['module-hygiene'].doWorkRequiresWorktree).toBe(true)
      expect(status.tasks['simplify'].doWorkRequiresWorktree).toBeUndefined()
      expect(status.tasks['claim-issue'].fileIssuesCapable).toBeUndefined()
    })

    // A per-app provider/model pin outranks the task's own pin at spawn for EVERY
    // task type (#4783). The Schedule page needs to show what each app pinned, on
    // every row, or it advertises a provider the run never used. The retired
    // `providerOverrideCapable` stamp must not come back — it existed only while
    // the generic spawn path declined to read the pin.
    it('carries each app\'s provider/model pin into appOverrides, with no capability stamp', async () => {
      mockSchedule()
      const apps = await import('./apps.js')
      apps.getActiveApps.mockResolvedValueOnce([{ id: 'app-1', name: 'Acme' }])
      apps.getAppTaskTypeOverrides.mockResolvedValue({
        'layered-intelligence': { enabled: true, providerId: 'claude-ollama-tui', model: 'qwen-b' },
        security: { enabled: true }
      })
      const status = await getScheduleStatus()
      expect(status.tasks['layered-intelligence'].appOverrides['app-1']).toMatchObject({
        providerId: 'claude-ollama-tui',
        model: 'qwen-b'
      })
      // A non-LI type surfaces the SAME pin — the capability flag is gone.
      expect(status.tasks['layered-intelligence']).not.toHaveProperty('providerOverrideCapable')
      expect(status.tasks['security']).not.toHaveProperty('providerOverrideCapable')
      // An app that pinned nothing carries no provider keys at all — absent must
      // stay distinguishable from "explicitly pinned".
      expect(status.tasks['security'].appOverrides['app-1']).not.toHaveProperty('providerId')
      apps.getAppTaskTypeOverrides.mockResolvedValue({})
    })
  })

  describe('resetExecutionHistory', () => {
    it('should reset global execution history', async () => {
      mockSchedule({
        executions: { 'task:reset-test': { lastRun: '2025-01-01T00:00:00Z', count: 5, perApp: {} } }
      })
      const result = await resetExecutionHistory('reset-test')
      expect(result.success).toBe(true)
    })

    it('should reset per-app execution history', async () => {
      mockSchedule({
        executions: {
          'task:reset-app-test': {
            lastRun: '2025-01-01T00:00:00Z', count: 3,
            perApp: { 'app-1': { lastRun: '2025-01-01T00:00:00Z', count: 2 } }
          }
        }
      })
      const result = await resetExecutionHistory('reset-app-test', 'app-1')
      expect(result.success).toBe(true)
    })
  })

  describe('triggerOnDemandTask', () => {
    beforeEach(() => {
      loadState.mockResolvedValue({ config: { improvementEnabled: true } })
    })

    describe('inputs-unchanged gate (#12907)', () => {
      const HEAD = 'a'.repeat(40)
      const gated = (lastCleanHead) => mockSchedule({
        tasks: { 'upgrade-rehearsal': { type: 'on-demand', enabled: true } },
        executions: { 'task:upgrade-rehearsal': { perApp: { 'app-1': { lastRun: null, count: 0, ...(lastCleanHead ? { lastCleanHead } : {}) } } } }
      })
      beforeEach(() => {
        getAppById.mockResolvedValue({ id: 'app-1', repoPath: '/repo' })
        isTaskTypeEnabledForApp.mockResolvedValue(true)
        inputsUnchangedSince.mockReset().mockResolvedValue(true)
      })

      it('declines unattended launches while no declared input changed since the clean baseline, but never a user Run', async () => {
        gated(HEAD)
        const refill = await triggerOnDemandTask('upgrade-rehearsal', 'app-1', { origin: ON_DEMAND_ORIGINS.REFILL })
        expect(refill).toMatchObject({ reason: 'inputs-unchanged' })
        expect(inputsUnchangedSince).toHaveBeenCalledWith(expect.objectContaining({ repoPath: '/repo', lastCleanHead: HEAD }))
        expect(await triggerOnDemandTask('upgrade-rehearsal', 'app-1')).toMatchObject({ taskType: 'upgrade-rehearsal', origin: ON_DEMAND_ORIGINS.USER })
      })

      it('launches when an input changed or no clean baseline exists', async () => {
        gated(HEAD)
        inputsUnchangedSince.mockResolvedValue(false)
        expect(await triggerOnDemandTask('upgrade-rehearsal', 'app-1', { origin: ON_DEMAND_ORIGINS.REFILL })).toMatchObject({ taskType: 'upgrade-rehearsal' })
        gated(null)
        inputsUnchangedSince.mockClear()
        expect(await triggerOnDemandTask('upgrade-rehearsal', 'app-1', { origin: ON_DEMAND_ORIGINS.REFILL })).toMatchObject({ taskType: 'upgrade-rehearsal' })
        expect(inputsUnchangedSince).not.toHaveBeenCalled()
      })

      it('reports inputs-unchanged from readiness instead of a due cron slot', async () => {
        mockSchedule({
          tasks: { 'upgrade-rehearsal': { type: 'cron', enabled: true, cronExpression: '* * * * *' } },
          executions: { 'task:upgrade-rehearsal': { perApp: { 'app-1': { lastRun: null, count: 0, lastCleanHead: HEAD } } } }
        })
        parseCronToNextRun.mockReturnValue(new Date(Date.now() - 1000))
        expect(await shouldRunTask('upgrade-rehearsal', 'app-1')).toMatchObject({ shouldRun: false, reason: 'inputs-unchanged' })
        inputsUnchangedSince.mockResolvedValue(false)
        expect(await shouldRunTask('upgrade-rehearsal', 'app-1')).toMatchObject({ shouldRun: true, reason: 'cron-due' })
      })
    })

    it('keeps model research global for both scheduled and manual dispatch', async () => {
      mockSchedule({ tasks: { 'model-comparison-refresh': { type: INTERVAL_TYPES.CRON, cronExpression: '* * * * *', enabled: true } } })
      parseCronToNextRun.mockReturnValue(new Date(Date.now() - 1000))

      expect(await shouldRunTask('model-comparison-refresh', 'app-1')).toMatchObject({ shouldRun: false, reason: 'requires-install-wide-target' })
      expect((await triggerOnDemandTask('model-comparison-refresh', 'app-1')).error).toMatch(/requires an install-wide target/i)
      expect((await getOnDemandRequests()).filter(r => r.taskType === 'model-comparison-refresh')).toHaveLength(0)
      expect((await shouldRunTask('model-comparison-refresh')).shouldRun).toBe(true)
      expect(await triggerOnDemandTask('model-comparison-refresh')).toMatchObject({ taskType: 'model-comparison-refresh', appId: null })
    })

    it('should reject and not persist when master Improve is disabled', async () => {
      mockSchedule({
        tasks: { 'feature-ideas': { type: 'weekly', enabled: true } }
      })
      loadState.mockResolvedValue({ config: { improvementEnabled: false } })

      const result = await triggerOnDemandTask('feature-ideas', 'critical-mass')

      expect(result.error).toMatch(/improvement is disabled/i)
      // Read schedule back: no on-demand request should have been written.
      const schedule = await loadSchedule()
      expect(schedule.onDemandRequests || []).toHaveLength(0)
    })

    it('rejects automated refills when the task type is disabled before reading state', async () => {
      mockSchedule({
        tasks: { 'feature-ideas': { type: 'weekly', enabled: false } }
      })

      const result = await triggerOnDemandTask('feature-ideas', 'app-1', { origin: ON_DEMAND_ORIGINS.REFILL })

      expect(result.error).toMatch(/'feature-ideas' is disabled/i)
      // loadState should not have been called — task-type check short-circuits before loadState.
      expect(loadState).not.toHaveBeenCalled()
    })

    it('rejects a manual run when the task feature is disabled', async () => {
      isInstanceFeatureEnabled.mockResolvedValue(false)
      mockSchedule({ tasks: { 'jira-sprint-manager': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true } } })

      const result = await triggerOnDemandTask('jira-sprint-manager', 'app-1')

      expect(result.error).toMatch(/requires the 'jira' feature/i)
      expect(loadState).not.toHaveBeenCalled()
    })

    it('does not dispatch a queued request after its task feature is disabled', async () => {
      isInstanceFeatureEnabled.mockResolvedValue(false)
      mockSchedule({
        tasks: { 'jira-sprint-manager': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true } },
        onDemandRequests: [{ id: 'demand-existing', taskType: 'jira-sprint-manager', appId: 'app-1' }],
      })

      expect(await getOnDemandRequests()).toEqual([])
    })

    it('should accept a manual run for an enabled on-demand task', async () => {
      mockSchedule({
        tasks: { 'security': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true } }
      })

      const result = await triggerOnDemandTask('security', 'app-1')

      expect(result.error).toBeUndefined()
      expect(result.taskType).toBe('security')
      expect(result.appId).toBe('app-1')
      expect(result.origin).toBe(ON_DEMAND_ORIGINS.USER)
    })

    it('rejects an app-required task without a managed app target', async () => {
      mockSchedule({
        tasks: { 'pr-reviewer': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true } }
      })

      const result = await triggerOnDemandTask('pr-reviewer')

      expect(result.error).toMatch(/requires a managed app target/i)
      expect(recordUserAction).not.toHaveBeenCalled()
      expect((await getOnDemandRequests()).filter(r => r.taskType === 'pr-reviewer')).toHaveLength(0)
    })

    it('carries a targeted PR number onto the queued request', async () => {
      mockSchedule({
        tasks: { 'pr-reviewer': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true } }
      })

      const result = await triggerOnDemandTask('pr-reviewer', 'app-1', { targetPullRequest: 17 })

      expect(result.error).toBeUndefined()
      expect(result.targetPullRequest).toBe(17)
      const queued = (await getOnDemandRequests()).find(r => r.id === result.id)
      expect(queued.targetPullRequest).toBe(17)
    })

    it('drops a non-positive-integer PR target rather than queueing an unusable filter', async () => {
      mockSchedule({
        tasks: { 'pr-reviewer': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true } }
      })

      const result = await triggerOnDemandTask('pr-reviewer', 'app-1', { targetPullRequest: 'all' })

      expect(result.error).toBeUndefined()
      expect('targetPullRequest' in result).toBe(false)
    })

    it('should reject unknown task types instead of silently queuing them', async () => {
      mockSchedule({
        tasks: { 'feature-ideas': { type: 'weekly', enabled: true } }
      })

      const result = await triggerOnDemandTask('not-a-real-type', 'critical-mass')

      expect(result.error).toMatch(/unknown task type 'not-a-real-type'/i)
      expect(loadState).not.toHaveBeenCalled()
    })

    it('should fall back to legacy split flags when improvementEnabled is undefined', async () => {
      mockSchedule({
        tasks: { 'feature-ideas': { type: 'weekly', enabled: true } }
      })
      loadState.mockResolvedValue({
        config: { selfImprovementEnabled: false, appImprovementEnabled: false }
      })

      const result = await triggerOnDemandTask('feature-ideas', 'critical-mass')

      expect(result.error).toMatch(/improvement is disabled/i)
    })

    it('should persist the request and emit event when improvement is enabled', async () => {
      mockSchedule({
        tasks: { 'feature-ideas': { type: 'weekly', enabled: true } }
      })

      const result = await triggerOnDemandTask('feature-ideas', 'critical-mass')

      expect(result.error).toBeUndefined()
      expect(result.taskType).toBe('feature-ideas')
      expect(result.appId).toBe('critical-mass')
      expect(result.id).toMatch(/^demand-/)
    })

    it('allocates distinct receipt IDs for mixed task types within one clock tick', async () => {
      vi.useFakeTimers()
      vi.setSystemTime(new Date('2026-01-02T03:04:05.000Z'))
      mockSchedule({ tasks: {
        security: { type: INTERVAL_TYPES.ON_DEMAND, enabled: true },
        'universe-bible-describe': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true },
      } })

      const agentRequest = await triggerOnDemandTask('security', null, { emit: false })
      const programmaticRequest = await triggerOnDemandTask('universe-bible-describe', null, { emit: false })

      expect(agentRequest.id).toMatch(/^demand-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)
      expect(programmaticRequest.id).toMatch(/^demand-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)
      expect(agentRequest.id).not.toBe(programmaticRequest.id)
      expect(agentRequest.requestedAt).toBe('2026-01-02T03:04:05.000Z')
      expect(programmaticRequest.requestedAt).toBe(agentRequest.requestedAt)
    })

    it('keeps legacy timestamp receipt IDs cancellable', async () => {
      const legacyRequest = {
        id: 'demand-m5d4ruo0', taskType: 'security', appId: null,
        origin: ON_DEMAND_ORIGINS.USER, requestedAt: '2024-01-01T00:00:00.000Z',
      }
      mockSchedule({ onDemandRequests: [legacyRequest] })

      await expect(clearOnDemandRequest(legacyRequest.id)).resolves.toEqual(legacyRequest)

      const persisted = JSON.parse(writeFile.mock.calls.at(-1)[1])
      expect(persisted.onDemandRequests).toEqual([])
    })

    // The drain's completion refill re-issues itself through this same queue. It
    // must be distinguishable from a human "Run", because the engines clear the
    // park + convergence signature + dispatch counter for a human and MUST NOT for
    // a refill — that reset is what let branch-reconcile re-dispatch all night.
    it('stamps origin: user by default and refill when the drain re-issues itself', async () => {
      mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true } } })
      expect((await triggerOnDemandTask('branch-reconcile', 'app-1')).origin).toBe(ON_DEMAND_ORIGINS.USER)

      mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true } } })
      const refill = await triggerOnDemandTask('branch-reconcile', 'app-1', { emit: false, origin: ON_DEMAND_ORIGINS.REFILL })
      expect(refill.origin).toBe(ON_DEMAND_ORIGINS.REFILL)
    })

    it('queues a perpetual refill with its non-emitting automated origin', async () => {
      mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true } } })

      const refill = await queuePerpetualRefill('branch-reconcile', 'app-1')

      expect(refill).toMatchObject({
        taskType: 'branch-reconcile',
        appId: 'app-1',
        origin: ON_DEMAND_ORIGINS.REFILL,
      })
      expect(cosEvents.emit).not.toHaveBeenCalled()
      expect(recordUserAction).not.toHaveBeenCalled()
    })

    // Operator-action ledger (#5594). Only a human pressing Run Now is an
    // operator action; the perpetual drain re-issues itself through this same
    // lane, and logging that would fill the ledger with events nobody performed.
    it('records a cos.schedule.trigger row for a human Run Now, and none for a refill', async () => {
      mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true } } })
      const request = await triggerOnDemandTask('branch-reconcile', 'app-1')

      expect(recordUserAction).toHaveBeenCalledTimes(1)
      expect(recordUserAction).toHaveBeenCalledWith(expect.objectContaining({
        type: 'cos.schedule.trigger',
        target: 'branch-reconcile',
        targetName: 'app-1',
        dedupeKey: `cos.schedule.trigger:${request.id}`,
        payload: { taskType: 'branch-reconcile', appId: 'app-1', requestId: request.id },
      }))
      // actor defaults to 'user' in the recorder; the hook must not override it.
      expect(recordUserAction.mock.calls[0][0].actor).toBeUndefined()

      recordUserAction.mockClear()
      mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true } } })
      await triggerOnDemandTask('branch-reconcile', 'app-1', { emit: false, origin: ON_DEMAND_ORIGINS.REFILL })
      expect(recordUserAction).not.toHaveBeenCalled()
    })

    it('records nothing when the trigger is refused', async () => {
      mockSchedule({ tasks: {} })
      expect((await triggerOnDemandTask('unknown-task', 'app-1')).error).toMatch(/unknown/i)
      expect(recordUserAction).not.toHaveBeenCalled()
    })

    // The policy that used to be open-coded in each spawn engine — which is how the
    // loop got in. One home, so the three queue consumers can't drift on it.
    describe('applyOnDemandRunResets', () => {
      const parked = (extra = {}) => ({
        tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true } },
        executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: {
          'app-1': {
            lastRun: null, count: 0,
            parkedUntil: new Date(Date.now() + 3600000).toISOString(), parkReason: 'no-progress',
            lastActionableSignature: 'a:NEEDS_PR:none', perpetualDispatchCount: 3,
            ...extra
          }
        } } }
      })

      it('clears the drain state for a human "Run" and reports it as user-initiated', async () => {
        mockSchedule(parked())
        expect(await applyOnDemandRunResets({ taskType: 'branch-reconcile', origin: ON_DEMAND_ORIGINS.USER }, 'app-1')).toBe(true)
        const rec = JSON.parse(writeFile.mock.calls.at(-1)[1]).executions['task:branch-reconcile'].perApp['app-1']
        expect(rec.parkedUntil).toBeUndefined()
        expect(rec.lastActionableSignature).toBeUndefined()
        expect(rec.perpetualDispatchCount).toBeUndefined()
      })

      it('clears NOTHING for an automated drain refill — the brakes must survive the hop', async () => {
        mockSchedule(parked())
        expect(await applyOnDemandRunResets({ taskType: 'branch-reconcile', origin: ON_DEMAND_ORIGINS.REFILL }, 'app-1')).toBe(false)
        expect(writeFile).not.toHaveBeenCalled()
      })

      it('clears NOTHING for a quota burn either — it is automation, not a human Run', async () => {
        // A burn that cleared the park would re-run a converged drain every time
        // its window opened, which is the opposite of "invoke this once".
        mockSchedule(parked())
        expect(await applyOnDemandRunResets({ taskType: 'branch-reconcile', origin: ON_DEMAND_ORIGINS.QUOTA_BURN }, 'app-1')).toBe(false)
        expect(writeFile).not.toHaveBeenCalled()
      })

      it('treats a pre-origin request as user-initiated (safe default for a human-filled queue)', async () => {
        mockSchedule(parked())
        expect(await applyOnDemandRunResets({ taskType: 'branch-reconcile' }, 'app-1')).toBe(true)
      })
    })

    // A quota burn asks the schedule to run a task the user already owns. The
    // request has to carry enough to attribute the burn later — acceptance is
    // asynchronous, so nothing else can reconstruct it — and it must face the
    // same invocation-eligibility gate a human Run does.
    describe('quota-burn origin', () => {
      // `overrides.params` rides along because a migrated issues-only step pins
      // `fileIssues` there, and the generator has to see it BEFORE it renders the
      // prompt (#6381).
      const burn = { family: 'grok', stepId: 'step-1', limitingResetAt: 1700000000000, overrides: { providerId: 'grok-tui', model: null, effort: null, params: { fileIssues: true } } }
      const trigger = (options) => triggerOnDemandTask('security', null, { emit: false, origin: ON_DEMAND_ORIGINS.QUOTA_BURN, ...options })

      it('persists the burn provenance on the queued request', async () => {
        mockSchedule({ tasks: { security: { type: 'on-demand', enabled: true } } })
        const request = await trigger({ burn })
        expect(request.origin).toBe(ON_DEMAND_ORIGINS.QUOTA_BURN)
        expect(request.burn).toEqual(burn)
        // And it survives the write, so an engine draining it after a restart
        // still knows which family and step to credit.
        const written = JSON.parse(writeFile.mock.calls.at(-1)[1]).onDemandRequests.at(-1)
        expect(written.burn).toEqual(burn)
      })

      it('refuses a burn request that cannot be attributed, before touching the schedule', async () => {
        mockSchedule({ tasks: { security: { type: 'on-demand', enabled: true } } })
        expect((await trigger({ burn: { family: 'grok' } })).error).toMatch(/must name the burning family and its burn step/)
        expect(writeFile).not.toHaveBeenCalled()
      })

      it('is not written to the operator-action ledger', async () => {
        mockSchedule({ tasks: { security: { type: 'on-demand', enabled: true } } })
        await trigger({ burn })
        expect(recordUserAction).not.toHaveBeenCalled()
      })

      it('faces the same gates a human Run does', async () => {
        mockSchedule({ tasks: { security: { type: 'on-demand', enabled: false } } })
        expect((await trigger({ burn })).error).toMatch(/disabled/i)
        mockSchedule({ tasks: { security: { type: 'on-demand', enabled: true } } })
        expect((await triggerOnDemandTask('not-a-task', null, { emit: false, origin: ON_DEMAND_ORIGINS.QUOTA_BURN, burn })).error)
          .toMatch(/Unknown task type/)
      })

      // The invocation-eligibility gate is the one that cannot be exercised
      // behaviorally: `TASK_TYPE_INVOCATION` is deliberately empty today, so no
      // shipped type is subsidiary and there is nothing to refuse. The rule still
      // has to hold the day one is added, and the failure mode is silent — an
      // unattended burn commandeering a task another automation owns — so the
      // shape is pinned here. Only REFILL (that automation re-issuing itself) is
      // exempt; a burn is gated exactly like a human Run.
      it('exempts only a drain refill from the invocation-eligibility gate', async () => {
        // `fs` is doubled for this suite, so read through the real one.
        const { readFileSync } = await vi.importActual('node:fs')
        const src = readFileSync(new URL('./taskSchedule.js', import.meta.url), 'utf8')
        // The rung itself lives in `evaluateOnDemandEligibility`; what this file
        // still owns is which origins are exempt, so that is what is pinned.
        expect(src).toMatch(/eligible: origin === ON_DEMAND_ORIGINS\.REFILL \|\| getTaskTypeInvocation\(taskType\)\.userInvokable !== false/)
        // Probe: the previous, narrower gate must be gone, or the assertion above
        // could pass on a file that still only checks USER somewhere else.
        expect(src).not.toMatch(/origin === ON_DEMAND_ORIGINS\.USER && !invocation\.userInvokable/)
      })
    })

    it('isRefillRequest only matches an explicit refill origin', () => {
      expect(isRefillRequest({ origin: ON_DEMAND_ORIGINS.REFILL })).toBe(true)
      expect(isRefillRequest({ origin: ON_DEMAND_ORIGINS.USER })).toBe(false)
      // A request queued before `origin` existed reads as user-initiated — the safe
      // default for a queue that is otherwise human-filled.
      expect(isRefillRequest({ taskType: 'branch-reconcile' })).toBe(false)
      expect(isRefillRequest(null)).toBe(false)
    })
  })

  describe('getScheduleStatus', () => {
    it('keeps missing preservation obligations while marking their checkout unavailable only in the response', async () => {
      const row = { branch: 'fix/example', path: '/example/gone', head: 'abc', locked: false, reason: 'retirement-receipt-unverified' };
      const outcome = { status: 'incomplete', remaining: [row], retirementObligations: [row] };
      mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', enabled: true } }, executions: {
        'task:branch-reconcile': { perApp: { 'app-1': { branchReconcileOutcome: outcome } } },
      } });
      getAppById.mockResolvedValue({ id: 'app-1', repoPath: '/example' });
      findGoneInventoryRows.mockResolvedValueOnce([row]);
      const status = await getScheduleStatus();
      expect(status.tasks['branch-reconcile'].reconcileOutcomes['app-1']).toMatchObject({
        status: 'incomplete', remaining: [{ ...row, checkoutMissing: true }], retirementObligations: [row],
      });
      expect(await getBranchReconcileOutcome('app-1')).toEqual(outcome);
      findGoneInventoryRows.mockRejectedValueOnce(new Error('inventory unavailable'));
      const unknown = await getScheduleStatus();
      expect(unknown.tasks['branch-reconcile'].reconcileOutcomes['app-1'].remaining).toEqual([row]);
    });

    beforeEach(() => {
      loadState.mockResolvedValue({ config: { improvementEnabled: true } })
    })

    it('should include improvementEnabled: true when master flag is on', async () => {
      mockSchedule({ tasks: { 'security': { type: 'weekly', enabled: true } } })

      const status = await getScheduleStatus()

      expect(status.improvementEnabled).toBe(true)
    })

    it('should include improvementEnabled: false when master flag is off', async () => {
      mockSchedule({ tasks: { 'security': { type: 'weekly', enabled: true } } })
      loadState.mockResolvedValue({ config: { improvementEnabled: false } })

      const status = await getScheduleStatus()

      expect(status.improvementEnabled).toBe(false)
    })

    it('upgrades audit presentation without renaming stored schedule identities', async () => {
      mockSchedule({ tasks: { security: { type: 'on-demand', enabled: false, labels: ['backend'], description: 'Custom summary' } } })
      const status = await getScheduleStatus()
      expect(status.tasks.security).toMatchObject({ displayName: 'better-security', labels: ['backend'], description: 'Custom summary', enabled: false })
      expect(status.tasks.security.defaultLabels).toEqual(expect.arrayContaining(['slashdo', 'codebase-improvement', 'security']))
      expect(status.tasks['better-security']).toBeUndefined()
      // Ordering is carried by NAMED task types, not by the prose — the prose
      // only says why. A reader of the old guidance couldn't tell whether
      // "structural drift" was another scheduled task or just a concept.
      expect(status.tasks['module-hygiene'].suggestedAfter).toEqual(['simplify'])
      expect(status.tasks['better-complexity'].suggestedAfter).toEqual(['module-hygiene'])
      expect(status.tasks['module-hygiene'].runGuidance).toContain('module boundaries')
      expect(status.tasks['claim-issue']).toMatchObject({ displayName: 'claim-issue', defaultLabels: [] })
      expect(status.tasks['music-video-autopilot']).toMatchObject({ displayName: 'Autonomous run' })
    })

    it('projects task summaries and explains hook-owned prompts', async () => {
      mockSchedule()

      const status = await getScheduleStatus()

      expect(status.tasks['issue-watcher']).toMatchObject({
        description: TASK_TYPE_DESCRIPTIONS['issue-watcher'],
        promptMode: 'runtime-generated',
        promptDescription: expect.stringContaining('Three enforced server phases'),
        invocation: { kind: 'direct', visibility: 'visible', userInvokable: true },
      })
      expect(status.tasks.security).toMatchObject({
        description: TASK_TYPE_DESCRIPTIONS.security,
        promptMode: 'template',
        invocation: { kind: 'direct', visibility: 'visible', userInvokable: true },
      })
    })

    it('keeps subsidiary-task visibility explicit instead of inferring it from task names', () => {
      expect(Object.keys(TASK_TYPE_INVOCATION)).toEqual([])
      for (const taskType of SELF_IMPROVEMENT_TASK_TYPES) {
        expect(getTaskTypeInvocation(taskType), taskType).toEqual({
          kind: 'direct', visibility: 'visible', userInvokable: true
        })
      }
    })

    it('hides shipped tasks whose required instance feature is disabled', async () => {
      isInstanceFeatureEnabled.mockResolvedValue(false)
      mockSchedule({ tasks: { 'jira-sprint-manager': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true } } })

      const status = await getScheduleStatus()

      expect(status.tasks).not.toHaveProperty('jira-sprint-manager')
      expect(status.tasks).not.toHaveProperty('jira-status-report')
    })
  })

  describe('perpetual (drain-until-done)', () => {
    describe('computePerpetualRecheckAt', () => {
      it('uses recheckIntervalMs when no cron is set', async () => {
        const at = await computePerpetualRecheckAt({ recheckIntervalMs: 3600000 }, 0)
        expect(at).toBe(new Date(3600000).toISOString())
      })

      it('defaults to a daily (24h) recheck when nothing is configured', async () => {
        const at = await computePerpetualRecheckAt({}, 0)
        expect(at).toBe(new Date(24 * 60 * 60 * 1000).toISOString())
      })

      it('prefers a 5-field recheckCron over the interval', async () => {
        const cronNext = new Date('2999-01-02T09:00:00.000Z')
        parseCronToNextRun.mockReturnValue(cronNext)
        const at = await computePerpetualRecheckAt({ recheckCron: '0 9 * * *', recheckIntervalMs: 1000 }, 0)
        expect(at).toBe(cronNext.toISOString())
        expect(parseCronToNextRun).toHaveBeenCalled()
      })

      it('falls back to the interval when recheckCron is not a 5-field expression', async () => {
        const at = await computePerpetualRecheckAt({ recheckCron: 'not-a-cron', recheckIntervalMs: 5000 }, 0)
        expect(at).toBe(new Date(5000).toISOString())
      })
    })

    describe('shouldRunTask', () => {
      it('is due (drain) when enabled and not parked', async () => {
        mockSchedule({ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } } })
        const result = await shouldRunTask('claim-issue')
        expect(result.shouldRun).toBe(true)
        expect(result.reason).toBe('perpetual-drain')
      })

      it('is NOT due while parked in the future', async () => {
        const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {}, parkedUntil: future, parkReason: 'no-actionable-issues', parkActionableCount: 0 } }
        })
        const result = await shouldRunTask('claim-issue')
        expect(result.shouldRun).toBe(false)
        expect(result.reason).toBe('perpetual-parked')
        expect(result.nextRunAt).toBe(future)
        expect(result.parkReason).toBe('no-actionable-issues')
      })

      it('becomes due again (recheck) once the park elapses', async () => {
        const past = new Date(Date.now() - 60 * 1000).toISOString()
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {}, parkedUntil: past } }
        })
        const result = await shouldRunTask('claim-issue')
        expect(result.shouldRun).toBe(true)
        expect(result.reason).toBe('perpetual-recheck')
      })

      it('reads per-app park state', async () => {
        isTaskTypeEnabledForApp.mockResolvedValue(true)
        const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, parkedUntil: future } } } }
        })
        const result = await shouldRunTask('claim-issue', 'app-1')
        expect(result.shouldRun).toBe(false)
        expect(result.reason).toBe('perpetual-parked')
      })
    })

    describe('shouldContinuePerpetualDrain', () => {
      it('only continues an explicitly started manual drain and never schedules its recheck', async () => {
        mockSchedule({ tasks: {
          ...PAUSED_SHIPPED_DRAINS,
          'claim-issue': { type: 'on-demand', perpetual: true, autoStart: false, enabled: true }
        } })
        expect(await shouldRunTask('claim-issue')).toMatchObject({ shouldRun: false, reason: 'on-demand-only' })
        expect(await shouldContinuePerpetualDrain('claim-issue')).toMatchObject({ shouldRun: true, reason: 'perpetual-drain' })
        expect(await getDueTasks()).not.toEqual(expect.arrayContaining([expect.objectContaining({ taskType: 'claim-issue' })]))
        expect(await getDueTasks(null, { continuingTaskType: 'claim-issue' })).toEqual(expect.arrayContaining([expect.objectContaining({ taskType: 'claim-issue' })]))
        await parkPerpetual('claim-issue', null, { reason: 'no-actionable-work', actionableCount: 0 })
        expect(await shouldContinuePerpetualDrain('claim-issue')).toMatchObject({ shouldRun: false, reason: 'perpetual-parked' })
        expect(await getUpcomingTasks()).not.toEqual(expect.arrayContaining([expect.objectContaining({ taskType: 'claim-issue' })]))
        vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 2 * 86400000)
        expect(await shouldRunTask('claim-issue')).toMatchObject({ shouldRun: false, reason: 'on-demand-only' })
        vi.restoreAllMocks()
      })

      it('does not force a non-perpetual task past its normal cadence', async () => {
        cronNotDueYet()
        mockSchedule({
          tasks: {
            ...PAUSED_SHIPPED_DRAINS,
            security: { type: 'cron', cronExpression: '0 7 * * *', enabled: true }
          }
        })

        expect(await shouldContinuePerpetualDrain('security'))
          .toMatchObject({ shouldRun: false, reason: 'cron-cooldown' })
      })

      it('keeps continuation behind feature and runAfter gates', async () => {
        cronNotDueYet()
        const featureEnabled = vi.fn().mockResolvedValue(false)
        mockSchedule({
          tasks: {
            // Feature ownership comes from the task registry, not stored overrides.
            'jira-sprint-manager': {
              type: 'cron', cronExpression: '0 7 * * *', perpetual: true,
              enabled: true
            }
          }
        })

        expect(await shouldContinuePerpetualDrain('jira-sprint-manager', null, { featureEnabled }))
          .toEqual({ shouldRun: false, reason: 'feature-disabled', feature: 'jira' })

        featureEnabled.mockResolvedValue(true)
        mockSchedule({
          tasks: {
            'claim-issue': {
              type: 'cron', cronExpression: '0 7 * * *', perpetual: true,
              enabled: true, runAfter: ['security']
            },
            security: { type: 'cron', cronExpression: '0 6 * * *', enabled: true }
          },
          executions: {
            'task:claim-issue': { lastRun: new Date().toISOString(), count: 1, perApp: {} },
            'task:security': { lastRun: null, count: 0, perApp: {} }
          }
        })
        expect(await shouldContinuePerpetualDrain('claim-issue', null, { featureEnabled }))
          .toEqual({ shouldRun: false, reason: 'waiting-on-dependencies', pendingDeps: ['security'] })
      })
    })

    describe('getNextTaskType', () => {
      it('picks a draining perpetual task when no cron task is due', async () => {
        cronNotDueYet()
        mockSchedule({
          tasks: {
            ...PAUSED_SHIPPED_DRAINS,
            'claim-issue': { type: 'on-demand', perpetual: true, enabled: true },
            'security': { type: 'cron', cronExpression: '0 7 * * *', enabled: true }
          }
        })
        const next = await getNextTaskType()
        expect(next.taskType).toBe('claim-issue')
        expect(next.reason).toBe('perpetual-drain')
      })

      it('does not pick a parked perpetual task — yields to the due cron task', async () => {
        cronDueNow()
        const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
        mockSchedule({
          tasks: {
            ...PAUSED_SHIPPED_DRAINS,
            'claim-issue': { type: 'on-demand', perpetual: true, enabled: true },
            'security': { type: 'cron', cronExpression: '0 7 * * *', enabled: true }
          },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {}, parkedUntil: future } }
        })
        const next = await getNextTaskType()
        expect(next.taskType).toBe('security')
      })

      it('a cron+perpetual task parks on its own expression and stays out of the pick', async () => {
        cronDueNow()
        const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
        mockSchedule({
          tasks: {
            ...PAUSED_SHIPPED_DRAINS,
            'claim-issue': { type: 'cron', cronExpression: '0 7 * * *', perpetual: true, enabled: true }
          },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {}, parkedUntil: future } }
        })
        // The cron slot is due, but the park outranks it — the drain is idle.
        expect(await shouldRunTask('claim-issue')).toMatchObject({ shouldRun: false, reason: 'perpetual-parked' })
        expect(await getNextTaskType()).toBeNull()
      })

      it('continues only the completed cron drain after its initiating slot is consumed', async () => {
        cronNotDueYet()
        mockSchedule({
          tasks: {
            ...PAUSED_SHIPPED_DRAINS,
            'claim-issue': { type: 'cron', cronExpression: '0 7 * * *', perpetual: true, enabled: true },
            security: { type: 'cron', cronExpression: '0 7 * * *', enabled: true }
          },
          executions: { 'task:claim-issue': { lastRun: new Date().toISOString(), count: 1, perApp: {} } }
        })
        expect(await shouldRunTask('claim-issue')).toMatchObject({ shouldRun: false, reason: 'cron-cooldown' })
        expect(await shouldContinuePerpetualDrain('claim-issue'))
          .toEqual({ shouldRun: true, reason: 'perpetual-drain' })
        expect(await getNextTaskType()).toBeNull()
        expect(await getNextTaskType(null, { continuingTaskType: 'security' })).toBeNull()
        expect(await getNextTaskType(null, { continuingTaskType: 'claim-issue', perpetualOnly: true }))
          .toEqual({ taskType: 'claim-issue', reason: 'perpetual-drain' })
      })

      it.each(['parkedUntil', 'failureParkedAt'])('keeps continuation behind %s', async (field) => {
        cronNotDueYet()
        mockSchedule({
          tasks: {
            ...PAUSED_SHIPPED_DRAINS,
            'claim-issue': { type: 'cron', cronExpression: '0 7 * * *', perpetual: true, enabled: true }
          },
          executions: { 'task:claim-issue': {
            lastRun: new Date().toISOString(), count: 1, perApp: {},
            [field]: new Date(Date.now() + 3600000).toISOString()
          } }
        })
        expect(await getNextTaskType(null, { continuingTaskType: 'claim-issue' })).toBeNull()
      })

      it('an ELAPSED park makes a cron+perpetual task due immediately, without waiting for the next slot', async () => {
        cronNotDueYet()
        const past = new Date(Date.now() - 60 * 1000).toISOString()
        mockSchedule({
          tasks: {
            ...PAUSED_SHIPPED_DRAINS,
            'claim-issue': { type: 'cron', cronExpression: '0 7 * * *', perpetual: true, enabled: true }
          },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {}, parkedUntil: past } }
        })
        expect(await shouldRunTask('claim-issue')).toMatchObject({ shouldRun: true, reason: 'perpetual-recheck' })
      })
    })

    // Perpetual tasks park PER-APP, so the global shouldRunTask always reads
    // 'perpetual-drain'. getUpcomingTasks must instead surface the per-app recheck
    // boundary as a 'scheduled' upcoming task — otherwise scheduleNextImprovementCheck
    // (which only shortens its wake-up for 'scheduled' tasks) never wakes the daemon
    // at the recheck cadence (e.g. a 9am recheckCron), and the parked drain resumes
    // only on the ≤1h fallback poll.
    describe('getUpcomingTasks — perpetual recheck boundary', () => {
      it('reports a perpetual task PARKED on every app as scheduled at the soonest recheck', async () => {
        // Clock frozen (#3693): this case compares two ABSOLUTE park timestamps,
        // so on a real clock its verdict depended on when the suite ran — the
        // next 9am is >30m out at 10am but only 15m out at 08:45, which flips
        // which park is soonest and fails the assertion below.
        vi.useFakeTimers()
        vi.setSystemTime(new Date('2026-01-01T12:00:00Z'))
        const nineAm = new Date('2026-01-02T09:00:00Z') // next 9am (future, well past `soon`)
        const soon = new Date(Date.now() + 30 * 60 * 1000).toISOString() // 30m out
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true, recheckCron: '0 9 * * *' } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0, parkedUntil: nineAm.toISOString() },
            'app-2': { lastRun: null, count: 0, parkedUntil: soon }
          } } }
        })
        const upcoming = await getUpcomingTasks(50)
        const claim = upcoming.find(t => t.taskType === 'claim-issue')
        expect(claim).toBeTruthy()
        expect(claim.status).toBe('scheduled')
        // Soonest of the two per-app parks (app-2, 30m out).
        expect(claim.eligibleAt).toBe(new Date(soon).getTime())
        expect(claim.eligibleIn).toBeGreaterThan(0)
      })

      it('reports the perpetual task ready when any app park has already elapsed', async () => {
        const past = new Date(Date.now() - 60 * 1000).toISOString()
        const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true, recheckCron: '0 9 * * *' } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0, parkedUntil: past },   // recheck due now
            'app-2': { lastRun: null, count: 0, parkedUntil: future }
          } } }
        })
        const upcoming = await getUpcomingTasks(50)
        const claim = upcoming.find(t => t.taskType === 'claim-issue')
        expect(claim.status).toBe('ready')
        expect(claim.eligibleIn).toBeLessThanOrEqual(0)
      })

      it('treats an app mid-drain (park cleared) as ready even if a sibling app is parked', async () => {
        const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0 },                      // no park → draining
            'app-2': { lastRun: null, count: 0, parkedUntil: future }
          } } }
        })
        const upcoming = await getUpcomingTasks(50)
        const claim = upcoming.find(t => t.taskType === 'claim-issue')
        expect(claim.status).toBe('ready')
      })

      it('keeps the global ready default for a never-run perpetual task (no per-app records)', async () => {
        mockSchedule({ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } } })
        const upcoming = await getUpcomingTasks(50)
        const claim = upcoming.find(t => t.taskType === 'claim-issue')
        expect(claim.status).toBe('ready')
      })
    })

    describe('getUpcomingTasks — per-app cron overrides', () => {
      it.each([false, true])('preserves a future deadline alongside a ready app (reverse=%s)', async (reverse) => {
        vi.useFakeTimers()
        vi.setSystemTime(new Date('2026-01-01T16:00:00Z'))
        const actual = await vi.importActual('./eventScheduler.js')
        const actualTimezone = await vi.importActual('../lib/timezone.js')
        parseCronToNextRun.mockImplementation(actual.parseCronToNextRun)
        getLocalParts.mockImplementation(actualTimezone.getLocalParts)
        const apps = [{ id: 'ready' }, { id: 'future' }]
        getActiveApps.mockResolvedValueOnce(reverse ? apps.reverse() : apps)
        const cron = id => id === 'ready' ? '0 8 * * *' : '5 8 * * *'
        for (const app of apps) {
          getAppTaskTypeInterval.mockResolvedValueOnce(cron(app.id))
          getAppTaskTypeOverrides.mockResolvedValueOnce({
            'do-release': { enabled: true, interval: cron(app.id) }
          })
        }
        mockSchedule({ tasks: { 'do-release': { type: 'on-demand', enabled: true, runAfter: [] } } })
        const upcoming = await getUpcomingTasks(50)
        expect(upcoming.find(t => t.taskType === 'do-release')).toMatchObject({
          status: 'ready', nextScheduledAt: new Date('2026-01-01T16:05:00Z').getTime()
        })
      })

      it('surfaces an enabled app cron boundary even when the global task is on-demand', async () => {
        vi.useFakeTimers()
        vi.setSystemTime(new Date('2026-01-01T16:00:00Z')) // 08:00 in the mocked America/Los_Angeles zone
        const actual = await vi.importActual('./eventScheduler.js')
        const actualTimezone = await vi.importActual('../lib/timezone.js')
        parseCronToNextRun.mockImplementation(actual.parseCronToNextRun)
        getLocalParts.mockImplementation(actualTimezone.getLocalParts)
        getActiveApps.mockResolvedValueOnce([{ id: 'app-1', name: 'Acme' }])
        isTaskTypeEnabledForApp.mockResolvedValueOnce(true)
        getAppTaskTypeInterval.mockResolvedValueOnce('15 9 * * *')
        getAppTaskTypeOverrides.mockResolvedValueOnce({
          'do-release': { enabled: true, interval: '15 9 * * *' }
        })
        mockSchedule({
          tasks: { 'do-release': { type: 'on-demand', enabled: true, runAfter: [] } }
        })
        const upcoming = await getUpcomingTasks(50)
        const release = upcoming.find(t => t.taskType === 'do-release')

        expect(release).toMatchObject({
          status: 'scheduled',
          eligibleAt: new Date('2026-01-01T17:15:00Z').getTime()
        })
      })
    })

    // #7527: a rejected app inventory/override/readiness read used to be
    // swallowed into [] / {} / null, which read as "no apps configured" or
    // "not ready" rather than "the calculation is unavailable" — hiding the
    // failure from cosJobScheduler.scheduleNextImprovementCheck (which then
    // armed its 1h fallback and could sleep through a cron minute). Assert
    // the rejection now propagates out of getUpcomingTasks instead.
    describe('getUpcomingTasks — propagates input failures instead of swallowing them (#7527)', () => {
      it('propagates a rejected active-apps read instead of treating it as no apps', async () => {
        getActiveApps.mockRejectedValueOnce(new Error('app inventory unavailable'))
        mockSchedule({ tasks: { 'do-release': { type: 'on-demand', enabled: true, runAfter: [] } } })
        await expect(getUpcomingTasks(50)).rejects.toThrow('app inventory unavailable')
      })

      it('propagates a rejected app-override read instead of treating it as no overrides', async () => {
        getActiveApps.mockResolvedValueOnce([{ id: 'app-1', name: 'Acme' }])
        getAppTaskTypeOverrides.mockRejectedValueOnce(new Error('app overrides unavailable'))
        mockSchedule({ tasks: { 'do-release': { type: 'on-demand', enabled: true, runAfter: [] } } })
        await expect(getUpcomingTasks(50)).rejects.toThrow('app overrides unavailable')
      })

      it('propagates a rejected per-app readiness read instead of treating the app as not-ready', async () => {
        getActiveApps.mockResolvedValueOnce([{ id: 'app-1', name: 'Acme' }])
        getAppTaskTypeOverrides.mockResolvedValueOnce({
          'do-release': { enabled: true, interval: '15 9 * * *' }
        })
        isTaskTypeEnabledForApp.mockRejectedValueOnce(new Error('app readiness unavailable'))
        mockSchedule({ tasks: { 'do-release': { type: 'on-demand', enabled: true, runAfter: [] } } })
        await expect(getUpcomingTasks(50)).rejects.toThrow('app readiness unavailable')
      })
    })

    describe('getScheduleStatus — appSchedules', () => {
      it('rejects an unavailable registry and recovers with a valid empty registry', async () => {
        mockSchedule({ tasks: { 'do-release': { type: 'on-demand', enabled: true, runAfter: [] } } })
        getActiveApps.mockRejectedValueOnce(new Error('app registry unavailable'))

        await expect(getScheduleStatus()).rejects.toThrow('app registry unavailable')

        getActiveApps.mockResolvedValue([])
        const task = (await getScheduleStatus()).tasks['do-release']
        expect(task).toMatchObject({ totalAppCount: 0, enabledAppCount: 0, appOverrides: {}, appSchedules: [] })
        expect(task.status).toMatchObject({ shouldRun: false, reason: 'on-demand-only' })
      })

      it('rejects unavailable app cadence instead of reporting a not-due row, then recovers', async () => {
        await withRealCron()
        getActiveApps.mockResolvedValue([{ id: 'app-1', name: 'Example App' }])
        getAppTaskTypeOverrides.mockResolvedValue({ 'do-release': { enabled: true, interval: '15 9 * * *' } })
        getAppTaskTypeInterval.mockRejectedValueOnce(new Error('app cadence unavailable'))
        mockSchedule({ tasks: { 'do-release': { type: 'on-demand', enabled: true, runAfter: [] } } })

        await expect(getScheduleStatus()).rejects.toThrow('app cadence unavailable')

        getAppTaskTypeInterval.mockResolvedValue('15 9 * * *')
        expect((await getScheduleStatus()).tasks['do-release'].appSchedules).toEqual([
          expect.objectContaining({ appId: 'app-1', nextRunAt: '2026-01-01T17:15:00.000Z', reason: 'cron-cooldown' })
        ])
      })

      // vi.clearAllMocks() keeps a mockResolvedValue, so these cases restore the
      // apps.js factory defaults rather than leaking an app roster into the
      // suites that follow.
      afterEach(() => {
        vi.useRealTimers()
        isTaskTypeEnabledForApp.mockResolvedValue(true)
        getAppTaskTypeInterval.mockResolvedValue(null)
        getActiveApps.mockResolvedValue([])
        getAppTaskTypeOverrides.mockResolvedValue({})
      })

      const withRealCron = async () => {
        vi.useFakeTimers()
        vi.setSystemTime(new Date('2026-01-01T16:00:00Z')) // 08:00 in the mocked America/Los_Angeles zone
        const actual = await vi.importActual('./eventScheduler.js')
        const actualTimezone = await vi.importActual('../lib/timezone.js')
        parseCronToNextRun.mockImplementation(actual.parseCronToNextRun)
        getLocalParts.mockImplementation(actualTimezone.getLocalParts)
      }

      // The reported bug: a task left on-demand globally while one app puts it
      // on a cron read as "manual trigger only" everywhere, and the Schedule
      // Timeline dropped it into the unpinned bucket.
      it('lists an app cron on a task that is on-demand globally, with that app\'s next slot', async () => {
        await withRealCron()
        getActiveApps.mockResolvedValue([{ id: 'app-1', name: 'Acme' }])
        isTaskTypeEnabledForApp.mockResolvedValue(true)
        getAppTaskTypeInterval.mockResolvedValue('15 9 * * *')
        getAppTaskTypeOverrides.mockResolvedValue({ 'do-release': { enabled: true, interval: '15 9 * * *' } })
        mockSchedule({ tasks: { 'do-release': { type: 'on-demand', enabled: true, runAfter: [] } } })

        const status = await getScheduleStatus()
        expect(status.tasks['do-release'].appSchedules).toEqual([{
          appId: 'app-1',
          appName: 'Acme',
          cronExpression: '15 9 * * *',
          nextRunAt: '2026-01-01T17:15:00.000Z',
          shouldRun: false,
          reason: 'cron-cooldown',
          missedSlot: null
        }])
      })

      it('omits an app that merely inherits the global cadence', async () => {
        await withRealCron()
        getActiveApps.mockResolvedValue([{ id: 'app-1', name: 'Acme' }])
        isTaskTypeEnabledForApp.mockResolvedValue(true)
        getAppTaskTypeInterval.mockResolvedValue(null)
        getAppTaskTypeOverrides.mockResolvedValue({ 'do-release': { enabled: true } })
        mockSchedule({ tasks: { 'do-release': { type: 'cron', cronExpression: '15 9 * * *', enabled: true, runAfter: [] } } })

        expect((await getScheduleStatus()).tasks['do-release'].appSchedules).toEqual([])
      })

      // An app restating the task's own expression adds no schedule the global
      // row cannot already show, so counting it would make "N apps scheduled"
      // mean something different per task.
      it('omits an app that restates the global expression', async () => {
        await withRealCron()
        getActiveApps.mockResolvedValue([{ id: 'app-1', name: 'Acme' }])
        isTaskTypeEnabledForApp.mockResolvedValue(true)
        getAppTaskTypeInterval.mockResolvedValue('15 9 * * *')
        getAppTaskTypeOverrides.mockResolvedValue({ 'do-release': { enabled: true, interval: '15 9 * * *' } })
        mockSchedule({ tasks: { 'do-release': { type: 'cron', cronExpression: '15 9 * * *', enabled: true, runAfter: [] } } })

        expect((await getScheduleStatus()).tasks['do-release'].appSchedules).toEqual([])
      })

      it('omits an app that is disabled for the task', async () => {
        await withRealCron()
        getActiveApps.mockResolvedValue([{ id: 'app-1', name: 'Acme' }])
        isTaskTypeEnabledForApp.mockResolvedValue(false)
        getAppTaskTypeInterval.mockResolvedValue('15 9 * * *')
        getAppTaskTypeOverrides.mockResolvedValue({ 'do-release': { enabled: false, interval: '15 9 * * *' } })
        mockSchedule({ tasks: { 'do-release': { type: 'on-demand', enabled: true, runAfter: [] } } })

        expect((await getScheduleStatus()).tasks['do-release'].appSchedules).toEqual([])
      })
    })

    describe('parkPerpetual / perpetual park state', () => {
      it('parkPerpetual stamps parkedUntil + reason on the per-app record', async () => {
        mockSchedule({ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } } })
        const record = await parkPerpetual('claim-issue', 'app-1', { reason: 'no-actionable-issues', actionableCount: 0, counts: { open: 40, inFlight: 2, filtered: 38 } })
        expect(record.parkedUntil).toBeTruthy()
        expect(record.parkReason).toBe('no-actionable-issues')
        expect(record.parkActionableCount).toBe(0)
        expect(record.parkCounts).toEqual({ open: 40, inFlight: 2, filtered: 38 })
      })

      // A park on a non-empty queue must carry its WHY: the per-cause skip
      // attribution ("49 needs-input, 17 blocked") is what tells the operator
      // their work is waiting on decisions, not that the task is broken — the
      // exact confusion behind reading a bare `no-actionable-issues` in PM2
      // output next to 88 open issues.
      it('parkPerpetual persists the per-cause skip attribution and names the top causes in its log line', async () => {
        mockSchedule({ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } } })
        const record = await parkPerpetual('claim-issue', 'app-1', {
          reason: 'no-actionable-issues', actionableCount: 0,
          counts: { open: 88, inFlight: 10, filtered: 78 },
          skipCauses: { 'needs-input': 49, blocked: 17, 'decomposed-epic': 12, assigned: 2 }
        })
        expect(record.parkSkipCauses).toEqual({ 'needs-input': 49, blocked: 17, 'decomposed-epic': 12, assigned: 2 })
        // The log line the operator reads in PM2 names the top 3 causes inline.
        const logged = emitLog.mock.calls.at(-1);
        expect(logged[1]).toMatch(/no-actionable-issues — 49 needs-input, 17 blocked, 12 decomposed-epic/);
        expect(logged[1]).not.toMatch(/2 assigned/);
      })

      it('parkPerpetual leaves parkSkipCauses absent when the detector reports no attribution', async () => {
        mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true } } })
        const record = await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-in-flight-branches', actionableCount: 0, counts: null, skipCauses: null })
        expect(record.parkSkipCauses).toBeUndefined()
      })

      it('getPerpetualParkInfo reads back the park record (and null when not parked)', async () => {
        const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0, parkedUntil: future, parkReason: 'no-actionable-issues', parkActionableCount: 0, parkCounts: { open: 40, inFlight: 2, filtered: 38 }, parkSkipCauses: { 'needs-input': 30, blocked: 8 } },
            'app-2': { lastRun: null, count: 0 }
          } } }
        })
        const info = await getPerpetualParkInfo('claim-issue', 'app-1')
        expect(info).toMatchObject({ parkedUntil: future, parkReason: 'no-actionable-issues', parkActionableCount: 0, parkCounts: { open: 40, inFlight: 2, filtered: 38 }, parkSkipCauses: { 'needs-input': 30, blocked: 8 } })
        expect(await getPerpetualParkInfo('claim-issue', 'app-2')).toBeNull()
        expect(await getPerpetualParkInfo('claim-issue', 'unknown-app')).toBeNull()
      })

      // The elapse-aware question the completion refill asks (#3848). It must differ
      // from getPerpetualParkInfo's "is there a park record": an ELAPSED park is
      // deliberately left on disk (it reads as "due right now"), so treating its
      // presence as a stop signal would wedge the drain until something cleared it.
      it('isPerpetualParkActive is true only while parkedUntil is in the future', async () => {
        const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
        const past = new Date(Date.now() - 60 * 60 * 1000).toISOString()
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
            'app-parked': { lastRun: null, count: 0, parkedUntil: future },
            'app-elapsed': { lastRun: null, count: 0, parkedUntil: past },
            'app-unparked': { lastRun: null, count: 0 }
          } } }
        })
        expect(await isPerpetualParkActive('claim-issue', 'app-parked')).toBe(true)
        expect(await isPerpetualParkActive('claim-issue', 'app-elapsed')).toBe(false)
        expect(await isPerpetualParkActive('claim-issue', 'app-unparked')).toBe(false)
        expect(await isPerpetualParkActive('claim-issue', 'unknown-app')).toBe(false)
        expect(await isPerpetualParkActive('unknown-type', 'app-parked')).toBe(false)
      })

      // branch-reconcile knows exactly when a claim worktree's grace window lapses.
      // Sleeping past it stacked the hold and the recheck cadence into a stall
      // several times longer than either — the shape that made a task with four
      // stale claim branches queued behind it look like it had stopped running.
      // (parseCronToNextRun is pinned off so the interval path is what runs; a
      // sibling test leaves it returning a year-2999 date.)
      it('parkPerpetual honours notLaterThan when the hold lifts before the recheck', async () => {
        parseCronToNextRun.mockReturnValue(null)
        mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 7 * 24 * 3600000 } } })
        const soon = new Date(Date.now() + 60 * 60 * 1000).toISOString()
        const record = await parkPerpetual('branch-reconcile', 'app-1', {
          reason: 'merged-branches-held-back', actionableCount: 0, signature: null,
          counts: { heldBackMerged: 4 }, notLaterThan: soon
        })
        expect(record.parkedUntil).toBe(soon)
        expect(record.parkReason).toBe('merged-branches-held-back')
        expect(record.parkCounts).toEqual({ heldBackMerged: 4 })
      })

      // The record, the log line and the schedule:perpetual-parked event all read
      // from one value. Bounding only the record's copy would keep publishing the
      // un-shortened time — a "parked until" the task no longer honours.
      it('parkPerpetual publishes the SHORTENED time on the parked event, not the raw cadence', async () => {
        parseCronToNextRun.mockReturnValue(null)
        cosEvents.emit.mockClear()
        mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 7 * 24 * 3600000 } } })
        const soon = new Date(Date.now() + 60 * 60 * 1000).toISOString()
        const record = await parkPerpetual('branch-reconcile', 'app-1', {
          reason: 'merged-branches-held-back', actionableCount: 0, signature: null, notLaterThan: soon
        })
        const parked = cosEvents.emit.mock.calls.find(([name]) => name === 'schedule:perpetual-parked')
        expect(parked?.[1].parkedUntil).toBe(soon)
        expect(parked[1].parkedUntil).toBe(record.parkedUntil)
      })

      // A cadence edit restamps every un-elapsed park. Without the bound
      // remembered ON the record, that edit stretches a correctly-shortened park
      // back out — the stacking this option exists to remove, reintroduced by an
      // unrelated settings change.
      it('a shortened park survives a recheck-cadence edit', async () => {
        parseCronToNextRun.mockReturnValue(null)
        const soon = new Date(Date.now() + 60 * 60 * 1000).toISOString()
        mockSchedule({
          tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } },
          executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0, parkedUntil: soon, parkNotLaterThan: soon, parkReason: 'merged-branches-held-back' }
          } } }
        })
        await updateTaskInterval('branch-reconcile', { recheckIntervalMs: 30 * 24 * 3600000 })
        const info = await getPerpetualParkInfo('branch-reconcile', 'app-1')
        expect(info.parkedUntil).toBe(soon)
      })

      it('parkPerpetual drops parkNotLaterThan when no bound is given', async () => {
        parseCronToNextRun.mockReturnValue(null)
        mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } } })
        const record = await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-in-flight-branches', actionableCount: 0, signature: null })
        expect(record.parkNotLaterThan).toBeUndefined()
      })

      it('parkPerpetual ignores a notLaterThan that is later than the recheck', async () => {
        parseCronToNextRun.mockReturnValue(null)
        mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } } })
        const far = new Date(Date.now() + 30 * 24 * 3600000).toISOString()
        const record = await parkPerpetual('branch-reconcile', 'app-1', {
          reason: 'merged-branches-held-back', actionableCount: 0, signature: null, notLaterThan: far
        })
        // The configured hourly cadence stands — a distant hold must not stretch it.
        expect(Date.parse(record.parkedUntil)).toBeLessThanOrEqual(Date.now() + 3600000)
        expect(Date.parse(record.parkedUntil)).toBeGreaterThan(Date.now())
      })

      it('derives retry eligibility from the app cadence and enabled switches, not a stale park', async () => {
        const future = new Date(Date.now() + 3_600_000).toISOString();
        const task = { type: 'on-demand', perpetual: false, autoStart: false, enabled: true };
        const execution = { perApp: { 'app-1': { parkedUntil: future } } };
        mockSchedule({ tasks: { 'branch-reconcile': task }, executions: { 'task:branch-reconcile': execution } });
        expect(await shouldRunTask('branch-reconcile', 'app-1')).toMatchObject({ shouldRun: false, reason: 'on-demand-only' });
        getAppTaskTypeInterval.mockResolvedValueOnce('0 3 * * *');
        parseCronToNextRun.mockReturnValueOnce(new Date(future));
        expect(await shouldRunTask('branch-reconcile', 'app-1')).toMatchObject({ shouldRun: false, reason: 'cron-cooldown', nextRunAt: future });
        isTaskTypeEnabledForApp.mockResolvedValue(false);
        expect(await shouldRunTask('branch-reconcile', 'app-1')).toEqual({ shouldRun: false, reason: 'disabled-for-app' });
        isTaskTypeEnabledForApp.mockResolvedValue(true);
        mockSchedule({ tasks: { 'branch-reconcile': { ...task, enabled: false } }, executions: { 'task:branch-reconcile': execution } });
        expect(await shouldRunTask('branch-reconcile', 'app-1')).toEqual({ shouldRun: false, reason: 'disabled' });
      });

      it('does not adopt new missing-checkout incidents into the frozen upgrade scope', async () => {
        let saved = { version: 2, retirementPolicyVersion: 2, tasks: {}, executions: {}, templates: [] };
        readJSONFile.mockImplementation(async () => structuredClone(saved));
        writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });
        const row = { branch: 'fix/new-incident', path: '/example/new', head: 'a'.repeat(40), reason: 'retirement-provenance-unverified' };
        const result = await recordBranchReconcileOutcome('app-1', { status: 'incomplete', remaining: [row] });
        expect(result.legacyRetirementTransition).toEqual({ version: 1, observations: [], resolutions: [] });
        expect(result.retirementObligations).toEqual([expect.objectContaining(row)]);
      });

      it('persists legacy audit settlement only against unchanged inventory and absent originals', async () => {
        const { markLegacyRetirements, legacyRetirementKey } = await import('../lib/legacyRetirementTransition.js');
        const row = { branch: 'fix/delivered', path: '/example/old', head: 'a'.repeat(40),
          reason: 'retirement-provenance-unverified', createdAt: '2026-01-01T00:00:00.000Z' };
        const original = { status: 'incomplete', remaining: [row], retirementObligations: [row], retired: [] };
        markLegacyRetirements(original);
        let saved = { version: 2, tasks: {}, executions: { 'task:branch-reconcile': {
          perApp: { 'app-1': { branchReconcileOutcome: original } },
        } }, templates: [] };
        readJSONFile.mockImplementation(async () => structuredClone(saved));
        writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });
        const plans = [{ key: legacyRetirementKey(row), observation: row, removalVerified: false,
          evidence: { kind: 'merged-ancestry', head: row.head, defaultHead: 'b'.repeat(40) } }];
        expect(await recordLegacyRetirementResolutions('app-1', { ...original, updatedAt: 'changed' }, plans, async () => true)).toEqual(original);
        expect(await recordLegacyRetirementResolutions('app-1', original, plans, async () => false)).toEqual(original);
        const result = await recordLegacyRetirementResolutions('app-1', original, plans, async () => true);
        expect(result).toMatchObject({ retirementObligations: [], remaining: [], retired: [],
          legacyRetirementTransition: { resolutions: [{ observation: row, removalVerified: false }] } });
        expect(await recordLegacyRetirementResolutions('app-1', original, plans, async () => true)).toEqual(result);
        expect(await getBranchReconcileOutcome('app-1')).toEqual(result);
      });

      it('persists incomplete sweep evidence and exposes it when recurring dispatch is off', async () => {
        let saved = { version: 2, tasks: { 'branch-reconcile': { enabled: true, type: 'on-demand', perpetual: false } }, executions: {}, templates: [] };
        readJSONFile.mockImplementation(async () => structuredClone(saved));
        writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });
        const remaining = [{ branch: 'fix/example', path: '/example/checkout', reason: 'worktree-locked' }];
        await recordBranchReconcileOutcome('app-1', { status: 'running', reason: 'batch-pending', remaining, nextAction: 'Continue.' });
        await recordInitializedRetirementRecovery('app-1', { transactionId: 'transaction-a', branch: 'claim/held',
          phase: 'quarantined-working', journalDigest: 'digest-a', ok: false, reason: 'automatic-retirement-independent-review-required' });
        expect((await getScheduleStatus()).tasks['branch-reconcile'].reconcileOutcomes['app-1'].initializedRetirements)
          .toEqual([expect.objectContaining({ transactionId: 'transaction-a', branch: 'claim/held', reason: 'automatic-retirement-independent-review-required' })]);

        const observedAt = saved.executions['task:branch-reconcile'].perApp['app-1'].branchReconcileOutcome.observedAt;
        await recordBranchReconcileOutcome('app-1', { status: 'incomplete', reason: 'agent-failed', nextAction: 'Resolve the provider failure and run again.' });
        expect(saved.executions['task:branch-reconcile'].perApp['app-1'].branchReconcileOutcome)
          .toMatchObject({ status: 'incomplete', reason: 'agent-failed', remaining, observedAt });
        expect((await getScheduleStatus()).tasks['branch-reconcile'].reconcileOutcomes['app-1'])
          .toMatchObject({ status: 'incomplete', reason: 'agent-failed', remaining, observedAt });
      });

      it('persists missing checkout and branch evidence when the Schedule view refreshes', async () => {
        let saved = { version: 2, tasks: { 'branch-reconcile': { enabled: true, type: 'on-demand', perpetual: false } }, executions: {}, templates: [] };
        readJSONFile.mockImplementation(async () => structuredClone(saved));
        writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });
        getAppById.mockResolvedValueOnce({ repoPath: '/example/repo' });
        const rows = [
          { branch: 'fix/missing-checkout', path: '/example/checkout', head: 'a'.repeat(40), reason: 'worktree-locked' },
          { branch: 'fix/missing-ref', head: 'b'.repeat(40), reason: 'branch-held' },
        ];
        await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: rows });
        findGoneInventoryRows.mockResolvedValueOnce(rows);
        const outcome = (await getScheduleStatus()).tasks['branch-reconcile'].reconcileOutcomes['app-1'];
        expect(outcome).toMatchObject({ status: 'incomplete', reason: 'retirement-provenance-unverified',
          retirementObligations: rows.map(row => ({ ...row, reason: 'retirement-provenance-unverified', createdAt: expect.any(String) })),
        });
        expect(outcome.retired).toBeUndefined();
        // Loading the persisted state again and an empty sweep cannot clear the evidence.
        await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [] });
        const reloaded = (await getScheduleStatus()).tasks['branch-reconcile'].reconcileOutcomes['app-1'];
        expect(reloaded.retirementObligations).toEqual(outcome.retirementObligations);
        expect(reloaded.remaining).toEqual(outcome.retirementObligations);
      });

      it('keeps the previous observation when a replacement sweep cannot read source presence', async () => {
        let saved = { version: 2, tasks: { 'branch-reconcile': { enabled: true, type: 'on-demand' } }, executions: {}, templates: [] };
        readJSONFile.mockImplementation(async () => structuredClone(saved));
        writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });
        const remaining = [{ branch: 'fix/example', path: '/example/checkout', head: 'a'.repeat(40), reason: 'worktree-locked' }];
        const previous = await recordBranchReconcileOutcome('app-1', { status: 'incomplete', remaining });
        getAppById.mockResolvedValueOnce({ repoPath: '/example/repo' });
        findGoneInventoryRows.mockRejectedValueOnce(new Error('checkout-presence-unavailable'));
        await expect(recordBranchReconcileOutcome('app-1', { status: 'drained', remaining: [] }))
          .rejects.toThrow('checkout-presence-unavailable');
        expect(saved.executions['task:branch-reconcile'].perApp['app-1'].branchReconcileOutcome).toEqual(previous);
      });

      it('never loses exact retirement obligations across empty scans, restart reads or unrelated receipts', async () => {
        let saved = { version: 2, tasks: { 'branch-reconcile': { enabled: true, type: 'on-demand', perpetual: true } }, executions: {}, templates: [] };
        readJSONFile.mockImplementation(async () => structuredClone(saved));
        writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });
        const release = { branch: 'fix/example', path: '/example/checkout', head: 'a'.repeat(40), reason: 'retirement-review-pending' };
        const outcome = () => saved.executions['task:branch-reconcile'].perApp['app-1'].branchReconcileOutcome;
        const unrelated = { branch: 'fix/other', reason: 'worktree-locked' };
        await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [unrelated] });
        await recordBranchReconcileOutcome('app-1', { status: 'running', retirementObligations: [release] });
        const createdAt = outcome().retirementObligations[0].createdAt;
        expect(Number.isFinite(Date.parse(createdAt))).toBe(true);
        expect(outcome().remaining).toEqual([unrelated, { ...release, createdAt, reason: 'retirement-receipt-unverified' }]);
        await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [] });
        await recordHeldCheckoutRetirement('app-1', { ...release, head: 'b'.repeat(40), branchDeleted: true, archiveDir: '/example/other' });
        await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [] });
        await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-in-flight-branches' });
        expect(outcome()).toMatchObject({ status: 'incomplete', retirementObligations: [{ ...release, createdAt, reason: 'retirement-receipt-unverified' }], remaining: [{ ...release, createdAt, reason: 'retirement-receipt-unverified' }] });
        await recordHeldCheckoutRetirement('app-1', { ...release, branchDeleted: true, archiveDir: '/example/archive' });
        await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [] });
        await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-in-flight-branches' });
        expect(outcome()).toMatchObject({ status: 'drained', retirementObligations: [], remaining: [] });
        // A new checkout with identical branch/path/head cannot reuse that receipt.
        const retiredAt = outcome().retired[0].retiredAt;
        isCurrentRetirementCheckout.mockResolvedValueOnce(true);
        await recordBranchReconcileOutcome('app-1', { status: 'running', retirementObligations: [{ ...release, checkoutIdentity: 'new-incarnation' }] });
        const recreatedAt = outcome().retirementObligations[0].createdAt;
        expect(Date.parse(recreatedAt)).toBeGreaterThan(Date.parse(retiredAt));
        await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [] });
        await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-in-flight-branches' });
        expect(outcome()).toMatchObject({ status: 'incomplete', retirementObligations: [{ ...release, checkoutIdentity: 'new-incarnation', createdAt: recreatedAt, reason: 'retirement-receipt-unverified' }] });

      });

      it('records a separate receipt when the same checkout tuple is recreated without an archive', async () => {
        let saved = { version: 2, tasks: {}, executions: {}, templates: [] };
        readJSONFile.mockImplementation(async () => structuredClone(saved));
        writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });
        const row = { branch: 'fix/example', path: '/example/checkout', head: 'a'.repeat(40),
          checkoutIdentity: 'original', reason: 'retirement-review-pending' };
        const outcome = () => saved.executions['task:branch-reconcile'].perApp['app-1'].branchReconcileOutcome;
        await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [row] });
        await recordHeldCheckoutRetirement('app-1', { ...row, branchDeleted: true });
        expect(outcome().retirementObligations).toEqual([]);
        const recreated = { ...row, checkoutIdentity: 'recreated' };
        isCurrentRetirementCheckout.mockResolvedValueOnce(true);
        await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [recreated] });
        expect(outcome().retirementObligations).toEqual([expect.objectContaining({ checkoutIdentity: 'recreated' })]);
        await recordHeldCheckoutRetirement('app-1', { ...recreated, branchDeleted: true });
        expect(outcome().retirementObligations).toEqual([]);
        expect(Object.values(outcome().retirementReceiptEvidence).map(entry => entry.checkoutIdentity).sort())
          .toEqual(['original', 'recreated']);
        expect(Object.keys(outcome().retirementReceiptIdentities)).toHaveLength(2);
        await recordHeldCheckoutRetirement('app-1', { ...row, branchDeleted: true });
        expect(Object.keys(outcome().retirementReceiptIdentities)).toHaveLength(2);
      });

      it.each(['scan-first', 'receipt-first'])('does not resurrect a stale scan across serialized %s writes', async order => {
        let saved = { version: 2, tasks: {}, executions: {}, templates: [] };
        readJSONFile.mockImplementation(async () => structuredClone(saved));
        writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });
        vi.useFakeTimers({ toFake: ['Date'] });
        vi.setSystemTime(new Date('2026-10-23T00:00:00Z'));
        const row = { branch: 'fix/example', path: '/example/checkout', head: 'a'.repeat(40),
          checkoutIdentity: 'original', observedAt: new Date().toISOString(), reason: 'retirement-review-pending' };
        const receipt = { ...row, branchDeleted: true, archiveDir: '/example/archive' };
        const outcome = () => saved.executions['task:branch-reconcile'].perApp['app-1'].branchReconcileOutcome;
        const scan = () => recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [row] });
        const retire = () => recordHeldCheckoutRetirement('app-1', receipt);
        // Queue both without awaiting: updateSchedule must merge with the prior write.
        await Promise.all(order === 'scan-first' ? [scan(), retire()] : [retire(), scan()]);
        expect(outcome()).toMatchObject({ retirementObligations: [], remaining: [] });
        const retiredAt = outcome().retired[0].retiredAt;
        vi.setSystemTime(new Date('2026-10-23T00:00:20Z'));
        await scan();
        // A legacy delayed producer has its original timestamp, not filesystem identity.
        await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [{ ...row, checkoutIdentity: undefined }] });
        expect(outcome()).toMatchObject({ retirementObligations: [], remaining: [] });
        expect(isCurrentRetirementCheckout).not.toHaveBeenCalled();
        // A fresh same-tuple checkout needs a live identity check, even in the same clock tick.
        vi.setSystemTime(new Date(retiredAt));
        const recreated = { ...row, checkoutIdentity: 'recreated' };
        isCurrentRetirementCheckout.mockResolvedValueOnce(true);
        await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [recreated] });
        const obligation = outcome().retirementObligations[0];
        expect(obligation).toMatchObject({ checkoutIdentity: 'recreated' });
        expect(Date.parse(obligation.createdAt)).toBeGreaterThan(Date.parse(retiredAt));
        expect(isCurrentRetirementCheckout).toHaveBeenCalledWith(recreated);
        vi.setSystemTime(new Date('2026-10-23T00:01:00Z'));
        await retire();
        expect(outcome().retired[0].retiredAt).toBe(retiredAt);
        expect(outcome().retirementObligations).toEqual([obligation]);
        await recordHeldCheckoutRetirement('app-1', { ...receipt, checkoutIdentity: 'recreated', archiveDir: '/example/new-archive' });
        expect(outcome().retirementObligations).toEqual([]);
        // A delayed observation of a different, now absent incarnation cannot mint another obligation.
        await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [{ ...row, checkoutIdentity: 'absent' }] });
        expect(outcome()).toMatchObject({ retirementObligations: [], remaining: [] });
        vi.useRealTimers();
      });

      it('retains an unidentified obligation instead of borrowing a branch-name receipt', async () => {
        let saved = { version: 2, tasks: {}, executions: {}, templates: [] };
        readJSONFile.mockImplementation(async () => structuredClone(saved));
        writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });
        const row = { branch: 'fix/example', createdAt: '2026-01-01T00:00:00Z', reason: 'retirement-review-pending' };
        await recordHeldCheckoutRetirement('app-1', { branch: row.branch, path: '/example/checkout', head: 'a'.repeat(40),
          branchDeleted: true, archiveDir: '/example/archive' });
        const result = await recordBranchReconcileOutcome('app-1', { status: 'incomplete', retirementObligations: [row] });
        expect(result.retirementObligations).toEqual([{ ...row, reason: 'retirement-receipt-unverified' }]);
      });

      it('routes workspace retirement only to the matching repository and exact checkout tuple', async () => {
        let saved = { version: 2, tasks: {}, executions: {}, templates: [] };
        readJSONFile.mockImplementation(async () => structuredClone(saved));
        writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });
        const row = { branch: 'fix/example', path: '/example/checkout', head: 'a'.repeat(40),
          checkoutIdentity: 'original', reason: 'worktree-locked' };
        await recordBranchReconcileOutcome('matching', { status: 'incomplete', remaining: [row] });
        await recordBranchReconcileOutcome('different-head', { status: 'incomplete', remaining: [{ ...row, head: 'b'.repeat(40) }] });
        await recordBranchReconcileOutcome('different-repo', { status: 'incomplete', remaining: [row] });
        getAppById.mockImplementation(async id => ({ repoPath: id === 'different-repo' ? '/other/repo' : '/example/repo' }));
        await recordWorkspaceCheckoutRetirement('/example/repo', { ...row, branchDeleted: true, archiveDir: '/example/archive' });
        const perApp = saved.executions['task:branch-reconcile'].perApp;
        expect(perApp.matching.branchReconcileOutcome.remaining).toEqual([]);
        expect(perApp['different-head'].branchReconcileOutcome).toMatchObject({ remaining: [{ ...row, head: 'b'.repeat(40) }] });
        expect(perApp['different-head'].branchReconcileOutcome.retired).toBeUndefined();
        expect(perApp['different-repo'].branchReconcileOutcome.remaining).toEqual([row]);
        expect(perApp['different-repo'].branchReconcileOutcome.retired).toBeUndefined();
      });

      it('keeps a current inventory observation when a different-head retirement arrives at the same path', async () => {
        let saved = { version: 2, tasks: {}, executions: {}, templates: [] };
        readJSONFile.mockImplementation(async () => structuredClone(saved));
        writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });
        const current = { branch: 'fix/example', path: '/example/checkout', head: 'b'.repeat(40),
          checkoutIdentity: 'recreated', reason: 'worktree-locked' };
        await recordBranchReconcileOutcome('app-1', { status: 'incomplete', remaining: [current] });
        const result = await recordHeldCheckoutRetirement('app-1', { ...current, head: 'a'.repeat(40),
          checkoutIdentity: 'original', branchDeleted: true, archiveDir: '/example/archive' });
        expect(result.remaining).toEqual([current]);
      });

      it('keeps both incarnations when recreation is observed before the original receipt arrives', async () => {
        let saved = { version: 2, tasks: {}, executions: {}, templates: [] };
        readJSONFile.mockImplementation(async () => structuredClone(saved));
        writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });
        const original = { branch: 'fix/example', path: '/example/checkout', head: 'a'.repeat(40),
          checkoutIdentity: 'original', reason: 'retirement-review-pending' };
        const recreated = { ...original, checkoutIdentity: 'recreated' };
        await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [original] });
        isCurrentRetirementCheckout.mockResolvedValueOnce(true);
        const pending = await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [recreated] });
        expect(pending.retirementObligations.map(row => row.checkoutIdentity)).toEqual(['original', 'recreated']);
        const retired = await recordHeldCheckoutRetirement('app-1', { ...original, branchDeleted: true, archiveDir: '/example/archive' });
        expect(retired.retirementObligations).toEqual([expect.objectContaining({ checkoutIdentity: 'recreated' })]);
        expect(retired.remaining).toEqual([expect.objectContaining({ checkoutIdentity: 'recreated' })]);
      });

      it('keeps stale-observation evidence after receipt display eviction and refuses duplicate replay', async () => {
        let saved = { version: 2, tasks: {}, executions: {}, templates: [] };
        readJSONFile.mockImplementation(async () => structuredClone(saved));
        writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });
        const row = { branch: 'fix/example', path: '/example/checkout', head: 'a'.repeat(40),
          createdAt: '2026-01-01T00:00:00Z', reason: 'retirement-review-pending' };
        const receipt = { ...row, branchDeleted: true, archiveDir: '/example/archive' };
        const outcome = () => saved.executions['task:branch-reconcile'].perApp['app-1'].branchReconcileOutcome;
        await recordHeldCheckoutRetirement('app-1', receipt);
        const evidence = structuredClone(outcome().retirementReceiptEvidence);
        for (let index = 0; index < 20; index++) {
          await recordHeldCheckoutRetirement('app-1', { ...receipt, branch: `fix/other-${index}` });
        }
        expect(outcome().retired.some(entry => entry.branch === row.branch)).toBe(false);
        await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [row] });
        await recordHeldCheckoutRetirement('app-1', receipt);
        expect(outcome()).toMatchObject({ retirementObligations: [], remaining: [], retirementReceiptEvidence: evidence });
        expect(outcome().retired.some(entry => entry.branch === row.branch)).toBe(false);
      });

      it('persists branch attempts through cap parks and manual resets, clearing only on sweep exhaustion', async () => {
        let saved = { version: 2, tasks: { 'branch-reconcile': { enabled: true, type: 'on-demand', perpetual: true } }, executions: {}, templates: [] };
        readJSONFile.mockImplementation(async () => JSON.parse(JSON.stringify(saved)));
        writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });
        const branchAttempts = { 'fix/first': 'fix/first:IN_REVIEW:1:head' };
        await recordPerpetualDispatch('branch-reconcile', 'app-1', 'batch', { branchAttempts });
        await parkPerpetual('branch-reconcile', 'app-1', { reason: 'drain-cap', signature: null });
        await resetPerpetualForManualRun('branch-reconcile', 'app-1');
        expect(await getPerpetualDrainState('branch-reconcile', 'app-1')).toEqual({ signature: null, dispatchCount: 0, branchAttempts });
        const counts = { heldBranches: 2, heldDetached: 1 };
        const skipCauses = { 'draft-review-required': 1, 'claim-owner-active': 1, 'worktree-locked': 1 };
        await parkPerpetual('branch-reconcile', 'app-1', { reason: 'branches-blocked', counts, skipCauses, branchAttempts: null });
        expect((await getPerpetualDrainState('branch-reconcile', 'app-1')).branchAttempts).toBeUndefined();
        expect(await getPerpetualParkInfo('branch-reconcile', 'app-1')).toMatchObject({ parkReason: 'branches-blocked', parkCounts: counts, parkSkipCauses: skipCauses });
      });

      it('parkPerpetual omits parkCounts when no breakdown is provided', async () => {
        mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } } })
        const record = await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-in-flight-branches', actionableCount: 0, signature: null })
        expect(record.parkCounts).toBeUndefined()
      })

      // The mid-drain unpark is recordPerpetualDispatch's job (it clears the park
      // fields in the same write it spends a dispatch) — there is no separate
      // clear-only path any more, so a resumed drain can never forget to spend
      // one and slip the cap.
      it('recordPerpetualDispatch clears an existing park as it spends a dispatch', async () => {
        const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0, parkedUntil: future, parkReason: 'no-actionable-issues', perpetualDispatchCount: 2 }
          } } }
        })
        expect(await recordPerpetualDispatch('claim-issue', 'app-1', null)).toBe(3)
        expect(await isPerpetualParkActive('claim-issue', 'app-1')).toBe(false)
        expect(await getPerpetualParkInfo('claim-issue', 'app-1')).toBeNull()
      })

      it('resetPerpetualForManualRun drops the park, the convergence signature, AND the dispatch count', async () => {
        const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
        mockSchedule({
          tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0, parkedUntil: future, parkReason: 'no-progress', lastActionableSignature: 'a:NEEDS_PR:none', perpetualDispatchCount: 4 }
          } } }
        })
        expect(await resetPerpetualForManualRun('branch-reconcile', 'app-1')).toBe(true)
        const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
        const rec = saved.executions['task:branch-reconcile'].perApp['app-1']
        expect(rec.parkedUntil).toBeUndefined()
        expect(rec.parkReason).toBeUndefined()
        expect(rec.lastActionableSignature).toBeUndefined()
        // A human asking to re-run gets a full dispatch budget, not the tail of the
        // previous window — otherwise a drain that just hit the cap would park again
        // on its first cycle.
        expect(rec.perpetualDispatchCount).toBeUndefined()
      })

      it('getPerpetualDrainState reads both brakes in one pass (and defaults them)', async () => {
        mockSchedule({
          tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0, lastActionableSignature: 'sig-1', perpetualDispatchCount: 3 }
          } } }
        })
        expect(await getPerpetualDrainState('branch-reconcile', 'app-1')).toEqual({ signature: 'sig-1', dispatchCount: 3 })
        // An app with no record yet is "fresh drain", not undefined.
        expect(await getPerpetualDrainState('branch-reconcile', 'app-9')).toEqual({ signature: null, dispatchCount: 0 })
      })

      it('recordPerpetualDispatch drops the park, records the signature, and spends one dispatch in ONE write', async () => {
        const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
        mockSchedule({
          tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0, parkedUntil: future, parkReason: 'no-progress', perpetualDispatchCount: 2 }
          } } }
        })
        expect(await recordPerpetualDispatch('branch-reconcile', 'app-1', 'sig-2')).toBe(3)
        const rec = JSON.parse(writeFile.mock.calls.at(-1)[1]).executions['task:branch-reconcile'].perApp['app-1']
        expect(rec.parkedUntil).toBeUndefined()
        expect(rec.parkReason).toBeUndefined()
        expect(rec.lastActionableSignature).toBe('sig-2')
        expect(rec.perpetualDispatchCount).toBe(3)
        // The three facts land TOGETHER: no persisted state exists in which the new
        // signature is recorded without the park cleared and the dispatch counted.
        // (loadSchedule may itself write once for prompt self-heal, so this asserts
        // the invariant rather than a raw write count.)
        const partial = writeFile.mock.calls
          .map((c) => JSON.parse(c[1]).executions['task:branch-reconcile']?.perApp?.['app-1'])
          .filter((r) => r?.lastActionableSignature === 'sig-2')
          .filter((r) => r.parkedUntil !== undefined || r.perpetualDispatchCount !== 3)
        expect(partial).toEqual([])
      })

      // The churn detector (agentChurn.js) parks a coordinator when a local
      // signal fires. A dispatch that leaves a stale count behind makes the next
      // park over-report "same finding again". A dispatch only happens on a
      // CHANGED set, so it resets to 1.
      it('recordPerpetualDispatch resets signatureRepeatCount for the new signature', async () => {
        mockSchedule({
          tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0, lastActionableSignature: 'old-sig', signatureRepeatCount: 4 }
          } } }
        })
        await recordPerpetualDispatch('branch-reconcile', 'app-1', 'new-sig')
        const rec = JSON.parse(writeFile.mock.calls.at(-1)[1]).executions['task:branch-reconcile'].perApp['app-1']
        expect(rec.lastActionableSignature).toBe('new-sig')
        expect(rec.signatureRepeatCount).toBe(1)
      })

      // The park has to land the zeroed budget itself: a second await is a step a
      // future park path can forget, and a stale count caps the NEXT drain early.
      it('parkPerpetual clears the dispatch budget when handed dispatchCount: 0', async () => {
        mockSchedule({
          tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } },
          executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, perpetualDispatchCount: 4 } } } }
        })
        await parkPerpetual('branch-reconcile', 'app-1', { reason: 'drain-cap', actionableCount: 2, signature: null, dispatchCount: 0 })
        const rec = JSON.parse(writeFile.mock.calls.at(-1)[1]).executions['task:branch-reconcile'].perApp['app-1']
        expect(rec.perpetualDispatchCount).toBeUndefined()
        expect(rec.lastActionableSignature).toBeUndefined()
        expect(rec.parkReason).toBe('drain-cap')
      })

      // Inverted deliberately (#3848): omitting the option used to PRESERVE the
      // count. A park ends the drain window by definition, so zeroing the budget is
      // the invariant, not something each call site has to opt into — the churn
      // detector's park (agentChurn.js) is exactly the caller that forgot, leaving
      // the next window to cap early on a spend it never made.
      it('parkPerpetual zeroes the dispatch budget even when the caller omits dispatchCount', async () => {
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, perpetualDispatchCount: 4 } } } }
        })
        await parkPerpetual('claim-issue', 'app-1', { reason: 'churn-detected', actionableCount: 12 })
        const rec = JSON.parse(writeFile.mock.calls.at(-1)[1]).executions['task:claim-issue'].perApp['app-1']
        expect(rec.perpetualDispatchCount).toBeUndefined()
      })

      it('resetPerpetualForManualRun is a no-op (false) when nothing is cached', async () => {
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0 } } } }
        })
        expect(await resetPerpetualForManualRun('claim-issue', 'app-1')).toBe(false)
      })

      it('parkPerpetual stores the actionable signature it parked on', async () => {
        mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } } })
        await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-progress', actionableCount: 2, signature: 'a:NEEDS_PR:none|b:IN_REVIEW:5' })
        const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
        expect(saved.executions['task:branch-reconcile'].perApp['app-1'].lastActionableSignature).toBe('a:NEEDS_PR:none|b:IN_REVIEW:5')
      })

      it('parkPerpetual with signature:null clears a prior signature (idle park)', async () => {
        mockSchedule({
          tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } },
          executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, lastActionableSignature: 'old-sig' } } } }
        })
        await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-in-flight-branches', actionableCount: 0, signature: null })
        const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
        expect(saved.executions['task:branch-reconcile'].perApp['app-1'].lastActionableSignature).toBeUndefined()
      })

      it('parkPerpetual increments signatureRepeatCount when the same finding is parked again', async () => {
        mockSchedule({
          tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } },
          executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, lastActionableSignature: 'a:NEEDS_PR:none' } } } }
        })
        await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-progress', actionableCount: 1, signature: 'a:NEEDS_PR:none' })
        const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
        expect(saved.executions['task:branch-reconcile'].perApp['app-1'].signatureRepeatCount).toBe(2)
        expect(saved.executions['task:branch-reconcile'].perApp['app-1'].lastActionableSignature).toBe('a:NEEDS_PR:none')
      })

      it('parkPerpetual resets signatureRepeatCount when the finding changes', async () => {
        mockSchedule({
          tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } },
          executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, lastActionableSignature: 'old', signatureRepeatCount: 6 } } } }
        })
        await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-progress', actionableCount: 1, signature: 'new' })
        const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
        expect(saved.executions['task:branch-reconcile'].perApp['app-1'].lastActionableSignature).toBe('new')
        expect(saved.executions['task:branch-reconcile'].perApp['app-1'].signatureRepeatCount).toBe(1)
      })
    })

    describe('type-level failure ledger (#2616)', () => {
      it('computeFailureBackoffMs scales 2^n × base, capped, and 0 for n<=0', () => {
        expect(computeFailureBackoffMs(0)).toBe(0)
        expect(computeFailureBackoffMs(-3)).toBe(0)
        expect(computeFailureBackoffMs(1)).toBe(FAILURE_BACKOFF_BASE_MS * 2)
        expect(computeFailureBackoffMs(2)).toBe(FAILURE_BACKOFF_BASE_MS * 4)
        expect(computeFailureBackoffMs(3)).toBe(FAILURE_BACKOFF_BASE_MS * 8)
        // Large n saturates at the cap.
        expect(computeFailureBackoffMs(50)).toBe(FAILURE_BACKOFF_CAP_MS)
      })

      it('recordTaskTypeFailure increments consecutiveFailures + stamps category', async () => {
        mockSchedule({ tasks: { security: { type: 'rotation', enabled: true } } })
        const rec = await recordTaskTypeFailure('security', 'app-1', { errorCategory: 'timeout' })
        expect(rec.consecutiveFailures).toBe(1)
        expect(rec.lastErrorCategory).toBe('timeout')
        expect(rec.lastFailureAt).toBeTruthy()
        expect(rec.failureParkedAt).toBeUndefined()
        const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
        expect(saved.executions['task:security'].perApp['app-1'].consecutiveFailures).toBe(1)
      })

      it('records a task queued under a retired type name on the renamed ledger', async () => {
        // A release-check task queued before migration 417 finishes after it.
        mockSchedule({
          tasks: { 'do-release': { type: 'on-demand', enabled: true } },
          executions: { 'task:do-release': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0, consecutiveFailures: 1, lastFailureAt: new Date().toISOString() }
          } } }
        })
        const rec = await recordTaskTypeFailure('release-check', 'app-1', { errorCategory: 'timeout' })
        expect(rec.consecutiveFailures).toBe(2)
        const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
        expect(saved.executions).not.toHaveProperty('task:release-check')
      })

      it('auto-parks + notifies after FAILURE_PARK_THRESHOLD consecutive failures', async () => {
        mockSchedule({
          tasks: { security: { type: 'rotation', enabled: true } },
          executions: { 'task:security': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0, consecutiveFailures: FAILURE_PARK_THRESHOLD - 1, lastFailureAt: new Date().toISOString() }
          } } }
        })
        const rec = await recordTaskTypeFailure('security', 'app-1', { errorCategory: 'auth-error' })
        expect(rec.consecutiveFailures).toBe(FAILURE_PARK_THRESHOLD)
        expect(rec.failureParkedAt).toBeTruthy()
        expect(rec.failureParkReason).toBe('auth-error')
        expect(addNotification).toHaveBeenCalledTimes(1)
        expect(addNotification.mock.calls[0][0]).toMatchObject({
          type: 'agent_warning',
          metadata: { taskType: 'security', appId: 'app-1', failureParkKey: 'security:app-1' }
        })
      })

      it('does not re-notify (deduped) when a park already exists', async () => {
        notificationExists.mockResolvedValueOnce(true)
        mockSchedule({
          tasks: { security: { type: 'rotation', enabled: true } },
          executions: { 'task:security': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0, consecutiveFailures: FAILURE_PARK_THRESHOLD - 1, lastFailureAt: new Date().toISOString() }
          } } }
        })
        await recordTaskTypeFailure('security', 'app-1', { errorCategory: 'auth-error' })
        expect(addNotification).not.toHaveBeenCalled()
      })

      it('recordTaskTypeSuccess prunes the stale park notification (so a re-park re-notifies)', async () => {
        mockSchedule({
          tasks: { security: { type: 'rotation', enabled: true } },
          executions: { 'task:security': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0, consecutiveFailures: 5, failureParkedAt: new Date().toISOString(), failureParkReason: 'auth-error' }
          } } }
        })
        await recordTaskTypeSuccess('security', 'app-1')
        expect(removeByMetadata).toHaveBeenCalledWith('failureParkKey', 'security:app-1')
      })

      it('recordTaskTypeSuccess does NOT prune when the type was not parked', async () => {
        mockSchedule({
          tasks: { security: { type: 'rotation', enabled: true } },
          executions: { 'task:security': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0, consecutiveFailures: 2 }
          } } }
        })
        await recordTaskTypeSuccess('security', 'app-1')
        expect(removeByMetadata).not.toHaveBeenCalled()
      })

      it('recordTaskTypeSuccess resets the ledger and returns false when already clean', async () => {
        mockSchedule({
          tasks: { security: { type: 'rotation', enabled: true } },
          executions: { 'task:security': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0, consecutiveFailures: 3, lastFailureAt: new Date().toISOString(), failureParkedAt: new Date().toISOString(), failureParkReason: 'x' }
          } } }
        })
        expect(await recordTaskTypeSuccess('security', 'app-1')).toBe(true)
        const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
        const rec = saved.executions['task:security'].perApp['app-1']
        expect(rec.consecutiveFailures).toBeUndefined()
        expect(rec.failureParkedAt).toBeUndefined()
        // Second call: nothing left to clear.
        mockSchedule({ tasks: { security: { type: 'rotation', enabled: true } }, executions: { 'task:security': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0 } } } } })
        expect(await recordTaskTypeSuccess('security', 'app-1')).toBe(false)
      })

      it('clearTaskTypeFailurePark(appId=null) clears ONLY the global record, not other apps', async () => {
        mockSchedule({
          tasks: { security: { type: 'rotation', enabled: true } },
          executions: { 'task:security': {
            lastRun: null, count: 0, consecutiveFailures: 4, failureParkedAt: new Date().toISOString(),
            perApp: {
              'app-1': { lastRun: null, count: 0, consecutiveFailures: 5, failureParkedAt: new Date().toISOString() }
            }
          } }
        })
        expect(await clearTaskTypeFailurePark('security')).toBe(true)
        const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
        const top = saved.executions['task:security']
        // Global record cleared...
        expect(top.consecutiveFailures).toBeUndefined()
        expect(top.failureParkedAt).toBeUndefined()
        // ...but app-1's independent ledger is untouched (its cause was never addressed).
        expect(top.perApp['app-1'].consecutiveFailures).toBe(5)
        expect(top.perApp['app-1'].failureParkedAt).toBeTruthy()
      })

      it('clearTaskTypeFailurePark(appId) clears ONLY that app, not the global record', async () => {
        mockSchedule({
          tasks: { security: { type: 'rotation', enabled: true } },
          executions: { 'task:security': {
            lastRun: null, count: 0, consecutiveFailures: 4, failureParkedAt: new Date().toISOString(),
            perApp: { 'app-1': { lastRun: null, count: 0, consecutiveFailures: 5, failureParkedAt: new Date().toISOString() } }
          } }
        })
        expect(await clearTaskTypeFailurePark('security', 'app-1')).toBe(true)
        const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
        const top = saved.executions['task:security']
        expect(top.perApp['app-1'].failureParkedAt).toBeUndefined()
        expect(top.consecutiveFailures).toBe(4)
        expect(removeByMetadata).toHaveBeenCalledWith('failureParkKey', 'security:app-1')
      })

      it('shouldRunTask returns failure-parked for a parked type', async () => {
        mockSchedule({
          tasks: { security: { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:security': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0, consecutiveFailures: FAILURE_PARK_THRESHOLD, failureParkedAt: new Date().toISOString(), failureParkReason: 'auth-error' }
          } } }
        })
        const res = await shouldRunTask('security', 'app-1')
        expect(res.shouldRun).toBe(false)
        expect(res.reason).toBe('failure-parked')
        expect(res.failureParkReason).toBe('auth-error')
      })

      it('shouldRunTask applies escalating failure-cooldown to an otherwise always-run perpetual drain', async () => {
        // 2 consecutive failures → backoff = base*4; last failure just now → in cooldown.
        mockSchedule({
          tasks: { security: { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:security': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0, consecutiveFailures: 2, lastFailureAt: new Date().toISOString(), lastErrorCategory: 'timeout' }
          } } }
        })
        const res = await shouldRunTask('security', 'app-1')
        expect(res.shouldRun).toBe(false)
        expect(res.reason).toBe('failure-cooldown')
        expect(res.consecutiveFailures).toBe(2)
        expect(res.failureBackoffMs).toBe(FAILURE_BACKOFF_BASE_MS * 4)
      })

      it('shouldRunTask lets a perpetual drain run once the failure-cooldown has elapsed', async () => {
        // 1 failure → backoff = base*2; last failure long ago → cooldown elapsed.
        const longAgo = new Date(Date.now() - (FAILURE_BACKOFF_CAP_MS + 60_000)).toISOString()
        mockSchedule({
          tasks: { security: { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:security': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0, consecutiveFailures: 1, lastFailureAt: longAgo }
          } } }
        })
        const res = await shouldRunTask('security', 'app-1')
        expect(res.shouldRun).toBe(true)
        expect(res.reason).toBe('perpetual-drain')
      })

      it('updateTaskInterval clears the failure ledger (config-change unpark)', async () => {
        mockSchedule({
          tasks: { security: { type: 'rotation', enabled: true } },
          executions: { 'task:security': {
            lastRun: null, count: 0, consecutiveFailures: 5, failureParkedAt: new Date().toISOString(),
            perApp: { 'app-1': { lastRun: null, count: 0, consecutiveFailures: 5, failureParkedAt: new Date().toISOString() } }
          } }
        })
        await updateTaskInterval('security', { enabled: true })
        const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
        const top = saved.executions['task:security']
        expect(top.consecutiveFailures).toBeUndefined()
        expect(top.failureParkedAt).toBeUndefined()
        expect(top.perApp['app-1'].failureParkedAt).toBeUndefined()
      })
    })

    describe('updateTaskInterval recompute-on-cadence-change', () => {
      it('re-derives an existing park when the recheck cadence changes', async () => {
        const farFuture = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString()
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 30 * 24 * 60 * 60 * 1000 } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, parkedUntil: farFuture } } } }
        })
        await updateTaskInterval('claim-issue', { recheckIntervalMs: 1000 })
        const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
        const newParked = saved.executions['task:claim-issue'].perApp['app-1'].parkedUntil
        // Recomputed from the shortened cadence (now + 1s), far earlier than the old 30-day park.
        expect(new Date(newParked).getTime()).toBeLessThan(new Date(farFuture).getTime())
        expect(new Date(newParked).getTime()).toBeLessThan(Date.now() + 60_000)
      })

      it('does not create a park when none exists', async () => {
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0 } } } }
        })
        await updateTaskInterval('claim-issue', { recheckIntervalMs: 1000 })
        const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
        expect(saved.executions['task:claim-issue'].perApp['app-1'].parkedUntil).toBeUndefined()
      })

      // #3590: an elapsed park is never cleared when it expires — shouldRunTask
      // reports `perpetual-recheck` and the dispatch gate clears it — so a record
      // whose parkedUntil is in the past is DUE RIGHT NOW. Restamping it from a
      // LENGTHENED cadence would silently delay work the user is already waiting on.
      it('leaves an already-elapsed park alone while re-deriving a future one', async () => {
        isTaskTypeEnabledForApp.mockResolvedValue(true)
        const soon = new Date(Date.now() + 60 * 1000).toISOString()
        const elapsed = new Date(Date.now() - 60 * 1000).toISOString()
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 60 * 1000 } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
            'app-future': { lastRun: null, count: 0, parkedUntil: soon },
            'app-elapsed': { lastRun: null, count: 0, parkedUntil: elapsed }
          } } }
        })
        // Cadence LENGTHENED from 1 minute to 30 days.
        await updateTaskInterval('claim-issue', { recheckIntervalMs: 30 * 24 * 60 * 60 * 1000 })
        const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
        const perApp = saved.executions['task:claim-issue'].perApp
        // The future park is rewritten from the new (longer) cadence.
        expect(new Date(perApp['app-future'].parkedUntil).getTime())
          .toBeGreaterThan(new Date(soon).getTime())
        // The elapsed park is untouched, so the recheck it was owed still fires now.
        expect(perApp['app-elapsed'].parkedUntil).toBe(elapsed)

        readJSONFile.mockResolvedValue(saved)
        const result = await shouldRunTask('claim-issue', 'app-elapsed')
        expect(result.shouldRun).toBe(true)
        expect(result.reason).toBe('perpetual-recheck')
      })
    })

    describe('getScheduleStatus per-app park aggregate', () => {
      it('aggregates per-app parks into taskStatus.perpetualStatus', async () => {
        const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
            'app-1': {
              lastRun: null,
              count: 0,
              parkedUntil: future,
              parkReason: 'no-actionable-issues',
              parkCounts: { open: 88, inFlight: 2, filtered: 86 },
              parkSkipCauses: { 'needs-input': 49, blocked: 17 }
            },
            'app-2': { lastRun: null, count: 0 }
          } } }
        })
        const status = await getScheduleStatus()
        const p = status.tasks['claim-issue'].perpetualStatus
        expect(p).toMatchObject({
          parkedAppCount: 1,
          trackedAppCount: 2,
          globalParked: false,
          nextRecheckAt: future,
          parkReason: 'no-actionable-issues',
          parkCounts: { open: 88, inFlight: 2, filtered: 86 },
          parkSkipCauses: { 'needs-input': 49, blocked: 17 }
        })
      })
    })

    // The escalated-stall diagnostic (#7551): a perpetual gate that skips
    // WITHOUT parking (a broken forge CLI) has no park record to hang its
    // reason on, so it needs its own persisted channel — one that survives a
    // process restart the same way a park does, and that coexists with a
    // "draining" (not parked) status.
    describe('recordPerpetualStall + getScheduleStatus stall surfacing', () => {
      it('stamps a stall on the per-app record without touching the park fields', async () => {
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0 } } } }
        })
        await recordPerpetualStall('claim-issue', 'app-1', { cli: 'gh', reason: 'gh-list-failed', detail: 'gh: authentication failed', consecutive: 3 })
        const status = await getScheduleStatus()
        const p = status.tasks['claim-issue'].perpetualStatus
        expect(p.stall).toMatchObject({ cli: 'gh', reason: 'gh-list-failed', detail: 'gh: authentication failed', consecutive: 3 })
        expect(p.globalParked).toBe(false)
        expect(p.parkedAppCount).toBe(0)
      })

      it('clears the stall when recorded with a null verdict', async () => {
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0 } } } }
        })
        await recordPerpetualStall('claim-issue', 'app-1', { cli: 'gh', reason: 'gh-list-failed', consecutive: 3 })
        await recordPerpetualStall('claim-issue', 'app-1', null)
        const status = await getScheduleStatus()
        expect(status.tasks['claim-issue'].perpetualStatus.stall).toBeNull()
      })

      it('survives being re-read as if from a process restart (persisted, not in-memory)', async () => {
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0 } } } }
        })
        await recordPerpetualStall('claim-issue', 'app-1', { cli: 'gh', reason: 'gh-list-failed', consecutive: 5 })
        // A fresh getScheduleStatus() call re-reads the persisted schedule from
        // scratch rather than any in-process cache, standing in for a restart.
        const status = await getScheduleStatus()
        expect(status.tasks['claim-issue'].perpetualStatus.stall).toMatchObject({ consecutive: 5 })
      })
    })

    // getScheduleStatus (UI rollup) and getUpcomingTasks (daemon wake-up) both
    // project the shared aggregatePerpetualParks rollup. These fixtures pin them
    // to the SAME park semantics — including the global-record inclusion rule
    // the two used to disagree on (status only ever folded in a global park that
    // hadn't elapsed; eligibility folded in any global record carrying a park).
    describe('perpetual park aggregate — getScheduleStatus and getUpcomingTasks agree', () => {
      const perpetualOf = async (taskType = 'claim-issue') =>
        (await getScheduleStatus()).tasks[taskType].perpetualStatus
      const upcomingOf = async (taskType = 'claim-issue') =>
        (await getUpcomingTasks(50)).find(t => t.taskType === taskType)

      it('every app parked: the status nextRecheckAt IS the upcoming eligibleAt', async () => {
        const soon = new Date(Date.now() + 30 * 60 * 1000).toISOString()
        const later = new Date(Date.now() + 6 * 60 * 60 * 1000).toISOString()
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0, parkedUntil: later, parkReason: 'no-actionable-issues' },
            'app-2': { lastRun: null, count: 0, parkedUntil: soon, parkReason: 'no-progress' }
          } } }
        })
        const p = await perpetualOf()
        const claim = await upcomingOf()
        expect(p).toMatchObject({ parkedAppCount: 2, trackedAppCount: 2, globalParked: false, nextRecheckAt: soon })
        expect(claim.status).toBe('scheduled')
        expect(new Date(claim.eligibleAt).toISOString()).toBe(p.nextRecheckAt)
      })

      it('an ELAPSED app park counts as due for both: ready upcoming, not parked in status', async () => {
        const past = new Date(Date.now() - 60 * 1000).toISOString()
        const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
            'app-1': { lastRun: null, count: 0, parkedUntil: past, parkReason: 'stale' },
            'app-2': { lastRun: null, count: 0, parkedUntil: future, parkReason: 'no-actionable-issues' }
          } } }
        })
        const p = await perpetualOf()
        const claim = await upcomingOf()
        expect(p).toMatchObject({ parkedAppCount: 1, trackedAppCount: 2, nextRecheckAt: future, parkReason: 'no-actionable-issues' })
        expect(claim.status).toBe('ready')
      })

      it('an own-parked GLOBAL record (no per-app) is a tracked scope for both', async () => {
        const future = new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString()
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {}, parkedUntil: future, parkReason: 'no-actionable-issues' } }
        })
        const p = await perpetualOf()
        const claim = await upcomingOf()
        expect(p).toMatchObject({ globalParked: true, parkedAppCount: 0, trackedAppCount: 0, nextRecheckAt: future, parkReason: 'no-actionable-issues' })
        expect(claim.status).toBe('scheduled')
        expect(new Date(claim.eligibleAt).toISOString()).toBe(p.nextRecheckAt)
      })

      it('an ELAPSED global park is due now for both (no lingering nextRecheckAt)', async () => {
        const past = new Date(Date.now() - 60 * 1000).toISOString()
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {}, parkedUntil: past, parkReason: 'no-actionable-issues' } }
        })
        const p = await perpetualOf()
        const claim = await upcomingOf()
        expect(p).toMatchObject({ globalParked: false, nextRecheckAt: null, parkReason: null })
        expect(claim.status).toBe('ready')
      })

      it('a global park is folded in alongside per-app parks when it is the soonest', async () => {
        const globalPark = new Date(Date.now() + 10 * 60 * 1000).toISOString()
        const appPark = new Date(Date.now() + 60 * 60 * 1000).toISOString()
        mockSchedule({
          tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
          executions: { 'task:claim-issue': { lastRun: null, count: 0, parkedUntil: globalPark, parkReason: 'global-idle', perApp: {
            'app-1': { lastRun: null, count: 0, parkedUntil: appPark, parkReason: 'no-actionable-issues' }
          } } }
        })
        const p = await perpetualOf()
        const claim = await upcomingOf()
        // parkReason still prefers the first parked APP over the global one.
        expect(p).toMatchObject({ globalParked: true, parkedAppCount: 1, trackedAppCount: 1, nextRecheckAt: globalPark, parkReason: 'no-actionable-issues' })
        expect(claim.status).toBe('scheduled')
        expect(new Date(claim.eligibleAt).toISOString()).toBe(p.nextRecheckAt)
      })

      it('no tracked scope at all: status reports nothing parked and upcoming stays ready', async () => {
        mockSchedule({ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } } })
        const p = await perpetualOf()
        const claim = await upcomingOf()
        expect(p).toMatchObject({ globalParked: false, parkedAppCount: 0, trackedAppCount: 0, nextRecheckAt: null, parkReason: null })
        expect(claim.status).toBe('ready')
      })
    })
  })
})

describe('boundParkedUntil', () => {
  const NOW = Date.parse('2026-01-10T00:00:00.000Z')
  const RECHECK = '2026-01-17T05:30:00.000Z' // a weekly cron fire

  it('shortens a park to a hold that lifts before the next recheck', () => {
    expect(boundParkedUntil(RECHECK, '2026-01-12T00:00:00.000Z', NOW)).toBe('2026-01-12T00:00:00.000Z')
  })

  it('keeps the recheck when the hold outlasts it', () => {
    // The bound only ever shortens — a later deadline must not stretch the park
    // past the cadence the user configured.
    expect(boundParkedUntil(RECHECK, '2026-02-01T00:00:00.000Z', NOW)).toBe(RECHECK)
  })

  it('ignores a bound that is absent or unparseable', () => {
    for (const bound of [null, undefined, '', 'soon', 42]) {
      expect(boundParkedUntil(RECHECK, bound, NOW)).toBe(RECHECK)
    }
  })

  it('ignores a bound that has already elapsed rather than parking in the past', () => {
    // A stale bound must not collapse the park to "retry immediately" — that
    // turns a converged drain into a hot loop against the same held branches.
    expect(boundParkedUntil(RECHECK, '2026-01-09T00:00:00.000Z', NOW)).toBe(RECHECK)
    expect(boundParkedUntil(RECHECK, new Date(NOW).toISOString(), NOW)).toBe(RECHECK)
  })

  it('returns the recheck unchanged when it is itself unparseable', () => {
    expect(boundParkedUntil('never', '2026-01-12T00:00:00.000Z', NOW)).toBe('never')
  })
})

// The code-quality lane's ranked triage output lives beside its execution
// record and surfaces on the Schedule card (#12085).
describe('recordRecommendedAudits', () => {
  it('stores the ranked list on the execution record and exposes it on schedule status', async () => {
    mockSchedule({ tasks: {}, executions: { 'task:code-quality': { lastRun: '2026-10-01T00:00:00Z', count: 2, perApp: {} } } })
    const recorded = await recordRecommendedAudits('code-quality', 'app-1', [
      'better-structural-drift — drifted registries: server/lib/navManifest.js',
      'ux — buried primary action: client/src/pages/Apps.jsx',
    ])
    expect(recorded).toMatchObject({ appId: 'app-1', items: [expect.stringContaining('better-structural-drift'), expect.stringContaining('ux —')] })
    expect(Date.parse(recorded.at)).toBeGreaterThan(0)
    const history = await getExecutionHistory('code-quality')
    expect(history.count).toBe(2)
    expect(history.recommendedAudits.items).toHaveLength(2)
    const status = await getScheduleStatus()
    expect(status.tasks['code-quality'].recommendedAudits).toEqual(history.recommendedAudits)
    expect(status.tasks['security'].recommendedAudits).toBeNull()
  })

  it('keeps the previous recommendation when a run produced none', async () => {
    const previous = { at: '2026-10-01T00:00:00Z', appId: 'app-1', items: ['ux — one'] }
    mockSchedule({ tasks: {}, executions: { 'task:code-quality': { lastRun: '2026-10-01T00:00:00Z', count: 1, perApp: {}, recommendedAudits: previous } } })
    expect(await recordRecommendedAudits('code-quality', 'app-1', [])).toBeNull()
    expect((await getExecutionHistory('code-quality')).recommendedAudits).toEqual(previous)
  })
})