Skip to content

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

fix: queue due install-wide scheduled tasks (#5629)

Adam Eivyeb516f98fd82
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index a52c93359d..fd1a96dd24 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -1571,6 +1571,69 @@ export function buildImprovementDedupSets(existingTasks, { ignoreTaskId = null }
return { existingTaskTypes, appsWithPendingImprovement, blockedTaskTypes, appsWithBlockedImprovement };
}
+function prepareQueuedImprovementTask(task) {
+ // Queued tasks round-trip through COS-TASKS.md, whose task description field
+ // is single-line. Preserve the full prompt in metadata so the agent receives
+ // it after the task is re-read from disk.
+ if (typeof task.description === 'string' && task.description.includes('\n')) {
+ task.metadata = task.metadata || {};
+ task.metadata.prompt = task.description;
+ task.description = firstLine(task.description);
+ }
+ return task;
+}
+
+export async function queueDueInstallWideImprovementTasks({
+ dueTasks,
+ state,
+ taskSchedule,
+ existingTaskTypes,
+ blockedTaskTypes,
+ ignoreTaskId = null,
+ wakeAfterRecord = true,
+ generateTask = generateSelfImprovementTaskForType,
+ persistTask = addTask,
+ wake = () => cosEvents.emit('cos:dequeue-requested')
+}) {
+ let queued = 0;
+ const dueInstallWideTasks = dueTasks
+ .filter(({ taskType }) => taskSchedule.INSTALL_WIDE_TASK_TYPES.has(taskType));
+
+ for (const { taskType } of dueInstallWideTasks) {
+ const taskKey = taskType;
+ if (existingTaskTypes.has(taskKey)) {
+ if (blockedTaskTypes.has(taskKey)) {
+ emitLog('info', `⛔ Skipping install-wide ${taskType}: blocked task ${blockedTaskTypes.get(taskKey)} already exists — resolve or delete it to resume`, { analysisType: taskType });
+ } else {
+ emitLog('debug', `Install-wide improvement task ${taskType} already queued`);
+ }
+ continue;
+ }
+
+ const task = await generateTask(taskType, state);
+ // Hooks such as user-action-review's empty-ledger check deliberately
+ // advance their cadence while returning no task, so do not record a second
+ // execution here when the generator declines to dispatch.
+ if (!task) continue;
+
+ task.priority = 'LOW';
+ task.priorityValue = PRIORITY_VALUES.LOW;
+ task.id = `sys-install-${taskType}-${Date.now().toString(36)}`;
+ prepareQueuedImprovementTask(task);
+
+ const newTask = await persistTask(task, 'internal', { raw: true, ignoreTaskId, suppressDequeue: true });
+ if (newTask?.duplicate) continue;
+ if (wakeAfterRecord) wake();
+
+ await taskSchedule.recordExecution(`task:${taskType}`);
+ emitLog('info', `Queued install-wide improvement task: ${taskType}`, { taskId: newTask.id, analysisType: taskType });
+ existingTaskTypes.add(taskKey);
+ queued++;
+ }
+
+ return queued;
+}
+
/**
* Queue eligible self-improvement and app improvement tasks as system tasks
* Called during every evaluation to ensure system tasks are queued even when user tasks exist
@@ -1578,7 +1641,7 @@ export function buildImprovementDedupSets(existingTasks, { ignoreTaskId = null }
*/
export async function queueEligibleImprovementTasks(state, cosTaskData, { ignoreTaskId = null, wakeAfterRecord = true } = {}) {
const taskSchedule = await import('./taskSchedule.js');
- const { getNextTaskType, recordExecution } = taskSchedule;
+ const { getDueTasks, getNextTaskType, recordExecution } = taskSchedule;
if (!isImprovementEnabled(state)) return;
@@ -1592,6 +1655,21 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, { ignore
let queued = 0;
+ // Install-wide task types have no managed-app target: their cadence is
+ // tracked by the global execution record, and one task is the complete run
+ // for this PortOS install. Run this before the per-app pass: an install-wide
+ // hook may deliberately reject app targets while recording that app-scoped
+ // check, which must not consume the global due window first.
+ //
+ // Do not select a single generic next task here — every install-wide type
+ // that is independently due must get its own lane. The dedup key is the bare
+ // analysis type, matching buildImprovementDedupSets for globally-scoped tasks
+ // and ensuring one pending/blocked task suppresses only its own duplicate.
+ queued += await queueDueInstallWideImprovementTasks({
+ dueTasks: await getDueTasks(), state, taskSchedule, existingTaskTypes,
+ blockedTaskTypes, ignoreTaskId, wakeAfterRecord
+ });
+
// Load the activity snapshot ONCE before the per-app loop. Both the
// cooldown gate and the rotation `lastType` lookup are derived from
// `data/app-activity.json`; before this hoist, each app paid two
@@ -1709,11 +1787,7 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, { ignore
// multi-thousand-character agent prompt indistinguishable from one. Readers
// go through `getTaskPrompt` (server/lib/cosTaskPrompt.js), which falls back
// to `metadata.context` for tasks written before the split.
- if (typeof task.description === 'string' && task.description.includes('\n')) {
- task.metadata = task.metadata || {};
- task.metadata.prompt = task.description;
- task.description = firstLine(task.description);
- }
+ prepareQueuedImprovementTask(task);
const newTask = await addTask(task, 'internal', { raw: true, ignoreTaskId, suppressDequeue: true });
if (newTask?.duplicate) continue;
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index e105b2b087..9ee9389da4 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -71,6 +71,7 @@ import {
buildJiraTicketTask,
buildClaimWorkTask,
buildImprovementDedupSets,
+ queueDueInstallWideImprovementTasks,
normalizeWorkItemRef,
buildTargetWorkItemBlock,
buildPrefetchedIssueContextBlock,
@@ -1384,6 +1385,85 @@ describe('buildImprovementDedupSets (#2614 — failure-blocked tasks occupy thei
// its occupancy semantics can't silently drift from the tested helper.
expect(GEN_SRC).toMatch(/buildImprovementDedupSets\(existingTasks/);
});
+
+ it('queues a due install-wide task once and skips blocked or hook-declined types', async () => {
+ const generateTask = vi.fn(async (taskType) => (taskType === 'user-action-review'
+ ? null
+ : { id: 'generated', description: 'Global task\nwith full prompt', metadata: {} }));
+ const persistTask = vi.fn(async (task) => ({ ...task, id: 'persisted-task' }));
+ const recordExecution = vi.fn();
+ const wake = vi.fn();
+ const existingTaskTypes = new Set(['repo-sync']);
+ const blockedTaskTypes = new Map([['repo-sync', 'blocked-repo-sync']]);
+
+ const queued = await queueDueInstallWideImprovementTasks({
+ dueTasks: [
+ { taskType: 'repo-sync' },
+ { taskType: 'user-action-review' },
+ { taskType: 'unrelated-task' }
+ ],
+ state: { config: {} },
+ taskSchedule: {
+ INSTALL_WIDE_TASK_TYPES: new Set(['repo-sync', 'user-action-review']),
+ recordExecution
+ },
+ existingTaskTypes,
+ blockedTaskTypes,
+ generateTask,
+ persistTask,
+ wake
+ });
+
+ expect(queued).toBe(0);
+ expect(generateTask).toHaveBeenCalledTimes(1);
+ expect(generateTask).toHaveBeenCalledWith('user-action-review', { config: {} });
+ expect(persistTask).not.toHaveBeenCalled();
+ expect(recordExecution).not.toHaveBeenCalled();
+ expect(wake).not.toHaveBeenCalled();
+ expect(existingTaskTypes).toEqual(new Set(['repo-sync']));
+ });
+
+ it('persists and records one global dispatch when a due type appears twice', async () => {
+ const generateTask = vi.fn(async () => ({ id: 'generated', description: 'Global task\nwith full prompt', metadata: {} }));
+ const persistTask = vi.fn(async (task) => ({ ...task, id: 'persisted-task' }));
+ const recordExecution = vi.fn();
+ const wake = vi.fn();
+ const existingTaskTypes = new Set();
+
+ const queued = await queueDueInstallWideImprovementTasks({
+ dueTasks: [{ taskType: 'user-action-review' }, { taskType: 'user-action-review' }],
+ state: { config: {} },
+ taskSchedule: {
+ INSTALL_WIDE_TASK_TYPES: new Set(['user-action-review']),
+ recordExecution
+ },
+ existingTaskTypes,
+ blockedTaskTypes: new Map(),
+ generateTask,
+ persistTask,
+ wake
+ });
+
+ expect(queued).toBe(1);
+ expect(generateTask).toHaveBeenCalledTimes(1);
+ expect(persistTask).toHaveBeenCalledTimes(1);
+ expect(persistTask.mock.calls[0][0]).toMatchObject({
+ id: expect.stringMatching(/^sys-install-user-action-review-/),
+ description: 'Global task',
+ metadata: { prompt: 'Global task\nwith full prompt' }
+ });
+ expect(recordExecution).toHaveBeenCalledTimes(1);
+ expect(recordExecution).toHaveBeenCalledWith('task:user-action-review');
+ expect(wake).toHaveBeenCalledTimes(1);
+ expect(existingTaskTypes).toEqual(new Set(['user-action-review']));
+ });
+
+ it('uses the global due list before the per-app loop', () => {
+ const start = GEN_SRC.indexOf('export async function queueEligibleImprovementTasks');
+ const body = GEN_SRC.slice(start, GEN_SRC.indexOf('\n/**', start + 1));
+ expect(body).toContain('queueDueInstallWideImprovementTasks({');
+ expect(body.indexOf('queueDueInstallWideImprovementTasks({')).toBeLessThan(body.indexOf('for (const app of apps)'));
+ });
});
describe('resolveUserActionDeliveryBlock (#5595)', () => {