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

address review (codex r2): constrain queue pick to perpetual when on cooldown so mixed schedules drain

Adam Eivy6e73986d92f1
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index 88e018367e..6e64012eda 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -908,7 +908,7 @@ describe('cos.js source — priority + capacity invariants', () => {
expect(
fnBody,
'queue path must pass the loaded lastType through to getNextTaskType so rotation advances'
- ).toMatch(/getNextTaskType\(app\.id,\s*\w+\s*\)/);
+ ).toMatch(/getNextTaskType\(app\.id,\s*\w+\s*(?:,|\))/);
// appActivity helpers must come from the file-level static import (line ~23),
// NOT a dynamic `await import('./appActivity.js')` *inside* the per-app
@@ -942,35 +942,33 @@ describe('cos.js source — priority + capacity invariants', () => {
'queue path must not call the disk-reading isAppOnCooldown per app'
).not.toMatch(/await\s+isAppOnCooldown\(/);
- // Perpetual (drain-until-done) picks must BYPASS the per-app review
- // cooldown — their work-detector park is the throttle, not the cooldown
- // window. The spawn-time `markAppReviewCooldown` stamp (on-demand manual
- // trigger + idle-review loop) writes `lastReviewedAt`, so without the
- // bypass the back-to-back refill after a perpetual completion reads its own
- // app as on-cooldown and stalls — a manually-triggered perpetual task then
- // runs once instead of continuing the drain. Pin two halves: (a) the
- // cooldown gate is guarded by a non-perpetual predicate, and (b) the gate
- // is resolved AFTER getNextTaskType (so the picked type's reason is known
- // before the cooldown decision). `getNextTaskType` tags perpetual picks
- // with reason `perpetual-drain`.
+ // Perpetual (drain-until-done) picks must BYPASS the per-app review cooldown
+ // — their work-detector park is the throttle, not the cooldown window. The
+ // spawn-time `markAppReviewCooldown` stamp (on-demand manual trigger +
+ // idle-review loop) writes `lastReviewedAt`, so without the bypass the
+ // back-to-back refill after a perpetual completion reads its own app as
+ // on-cooldown and stalls — a manually-triggered perpetual task then runs
+ // once instead of continuing the drain. The bypass is implemented by
+ // CONSTRAINING the pick to perpetual when the app is on cooldown: the
+ // cooldown state is computed first and passed to getNextTaskType as
+ // `perpetualOnly`, so in a MIXED schedule a due higher-priority cron/custom
+ // type can't mask the perpetual drain (which would strand the whole app for
+ // the window). Pin: (a) the cooldown is resolved BEFORE getNextTaskType, and
+ // (b) getNextTaskType is asked for a perpetual-only pick gated on cooldown.
const cooldownIdx = fnBody.indexOf('isAppActivityOnCooldown(');
const nextTypeIdx = fnBody.indexOf('getNextTaskType(');
expect(
- nextTypeIdx,
- 'getNextTaskType must be resolved before the cooldown gate so perpetual picks can bypass it'
+ cooldownIdx,
+ 'queue path must compute cooldown via isAppActivityOnCooldown'
).toBeGreaterThan(-1);
expect(
- cooldownIdx > nextTypeIdx,
- 'the per-app cooldown gate must come AFTER getNextTaskType so it can bypass perpetual picks'
+ cooldownIdx < nextTypeIdx,
+ 'cooldown must be resolved BEFORE getNextTaskType so it can constrain the pick to perpetual'
).toBe(true);
expect(
fnBody,
- 'queue path must bypass the cooldown gate for perpetual-drain picks (reason === "perpetual-drain")'
- ).toMatch(/perpetual-drain/);
- expect(
- fnBody,
- 'the cooldown gate must be guarded so it only applies to non-perpetual picks'
- ).toMatch(/!\s*\w*[Pp]erpetual\w*\s*&&\s*isAppActivityOnCooldown\(/);
+ 'queue path must constrain the pick to perpetual when on cooldown (perpetualOnly gated on cooldown)'
+ ).toMatch(/getNextTaskType\([^)]*\{\s*perpetualOnly:\s*onCooldown\s*\}/);
});
it('generateManagedAppImprovementTaskForType defers updateAppActivity until after gates', () => {
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 5461b1cb57..e6b213dcf5 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -1063,35 +1063,35 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, { ignore
// "no activity yet."
const appActivity = activitySnapshot.apps?.[app.id];
- // Resolve the next eligible improvement type for this app BEFORE the
- // per-app cooldown gate — the picked type's interval decides whether the
- // cooldown even applies (see the perpetual bypass below). `getNextTaskType`
- // falls back to ROTATION when nothing is time-due, and the rotation
- // pointer is derived from the `lastType` argument — without it, the
- // rotation always restarts from index 0 and starves every other
- // rotation type for the app. Mirror `generateManagedAppTask` (the
- // legacy direct-spawn caller above) which threads the per-app
- // `lastImprovementType` in.
+ // Perpetual (drain-until-done) tasks BYPASS the per-app review cooldown:
+ // their work-detector park IS the throttle (taskSchedule.parkPerpetual), and
+ // agentCompletion.js already skips the post-completion cooldown bump for
+ // them. But the spawn-time `markAppReviewCooldown` stamp (written by BOTH the
+ // on-demand manual-trigger path and the idle-review loop) sets
+ // `lastReviewedAt`, which `isAppActivityOnCooldown` reads — so without a
+ // bypass the back-to-back refill fired right after a perpetual run reads its
+ // OWN app as "on cooldown" and skips the re-queue, and the drain stalls.
+ //
+ // When the app IS on cooldown, constrain the pick to a due perpetual task
+ // (`perpetualOnly`). This is what makes a MIXED schedule converge: if the app
+ // also has a due cron/custom type (e.g. pr-watcher), the unconstrained
+ // `getNextTaskType` would return that higher-priority NON-exempt type first,
+ // we'd see a non-perpetual pick, and we'd skip the whole app for the cooldown
+ // window — stranding the perpetual drain behind it. Asking perpetual-only
+ // returns the due perpetual drain (or null → leave the cooled-down app
+ // alone). When NOT on cooldown, the normal full-priority pick runs.
+ const onCooldown = isAppActivityOnCooldown(appActivity, state.config.appReviewCooldownMs);
+
+ // `getNextTaskType` falls back to ROTATION when nothing is time-due, and the
+ // rotation pointer is derived from `lastType` — without it the rotation
+ // always restarts from index 0 and starves every other rotation type for the
+ // app. Mirror `generateManagedAppTask` (the legacy direct-spawn caller) which
+ // threads the per-app `lastImprovementType` in.
const lastType = appActivity?.lastImprovementType || '';
- const nextTypeResult = await getNextTaskType(app.id, lastType).catch(() => null);
+ const nextTypeResult = await getNextTaskType(app.id, lastType, { perpetualOnly: onCooldown }).catch(() => null);
if (!nextTypeResult) continue;
const nextType = nextTypeResult.taskType;
- // Perpetual (drain-until-done) picks BYPASS the per-app review cooldown:
- // their work-detector park IS the throttle (taskSchedule.parkPerpetual),
- // and agentCompletion.js already skips the post-completion cooldown bump
- // for them. But the spawn-time `markAppReviewCooldown` stamp (written by
- // BOTH the on-demand manual-trigger path and the idle-review loop) sets
- // `lastReviewedAt`, which `isAppActivityOnCooldown` reads. Without this
- // bypass, the back-to-back refill fired right after a perpetual run reads
- // its OWN app as "on cooldown" (lastReviewedAt is minutes old, the window
- // is 30 min) and skips the re-queue — so a manually-triggered perpetual
- // task runs exactly once and stalls instead of continuing the drain. The
- // cooldown still gates non-perpetual rotation types. `getNextTaskType`
- // tags every perpetual pick with reason `perpetual-drain`.
- const isPerpetualDrain = nextTypeResult.reason === 'perpetual-drain';
- if (!isPerpetualDrain && isAppActivityOnCooldown(appActivity, state.config.appReviewCooldownMs)) continue;
-
const taskKey = `app:${app.id}:${nextType}`;
if (existingTaskTypes.has(taskKey)) {
emitLog('debug', `Improvement task ${nextType} for ${app.name} already queued`);
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 44eda70939..ac63179028 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -1034,12 +1034,27 @@ export async function getDueTasks(appId = null) {
/**
* Get the next task type to run (optionally for a specific app)
*/
-export async function getNextTaskType(appId = null, lastType = '') {
+export async function getNextTaskType(appId = null, lastType = '', { perpetualOnly = false } = {}) {
const schedule = await loadSchedule();
const taskTypes = Object.keys(schedule.tasks);
const dueTasks = await getDueTasks(appId);
+ // `perpetualOnly` constrains the pick to a due perpetual (drain-until-done)
+ // task, skipping every other schedule type. Callers set this when the app is
+ // on its review cooldown: only perpetual drains bypass that cooldown (their
+ // work-detector park is the throttle), so a higher-priority cron/custom/daily
+ // type that's also due must NOT be returned — it would mask the perpetual
+ // drain and the caller, seeing a non-exempt pick, would skip the whole app for
+ // the cooldown window (the mixed-schedule stall). Returns null when nothing
+ // perpetual is due, so the caller leaves the cooled-down app alone.
+ if (perpetualOnly) {
+ const perpetualDue = dueTasks.filter(t => t.interval.type === INTERVAL_TYPES.PERPETUAL);
+ return perpetualDue.length > 0
+ ? { taskType: perpetualDue[0].taskType, reason: 'perpetual-drain' }
+ : null;
+ }
+
// Explicit time-based schedules (cron, custom interval) outrank loose interval-based
// ones (daily/weekly/once). A user-pinned 9 AM cron should fire at 9 AM even if a
// weekly task is perpetually "ready" — the loose tasks will pick up the next slot.
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index c5f3637abc..8e9e4c82fb 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -866,6 +866,49 @@ describe('taskSchedule', () => {
expect(result.taskType).toBe('plan-task')
expect(result.reason).toBe('cron-due')
})
+
+ it('perpetualOnly returns the due perpetual task even when a higher-priority cron task is also due', async () => {
+ // The mixed-schedule stall: an app on review cooldown has BOTH a due cron
+ // task and a due perpetual drain. Unconstrained, getNextTaskType returns
+ // the cron task (cron outranks perpetual) — but on cooldown only the
+ // perpetual drain is eligible, so the caller passes perpetualOnly to get
+ // the drain instead of being stranded behind the cooled-down cron pick.
+ const todayNineAm = recentNineAm()
+ const tomorrowNineAm = new Date(todayNineAm.getTime() + 24 * 60 * 60 * 1000)
+ const yesterdayNineAm = new Date(todayNineAm.getTime() - 24 * 60 * 60 * 1000)
+ parseCronToPrevRun
+ .mockReturnValueOnce(todayNineAm)
+ .mockReturnValueOnce(yesterdayNineAm)
+ parseCronToNextRun.mockReturnValue(tomorrowNineAm)
+
+ mockSchedule({
+ tasks: {
+ 'pr-watcher': { type: 'cron', enabled: true, cronExpression: '0 9 * * *', providerId: null, model: null, prompt: null },
+ 'claim-issue': { type: 'perpetual', enabled: true, providerId: null, model: null, prompt: null }
+ }
+ })
+
+ // Unconstrained: cron wins.
+ const unconstrained = await getNextTaskType()
+ expect(unconstrained.taskType).toBe('pr-watcher')
+
+ // perpetualOnly: the perpetual drain is returned instead.
+ const constrained = await getNextTaskType(null, '', { perpetualOnly: true })
+ expect(constrained).not.toBeNull()
+ expect(constrained.taskType).toBe('claim-issue')
+ expect(constrained.reason).toBe('perpetual-drain')
+ })
+
+ it('perpetualOnly returns null when no perpetual task is due (app stays throttled)', async () => {
+ mockSchedule({
+ tasks: {
+ 'code-quality': { type: 'rotation', enabled: true, providerId: null, model: null, prompt: null },
+ 'error-handling': { type: 'rotation', enabled: true, providerId: null, model: null, prompt: null }
+ }
+ })
+ const result = await getNextTaskType(null, '', { perpetualOnly: true })
+ expect(result).toBeNull()
+ })
})
describe('templates', () => {