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

feat([issue-2322]): migrate Layered Intelligence to a per-app scheduled task

[._.]/ Adam Eivye7701f667c0e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 4ff74baa34..b84d671e92 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,9 @@
# Unreleased
+## Layered Intelligence
+
+- **[issue-2322] Layered Intelligence is now a per-app scheduled task, not a global sweep.** The self-improvement loop used to run as a single global "Layered Intelligence Loop" job that swept every enabled app on one daily fire, with a confusing split between a global on/off (CoS → System Tasks) and per-app config (Edit App → Intelligence) — a per-app card could read "Enabled · Due now" while nothing ran. It now runs like every other self-improvement automation: a per-app, deterministic, handler-backed task in CoS → Schedule with its own per-app enable, interval, provider/model, and "Run now". Enabling the `layered-intelligence` task in the Schedule (plus per app on the Intelligence tab) drives it; the reasoning model still only returns JSON and files one deduplicated tracker issue — no code, no agent. Per-app behavior (telemetry sources, allowed scopes, guidance rules, hand-off) still lives on the app's Intelligence tab. An install upgrade migrates each app's scheduling into its per-app task override and tombstones the old global job, preserving effective on/off state. Note: because it's now a self-improvement task, the loop runs only while CoS improvement is enabled.
+
## Fixed
- **Layered Intelligence loop now supports every provider type.** The per-app AI-provider picker previously listed only `cli` providers, while the reasoning call went through the api-only `callProviderAISimple` — so a selected CLI provider failed at runtime with "requires an API-based provider," and API/TUI providers (Ollama, LM Studio, Claude/Codex/OpenCode TUI, etc.) never appeared at all. The reasoning call now routes through the unified `runPromptThroughProvider`, which dispatches on `provider.type`, and the picker lists all enabled `cli`/`api`/`tui` providers. CLI/TUI spawns run in the app's repo (`cwd`).
diff --git a/client/src/components/apps/EditAppDrawer.jsx b/client/src/components/apps/EditAppDrawer.jsx
index 83205a608b..0b6bd4b954 100644
--- a/client/src/components/apps/EditAppDrawer.jsx
+++ b/client/src/components/apps/EditAppDrawer.jsx
@@ -9,7 +9,7 @@ import Drawer from '../Drawer';
import Banner from '../ui/Banner';
import useDrawerTab from '../../hooks/useDrawerTab';
import { copyToClipboard } from '../../lib/clipboard';
-import LayeredIntelligenceTab, { buildLayeredIntelligenceUpdate } from './LayeredIntelligenceTab';
+import LayeredIntelligenceTab, { buildLayeredIntelligenceUpdate, buildLayeredIntelligenceScheduleUpdate } from './LayeredIntelligenceTab';
import { PROVIDER_TYPES } from '../../utils/providers';
const WORK_TRACKER_OPTIONS = [
@@ -166,10 +166,25 @@ export default function EditAppDrawer({ app, onClose, onSave }) {
setLiError(false);
Promise.all([
api.getAppLayeredIntelligence(app.id),
- api.getProviders({ silent: true }).catch(() => ({ providers: [] }))
- ]).then(([li, provData]) => {
+ api.getProviders({ silent: true }).catch(() => ({ providers: [] })),
+ // Scheduling (enabled/interval/provider/model) lives in the per-app task
+ // override now (#2322); behavior (sources/scopes/rules/handoff) stays in the
+ // layeredIntelligence config. Merge the override on top so the tab shows the
+ // scheduling source of truth.
+ api.getAppTaskTypes(app.id).catch(() => ({ taskTypeOverrides: {} }))
+ ]).then(([li, provData, taskTypes]) => {
if (cancelled) return;
- const cfg = li?.config || null;
+ const behavior = li?.config || null;
+ const ov = taskTypes?.taskTypeOverrides?.['layered-intelligence'] || {};
+ const cfg = behavior
+ ? {
+ ...behavior,
+ enabled: ov.enabled === true,
+ intervalMs: (typeof ov.intervalMs === 'number' && ov.intervalMs > 0) ? ov.intervalMs : behavior.intervalMs,
+ providerId: ov.providerId ?? null,
+ model: ov.model ?? null
+ }
+ : null;
setLiConfig(cfg);
setLiBaseline(cfg);
setLiIsPortos(!!li?.isPortos);
@@ -372,10 +387,10 @@ export default function EditAppDrawer({ app, onClose, onSave }) {
} : { enabled: false }
};
- // Only send layeredIntelligence when the user actually changed something —
- // the server merges the PATCH over the STORED config, so an unchanged config
- // must stay absent (persisting the full effective config would freeze this
- // install against future default changes).
+ // Only send layeredIntelligence when the user actually changed a BEHAVIOR
+ // field (sources/scopes/rules/handoff) — the server merges the PATCH over the
+ // STORED config, so an unchanged config must stay absent (persisting the full
+ // effective config would freeze this install against future default changes).
const liUpdate = buildLayeredIntelligenceUpdate(liBaseline, liConfig);
if (liUpdate) data.layeredIntelligence = liUpdate;
@@ -385,6 +400,18 @@ export default function EditAppDrawer({ app, onClose, onSave }) {
throw err;
});
+ // Scheduling (enabled/interval/provider/model) is stored on the per-app task
+ // override (#2322), NOT app.layeredIntelligence — PUT it separately when the
+ // user changed a scheduling field.
+ const schedUpdate = buildLayeredIntelligenceScheduleUpdate(liBaseline, liConfig);
+ if (schedUpdate) {
+ await api.updateAppTaskTypeOverride(app.id, 'layered-intelligence', schedUpdate, { silent: true }).catch(err => {
+ setError(err.message);
+ setSaving(false);
+ throw err;
+ });
+ }
+
setSaving(false);
onSave();
};
diff --git a/client/src/components/apps/EditAppDrawer.test.jsx b/client/src/components/apps/EditAppDrawer.test.jsx
index a8e7b85baa..e44b8fd315 100644
--- a/client/src/components/apps/EditAppDrawer.test.jsx
+++ b/client/src/components/apps/EditAppDrawer.test.jsx
@@ -10,6 +10,8 @@ vi.mock('../../services/api', () => ({
getJiraProjects: vi.fn(),
getAppWorkTracker: vi.fn(),
getAppLayeredIntelligence: vi.fn(),
+ getAppTaskTypes: vi.fn(),
+ updateAppTaskTypeOverride: vi.fn(),
getProviders: vi.fn(),
updateApp: vi.fn(),
upgradeAppTls: vi.fn(),
@@ -66,6 +68,10 @@ beforeEach(() => {
},
});
api.getProviders.mockResolvedValue({ providers: [] });
+ // Scheduling (enabled/interval/provider/model) is read from the per-app task
+ // override now (#2322); default to an empty override.
+ api.getAppTaskTypes.mockResolvedValue({ taskTypeOverrides: {} });
+ api.updateAppTaskTypeOverride.mockResolvedValue({ success: true });
api.updateApp.mockResolvedValue({});
});
diff --git a/client/src/components/apps/LayeredIntelligenceTab.jsx b/client/src/components/apps/LayeredIntelligenceTab.jsx
index 6a6dc97663..715d3a5cbe 100644
--- a/client/src/components/apps/LayeredIntelligenceTab.jsx
+++ b/client/src/components/apps/LayeredIntelligenceTab.jsx
@@ -90,23 +90,21 @@ function sameCustom(a, b) {
}
/**
- * Build the minimal Layered Intelligence PATCH: only the top-level keys whose
- * value differs from the effective baseline the drawer loaded. Sending the full
- * effective config would persist every default to disk and freeze this install
- * against future default changes — the server's merge-over-stored contract
+ * Build the minimal Layered Intelligence BEHAVIOR PATCH: only the top-level
+ * behavior keys (rules / sources / allowedScopes / handoff) whose value differs
+ * from the effective baseline the drawer loaded. Sending the full effective config
+ * would persist every default to disk and freeze this install against future
+ * default changes — the server's merge-over-stored contract
* (updateAppLayeredIntelligence) depends on untouched fields staying absent.
* Returns null when nothing changed (caller then omits `layeredIntelligence`).
- * providerId/model normalize '' → null (the "use default" sentinel).
+ *
+ * SCHEDULING fields (enabled / intervalMs / providerId / model) are NOT included
+ * here — they live in the per-app task override now (#2322) and are diffed by
+ * `buildLayeredIntelligenceScheduleUpdate` below.
*/
export function buildLayeredIntelligenceUpdate(baseline, current) {
if (!baseline || !current) return null;
const update = {};
- if (!!current.enabled !== !!baseline.enabled) update.enabled = !!current.enabled;
- if (current.intervalMs !== baseline.intervalMs) update.intervalMs = current.intervalMs;
- const curProvider = current.providerId || null;
- if (curProvider !== (baseline.providerId || null)) update.providerId = curProvider;
- const curModel = current.model || null;
- if (curModel !== (baseline.model || null)) update.model = curModel;
if ((current.rules || '') !== (baseline.rules || '')) update.rules = current.rules || '';
const curSources = current.sources || {};
@@ -132,6 +130,44 @@ export function buildLayeredIntelligenceUpdate(baseline, current) {
return Object.keys(update).length > 0 ? update : null;
}
+const DAY_MS = 24 * 60 * 60 * 1000;
+const WEEK_MS = 7 * DAY_MS;
+
+// Map a chosen intervalMs to the per-app override's { interval, intervalMs } pair
+// the scheduler understands: 'daily'/'weekly' for the standard cadences, else
+// 'custom' (the scheduler's CUSTOM branch reads the numeric intervalMs). Mirrors
+// the server migration's intervalFieldsFromMs.
+export function intervalFieldsFromMs(intervalMs) {
+ const ms = typeof intervalMs === 'number' && intervalMs > 0 ? intervalMs : DAY_MS;
+ if (ms === DAY_MS) return { interval: 'daily', intervalMs: ms };
+ if (ms === WEEK_MS) return { interval: 'weekly', intervalMs: ms };
+ return { interval: 'custom', intervalMs: ms };
+}
+
+/**
+ * Build the minimal per-app SCHEDULING override PATCH for the layered-intelligence
+ * task type (enabled / interval+intervalMs / providerId / model) — only the fields
+ * the user changed vs the baseline. Returns null when nothing changed (caller then
+ * skips the task-override PUT). providerId/model normalize '' → null (the "use
+ * default" sentinel). When the interval changes, both `interval` and `intervalMs`
+ * are sent so the scheduler resolves the cadence correctly.
+ */
+export function buildLayeredIntelligenceScheduleUpdate(baseline, current) {
+ if (!baseline || !current) return null;
+ const update = {};
+ if (!!current.enabled !== !!baseline.enabled) update.enabled = !!current.enabled;
+ if (current.intervalMs !== baseline.intervalMs) {
+ const { interval, intervalMs } = intervalFieldsFromMs(current.intervalMs);
+ update.interval = interval;
+ update.intervalMs = intervalMs;
+ }
+ const curProvider = current.providerId || null;
+ if (curProvider !== (baseline.providerId || null)) update.providerId = curProvider;
+ const curModel = current.model || null;
+ if (curModel !== (baseline.model || null)) update.model = curModel;
+ return Object.keys(update).length > 0 ? update : null;
+}
+
/**
* Presentational Layered Intelligence config tab. All mutable state lives in the
* parent EditAppDrawer's `formData` (the Drawer body remounts per tab), so this
diff --git a/client/src/components/apps/LayeredIntelligenceTab.test.jsx b/client/src/components/apps/LayeredIntelligenceTab.test.jsx
index 67dc89a8b9..b59a8cc566 100644
--- a/client/src/components/apps/LayeredIntelligenceTab.test.jsx
+++ b/client/src/components/apps/LayeredIntelligenceTab.test.jsx
@@ -1,6 +1,6 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
-import LayeredIntelligenceTab, { buildLayeredIntelligenceUpdate } from './LayeredIntelligenceTab';
+import LayeredIntelligenceTab, { buildLayeredIntelligenceUpdate, buildLayeredIntelligenceScheduleUpdate, intervalFieldsFromMs } from './LayeredIntelligenceTab';
const baseline = {
enabled: false,
@@ -22,14 +22,12 @@ describe('buildLayeredIntelligenceUpdate', () => {
expect(buildLayeredIntelligenceUpdate(baseline, null)).toBeNull();
});
- it('emits only the changed enabled flag', () => {
- const update = buildLayeredIntelligenceUpdate(baseline, { ...baseline, enabled: true });
- expect(update).toEqual({ enabled: true });
- });
-
- it('emits intervalMs when it changes', () => {
- const update = buildLayeredIntelligenceUpdate(baseline, { ...baseline, intervalMs: 3600000 });
- expect(update).toEqual({ intervalMs: 3600000 });
+ it('does NOT emit scheduling fields (they go to the task override, #2322)', () => {
+ // enabled / intervalMs / providerId / model are handled by
+ // buildLayeredIntelligenceScheduleUpdate, so the behavior PATCH ignores them.
+ expect(buildLayeredIntelligenceUpdate(baseline, { ...baseline, enabled: true })).toBeNull();
+ expect(buildLayeredIntelligenceUpdate(baseline, { ...baseline, intervalMs: 3600000 })).toBeNull();
+ expect(buildLayeredIntelligenceUpdate(baseline, { ...baseline, providerId: 'claude-code', model: 'sonnet' })).toBeNull();
});
it('emits the hand-off toggle only when it changes', () => {
@@ -39,13 +37,6 @@ describe('buildLayeredIntelligenceUpdate', () => {
expect(update).toEqual({ handoff: { enabled: true } });
});
- it('normalizes empty provider/model to null and only emits when changed', () => {
- // '' provider equals the null baseline → no change
- expect(buildLayeredIntelligenceUpdate(baseline, { ...baseline, providerId: '', model: '' })).toBeNull();
- const update = buildLayeredIntelligenceUpdate(baseline, { ...baseline, providerId: 'claude-code', model: 'sonnet' });
- expect(update).toEqual({ providerId: 'claude-code', model: 'sonnet' });
- });
-
it('emits the full source object (toggles + sanitized custom) when a toggle flips', () => {
const update = buildLayeredIntelligenceUpdate(baseline, {
...baseline,
@@ -121,6 +112,37 @@ describe('buildLayeredIntelligenceUpdate', () => {
});
});
+describe('buildLayeredIntelligenceScheduleUpdate (per-app task override, #2322)', () => {
+ it('returns null when no scheduling field changed', () => {
+ expect(buildLayeredIntelligenceScheduleUpdate(baseline, { ...baseline })).toBeNull();
+ expect(buildLayeredIntelligenceScheduleUpdate(null, baseline)).toBeNull();
+ });
+
+ it('emits the enabled flag when it changes', () => {
+ expect(buildLayeredIntelligenceScheduleUpdate(baseline, { ...baseline, enabled: true })).toEqual({ enabled: true });
+ });
+
+ it('emits interval + intervalMs together, mapping to daily/weekly/custom', () => {
+ expect(buildLayeredIntelligenceScheduleUpdate(baseline, { ...baseline, intervalMs: 3600000 }))
+ .toEqual({ interval: 'custom', intervalMs: 3600000 });
+ expect(buildLayeredIntelligenceScheduleUpdate({ ...baseline, intervalMs: 3600000 }, { ...baseline, intervalMs: 7 * 86400000 }))
+ .toEqual({ interval: 'weekly', intervalMs: 7 * 86400000 });
+ });
+
+ it('normalizes empty provider/model to null and only emits when changed', () => {
+ expect(buildLayeredIntelligenceScheduleUpdate(baseline, { ...baseline, providerId: '', model: '' })).toBeNull();
+ expect(buildLayeredIntelligenceScheduleUpdate(baseline, { ...baseline, providerId: 'claude-code', model: 'sonnet' }))
+ .toEqual({ providerId: 'claude-code', model: 'sonnet' });
+ });
+
+ it('intervalFieldsFromMs maps standard cadences + falls back to daily', () => {
+ expect(intervalFieldsFromMs(86400000)).toEqual({ interval: 'daily', intervalMs: 86400000 });
+ expect(intervalFieldsFromMs(7 * 86400000)).toEqual({ interval: 'weekly', intervalMs: 7 * 86400000 });
+ expect(intervalFieldsFromMs(6 * 3600000)).toEqual({ interval: 'custom', intervalMs: 6 * 3600000 });
+ expect(intervalFieldsFromMs(0)).toEqual({ interval: 'daily', intervalMs: 86400000 });
+ });
+});
+
describe('LayeredIntelligenceTab (render)', () => {
const props = { li: baseline, onChange: () => {}, providers: [], loaded: true };
diff --git a/client/src/hooks/useOnDemandTaskToast.js b/client/src/hooks/useOnDemandTaskToast.js
index c4fefaaaf1..2d6d6225fa 100644
--- a/client/src/hooks/useOnDemandTaskToast.js
+++ b/client/src/hooks/useOnDemandTaskToast.js
@@ -81,9 +81,24 @@ export function useOnDemandTaskToast() {
});
};
+ // A handler-backed task (e.g. Layered Intelligence) that DID work on an
+ // explicit "Run" — it files a tracker issue rather than spawning an agent, so
+ // there's no task card to see; a success toast is the only user feedback.
+ const handleRan = (data) => {
+ const task = data?.taskType || 'task';
+ const scope = data?.appName ? ` for ${data.appName}` : '';
+ const ref = data?.filedKey || (data?.filedNumber != null ? `#${data.filedNumber}` : '');
+ toast(`${task}${scope}: ran now — filed an improvement issue${ref ? ` (${ref})` : ''}.`, {
+ duration: 6000,
+ icon: '🧠'
+ });
+ };
+
socket.on('cos:schedule:on-demand-empty', handleEmpty);
+ socket.on('cos:schedule:on-demand-ran', handleRan);
return () => {
socket.off('cos:schedule:on-demand-empty', handleEmpty);
+ socket.off('cos:schedule:on-demand-ran', handleRan);
// Don't unsubscribe from cos — other components share the room.
};
}, []);
diff --git a/client/src/pages/LayeredIntelligence.jsx b/client/src/pages/LayeredIntelligence.jsx
index 8a41643e8e..e2b8c5776b 100644
--- a/client/src/pages/LayeredIntelligence.jsx
+++ b/client/src/pages/LayeredIntelligence.jsx
@@ -236,11 +236,17 @@ export default function LayeredIntelligence() {
</div>
) : (
<>
- {!data.jobEnabled && (
+ {!data.taskEnabled && (
<Banner tone="warning" size="md">
- The global <strong>Layered Intelligence Loop</strong> job is off, so no app&apos;s loop will run even when
- enabled below. Turn it on under{' '}
- <Link to="/cos/jobs" className="underline hover:text-white">Chief of Staff → System Tasks</Link>.
+ The <strong>Layered Intelligence</strong> scheduled task is off globally, so no app&apos;s loop will run even
+ when enabled below. Turn the task on under{' '}
+ <Link to="/cos/schedule" className="underline hover:text-white">Chief of Staff → Schedule</Link>.
+ </Banner>
+ )}
+ {data.taskEnabled && !data.improvementEnabled && (
+ <Banner tone="warning" size="md">
+ CoS <strong>improvement</strong> is disabled, so scheduled loops (including this one) won&apos;t run. Enable
+ it under <Link to="/cos" className="underline hover:text-white">Chief of Staff</Link>.
</Banner>
)}
diff --git a/client/src/pages/LayeredIntelligence.test.jsx b/client/src/pages/LayeredIntelligence.test.jsx
index e127d1551a..0461dcac6a 100644
--- a/client/src/pages/LayeredIntelligence.test.jsx
+++ b/client/src/pages/LayeredIntelligence.test.jsx
@@ -17,9 +17,8 @@ const renderPage = () => render(
);
const overview = (extra = {}) => ({
- jobId: 'job-layered-intelligence',
- jobEnabled: true,
- jobExists: true,
+ taskEnabled: true,
+ improvementEnabled: true,
enabledCount: 1,
apps: [
{
@@ -56,12 +55,19 @@ describe('LayeredIntelligence page', () => {
expect(screen.getByText('1 of 2 apps have the loop enabled.')).toBeInTheDocument();
});
- it('warns when the global job is disabled', async () => {
- api.getLayeredIntelligenceOverview.mockResolvedValue(overview({ jobEnabled: false }));
+ it('warns when the scheduled task is disabled globally', async () => {
+ api.getLayeredIntelligenceOverview.mockResolvedValue(overview({ taskEnabled: false }));
renderPage();
- await waitFor(() => expect(screen.getByText(/global/i)).toBeInTheDocument());
- expect(screen.getByText(/System Tasks/)).toBeInTheDocument();
+ await waitFor(() => expect(screen.getByText(/scheduled task is off globally/i)).toBeInTheDocument());
+ expect(screen.getByText(/Schedule/)).toBeInTheDocument();
+ });
+
+ it('warns when CoS improvement is disabled (task on)', async () => {
+ api.getLayeredIntelligenceOverview.mockResolvedValue(overview({ taskEnabled: true, improvementEnabled: false }));
+ renderPage();
+
+ await waitFor(() => expect(screen.getByText(/improvement/i)).toBeInTheDocument());
});
it('shows an error banner + retry when the overview fails to load', async () => {
diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.js
index 762e4a5696..2bf895e335 100644
--- a/client/src/services/apiApps.js
+++ b/client/src/services/apiApps.js
@@ -92,9 +92,12 @@ export const toggleAllAppTaskTypes = (id, enabled, options = {}) => request(`/ap
body: JSON.stringify({ enabled }),
...options
});
-export const updateAppTaskTypeOverride = (id, taskType, { enabled, interval, taskMetadata } = {}, options = {}) => request(`/apps/${id}/task-types/${taskType}`, {
+// `intervalMs` / `providerId` / `model` are the per-app scheduling fields for
+// handler-backed task types (layered-intelligence). Sent only when defined so
+// existing callers (enabled/interval-only toggles) are unaffected.
+export const updateAppTaskTypeOverride = (id, taskType, { enabled, interval, intervalMs, providerId, model, taskMetadata } = {}, options = {}) => request(`/apps/${id}/task-types/${taskType}`, {
method: 'PUT',
- body: JSON.stringify({ enabled, interval, taskMetadata }),
+ body: JSON.stringify({ enabled, interval, intervalMs, providerId, model, taskMetadata }),
...options
});
export const bulkUpdateAppTaskTypeOverride = (taskType, { enabled }, options = {}) => request(`/apps/bulk-task-type/${taskType}`, {
diff --git a/scripts/migrations/184-migrate-layered-intelligence-to-scheduled-task.js b/scripts/migrations/184-migrate-layered-intelligence-to-scheduled-task.js
new file mode 100644
index 0000000000..87f85bd63f
--- /dev/null
+++ b/scripts/migrations/184-migrate-layered-intelligence-to-scheduled-task.js
@@ -0,0 +1,152 @@
+/**
+ * Migrate the retired global "Layered Intelligence Loop" autonomous-job into the
+ * per-app HANDLER-BACKED `layered-intelligence` Chief-of-Staff scheduled task
+ * (issue #2322).
+ *
+ * The loop shipped as ONE global autonomous-job (`job-layered-intelligence`) that
+ * swept every enabled app on a single daily fire, with a global on/off under CoS
+ * → System Tasks and per-app config living in `app.layeredIntelligence`. That was
+ * confusing (a per-app card could read "Enabled · Due now" yet nothing ran,
+ * because the single global sweep already fired) and bespoke (every other per-app
+ * automation is a scheduled task). The job, its SCRIPT_HANDLERS registration and
+ * its DEFAULT_JOBS catalog entry were removed. Without this migration, an install
+ * whose loop was running would silently stop.
+ *
+ * This migration:
+ * 1. In `data/cos/autonomous-jobs.json`: find `job-layered-intelligence`,
+ * capture its `enabled` as `globalEnabled`, and REMOVE the record
+ * (tombstone — nothing dispatches on it anymore).
+ * 2. For each app in `data/apps.json` that has a `layeredIntelligence` object,
+ * move the SCHEDULING fields into `taskTypeOverrides['layered-intelligence']`
+ * = { enabled: (globalEnabled && !!li.enabled), interval, intervalMs,
+ * providerId?, model? }. BEHAVIOR (sources/allowedScopes/rules/handoff) and
+ * `lastRunAt` stay in `app.layeredIntelligence`. Faithful effective-state:
+ * a per-app enable did nothing while the global job was off, so the override
+ * is enabled only when BOTH were on.
+ * 3. If the global job was enabled, enable the `layered-intelligence` task TYPE
+ * in `data/cos/task-schedule.json` (the master switch the scheduler checks
+ * before any per-app override) — otherwise the moved per-app enables would be
+ * inert and a running loop would stop.
+ *
+ * Idempotent: the per-app move is skipped when the override already exists, and a
+ * re-run after the job is gone finds nothing to tombstone. Safe when any target
+ * file is absent (fresh install → no-op).
+ */
+
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+
+const JOBS_REL = 'data/cos/autonomous-jobs.json';
+const APPS_REL = 'data/apps.json';
+const SCHEDULE_REL = 'data/cos/task-schedule.json';
+const LI_JOB_ID = 'job-layered-intelligence';
+const LI_TASK_TYPE = 'layered-intelligence';
+const DAY = 24 * 60 * 60 * 1000;
+const WEEK = 7 * DAY;
+
+const isObject = (v) => v && typeof v === 'object' && !Array.isArray(v);
+
+async function readJson(path) {
+ const raw = await readFile(path, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) return null;
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return null;
+ }
+}
+
+async function writeJson(path, value) {
+ await writeFile(path, `${JSON.stringify(value, null, 2)}\n`);
+}
+
+/**
+ * Map a stored per-app intervalMs to the override's { interval, intervalMs }
+ * pair the scheduler understands: 'daily'/'weekly' for the standard cadences,
+ * else 'custom' (the CUSTOM branch reads the numeric intervalMs). Exported for
+ * the migration test.
+ */
+export function intervalFieldsFromMs(intervalMs) {
+ const ms = typeof intervalMs === 'number' && Number.isFinite(intervalMs) && intervalMs > 0 ? intervalMs : DAY;
+ if (Math.abs(ms - DAY) < 1000) return { interval: 'daily', intervalMs: ms };
+ if (Math.abs(ms - WEEK) < 1000) return { interval: 'weekly', intervalMs: ms };
+ return { interval: 'custom', intervalMs: ms };
+}
+
+/**
+ * Build the per-app task override from an app's legacy layeredIntelligence config
+ * + whether the global job was enabled. Pure — exported for the migration test.
+ */
+export function buildOverride(li, globalEnabled) {
+ const { interval, intervalMs } = intervalFieldsFromMs(li?.intervalMs);
+ const override = {
+ enabled: !!globalEnabled && li?.enabled === true,
+ interval,
+ intervalMs
+ };
+ if (typeof li?.providerId === 'string' && li.providerId) override.providerId = li.providerId;
+ if (typeof li?.model === 'string' && li.model) override.model = li.model;
+ return override;
+}
+
+export default {
+ async up({ rootDir }) {
+ // 1. Tombstone the global job + capture its enabled state.
+ const jobsPath = join(rootDir, JOBS_REL);
+ const jobsData = await readJson(jobsPath);
+ let globalEnabled = false;
+ let jobRemoved = false;
+ if (isObject(jobsData) && Array.isArray(jobsData.jobs)) {
+ const job = jobsData.jobs.find((j) => isObject(j) && j.id === LI_JOB_ID);
+ if (job) {
+ globalEnabled = job.enabled === true;
+ jobsData.jobs = jobsData.jobs.filter((j) => !(isObject(j) && j.id === LI_JOB_ID));
+ await writeJson(jobsPath, jobsData);
+ jobRemoved = true;
+ console.log(`📝 layered-intelligence: tombstoned the retired global job (was ${globalEnabled ? 'enabled' : 'disabled'})`);
+ }
+ }
+
+ // 2. Move per-app scheduling into taskTypeOverrides['layered-intelligence'].
+ const appsPath = join(rootDir, APPS_REL);
+ const appsData = await readJson(appsPath);
+ let migratedApps = 0;
+ if (isObject(appsData) && isObject(appsData.apps)) {
+ for (const app of Object.values(appsData.apps)) {
+ if (!isObject(app) || !isObject(app.layeredIntelligence)) continue;
+ const overrides = isObject(app.taskTypeOverrides) ? app.taskTypeOverrides : {};
+ if (isObject(overrides[LI_TASK_TYPE])) continue; // idempotent — already moved
+ overrides[LI_TASK_TYPE] = buildOverride(app.layeredIntelligence, globalEnabled);
+ app.taskTypeOverrides = overrides;
+ migratedApps += 1;
+ }
+ if (migratedApps > 0) {
+ await writeJson(appsPath, appsData);
+ console.log(`📝 layered-intelligence: moved scheduling into per-app task overrides for ${migratedApps} app(s)`);
+ }
+ }
+
+ // 3. Preserve effective enablement: if the old global job was on, enable the
+ // task TYPE globally (the master switch every per-app override is gated on).
+ if (globalEnabled) {
+ const schedulePath = join(rootDir, SCHEDULE_REL);
+ const schedule = await readJson(schedulePath);
+ if (isObject(schedule) && isObject(schedule.tasks)) {
+ const task = isObject(schedule.tasks[LI_TASK_TYPE]) ? schedule.tasks[LI_TASK_TYPE] : {};
+ if (task.enabled !== true) {
+ task.enabled = true;
+ schedule.tasks[LI_TASK_TYPE] = task;
+ await writeJson(schedulePath, schedule);
+ console.log('📝 layered-intelligence: enabled the scheduled task type (the global job was on)');
+ }
+ } else {
+ console.log('⚠️ layered-intelligence: no task-schedule.json to enable — loadSchedule backfills the disabled default; enable it under Chief of Staff → Schedule');
+ }
+ }
+
+ return { updated: migratedApps + (jobRemoved ? 1 : 0), globalEnabled, jobRemoved, migratedApps };
+ }
+};
diff --git a/scripts/migrations/184-migrate-layered-intelligence-to-scheduled-task.test.js b/scripts/migrations/184-migrate-layered-intelligence-to-scheduled-task.test.js
new file mode 100644
index 0000000000..e51b89848a
--- /dev/null
+++ b/scripts/migrations/184-migrate-layered-intelligence-to-scheduled-task.test.js
@@ -0,0 +1,134 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration, { intervalFieldsFromMs, buildOverride } from './184-migrate-layered-intelligence-to-scheduled-task.js';
+
+const DAY = 24 * 60 * 60 * 1000;
+const WEEK = 7 * DAY;
+const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));
+
+describe('migration 184 — layered intelligence → per-app scheduled task', () => {
+ let rootDir, jobsPath, appsPath, schedulePath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-184-'));
+ mkdirSync(join(rootDir, 'data', 'cos'), { recursive: true });
+ jobsPath = join(rootDir, 'data', 'cos', 'autonomous-jobs.json');
+ appsPath = join(rootDir, 'data', 'apps.json');
+ schedulePath = join(rootDir, 'data', 'cos', 'task-schedule.json');
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ describe('pure helpers', () => {
+ it('intervalFieldsFromMs maps day/week to the string enum, else custom', () => {
+ expect(intervalFieldsFromMs(DAY)).toEqual({ interval: 'daily', intervalMs: DAY });
+ expect(intervalFieldsFromMs(WEEK)).toEqual({ interval: 'weekly', intervalMs: WEEK });
+ expect(intervalFieldsFromMs(6 * 60 * 60 * 1000)).toEqual({ interval: 'custom', intervalMs: 6 * 60 * 60 * 1000 });
+ expect(intervalFieldsFromMs(undefined)).toEqual({ interval: 'daily', intervalMs: DAY });
+ expect(intervalFieldsFromMs(0)).toEqual({ interval: 'daily', intervalMs: DAY });
+ });
+
+ it('buildOverride enables only when BOTH the job and the per-app config were on', () => {
+ expect(buildOverride({ enabled: true, intervalMs: DAY }, true).enabled).toBe(true);
+ expect(buildOverride({ enabled: true, intervalMs: DAY }, false).enabled).toBe(false);
+ expect(buildOverride({ enabled: false, intervalMs: DAY }, true).enabled).toBe(false);
+ });
+
+ it('buildOverride carries provider/model only when set', () => {
+ expect(buildOverride({ enabled: true, providerId: 'p', model: 'm', intervalMs: DAY }, true))
+ .toMatchObject({ enabled: true, providerId: 'p', model: 'm' });
+ const bare = buildOverride({ enabled: true, intervalMs: DAY }, true);
+ expect(bare).not.toHaveProperty('providerId');
+ expect(bare).not.toHaveProperty('model');
+ });
+ });
+
+ it('no-ops cleanly on a fresh install (no files)', async () => {
+ const result = await migration.up({ rootDir });
+ expect(result).toMatchObject({ updated: 0, globalEnabled: false, jobRemoved: false, migratedApps: 0 });
+ });
+
+ it('tombstones the job and moves each app when the global job was enabled', async () => {
+ writeJson(jobsPath, {
+ jobs: [
+ { id: 'job-other', enabled: true },
+ { id: 'job-layered-intelligence', enabled: true, category: 'layered-intelligence' }
+ ]
+ });
+ writeJson(appsPath, {
+ apps: {
+ 'portos-default': { name: 'PortOS', layeredIntelligence: { enabled: true, intervalMs: DAY, providerId: 'ollama', model: 'qwen', rules: 'keep it tight', sources: { goals: true } } },
+ 'app-a': { name: 'A', layeredIntelligence: { enabled: false, intervalMs: 6 * 60 * 60 * 1000 } },
+ 'app-noli': { name: 'No LI' }
+ }
+ });
+ writeJson(schedulePath, { tasks: { 'layered-intelligence': { type: 'daily', enabled: false } } });
+
+ const result = await migration.up({ rootDir });
+ expect(result).toMatchObject({ globalEnabled: true, jobRemoved: true, migratedApps: 2 });
+
+ // Job tombstoned; sibling job untouched.
+ const jobs = readJson(jobsPath).jobs;
+ expect(jobs.map((j) => j.id)).toEqual(['job-other']);
+
+ // PortOS: enabled (job on + app on), provider/model carried, behavior kept.
+ const apps = readJson(appsPath).apps;
+ expect(apps['portos-default'].taskTypeOverrides['layered-intelligence']).toEqual({
+ enabled: true, interval: 'daily', intervalMs: DAY, providerId: 'ollama', model: 'qwen'
+ });
+ expect(apps['portos-default'].layeredIntelligence.rules).toBe('keep it tight'); // behavior stays
+ expect(apps['portos-default'].layeredIntelligence.sources.goals).toBe(true);
+
+ // app-a: per-app was off ⇒ override disabled; sub-daily interval ⇒ custom.
+ expect(apps['app-a'].taskTypeOverrides['layered-intelligence']).toEqual({
+ enabled: false, interval: 'custom', intervalMs: 6 * 60 * 60 * 1000
+ });
+
+ // app with no LI config gets no override.
+ expect(apps['app-noli'].taskTypeOverrides).toBeUndefined();
+
+ // Global task type enabled so the moved per-app enables actually run.
+ expect(readJson(schedulePath).tasks['layered-intelligence'].enabled).toBe(true);
+ });
+
+ it('disables every app override + leaves the task off when the job was disabled', async () => {
+ writeJson(jobsPath, { jobs: [{ id: 'job-layered-intelligence', enabled: false }] });
+ writeJson(appsPath, {
+ apps: { 'app-a': { name: 'A', layeredIntelligence: { enabled: true, intervalMs: DAY } } }
+ });
+ writeJson(schedulePath, { tasks: { 'layered-intelligence': { enabled: false } } });
+
+ const result = await migration.up({ rootDir });
+ expect(result.globalEnabled).toBe(false);
+
+ const apps = readJson(appsPath).apps;
+ // per-app was on but the job was off ⇒ effective off preserved.
+ expect(apps['app-a'].taskTypeOverrides['layered-intelligence'].enabled).toBe(false);
+ // Task type stays disabled (nothing to enable).
+ expect(readJson(schedulePath).tasks['layered-intelligence'].enabled).toBe(false);
+ });
+
+ it('is idempotent — a second run does not overwrite an existing override', async () => {
+ writeJson(jobsPath, { jobs: [{ id: 'job-layered-intelligence', enabled: true }] });
+ writeJson(appsPath, {
+ apps: { 'app-a': { name: 'A', layeredIntelligence: { enabled: true, intervalMs: DAY } } }
+ });
+ writeJson(schedulePath, { tasks: { 'layered-intelligence': { enabled: false } } });
+
+ await migration.up({ rootDir });
+ // Hand-edit the override to prove a re-run leaves it alone.
+ const apps1 = readJson(appsPath);
+ apps1.apps['app-a'].taskTypeOverrides['layered-intelligence'].enabled = false;
+ writeJson(appsPath, apps1);
+
+ const result2 = await migration.up({ rootDir });
+ expect(result2.migratedApps).toBe(0); // nothing re-moved
+ expect(readJson(appsPath).apps['app-a'].taskTypeOverrides['layered-intelligence'].enabled).toBe(false);
+ });
+});
diff --git a/server/routes/apps.js b/server/routes/apps.js
index 798b129a5c..29b1e8ed0d 100644
--- a/server/routes/apps.js
+++ b/server/routes/apps.js
@@ -20,10 +20,10 @@ import { checkViteHost, findViteConfig, rewriteAllowedHosts } from '../lib/viteA
import { detectAppIcon, getIconContentType, isUsableSvg } from '../services/appIconDetect.js';
import { hasDeployScript } from '../services/appDeployer.js';
import { checkScripts, installScripts, XCODE_SCRIPT_NAMES } from '../services/xcodeScripts.js';
-import { SELF_IMPROVEMENT_TASK_TYPES } from '../services/taskSchedule.js';
-import { summarizeLoopStatus, summarizeFiledProposals, LI_JOB_ID } from '../services/layeredIntelligence.js';
+import { SELF_IMPROVEMENT_TASK_TYPES, loadSchedule } from '../services/taskSchedule.js';
+import { loadState, isImprovementEnabled } from '../services/cosState.js';
+import { summarizeLoopStatus, summarizeFiledProposals } from '../services/layeredIntelligence.js';
import { resolveAppWorkTracker } from '../lib/workTracker.js';
-import * as autonomousJobs from '../services/autonomousJobs.js';
import { certPaths } from '../../lib/certPaths.js';
const router = Router();
@@ -746,23 +746,30 @@ router.get('/:id/work-tracker', loadApp, asyncHandler(async (req, res) => {
// collide with `/:id` (one segment) or `/:id/layered-intelligence` (literal
// second segment), so ordering is safe.
router.get('/layered-intelligence/overview', asyncHandler(async (req, res) => {
- const [apps, job] = await Promise.all([
+ const [apps, schedule, state] = await Promise.all([
appsService.getActiveApps(),
- autonomousJobs.getJob(LI_JOB_ID).catch(() => null)
+ loadSchedule().catch(() => null),
+ loadState().catch(() => null)
]);
const now = Date.now();
- const summaries = apps
- .map(app => summarizeLoopStatus({ app, isPortos: app.id === PORTOS_APP_ID, now }))
+ // Scheduling (enabled/interval/provider/model) lives in each app's per-app task
+ // override now (#2322), not app.layeredIntelligence — pass it to the summarizer.
+ const summaries = (await Promise.all(apps.map(async (app) => {
+ const overrides = await appsService.getAppTaskTypeOverrides(app.id).catch(() => ({}));
+ return summarizeLoopStatus({ app, isPortos: app.id === PORTOS_APP_ID, override: overrides?.['layered-intelligence'], now });
+ })))
.sort((a, b) => {
// Enabled apps first, then the PortOS baseline, then alphabetical by name.
if (a.enabled !== b.enabled) return a.enabled ? -1 : 1;
if (a.isPortos !== b.isPortos) return a.isPortos ? -1 : 1;
return a.name.localeCompare(b.name);
});
+ // The loop is driven by the per-app `layered-intelligence` scheduled task, so
+ // "nothing will run" now depends on (a) the task type being enabled globally in
+ // CoS → Schedule and (b) CoS improvement being on — NOT a bespoke global job.
res.json({
- jobId: LI_JOB_ID,
- jobEnabled: !!job?.enabled,
- jobExists: !!job,
+ taskEnabled: !!schedule?.tasks?.['layered-intelligence']?.enabled,
+ improvementEnabled: state ? isImprovementEnabled(state) : false,
enabledCount: summaries.filter(s => s.enabled).length,
apps: summaries
});
@@ -783,8 +790,15 @@ router.get('/layered-intelligence/proposals', asyncHandler(async (req, res) => {
const apps = await appsService.getActiveApps();
// Bound the I/O fan-out to apps whose loop is actually enabled — a disabled
// app has filed nothing this config cares about, and sweeping every managed
- // app would shell out `gh`/`glab` needlessly.
- const enabled = apps.filter(app => summarizeLoopStatus({ app, isPortos: app.id === PORTOS_APP_ID }).enabled);
+ // app would shell out `gh`/`glab` needlessly. Enablement lives in the per-app
+ // task override now (#2322).
+ const withOverrides = await Promise.all(apps.map(async (app) => ({
+ app,
+ override: (await appsService.getAppTaskTypeOverrides(app.id).catch(() => ({})))?.['layered-intelligence']
+ })));
+ const enabled = withOverrides
+ .filter(({ app, override }) => summarizeLoopStatus({ app, isPortos: app.id === PORTOS_APP_ID, override }).enabled)
+ .map(({ app }) => app);
const results = await Promise.all(enabled.map(async (app) => {
const tracker = await resolveAppWorkTracker(app).catch(() => ({ resolved: 'plan', forge: null }));
const summary = await summarizeFiledProposals({ app, tracker })
@@ -823,15 +837,31 @@ router.put('/:id/task-types/all', loadApp, asyncHandler(async (req, res) => {
// PUT /api/apps/:id/task-types/:taskType - Update a task type override for an app
router.put('/:id/task-types/:taskType', asyncHandler(async (req, res) => {
- const { enabled, interval, taskMetadata } = req.body;
+ const { enabled, interval, intervalMs, providerId, model, taskMetadata } = req.body;
if (!SELF_IMPROVEMENT_TASK_TYPES.includes(req.params.taskType)) {
throw new ServerError(`Unknown task type '${req.params.taskType}'`, { status: 400, code: 'INVALID_TASK_TYPE' });
}
if (enabled !== undefined && typeof enabled !== 'boolean') {
throw new ServerError('enabled must be a boolean', { status: 400, code: 'VALIDATION_ERROR' });
}
- if (typeof enabled !== 'boolean' && interval === undefined && taskMetadata === undefined) {
- throw new ServerError('enabled (boolean), interval (string|null), or taskMetadata (object|null) required', { status: 400, code: 'VALIDATION_ERROR' });
+ if (typeof enabled !== 'boolean' && interval === undefined && intervalMs === undefined &&
+ providerId === undefined && model === undefined && taskMetadata === undefined) {
+ throw new ServerError('enabled (boolean), interval (string|null), intervalMs (number|null), providerId (string|null), model (string|null), or taskMetadata (object|null) required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+
+ // Per-app scheduling fields for handler-backed tasks (layered-intelligence).
+ // `null`/'' clears back to inherit; a numeric intervalMs must be a positive
+ // finite number (a sub-daily cadence the string interval enum can't express).
+ if (intervalMs !== undefined && intervalMs !== null) {
+ if (typeof intervalMs !== 'number' || !Number.isFinite(intervalMs) || intervalMs <= 0) {
+ throw new ServerError('intervalMs must be a positive number or null', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ }
+ if (providerId !== undefined && providerId !== null && typeof providerId !== 'string') {
+ throw new ServerError('providerId must be a string or null', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (model !== undefined && model !== null && typeof model !== 'string') {
+ throw new ServerError('model must be a string or null', { status: 400, code: 'VALIDATION_ERROR' });
}
// Validate and sanitize taskMetadata to allowed agent-option keys only
@@ -852,11 +882,13 @@ router.put('/:id/task-types/:taskType', asyncHandler(async (req, res) => {
// Validate interval against allowed values (also accepts 5-field cron expressions)
if (interval !== undefined) {
- const allowedIntervals = ['rotation', 'daily', 'weekly', 'once', 'on-demand'];
+ // 'custom' pairs with a numeric intervalMs (handler-backed tasks with a
+ // sub-daily per-app cadence); the scheduler's CUSTOM branch reads intervalMs.
+ const allowedIntervals = ['rotation', 'daily', 'weekly', 'once', 'on-demand', 'custom'];
if (interval !== null && typeof interval === 'string') {
const isCron = interval.trim().split(/\s+/).length === 5;
if (!isCron && !allowedIntervals.includes(interval)) {
- throw new ServerError('interval must be one of rotation|daily|weekly|once|on-demand, a cron expression, or null', { status: 400, code: 'VALIDATION_ERROR' });
+ throw new ServerError('interval must be one of rotation|daily|weekly|once|on-demand|custom, a cron expression, or null', { status: 400, code: 'VALIDATION_ERROR' });
}
if (isCron) {
// Validate syntax and field ranges (parseCronToNextRun throws on invalid expressions)
@@ -868,7 +900,7 @@ router.put('/:id/task-types/:taskType', asyncHandler(async (req, res) => {
}
}
- const result = await appsService.updateAppTaskTypeOverride(req.params.id, req.params.taskType, { enabled, interval, taskMetadata: sanitizedTaskMetadata });
+ const result = await appsService.updateAppTaskTypeOverride(req.params.id, req.params.taskType, { enabled, interval, intervalMs, providerId, model, taskMetadata: sanitizedTaskMetadata });
if (!result) {
throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
}
diff --git a/server/routes/apps.test.js b/server/routes/apps.test.js
index 9143647a2d..fd158ae03b 100644
--- a/server/routes/apps.test.js
+++ b/server/routes/apps.test.js
@@ -36,10 +36,17 @@ vi.mock('../services/history.js', () => ({
logAction: vi.fn()
}));
-// Mock the autonomous-jobs barrel so the layered-intelligence overview route can
-// read the global job's enabled state without pulling in the whole CoS graph.
-vi.mock('../services/autonomousJobs.js', () => ({
- getJob: vi.fn()
+// The layered-intelligence overview route now reads the per-app task schedule +
+// CoS improvement state (the global autonomous-job is retired, #2322). Stub
+// loadSchedule (keeping the real SELF_IMPROVEMENT_TASK_TYPES the route imports)
+// and cosState so the route tests stay deterministic + I/O-free.
+vi.mock('../services/taskSchedule.js', async (importActual) => {
+ const actual = await importActual();
+ return { ...actual, loadSchedule: vi.fn().mockResolvedValue({ tasks: {} }) };
+});
+vi.mock('../services/cosState.js', () => ({
+ loadState: vi.fn().mockResolvedValue({}),
+ isImprovementEnabled: vi.fn().mockReturnValue(true)
}));
// Partial-mock layeredIntelligence: keep the real pure helpers (summarizeLoopStatus,
@@ -108,7 +115,7 @@ import * as pm2Service from '../services/pm2.js';
import * as history from '../services/history.js';
import * as streamingDetect from '../services/streamingDetect.js';
import * as cos from '../services/cos.js';
-import * as autonomousJobs from '../services/autonomousJobs.js';
+import { loadSchedule } from '../services/taskSchedule.js';
import { summarizeFiledProposals } from '../services/layeredIntelligence.js';
import { resolveAppWorkTracker } from '../lib/workTracker.js';
import { detectAppIcon, getIconContentType, isUsableSvg } from '../services/appIconDetect.js';
@@ -336,19 +343,25 @@ describe('Apps Routes', () => {
expect(response.status).toBe(404);
});
- it('GET /layered-intelligence/overview summarizes every active app + global job state', async () => {
+ it('GET /layered-intelligence/overview summarizes every active app + scheduled-task state', async () => {
appsService.getActiveApps.mockResolvedValue([
- { id: 'off-app', name: 'Zeta Off', layeredIntelligence: { enabled: false } },
- { id: 'on-app', name: 'Alpha On', layeredIntelligence: { enabled: true, intervalMs: 86400000 } },
- { id: 'portos-default', name: 'PortOS', layeredIntelligence: { enabled: true } }
+ { id: 'off-app', name: 'Zeta Off' },
+ { id: 'on-app', name: 'Alpha On' },
+ { id: 'portos-default', name: 'PortOS' }
]);
- autonomousJobs.getJob.mockResolvedValue({ id: 'job-layered-intelligence', enabled: true });
+ // Scheduling/enablement now comes from each app's task override (#2322).
+ appsService.getAppTaskTypeOverrides.mockImplementation(async (id) => ({
+ 'off-app': {},
+ 'on-app': { 'layered-intelligence': { enabled: true, intervalMs: 86400000 } },
+ 'portos-default': { 'layered-intelligence': { enabled: true } }
+ }[id] || {}));
+ loadSchedule.mockResolvedValue({ tasks: { 'layered-intelligence': { enabled: true } } });
const response = await request(app).get('/api/apps/layered-intelligence/overview');
expect(response.status).toBe(200);
- expect(response.body.jobEnabled).toBe(true);
- expect(response.body.jobExists).toBe(true);
+ expect(response.body.taskEnabled).toBe(true);
+ expect(response.body.improvementEnabled).toBe(true);
expect(response.body.enabledCount).toBe(2);
// Enabled first, PortOS ahead of other enabled, disabled last.
expect(response.body.apps.map(a => a.id)).toEqual(['portos-default', 'on-app', 'off-app']);
@@ -360,23 +373,26 @@ describe('Apps Routes', () => {
expect(appsService.getActiveApps).toHaveBeenCalled();
});
- it('GET /layered-intelligence/overview reports jobEnabled:false when the job is missing', async () => {
+ it('GET /layered-intelligence/overview reports taskEnabled:false when the scheduled task is off', async () => {
appsService.getActiveApps.mockResolvedValue([]);
- autonomousJobs.getJob.mockResolvedValue(null);
+ appsService.getAppTaskTypeOverrides.mockResolvedValue({});
+ loadSchedule.mockResolvedValue({ tasks: {} });
const response = await request(app).get('/api/apps/layered-intelligence/overview');
expect(response.status).toBe(200);
- expect(response.body.jobEnabled).toBe(false);
- expect(response.body.jobExists).toBe(false);
+ expect(response.body.taskEnabled).toBe(false);
expect(response.body.enabledCount).toBe(0);
});
it('GET /layered-intelligence/proposals sweeps only enabled apps and returns counts + links', async () => {
appsService.getActiveApps.mockResolvedValue([
- { id: 'off-app', name: 'Off', layeredIntelligence: { enabled: false }, repoPath: '/off' },
- { id: 'on-app', name: 'On', layeredIntelligence: { enabled: true }, repoPath: '/on' }
+ { id: 'off-app', name: 'Off', repoPath: '/off' },
+ { id: 'on-app', name: 'On', repoPath: '/on' }
]);
+ // Enablement is per-app-override driven now (#2322).
+ appsService.getAppTaskTypeOverrides.mockImplementation(async (id) =>
+ id === 'on-app' ? { 'layered-intelligence': { enabled: true } } : {});
resolveAppWorkTracker.mockResolvedValue({ resolved: 'github', forge: 'gh' });
summarizeFiledProposals.mockResolvedValue({
ok: true, tracker: 'github', open: 2, closed: 1, total: 3,
@@ -395,9 +411,10 @@ describe('Apps Routes', () => {
it('GET /layered-intelligence/proposals degrades one failing app without aborting the batch', async () => {
appsService.getActiveApps.mockResolvedValue([
- { id: 'a', name: 'A', layeredIntelligence: { enabled: true }, repoPath: '/a' },
- { id: 'b', name: 'B', layeredIntelligence: { enabled: true }, repoPath: '/b' }
+ { id: 'a', name: 'A', repoPath: '/a' },
+ { id: 'b', name: 'B', repoPath: '/b' }
]);
+ appsService.getAppTaskTypeOverrides.mockResolvedValue({ 'layered-intelligence': { enabled: true } });
resolveAppWorkTracker.mockResolvedValue({ resolved: 'github', forge: 'gh' });
summarizeFiledProposals
.mockResolvedValueOnce({ ok: true, tracker: 'github', open: 1, closed: 0, total: 1, issues: [] })
diff --git a/server/services/apps.js b/server/services/apps.js
index 7e039edee5..53ab80f24e 100644
--- a/server/services/apps.js
+++ b/server/services/apps.js
@@ -499,10 +499,23 @@ export async function getAppTaskTypeInterval(appId, taskType) {
return overrides[taskType]?.interval || null;
}
+/**
+ * Get a per-app numeric intervalMs override for a task type (null = none). Used
+ * by handler-backed tasks (e.g. layered-intelligence) whose per-app cadence can
+ * be sub-daily — the string `interval` enum ('daily'/'weekly'/…) can't express
+ * that, so those override entries also carry a numeric `intervalMs` that the
+ * scheduler's CUSTOM branch honors. Returns null for a missing/invalid value.
+ */
+export async function getAppTaskTypeIntervalMs(appId, taskType) {
+ const overrides = await getAppTaskTypeOverrides(appId);
+ const ms = overrides[taskType]?.intervalMs;
+ return typeof ms === 'number' && Number.isFinite(ms) && ms > 0 ? ms : null;
+}
+
/**
* Update a task type override for a specific app (enable/disable + optional interval)
*/
-export async function updateAppTaskTypeOverride(id, taskType, { enabled, interval, taskMetadata } = {}) {
+export async function updateAppTaskTypeOverride(id, taskType, { enabled, interval, intervalMs, providerId, model, taskMetadata } = {}) {
const data = await loadApps();
if (!data.apps[id]) return null;
@@ -515,6 +528,21 @@ export async function updateAppTaskTypeOverride(id, taskType, { enabled, interva
const updated = { ...existing };
if (typeof enabled === 'boolean') updated.enabled = enabled;
if (interval !== undefined) updated.interval = interval;
+ // intervalMs / providerId / model are the per-app scheduling fields for
+ // handler-backed tasks (layered-intelligence, option A). `null` clears the
+ // stored value (back to "inherit / use default").
+ if (intervalMs !== undefined) {
+ if (intervalMs === null) delete updated.intervalMs;
+ else updated.intervalMs = intervalMs;
+ }
+ if (providerId !== undefined) {
+ if (providerId === null || providerId === '') delete updated.providerId;
+ else updated.providerId = providerId;
+ }
+ if (model !== undefined) {
+ if (model === null || model === '') delete updated.model;
+ else updated.model = model;
+ }
if (taskMetadata !== undefined) {
const sanitized = sanitizeTaskMetadata(taskMetadata);
if (!sanitized) {
@@ -524,8 +552,10 @@ export async function updateAppTaskTypeOverride(id, taskType, { enabled, interva
}
}
- // Remove entry when all fields are inherit (enabled undefined, no interval, no metadata)
- if (updated.enabled === undefined && !updated.interval && !updated.taskMetadata) {
+ // Remove entry when every field is inherit (enabled undefined, no interval, no
+ // intervalMs/provider/model, no metadata) — an empty override is just noise.
+ if (updated.enabled === undefined && !updated.interval && updated.intervalMs === undefined &&
+ updated.providerId === undefined && updated.model === undefined && !updated.taskMetadata) {
delete overrides[taskType];
} else {
overrides[taskType] = updated;
diff --git a/server/services/autonomousJobs/defaults.js b/server/services/autonomousJobs/defaults.js
index bd8e179266..d783ed3d15 100644
--- a/server/services/autonomousJobs/defaults.js
+++ b/server/services/autonomousJobs/defaults.js
@@ -10,7 +10,6 @@
*/
import { DAY, WEEK, JOB_STRUCTURAL_FIELDS, JOB_ADDITIVE_FIELDS } from './constants.js'
-import { LI_JOB_ID } from '../layeredIntelligence.js'
/**
* Default job definitions
@@ -256,22 +255,10 @@ Phase 4 — Report:
createdAt: null,
updatedAt: null
},
- {
- id: LI_JOB_ID,
- name: 'Layered Intelligence Loop',
- description: 'Per-managed-app self-improvement loop. Reads each enabled app\'s goals + telemetry, asks a reasoning model (default: local LLM) for the single most-valuable improvement, and files ONE deduplicated tracker issue (GitHub/GitLab/Jira/PLAN.md) for a coding agent. The model never writes code — every side effect is deterministic. Off by default; enable per app under its config.',
- category: 'layered-intelligence',
- interval: 'daily',
- intervalMs: DAY,
- enabled: false,
- priority: 'MEDIUM',
- type: 'script',
- scriptHandler: 'layered-intelligence',
- lastRun: null,
- runCount: 0,
- createdAt: null,
- updatedAt: null
- },
+ // 'job-layered-intelligence' removed (#2322): Layered Intelligence is now a
+ // per-app HANDLER-BACKED scheduled task (CoS → Schedule) rather than a global
+ // autonomous-job sweep. Migration 184 tombstones the persisted job record and
+ // moves each app's scheduling into taskTypeOverrides['layered-intelligence'].
{
id: 'job-wiki-maintenance',
name: 'Wiki Maintenance',
@@ -399,9 +386,13 @@ function applyAdditiveFields(existing, defaultJob) {
* was made that requires the caller to persist the result.
*/
function mergeWithDefaults(loaded) {
- // Migration: remove jobs moved to Schedule system
+ // Migration: remove jobs moved to the Schedule system. `job-layered-intelligence`
+ // is retired to a per-app handler-backed scheduled task (#2322) — migration 184
+ // captures its enabled state + tombstones it (and runs at boot BEFORE this), so
+ // this filter is defense-in-depth against a lingering orphan (which, lacking a
+ // SCRIPT_HANDLERS entry, would otherwise error on every scheduler fire).
const countBefore = loaded.jobs.length
- loaded.jobs = loaded.jobs.filter(j => j.id !== 'job-pr-reviewer' && j.id !== 'job-jira-sprint-manager')
+ loaded.jobs = loaded.jobs.filter(j => j.id !== 'job-pr-reviewer' && j.id !== 'job-jira-sprint-manager' && j.id !== 'job-layered-intelligence')
let dirty = loaded.jobs.length !== countBefore
const existingById = new Map(loaded.jobs.map(j => [j.id, j]))
diff --git a/server/services/autonomousJobs/layeredIntelligenceHandler.js b/server/services/autonomousJobs/layeredIntelligenceHandler.js
index 4f6b346d37..96617a9310 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHandler.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHandler.js
@@ -1,19 +1,26 @@
/**
- * Layered Intelligence Loop — the Engine-B sweep handler.
+ * Layered Intelligence Loop — the per-app deterministic handler.
*
- * Registered in SCRIPT_HANDLERS as `layered-intelligence`. On each fire it sweeps
- * getActiveApps() and processes every app whose `layeredIntelligence.enabled ===
- * true`, honoring a per-app `intervalMs`. For each due app it runs the four
- * layers: GATHER → REASON → DECIDE → ACT. The reasoning model only returns
- * structured JSON; all side effects (dedup, scope-gate, pause, filing) are the
- * deterministic helpers in ../layeredIntelligence.js.
+ * Driven by the `layered-intelligence` HANDLER-BACKED scheduled task (issue
+ * #2322): the CoS scheduler tick + on-demand drain call
+ * `runLayeredIntelligenceForApp(app)` for ONE app whose per-app override is due,
+ * instead of spawning a coding agent. For that app it runs the four layers:
+ * GATHER → REASON → DECIDE → ACT. The reasoning model only returns structured
+ * JSON; all side effects (dedup, scope-gate, pause, filing) are the deterministic
+ * helpers in ../layeredIntelligence.js.
+ *
+ * The scheduler now owns gating (per-app enabled) and cadence (interval / due-ness
+ * via the task schedule), so this handler does NOT re-check enabled/due — it just
+ * runs the layers and records `lastRunAt` bookkeeping. Scheduling provider/model
+ * come from the per-app `taskTypeOverrides['layered-intelligence']` (option A);
+ * behavior (sources/scopes/rules/handoff) stays in `app.layeredIntelligence`.
*
* Runs OUTSIDE the request lifecycle, so — per the CLAUDE.md no-try/catch rule —
- * a per-app failure is wrapped, logged emoji-style, and the sweep continues; one
- * bad app never aborts the whole sweep. Off by default (AI-provider policy).
+ * the scheduler's fire-and-forget wrapper is the async boundary; this stays
+ * defensive so a partial failure degrades to a no-op outcome. Off by default.
*/
-import { PORTOS_APP_ID, getActiveApps, updateAppLayeredIntelligence } from '../apps.js'
+import { PORTOS_APP_ID, updateAppLayeredIntelligence } from '../apps.js'
import {
getEffectiveConfig,
buildPrompt,
@@ -57,14 +64,24 @@ export function isAppDue(config, lastRunAt, now = Date.now()) {
}
/**
- * Process ONE app end-to-end (the four layers). Returns a structured outcome for
- * logging/telemetry: { app, action, ... }. Never throws — the caller's sweep
- * wrap is the async boundary, but this stays defensive so a partial failure of
- * one layer degrades to a no-op outcome rather than aborting.
+ * Run the Layered Intelligence loop for ONE app end-to-end (the four layers).
+ * Returns a structured outcome for logging/telemetry: { app, action, ... }.
+ * Never throws — the scheduler's fire-and-forget wrapper is the async boundary,
+ * but this stays defensive so a partial failure of one layer degrades to a no-op
+ * outcome rather than aborting.
+ *
+ * Does NOT gate on enabled/due — the scheduler owns per-app enablement + cadence
+ * now (this only runs when the schedule says the app's task is due). It still
+ * records `lastRunAt` bookkeeping via updateAppLayeredIntelligence.
+ *
+ * Behavior (sources/scopes/rules/handoff) reads from `app.layeredIntelligence`;
+ * the scheduling provider/model come from the per-app task override
+ * (taskTypeOverrides['layered-intelligence'], option A) and are overlaid onto the
+ * effective config here so the LLM step resolves the app-chosen provider.
*
* `deps` is injectable for tests (callLLM, forge listers/filers, plan append).
*/
-export async function processApp(app, deps = {}) {
+export async function runLayeredIntelligenceForApp(app, deps = {}) {
const {
callLLM,
enqueueHandoff = defaultEnqueueHandoff,
@@ -74,10 +91,13 @@ export async function processApp(app, deps = {}) {
const isPortos = app.id === PORTOS_APP_ID
const config = getEffectiveConfig({ ...app, isPortos })
- if (!config.enabled) return { app: app.id, action: 'skipped', reason: 'disabled' }
- if (!isAppDue(config, app.layeredIntelligence?.lastRunAt, now)) {
- return { app: app.id, action: 'skipped', reason: 'not-due' }
- }
+ // Option A: provider/model live in the per-app scheduled-task override, not in
+ // app.layeredIntelligence. Overlay them so resolveLLM picks the app's choice.
+ const override = (app.taskTypeOverrides && typeof app.taskTypeOverrides === 'object')
+ ? (app.taskTypeOverrides['layered-intelligence'] || {})
+ : {}
+ if (override.providerId != null) config.providerId = override.providerId
+ if (override.model != null) config.model = override.model
// Resolve where this app files work — branch up front so a `plan` app never
// hits the forge-only label/issue paths.
@@ -340,24 +360,8 @@ async function recordRun(app, config, now) {
})
}
-/**
- * The SCRIPT_HANDLERS entry. Sweeps active apps and processes each enabled+due
- * one. Per-app failures are caught and logged so the sweep continues.
- */
-export async function runLayeredIntelligence() {
- const apps = await getActiveApps()
- const results = []
- let processed = 0
- for (const app of apps) {
- const config = getEffectiveConfig({ ...app, isPortos: app.id === PORTOS_APP_ID })
- if (!config.enabled) continue
- const outcome = await processApp(app).catch((err) => {
- console.error(`❌ Layered Intelligence: ${app.name} sweep error: ${err.message}`)
- return { app: app.id, action: 'error', error: err.message }
- })
- if (outcome.action !== 'skipped') processed++
- results.push(outcome)
- }
- console.log(`🧠 Layered Intelligence sweep complete: ${processed} app(s) processed of ${apps.length} active`)
- return { processed, total: apps.length, results }
-}
+// Back-compat alias for the per-app entry point. The global cross-app sweep
+// (`runLayeredIntelligence`) was removed with the migration to a per-app
+// handler-backed scheduled task (#2322) — the scheduler now calls
+// runLayeredIntelligenceForApp for one due app at a time.
+export const processApp = runLayeredIntelligenceForApp
diff --git a/server/services/autonomousJobs/layeredIntelligenceHandler.test.js b/server/services/autonomousJobs/layeredIntelligenceHandler.test.js
index 03eab5a718..2b515191e5 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHandler.test.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHandler.test.js
@@ -74,8 +74,7 @@ vi.mock('../providers.js', () => ({
getActiveProvider: (...args) => getActiveProviderMock(...args)
}));
-import { isAppDue, processApp, runLayeredIntelligence } from './layeredIntelligenceHandler.js';
-import { getActiveApps } from '../apps.js';
+import { isAppDue, processApp, runLayeredIntelligenceForApp } from './layeredIntelligenceHandler.js';
const DAY = 24 * 60 * 60 * 1000;
@@ -136,19 +135,34 @@ describe('processApp', () => {
...extra
});
- it('skips a disabled app', async () => {
- const out = await processApp({ id: 'x', name: 'X', layeredIntelligence: { enabled: false } });
- expect(out.action).toBe('skipped');
- expect(out.reason).toBe('disabled');
+ // The scheduler now owns enabled/due gating (#2322) — the handler no longer
+ // self-gates on config.enabled or interval, so a disabled/not-due app is simply
+ // never dispatched to it. `runLayeredIntelligenceForApp` (aliased as processApp)
+ // always runs the layers and records the run.
+ it('runs the layers even for a config marked disabled (scheduler owns gating)', async () => {
+ const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X', body: 'do it' } });
+ const out = await runLayeredIntelligenceForApp({ id: 'app-1', name: 'App One', repoPath: '/repo', layeredIntelligence: { enabled: false, allowedScopes: ['app-improvement'] } }, { callLLM });
+ expect(out.action).toBe('filed');
+ expect(updateAppMock).toHaveBeenCalled(); // still records the run
});
- it('skips an app that is not due', async () => {
+ it('runs regardless of lastRunAt (cadence is the scheduler\'s job now)', async () => {
const now = Date.parse('2026-07-07T00:00:00Z');
const app = enabledApp();
- app.layeredIntelligence.lastRunAt = new Date(now - DAY / 2).toISOString();
- const out = await processApp(app, { now });
- expect(out.action).toBe('skipped');
- expect(out.reason).toBe('not-due');
+ app.layeredIntelligence.lastRunAt = new Date(now - DAY / 2).toISOString(); // "not due" by old logic
+ const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X', body: 'do it' } });
+ const out = await processApp(app, { now, callLLM });
+ expect(out.action).toBe('filed');
+ });
+
+ it('overlays provider/model from the per-app task override onto the effective config', async () => {
+ // No callLLM injected → resolveLLM resolves via getProviderById using the
+ // override's providerId. Assert the override provider is the one looked up.
+ getProviderByIdMock.mockResolvedValue({ id: 'ov-provider', type: 'api', defaultModel: 'ov-default' });
+ const app = enabledApp({ taskTypeOverrides: { 'layered-intelligence': { providerId: 'ov-provider', model: 'ov-model' } } });
+ await runLayeredIntelligenceForApp(app, {});
+ expect(getProviderByIdMock).toHaveBeenCalledWith('ov-provider');
+ expect(runPromptMock).toHaveBeenCalledWith(expect.objectContaining({ model: 'ov-model' }));
});
it('parks (skips reasoning) when a blocking issue is open', async () => {
@@ -451,19 +465,11 @@ describe('processApp — jira tracker', () => {
});
});
-describe('runLayeredIntelligence sweep', () => {
- it('processes only enabled apps and continues past a per-app error', async () => {
- getActiveApps.mockResolvedValue([
- { id: 'off', name: 'Off', layeredIntelligence: { enabled: false } },
- { id: 'app-1', name: 'On', repoPath: '/r', layeredIntelligence: { enabled: true, intervalMs: DAY, allowedScopes: ['app-improvement'] } }
- ]);
- // No callLLM injected → resolveLLM will try to import providers; make the
- // tracker resolve so processApp reaches the provider step and no-ops on no provider.
- resolveTrackerMock.mockResolvedValue({ resolved: 'plan', forge: null });
- const res = await runLayeredIntelligence();
- expect(res.total).toBe(2);
- // The enabled app is attempted (processed >= 0); the disabled one is skipped before processApp.
- expect(res.results.some(r => r.app === 'off')).toBe(false);
- expect(res.results.some(r => r.app === 'app-1')).toBe(true);
+describe('runLayeredIntelligenceForApp (removed global sweep)', () => {
+ it('no longer exports a cross-app sweep — the scheduler drives one app at a time', async () => {
+ const mod = await import('./layeredIntelligenceHandler.js');
+ expect(mod.runLayeredIntelligence).toBeUndefined();
+ expect(typeof mod.runLayeredIntelligenceForApp).toBe('function');
+ expect(mod.processApp).toBe(mod.runLayeredIntelligenceForApp); // back-compat alias
});
});
diff --git a/server/services/autonomousJobs/scriptHandlers.js b/server/services/autonomousJobs/scriptHandlers.js
index c9340a65f5..4e53d662ae 100644
--- a/server/services/autonomousJobs/scriptHandlers.js
+++ b/server/services/autonomousJobs/scriptHandlers.js
@@ -16,7 +16,6 @@ import { checkAndPrompt as autobiographyCheckAndPrompt } from '../autobiography.
import { runGoalCheckIn } from '../goalCheckIn.js'
import { cleanupOrphanedWorktrees, reapMergedWorktrees } from '../worktreeManager.js'
import { getActiveAgentIds } from '../agentState.js'
-import { runLayeredIntelligence } from './layeredIntelligenceHandler.js'
/**
* Run the moltworld-explore.mjs script as a child process (no AI agent needed).
@@ -140,8 +139,10 @@ const SCRIPT_HANDLERS = {
'autobiography-prompt': autobiographyCheckAndPrompt,
'moltworld-exploration': runMoltworldExploration,
'agent-data-cleanup': agentDataCleanup,
- 'goal-check-in': runGoalCheckIn,
- 'layered-intelligence': runLayeredIntelligence
+ 'goal-check-in': runGoalCheckIn
+ // 'layered-intelligence' retired (#2322): LI is now a per-app HANDLER-BACKED
+ // scheduled task, not a global autonomous-job sweep. See taskSchedule.js
+ // HANDLER_BACKED_TASK_TYPES + cosTaskGenerator.runHandlerBackedTaskForApp.
}
export { runMoltworldExploration, agentDataCleanup, SCRIPT_HANDLERS }
diff --git a/server/services/cos.js b/server/services/cos.js
index 6420fa3297..ef6f676832 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -93,7 +93,9 @@ import {
countRunningAgentsByProject,
isWithinProjectLimit,
checkStagePrecondition,
- applyAppWorktreeDefault
+ applyAppWorktreeDefault,
+ runHandlerBackedTaskForApp,
+ emitHandlerBackedOnDemand
} from './cosTaskGenerator.js';
export { evaluateTasks, checkStagePrecondition, applyAppWorktreeDefault };
@@ -763,6 +765,14 @@ async function dequeueNextTask() {
await taskScheduleMod.clearOnDemandRequest(request.id);
+ // Handler-backed tasks (layered-intelligence) are inherently per-app — a
+ // global (no-app) request can't dispatch one, and must NEVER fall through to
+ // the self-improvement agent path below.
+ if (taskScheduleMod.HANDLER_BACKED_TASK_TYPES.has(request.taskType) && !targetApp) {
+ emitLog('info', `On-demand ${request.taskType} skipped — handler-backed tasks require an app`, { requestId: request.id });
+ continue;
+ }
+
if (targetApp) {
emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}`, { requestId: request.id, appId: targetApp.id });
// A user-initiated "Run" must re-check live state, never honor a stale
@@ -778,6 +788,15 @@ async function dequeueNextTask() {
reviewStartedApps.add(targetApp.id);
}
await taskScheduleMod.recordExecution(`task:${request.taskType}`, targetApp.id);
+ // HANDLER-BACKED types (layered-intelligence) run a deterministic handler
+ // for this app instead of generating an agent task. Emit the same ran/
+ // no-work feedback and move on — no agent enqueue.
+ if (taskScheduleMod.HANDLER_BACKED_TASK_TYPES.has(request.taskType)) {
+ const outcome = await runHandlerBackedTaskForApp(request.taskType, targetApp)
+ .catch((err) => { emitLog('warn', `Handler-backed ${request.taskType} failed for ${targetApp.name}: ${err.message}`, { appId: targetApp.id }); return { action: 'error', error: err.message }; });
+ await emitHandlerBackedOnDemand({ outcome, request, targetApp });
+ continue;
+ }
task = await generateManagedAppImprovementTaskForType(request.taskType, targetApp, state, { skipPreconditions: true });
if (task) {
await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index 6e64012eda..35de19e0a9 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -846,6 +846,37 @@ describe('cos.js source — priority + capacity invariants', () => {
}
});
+ it('queueEligibleImprovementTasks runs HANDLER-BACKED types via the handler, never the agent path', () => {
+ // #2322: layered-intelligence is a deterministic handler-backed task. When
+ // getNextTaskType picks a handler-backed type for an app, the queue path MUST
+ // dispatch the in-process handler and `continue` — BEFORE (and instead of)
+ // calling generateManagedAppImprovementTaskForType. A bug here can only fail
+ // to run the handler; it can never spawn a runaway coding agent.
+ const fnStart = GEN_SRC.indexOf('async function queueEligibleImprovementTasks');
+ const fnBody = extractFnBody(GEN_SRC, fnStart);
+
+ // Imports HANDLER_BACKED_TASK_TYPES from the schedule and branches on it.
+ expect(fnBody).toMatch(/HANDLER_BACKED_TASK_TYPES/);
+ expect(fnBody).toMatch(/HANDLER_BACKED_TASK_TYPES\.has\(nextType\)/);
+
+ // The handler-backed branch dispatches + continues BEFORE the agent-spawn call.
+ const handlerIdx = fnBody.indexOf('HANDLER_BACKED_TASK_TYPES.has(nextType)');
+ const dispatchIdx = fnBody.indexOf('dispatchHandlerBackedTask(');
+ const generatorIdx = fnBody.indexOf('generateManagedAppImprovementTaskForType(');
+ expect(handlerIdx).toBeGreaterThan(-1);
+ expect(dispatchIdx).toBeGreaterThan(handlerIdx);
+ expect(dispatchIdx).toBeLessThan(generatorIdx); // handler dispatched before the agent path
+
+ // The shared runner lazily imports the LI handler (no static import cycle).
+ expect(GEN_SRC).toMatch(/export async function runHandlerBackedTaskForApp/);
+ expect(GEN_SRC).toMatch(/import\(['"]\.\/autonomousJobs\/layeredIntelligenceHandler\.js['"]\)/);
+ // And it never routes a handler-backed type through the agent generator.
+ const runnerStart = GEN_SRC.indexOf('export async function runHandlerBackedTaskForApp');
+ const runnerBody = extractFnBody(GEN_SRC, runnerStart);
+ expect(runnerBody).not.toMatch(/generateManagedAppImprovementTaskForType/);
+ expect(runnerBody).toMatch(/runLayeredIntelligenceForApp/);
+ });
+
it('queueEligibleImprovementTasks routes through generateManagedAppImprovementTaskForType', () => {
// Regression guard: a 2026-05-21 incident saw two `plan-task` agents both
// open PRs for the same PLAN.md slug because the queue path was writing
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index f5c4483742..27b1927d35 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -533,6 +533,7 @@ async function spawnPriority0OnDemand(ctx) {
const { state, availableSlots, tasksToSpawn, canSpawnTask, trackSpawn } = ctx;
const taskSchedule = await import('./taskSchedule.js');
+ const { HANDLER_BACKED_TASK_TYPES } = taskSchedule;
const liveSchedule = await taskSchedule.loadSchedule();
const onDemandRequests = Array.isArray(liveSchedule?.onDemandRequests) ? liveSchedule.onDemandRequests : [];
@@ -572,6 +573,14 @@ async function spawnPriority0OnDemand(ctx) {
await taskSchedule.clearOnDemandRequest(request.id);
+ // Handler-backed tasks (layered-intelligence) are inherently per-app — a
+ // global (no-app) request can't dispatch one, and must NEVER fall through
+ // to the self-improvement agent path below.
+ if (HANDLER_BACKED_TASK_TYPES.has(request.taskType) && !targetApp) {
+ emitLog('info', `On-demand ${request.taskType} skipped — handler-backed tasks require an app`, { requestId: request.id });
+ continue;
+ }
+
if (targetApp) {
emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}`, { requestId: request.id, appId: targetApp.id });
// A user-initiated "Run" must re-check live state — reset any park + the
@@ -586,6 +595,15 @@ async function spawnPriority0OnDemand(ctx) {
reviewStartedApps.add(targetApp.id);
}
await taskSchedule.recordExecution(`task:${request.taskType}`, targetApp.id);
+ // HANDLER-BACKED types run the deterministic handler for this app instead
+ // of generating an agent task. Emit the same ran/no-work feedback, then
+ // move to the next request (never enqueue an agent task).
+ if (HANDLER_BACKED_TASK_TYPES.has(request.taskType)) {
+ const outcome = await runHandlerBackedTaskForApp(request.taskType, targetApp)
+ .catch((err) => { console.error(`❌ Handler-backed ${request.taskType} failed for ${targetApp.name}: ${err.message}`); return { action: 'error', error: err.message }; });
+ await emitHandlerBackedOnDemand({ outcome, request, targetApp });
+ continue;
+ }
task = await generateManagedAppImprovementTaskForType(request.taskType, targetApp, state, { skipPreconditions: true });
if (task) {
await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);
@@ -1092,7 +1110,7 @@ export async function generateIdleReviewTask(state) {
* Tasks are queued to COS-TASKS.md and will be picked up in Priority 2
*/
export async function queueEligibleImprovementTasks(state, cosTaskData, { ignoreTaskId = null } = {}) {
- const { getNextTaskType, recordExecution } = await import('./taskSchedule.js');
+ const { getNextTaskType, recordExecution, HANDLER_BACKED_TASK_TYPES } = await import('./taskSchedule.js');
if (!isImprovementEnabled(state)) return;
@@ -1193,6 +1211,16 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, { ignore
if (!nextTypeResult) continue;
const nextType = nextTypeResult.taskType;
+ // HANDLER-BACKED types (e.g. layered-intelligence) run a deterministic
+ // in-process handler for this app instead of spawning a coding agent. Fire
+ // it and-forget (guarded per-app so the next tick can't double-run it),
+ // record the execution on completion, and move on — NEVER touch the
+ // agent-spawn path below. A bug here can only fail to run the handler.
+ if (HANDLER_BACKED_TASK_TYPES.has(nextType)) {
+ dispatchHandlerBackedTask(nextType, app, recordExecution);
+ continue;
+ }
+
const taskKey = `app:${app.id}:${nextType}`;
if (existingTaskTypes.has(taskKey)) {
emitLog('debug', `Improvement task ${nextType} for ${app.name} already queued`);
@@ -1519,6 +1547,92 @@ async function generateManagedAppImprovementTask(app, state) {
* user-initiated on-demand path, so the client can toast it without
* background-park noise.
*/
+// Per-app in-flight guard for handler-backed tasks so a fire-and-forget run
+// started by one scheduler tick (or an on-demand drain) can't be double-started
+// by the next tick for the same app before it settles. Keyed by app id.
+const handlerBackedInFlight = new Set();
+
+/** True when a handler-backed task is currently running for this app. */
+export function isHandlerBackedInFlight(appId) {
+ return handlerBackedInFlight.has(appId);
+}
+
+/**
+ * Run a HANDLER-BACKED (deterministic, no-agent) scheduled task for ONE app,
+ * dispatching to the in-process handler for its type instead of spawning a coding
+ * agent (see taskSchedule.HANDLER_BACKED_TASK_TYPES). Guarded by a module-level
+ * per-app in-flight Set. Returns the handler's outcome, `{ action: 'in-flight' }`
+ * when a prior run for this app is still active, or `{ action: 'no-handler' }`
+ * for an unrecognized type. The handler is lazily imported to avoid a static
+ * import cycle (the handler pulls in apps.js / providers). Callers that run this
+ * outside the request lifecycle MUST wrap it (the `finally` clears the guard even
+ * if the handler throws, but the throw still propagates to the caller's boundary).
+ */
+export async function runHandlerBackedTaskForApp(taskType, app) {
+ if (handlerBackedInFlight.has(app.id)) return { app: app.id, action: 'in-flight' };
+ handlerBackedInFlight.add(app.id);
+ try {
+ if (taskType === 'layered-intelligence') {
+ const { runLayeredIntelligenceForApp } = await import('./autonomousJobs/layeredIntelligenceHandler.js');
+ return await runLayeredIntelligenceForApp(app);
+ }
+ return { app: app.id, action: 'no-handler' };
+ } finally {
+ handlerBackedInFlight.delete(app.id);
+ }
+}
+
+/**
+ * Fire-and-forget a handler-backed task from the scheduler tick: run it, record
+ * the execution (so cadence advances), and log — never throwing into the tick
+ * loop. Skips the recordExecution when the run was a no-op because another run
+ * for this app was already in flight. Boundary-wrapped (runs outside the request
+ * lifecycle). `recordExecution` is passed in (already imported by the caller).
+ */
+function dispatchHandlerBackedTask(taskType, app, recordExecution) {
+ runHandlerBackedTaskForApp(taskType, app)
+ .then(async (outcome) => {
+ if (outcome?.action === 'in-flight') return; // a prior tick is still running
+ await recordExecution(`task:${taskType}`, app.id);
+ emitLog('info', `Ran handler-backed ${taskType} for ${app.name} (${outcome?.action || 'done'})`, { appId: app.id, action: outcome?.action });
+ })
+ .catch((err) => {
+ console.error(`❌ Handler-backed ${taskType} failed for ${app.name}: ${err.message}`);
+ });
+}
+
+/**
+ * On-demand (user "Run now") feedback for a handler-backed task: it produces no
+ * agent task, so mirror the agent path's "ran / no work" signal. When the run
+ * filed an issue we toast a success; otherwise we reuse the on-demand-empty
+ * channel with outcome 'idle' (nothing to do right now). Boundary-safe.
+ */
+export async function emitHandlerBackedOnDemand({ outcome, request, targetApp }) {
+ const appName = targetApp?.name || null;
+ const appId = targetApp?.id || null;
+ const filed = outcome?.action === 'filed';
+ if (filed) {
+ cosEvents.emit('schedule:on-demand-ran', {
+ requestId: request.id,
+ taskType: request.taskType,
+ appId,
+ appName,
+ action: outcome.action,
+ filedNumber: outcome.filedNumber ?? null,
+ filedKey: outcome.filedKey ?? null
+ });
+ return;
+ }
+ cosEvents.emit('schedule:on-demand-empty', {
+ requestId: request.id,
+ taskType: request.taskType,
+ appId,
+ appName,
+ outcome: 'idle',
+ handlerAction: outcome?.action || 'no-op'
+ });
+}
+
export async function emitOnDemandEmpty({ taskScheduleMod, request, targetApp, taskConfig }) {
const appId = targetApp?.id || null;
const parkInfo = await taskScheduleMod.getPerpetualParkInfo(request.taskType, appId).catch(() => null);
diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.js
index 2c5cbf199e..0d2ebafa1f 100644
--- a/server/services/layeredIntelligence.js
+++ b/server/services/layeredIntelligence.js
@@ -54,10 +54,11 @@ export const SEMANTIC_DEDUP_THRESHOLD = 0.9;
// issues should be few (the loop files ≤1/run), so this is a generous ceiling.
export const SEMANTIC_DEDUP_MAX_CANDIDATES = 50;
-// The autonomous-job id that drives the whole loop (the global sweep). Single
-// source of truth — the DEFAULT_JOBS catalog entry and the cross-app overview
-// route both key on this so per-app enablement and the global on/off stay in
-// sync in the UI (a per-app config does nothing while this job is disabled).
+// The id of the RETIRED global autonomous-job that used to drive the whole loop
+// (the cross-app sweep). Layered Intelligence is now a per-app handler-backed
+// scheduled task (#2322), so this constant is kept ONLY so migration 184 can find
+// and tombstone the legacy `data/cos/autonomous-jobs.json` record on installs that
+// still carry it. Nothing dispatches on it anymore.
export const LI_JOB_ID = 'job-layered-intelligence';
// Every proposal scope the reasoner may return. The handler enforces WHERE each
@@ -140,34 +141,44 @@ export function getEffectiveConfig(app) {
/**
* Summarize one app's loop status for the cross-app overview page. Pure and
* side-effect-free (no LLM, no forge I/O): derives the display shape from the
- * app's stored config + scheduler bookkeeping only. `lastRunAt` rides along on
- * the effective config (a passthrough stored key, absent on a never-run app);
- * `nextDueAt` is `lastRunAt + intervalMs` (null when never run), and `due` is a
- * display flag (only meaningful when enabled) mirroring the sweep's cadence
- * check. `rules` is reduced to a boolean so the free-text guidance never leaks
- * into a list payload.
+ * app's stored config + the per-app scheduled-task override.
+ *
+ * Under option A (#2322) the SCHEDULING fields — enabled / intervalMs /
+ * providerId / model — live in the per-app `taskTypeOverrides['layered-intelligence']`
+ * (passed in as `override`), NOT in `app.layeredIntelligence`. BEHAVIOR fields
+ * (sources / scopes / rules / handoff) plus `lastRunAt` bookkeeping still come
+ * from the effective config. `nextDueAt` is `lastRunAt + intervalMs` (null when
+ * never run), and `due` is a display flag (only meaningful when enabled) mirroring
+ * the scheduler's cadence check. `rules` is reduced to a boolean so the free-text
+ * guidance never leaks into a list payload.
*/
-export function summarizeLoopStatus({ app, isPortos = false, now = Date.now() } = {}) {
+export function summarizeLoopStatus({ app, isPortos = false, override = null, now = Date.now() } = {}) {
const config = getEffectiveConfig({ ...app, isPortos });
const sources = config.sources || {};
+ const ov = (override && typeof override === 'object' && !Array.isArray(override)) ? override : {};
+ const enabled = ov.enabled === true;
+ const intervalMs = (typeof ov.intervalMs === 'number' && Number.isFinite(ov.intervalMs) && ov.intervalMs > 0)
+ ? ov.intervalMs
+ : (config.intervalMs || 0);
+ const providerId = ov.providerId || null;
+ const model = ov.model || null;
const lastRunAt = typeof config.lastRunAt === 'string' ? config.lastRunAt : null;
const last = lastRunAt ? Date.parse(lastRunAt) : NaN;
- const interval = config.intervalMs || 0;
- const nextDueAt = Number.isFinite(last) ? new Date(last + interval).toISOString() : null;
- const due = !Number.isFinite(last) || (now - last) >= interval;
+ const nextDueAt = Number.isFinite(last) ? new Date(last + intervalMs).toISOString() : null;
+ const due = !Number.isFinite(last) || (now - last) >= intervalMs;
return {
id: app.id,
name: app.name || app.id,
isPortos,
- enabled: !!config.enabled,
- intervalMs: config.intervalMs,
- providerId: config.providerId || null,
- model: config.model || null,
+ enabled,
+ intervalMs,
+ providerId,
+ model,
handoffEnabled: !!config.handoff?.enabled,
hasRules: !!(typeof config.rules === 'string' && config.rules.trim()),
lastRunAt,
nextDueAt,
- due: !!config.enabled && due,
+ due: enabled && due,
allowedScopes: Array.isArray(config.allowedScopes) ? config.allowedScopes : [],
sources: {
goals: !!sources.goals,
diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.js
index 0474844981..6ad7689a8d 100644
--- a/server/services/layeredIntelligence.test.js
+++ b/server/services/layeredIntelligence.test.js
@@ -125,9 +125,12 @@ describe('summarizeLoopStatus (overview page shape)', () => {
const DAY = 24 * 60 * 60 * 1000;
const NOW = Date.parse('2026-07-07T12:00:00Z');
+ // Scheduling (enabled/intervalMs) now lives in the per-app task override (#2322);
+ // behavior + lastRunAt still come from app.layeredIntelligence.
it('summarizes a never-run enabled app as due with no lastRun/nextDue', () => {
const s = summarizeLoopStatus({
- app: { id: 'a1', name: 'App One', layeredIntelligence: { enabled: true, intervalMs: DAY } },
+ app: { id: 'a1', name: 'App One' },
+ override: { enabled: true, intervalMs: DAY },
now: NOW
});
expect(s).toMatchObject({ id: 'a1', name: 'App One', enabled: true, due: true, lastRunAt: null, nextDueAt: null });
@@ -138,7 +141,8 @@ describe('summarizeLoopStatus (overview page shape)', () => {
it('computes nextDueAt = lastRunAt + intervalMs and due=false before the interval elapses', () => {
const lastRunAt = new Date(NOW - DAY / 2).toISOString();
const s = summarizeLoopStatus({
- app: { id: 'a2', name: 'App Two', layeredIntelligence: { enabled: true, intervalMs: DAY, lastRunAt } },
+ app: { id: 'a2', name: 'App Two', layeredIntelligence: { lastRunAt } },
+ override: { enabled: true, intervalMs: DAY },
now: NOW
});
expect(s.lastRunAt).toBe(lastRunAt);
@@ -149,7 +153,8 @@ describe('summarizeLoopStatus (overview page shape)', () => {
it('due is always false when the app is disabled, even past the interval', () => {
const lastRunAt = new Date(NOW - 2 * DAY).toISOString();
const s = summarizeLoopStatus({
- app: { id: 'a3', name: 'Off', layeredIntelligence: { enabled: false, intervalMs: DAY, lastRunAt } },
+ app: { id: 'a3', name: 'Off', layeredIntelligence: { lastRunAt } },
+ override: { enabled: false, intervalMs: DAY },
now: NOW
});
expect(s.enabled).toBe(false);
@@ -158,26 +163,39 @@ describe('summarizeLoopStatus (overview page shape)', () => {
it('reduces rules to a boolean and never leaks the free text', () => {
const s = summarizeLoopStatus({
- app: { id: 'a4', name: 'Ruled', layeredIntelligence: { enabled: true, rules: 'never add deps' } },
+ app: { id: 'a4', name: 'Ruled', layeredIntelligence: { rules: 'never add deps' } },
+ override: { enabled: true },
now: NOW
});
expect(s.hasRules).toBe(true);
expect(JSON.stringify(s)).not.toContain('never add deps');
});
- it('surfaces the hand-off enabled flag', () => {
+ it('surfaces the hand-off enabled flag (behavior, from layeredIntelligence)', () => {
const off = summarizeLoopStatus({ app: { id: 'h0', name: 'Off' }, now: NOW });
expect(off.handoffEnabled).toBe(false);
const on = summarizeLoopStatus({
- app: { id: 'h1', name: 'On', layeredIntelligence: { enabled: true, handoff: { enabled: true } } },
+ app: { id: 'h1', name: 'On', layeredIntelligence: { handoff: { enabled: true } } },
+ override: { enabled: true },
now: NOW
});
expect(on.handoffEnabled).toBe(true);
});
+ it('reads provider/model from the override, not layeredIntelligence', () => {
+ const s = summarizeLoopStatus({
+ app: { id: 'p1', name: 'Prov' },
+ override: { enabled: true, providerId: 'ov-prov', model: 'ov-model' },
+ now: NOW
+ });
+ expect(s.providerId).toBe('ov-prov');
+ expect(s.model).toBe('ov-model');
+ });
+
it('surfaces PortOS scopes + custom source count', () => {
const s = summarizeLoopStatus({
- app: { id: 'portos-default', name: 'PortOS', layeredIntelligence: { enabled: true, sources: { custom: [{ type: 'file', ref: 'x.md' }] } } },
+ app: { id: 'portos-default', name: 'PortOS', layeredIntelligence: { sources: { custom: [{ type: 'file', ref: 'x.md' }] } } },
+ override: { enabled: true },
isPortos: true,
now: NOW
});
diff --git a/server/services/socket.js b/server/services/socket.js
index ab43e7a8d1..03f4ed33e5 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -734,6 +734,7 @@ function setupCosEventForwarding() {
// this so an explicit trigger that finds no actionable work (parked) isn't a
// silent no-op.
cosEvents.on('schedule:on-demand-empty', (data) => broadcastToCos('cos:schedule:on-demand-empty', data));
+ cosEvents.on('schedule:on-demand-ran', (data) => broadcastToCos('cos:schedule:on-demand-ran', data));
}
// Set up error event forwarding
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 76f6ee83eb..24d56472c4 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -26,7 +26,7 @@ import { atomicWrite, DAY, ensureDir, HOUR, readJSONFile, PATHS, safeDate } from
import { isPlainObject } from '../lib/objects.js';
import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';
import { getAdaptiveCooldownMultiplier } from './taskLearning.js';
-import { isTaskTypeEnabledForApp, getAppTaskTypeInterval, getActiveApps, getAppTaskTypeOverrides, clearAllPrWatcherState } from './apps.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';
@@ -167,9 +167,26 @@ export const SELF_IMPROVEMENT_TASK_TYPES = [
// + 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'
+ 'refresh-local-llm-catalog',
+ // layered-intelligence is HANDLER-BACKED (deterministic, no coding agent): on
+ // each per-app fire it reads that app's goals + telemetry, asks a reasoning
+ // model for the single most-valuable improvement, and files ONE deduplicated
+ // tracker issue — the model never writes code. Unlike every other type here it
+ // does NOT spawn an agent (see HANDLER_BACKED_TASK_TYPES + the seam in
+ // cosTaskGenerator.queueEligibleImprovementTasks). 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 prompt is built deterministically by the handler.
+ 'layered-intelligence'
];
+// Task types whose scheduled fire runs a deterministic in-process handler instead
+// of spawning a coding agent. The scheduler tick + on-demand drain detect these
+// and dispatch the handler directly (never generateManagedAppImprovementTaskForType).
+// A bug in this path can only fail to run the handler — it can never spawn a
+// runaway agent. See server/services/cosTaskGenerator.js#runHandlerBackedTaskForApp.
+export const HANDLER_BACKED_TASK_TYPES = new Set(['layered-intelligence']);
+
// 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' } }] } } };
@@ -290,7 +307,13 @@ export const DEFAULT_TASK_INTERVALS = {
// 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 } }
+ 'refresh-local-llm-catalog': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: true, simplify: true } },
+ // layered-intelligence is handler-backed (deterministic, no agent). 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 handler builds its prompt itself (no DEFAULT_TASK_PROMPTS
+ // entry, so the prompt-version machinery in loadSchedule skips it).
+ 'layered-intelligence': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null }
};
// Agent-options that a task manages internally — UI locks the toggle, and
@@ -954,6 +977,12 @@ export async function shouldRunTask(taskType, appId = null) {
// Determine effective interval type: per-app override takes precedence
const perAppInterval = appId ? await getAppTaskTypeInterval(appId, taskType) : null;
+ // A per-app numeric intervalMs override (used by handler-backed tasks like
+ // layered-intelligence, whose Intelligence-tab UI offers sub-daily cadences the
+ // string enum can't express). When set alongside interval:'custom', the CUSTOM
+ // branch below uses THIS value as the base interval instead of the global one.
+ const perAppIntervalMs = appId ? await getAppTaskTypeIntervalMs(appId, taskType) : null;
+ const hasCustomIntervalMs = Number.isFinite(perAppIntervalMs) && perAppIntervalMs > 0;
// Cron expressions (contain spaces) are stored directly as the interval value
const isCronOverride = perAppInterval && perAppInterval.includes(' ');
const effectiveType = isCronOverride ? INTERVAL_TYPES.CRON : (perAppInterval || interval.type);
@@ -1029,7 +1058,9 @@ export async function shouldRunTask(taskType, appId = null) {
break;
case INTERVAL_TYPES.CUSTOM: {
- const baseInterval = interval.intervalMs || DAY;
+ // A per-app numeric intervalMs override wins over the global custom interval
+ // (handler-backed tasks store their per-app cadence there).
+ const baseInterval = (hasCustomIntervalMs ? perAppIntervalMs : interval.intervalMs) || DAY;
const learningAdjustment = await getPerformanceAdjustedInterval(taskType, baseInterval);
const adjustedInterval = learningAdjustment.adjustedIntervalMs;
if (timeSinceLastRun >= adjustedInterval) {
@@ -1595,7 +1626,8 @@ export const TASK_TYPE_DESCRIPTIONS = {
'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',
- 'refresh-local-llm-catalog': "Refresh PortOS's bundled suggested local-model catalog + editorial ranking (PortOS repo only)"
+ 'refresh-local-llm-catalog': "Refresh PortOS's bundled suggested local-model catalog + editorial ranking (PortOS repo only)",
+ '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) {
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index 17dd82d947..c9a223fed3 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -52,6 +52,7 @@ vi.mock('./taskLearning.js', () => ({
vi.mock('./apps.js', () => ({
isTaskTypeEnabledForApp: vi.fn().mockResolvedValue(true),
getAppTaskTypeInterval: vi.fn().mockResolvedValue(null),
+ getAppTaskTypeIntervalMs: vi.fn().mockResolvedValue(null),
getActiveApps: vi.fn().mockResolvedValue([]),
getAppTaskTypeOverrides: vi.fn().mockResolvedValue({}),
clearAllPrWatcherState: vi.fn().mockResolvedValue({ changed: false })
@@ -110,7 +111,8 @@ import {
DEFAULT_TASK_INTERVALS,
MANAGED_AGENT_OPTIONS,
TASK_TYPE_DESCRIPTIONS,
- REFERENCE_WATCH_AUDITED_VERSION
+ REFERENCE_WATCH_AUDITED_VERSION,
+ HANDLER_BACKED_TASK_TYPES
} from './taskSchedule.js'
// Prompt getters moved to taskPromptService.js (issue #744 split, #1083 cycle
@@ -214,6 +216,33 @@ describe('taskSchedule', () => {
})
})
+ describe('layered-intelligence (handler-backed task type)', () => {
+ it('is registered as a self-improvement task with a description and a daily default', () => {
+ expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('layered-intelligence');
+ expect(TASK_TYPE_DESCRIPTIONS['layered-intelligence']).toBeTruthy();
+ expect(DEFAULT_TASK_INTERVALS['layered-intelligence']).toMatchObject({ type: 'daily', enabled: false });
+ });
+
+ it('is in HANDLER_BACKED_TASK_TYPES and has NO default prompt (deterministic)', () => {
+ expect(HANDLER_BACKED_TASK_TYPES.has('layered-intelligence')).toBe(true);
+ expect(DEFAULT_TASK_PROMPTS['layered-intelligence']).toBeUndefined();
+ });
+
+ it('honors a per-app numeric intervalMs override via the CUSTOM branch', async () => {
+ const { getAppTaskTypeInterval, getAppTaskTypeIntervalMs } = await import('./apps.js');
+ mockSchedule({
+ tasks: { 'layered-intelligence': { type: 'daily', enabled: true, providerId: null, model: null, prompt: null } },
+ executions: { 'task:layered-intelligence': { lastRun: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(), count: 1, perApp: { 'app-1': { lastRun: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(), count: 1 } } } }
+ });
+ getAppTaskTypeInterval.mockResolvedValue('custom');
+ getAppTaskTypeIntervalMs.mockResolvedValue(60 * 60 * 1000); // hourly → 2h since last run ⇒ due
+ const res = await shouldRunTask('layered-intelligence', 'app-1');
+ expect(res.shouldRun).toBe(true);
+ getAppTaskTypeInterval.mockResolvedValue(null);
+ getAppTaskTypeIntervalMs.mockResolvedValue(null);
+ });
+ });
+
describe('do-replan task type', () => {
it('should default to weekly, disabled, with worktree+PR metadata', async () => {
const interval = await getTaskInterval('do-replan')