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): gate perpetual refill on success + sequence before dequeue

Adam Eivy48ed83d1325f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index fcd64913ab..a02a79ddcf 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -8,7 +8,7 @@
- **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`)
+- **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 **successfully** (a failed run is left to task-retry/backoff and the recheck cadence, so the daemon can't spin through back-to-back failures), sequenced *before* the generic dequeue so the next perpetual task is on the queue before any freed slot is filled, and 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`)
diff --git a/server/services/cos.js b/server/services/cos.js
index d08971dc9d..30e45580fd 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -969,6 +969,14 @@ export function isPerpetualRefillCandidate(agent, schedule) {
*/
async function refillPerpetualForCompletedAgent(agent) {
if (!isDaemonRunning()) return;
+ // Only a SUCCESSFUL perpetual run drains to the next item immediately. A failed
+ // run (provider/setup/test failure) must NOT refill back-to-back: perpetual
+ // completions skip the per-app cooldown, and the work-detector will usually
+ // still see the same issue as actionable — so an immediate refill would spin
+ // the daemon through repeated failures. On failure, fall back to the task
+ // retry/backoff and the improvement-check recheck cadence (the park IS the
+ // throttle only once work genuinely runs out, not when a run errors).
+ if (!agent?.result?.success) return;
if (await isPaused()) return;
const taskScheduleMod = await import('./taskSchedule.js');
@@ -992,7 +1000,10 @@ async function refillPerpetualForCompletedAgent(agent) {
? { ...cosTaskData, tasks: (cosTaskData.tasks || []).filter(t => t.id !== completedTaskId) }
: cosTaskData;
await queueEligibleImprovementTasks(state, refillTaskData);
- setImmediate(() => dequeueNextTask());
+ // NOTE: the caller (the agent:completed handler) runs dequeueNextTask AFTER
+ // this resolves, so the freshly-queued perpetual task is on the queue before
+ // slots are filled. Do not dequeue here — that would re-introduce the ordering
+ // race where generic dequeue claims the freed slot with idle/mission work.
}
/**
@@ -1002,19 +1013,22 @@ async function refillPerpetualForCompletedAgent(agent) {
export async function init() {
await ensureDirectories();
- // When an agent completes, immediately try to dequeue the next pending task
+ // When an agent completes, refill perpetual work then dequeue the next task
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.
+ // Refill the perpetual backlog FIRST, THEN dequeue — in one async task so the
+ // generic dequeue can't fill the just-freed slot with idle/mission work ahead
+ // of the perpetual re-queue. 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 only spawns ALREADY-queued
+ // work, so on its own a perpetual backlog stalls between ticks). The refill
+ // early-returns fast for non-perpetual or failed completions, so for those
+ // this stays a thin wrapper around the dequeue. Both steps are .catch-guarded
+ // because this runs outside the request lifecycle.
setImmediate(() => {
- refillPerpetualForCompletedAgent(agent).catch(err =>
- console.error(`❌ Perpetual refill after ${agent?.id} failed: ${err.message}`)
- );
+ refillPerpetualForCompletedAgent(agent)
+ .catch(err => console.error(`❌ Perpetual refill after ${agent?.id} failed: ${err.message}`))
+ .then(() => dequeueNextTask())
+ .catch(err => console.error(`❌ Dequeue after ${agent?.id} completion failed: ${err.message}`));
});
// Create notification when a daily briefing completes
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index 4fb304a8c6..3f36118cf1 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -1145,6 +1145,37 @@ describe('cos.js source — agent:completed triggers perpetual refill', () => {
'refill must pass the filtered refillTaskData to queueEligibleImprovementTasks'
).toBe(true);
});
+
+ it('the refill only fires on a SUCCESSFUL completion (no back-to-back spin on failures)', () => {
+ // Perpetual completions skip the per-app cooldown, so refilling after a failed
+ // run would spin the daemon through repeated failures (the work-detector still
+ // sees the same issue as actionable). The refill must bail on a non-success
+ // result and let task-retry/backoff + the recheck cadence handle failures.
+ const fnIdx = COS_SRC.indexOf('async function refillPerpetualForCompletedAgent');
+ const fnSlice = COS_SRC.slice(fnIdx, fnIdx + 2500);
+ expect(
+ /if\s*\(\s*!agent\?\.result\?\.success\s*\)\s*return/.test(fnSlice),
+ 'refill must early-return when the completed agent did not succeed'
+ ).toBe(true);
+ });
+
+ it('refill is sequenced BEFORE dequeue in the handler (perpetual task queued before slots fill)', () => {
+ // If generic dequeue ran first (or concurrently), it could claim the just-
+ // freed slot with idle/mission work before the perpetual task is queued,
+ // breaking the back-to-back drain. The handler must chain refill → dequeue.
+ const onIdx = COS_SRC.indexOf("cosEvents.on('agent:completed'");
+ const handlerSlice = COS_SRC.slice(onIdx, onIdx + 1400);
+ expect(
+ /refillPerpetualForCompletedAgent\(agent\)[\s\S]*\.then\(\s*\(\)\s*=>\s*dequeueNextTask\(\)\s*\)/.test(handlerSlice),
+ 'handler must run dequeueNextTask in a .then() AFTER the refill resolves'
+ ).toBe(true);
+ // The old standalone `setImmediate(() => dequeueNextTask())` must be gone —
+ // its presence would race the refill.
+ expect(
+ handlerSlice.includes('setImmediate(() => dequeueNextTask())'),
+ 'the unconditional pre-refill dequeue must be removed'
+ ).toBe(false);
+ });
});
// Shared autonomous-queuing gate (cosState.canQueueImprovementTasks). Extracted