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 r3): thread ignoreTaskId so refill survives addTask dedup

Adam Eivy383110bb719a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a02a79ddcf..c625478b24 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 **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`)
+- **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. The completing task is still `in_progress` on disk when the refill runs (the event fires before its status is persisted), so its id is threaded through as `ignoreTaskId` to keep the duplicate scan from rejecting the identical-first-line re-queue. (`server/services/cos.js`, `server/services/cosState.js`, `server/services/cosJobScheduler.js`, `server/services/cosTaskGenerator.js`, `server/services/cosTaskStore.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 30e45580fd..91d9c95e8e 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -989,17 +989,14 @@ async function refillPerpetualForCompletedAgent(agent) {
// `agent:completed` fires from `completeAgent` BEFORE the completion flow's
// `updateTask` marks this agent's task done (agentLifecycle.js: completeAgent
// emits, THEN updateTask persists). So the just-finished task can still read as
- // `in_progress` here — and `queueEligibleImprovementTasks` caps each app at one
- // pending improvement, so it would treat this app as still-busy and skip the
- // re-queue, defeating the back-to-back drain. Drop the completed task from the
- // snapshot we hand it so eligibility is computed as if the task is already
- // done; this is correct regardless of whether updateTask has landed yet.
+ // `in_progress` both in this snapshot AND on disk when queueEligible's addTask
+ // re-reads COS-TASKS.md. Pass its id as `ignoreTaskId` so the per-app busy cap,
+ // the per-type dedup set, and addTask's disk-level duplicate scan all treat it
+ // as already done — otherwise a perpetual schedule (claim-issue/claim-work
+ // regenerates an identical first-line per app) is rejected as a duplicate of
+ // the completing task and the drain stalls until the next scheduler tick.
const cosTaskData = await getCosTasks();
- const completedTaskId = agent?.taskId;
- const refillTaskData = completedTaskId
- ? { ...cosTaskData, tasks: (cosTaskData.tasks || []).filter(t => t.id !== completedTaskId) }
- : cosTaskData;
- await queueEligibleImprovementTasks(state, refillTaskData);
+ await queueEligibleImprovementTasks(state, cosTaskData, { ignoreTaskId: agent?.taskId });
// 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
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index 3f36118cf1..dd524c4fa2 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -486,7 +486,20 @@ describe('dequeueNextTask — capacity guards', () => {
* will fail loudly rather than silently miss matches.
*/
function extractFnBody(src, fnStart) {
- const openIdx = src.indexOf('{', fnStart);
+ // Skip the parameter list before locating the body brace: a destructured /
+ // defaulted param (e.g. `(state, data, { x = null } = {})`) contains `{`
+ // braces, so the body `{` is the first one AFTER the signature's closing `)`,
+ // not the first `{` after fnStart. Paren-match the signature first.
+ const parenIdx = src.indexOf('(', fnStart);
+ let searchFrom = fnStart;
+ if (parenIdx !== -1) {
+ let pdepth = 0;
+ for (let j = parenIdx; j < src.length; j++) {
+ if (src[j] === '(') pdepth++;
+ else if (src[j] === ')') { pdepth--; if (pdepth === 0) { searchFrom = j + 1; break; } }
+ }
+ }
+ const openIdx = src.indexOf('{', searchFrom);
if (openIdx === -1) return '';
let depth = 0;
let i = openIdx;
@@ -854,11 +867,13 @@ describe('cos.js source — priority + capacity invariants', () => {
// Match the call shape, not the specific variable name — `task` could
// legitimately be renamed (e.g. `queuedTask`) in a behavior-preserving
// refactor. The contract being pinned is "raw:true addTask call to the
- // internal lane," not the identifier.
+ // internal lane," not the identifier. The options object may carry siblings
+ // beyond `raw:true` (e.g. `ignoreTaskId` for the perpetual refill), so don't
+ // require `}` immediately after `raw: true`.
expect(
fnBody,
'queue path must persist via addTask with raw:true so the enriched task object survives serialization'
- ).toMatch(/addTask\s*\(\s*\w+\s*,\s*['"]internal['"]\s*,\s*\{\s*raw:\s*true\s*\}/);
+ ).toMatch(/addTask\s*\(\s*\w+\s*,\s*['"]internal['"]\s*,\s*\{\s*raw:\s*true\b/);
// The old buggy path called `getTaskDescription` to build a one-line
// description and then passed app/context/approvalRequired fields to
@@ -1125,24 +1140,19 @@ describe('cos.js source — agent:completed triggers perpetual refill', () => {
).toBe(true);
});
- it('the refill excludes the just-completed task from the queueEligible snapshot (avoids the completeAgent-before-updateTask race)', () => {
- // agent:completed fires before the completion flow's updateTask marks the
- // task done, so the just-finished task can still read as in_progress. If the
- // refill handed the raw cosTaskData to queueEligibleImprovementTasks, its
- // one-pending-per-app cap would skip the app and the drain would stall —
- // exactly the bug this whole change fixes. Pin the filter so a refactor
- // can't silently reintroduce the race.
+ it('the refill passes the completed task id as ignoreTaskId (avoids the completeAgent-before-updateTask dedup race)', () => {
+ // agent:completed fires before the completion flow's updateTask marks the task
+ // done, so the just-finished task can still read as in_progress — both in the
+ // snapshot AND on disk when queueEligible's addTask re-reads COS-TASKS.md. A
+ // perpetual schedule regenerates an identical first-line per app, so without
+ // excluding the completing task the refill is rejected as a duplicate and the
+ // drain stalls. Pin the ignoreTaskId thread so a refactor can't reintroduce it.
const fnIdx = COS_SRC.indexOf('async function refillPerpetualForCompletedAgent');
expect(fnIdx, 'refillPerpetualForCompletedAgent must exist').toBeGreaterThan(-1);
const fnSlice = COS_SRC.slice(fnIdx, fnIdx + 2500);
expect(
- /filter\(\s*t\s*=>\s*t\.id\s*!==\s*completedTaskId\s*\)/.test(fnSlice),
- 'refill must drop the completed task (agent.taskId) before queueEligibleImprovementTasks'
- ).toBe(true);
- // And the filtered snapshot — not the raw one — must be what is passed in.
- expect(
- /queueEligibleImprovementTasks\(\s*state\s*,\s*refillTaskData\s*\)/.test(fnSlice),
- 'refill must pass the filtered refillTaskData to queueEligibleImprovementTasks'
+ /queueEligibleImprovementTasks\(\s*state\s*,\s*cosTaskData\s*,\s*\{\s*ignoreTaskId:\s*agent\?\.taskId\s*\}\s*\)/.test(fnSlice),
+ 'refill must forward { ignoreTaskId: agent?.taskId } to queueEligibleImprovementTasks'
).toBe(true);
});
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 8494b9c37d..a46a716544 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -962,13 +962,19 @@ export async function generateIdleReviewTask(state) {
* Called during every evaluation to ensure system tasks are queued even when user tasks exist
* Tasks are queued to COS-TASKS.md and will be picked up in Priority 2
*/
-export async function queueEligibleImprovementTasks(state, cosTaskData) {
+export async function queueEligibleImprovementTasks(state, cosTaskData, { ignoreTaskId = null } = {}) {
const { getNextTaskType, recordExecution } = await import('./taskSchedule.js');
if (!isImprovementEnabled(state)) return;
// Get existing pending/in_progress system tasks to avoid duplicates
// Also skip task types where a user-terminated blocked task exists (user intentionally killed it)
+ // `ignoreTaskId` excludes one task from both the per-app "already busy" cap and
+ // the per-type dedup set — used by the perpetual drain-on-completion refill,
+ // where the just-completed task is still `in_progress` on disk (agent:completed
+ // fires before updateTask finalizes it). Without it the completing task would
+ // make its own app look busy and block the next perpetual run. The same id is
+ // forwarded to addTask below so its disk-level duplicate scan ignores it too.
const existingTasks = cosTaskData.tasks || [];
const existingTaskTypes = new Set();
// Apps that already have *any* pending/in_progress improvement task. We cap each
@@ -977,6 +983,7 @@ export async function queueEligibleImprovementTasks(state, cosTaskData) {
const appsWithPendingImprovement = new Set();
for (const task of existingTasks) {
+ if (task.id === ignoreTaskId) continue;
const isActive = task.status === 'pending' || task.status === 'in_progress';
const isUserTerminated = task.status === 'blocked' && task.metadata?.blockedCategory === 'user-terminated';
if (isActive || isUserTerminated) {
@@ -1085,7 +1092,7 @@ export async function queueEligibleImprovementTasks(state, cosTaskData) {
task.description = firstLine(task.description);
}
- const newTask = await addTask(task, 'internal', { raw: true });
+ const newTask = await addTask(task, 'internal', { raw: true, ignoreTaskId });
if (newTask?.duplicate) continue;
await recordExecution(`task:${nextType}`, app.id);
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 342a2511d1..735700cc97 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -113,7 +113,7 @@ export async function getTaskById(taskId) {
* submitted task starts instantly instead of waiting for the next evaluation
* interval.
*/
-export async function addTask(taskData, taskType = 'user', { raw = false } = {}) {
+export async function addTask(taskData, taskType = 'user', { raw = false, ignoreTaskId = null } = {}) {
return withStateLock(async () => {
const state = await loadState();
const filePath = taskType === 'user'
@@ -132,9 +132,20 @@ export async function addTask(taskData, taskType = 'user', { raw = false } = {})
// description against two different apps is two different pieces of work
// (e.g. "fix the failing test" in PortOS vs in BookLoom), and collapsing
// them silently drops the second dispatch.
+ //
+ // `ignoreTaskId` excludes one specific task from the dedup scan. The perpetual
+ // drain-on-completion refill needs this: `agent:completed` fires from
+ // completeAgent BEFORE the completion flow's updateTask marks the just-finished
+ // task done, so that task is still `in_progress` on disk here. A perpetual
+ // schedule (claim-issue/claim-work) regenerates an identical first-line for the
+ // same app, so without excluding the completing task the refill is rejected as a
+ // duplicate of it and the back-to-back drain stalls until the next scheduler
+ // tick. The completing task is about to become `completed`, so ignoring it is
+ // correct, not a dedup hole.
const normalizedDesc = firstLine(taskData.description).toLowerCase();
const targetApp = taskData.app || null;
const duplicate = tasks.find(t =>
+ t.id !== ignoreTaskId &&
(t.status === 'pending' || t.status === 'in_progress') &&
firstLine(t.description).toLowerCase() === normalizedDesc &&
(t.metadata?.app || null) === targetApp
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index 0255360d26..804052d642 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -176,6 +176,21 @@ describe('cosTaskStore.addTask', () => {
expect(tasks).toHaveLength(2);
});
+ it('ignoreTaskId excludes one in-flight task from the dedup scan (perpetual drain-on-completion)', async () => {
+ // The just-completed perpetual task is still in_progress on disk when the
+ // refill re-queues an identical first-line for the same app. Passing its id
+ // as ignoreTaskId must let the new task through instead of colliding with it.
+ const first = await addTask({ description: 'claim issue', app: 'portos', id: 'sys-old' }, 'internal');
+ // Without ignoreTaskId the identical task collides...
+ const blocked = await addTask({ description: 'claim issue', app: 'portos' }, 'internal');
+ expect(blocked.duplicate).toBe(true);
+ // ...but excluding the still-in-flight task lets the refill queue the next one.
+ const allowed = await addTask({ description: 'claim issue', app: 'portos' }, 'internal', { raw: false, ignoreTaskId: first.id });
+ expect(allowed.duplicate).toBeUndefined();
+ const { tasks } = await getCosTasks();
+ expect(tasks.filter(t => firstLine(t.description) === 'claim issue')).toHaveLength(2);
+ });
+
it('persists boolean override flags (true and false) into metadata', async () => {
const task = await addTask({ description: 'flagged', useWorktree: false, openPR: true }, 'user');
expect(task.metadata.useWorktree).toBe(false);