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

refactor: split task schedule service modules (#4897)

Adam Eivy22c48bfd15aa
diff --git a/server/routes/apps/taskTypes.js b/server/routes/apps/taskTypes.js
index 3f870d5c43..6f6ee619ea 100644
--- a/server/routes/apps/taskTypes.js
+++ b/server/routes/apps/taskTypes.js
@@ -23,7 +23,7 @@ import { listWorkItems } from '../../services/workItems.js';
import { resolveClaimWorkMetadata, resolveClaimAuthorFilter } from '../../services/cosTaskGenerator.js';
import { parseCronToNextRun } from '../../services/eventScheduler.js';
import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
-import { SELF_IMPROVEMENT_TASK_TYPES } from '../../services/taskSchedule.js';
+import { SELF_IMPROVEMENT_TASK_TYPES } from '../../services/taskScheduleRegistry.js';
import { summarizeOutcomeStats, computePostApprovalCompletion, computeProposalOutcomeMetrics, computeApprovalFunnel } from '../../services/layeredIntelligence.js';
import { listOutcomesResult } from '../../services/layeredIntelligenceOutcomes.js';
import { summarizeRejectionReasons } from '../../services/layeredIntelligenceRejections.js';
diff --git a/server/routes/apps/taskTypes.test.js b/server/routes/apps/taskTypes.test.js
index 79df80196e..01e68af17c 100644
--- a/server/routes/apps/taskTypes.test.js
+++ b/server/routes/apps/taskTypes.test.js
@@ -3,7 +3,7 @@ import express from 'express';
import { request } from '../../lib/testHelper.js';
import taskTypeRoutes from './taskTypes.js';
-// Only the apps service is mocked; SELF_IMPROVEMENT_TASK_TYPES (taskSchedule) and
+// Only the apps service is mocked; SELF_IMPROVEMENT_TASK_TYPES (taskScheduleRegistry) and
// parseCronToNextRun (eventScheduler) run for real, as do the sanitizeTaskMetadata
// validators.
vi.mock('../../services/apps.js', () => ({
diff --git a/server/services/apps.js b/server/services/apps.js
index 76b8dfbd37..3e67fe93b0 100644
--- a/server/services/apps.js
+++ b/server/services/apps.js
@@ -5,7 +5,7 @@ import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js
import { PORTOS_APP_ID } from '../lib/appIdentity.js';
import { NON_PM2_TYPES, usesPm2, isDesktopType } from './streamingDetect.js';
import { listProcessesStrict } from './pm2.js';
-import { SELF_IMPROVEMENT_TASK_TYPES } from './taskSchedule.js';
+import { SELF_IMPROVEMENT_TASK_TYPES } from './taskScheduleRegistry.js';
import { sanitizeTaskMetadata } from '../lib/validation.js';
import { resolveAppWorkTracker } from '../lib/workTracker.js';
import { PORTS } from '../lib/ports.js';
diff --git a/server/services/apps.layeredIntelligence.test.js b/server/services/apps.layeredIntelligence.test.js
index fefc043e33..9b0d6577ae 100644
--- a/server/services/apps.layeredIntelligence.test.js
+++ b/server/services/apps.layeredIntelligence.test.js
@@ -15,7 +15,7 @@ vi.mock('../lib/fileUtils.js', () => ({
vi.mock('../../lib/tailscale-https.js', () => ({ hasTailscaleCert: () => false }));
vi.mock('../../lib/certPaths.js', () => ({ certPaths: () => ({ dir: '/mock' }) }));
vi.mock('../lib/ports.js', () => ({ PORTS: { API: 5555, API_LOCAL: 5553, UI: 5554, COS: 5556, AUTOFIXER: 5557, AUTOFIXER_UI: 5558, CDP: 5559, CDP_HEALTH: 5560 } }));
-vi.mock('./taskSchedule.js', () => ({ SELF_IMPROVEMENT_TASK_TYPES: [] }));
+vi.mock('./taskScheduleRegistry.js', () => ({ SELF_IMPROVEMENT_TASK_TYPES: [] }));
vi.mock('./pm2.js', () => ({ listProcessesStrict: vi.fn().mockResolvedValue([]) }));
import { getAppLayeredIntelligenceConfig, updateAppLayeredIntelligence, createApp, getAppById, invalidateCache, PORTOS_APP_ID } from './apps.js';
diff --git a/server/services/apps.test.js b/server/services/apps.test.js
index 9ae9d79385..151571ceed 100644
--- a/server/services/apps.test.js
+++ b/server/services/apps.test.js
@@ -21,10 +21,13 @@ vi.mock('../lib/ports.js', () => ({
}));
vi.mock('./taskSchedule.js', () => ({
- SELF_IMPROVEMENT_TASK_TYPES: [],
resetExecutionHistory: vi.fn().mockResolvedValue({ error: 'No execution history found' }),
}));
+vi.mock('./taskScheduleRegistry.js', () => ({
+ SELF_IMPROVEMENT_TASK_TYPES: [],
+}));
+
vi.mock('./pm2.js', () => ({
// Strict variant: resolves an array on success (incl. []), or null on a
// failed PM2 read. The status getters use this, not the forgiving listProcesses.
diff --git a/server/services/taskPromptDefaults.js b/server/services/taskPromptDefaults.js
index b9a6d200e1..e5b4ea3644 100644
--- a/server/services/taskPromptDefaults.js
+++ b/server/services/taskPromptDefaults.js
@@ -4,8 +4,9 @@
* Owns the default prompt catalog and the distribution-model compatibility
* constants for scheduled improvement tasks. This module is a pure data leaf:
* it imports nothing from the rest of the task-scheduling graph, so both
- * taskPromptService.js (the getters) and taskSchedule.js (the auto-upgrade
- * machinery) can import it statically without forming a circular import.
+ * taskPromptService.js (the getters), taskSchedule.js (status rendering), and
+ * taskScheduleStore.js (the auto-upgrade machinery) can import it statically
+ * without forming a circular import.
*
* The content lives in ./taskPromptDefaults/ — prompts.js (current defaults),
* versions.js (PROMPT_VERSIONS + audit anchor), previousDefaults.js (prior
diff --git a/server/services/taskPromptService.js b/server/services/taskPromptService.js
index 11579fa375..5c5b0a990f 100644
--- a/server/services/taskPromptService.js
+++ b/server/services/taskPromptService.js
@@ -11,8 +11,10 @@
* Import graph (issue #1083 — no cycles):
* taskPromptDefaults.js (data leaf, imports only PORTOS_API_URL)
* ↑ static ↑ static
- * taskPromptService.js taskSchedule.js
- * └──────── static ───────┘ (this module imports getTaskInterval from taskSchedule)
+ * taskPromptService.js taskScheduleStore.js
+ * │ ↑ static
+ * └──── static ─── taskSchedule.js
+ * (this module imports getTaskInterval from the compatibility facade)
*
* The prior split papered over a static circular import (taskSchedule ⇄
* taskPromptService) with a lazy `await import('./taskSchedule.js')` inside
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index afa9db652a..6bfcb32298 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -19,96 +19,54 @@
* perpetual gate in cosTaskGenerator.generateManagedAppImprovementTaskForType.
*/
-import { existsSync } from 'fs';
-import { join } from 'path';
import { cosEvents, emitLog } from './cosEvents.js';
-import { atomicWrite, DAY, ensureDir, HOUR, readJSONFile, PATHS, safeDate } from '../lib/fileUtils.js';
-import { BRANCHES_PER_AGENT_MAX, BRANCHES_PER_AGENT_MIN } from '../lib/cosValidation.js';
-import { isPlainObject } from '../lib/objects.js';
+import { DAY, safeDate } from '../lib/fileUtils.js';
import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';
import { getAdaptiveCooldownMultiplier } from './taskLearning.js';
import { isTaskTypeEnabledForApp, getAppTaskTypeInterval, getAppTaskTypeIntervalMs, getActiveApps, getAppTaskTypeOverrides, clearAllPrWatcherState } from './apps.js';
import { loadState, isImprovementEnabled } from './cosState.js';
import { getUserTimezone, getLocalParts } from '../lib/timezone.js';
import { parseCronToNextRun, parseCronToPrevRun } from './eventScheduler.js';
-// The prompt catalog + compat constants live in the taskPromptDefaults.js data
-// leaf (issue #1083); the prompt getters live in taskPromptService.js (split
-// out in issue #744). loadSchedule()/getScheduleStatus() below consume the
-// prompt-version machinery (DEFAULT_TASK_PROMPTS / PROMPT_VERSIONS /
-// PREVIOUS_DEFAULT_PROMPTS) for the auto-upgrade path, so import those from the
-// leaf here. Importing from the leaf (not taskPromptService) is what keeps the
-// graph acyclic: taskPromptService imports getTaskInterval from THIS module, so
-// this module must not import taskPromptService back. PROMPT_VERSIONS and
-// REFERENCE_WATCH_AUDITED_VERSION are part of taskSchedule.js's public API
-// (consumers import them from here), so they're re-exported below;
-// DEFAULT_TASK_PROMPTS and PREVIOUS_DEFAULT_PROMPTS stay internal.
-import {
- DEFAULT_TASK_PROMPTS,
- PROMPT_VERSIONS,
- REFERENCE_WATCH_AUDITED_VERSION,
- PREVIOUS_DEFAULT_PROMPTS
-} from './taskPromptDefaults.js';
import { isAuditTaskType, defaultFileIssuesFor } from '../lib/auditCatalog.js';
-
-// Re-export the prompt-version constants so existing importers of taskSchedule.js
-// are unaffected. The prompt GETTERS (getDefaultPrompt / getTaskPrompt /
-// getStagePrompt) moved to taskPromptService.js and are NO LONGER re-exported
-// here — import them from './taskPromptService.js' directly (re-exporting them
-// would re-form the taskSchedule ⇄ taskPromptService cycle this split removed).
-export { PROMPT_VERSIONS, REFERENCE_WATCH_AUDITED_VERSION };
-
-const DATA_DIR = PATHS.cos;
-const SCHEDULE_FILE = join(DATA_DIR, 'task-schedule.json');
-
-// Interval type constants
-export const INTERVAL_TYPES = {
- ROTATION: 'rotation', // Default: runs in normal task rotation
- DAILY: 'daily', // Runs once per day
- WEEKLY: 'weekly', // Runs once per week
- ONCE: 'once', // Runs once per app or globally
- ON_DEMAND: 'on-demand', // Only runs when manually triggered
- CUSTOM: 'custom', // Custom interval in milliseconds
- CRON: 'cron', // Cron expression schedule
- PERPETUAL: 'perpetual' // Drain back-to-back until a work-detector idles, then park on a recheck cadence
-};
-
-const WEEK = 7 * DAY;
-
-// Default cadence a parked perpetual task waits before re-probing its
-// work-detector, when neither `recheckCron` nor `recheckIntervalMs` is set.
-const DEFAULT_PERPETUAL_RECHECK_MS = DAY;
-
-// ── Type-level consecutive-failure backoff (#2616) ────────────────────────────
-// Distinct from the per-INSTANCE retry ladder (MAX_TASK_RETRIES /
-// MAX_TOTAL_SPAWNS in agentErrorAnalysis.js), which blocks a SINGLE task after
-// too many failures. This ledger tracks a task TYPE (per app + global) so a
-// permanently-broken scheduled type slows down and eventually auto-parks instead
-// of burning provider quota on schedule forever. The ledger lives on the
-// execution record alongside `lastRun` (survives restarts; per-install runtime
-// state, never synced).
-export const FAILURE_BACKOFF_BASE_MS = HOUR; // scaled by 2^n (n = consecutiveFailures)
-export const FAILURE_BACKOFF_CAP_MS = DAY; // cap the escalation
-export const FAILURE_PARK_THRESHOLD = 5; // auto-park after N consecutive failures
-
-// The full set of ledger fields, kept as one list so the record/reset/clear
-// paths can't drift from what recordTaskTypeFailure writes.
-const FAILURE_LEDGER_FIELDS = [
- 'consecutiveFailures',
- 'lastFailureAt',
- 'lastErrorCategory',
- 'failureParkedAt',
- 'failureParkReason'
-];
-
-/**
- * Escalating failure cooldown: 2^n × base, capped. n=0 → 0 (no cooldown).
- * Pure — exported for direct unit testing.
- */
-export function computeFailureBackoffMs(consecutiveFailures, baseMs = FAILURE_BACKOFF_BASE_MS, capMs = FAILURE_BACKOFF_CAP_MS) {
- const n = Number(consecutiveFailures) || 0;
- if (n <= 0) return 0;
- return Math.min(baseMs * Math.pow(2, n), capMs);
-}
+import { DEFAULT_TASK_PROMPTS } from './taskPromptDefaults.js';
+import {
+ DEFAULT_PERPETUAL_RECHECK_MS,
+ INTERVAL_TYPES,
+ ON_DEMAND_ORIGINS,
+ WEEK,
+ isRefillRequest
+} from './taskScheduleConstants.js';
+import {
+ DEFAULT_TASK_INTERVALS,
+ MANAGED_AGENT_OPTIONS,
+ getTaskTypeDescription,
+ enforceBranchReconcileBatch,
+ enforceManagedAgentOptions
+} from './taskScheduleRegistry.js';
+import { loadSchedule, saveSchedule } from './taskScheduleStore.js';
+import {
+ clearFailureLedgerFields,
+ clearTaskTypeFailurePark,
+ clearTaskTypeFailureParkNotification,
+ computeFailureBackoffMs
+} from './taskScheduleBackoff.js';
+
+export { PROMPT_VERSIONS, REFERENCE_WATCH_AUDITED_VERSION } from './taskPromptDefaults.js';
+export {
+ INTERVAL_TYPES, ON_DEMAND_ORIGINS, isRefillRequest
+} from './taskScheduleConstants.js';
+export {
+ DEFAULT_BRANCHES_PER_AGENT, DEFAULT_TASK_INTERVALS, MANAGED_AGENT_OPTIONS,
+ PERPETUAL_DRAIN_DISPATCH_CAP, SELF_IMPROVEMENT_TASK_TYPES, TASK_TYPE_DESCRIPTIONS,
+ stripManagedAgentOptionsFromOverride
+} from './taskScheduleRegistry.js';
+export { loadSchedule } from './taskScheduleStore.js';
+export {
+ FAILURE_BACKOFF_BASE_MS, FAILURE_BACKOFF_CAP_MS, FAILURE_PARK_THRESHOLD,
+ clearTaskTypeFailurePark, computeFailureBackoffMs, recordTaskTypeFailure,
+ recordTaskTypeSuccess
+} from './taskScheduleBackoff.js';
+export { addTemplateTask, deleteTemplateTask, getTemplateTasks } from './taskScheduleTemplates.js';
/**
* Get learning-adjusted interval for a task type
@@ -179,668 +137,6 @@ async function getPerformanceAdjustedInterval(taskType, baseIntervalMs) {
};
}
-// Unified default interval settings for all task types
-export const SELF_IMPROVEMENT_TASK_TYPES = [
- 'security', 'code-quality', 'test-coverage', 'performance',
- 'accessibility', 'branch-reconcile', 'issue-reconcile', 'console-errors', 'dependency-updates', 'documentation',
- 'ui-bugs', 'mobile-responsive', 'feature-ideas', 'plan-task', 'claim-issue', 'claim-work', 'error-handling',
- 'typing', 'release-check', 'pr-reviewer', 'code-reviewer-a', 'code-reviewer-b',
- 'jira-sprint-manager', 'jira-status-report', 'do-replan',
- // Polls the app's GitHub repo for pull requests newly opened against the
- // default branch and dispatches an agent (running the configurable
- // pr-watcher prompt) for each one. `taskMetadata.prAuthorFilter` gates on
- // PR authorship (self / others / any). See server/services/prWatcher.js.
- 'pr-watcher',
- // Watches `referenceRepos` configured on the app — fetches each upstream
- // repo, finds commits since lastReviewedSha, and appends slug-tagged
- // `[ref-watch-…]` checklist items to the app's PLAN.md for `/claim` /
- // `plan-task` to pick up. No source-code edits, no separate review file.
- 'reference-watch',
- // Walks the running app UI with a UX reviewer's eye (Playwright MCP) against a
- // named checklist — buried primary actions, dead-end empty/error states,
- // affordances that drift between sibling screens. Defaults to filing tracker
- // issues (`fileIssues: true`); the user can flip it to implement. Deliberately
- // narrower than its siblings: raw console errors belong to `ui-bugs`, viewport
- // breakage to `mobile-responsive`, ARIA/contrast/keyboard to `accessibility`.
- 'ux',
- // Quota-burn `data-safety-audit` counterpart. Migrations, schema parity, and
- // cross-version compatibility. Defaults to file-issues (safer for unattended).
- 'data-safety',
- // Quota-burn `simplify-audit` counterpart. Dead code, unused exports, and
- // copy-paste drift — distinct from `code-quality` (which is the broader DRY /
- // long-function / TODO pass). Defaults to file-issues.
- 'simplify',
- // Audits `git stash list` for {appName} and drops entries already superseded
- // by (or a subset of) current `main`/HEAD, or that are stale/abandoned scratch
- // work — without discarding real unlanded work. On-demand only (no cadence
- // makes sense for something the user notices ad hoc); non-committing
- // coordinator posture, since a cleared stash is a repo-hygiene side effect,
- // never a commit. See DEFAULT_TASK_PROMPTS['stash-cleanup'].
- 'stash-cleanup',
- // PortOS-only: researches the current best local LLMs per category and
- // refreshes the bundled suggested-models catalog (server/lib/localLlmCatalog.js)
- // + the editorial family ranking (server/lib/localModelHeuristics.js), opening a
- // PR. No-ops on any repo lacking that catalog file, so enabling it on a
- // non-PortOS app does nothing. See DEFAULT_TASK_PROMPTS['refresh-local-llm-catalog'].
- 'refresh-local-llm-catalog',
- // The planning-only sibling of `feature-ideas`: runs the same brainstorm
- // research (PRD.md/GOALS.md or repository docs, changelog/git log, and
- // closed-unmerged PRs)
- // but NEVER implements — its deliverable is ONE decision-complete feature
- // plan filed into the app's resolved work tracker via {trackerInstructions}
- // (PLAN.md checklist item / GitHub / GitLab issue / JIRA ticket), which the
- // claim flows pick up later. Always-filing tracker-filing type
- // (TRACKER_FILING_PRESETS['plan-feature']), like reference-watch/repo-study.
- 'plan-feature',
- // layered-intelligence is a PROGRAMMATIC-I/O task: it spawns a NORMAL reasoning
- // agent (visible in the CoS queue + Active Agents, TUI-attachable) with two
- // deterministic hooks around it — buildTaskInput gathers the app's goals +
- // telemetry + open issues and builds the reasoning prompt; processTaskOutput
- // validates the agent's `.agent-done` payload, dedups, and files ONE tracker
- // issue. The agent runs in a THROWAWAY worktree (discardWorktree) that is never
- // committed/merged, so the reasoner still can't write code — the structured
- // payload is its only channel out. Scheduling (enabled/interval/provider/model)
- // lives in the per-app taskTypeOverrides; behavior (sources/scopes/rules/handoff)
- // stays in app.layeredIntelligence. Has NO DEFAULT_TASK_PROMPTS entry — the
- // buildTaskInput hook renders the prompt. See taskTypeHooks.js +
- // autonomousJobs/layeredIntelligenceHooks.js.
- 'layered-intelligence',
- // NOTE: `quota-burn` used to live here as a per-app perpetual task type. It is
- // now ONE install-level loop (services/quotaBurnRunner.js) configured on the
- // Quota Burn page — the burn plan is machine-local, and its jobs name which
- // managed app (if any) the work targets. Migration 221 moves existing per-app
- // overrides across; do not re-add it as a scheduled type.
-];
-
-// Shared taskMetadata posture for the NON-COMMITTING COORDINATOR types
-// (NON_COMMITTING_COORDINATOR_TASK_TYPES in taskTypeHooks.js — branch-reconcile /
-// issue-reconcile / branch-cleanup / jira-status-report / release-check). Each delivers its work
-// as a SIDE EFFECT in the app's live checkout — a deleted branch, a merged PR, a
-// relabeled issue, a posted report — and by design produces no commit of its own.
-// Two code-shipping criteria therefore have to be switched off or every SUCCESSFUL
-// run is recorded as a failure:
-// * `useWorktree`/`openPR` — explicitly false (not merely absent) so
-// applyAppWorktreeDefault's `=== undefined` checks can't fill them from the
-// app's `defaultOpenPR`/`defaultUseWorktree`. A worktree these tasks never cd
-// into is at best unused and at worst harmful (it hides sibling refs the
-// reconcile scan must inspect), and the implied PR expectation fails the run at finalize
-// with `pr-missing` — there is no code to open a PR for. Locked in
-// MANAGED_AGENT_OPTIONS below so a per-app override can't re-attach them.
-// `readOnly: true` is NOT a substitute: it gates worktree CREATION
-// (agentWorkspacePrep.js) but the PR-claim check reads `metadata.openPR`
-// directly (agentTuiSpawning.js).
- // * `worktreeChangesExpected` — a clean tree IS the success shape here, so the
- // task's deliverable posture must record that this is not code work.
-// A guard test in taskSchedule.test.js asserts every member of that set carries
-// this posture, so a new coordinator type can't be added to one list only.
-const NON_COMMITTING_COORDINATOR_METADATA = { useWorktree: false, openPR: false, worktreeChangesExpected: false };
-// Migration 274 removes branch-cleanup from new schedules, but a partially
-// upgraded install may still load its stored task before the migration runs.
-// Keep its safety posture available without making it a newly-shipped task.
-const LEGACY_MANAGED_TASK_METADATA = {
- 'branch-cleanup': NON_COMMITTING_COORDINATOR_METADATA
-};
-
-// Shared config for code-reviewer-a and code-reviewer-b (two instances for independent provider/model configuration)
-const CODE_REVIEWER_INTERVAL = { type: INTERVAL_TYPES.WEEKLY, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: true, simplify: true, pipeline: { stages: [{ name: 'Codebase Review', promptKey: 'code-reviewer-review', readOnly: true, providerId: null, model: null, precondition: { fileNotExists: 'REVIEW.md' } }, { name: 'Triage & Implement', promptKey: 'code-reviewer-implement', readOnly: false, providerId: null, model: null, precondition: { fileExists: 'REVIEW.md' } }] } } };
-
-/**
- * Default `drainDispatchCap` for the reconcile drains: how many times a perpetual
- * drain may dispatch back-to-back before it is parked regardless of how much
- * progress it reports.
- *
- * The `lastActionableSignature` guard stops the drain only when a full cycle
- * changes NOTHING. It cannot stop a drain whose set keeps changing without ever
- * emptying — a branch that oscillates between two states, a coordinator that opens
- * a PR one run and closes it the next, a repo where new work arrives as fast as it
- * is finished. Those are indistinguishable from healthy progress one cycle at a
- * time, and on 2026-08-12 that shape ran ~40 coordinator agents between 05:19 and
- * 08:47 against the same two branches. So progress buys more cycles, not unlimited
- * ones: past the cap the drain parks until its recheck cadence, which is a delay,
- * never a dropped item — the branches are still there and the next recheck sees
- * them. Five is enough for a legitimately long drain (open PR → CI → merge →
- * cleanup) to finish a couple of branches per window.
- *
- * The count is very nearly "consecutive dispatches": every terminal park and every
- * manual re-run zero it. The one gap is a FAILED run — it neither refills nor
- * parks, so its spent dispatches carry into the next scheduled window and that
- * window caps early. It self-heals within one window (the next park zeroes it), and
- * erring toward capping early is the safe direction for a runaway guard.
- *
- * Why the cap is PER TYPE (`drainDispatchCap`) and not one global number: five is
- * ample for finishing branches (a handful per day) but would throttle a HEALTHY
- * claim-issue drain to five issues per recheck window — a real regression for a
- * drain the user relies on running productively overnight. So the claim drains
- * ship without the key at all (absent/`null` ⇒ unbounded, their work-detector's
- * idle park remains the only brake) and only the reconcile scans carry a number.
- */
-export const PERPETUAL_DRAIN_DISPATCH_CAP = 5;
-export const DEFAULT_BRANCHES_PER_AGENT = 3;
-
-export const DEFAULT_TASK_INTERVALS = {
- 'security': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
- 'code-quality': { type: INTERVAL_TYPES.ROTATION, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
- 'test-coverage': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
- 'performance': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
- 'accessibility': { type: INTERVAL_TYPES.ONCE, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
- // branch-reconcile first removes fully-merged, clean orphaned worktrees and
- // branches, then finishes THIS machine's remaining in-flight LOCAL branches
- // per app (open a PR for pushed-but-unopened work, resolve merge conflicts,
- // drive the review loop, auto-merge when green). PERPETUAL (drain-until-done):
- // the generator runs the deterministic reconcile every dispatch, and dispatches
- // the coordinator agent only while actionable in-flight branches remain — then
- // PARKS on the daily recheckCron. The action toggles (cleanupMerged / openPr /
- // resolveConflicts / autoMerge / finishAbandoned) are per-app taskMetadata
- // booleans (each ON unless explicitly false); `finishAbandoned` covers the work
- // a dead agent left UNCOMMITTED in its worktree — commit + ship it, or report it
- // as unfinished. `branchesPerAgent` bounds each coordinator prompt to a
- // prioritized batch so a large backlog drains across several agents. It is
- // independently overridable per app. useWorktree/openPR are LOCKED off
- // (MANAGED_AGENT_OPTIONS):
- // the coordinator runs in the app's live checkout so it can see + operate on the
- // sibling worktrees; a CoS-managed worktree would hide the branches and could
- // trigger cleanupAgentWorktree's auto-merge. Its edits likewise land in those
- // SIBLING worktrees, never in its own cwd — hence the shared non-committing
- // -coordinator posture above. Off by default — enabling it is the user's
- // explicit consent to let it drive PRs on a schedule.
- 'branch-reconcile': { type: INTERVAL_TYPES.PERPETUAL, enabled: false, providerId: null, model: null, prompt: null, recheckCron: '0 3 * * *', drainDispatchCap: PERPETUAL_DRAIN_DISPATCH_CAP, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA, cleanupMerged: true, openPr: true, resolveConflicts: true, autoMerge: true, finishAbandoned: true, branchesPerAgent: DEFAULT_BRANCHES_PER_AGENT } },
- // issue-reconcile heals ZOMBIE issues: open + `in-progress` (claimed) yet with
- // their PR already MERGED and no live claim anywhere — a partial ship left the
- // claim marker on, so the queue (which skips `in-progress`) never re-picks the
- // remaining scope. PERPETUAL (drain-until-done): the generator runs the
- // deterministic gh/git scan every dispatch and dispatches the coordinator agent
- // only while zombies remain — then PARKS on the daily recheckCron (offset an
- // hour after branch-reconcile so merged-branch cleanup lands first). The
- // coordinator applies the partial-ship hybrid per zombie (close + file a scoped
- // follow-up when the remainder is separable, else comment "done/remaining" +
- // release the claim). `autoClose` (ON unless explicitly false) is the only
- // per-app toggle: OFF forbids closing/filing — comment + unlabel only.
- // The coordinator works purely over `gh` — no code changes, no worktree, and
- // issue-state mutation is its whole deliverable — hence the shared
- // non-committing-coordinator posture above. Off by default — enabling it is the
- // user's explicit consent to let it mutate issue state on a schedule.
- 'issue-reconcile': { type: INTERVAL_TYPES.PERPETUAL, enabled: false, providerId: null, model: null, prompt: null, recheckCron: '0 4 * * *', drainDispatchCap: PERPETUAL_DRAIN_DISPATCH_CAP, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA, autoClose: true } },
- 'console-errors': { type: INTERVAL_TYPES.ROTATION, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
- 'dependency-updates': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null },
- 'documentation': { type: INTERVAL_TYPES.ONCE, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
- 'ui-bugs': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
- 'mobile-responsive': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
- // feature-ideas waits for do-replan so new work is grounded in a fresh PLAN.md
- // that already accounts for any in-flight or unmerged work.
- 'feature-ideas': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, runAfter: ['do-replan'], taskMetadata: { useWorktree: true, openPR: true, simplify: true } },
- // plan-task is a strict executor of PLAN.md items — no brainstorm fallback, no
- // runAfter deps. Picks the next unchecked item, implements it, and removes it
- // from PLAN.md in the same commit (changelog + git log are the audit trail).
- // plan-task (prompt v5+) drives the /claim flow itself — the agent creates its OWN `claim/<slug>` worktree, opens the PR, merges via `gh pr merge`, and cleans up.
- // Both `useWorktree` and `openPR` are OFF on the CoS side:
- // * `useWorktree: false` — CoS pre-creating a worktree under `cos/<task>/<agent>` would hide the slug from the in-flight branch scan AND trigger
- // `cleanupAgentWorktree`'s auto-merge into whatever the source repo's HEAD is on (clobbering a TUI user's in-flight claim branch).
- // * `openPR: false` — keeps the cos.js "openPR implies useWorktree" invariant from forcing useWorktree back on. The agent opens its own PR via `gh pr create`
- // and merges via `gh pr merge`, so CoS doesn't need to.
- // `claimFlow: true` is the lifecycle marker. It is deliberately separate from
- // `openPR`: the former tells prompt/completion handling that the claim prompt
- // owns push → PR/MR → review → merge/cleanup, while the latter tells CoS whether
- // it should provision and publish a managed worktree. Conflating them sent
- // claim agents into the generic commit-only handoff (#4153).
- // The agent runs in the source repo's working directory; `git worktree add` doesn't touch that working tree, so it's safe even with uncommitted user changes.
- 'plan-task': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: false, openPR: false, claimFlow: true, simplify: true } },
- // claim-issue drives the /claim --issues flow — the agent creates its OWN
- // claim/issue-<num> worktree, opens the PR (Closes #<num>), merges via
- // `gh pr merge`, and cleans up. Both `useWorktree` and `openPR` are OFF on the
- // CoS side for the SAME reasons as plan-task (a CoS-managed worktree under
- // cos/<task>/<agent> would hide the issue-<num> slug from the in-flight scan
- // and trigger cleanupAgentWorktree's auto-merge into the source repo's HEAD).
- // `issueAuthorFilter` gates which issues are claimable: 'self' (default, the
- // slashdo `/do:next --self` security boundary) only claims issues YOU filed
- // (`@me`); 'collaborators' widens that to you plus every account with repo
- // access (GitHub collaborators / GitLab project members); 'owner' only claims
- // issues the repo owner filed; 'any' claims any open issue. Per-app override
- // supported via taskTypeOverrides.
- // `issueExcludeLabels` (default `[]`) lists ADDITIONAL labels to skip when
- // auto-claiming, on top of the fixed NON_ACTIONABLE_ISSUE_LABELS set
- // (perpetualWork.js) — e.g. `good first issue`, to leave those open for human
- // contributors. Per-app override supported via taskTypeOverrides, like
- // `issueAuthorFilter`.
- 'claim-issue': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: false, openPR: false, claimFlow: true, simplify: true, issueAuthorFilter: 'self', issueExcludeLabels: [] } },
- // claim-work is the SINGLE-SOURCE router: one toggle per app that ships the
- // next work item from whatever tracker the app is configured for
- // (app.workTracker, default 'auto' → resolved from the git origin host). At
- // dispatch the generator resolves the tracker and delegates to the matching
- // prompt body — plan→plan-task, github→claim-issue, gitlab→claim-issue-gitlab,
- // jira→claim-issue-jira — so the agent still creates its OWN worktree and
- // opens its OWN MR/PR. (jira routes to the per-ticket claim-issue-jira flow,
- // NOT the broader jira-sprint-manager triage job, which stays standalone.)
- // Both `useWorktree` and `openPR` are OFF on the CoS side
- // for the SAME reasons as plan-task/claim-issue (a CoS-managed worktree would
- // hide the claim slug and trigger cleanupAgentWorktree's auto-merge).
- // `issueAuthorFilter` / `issueExcludeLabels` apply only when the resolved
- // tracker is a forge (github/gitlab); both are inert for plan/jira.
- 'claim-work': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: false, openPR: false, claimFlow: true, simplify: true, issueAuthorFilter: 'self', issueExcludeLabels: [] } },
- 'error-handling': { type: INTERVAL_TYPES.ROTATION, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
- 'typing': { type: INTERVAL_TYPES.ONCE, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
- // Release-check inspects and mutates release state (for example, the main →
- // release PR) rather than producing source commits. It must run from the app's
- // live main checkout so its branch/ref checks describe the real release flow;
- // a CoS worktree hides that checkout and creates an irrelevant task branch.
- 'release-check': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA } },
- // stash-cleanup triages `git stash list` and drops what's superseded/stale,
- // leaving real unlanded work in place for the user to recover by hand. It
- // runs in the app's live checkout (never a CoS worktree — a stash is a
- // property of the checkout it was taken in) and, like the other coordinators,
- // ships no code of its own. On-demand only: unlike branch/issue reconcile,
- // there's no useful cadence for a stash a user hasn't necessarily touched
- // since the last run — they trigger it when they notice stash clutter.
- 'stash-cleanup': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA } },
- 'pr-reviewer': { type: INTERVAL_TYPES.CUSTOM, intervalMs: 7200000, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null, taskMetadata: { readOnly: true, pipeline: { stages: [{ name: 'Security Scan', promptKey: 'pr-reviewer-security', readOnly: true }, { name: 'Code Review & Merge', promptKey: 'pr-reviewer-review', readOnly: false }] } } },
- 'code-reviewer-a': { ...CODE_REVIEWER_INTERVAL },
- 'code-reviewer-b': { ...CODE_REVIEWER_INTERVAL },
- 'jira-sprint-manager': { type: INTERVAL_TYPES.DAILY, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: true, simplify: true } },
- // jira-status-report posts its report to JIRA and edits nothing in the repo, so it
- // takes the shared non-committing-coordinator posture above. `readOnly: true` alone
- // was NOT enough: it skips worktree creation but leaves `openPR` free to be filled
- // from the app's `defaultOpenPR`, and the finalize-time PR-claim check reads
- // `metadata.openPR` directly — scoring a posted report as `pr-missing`.
- 'jira-status-report': { type: INTERVAL_TYPES.WEEKLY, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA, readOnly: true } },
- // do-replan audits PLAN.md after open PRs and stale branches have been cleaned up,
- // so the plan reflects what actually merged.
- 'do-replan': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, runAfter: ['pr-reviewer', 'branch-reconcile'], taskMetadata: { useWorktree: true, openPR: true } },
- // Writable — the v2 reference-watch prompt (PROMPT_VERSIONS['reference-watch'] = 2)
- // instructs the agent to APPEND slug-tagged `[ref-watch-…]` checklist items to
- // PLAN.md and commit them. `readOnly: true` would inject the "do not modify or
- // commit files" guard into the system prompt and the agent would refuse to write
- // the PLAN entries — defeating the whole flow. Worktree off because the task body
- // itself reads from data/cos/reference-repos (managed clones the user can't
- // accidentally clobber) and the PLAN.md write is small enough that the in-place
- // commit on the source repo is simpler than a worktree round-trip. Mirrors the
- // on-commit trigger path in referenceRepos.js#triggerReferenceAnalysis.
- // `readOnly` is coupled to PROMPT_VERSIONS['reference-watch'] — see
- // REFERENCE_WATCH_AUDITED_VERSION above; bumping the prompt version requires
- // re-auditing this default (a guard test in taskSchedule.test.js enforces it).
- 'reference-watch': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { readOnly: false } },
- // ux audits the RUNNING app UI. Defaults to filing tracker issues
- // (`fileIssues: true`); flip that off to implement. `readOnly: false` so the
- // PLAN.md path can commit checklist items / forge paths can `gh issue create`.
- // Off by default (AI Provider Usage Policy — enabling it is the user's consent
- // to a weekly browser-driving LLM run).
- 'ux': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: true, useWorktree: false, openPR: false, readOnly: false } },
- // data-safety / simplify are the scheduled counterparts of the quota-burn
- // `data-safety-audit` and `simplify-audit` presets. New types default to
- // file-issues so an unattended enable doesn't land code. Off by default.
- 'data-safety': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },
- 'simplify': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },
- // pr-watcher polls for newly-opened PRs, so it runs on a short custom
- // interval rather than the loose rotation/daily cadence. 30 min keeps the
- // gh polling cheap while still reacting to a PR within one cycle. Default
- // gate is `prAuthorFilter: 'any'` (react to every PR); the operator narrows
- // it to 'self' or 'others' in the schedule UI. `readOnly: false` so a
- // customized prompt can make changes if the operator wants — the shipped
- // default prompt only reviews + comments.
- 'pr-watcher': { type: INTERVAL_TYPES.CUSTOM, intervalMs: 1800000, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { prAuthorFilter: 'any', readOnly: false } },
- // refresh-local-llm-catalog maintains PortOS's own bundled suggested-models
- // catalog. CoS manages the worktree + PR (like feature-ideas/do-replan) — the
- // agent only edits the catalog file. Weekly is generous; the prompt only opens
- // a PR when the catalog is actually stale, so most runs are no-ops. Off by
- // default; the user enables it on the PortOS app.
- 'refresh-local-llm-catalog': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: true, simplify: true } },
- // plan-feature files a plan, not code — tracker-filing posture mirrors
- // reference-watch: writable (a file-based tracker commits checklist items), no
- // managed worktree, no PR. Weekly (not daily like feature-ideas) so an
- // enabled run doesn't flood the tracker with plans — one filed plan per run.
- // runAfter do-replan so proposals are checked against the freshest available
- // work tracker before a new feature plan is filed.
- 'plan-feature': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, runAfter: ['do-replan'], taskMetadata: { useWorktree: false, openPR: false, readOnly: false } },
- // layered-intelligence is a programmatic-I/O task (agent-backed, hooked). Daily
- // by default; per-app scheduling (enabled/interval/provider/model) is set in the
- // Intelligence tab and stored on the app's taskTypeOverrides['layered-intelligence'].
- // No `prompt` field — the buildTaskInput hook renders the prompt (no
- // DEFAULT_TASK_PROMPTS entry, so the prompt-version machinery in loadSchedule
- // skips it). taskMetadata pins the throwaway-worktree posture: the reasoning
- // agent runs in a worktree that is discarded without a commit/merge/PR
- // (discardWorktree), so it can't land code — its `.agent-done` payload is the
- // only sanctioned output (consumed by the processTaskOutput hook).
- 'layered-intelligence': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: false, discardWorktree: true } }
-};
-
-// Agent-options that a task manages internally — UI locks the toggle, and
-// loadSchedule/updateTaskInterval enforce the default value regardless of
-// what's persisted or POSTed. The reasoning lives next to each task above
-// (e.g., plan-task's prompt creates its own claim/<slug> worktree, so a
-// CoS-managed worktree would clobber it).
-export const MANAGED_AGENT_OPTIONS = {
- 'plan-task': ['useWorktree', 'openPR', 'claimFlow'],
- // The non-committing coordinators (NON_COMMITTING_COORDINATOR_METADATA above) all
- // run in the app's LIVE checkout and ship no code, so a CoS-managed worktree is at
- // best unused and at worst harmful — branch-reconcile needs to see the sibling
- // worktrees of the in-flight branches (a managed worktree hides them from the scan
- // AND could trip cleanupAgentWorktree's auto-merge). Locking both off also keeps the
- // finalize-time PR-claim check from scoring a completed run `pr-missing`.
- //
- // `worktreeChangesExpected` is managed for these coordinators as well — the one type-keyed
- // exception to it being a free per-app override. A clean tree is definitionally the
- // success shape for a branch deletion or a posted report, so setting it back to
- // `true` can only make successful runs fail; it is exactly as non-negotiable here as
- // the other two. Managing it is also what carries it through an explicit
- // `taskMetadata: null` clear — loadSchedule preserves that null (skipping the
- // defaults deep-merge), and enforceManagedAgentOptions rebuilds only the MANAGED
- // fields, so an unmanaged `worktreeChangesExpected` would silently go absent and the
- // task bookkeeping would otherwise treat the clean worktree as missing code work.
- ...Object.fromEntries(
- ['branch-reconcile', 'branch-cleanup', 'issue-reconcile', 'jira-status-report']
- .map((t) => [t, ['useWorktree', 'openPR', 'worktreeChangesExpected']])
- ),
- // claim-issue's prompt creates its own claim/issue-<num> worktree (same
- // rationale as plan-task), so CoS must not pre-create one or open the PR.
- 'claim-issue': ['useWorktree', 'openPR', 'claimFlow'],
- // claim-work delegates to one of the above prompt bodies, each of which
- // creates its own worktree + PR — so the same lock applies to the router.
- 'claim-work': ['useWorktree', 'openPR', 'claimFlow'],
- 'release-check': ['useWorktree', 'openPR', 'worktreeChangesExpected'],
- 'stash-cleanup': ['useWorktree', 'openPR', 'worktreeChangesExpected']
-};
-
-// Strip managed-agent fields from a per-app override map before merging on top
-// of the (already-enforced) global config. Without this, an app-level override
-// for a managed field (e.g. `plan-task.useWorktree=false`) carries through into
-// the task spawn even though the UI toggle is locked, defeating the lock's
-// intent. Returns the cleaned metadata (or null if every key was managed).
-export function stripManagedAgentOptionsFromOverride(taskType, taskMetadata) {
- const managed = MANAGED_AGENT_OPTIONS[taskType];
- if (!managed || !taskMetadata || typeof taskMetadata !== 'object') return taskMetadata;
- const cleaned = { ...taskMetadata };
- for (const field of managed) delete cleaned[field];
- return Object.keys(cleaned).length ? cleaned : null;
-}
-
-function enforceManagedAgentOptions(taskType, config) {
- const managed = MANAGED_AGENT_OPTIONS[taskType];
- if (!managed || !config) return false;
- const defaults = DEFAULT_TASK_INTERVALS[taskType]?.taskMetadata
- || LEGACY_MANAGED_TASK_METADATA[taskType]
- || {};
- let changed = false;
- // If the stored config explicitly cleared taskMetadata (or never had it),
- // we still need the managed fields present — otherwise upstream resolvers
- // (e.g., cos.js applyAppWorktreeDefault) can flip them on via app defaults.
- if (!config.taskMetadata || typeof config.taskMetadata !== 'object' || Array.isArray(config.taskMetadata)) {
- config.taskMetadata = {};
- changed = true;
- }
- for (const field of managed) {
- if (config.taskMetadata[field] !== defaults[field]) {
- config.taskMetadata[field] = defaults[field];
- changed = true;
- }
- }
- return changed;
-}
-
-// The batch size is user-configurable, but an old schedule or an explicit
-// metadata clear must not silently restore the pre-batch all-at-once behavior.
-// Keep the persisted global task on the same safe default as a fresh install;
-// per-app overrides still layer on top of it at dispatch time.
-function enforceBranchReconcileBatch(taskType, config) {
- if (taskType !== 'branch-reconcile' || !config) return false;
- if (!config.taskMetadata || typeof config.taskMetadata !== 'object' || Array.isArray(config.taskMetadata)) {
- config.taskMetadata = {};
- }
- const value = config.taskMetadata.branchesPerAgent;
- if (!Number.isInteger(value) || value < BRANCHES_PER_AGENT_MIN || value > BRANCHES_PER_AGENT_MAX) {
- config.taskMetadata.branchesPerAgent = DEFAULT_BRANCHES_PER_AGENT;
- return true;
- }
- return false;
-}
-
-/**
- * Default schedule data structure (v2 - unified)
- */
-const DEFAULT_SCHEDULE = {
- version: 2,
- lastUpdated: null,
-
- // Unified task intervals (applies to all apps including PortOS)
- tasks: {
- ...DEFAULT_TASK_INTERVALS
- },
-
- // Track last execution times
- // Format: 'task:security': { lastRun: timestamp, count: number, perApp: {} }
- executions: {},
-
- // On-demand task templates that can be triggered manually
- templates: []
-};
-
-async function ensureDataDir() {
- if (!existsSync(DATA_DIR)) {
- await ensureDir(DATA_DIR);
- }
-}
-
-/**
- * Migrate v1 schedule (selfImprovement + appImprovement) to v2 (unified tasks)
- */
-function migrateScheduleV1toV2(schedule) {
- emitLog('info', 'Migrating task schedule from v1 to v2 (unified)', {}, '📅 TaskSchedule');
-
- const migrated = {
- version: 2,
- lastUpdated: new Date().toISOString(),
- tasks: { ...DEFAULT_TASK_INTERVALS },
- executions: {},
- templates: schedule.templates || [],
- onDemandRequests: schedule.onDemandRequests || []
- };
-
- // Merge selfImprovement settings into tasks (excluding cos-enhancement)
- if (schedule.selfImprovement) {
- for (const [taskType, config] of Object.entries(schedule.selfImprovement)) {
- if (taskType === 'cos-enhancement') continue; // Removed
- // security stays as 'security' (was already named this in selfImprovement)
- if (migrated.tasks[taskType]) {
- migrated.tasks[taskType] = { ...migrated.tasks[taskType], ...config };
- }
- }
- }
-
- // Merge appImprovement settings into tasks
- if (schedule.appImprovement) {
- for (const [taskType, config] of Object.entries(schedule.appImprovement)) {
- // Rename security-audit → security
- const unifiedType = taskType === 'security-audit' ? 'security' : taskType;
- if (migrated.tasks[unifiedType]) {
- // If selfImprovement already set a non-default config, prefer it for overlapping types
- // unless appImprovement has a different non-default config
- const existing = migrated.tasks[unifiedType];
- const isExistingDefault = existing.type === DEFAULT_TASK_INTERVALS[unifiedType]?.type;
- const isNewDifferent = config.type !== (taskType === 'security-audit'
- ? INTERVAL_TYPES.WEEKLY : DEFAULT_TASK_INTERVALS[unifiedType]?.type);
- if (isExistingDefault || isNewDifferent) {
- migrated.tasks[unifiedType] = { ...existing, ...config };
- }
- }
- }
- }
-
- // Migrate execution keys: self-improve:X → task:X, app-improve:X → task:X
- if (schedule.executions) {
- for (const [key, data] of Object.entries(schedule.executions)) {
- let newKey = key;
- if (key.startsWith('self-improve:')) {
- const taskType = key.replace('self-improve:', '');
- if (taskType === 'cos-enhancement') continue; // Removed
- newKey = `task:${taskType}`;
- } else if (key.startsWith('app-improve:')) {
- let taskType = key.replace('app-improve:', '');
- if (taskType === 'security-audit') taskType = 'security';
- newKey = `task:${taskType}`;
- }
-
- if (migrated.executions[newKey]) {
- // Merge: combine counts, keep latest lastRun, merge perApp
- const existing = migrated.executions[newKey];
- existing.count = (existing.count || 0) + (data.count || 0);
- if (data.lastRun && (!existing.lastRun || new Date(data.lastRun) > new Date(existing.lastRun))) {
- existing.lastRun = data.lastRun;
- }
- if (data.perApp) {
- existing.perApp = { ...existing.perApp, ...data.perApp };
- }
- } else {
- migrated.executions[newKey] = { ...data };
- }
- }
- }
-
- // Populate prompts from defaults if missing
- for (const [taskType, config] of Object.entries(migrated.tasks)) {
- if (!config.prompt && DEFAULT_TASK_PROMPTS[taskType]) {
- config.prompt = DEFAULT_TASK_PROMPTS[taskType];
- }
- }
-
- return migrated;
-}
-
-// True when a stored prompt byte-matches a shipped default for this task — the
-// current default or any prior one in PREVIOUS_DEFAULT_PROMPTS. Used by
-// loadSchedule both to recognize legacy (unversioned) prompts and to self-heal a
-// prompt mis-flagged as customized. A genuine user edit never byte-matches a
-// shipped default, so callers can treat a match as "not really customized".
-function promptMatchesShippedDefault(prompt, taskType) {
- if (!prompt || !DEFAULT_TASK_PROMPTS[taskType]) return false;
- return (
- prompt === DEFAULT_TASK_PROMPTS[taskType] ||
- (PREVIOUS_DEFAULT_PROMPTS[taskType] || []).includes(prompt)
- );
-}
-
-/**
- * Load schedule data (auto-migrates from v1 if needed)
- */
-export async function loadSchedule() {
- await ensureDataDir();
-
- const loaded = await readJSONFile(SCHEDULE_FILE, null);
- if (!loaded) {
- return { ...DEFAULT_SCHEDULE };
- }
-
- // Auto-migrate v1 → v2
- if (!loaded.version || loaded.version === 1) {
- const migrated = migrateScheduleV1toV2(loaded);
- await saveSchedule(migrated);
- return migrated;
- }
-
- // v2: merge each task config with its default to backfill new fields
- // Deep-merge taskMetadata so new default keys are inherited unless explicitly overridden
- const mergedTasks = {};
- for (const taskType of Object.keys(DEFAULT_TASK_INTERVALS)) {
- const defaultTask = DEFAULT_TASK_INTERVALS[taskType];
- const loadedTask = loaded.tasks?.[taskType] || {};
- const merged = { ...defaultTask, ...loadedTask };
- // Deep-merge taskMetadata: preserve explicit null (clears metadata), otherwise merge defaults with stored
- // Only spread if loadedTask.taskMetadata is a plain object to avoid corrupting config
- if (defaultTask.taskMetadata && loadedTask.taskMetadata !== null) {
- const storedMeta = loadedTask.taskMetadata;
- merged.taskMetadata = { ...defaultTask.taskMetadata, ...(isPlainObject(storedMeta) ? storedMeta : {}) };
- }
- mergedTasks[taskType] = merged;
- }
- // Preserve any extra task types from loaded that aren't in defaults
- for (const taskType of Object.keys(loaded.tasks || {})) {
- if (!mergedTasks[taskType]) {
- mergedTasks[taskType] = loaded.tasks[taskType];
- }
- }
-
- const schedule = {
- ...DEFAULT_SCHEDULE,
- ...loaded,
- tasks: mergedTasks,
- executions: loaded.executions || {},
- templates: loaded.templates || []
- };
-
- // Populate prompts from defaults if missing, and auto-upgrade stale defaults
- let needsSave = false;
- for (const [taskType, config] of Object.entries(schedule.tasks)) {
- if (enforceManagedAgentOptions(taskType, config)) needsSave = true;
- if (enforceBranchReconcileBatch(taskType, config)) needsSave = true;
- // Stamp a creation timestamp the first time we see a task so the cron
- // catch-up bound (shouldRunTask) never replays a slot that predates the
- // task. Backfilling to "now" is conservative: it only suppresses catch-up
- // for slots already in the past — future slots fire on their real cadence.
- if (!config.createdAt) {
- config.createdAt = new Date().toISOString();
- needsSave = true;
- }
- if (!config.prompt && DEFAULT_TASK_PROMPTS[taskType]) {
- // No prompt set — initialize with current default and version
- config.prompt = DEFAULT_TASK_PROMPTS[taskType];
- config.promptVersion = PROMPT_VERSIONS[taskType] || 1;
- needsSave = true;
- } else {
- // Legacy migration: infer customization when promptVersion is missing
- if (
- config.prompt &&
- config.promptVersion === undefined &&
- DEFAULT_TASK_PROMPTS[taskType]
- ) {
- if (config.prompt === DEFAULT_TASK_PROMPTS[taskType]) {
- // Matches current default — assign current version (no upgrade needed)
- config.promptVersion = PROMPT_VERSIONS[taskType] || 1;
- needsSave = true;
- } else if ((PREVIOUS_DEFAULT_PROMPTS[taskType] || []).includes(config.prompt)) {
- // Matches a known previous default — assign version 1 so auto-upgrade triggers
- config.promptVersion = 1;
- needsSave = true;
- } else {
- // Prompt differs from all known defaults — treat as user-customized
- config.promptCustomized = true;
- config.promptVersion = PROMPT_VERSIONS[taskType] || 1;
- needsSave = true;
- }
- }
-
- // Self-heal a mis-flagged customization: a prompt marked promptCustomized
- // that nonetheless byte-matches a shipped default was never user-edited —
- // it was flagged by an earlier legacy migration that ran before this task
- // carried a PREVIOUS_DEFAULT_PROMPTS entry (e.g. the basic self-improvement
- // prompts that hardcoded the app name as "PortOS"). Clear the flag so the
- // auto-upgrade below can replace the stale default.
- if (config.promptCustomized && promptMatchesShippedDefault(config.prompt, taskType)) {
- config.promptCustomized = false;
- needsSave = true;
- }
-
- if (PROMPT_VERSIONS[taskType] && !config.promptCustomized) {
- // Auto-upgrade non-customized prompts when code version is newer
- const storedVersion = config.promptVersion || 1;
- if (storedVersion < PROMPT_VERSIONS[taskType]) {
- emitLog('info', `Upgrading ${taskType} prompt v${storedVersion} → v${PROMPT_VERSIONS[taskType]}`, { taskType }, '📅 TaskSchedule');
- config.prompt = DEFAULT_TASK_PROMPTS[taskType];
- config.promptVersion = PROMPT_VERSIONS[taskType];
- needsSave = true;
- }
- }
- }
- }
-
- if (needsSave) {
- await saveSchedule(schedule);
- }
-
- return schedule;
-}
-
-async function saveSchedule(schedule) {
- await ensureDataDir();
- schedule.lastUpdated = new Date().toISOString();
- await atomicWrite(SCHEDULE_FILE, schedule);
-}
-
// ============================================================
// Unified getters/setters (replace split self/app functions)
// ============================================================
@@ -1385,140 +681,6 @@ export async function applyOnDemandRunResets(request, appId = null) {
return true;
}
-// ============================================================
-// Type-level consecutive-failure ledger (#2616)
-// ============================================================
-
-/** Dedup / notification key for a type+app failure park. */
-function failureParkKeyFor(taskType, appId) {
- return appId ? `${taskType}:${appId}` : taskType;
-}
-
-/** Delete every failure-ledger field from a record. Returns true if any changed. */
-function clearFailureLedgerFields(record) {
- if (!record) return false;
- let changed = false;
- for (const field of FAILURE_LEDGER_FIELDS) {
- if (record[field] !== undefined) { delete record[field]; changed = true; }
- }
- return changed;
-}
-
-/**
- * Remove any lingering auto-park notification for a now-unparked type+app so the
- * bell stops showing a stale "parked" warning AND a later re-park can re-notify
- * (the `exists` dedup in notifyTaskTypeFailurePark keys on this same field, and
- * scans read notifications too). Best-effort — lazy-imported, never throws out.
- */
-async function clearTaskTypeFailureParkNotification(taskType, appId) {
- const { removeByMetadata } = await import('./notifications.js');
- await removeByMetadata('failureParkKey', failureParkKeyFor(taskType, appId)).catch(() => {});
-}
-
-/**
- * Surface a user-facing notification when a task type auto-parks. Lazy-imports
- * the notifications service so taskSchedule has no static dependency on it (and
- * so the failure path stays free of that I/O until a park actually fires).
- * Deduped per type+app so a re-park after a manual retry doesn't spam the bell.
- */
-async function notifyTaskTypeFailurePark(taskType, appId, record) {
- const { addNotification, exists, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('./notifications.js');
- const dedupeKey = failureParkKeyFor(taskType, appId);
- if (await exists(NOTIFICATION_TYPES.AGENT_WARNING, 'failureParkKey', dedupeKey)) return;
- const scope = appId ? `app ${appId}` : 'global';
- const category = record.failureParkReason || record.lastErrorCategory || 'unknown';
- await addNotification({
- type: NOTIFICATION_TYPES.AGENT_WARNING,
- title: `Scheduled task "${taskType}" auto-parked after ${record.consecutiveFailures} failures`,
- description: `The "${taskType}" scheduled task (${scope}) failed ${record.consecutiveFailures} times in a row (last error: ${category}). It is parked and will not re-queue until you retry it or change its config.`,
- priority: PRIORITY_LEVELS.HIGH,
- link: '/cos/schedule',
- metadata: {
- taskType,
- appId: appId || null,
- failureParkKey: dedupeKey,
- consecutiveFailures: record.consecutiveFailures,
- lastErrorCategory: category
- }
- });
-}
-
-/**
- * Record a task-type FAILURE into the per-type ledger (per app + global).
- * Increments `consecutiveFailures`, stamps `lastFailureAt`/`lastErrorCategory`,
- * and auto-parks (+notifies) once the threshold is crossed. The auto-park is
- * indefinite — cleared only by a success, a manual retry, or a config change.
- */
-export async function recordTaskTypeFailure(taskType, appId = null, { errorCategory = null } = {}) {
- const schedule = await loadSchedule();
- const record = ensureExecutionRecord(schedule, taskType, appId);
- record.consecutiveFailures = (Number(record.consecutiveFailures) || 0) + 1;
- record.lastFailureAt = new Date().toISOString();
- if (errorCategory) record.lastErrorCategory = errorCategory;
-
- let justParked = false;
- if (record.consecutiveFailures >= FAILURE_PARK_THRESHOLD && !record.failureParkedAt) {
- record.failureParkedAt = new Date().toISOString();
- record.failureParkReason = errorCategory || record.lastErrorCategory || 'unknown';
- justParked = true;
- }
-
- await saveSchedule(schedule);
- emitLog(
- justParked ? 'warn' : 'info',
- `Task type ${taskType}${appId ? ` (app ${appId})` : ''} failure #${record.consecutiveFailures}${justParked ? ' — AUTO-PARKED' : ''} (${errorCategory || 'unknown'})`,
- { taskType, appId, consecutiveFailures: record.consecutiveFailures, parked: justParked },
- '📅 TaskSchedule'
- );
-
- if (justParked) {
- cosEvents.emit('schedule:failure-parked', { taskType, appId, consecutiveFailures: record.consecutiveFailures, reason: record.failureParkReason });
- await notifyTaskTypeFailurePark(taskType, appId, record).catch((err) => {
- emitLog('warn', `Failure-park notification failed for ${taskType}: ${err.message}`, { taskType, appId }, '📅 TaskSchedule');
- });
- }
- return record;
-}
-
-/**
- * Record a task-type SUCCESS: reset the consecutive-failure ledger (and any
- * auto-park) for this type. No-op (no write) when the ledger is already clean.
- */
-export async function recordTaskTypeSuccess(taskType, appId = null) {
- const schedule = await loadSchedule();
- const record = resolveExecutionRecord(schedule, taskType, appId);
- const wasParked = !!record?.failureParkedAt;
- if (!clearFailureLedgerFields(record)) return false;
- await saveSchedule(schedule);
- emitLog('info', `Task type ${taskType}${appId ? ` (app ${appId})` : ''} succeeded — failure ledger reset`, { taskType, appId }, '📅 TaskSchedule');
- if (wasParked) await clearTaskTypeFailureParkNotification(taskType, appId);
- return true;
-}
-
-/**
- * Clear a task type's failure ledger + auto-park for a manual retry (unpark),
- * scoped to exactly the record being re-run: the per-app record when `appId` is
- * set (a per-app "Run now"), or the global (appId-less) record when null (a
- * global self-improvement "Run now"). Does NOT touch other apps' independent
- * ledgers — a global retrigger must not silently unpark an app whose failure
- * cause was never addressed. (The config-change unpark in updateTaskInterval,
- * which DOES reset every scope of the type, has its own inline clear.) Returns
- * true if anything was cleared.
- */
-export async function clearTaskTypeFailurePark(taskType, appId = null) {
- const schedule = await loadSchedule();
- const top = schedule.executions[executionKey(taskType)];
- if (!top) return false;
- const record = appId ? top.perApp?.[appId] : top;
- const wasParked = !!record?.failureParkedAt;
- if (!clearFailureLedgerFields(record)) return false;
- await saveSchedule(schedule);
- // Prune the stale park notification (if any) so the bell clears and a later
- // re-park can re-notify.
- if (wasParked) await clearTaskTypeFailureParkNotification(taskType, appId);
- return true;
-}
-
/**
* Check if all runAfter dependencies have completed since this task's last run.
* Returns { satisfied, pending } where pending lists unfinished dependency task types.
@@ -1905,51 +1067,6 @@ export async function getNextTaskType(appId = null, lastType = '', { perpetualOn
return { taskType: rotationTasks[nextIndex], reason: 'rotation' };
}
-// ============================================================
-// Templates
-// ============================================================
-
-export async function addTemplateTask(template) {
- const schedule = await loadSchedule();
-
- const newTemplate = {
- id: `template-${Date.now().toString(36)}`,
- createdAt: new Date().toISOString(),
- name: template.name,
- description: template.description,
- category: template.category || 'custom',
- taskType: template.taskType,
- priority: template.priority || 'MEDIUM',
- metadata: template.metadata || {}
- };
-
- schedule.templates.push(newTemplate);
- await saveSchedule(schedule);
-
- emitLog('info', `Added template task: ${newTemplate.name}`, { templateId: newTemplate.id }, '📅 TaskSchedule');
- return newTemplate;
-}
-
-export async function getTemplateTasks() {
- const schedule = await loadSchedule();
- return schedule.templates;
-}
-
-export async function deleteTemplateTask(templateId) {
- const schedule = await loadSchedule();
- const index = schedule.templates.findIndex(t => t.id === templateId);
-
- if (index === -1) {
- return { error: 'Template not found' };
- }
-
- const deleted = schedule.templates.splice(index, 1)[0];
- await saveSchedule(schedule);
-
- emitLog('info', `Deleted template task: ${deleted.name}`, { templateId }, '📅 TaskSchedule');
- return { success: true, deleted };
-}
-
// ============================================================
// On-Demand Requests
// ============================================================
@@ -1962,11 +1079,6 @@ export async function deleteTemplateTask(templateId) {
* perpetual drain re-issued ITSELF through the same lane after a completed run —
* automated, and therefore NOT allowed to clear its own brakes.
*/
-export const ON_DEMAND_ORIGINS = { USER: 'user', REFILL: 'refill' };
-
-/** Is this on-demand request an automated drain refill rather than a human "Run"? */
-export const isRefillRequest = (request) => request?.origin === ON_DEMAND_ORIGINS.REFILL;
-
export async function triggerOnDemandTask(taskType, appId = null, { emit = true, origin = ON_DEMAND_ORIGINS.USER } = {}) {
const schedule = await loadSchedule();
@@ -2298,49 +1410,3 @@ function formatRelativeTime(timestamp) {
if (minutes > 0) return `${minutes}m ago`;
return 'just now';
}
-
-// Short human-readable blurb per task type, shown in the schedule UI's
-// upcoming-tasks list. Every entry in SELF_IMPROVEMENT_TASK_TYPES must have a
-// key here — a missing one falls back to a dasherized label ("claim work"),
-// which reads as an orphaned/legacy task. A parity guard in taskSchedule.test.js
-// fails the suite if the two ever drift apart.
-export const TASK_TYPE_DESCRIPTIONS = {
- 'ui-bugs': 'Find UI bugs — file issues or implement fixes',
- 'mobile-responsive': 'Mobile/responsive audit — file issues or implement fixes',
- 'security': 'Security audit — file issues or implement fixes',
- 'code-quality': 'Code quality — file issues or implement fixes',
- 'console-errors': 'Console errors — file issues or implement fixes',
- 'performance': 'Performance audit — file issues or implement fixes',
- 'test-coverage': 'Test coverage — file issues or add tests',
- 'documentation': 'Docs drift — file issues or implement fixes',
- 'feature-ideas': 'Implement next planned feature or brainstorm new one',
- 'plan-task': 'Execute next PLAN.md item, remove it from PLAN.md, log to changelog (worktree+PR)',
- 'claim-issue': 'Claim and ship the next open GitHub issue (owner-filed or any author), PR closes it',
- 'claim-work': "Ship the next work item from the app's configured tracker (PLAN.md, GitHub/GitLab issues, or JIRA), routed automatically",
- 'accessibility': 'Accessibility audit — file issues or implement fixes',
- 'branch-reconcile': "Finish this machine's in-flight local branches: clean up merged ones, open PRs, resolve conflicts, drive review, auto-merge when green",
- 'issue-reconcile': "Heal zombie issues: open + in-progress but their PR already merged with no live claim — close + file a scoped follow-up when work remains, or release the claim so the queue re-picks it",
- 'dependency-updates': 'Land or resolve open Dependabot/Renovate PRs, then update the dependencies they missed',
- 'release-check': 'Check for release readiness',
- 'error-handling': 'Failure-path audit — file issues or implement fixes',
- 'typing': 'TypeScript types — file issues or implement fixes',
- 'pr-reviewer': 'Review open PRs from contributors',
- 'pr-watcher': 'Run a custom prompt on PRs newly opened against the default branch',
- 'code-reviewer-a': 'Review the codebase and triage/implement findings (independent provider/model instance A)',
- 'code-reviewer-b': 'Review the codebase and triage/implement findings (independent provider/model instance B)',
- 'do-replan': 'Audit and prune PLAN.md after merges and branch cleanup so it reflects what actually shipped',
- 'jira-sprint-manager': 'Triage and implement JIRA sprint tickets',
- 'jira-status-report': 'Generate JIRA weekly status report',
- 'reference-watch': 'Watch reference repos and append PLAN.md items for new upstream work',
- 'ux': 'UX/design audit — file issues (default) or implement fixes',
- 'data-safety': 'Data/upgrade-safety audit — file issues (default) or implement fixes',
- 'simplify': 'Dead-code/duplication audit — file issues (default) or implement removals',
- 'stash-cleanup': 'Triage git stash list — drop entries superseded by or stale relative to main, leave real unlanded work in place',
- 'refresh-local-llm-catalog': "Refresh PortOS's bundled suggested local-model catalog + editorial ranking (PortOS repo only)",
- 'plan-feature': "Brainstorm one feature and file its decision-complete plan to the app's work tracker (no code)",
- 'layered-intelligence': "Read this app's goals + telemetry, ask a reasoning model for one improvement, and file one deduplicated tracker issue — no code, no agent"
-};
-
-function getTaskTypeDescription(taskType) {
- return TASK_TYPE_DESCRIPTIONS[taskType] || taskType.replace(/-/g, ' ');
-}
diff --git a/server/services/taskScheduleBackoff.js b/server/services/taskScheduleBackoff.js
new file mode 100644
index 0000000000..0bb8655592
--- /dev/null
+++ b/server/services/taskScheduleBackoff.js
@@ -0,0 +1,177 @@
+/** Consecutive-failure backoff and auto-park state for scheduled task types. */
+
+import { cosEvents, emitLog } from './cosEvents.js';
+import { loadSchedule, saveSchedule } from './taskScheduleStore.js';
+import {
+ FAILURE_BACKOFF_BASE_MS,
+ FAILURE_BACKOFF_CAP_MS,
+ FAILURE_PARK_THRESHOLD
+} from './taskScheduleConstants.js';
+
+export { FAILURE_BACKOFF_BASE_MS, FAILURE_BACKOFF_CAP_MS, FAILURE_PARK_THRESHOLD };
+
+const FAILURE_LEDGER_FIELDS = [
+ 'consecutiveFailures',
+ 'lastFailureAt',
+ 'lastErrorCategory',
+ 'failureParkedAt',
+ 'failureParkReason'
+];
+
+export function computeFailureBackoffMs(consecutiveFailures, baseMs = FAILURE_BACKOFF_BASE_MS, capMs = FAILURE_BACKOFF_CAP_MS) {
+ const n = Number(consecutiveFailures) || 0;
+ if (n <= 0) return 0;
+ return Math.min(baseMs * Math.pow(2, n), capMs);
+}
+
+const executionKey = (taskType) => taskType.startsWith('task:') ? taskType : `task:${taskType}`;
+
+const ensureExecutionRecord = (schedule, taskType, appId) => {
+ const key = executionKey(taskType);
+ if (!schedule.executions[key]) schedule.executions[key] = { lastRun: null, count: 0, perApp: {} };
+ const top = schedule.executions[key];
+ if (!appId) return top;
+ if (!top.perApp) top.perApp = {};
+ if (!top.perApp[appId]) top.perApp[appId] = { lastRun: null, count: 0 };
+ return top.perApp[appId];
+};
+
+const resolveExecutionRecord = (schedule, taskType, appId) => {
+ const top = schedule.executions[executionKey(taskType)];
+ return top ? ((appId ? top.perApp?.[appId] : top) || null) : null;
+};
+
+// ============================================================
+// Type-level consecutive-failure ledger (#2616)
+// ============================================================
+
+/** Dedup / notification key for a type+app failure park. */
+function failureParkKeyFor(taskType, appId) {
+ return appId ? `${taskType}:${appId}` : taskType;
+}
+
+/** Delete every failure-ledger field from a record. Returns true if any changed. */
+export function clearFailureLedgerFields(record) {
+ if (!record) return false;
+ let changed = false;
+ for (const field of FAILURE_LEDGER_FIELDS) {
+ if (record[field] !== undefined) { delete record[field]; changed = true; }
+ }
+ return changed;
+}
+
+/**
+ * Remove any lingering auto-park notification for a now-unparked type+app so the
+ * bell stops showing a stale "parked" warning AND a later re-park can re-notify
+ * (the `exists` dedup in notifyTaskTypeFailurePark keys on this same field, and
+ * scans read notifications too). Best-effort — lazy-imported, never throws out.
+ */
+export async function clearTaskTypeFailureParkNotification(taskType, appId) {
+ const { removeByMetadata } = await import('./notifications.js');
+ await removeByMetadata('failureParkKey', failureParkKeyFor(taskType, appId)).catch(() => {});
+}
+
+/**
+ * Surface a user-facing notification when a task type auto-parks. Lazy-imports
+ * the notifications service so taskSchedule has no static dependency on it (and
+ * so the failure path stays free of that I/O until a park actually fires).
+ * Deduped per type+app so a re-park after a manual retry doesn't spam the bell.
+ */
+async function notifyTaskTypeFailurePark(taskType, appId, record) {
+ const { addNotification, exists, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('./notifications.js');
+ const dedupeKey = failureParkKeyFor(taskType, appId);
+ if (await exists(NOTIFICATION_TYPES.AGENT_WARNING, 'failureParkKey', dedupeKey)) return;
+ const scope = appId ? `app ${appId}` : 'global';
+ const category = record.failureParkReason || record.lastErrorCategory || 'unknown';
+ await addNotification({
+ type: NOTIFICATION_TYPES.AGENT_WARNING,
+ title: `Scheduled task "${taskType}" auto-parked after ${record.consecutiveFailures} failures`,
+ description: `The "${taskType}" scheduled task (${scope}) failed ${record.consecutiveFailures} times in a row (last error: ${category}). It is parked and will not re-queue until you retry it or change its config.`,
+ priority: PRIORITY_LEVELS.HIGH,
+ link: '/cos/schedule',
+ metadata: {
+ taskType,
+ appId: appId || null,
+ failureParkKey: dedupeKey,
+ consecutiveFailures: record.consecutiveFailures,
+ lastErrorCategory: category
+ }
+ });
+}
+
+/**
+ * Record a task-type FAILURE into the per-type ledger (per app + global).
+ * Increments `consecutiveFailures`, stamps `lastFailureAt`/`lastErrorCategory`,
+ * and auto-parks (+notifies) once the threshold is crossed. The auto-park is
+ * indefinite — cleared only by a success, a manual retry, or a config change.
+ */
+export async function recordTaskTypeFailure(taskType, appId = null, { errorCategory = null } = {}) {
+ const schedule = await loadSchedule();
+ const record = ensureExecutionRecord(schedule, taskType, appId);
+ record.consecutiveFailures = (Number(record.consecutiveFailures) || 0) + 1;
+ record.lastFailureAt = new Date().toISOString();
+ if (errorCategory) record.lastErrorCategory = errorCategory;
+
+ let justParked = false;
+ if (record.consecutiveFailures >= FAILURE_PARK_THRESHOLD && !record.failureParkedAt) {
+ record.failureParkedAt = new Date().toISOString();
+ record.failureParkReason = errorCategory || record.lastErrorCategory || 'unknown';
+ justParked = true;
+ }
+
+ await saveSchedule(schedule);
+ emitLog(
+ justParked ? 'warn' : 'info',
+ `Task type ${taskType}${appId ? ` (app ${appId})` : ''} failure #${record.consecutiveFailures}${justParked ? ' — AUTO-PARKED' : ''} (${errorCategory || 'unknown'})`,
+ { taskType, appId, consecutiveFailures: record.consecutiveFailures, parked: justParked },
+ '📅 TaskSchedule'
+ );
+
+ if (justParked) {
+ cosEvents.emit('schedule:failure-parked', { taskType, appId, consecutiveFailures: record.consecutiveFailures, reason: record.failureParkReason });
+ await notifyTaskTypeFailurePark(taskType, appId, record).catch((err) => {
+ emitLog('warn', `Failure-park notification failed for ${taskType}: ${err.message}`, { taskType, appId }, '📅 TaskSchedule');
+ });
+ }
+ return record;
+}
+
+/**
+ * Record a task-type SUCCESS: reset the consecutive-failure ledger (and any
+ * auto-park) for this type. No-op (no write) when the ledger is already clean.
+ */
+export async function recordTaskTypeSuccess(taskType, appId = null) {
+ const schedule = await loadSchedule();
+ const record = resolveExecutionRecord(schedule, taskType, appId);
+ const wasParked = !!record?.failureParkedAt;
+ if (!clearFailureLedgerFields(record)) return false;
+ await saveSchedule(schedule);
+ emitLog('info', `Task type ${taskType}${appId ? ` (app ${appId})` : ''} succeeded — failure ledger reset`, { taskType, appId }, '📅 TaskSchedule');
+ if (wasParked) await clearTaskTypeFailureParkNotification(taskType, appId);
+ return true;
+}
+
+/**
+ * Clear a task type's failure ledger + auto-park for a manual retry (unpark),
+ * scoped to exactly the record being re-run: the per-app record when `appId` is
+ * set (a per-app "Run now"), or the global (appId-less) record when null (a
+ * global self-improvement "Run now"). Does NOT touch other apps' independent
+ * ledgers — a global retrigger must not silently unpark an app whose failure
+ * cause was never addressed. (The config-change unpark in updateTaskInterval,
+ * which DOES reset every scope of the type, has its own inline clear.) Returns
+ * true if anything was cleared.
+ */
+export async function clearTaskTypeFailurePark(taskType, appId = null) {
+ const schedule = await loadSchedule();
+ const top = schedule.executions[executionKey(taskType)];
+ if (!top) return false;
+ const record = appId ? top.perApp?.[appId] : top;
+ const wasParked = !!record?.failureParkedAt;
+ if (!clearFailureLedgerFields(record)) return false;
+ await saveSchedule(schedule);
+ // Prune the stale park notification (if any) so the bell clears and a later
+ // re-park can re-notify.
+ if (wasParked) await clearTaskTypeFailureParkNotification(taskType, appId);
+ return true;
+}
+
diff --git a/server/services/taskScheduleConstants.js b/server/services/taskScheduleConstants.js
new file mode 100644
index 0000000000..13fc64037c
--- /dev/null
+++ b/server/services/taskScheduleConstants.js
@@ -0,0 +1,23 @@
+/** Dependency-free task scheduling constants shared by registry and runtime modules. */
+
+const HOUR_MS = 60 * 60 * 1000;
+const DAY_MS = 24 * HOUR_MS;
+
+export const INTERVAL_TYPES = {
+ ROTATION: 'rotation',
+ DAILY: 'daily',
+ WEEKLY: 'weekly',
+ ONCE: 'once',
+ ON_DEMAND: 'on-demand',
+ CUSTOM: 'custom',
+ CRON: 'cron',
+ PERPETUAL: 'perpetual'
+};
+
+export const WEEK = 7 * DAY_MS;
+export const DEFAULT_PERPETUAL_RECHECK_MS = DAY_MS;
+export const FAILURE_BACKOFF_BASE_MS = HOUR_MS;
+export const FAILURE_BACKOFF_CAP_MS = DAY_MS;
+export const FAILURE_PARK_THRESHOLD = 5;
+export const ON_DEMAND_ORIGINS = { USER: 'user', REFILL: 'refill' };
+export const isRefillRequest = (request) => request?.origin === ON_DEMAND_ORIGINS.REFILL;
diff --git a/server/services/taskScheduleModules.test.js b/server/services/taskScheduleModules.test.js
new file mode 100644
index 0000000000..d5fddf2a4a
--- /dev/null
+++ b/server/services/taskScheduleModules.test.js
@@ -0,0 +1,47 @@
+import { readFileSync } from 'fs';
+import { describe, expect, it } from 'vitest';
+import * as backoff from './taskScheduleBackoff.js';
+import * as constants from './taskScheduleConstants.js';
+import * as registry from './taskScheduleRegistry.js';
+import * as schedule from './taskSchedule.js';
+import * as templates from './taskScheduleTemplates.js';
+
+const source = (relativePath) => readFileSync(new URL(relativePath, import.meta.url), 'utf8');
+
+describe('taskSchedule module boundaries', () => {
+ it('keeps the legacy taskSchedule exports wired to the extracted modules', () => {
+ const exportsByModule = Object.fromEntries([
+ ...['INTERVAL_TYPES', 'ON_DEMAND_ORIGINS', 'isRefillRequest']
+ .map((name) => [name, constants[name]]),
+ ...['DEFAULT_BRANCHES_PER_AGENT', 'DEFAULT_TASK_INTERVALS', 'MANAGED_AGENT_OPTIONS',
+ 'PERPETUAL_DRAIN_DISPATCH_CAP', 'SELF_IMPROVEMENT_TASK_TYPES', 'TASK_TYPE_DESCRIPTIONS',
+ 'stripManagedAgentOptionsFromOverride'].map((name) => [name, registry[name]]),
+ ...['FAILURE_BACKOFF_BASE_MS', 'FAILURE_BACKOFF_CAP_MS', 'FAILURE_PARK_THRESHOLD',
+ 'clearTaskTypeFailurePark', 'computeFailureBackoffMs', 'recordTaskTypeFailure',
+ 'recordTaskTypeSuccess'].map((name) => [name, backoff[name]]),
+ ...['addTemplateTask', 'deleteTemplateTask', 'getTemplateTasks']
+ .map((name) => [name, templates[name]])
+ ]);
+
+ for (const [name, value] of Object.entries(exportsByModule)) {
+ expect(schedule[name], name).toBe(value);
+ }
+ });
+
+ it('keeps the static task registry independent from apps and schedule runtime state', () => {
+ const registrySource = source('./taskScheduleRegistry.js');
+ expect(registrySource).not.toContain("from './apps.js'");
+ expect(registrySource).not.toContain("from './taskSchedule.js'");
+
+ const appsSource = source('./apps.js');
+ expect(appsSource).toContain("from './taskScheduleRegistry.js'");
+ expect(appsSource).not.toContain("from './taskSchedule.js'");
+ });
+
+ it('keeps prompt-version migration data in the persisted store seam', () => {
+ const storeSource = source('./taskScheduleStore.js');
+ expect(storeSource).toContain('PROMPT_VERSIONS');
+ expect(storeSource).toContain('PREVIOUS_DEFAULT_PROMPTS');
+ expect(storeSource).toContain('promptMatchesShippedDefault');
+ });
+});
diff --git a/server/services/taskScheduleRegistry.js b/server/services/taskScheduleRegistry.js
new file mode 100644
index 0000000000..44f13b622a
--- /dev/null
+++ b/server/services/taskScheduleRegistry.js
@@ -0,0 +1,467 @@
+/**
+ * Static task-type registry.
+ *
+ * This module is deliberately independent of apps.js and persisted schedule state
+ * so app configuration can consume task definitions without forming a cycle.
+ */
+
+import { BRANCHES_PER_AGENT_MAX, BRANCHES_PER_AGENT_MIN } from '../lib/cosValidation.js';
+import { isAuditTaskType, defaultFileIssuesFor } from '../lib/auditCatalog.js';
+import { INTERVAL_TYPES } from './taskScheduleConstants.js';
+
+export const SELF_IMPROVEMENT_TASK_TYPES = [
+ 'security', 'code-quality', 'test-coverage', 'performance',
+ 'accessibility', 'branch-reconcile', 'issue-reconcile', 'console-errors', 'dependency-updates', 'documentation',
+ 'ui-bugs', 'mobile-responsive', 'feature-ideas', 'plan-task', 'claim-issue', 'claim-work', 'error-handling',
+ 'typing', 'release-check', 'pr-reviewer', 'code-reviewer-a', 'code-reviewer-b',
+ 'jira-sprint-manager', 'jira-status-report', 'do-replan',
+ // Polls the app's GitHub repo for pull requests newly opened against the
+ // default branch and dispatches an agent (running the configurable
+ // pr-watcher prompt) for each one. `taskMetadata.prAuthorFilter` gates on
+ // PR authorship (self / others / any). See server/services/prWatcher.js.
+ 'pr-watcher',
+ // Watches `referenceRepos` configured on the app — fetches each upstream
+ // repo, finds commits since lastReviewedSha, and appends slug-tagged
+ // `[ref-watch-…]` checklist items to the app's PLAN.md for `/claim` /
+ // `plan-task` to pick up. No source-code edits, no separate review file.
+ 'reference-watch',
+ // Walks the running app UI with a UX reviewer's eye (Playwright MCP) against a
+ // named checklist — buried primary actions, dead-end empty/error states,
+ // affordances that drift between sibling screens. Defaults to filing tracker
+ // issues (`fileIssues: true`); the user can flip it to implement. Deliberately
+ // narrower than its siblings: raw console errors belong to `ui-bugs`, viewport
+ // breakage to `mobile-responsive`, ARIA/contrast/keyboard to `accessibility`.
+ 'ux',
+ // Quota-burn `data-safety-audit` counterpart. Migrations, schema parity, and
+ // cross-version compatibility. Defaults to file-issues (safer for unattended).
+ 'data-safety',
+ // Quota-burn `simplify-audit` counterpart. Dead code, unused exports, and
+ // copy-paste drift — distinct from `code-quality` (which is the broader DRY /
+ // long-function / TODO pass). Defaults to file-issues.
+ 'simplify',
+ // Audits `git stash list` for {appName} and drops entries already superseded
+ // by (or a subset of) current `main`/HEAD, or that are stale/abandoned scratch
+ // work — without discarding real unlanded work. On-demand only (no cadence
+ // makes sense for something the user notices ad hoc); non-committing
+ // coordinator posture, since a cleared stash is a repo-hygiene side effect,
+ // never a commit. See DEFAULT_TASK_PROMPTS['stash-cleanup'].
+ 'stash-cleanup',
+ // PortOS-only: researches the current best local LLMs per category and
+ // refreshes the bundled suggested-models catalog (server/lib/localLlmCatalog.js)
+ // + the editorial family ranking (server/lib/localModelHeuristics.js), opening a
+ // PR. No-ops on any repo lacking that catalog file, so enabling it on a
+ // non-PortOS app does nothing. See DEFAULT_TASK_PROMPTS['refresh-local-llm-catalog'].
+ 'refresh-local-llm-catalog',
+ // The planning-only sibling of `feature-ideas`: runs the same brainstorm
+ // research (PRD.md/GOALS.md or repository docs, changelog/git log, and
+ // closed-unmerged PRs)
+ // but NEVER implements — its deliverable is ONE decision-complete feature
+ // plan filed into the app's resolved work tracker via {trackerInstructions}
+ // (PLAN.md checklist item / GitHub / GitLab issue / JIRA ticket), which the
+ // claim flows pick up later. Always-filing tracker-filing type
+ // (TRACKER_FILING_PRESETS['plan-feature']), like reference-watch/repo-study.
+ 'plan-feature',
+ // layered-intelligence is a PROGRAMMATIC-I/O task: it spawns a NORMAL reasoning
+ // agent (visible in the CoS queue + Active Agents, TUI-attachable) with two
+ // deterministic hooks around it — buildTaskInput gathers the app's goals +
+ // telemetry + open issues and builds the reasoning prompt; processTaskOutput
+ // validates the agent's `.agent-done` payload, dedups, and files ONE tracker
+ // issue. The agent runs in a THROWAWAY worktree (discardWorktree) that is never
+ // committed/merged, so the reasoner still can't write code — the structured
+ // payload is its only channel out. Scheduling (enabled/interval/provider/model)
+ // lives in the per-app taskTypeOverrides; behavior (sources/scopes/rules/handoff)
+ // stays in app.layeredIntelligence. Has NO DEFAULT_TASK_PROMPTS entry — the
+ // buildTaskInput hook renders the prompt. See taskTypeHooks.js +
+ // autonomousJobs/layeredIntelligenceHooks.js.
+ 'layered-intelligence',
+ // NOTE: `quota-burn` used to live here as a per-app perpetual task type. It is
+ // now ONE install-level loop (services/quotaBurnRunner.js) configured on the
+ // Quota Burn page — the burn plan is machine-local, and its jobs name which
+ // managed app (if any) the work targets. Migration 221 moves existing per-app
+ // overrides across; do not re-add it as a scheduled type.
+];
+
+// Shared taskMetadata posture for the NON-COMMITTING COORDINATOR types
+// (NON_COMMITTING_COORDINATOR_TASK_TYPES in taskTypeHooks.js — branch-reconcile /
+// issue-reconcile / branch-cleanup / jira-status-report / release-check). Each delivers its work
+// as a SIDE EFFECT in the app's live checkout — a deleted branch, a merged PR, a
+// relabeled issue, a posted report — and by design produces no commit of its own.
+// Two code-shipping criteria therefore have to be switched off or every SUCCESSFUL
+// run is recorded as a failure:
+// * `useWorktree`/`openPR` — explicitly false (not merely absent) so
+// applyAppWorktreeDefault's `=== undefined` checks can't fill them from the
+// app's `defaultOpenPR`/`defaultUseWorktree`. A worktree these tasks never cd
+// into is at best unused and at worst harmful (it hides sibling refs the
+// reconcile scan must inspect), and the implied PR expectation fails the run at finalize
+// with `pr-missing` — there is no code to open a PR for. Locked in
+// MANAGED_AGENT_OPTIONS below so a per-app override can't re-attach them.
+// `readOnly: true` is NOT a substitute: it gates worktree CREATION
+// (agentWorkspacePrep.js) but the PR-claim check reads `metadata.openPR`
+// directly (agentTuiSpawning.js).
+ // * `worktreeChangesExpected` — a clean tree IS the success shape here, so the
+ // task's deliverable posture must record that this is not code work.
+// A guard test in taskSchedule.test.js asserts every member of that set carries
+// this posture, so a new coordinator type can't be added to one list only.
+const NON_COMMITTING_COORDINATOR_METADATA = { useWorktree: false, openPR: false, worktreeChangesExpected: false };
+// Migration 274 removes branch-cleanup from new schedules, but a partially
+// upgraded install may still load its stored task before the migration runs.
+// Keep its safety posture available without making it a newly-shipped task.
+const LEGACY_MANAGED_TASK_METADATA = {
+ 'branch-cleanup': NON_COMMITTING_COORDINATOR_METADATA
+};
+
+// Shared config for code-reviewer-a and code-reviewer-b (two instances for independent provider/model configuration)
+const CODE_REVIEWER_INTERVAL = { type: INTERVAL_TYPES.WEEKLY, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: true, simplify: true, pipeline: { stages: [{ name: 'Codebase Review', promptKey: 'code-reviewer-review', readOnly: true, providerId: null, model: null, precondition: { fileNotExists: 'REVIEW.md' } }, { name: 'Triage & Implement', promptKey: 'code-reviewer-implement', readOnly: false, providerId: null, model: null, precondition: { fileExists: 'REVIEW.md' } }] } } };
+
+/**
+ * Default `drainDispatchCap` for the reconcile drains: how many times a perpetual
+ * drain may dispatch back-to-back before it is parked regardless of how much
+ * progress it reports.
+ *
+ * The `lastActionableSignature` guard stops the drain only when a full cycle
+ * changes NOTHING. It cannot stop a drain whose set keeps changing without ever
+ * emptying — a branch that oscillates between two states, a coordinator that opens
+ * a PR one run and closes it the next, a repo where new work arrives as fast as it
+ * is finished. Those are indistinguishable from healthy progress one cycle at a
+ * time, and on 2026-08-12 that shape ran ~40 coordinator agents between 05:19 and
+ * 08:47 against the same two branches. So progress buys more cycles, not unlimited
+ * ones: past the cap the drain parks until its recheck cadence, which is a delay,
+ * never a dropped item — the branches are still there and the next recheck sees
+ * them. Five is enough for a legitimately long drain (open PR → CI → merge →
+ * cleanup) to finish a couple of branches per window.
+ *
+ * The count is very nearly "consecutive dispatches": every terminal park and every
+ * manual re-run zero it. The one gap is a FAILED run — it neither refills nor
+ * parks, so its spent dispatches carry into the next scheduled window and that
+ * window caps early. It self-heals within one window (the next park zeroes it), and
+ * erring toward capping early is the safe direction for a runaway guard.
+ *
+ * Why the cap is PER TYPE (`drainDispatchCap`) and not one global number: five is
+ * ample for finishing branches (a handful per day) but would throttle a HEALTHY
+ * claim-issue drain to five issues per recheck window — a real regression for a
+ * drain the user relies on running productively overnight. So the claim drains
+ * ship without the key at all (absent/`null` ⇒ unbounded, their work-detector's
+ * idle park remains the only brake) and only the reconcile scans carry a number.
+ */
+export const PERPETUAL_DRAIN_DISPATCH_CAP = 5;
+export const DEFAULT_BRANCHES_PER_AGENT = 3;
+
+export const DEFAULT_TASK_INTERVALS = {
+ 'security': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
+ 'code-quality': { type: INTERVAL_TYPES.ROTATION, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
+ 'test-coverage': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
+ 'performance': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
+ 'accessibility': { type: INTERVAL_TYPES.ONCE, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
+ // branch-reconcile first removes fully-merged, clean orphaned worktrees and
+ // branches, then finishes THIS machine's remaining in-flight LOCAL branches
+ // per app (open a PR for pushed-but-unopened work, resolve merge conflicts,
+ // drive the review loop, auto-merge when green). PERPETUAL (drain-until-done):
+ // the generator runs the deterministic reconcile every dispatch, and dispatches
+ // the coordinator agent only while actionable in-flight branches remain — then
+ // PARKS on the daily recheckCron. The action toggles (cleanupMerged / openPr /
+ // resolveConflicts / autoMerge / finishAbandoned) are per-app taskMetadata
+ // booleans (each ON unless explicitly false); `finishAbandoned` covers the work
+ // a dead agent left UNCOMMITTED in its worktree — commit + ship it, or report it
+ // as unfinished. `branchesPerAgent` bounds each coordinator prompt to a
+ // prioritized batch so a large backlog drains across several agents. It is
+ // independently overridable per app. useWorktree/openPR are LOCKED off
+ // (MANAGED_AGENT_OPTIONS):
+ // the coordinator runs in the app's live checkout so it can see + operate on the
+ // sibling worktrees; a CoS-managed worktree would hide the branches and could
+ // trigger cleanupAgentWorktree's auto-merge. Its edits likewise land in those
+ // SIBLING worktrees, never in its own cwd — hence the shared non-committing
+ // -coordinator posture above. Off by default — enabling it is the user's
+ // explicit consent to let it drive PRs on a schedule.
+ 'branch-reconcile': { type: INTERVAL_TYPES.PERPETUAL, enabled: false, providerId: null, model: null, prompt: null, recheckCron: '0 3 * * *', drainDispatchCap: PERPETUAL_DRAIN_DISPATCH_CAP, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA, cleanupMerged: true, openPr: true, resolveConflicts: true, autoMerge: true, finishAbandoned: true, branchesPerAgent: DEFAULT_BRANCHES_PER_AGENT } },
+ // issue-reconcile heals ZOMBIE issues: open + `in-progress` (claimed) yet with
+ // their PR already MERGED and no live claim anywhere — a partial ship left the
+ // claim marker on, so the queue (which skips `in-progress`) never re-picks the
+ // remaining scope. PERPETUAL (drain-until-done): the generator runs the
+ // deterministic gh/git scan every dispatch and dispatches the coordinator agent
+ // only while zombies remain — then PARKS on the daily recheckCron (offset an
+ // hour after branch-reconcile so merged-branch cleanup lands first). The
+ // coordinator applies the partial-ship hybrid per zombie (close + file a scoped
+ // follow-up when the remainder is separable, else comment "done/remaining" +
+ // release the claim). `autoClose` (ON unless explicitly false) is the only
+ // per-app toggle: OFF forbids closing/filing — comment + unlabel only.
+ // The coordinator works purely over `gh` — no code changes, no worktree, and
+ // issue-state mutation is its whole deliverable — hence the shared
+ // non-committing-coordinator posture above. Off by default — enabling it is the
+ // user's explicit consent to let it mutate issue state on a schedule.
+ 'issue-reconcile': { type: INTERVAL_TYPES.PERPETUAL, enabled: false, providerId: null, model: null, prompt: null, recheckCron: '0 4 * * *', drainDispatchCap: PERPETUAL_DRAIN_DISPATCH_CAP, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA, autoClose: true } },
+ 'console-errors': { type: INTERVAL_TYPES.ROTATION, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
+ 'dependency-updates': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null },
+ 'documentation': { type: INTERVAL_TYPES.ONCE, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
+ 'ui-bugs': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
+ 'mobile-responsive': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
+ // feature-ideas waits for do-replan so new work is grounded in a fresh PLAN.md
+ // that already accounts for any in-flight or unmerged work.
+ 'feature-ideas': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, runAfter: ['do-replan'], taskMetadata: { useWorktree: true, openPR: true, simplify: true } },
+ // plan-task is a strict executor of PLAN.md items — no brainstorm fallback, no
+ // runAfter deps. Picks the next unchecked item, implements it, and removes it
+ // from PLAN.md in the same commit (changelog + git log are the audit trail).
+ // plan-task (prompt v5+) drives the /claim flow itself — the agent creates its OWN `claim/<slug>` worktree, opens the PR, merges via `gh pr merge`, and cleans up.
+ // Both `useWorktree` and `openPR` are OFF on the CoS side:
+ // * `useWorktree: false` — CoS pre-creating a worktree under `cos/<task>/<agent>` would hide the slug from the in-flight branch scan AND trigger
+ // `cleanupAgentWorktree`'s auto-merge into whatever the source repo's HEAD is on (clobbering a TUI user's in-flight claim branch).
+ // * `openPR: false` — keeps the cos.js "openPR implies useWorktree" invariant from forcing useWorktree back on. The agent opens its own PR via `gh pr create`
+ // and merges via `gh pr merge`, so CoS doesn't need to.
+ // `claimFlow: true` is the lifecycle marker. It is deliberately separate from
+ // `openPR`: the former tells prompt/completion handling that the claim prompt
+ // owns push → PR/MR → review → merge/cleanup, while the latter tells CoS whether
+ // it should provision and publish a managed worktree. Conflating them sent
+ // claim agents into the generic commit-only handoff (#4153).
+ // The agent runs in the source repo's working directory; `git worktree add` doesn't touch that working tree, so it's safe even with uncommitted user changes.
+ 'plan-task': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: false, openPR: false, claimFlow: true, simplify: true } },
+ // claim-issue drives the /claim --issues flow — the agent creates its OWN
+ // claim/issue-<num> worktree, opens the PR (Closes #<num>), merges via
+ // `gh pr merge`, and cleans up. Both `useWorktree` and `openPR` are OFF on the
+ // CoS side for the SAME reasons as plan-task (a CoS-managed worktree under
+ // cos/<task>/<agent> would hide the issue-<num> slug from the in-flight scan
+ // and trigger cleanupAgentWorktree's auto-merge into the source repo's HEAD).
+ // `issueAuthorFilter` gates which issues are claimable: 'self' (default, the
+ // slashdo `/do:next --self` security boundary) only claims issues YOU filed
+ // (`@me`); 'collaborators' widens that to you plus every account with repo
+ // access (GitHub collaborators / GitLab project members); 'owner' only claims
+ // issues the repo owner filed; 'any' claims any open issue. Per-app override
+ // supported via taskTypeOverrides.
+ // `issueExcludeLabels` (default `[]`) lists ADDITIONAL labels to skip when
+ // auto-claiming, on top of the fixed NON_ACTIONABLE_ISSUE_LABELS set
+ // (perpetualWork.js) — e.g. `good first issue`, to leave those open for human
+ // contributors. Per-app override supported via taskTypeOverrides, like
+ // `issueAuthorFilter`.
+ 'claim-issue': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: false, openPR: false, claimFlow: true, simplify: true, issueAuthorFilter: 'self', issueExcludeLabels: [] } },
+ // claim-work is the SINGLE-SOURCE router: one toggle per app that ships the
+ // next work item from whatever tracker the app is configured for
+ // (app.workTracker, default 'auto' → resolved from the git origin host). At
+ // dispatch the generator resolves the tracker and delegates to the matching
+ // prompt body — plan→plan-task, github→claim-issue, gitlab→claim-issue-gitlab,
+ // jira→claim-issue-jira — so the agent still creates its OWN worktree and
+ // opens its OWN MR/PR. (jira routes to the per-ticket claim-issue-jira flow,
+ // NOT the broader jira-sprint-manager triage job, which stays standalone.)
+ // Both `useWorktree` and `openPR` are OFF on the CoS side
+ // for the SAME reasons as plan-task/claim-issue (a CoS-managed worktree would
+ // hide the claim slug and trigger cleanupAgentWorktree's auto-merge).
+ // `issueAuthorFilter` / `issueExcludeLabels` apply only when the resolved
+ // tracker is a forge (github/gitlab); both are inert for plan/jira.
+ 'claim-work': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: false, openPR: false, claimFlow: true, simplify: true, issueAuthorFilter: 'self', issueExcludeLabels: [] } },
+ 'error-handling': { type: INTERVAL_TYPES.ROTATION, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
+ 'typing': { type: INTERVAL_TYPES.ONCE, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: false } },
+ // Release-check inspects and mutates release state (for example, the main →
+ // release PR) rather than producing source commits. It must run from the app's
+ // live main checkout so its branch/ref checks describe the real release flow;
+ // a CoS worktree hides that checkout and creates an irrelevant task branch.
+ 'release-check': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA } },
+ // stash-cleanup triages `git stash list` and drops what's superseded/stale,
+ // leaving real unlanded work in place for the user to recover by hand. It
+ // runs in the app's live checkout (never a CoS worktree — a stash is a
+ // property of the checkout it was taken in) and, like the other coordinators,
+ // ships no code of its own. On-demand only: unlike branch/issue reconcile,
+ // there's no useful cadence for a stash a user hasn't necessarily touched
+ // since the last run — they trigger it when they notice stash clutter.
+ 'stash-cleanup': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA } },
+ 'pr-reviewer': { type: INTERVAL_TYPES.CUSTOM, intervalMs: 7200000, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null, taskMetadata: { readOnly: true, pipeline: { stages: [{ name: 'Security Scan', promptKey: 'pr-reviewer-security', readOnly: true }, { name: 'Code Review & Merge', promptKey: 'pr-reviewer-review', readOnly: false }] } } },
+ 'code-reviewer-a': { ...CODE_REVIEWER_INTERVAL },
+ 'code-reviewer-b': { ...CODE_REVIEWER_INTERVAL },
+ 'jira-sprint-manager': { type: INTERVAL_TYPES.DAILY, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: true, simplify: true } },
+ // jira-status-report posts its report to JIRA and edits nothing in the repo, so it
+ // takes the shared non-committing-coordinator posture above. `readOnly: true` alone
+ // was NOT enough: it skips worktree creation but leaves `openPR` free to be filled
+ // from the app's `defaultOpenPR`, and the finalize-time PR-claim check reads
+ // `metadata.openPR` directly — scoring a posted report as `pr-missing`.
+ 'jira-status-report': { type: INTERVAL_TYPES.WEEKLY, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA, readOnly: true } },
+ // do-replan audits PLAN.md after open PRs and stale branches have been cleaned up,
+ // so the plan reflects what actually merged.
+ 'do-replan': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, runAfter: ['pr-reviewer', 'branch-reconcile'], taskMetadata: { useWorktree: true, openPR: true } },
+ // Writable — the v2 reference-watch prompt (PROMPT_VERSIONS['reference-watch'] = 2)
+ // instructs the agent to APPEND slug-tagged `[ref-watch-…]` checklist items to
+ // PLAN.md and commit them. `readOnly: true` would inject the "do not modify or
+ // commit files" guard into the system prompt and the agent would refuse to write
+ // the PLAN entries — defeating the whole flow. Worktree off because the task body
+ // itself reads from data/cos/reference-repos (managed clones the user can't
+ // accidentally clobber) and the PLAN.md write is small enough that the in-place
+ // commit on the source repo is simpler than a worktree round-trip. Mirrors the
+ // on-commit trigger path in referenceRepos.js#triggerReferenceAnalysis.
+ // `readOnly` is coupled to PROMPT_VERSIONS['reference-watch'] — see
+ // REFERENCE_WATCH_AUDITED_VERSION above; bumping the prompt version requires
+ // re-auditing this default (a guard test in taskSchedule.test.js enforces it).
+ 'reference-watch': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { readOnly: false } },
+ // ux audits the RUNNING app UI. Defaults to filing tracker issues
+ // (`fileIssues: true`); flip that off to implement. `readOnly: false` so the
+ // PLAN.md path can commit checklist items / forge paths can `gh issue create`.
+ // Off by default (AI Provider Usage Policy — enabling it is the user's consent
+ // to a weekly browser-driving LLM run).
+ 'ux': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: true, useWorktree: false, openPR: false, readOnly: false } },
+ // data-safety / simplify are the scheduled counterparts of the quota-burn
+ // `data-safety-audit` and `simplify-audit` presets. New types default to
+ // file-issues so an unattended enable doesn't land code. Off by default.
+ 'data-safety': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },
+ 'simplify': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },
+ // pr-watcher polls for newly-opened PRs, so it runs on a short custom
+ // interval rather than the loose rotation/daily cadence. 30 min keeps the
+ // gh polling cheap while still reacting to a PR within one cycle. Default
+ // gate is `prAuthorFilter: 'any'` (react to every PR); the operator narrows
+ // it to 'self' or 'others' in the schedule UI. `readOnly: false` so a
+ // customized prompt can make changes if the operator wants — the shipped
+ // default prompt only reviews + comments.
+ 'pr-watcher': { type: INTERVAL_TYPES.CUSTOM, intervalMs: 1800000, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { prAuthorFilter: 'any', readOnly: false } },
+ // refresh-local-llm-catalog maintains PortOS's own bundled suggested-models
+ // catalog. CoS manages the worktree + PR (like feature-ideas/do-replan) — the
+ // agent only edits the catalog file. Weekly is generous; the prompt only opens
+ // a PR when the catalog is actually stale, so most runs are no-ops. Off by
+ // default; the user enables it on the PortOS app.
+ 'refresh-local-llm-catalog': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: true, simplify: true } },
+ // plan-feature files a plan, not code — tracker-filing posture mirrors
+ // reference-watch: writable (a file-based tracker commits checklist items), no
+ // managed worktree, no PR. Weekly (not daily like feature-ideas) so an
+ // enabled run doesn't flood the tracker with plans — one filed plan per run.
+ // runAfter do-replan so proposals are checked against the freshest available
+ // work tracker before a new feature plan is filed.
+ 'plan-feature': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, runAfter: ['do-replan'], taskMetadata: { useWorktree: false, openPR: false, readOnly: false } },
+ // layered-intelligence is a programmatic-I/O task (agent-backed, hooked). Daily
+ // by default; per-app scheduling (enabled/interval/provider/model) is set in the
+ // Intelligence tab and stored on the app's taskTypeOverrides['layered-intelligence'].
+ // No `prompt` field — the buildTaskInput hook renders the prompt (no
+ // DEFAULT_TASK_PROMPTS entry, so the prompt-version machinery in loadSchedule
+ // skips it). taskMetadata pins the throwaway-worktree posture: the reasoning
+ // agent runs in a worktree that is discarded without a commit/merge/PR
+ // (discardWorktree), so it can't land code — its `.agent-done` payload is the
+ // only sanctioned output (consumed by the processTaskOutput hook).
+ 'layered-intelligence': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: false, discardWorktree: true } }
+};
+
+// Agent-options that a task manages internally — UI locks the toggle, and
+// loadSchedule/updateTaskInterval enforce the default value regardless of
+// what's persisted or POSTed. The reasoning lives next to each task above
+// (e.g., plan-task's prompt creates its own claim/<slug> worktree, so a
+// CoS-managed worktree would clobber it).
+export const MANAGED_AGENT_OPTIONS = {
+ 'plan-task': ['useWorktree', 'openPR', 'claimFlow'],
+ // The non-committing coordinators (NON_COMMITTING_COORDINATOR_METADATA above) all
+ // run in the app's LIVE checkout and ship no code, so a CoS-managed worktree is at
+ // best unused and at worst harmful — branch-reconcile needs to see the sibling
+ // worktrees of the in-flight branches (a managed worktree hides them from the scan
+ // AND could trip cleanupAgentWorktree's auto-merge). Locking both off also keeps the
+ // finalize-time PR-claim check from scoring a completed run `pr-missing`.
+ //
+ // `worktreeChangesExpected` is managed for these coordinators as well — the one type-keyed
+ // exception to it being a free per-app override. A clean tree is definitionally the
+ // success shape for a branch deletion or a posted report, so setting it back to
+ // `true` can only make successful runs fail; it is exactly as non-negotiable here as
+ // the other two. Managing it is also what carries it through an explicit
+ // `taskMetadata: null` clear — loadSchedule preserves that null (skipping the
+ // defaults deep-merge), and enforceManagedAgentOptions rebuilds only the MANAGED
+ // fields, so an unmanaged `worktreeChangesExpected` would silently go absent and the
+ // task bookkeeping would otherwise treat the clean worktree as missing code work.
+ ...Object.fromEntries(
+ ['branch-reconcile', 'branch-cleanup', 'issue-reconcile', 'jira-status-report']
+ .map((t) => [t, ['useWorktree', 'openPR', 'worktreeChangesExpected']])
+ ),
+ // claim-issue's prompt creates its own claim/issue-<num> worktree (same
+ // rationale as plan-task), so CoS must not pre-create one or open the PR.
+ 'claim-issue': ['useWorktree', 'openPR', 'claimFlow'],
+ // claim-work delegates to one of the above prompt bodies, each of which
+ // creates its own worktree + PR — so the same lock applies to the router.
+ 'claim-work': ['useWorktree', 'openPR', 'claimFlow'],
+ 'release-check': ['useWorktree', 'openPR', 'worktreeChangesExpected'],
+ 'stash-cleanup': ['useWorktree', 'openPR', 'worktreeChangesExpected']
+};
+
+// Strip managed-agent fields from a per-app override map before merging on top
+// of the (already-enforced) global config. Without this, an app-level override
+// for a managed field (e.g. `plan-task.useWorktree=false`) carries through into
+// the task spawn even though the UI toggle is locked, defeating the lock's
+// intent. Returns the cleaned metadata (or null if every key was managed).
+export function stripManagedAgentOptionsFromOverride(taskType, taskMetadata) {
+ const managed = MANAGED_AGENT_OPTIONS[taskType];
+ if (!managed || !taskMetadata || typeof taskMetadata !== 'object') return taskMetadata;
+ const cleaned = { ...taskMetadata };
+ for (const field of managed) delete cleaned[field];
+ return Object.keys(cleaned).length ? cleaned : null;
+}
+
+export function enforceManagedAgentOptions(taskType, config) {
+ const managed = MANAGED_AGENT_OPTIONS[taskType];
+ if (!managed || !config) return false;
+ const defaults = DEFAULT_TASK_INTERVALS[taskType]?.taskMetadata
+ || LEGACY_MANAGED_TASK_METADATA[taskType]
+ || {};
+ let changed = false;
+ // If the stored config explicitly cleared taskMetadata (or never had it),
+ // we still need the managed fields present — otherwise upstream resolvers
+ // (e.g., cos.js applyAppWorktreeDefault) can flip them on via app defaults.
+ if (!config.taskMetadata || typeof config.taskMetadata !== 'object' || Array.isArray(config.taskMetadata)) {
+ config.taskMetadata = {};
+ changed = true;
+ }
+ for (const field of managed) {
+ if (config.taskMetadata[field] !== defaults[field]) {
+ config.taskMetadata[field] = defaults[field];
+ changed = true;
+ }
+ }
+ return changed;
+}
+
+// The batch size is user-configurable, but an old schedule or an explicit
+// metadata clear must not silently restore the pre-batch all-at-once behavior.
+// Keep the persisted global task on the same safe default as a fresh install;
+// per-app overrides still layer on top of it at dispatch time.
+export function enforceBranchReconcileBatch(taskType, config) {
+ if (taskType !== 'branch-reconcile' || !config) return false;
+ if (!config.taskMetadata || typeof config.taskMetadata !== 'object' || Array.isArray(config.taskMetadata)) {
+ config.taskMetadata = {};
+ }
+ const value = config.taskMetadata.branchesPerAgent;
+ if (!Number.isInteger(value) || value < BRANCHES_PER_AGENT_MIN || value > BRANCHES_PER_AGENT_MAX) {
+ config.taskMetadata.branchesPerAgent = DEFAULT_BRANCHES_PER_AGENT;
+ return true;
+ }
+ return false;
+}
+
+// Short human-readable blurb per task type, shown in the schedule UI's
+// upcoming-tasks list. Every entry in SELF_IMPROVEMENT_TASK_TYPES must have a
+// key here — a missing one falls back to a dasherized label ("claim work"),
+// which reads as an orphaned/legacy task. A parity guard in taskSchedule.test.js
+// fails the suite if the two ever drift apart.
+export const TASK_TYPE_DESCRIPTIONS = {
+ 'ui-bugs': 'Find UI bugs — file issues or implement fixes',
+ 'mobile-responsive': 'Mobile/responsive audit — file issues or implement fixes',
+ 'security': 'Security audit — file issues or implement fixes',
+ 'code-quality': 'Code quality — file issues or implement fixes',
+ 'console-errors': 'Console errors — file issues or implement fixes',
+ 'performance': 'Performance audit — file issues or implement fixes',
+ 'test-coverage': 'Test coverage — file issues or add tests',
+ 'documentation': 'Docs drift — file issues or implement fixes',
+ 'feature-ideas': 'Implement next planned feature or brainstorm new one',
+ 'plan-task': 'Execute next PLAN.md item, remove it from PLAN.md, log to changelog (worktree+PR)',
+ 'claim-issue': 'Claim and ship the next open GitHub issue (owner-filed or any author), PR closes it',
+ 'claim-work': "Ship the next work item from the app's configured tracker (PLAN.md, GitHub/GitLab issues, or JIRA), routed automatically",
+ 'accessibility': 'Accessibility audit — file issues or implement fixes',
+ 'branch-reconcile': "Finish this machine's in-flight local branches: clean up merged ones, open PRs, resolve conflicts, drive review, auto-merge when green",
+ 'issue-reconcile': "Heal zombie issues: open + in-progress but their PR already merged with no live claim — close + file a scoped follow-up when work remains, or release the claim so the queue re-picks it",
+ 'dependency-updates': 'Land or resolve open Dependabot/Renovate PRs, then update the dependencies they missed',
+ 'release-check': 'Check for release readiness',
+ 'error-handling': 'Failure-path audit — file issues or implement fixes',
+ 'typing': 'TypeScript types — file issues or implement fixes',
+ 'pr-reviewer': 'Review open PRs from contributors',
+ 'pr-watcher': 'Run a custom prompt on PRs newly opened against the default branch',
+ 'code-reviewer-a': 'Review the codebase and triage/implement findings (independent provider/model instance A)',
+ 'code-reviewer-b': 'Review the codebase and triage/implement findings (independent provider/model instance B)',
+ 'do-replan': 'Audit and prune PLAN.md after merges and branch cleanup so it reflects what actually shipped',
+ 'jira-sprint-manager': 'Triage and implement JIRA sprint tickets',
+ 'jira-status-report': 'Generate JIRA weekly status report',
+ 'reference-watch': 'Watch reference repos and append PLAN.md items for new upstream work',
+ 'ux': 'UX/design audit — file issues (default) or implement fixes',
+ 'data-safety': 'Data/upgrade-safety audit — file issues (default) or implement fixes',
+ 'simplify': 'Dead-code/duplication audit — file issues (default) or implement removals',
+ 'stash-cleanup': 'Triage git stash list — drop entries superseded by or stale relative to main, leave real unlanded work in place',
+ 'refresh-local-llm-catalog': "Refresh PortOS's bundled suggested local-model catalog + editorial ranking (PortOS repo only)",
+ 'plan-feature': "Brainstorm one feature and file its decision-complete plan to the app's work tracker (no code)",
+ 'layered-intelligence': "Read this app's goals + telemetry, ask a reasoning model for one improvement, and file one deduplicated tracker issue — no code, no agent"
+};
+
+export function getTaskTypeDescription(taskType) {
+ return TASK_TYPE_DESCRIPTIONS[taskType] || taskType.replace(/-/g, ' ');
+}
diff --git a/server/services/taskScheduleStore.js b/server/services/taskScheduleStore.js
new file mode 100644
index 0000000000..bef62a8530
--- /dev/null
+++ b/server/services/taskScheduleStore.js
@@ -0,0 +1,272 @@
+/** Persisted task schedule state and prompt-default compatibility upgrades. */
+
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
+import { isPlainObject } from '../lib/objects.js';
+import { emitLog } from './cosEvents.js';
+import { INTERVAL_TYPES } from './taskScheduleConstants.js';
+import {
+ DEFAULT_TASK_INTERVALS,
+ enforceBranchReconcileBatch,
+ enforceManagedAgentOptions
+} from './taskScheduleRegistry.js';
+import {
+ DEFAULT_TASK_PROMPTS,
+ PROMPT_VERSIONS,
+ PREVIOUS_DEFAULT_PROMPTS
+} from './taskPromptDefaults.js';
+
+const DATA_DIR = PATHS.cos;
+const SCHEDULE_FILE = join(DATA_DIR, 'task-schedule.json');
+
+/**
+ * Default schedule data structure (v2 - unified)
+ */
+const DEFAULT_SCHEDULE = {
+ version: 2,
+ lastUpdated: null,
+
+ // Unified task intervals (applies to all apps including PortOS)
+ tasks: {
+ ...DEFAULT_TASK_INTERVALS
+ },
+
+ // Track last execution times
+ // Format: 'task:security': { lastRun: timestamp, count: number, perApp: {} }
+ executions: {},
+
+ // On-demand task templates that can be triggered manually
+ templates: []
+};
+
+async function ensureDataDir() {
+ if (!existsSync(DATA_DIR)) {
+ await ensureDir(DATA_DIR);
+ }
+}
+
+/**
+ * Migrate v1 schedule (selfImprovement + appImprovement) to v2 (unified tasks)
+ */
+function migrateScheduleV1toV2(schedule) {
+ emitLog('info', 'Migrating task schedule from v1 to v2 (unified)', {}, '📅 TaskSchedule');
+
+ const migrated = {
+ version: 2,
+ lastUpdated: new Date().toISOString(),
+ tasks: { ...DEFAULT_TASK_INTERVALS },
+ executions: {},
+ templates: schedule.templates || [],
+ onDemandRequests: schedule.onDemandRequests || []
+ };
+
+ // Merge selfImprovement settings into tasks (excluding cos-enhancement)
+ if (schedule.selfImprovement) {
+ for (const [taskType, config] of Object.entries(schedule.selfImprovement)) {
+ if (taskType === 'cos-enhancement') continue; // Removed
+ // security stays as 'security' (was already named this in selfImprovement)
+ if (migrated.tasks[taskType]) {
+ migrated.tasks[taskType] = { ...migrated.tasks[taskType], ...config };
+ }
+ }
+ }
+
+ // Merge appImprovement settings into tasks
+ if (schedule.appImprovement) {
+ for (const [taskType, config] of Object.entries(schedule.appImprovement)) {
+ // Rename security-audit → security
+ const unifiedType = taskType === 'security-audit' ? 'security' : taskType;
+ if (migrated.tasks[unifiedType]) {
+ // If selfImprovement already set a non-default config, prefer it for overlapping types
+ // unless appImprovement has a different non-default config
+ const existing = migrated.tasks[unifiedType];
+ const isExistingDefault = existing.type === DEFAULT_TASK_INTERVALS[unifiedType]?.type;
+ const isNewDifferent = config.type !== (taskType === 'security-audit'
+ ? INTERVAL_TYPES.WEEKLY : DEFAULT_TASK_INTERVALS[unifiedType]?.type);
+ if (isExistingDefault || isNewDifferent) {
+ migrated.tasks[unifiedType] = { ...existing, ...config };
+ }
+ }
+ }
+ }
+
+ // Migrate execution keys: self-improve:X → task:X, app-improve:X → task:X
+ if (schedule.executions) {
+ for (const [key, data] of Object.entries(schedule.executions)) {
+ let newKey = key;
+ if (key.startsWith('self-improve:')) {
+ const taskType = key.replace('self-improve:', '');
+ if (taskType === 'cos-enhancement') continue; // Removed
+ newKey = `task:${taskType}`;
+ } else if (key.startsWith('app-improve:')) {
+ let taskType = key.replace('app-improve:', '');
+ if (taskType === 'security-audit') taskType = 'security';
+ newKey = `task:${taskType}`;
+ }
+
+ if (migrated.executions[newKey]) {
+ // Merge: combine counts, keep latest lastRun, merge perApp
+ const existing = migrated.executions[newKey];
+ existing.count = (existing.count || 0) + (data.count || 0);
+ if (data.lastRun && (!existing.lastRun || new Date(data.lastRun) > new Date(existing.lastRun))) {
+ existing.lastRun = data.lastRun;
+ }
+ if (data.perApp) {
+ existing.perApp = { ...existing.perApp, ...data.perApp };
+ }
+ } else {
+ migrated.executions[newKey] = { ...data };
+ }
+ }
+ }
+
+ // Populate prompts from defaults if missing
+ for (const [taskType, config] of Object.entries(migrated.tasks)) {
+ if (!config.prompt && DEFAULT_TASK_PROMPTS[taskType]) {
+ config.prompt = DEFAULT_TASK_PROMPTS[taskType];
+ }
+ }
+
+ return migrated;
+}
+
+// True when a stored prompt byte-matches a shipped default for this task — the
+// current default or any prior one in PREVIOUS_DEFAULT_PROMPTS. Used by
+// loadSchedule both to recognize legacy (unversioned) prompts and to self-heal a
+// prompt mis-flagged as customized. A genuine user edit never byte-matches a
+// shipped default, so callers can treat a match as "not really customized".
+function promptMatchesShippedDefault(prompt, taskType) {
+ if (!prompt || !DEFAULT_TASK_PROMPTS[taskType]) return false;
+ return (
+ prompt === DEFAULT_TASK_PROMPTS[taskType] ||
+ (PREVIOUS_DEFAULT_PROMPTS[taskType] || []).includes(prompt)
+ );
+}
+
+/**
+ * Load schedule data (auto-migrates from v1 if needed)
+ */
+export async function loadSchedule() {
+ await ensureDataDir();
+
+ const loaded = await readJSONFile(SCHEDULE_FILE, null);
+ if (!loaded) {
+ return { ...DEFAULT_SCHEDULE };
+ }
+
+ // Auto-migrate v1 → v2
+ if (!loaded.version || loaded.version === 1) {
+ const migrated = migrateScheduleV1toV2(loaded);
+ await saveSchedule(migrated);
+ return migrated;
+ }
+
+ // v2: merge each task config with its default to backfill new fields
+ // Deep-merge taskMetadata so new default keys are inherited unless explicitly overridden
+ const mergedTasks = {};
+ for (const taskType of Object.keys(DEFAULT_TASK_INTERVALS)) {
+ const defaultTask = DEFAULT_TASK_INTERVALS[taskType];
+ const loadedTask = loaded.tasks?.[taskType] || {};
+ const merged = { ...defaultTask, ...loadedTask };
+ // Deep-merge taskMetadata: preserve explicit null (clears metadata), otherwise merge defaults with stored
+ // Only spread if loadedTask.taskMetadata is a plain object to avoid corrupting config
+ if (defaultTask.taskMetadata && loadedTask.taskMetadata !== null) {
+ const storedMeta = loadedTask.taskMetadata;
+ merged.taskMetadata = { ...defaultTask.taskMetadata, ...(isPlainObject(storedMeta) ? storedMeta : {}) };
+ }
+ mergedTasks[taskType] = merged;
+ }
+ // Preserve any extra task types from loaded that aren't in defaults
+ for (const taskType of Object.keys(loaded.tasks || {})) {
+ if (!mergedTasks[taskType]) {
+ mergedTasks[taskType] = loaded.tasks[taskType];
+ }
+ }
+
+ const schedule = {
+ ...DEFAULT_SCHEDULE,
+ ...loaded,
+ tasks: mergedTasks,
+ executions: loaded.executions || {},
+ templates: loaded.templates || []
+ };
+
+ // Populate prompts from defaults if missing, and auto-upgrade stale defaults
+ let needsSave = false;
+ for (const [taskType, config] of Object.entries(schedule.tasks)) {
+ if (enforceManagedAgentOptions(taskType, config)) needsSave = true;
+ if (enforceBranchReconcileBatch(taskType, config)) needsSave = true;
+ // Stamp a creation timestamp the first time we see a task so the cron
+ // catch-up bound (shouldRunTask) never replays a slot that predates the
+ // task. Backfilling to "now" is conservative: it only suppresses catch-up
+ // for slots already in the past — future slots fire on their real cadence.
+ if (!config.createdAt) {
+ config.createdAt = new Date().toISOString();
+ needsSave = true;
+ }
+ if (!config.prompt && DEFAULT_TASK_PROMPTS[taskType]) {
+ // No prompt set — initialize with current default and version
+ config.prompt = DEFAULT_TASK_PROMPTS[taskType];
+ config.promptVersion = PROMPT_VERSIONS[taskType] || 1;
+ needsSave = true;
+ } else {
+ // Legacy migration: infer customization when promptVersion is missing
+ if (
+ config.prompt &&
+ config.promptVersion === undefined &&
+ DEFAULT_TASK_PROMPTS[taskType]
+ ) {
+ if (config.prompt === DEFAULT_TASK_PROMPTS[taskType]) {
+ // Matches current default — assign current version (no upgrade needed)
+ config.promptVersion = PROMPT_VERSIONS[taskType] || 1;
+ needsSave = true;
+ } else if ((PREVIOUS_DEFAULT_PROMPTS[taskType] || []).includes(config.prompt)) {
+ // Matches a known previous default — assign version 1 so auto-upgrade triggers
+ config.promptVersion = 1;
+ needsSave = true;
+ } else {
+ // Prompt differs from all known defaults — treat as user-customized
+ config.promptCustomized = true;
+ config.promptVersion = PROMPT_VERSIONS[taskType] || 1;
+ needsSave = true;
+ }
+ }
+
+ // Self-heal a mis-flagged customization: a prompt marked promptCustomized
+ // that nonetheless byte-matches a shipped default was never user-edited —
+ // it was flagged by an earlier legacy migration that ran before this task
+ // carried a PREVIOUS_DEFAULT_PROMPTS entry (e.g. the basic self-improvement
+ // prompts that hardcoded the app name as "PortOS"). Clear the flag so the
+ // auto-upgrade below can replace the stale default.
+ if (config.promptCustomized && promptMatchesShippedDefault(config.prompt, taskType)) {
+ config.promptCustomized = false;
+ needsSave = true;
+ }
+
+ if (PROMPT_VERSIONS[taskType] && !config.promptCustomized) {
+ // Auto-upgrade non-customized prompts when code version is newer
+ const storedVersion = config.promptVersion || 1;
+ if (storedVersion < PROMPT_VERSIONS[taskType]) {
+ emitLog('info', `Upgrading ${taskType} prompt v${storedVersion} → v${PROMPT_VERSIONS[taskType]}`, { taskType }, '📅 TaskSchedule');
+ config.prompt = DEFAULT_TASK_PROMPTS[taskType];
+ config.promptVersion = PROMPT_VERSIONS[taskType];
+ needsSave = true;
+ }
+ }
+ }
+ }
+
+ if (needsSave) {
+ await saveSchedule(schedule);
+ }
+
+ return schedule;
+}
+
+export async function saveSchedule(schedule) {
+ await ensureDataDir();
+ schedule.lastUpdated = new Date().toISOString();
+ await atomicWrite(SCHEDULE_FILE, schedule);
+}
+
diff --git a/server/services/taskScheduleTemplates.js b/server/services/taskScheduleTemplates.js
new file mode 100644
index 0000000000..b51a02b8ab
--- /dev/null
+++ b/server/services/taskScheduleTemplates.js
@@ -0,0 +1,50 @@
+/** User-defined task templates stored with the task schedule. */
+
+import { emitLog } from './cosEvents.js';
+import { loadSchedule, saveSchedule } from './taskScheduleStore.js';
+
+// ============================================================
+// Templates
+// ============================================================
+
+export async function addTemplateTask(template) {
+ const schedule = await loadSchedule();
+
+ const newTemplate = {
+ id: `template-${Date.now().toString(36)}`,
+ createdAt: new Date().toISOString(),
+ name: template.name,
+ description: template.description,
+ category: template.category || 'custom',
+ taskType: template.taskType,
+ priority: template.priority || 'MEDIUM',
+ metadata: template.metadata || {}
+ };
+
+ schedule.templates.push(newTemplate);
+ await saveSchedule(schedule);
+
+ emitLog('info', `Added template task: ${newTemplate.name}`, { templateId: newTemplate.id }, '📅 TaskSchedule');
+ return newTemplate;
+}
+
+export async function getTemplateTasks() {
+ const schedule = await loadSchedule();
+ return schedule.templates;
+}
+
+export async function deleteTemplateTask(templateId) {
+ const schedule = await loadSchedule();
+ const index = schedule.templates.findIndex(t => t.id === templateId);
+
+ if (index === -1) {
+ return { error: 'Template not found' };
+ }
+
+ const deleted = schedule.templates.splice(index, 1)[0];
+ await saveSchedule(schedule);
+
+ emitLog('info', `Deleted template task: ${deleted.name}`, { templateId }, '📅 TaskSchedule');
+ return { success: true, deleted };
+}
+