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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix(cos): drain perpetual schedules back-to-back on agent completion
Adam Eivyebb18ef1a3c2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 9196740304..fcd64913ab 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,6 +8,8 @@- **New `perpetual` (drain-until-done) schedule mode: a task runs back-to-back until there's nothing left to do, then parks and rechecks on a cadence.** Most scheduled tasks fire on a timer (daily, weekly, cron). The new **Perpetual** interval type instead keeps re-queuing a task the moment the previous run finishes — for as long as a *programmatic* pre-run check (no LLM) reports there's still actionable work — and when the work runs out it PARKS itself and only re-probes on a configurable recheck cadence (a cron expression or interval, default daily). The motivating use is `claim-issue`/`claim-work`: set it to Perpetual and PortOS will claim and ship open GitHub issues one after another until the backlog of *claimable* issues is empty, then stop and recheck tomorrow — no wasted agent runs spinning on an empty queue. The pre-run check mirrors the claim prompt's own skip-list exactly (it excludes assigned issues, epics, in-flight `claim/issue-<num>` branches, and issues labeled `in-progress`/`blocked`/`needs-input`/`future`/`wontfix`/`question`/`discussion`), so the drain converges to the same empty state the agent would reach. To make it converge instead of re-picking an un-actionable issue forever, the `claim-issue` **and** `claim-issue-gitlab` agent prompts now **tag an ambiguous or too-large issue `needs-input`** (and comment what decision a human must make) before releasing it — that label is what the pre-run check uses to permanently exclude it. The detector is a pluggable registry (`server/services/perpetualWork.js`) shipping **GitHub-issue, GitLab-issue, and PLAN.md** detectors (the GitLab one mirrors the GitHub flow over `glab` — normalizing `iid`→number, reading MR source branches for the in-flight scan, and resolving the owner filter from the project namespace); a perpetual task whose tracker has no detector (e.g. JIRA) parks rather than draining blindly. Perpetual runs also skip the per-app review cooldown so the drain isn't throttled to one item per 30 minutes — the park is the throttle. Works for GitHub, GitLab, and PLAN.md-tracked apps (and the `claim-work` router, which resolves to the right detector per app). Configure it in **CoS → Schedule → Configure → Interval Type → Perpetual**. (`server/services/taskSchedule.js`, `server/services/perpetualWork.js`, `server/services/cosTaskGenerator.js`, `server/services/agentCompletion.js`, `server/routes/cosScheduleRoutes.js`, `server/services/taskPromptDefaults/`, `client/src/components/cos/tabs/schedule/`)+- **Perpetual schedules now actually drain back-to-back — the next run fires the moment the previous one finishes, instead of stalling until the next hourly check.** The `perpetual` mode promised "re-queue on completion," and the cooldown-skip that supports it was wired, but the completion *trigger* itself was missing: when a perpetual agent (e.g. `claim-issue`) finished, the `agent:completed` handler only ran `dequeueNextTask`, which drains *already-queued* work and never regenerates perpetual tasks. The only thing that re-queued them was the `cos-improvement-check` timer — and a "ready" (unparked) perpetual task doesn't even shorten that timer (its delay is gated on `status:'scheduled'` tasks only), so when a perpetual task was the only enabled schedule the next run waited up to a full hour (`MAX_CHECK_INTERVAL`) despite open, actionable work. The `agent:completed` handler now refills the perpetual queue immediately after a perpetual-schedule agent completes (gated identically to the timer: daemon running, not paused, idle-review on, CoS auto-run = `execute`), reusing `queueEligibleImprovementTasks` so per-app cooldown, the one-pending-per-app cap, the concurrency limits, and the work-detector park all still apply — i.e. it converges to the same empty/parked state, just without the up-to-an-hour gap between items. (`server/services/cos.js`, `server/services/cosState.js`, `server/services/cosJobScheduler.js`)+- **Feature Agents moved from Dev Tools to the Chief of Staff section.** The Feature Agents page (`/feature-agents`) now lives under the Chief of Staff sidebar group alongside the other agent-management pages, rather than buried in Dev Tools. The route is unchanged — only the sidebar grouping and the ⌘K / voice nav section label moved. (`client/src/components/Layout.jsx`, `server/lib/navManifest.js`)- **The CoS → Schedule page is now a scannable card grid instead of a flat expandable list.** Each task type renders as a status card you can read at a glance — a colored status dot (active / on-demand / waiting-on-deps / disabled), a **next-run countdown** ("in 3h", "Mon 9:00") that was previously computed server-side but never shown, an app-coverage bar with the enabled/total count kept front-and-center, and last-run/run-count. Cards sort by status then soonest next run (so what's about to run rises to the top), the All/Enabled toggle is replaced by per-status filters (Active / On-Demand / Waiting / Disabled), and a name filter box jumps to a task quickly. A **Run** button sits on each card — for app-targeting tasks it opens an app picker so the on-demand run carries app context (just like the old per-task controls), and falls back to a plain global run for tasks with no managed apps; **Configure** opens a slide-over drawer with the full per-task settings (interval, provider/model, prompt, agent options, dependencies, pipeline stages, and per-app overrides) — the same controls as before, now in a focused panel that's deep-linkable via `?task=` and closes on Esc/backdrop. Mobile collapses the grid to a single column.diff --git a/server/services/cos.js b/server/services/cos.jsindex ee78b17d53..9c8a2e45a6 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -32,7 +32,7 @@ import { normalizeDomainBudgets, remainingActionBudget } from '../lib/domainBudgimport { getDomainBudgetStatus } from './domainUsage.js';// Shared state management (extracted to avoid circular deps)-import { loadState, saveState, withStateLock, ensureDirectories, isImprovementEnabled, AGENTS_DIR, REPORTS_DIR, SCRIPTS_DIR, ROOT_DIR, isDaemonRunning, setDaemonRunning } from './cosState.js';+import { loadState, saveState, withStateLock, ensureDirectories, isImprovementEnabled, canQueueImprovementTasks, AGENTS_DIR, REPORTS_DIR, SCRIPTS_DIR, ROOT_DIR, isDaemonRunning, setDaemonRunning } from './cosState.js';// Events and logging (canonical source: cosEvents.js)import { cosEvents, emitLog } from './cosEvents.js';@@ -357,9 +357,8 @@ export async function start() {if (!isDaemonRunning()) return;loadState().then(async (state) => {// Gate on the CoS auto-run domain (parity with evaluateTasks and the- // cos-improvement-check timer): queueing improvement tasks mutates- // COS-TASKS.md with autonomous internal work, so off/dry-run must not queue.- if (!state.config.idleReviewEnabled || getDomainMode(state.config, 'cos') !== 'execute') return;+ // cos-improvement-check timer) — see canQueueImprovementTasks.+ if (!canQueueImprovementTasks(state)) return;const cosTaskData = await getCosTasks();await queueEligibleImprovementTasks(state, cosTaskData);setImmediate(() => dequeueNextTask());@@ -935,6 +934,55 @@ async function dequeueNextTask() {}}+/**+ * Pure gate: did the just-completed agent belong to an *enabled perpetual*+ * schedule (e.g. claim-issue)? Perpetual tasks are documented as "drain+ * actionable work back-to-back (re-queue on completion)" (taskSchedule.js), but+ * `dequeueNextTask` above only drains already-queued tasks — it never+ * regenerates perpetual work. Without an explicit refill on completion the next+ * run waits for the ~hourly `cos-improvement-check` timer (a "ready" perpetual+ * task doesn't even shorten that timer — cosJobScheduler gates the delay on+ * `status:'scheduled'` tasks only). This gate lets the completion handler decide+ * whether to refill the perpetual queue immediately instead of idling. Reads+ * the analysis type the same way `queueEligibleImprovementTasks` /+ * `isDisabledAnalysisType` do, and never throws on partial inputs.+ */+export function isPerpetualRefillCandidate(agent, schedule) {+ const analysisType = agent?.metadata?.taskAnalysisType+ || agent?.metadata?.analysisType+ || agent?.metadata?.selfImprovementType;+ if (!analysisType) return false;+ const taskDef = schedule?.tasks?.[analysisType];+ return Boolean(taskDef?.enabled) && taskDef.type === 'perpetual';+}++/**+ * When a perpetual-schedule agent finishes, re-queue the next eligible+ * improvement task right away so the backlog drains back-to-back rather than+ * stalling until the next improvement-check tick. Mirrors the gates the+ * improvement-check timer applies (daemon running, not paused, idle-review on,+ * CoS auto-run = execute) and reuses the same `queueEligibleImprovementTasks`+ * path — which already enforces per-app cooldown, the one-pending-per-app cap,+ * and the perpetual work-detector park, so this converges (when no actionable+ * work remains the task parks and nothing is re-queued) and can't fan out past+ * the concurrency limits in `dequeueNextTask`.+ */+async function refillPerpetualForCompletedAgent(agent) {+ if (!isDaemonRunning()) return;+ if (await isPaused()) return;++ const taskScheduleMod = await import('./taskSchedule.js');+ const schedule = await taskScheduleMod.loadSchedule();+ if (!isPerpetualRefillCandidate(agent, schedule)) return;++ const state = await loadState();+ if (!canQueueImprovementTasks(state)) return;++ const cosTaskData = await getCosTasks();+ await queueEligibleImprovementTasks(state, cosTaskData);+ setImmediate(() => dequeueNextTask());+}+/*** Wire event listeners, load state, and auto-start the daemon when configured.* Called once from `server/index.js` during boot.@@ -946,6 +994,17 @@ export async function init() {cosEvents.on('agent:completed', (agent) => {setImmediate(() => dequeueNextTask());+ // Perpetual schedules (e.g. claim-issue) drain back-to-back: regenerate the+ // next eligible task now instead of waiting for the ~hourly improvement+ // check. dequeueNextTask above only spawns ALREADY-queued work, so without+ // this a perpetual backlog stalls between ticks (issue: claim-issue not+ // re-queuing after each run). Guarded + gated inside the helper.+ setImmediate(() => {+ refillPerpetualForCompletedAgent(agent).catch(err =>+ console.error(`❌ Perpetual refill after ${agent?.id} failed: ${err.message}`)+ );+ });+// Create notification when a daily briefing completesif (agent?.metadata?.jobId === 'job-daily-briefing' && agent?.result?.success) {getUserTimezone()diff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex 44229c1a25..d9080c6764 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -32,7 +32,8 @@ import { describe, it, expect } from 'vitest';import { readFileSync } from 'fs';import { fileURLToPath } from 'url';import { dirname, join } from 'path';-import { firstLine } from './cos.js';+import { firstLine, isPerpetualRefillCandidate } from './cos.js';+import { canQueueImprovementTasks } from './cosState.js';const __dirname = dirname(fileURLToPath(import.meta.url));const COS_SRC = readFileSync(join(__dirname, 'cos.js'), 'utf-8');@@ -773,9 +774,11 @@ describe('cos.js source — priority + capacity invariants', () => {const reregIdx = skipBranch.indexOf('registerSingleJobSchedule');expect(recordIdx, 'autonomy-skip must call recordJobGateSkip').toBeGreaterThan(-1);expect(recordIdx, 'recordJobGateSkip must precede re-registration (no 1s refire loop)').toBeLessThan(reregIdx);- // The improvement-check timer must gate its queueEligibleImprovementTasks call.- expect(SCHED_SRC, 'improvement-check timer must gate queueing on cos === execute')- .toMatch(/idleReviewEnabled\s*&&\s*getDomainMode\(\s*state\.config\s*,\s*['"]cos['"]\s*\)\s*===\s*['"]execute['"]/);+ // The improvement-check timer must gate its queueEligibleImprovementTasks+ // call on the shared canQueueImprovementTasks predicate (idle-review ++ // cos===execute), which encapsulates the auto-run domain gate.+ expect(SCHED_SRC, 'improvement-check timer must gate queueing via canQueueImprovementTasks')+ .toMatch(/if\s*\(\s*canQueueImprovementTasks\(\s*state\s*\)\s*\)/);});it('both on-demand loops dedupe the cooldown stamp per app via reviewStartedApps set', () => {@@ -1052,3 +1055,100 @@ describe('addTask — first-line dedup', () => {// cosTaskStore.js. The firstLine behavioral tests above stay here because// cos.js still re-exports firstLine for backward compat.});++// ─── Perpetual re-queue on completion (drain back-to-back) ─────────────────+//+// Perpetual schedules (e.g. claim-issue) are documented as "drain actionable+// work back-to-back (re-queue on completion)" (taskSchedule.js), but the only+// thing that queues them is the ~hourly cos-improvement-check timer — the+// agent:completed handler (dequeueNextTask) merely drains already-queued tasks+// and never regenerates perpetual work. A "ready" perpetual task doesn't even+// shorten that timer (cosJobScheduler only gates the delay on status:'scheduled'+// tasks), so when claim-issue is the only enabled schedule the next run waits up+// to MAX_CHECK_INTERVAL (1h) instead of spawning immediately after the prior one.+//+// `isPerpetualRefillCandidate` is the pure gate that lets the completion handler+// decide whether the just-finished agent belongs to a perpetual schedule that+// should be refilled right now.+describe('isPerpetualRefillCandidate — perpetual drain on completion', () => {+ const schedule = {+ tasks: {+ 'claim-issue': { type: 'perpetual', enabled: true },+ 'claim-issue-disabled': { type: 'perpetual', enabled: false },+ 'plan-task': { type: 'daily', enabled: true },+ },+ };+ const agentFor = (analysisType, key = 'taskAnalysisType') => ({+ metadata: analysisType == null ? {} : { [key]: analysisType },+ });++ it('is true for an enabled perpetual type matching the agent task', () => {+ expect(isPerpetualRefillCandidate(agentFor('claim-issue'), schedule)).toBe(true);+ });++ it('is false for a disabled perpetual type (toggled off after spawn)', () => {+ expect(isPerpetualRefillCandidate(agentFor('claim-issue-disabled'), schedule)).toBe(false);+ });++ it('is false for a non-perpetual schedule type', () => {+ expect(isPerpetualRefillCandidate(agentFor('plan-task'), schedule)).toBe(false);+ });++ it('is false for an unknown / unscheduled type', () => {+ expect(isPerpetualRefillCandidate(agentFor('ghost-type'), schedule)).toBe(false);+ });++ it('reads the analysis type from metadata.analysisType and selfImprovementType fallbacks', () => {+ expect(isPerpetualRefillCandidate(agentFor('claim-issue', 'analysisType'), schedule)).toBe(true);+ expect(isPerpetualRefillCandidate(agentFor('claim-issue', 'selfImprovementType'), schedule)).toBe(true);+ });++ it('is false for missing agent / metadata / schedule (no throw)', () => {+ expect(isPerpetualRefillCandidate(null, schedule)).toBe(false);+ expect(isPerpetualRefillCandidate(agentFor(null), schedule)).toBe(false);+ expect(isPerpetualRefillCandidate(agentFor('claim-issue'), null)).toBe(false);+ expect(isPerpetualRefillCandidate(agentFor('claim-issue'), { tasks: null })).toBe(false);+ });+});++// Source-level guard: the agent:completed handler must wire the perpetual+// refill so completion drains back-to-back instead of waiting for the hourly+// improvement-check timer.+describe('cos.js source — agent:completed triggers perpetual refill', () => {+ it("the agent:completed listener invokes the perpetual refill path", () => {+ const onIdx = COS_SRC.indexOf("cosEvents.on('agent:completed'");+ expect(onIdx, 'agent:completed listener must exist').toBeGreaterThan(-1);+ const handlerSlice = COS_SRC.slice(onIdx, onIdx + 1200);+ expect(+ handlerSlice.includes('refillPerpetualForCompletedAgent'),+ 'agent:completed handler must call refillPerpetualForCompletedAgent'+ ).toBe(true);+ });+});++// Shared autonomous-queuing gate (cosState.canQueueImprovementTasks). Extracted+// from three drift-prone copies (post-startup queue, improvement-check timer,+// perpetual drain refill). Queuing requires BOTH idle-review on AND the CoS+// auto-run domain in `execute`.+describe('canQueueImprovementTasks — autonomous queuing gate', () => {+ const cfg = (idleReviewEnabled, cos) => ({+ config: { idleReviewEnabled, domainAutonomy: { cos } },+ });++ it('is true only when idle-review is on AND cos auto-run is execute', () => {+ expect(canQueueImprovementTasks(cfg(true, 'execute'))).toBe(true);+ });++ it('is false when cos auto-run is off or dry-run', () => {+ expect(canQueueImprovementTasks(cfg(true, 'off'))).toBe(false);+ expect(canQueueImprovementTasks(cfg(true, 'dry-run'))).toBe(false);+ });++ it('is false when idle-review is disabled, regardless of cos mode', () => {+ expect(canQueueImprovementTasks(cfg(false, 'execute'))).toBe(false);+ });++ it('coerces a falsy/undefined idleReviewEnabled to a boolean false', () => {+ expect(canQueueImprovementTasks(cfg(undefined, 'execute'))).toBe(false);+ });+});diff --git a/server/services/cosJobScheduler.js b/server/services/cosJobScheduler.jsindex 3b8badd093..bd8b25265b 100644--- a/server/services/cosJobScheduler.js+++ b/server/services/cosJobScheduler.js@@ -24,7 +24,7 @@import { schedule as scheduleEvent, cancel as cancelEvent, parseCronToNextRun } from './eventScheduler.js';import { getUserTimezone, getLocalParts, nextLocalTime } from '../lib/timezone.js';import { formatDuration } from '../lib/fileUtils.js';-import { loadState, isDaemonRunning } from './cosState.js';+import { loadState, isDaemonRunning, canQueueImprovementTasks } from './cosState.js';import { getDomainMode } from '../lib/domainAutonomy.js';import { remainingActionBudget } from '../lib/domainBudgets.js';import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';@@ -459,11 +459,9 @@ export async function scheduleNextImprovementCheck() {if (paused) return;const state = await loadState();- // Gate on the CoS auto-run domain: queueing improvement tasks mutates- // COS-TASKS.md with autonomous internal work, so off/dry-run must not- // queue (dry-run is purely a planning posture; the spawn-side gate- // already withholds execution, but we also avoid the queue mutation).- if (state.config.idleReviewEnabled && getDomainMode(state.config, 'cos') === 'execute') {+ // Gate on the CoS auto-run domain (see canQueueImprovementTasks): off/+ // dry-run are planning postures that withhold the COS-TASKS.md mutation.+ if (canQueueImprovementTasks(state)) {const cosTaskData = await getCosTasks();await queueEligibleImprovementTasks(state, cosTaskData);cosEvents.emit('cos:dequeue-requested');diff --git a/server/services/cosState.js b/server/services/cosState.jsindex 65688125ac..e8a498a387 100644--- a/server/services/cosState.js+++ b/server/services/cosState.js@@ -128,6 +128,16 @@ export function isImprovementEnabled(state) {(state.config.selfImprovementEnabled || state.config.appImprovementEnabled);}+// Autonomous improvement-task QUEUING gate. Queuing mutates COS-TASKS.md with+// autonomous internal work, so it requires BOTH the idle-review flag AND the CoS+// auto-run domain in `execute` (off/dry-run are planning postures that withhold+// the queue mutation). Shared by the post-startup queue, the+// cos-improvement-check timer, and the perpetual drain-on-completion refill so+// the three gates can't drift apart.+export function canQueueImprovementTasks(state) {+ return Boolean(state.config.idleReviewEnabled) && getDomainMode(state.config, 'cos') === 'execute';+}+export async function loadState() {if (stateCache) return stateCache;