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: finalize perpetual drain admission guards

[._.]/ Adam Eivyc6825220bcf2
diff --git a/server/services/cos.js b/server/services/cos.js
index 89644fcb14..6b59a43852 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -122,6 +122,7 @@ import {
queueEligibleImprovementTasks,
generateSelfImprovementTaskForType,
generateManagedAppImprovementTaskForType,
+ recordDeferredPerpetualDispatch,
applyOnDemandConsent,
emitOnDemandEmpty,
blockIfExceedsMaxSpawns,
@@ -988,7 +989,10 @@ async function spawnDequeuePriority0OnDemand(ctx) {
reviewStartedApps.add(targetApp.id);
}
await taskScheduleMod.recordExecution(`task:${request.taskType}`, targetApp.id);
- task = await generateManagedAppImprovementTaskForType(request.taskType, targetApp, state, { skipPreconditions: true });
+ task = await generateManagedAppImprovementTaskForType(request.taskType, targetApp, state, {
+ skipPreconditions: true,
+ deferPerpetualDispatch: true
+ });
if (task) {
await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);
}
@@ -1021,6 +1025,7 @@ async function spawnDequeuePriority0OnDemand(ctx) {
// rejected as a duplicate of the run that just finished and the drain stalls.
const persisted = await addTask(task, 'internal', { raw: true, ignoreTaskId });
if (!persisted?.duplicate) {
+ await recordDeferredPerpetualDispatch(task, taskScheduleMod);
cosEvents.emit('task:ready', task);
capacity.trackSpawn(task);
} else if (persisted.status === 'blocked') {
@@ -1029,6 +1034,7 @@ async function spawnDequeuePriority0OnDemand(ctx) {
// and without this branch the Run is a silent no-op that strands the
// bound on-demand review marker.
await reviveBlockedTask(persisted.id, { priority: task.priority, metadata: task.metadata }, 'internal');
+ await recordDeferredPerpetualDispatch(task, taskScheduleMod);
const revived = { ...task, id: persisted.id };
cosEvents.emit('task:ready', revived);
capacity.trackSpawn(revived);
@@ -1263,6 +1269,7 @@ async function spawnDequeuePriority4IdleReview(ctx) {
// that marker, which requires the emit. A denial would leave the app reading
// "in review" indefinitely (#978's mode). See canSpawnCommitted (#4834).
if (idleTask && capacity.canSpawnCommitted(idleTask, ctx.autonomousSpawnCeiling)) {
+ await recordDeferredPerpetualDispatch(idleTask, await import('./taskSchedule.js'));
cosEvents.emit('task:ready', idleTask);
capacity.trackSpawn(idleTask);
}
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 5e76b652ae..cd6048be70 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -154,11 +154,28 @@ export function isCooldownExemptTask(task) {
* valid idle result but never reaches this predicate because `actionable` is
* false.
*/
-export function shouldParkUnchangedPerpetualWork(detection, lastSignature) {
+export function shouldParkUnchangedPerpetualWork(detection, lastSignature, dispatchCount = 0) {
return detection?.actionable === true
&& detection.signature != null
&& lastSignature != null
- && detection.signature === lastSignature;
+ && detection.signature === lastSignature
+ // A same-issue continuation is allowed one unchanged recheck: the prior
+ // claim may have shipped a partial slice while leaving the issue actionable.
+ // A second unchanged observation is a genuine no-progress loop.
+ && dispatchCount > 1;
+}
+
+// The generator can be called before either spawn engine admits its result.
+// Keep the drain signature off persisted task metadata until that admission is
+// known to have succeeded; a WeakMap carries it only across the in-memory handoff.
+const deferredPerpetualSignatures = new WeakMap();
+
+export async function recordDeferredPerpetualDispatch(task, taskSchedule) {
+ const deferred = deferredPerpetualSignatures.get(task);
+ if (!deferred) return false;
+ deferredPerpetualSignatures.delete(task);
+ await taskSchedule.recordPerpetualDispatch(deferred.taskType, deferred.appId, deferred.signature);
+ return true;
}
/**
@@ -928,7 +945,10 @@ async function spawnPriority0OnDemand(ctx) {
reviewStartedApps.add(targetApp.id);
}
await taskSchedule.recordExecution(`task:${request.taskType}`, targetApp.id);
- task = await generateManagedAppImprovementTaskForType(request.taskType, targetApp, state, { skipPreconditions: true });
+ task = await generateManagedAppImprovementTaskForType(request.taskType, targetApp, state, {
+ skipPreconditions: true,
+ deferPerpetualDispatch: true
+ });
if (task) {
await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);
}
@@ -953,6 +973,7 @@ async function spawnPriority0OnDemand(ctx) {
task.metadata = { ...(task.metadata || {}), onDemand: true };
const persisted = await addTask(task, 'internal', { raw: true });
if (!persisted?.duplicate) {
+ await recordDeferredPerpetualDispatch(task, taskSchedule);
tasksToSpawn.push(task);
trackSpawn(task);
} else if (persisted.status === 'blocked') {
@@ -961,6 +982,7 @@ async function spawnPriority0OnDemand(ctx) {
// stranding the bound on-demand review marker. Mirrors the sibling
// dequeueNextTask on-demand engine in cos.js.
await reviveBlockedTask(persisted.id, { priority: task.priority, metadata: task.metadata }, 'internal');
+ await recordDeferredPerpetualDispatch(task, taskSchedule);
const revived = { ...task, id: persisted.id };
tasksToSpawn.push(revived);
trackSpawn(revived);
@@ -1189,6 +1211,7 @@ async function spawnPriority4IdleReview(ctx) {
if (pendingSystemTasks === 0) {
const idleTask = await generateIdleReviewTask(state);
if (idleTask && canSpawnTask(idleTask, autonomousSlotCeiling)) {
+ await recordDeferredPerpetualDispatch(idleTask, await import('./taskSchedule.js'));
tasksToSpawn.push(idleTask);
trackSpawn(idleTask);
}
@@ -1548,7 +1571,8 @@ export function buildImprovementDedupSets(existingTasks, { ignoreTaskId = null }
* Tasks are queued to COS-TASKS.md and will be picked up in Priority 2
*/
export async function queueEligibleImprovementTasks(state, cosTaskData, { ignoreTaskId = null } = {}) {
- const { getNextTaskType, recordExecution } = await import('./taskSchedule.js');
+ const taskSchedule = await import('./taskSchedule.js');
+ const { getNextTaskType, recordExecution } = taskSchedule;
if (!isImprovementEnabled(state)) return;
@@ -1644,7 +1668,10 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, { ignore
// agents claim the same slug (2026-05-21 incident). The generator
// returns null on plan-gate / precondition skip; we silently continue.
// Regression-pinned in cos.test.js.
- const task = await generateManagedAppImprovementTaskForType(nextType, app, state, { ignoreTaskId });
+ const task = await generateManagedAppImprovementTaskForType(nextType, app, state, {
+ ignoreTaskId,
+ deferPerpetualDispatch: true
+ });
if (!task) continue;
// Queue-path invariants override the generator's direct-spawn defaults
@@ -1684,6 +1711,7 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, { ignore
const newTask = await addTask(task, 'internal', { raw: true, ignoreTaskId });
if (newTask?.duplicate) continue;
+ await recordDeferredPerpetualDispatch(task, taskSchedule);
await recordExecution(`task:${nextType}`, app.id);
@@ -2066,7 +2094,10 @@ async function generateManagedAppImprovementTask(app, state, { ignoreTaskId = nu
// with the literal {prData}/{referenceData} markers and never poll. The
// recordExecution + activity bump above already accounted for the idle
// spawn; the per-type generator does not record execution itself.
- const task = await generateManagedAppImprovementTaskForType(nextType, app, state, { ignoreTaskId });
+ const task = await generateManagedAppImprovementTaskForType(nextType, app, state, {
+ ignoreTaskId,
+ deferPerpetualDispatch: true
+ });
// Idle-review can steal a queued on-demand request for this app. That
// request is still a user Run — apply the same consent as Priority 0.
if (selectionReason === 'on-demand') applyOnDemandConsent(task);
@@ -2340,8 +2371,8 @@ async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, i
? null
: JSON.stringify({ taskType: promptTaskType, candidates: detection.signature });
if (drainSignature != null) {
- const { signature: lastSignature } = await taskSchedule.getPerpetualDrainState(taskType, app.id);
- if (shouldParkUnchangedPerpetualWork({ ...detection, signature: drainSignature }, lastSignature)) {
+ const { signature: lastSignature, dispatchCount } = await taskSchedule.getPerpetualDrainState(taskType, app.id);
+ if (shouldParkUnchangedPerpetualWork({ ...detection, signature: drainSignature }, lastSignature, dispatchCount)) {
const counts = detection.total != null
? { open: detection.total, inFlight: detection.inFlightCount ?? 0, filtered: detection.filteredCount ?? 0 }
: null;
@@ -2993,7 +3024,11 @@ function applyProviderModelPins(metadata, interval, appPin, hookOverride) {
applyOneProviderPin(metadata, hookOverride);
}
-export async function generateManagedAppImprovementTaskForType(taskType, app, state, { skipPreconditions = false, ignoreTaskId = null } = {}) {
+export async function generateManagedAppImprovementTaskForType(taskType, app, state, {
+ skipPreconditions = false,
+ ignoreTaskId = null,
+ deferPerpetualDispatch = false
+} = {}) {
const { updateAppActivity } = await import('./appActivity.js');
const taskSchedule = await import('./taskSchedule.js');
const { getTaskPrompt, getStagePrompt } = await import('./taskPromptService.js');
@@ -3035,7 +3070,7 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st
// while the completing task is still `in_progress` on disk — a hook that
// counts in-flight tasks against a budget must not count the run that just
// finished and already recorded itself (#3179).
- const inputHook = await resolveTaskInputHook(app, taskType, taskSchedule, { ignoreTaskId });
+ const inputHook = await resolveTaskInputHook(app, taskType, taskSchedule, { ignoreTaskId });
if (inputHook.skip) return null;
const { hookPrompt, hookOverride, hookMetadata } = inputHook;
@@ -3205,16 +3240,6 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st
}
metadata[key] = value;
}
- // Every gate has now passed and a task is certain, so the perpetual drain can
- // finally be charged for this hop (and its park cleared). Sits beside
- // `updateAppActivity` for the same reason that call does: both are "a task was
- // really produced" side effects, and every `return null` above must skip them.
- // The reconcile drains spend theirs inside their own block, which no later gate
- // can skip (their types are outside PLAN_PICK_TASK_TYPES / pr-watcher /
- // reference-watch), so they are already charged only on real dispatches.
- if (perpetualGate.spendDispatch) {
- await taskSchedule.recordPerpetualDispatch(taskType, app.id, perpetualGate.signature ?? null);
- }
await updateAppActivity(app.id, { lastImprovementType: taskType });
emitLog('info', `Generating improvement task for ${app.name}: ${taskType}`, { appId: app.id, analysisType: taskType });
@@ -3229,6 +3254,21 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st
...approval
};
+ // Most callers return the task to a spawn engine, so keep this side effect
+ // deferred until that engine admits the task. Direct callers retain the old
+ // immediate behavior; queue/on-demand/idle paths opt into the handoff below.
+ if (perpetualGate.spendDispatch) {
+ if (deferPerpetualDispatch) {
+ deferredPerpetualSignatures.set(task, {
+ taskType,
+ appId: app.id,
+ signature: perpetualGate.signature ?? null
+ });
+ } else {
+ await taskSchedule.recordPerpetualDispatch(taskType, app.id, perpetualGate.signature ?? null);
+ }
+ }
+
return task;
}
// `normalizeClaimReviewers` moved to server/lib/cosValidation.js (#4770): the
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 63d4e9d39c..22716d0672 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -94,19 +94,21 @@ const noCooldown = () => Promise.resolve(false);
describe('claim drain convergence', () => {
it('parks a successful no-progress run when the actionable set is unchanged', () => {
const detection = { actionable: true, signature: '[101,202]' };
- expect(shouldParkUnchangedPerpetualWork(detection, '[101,202]')).toBe(true);
+ expect(shouldParkUnchangedPerpetualWork(detection, '[101,202]', 2)).toBe(true);
+ expect(shouldParkUnchangedPerpetualWork(detection, '[101,202]', 1)).toBe(false);
});
it('continues when the candidate set changed or has no progress identity', () => {
- expect(shouldParkUnchangedPerpetualWork({ actionable: true, signature: '[202]' }, '[101,202]')).toBe(false);
- expect(shouldParkUnchangedPerpetualWork({ actionable: true }, '[101,202]')).toBe(false);
- expect(shouldParkUnchangedPerpetualWork({ actionable: false, signature: '[]' }, '[]')).toBe(false);
+ expect(shouldParkUnchangedPerpetualWork({ actionable: true, signature: '[202]' }, '[101,202]', 2)).toBe(false);
+ expect(shouldParkUnchangedPerpetualWork({ actionable: true }, '[101,202]', 2)).toBe(false);
+ expect(shouldParkUnchangedPerpetualWork({ actionable: false, signature: '[]' }, '[]', 2)).toBe(false);
});
it('does not confuse tracker-specific signatures', () => {
expect(shouldParkUnchangedPerpetualWork(
{ actionable: true, signature: '{"taskType":"claim-issue-gitlab","candidates":"[1]"}' },
- '{"taskType":"claim-issue","candidates":"[1]"}'
+ '{"taskType":"claim-issue","candidates":"[1]"}',
+ 2
)).toBe(false);
});
});
diff --git a/server/services/perpetualWork.js b/server/services/perpetualWork.js
index 29bb84c6e2..17f7946856 100644
--- a/server/services/perpetualWork.js
+++ b/server/services/perpetualWork.js
@@ -307,8 +307,7 @@ const normalizeIssues = (raw, numberKey, authorKey) => raw.map((r) => ({
title: r.title,
labels: r.labels,
assignees: r.assignees,
- authorLogin: (r.author?.[authorKey] || '').toLowerCase(),
- updatedAt: r.updatedAt || r.updated_at || null
+ authorLogin: (r.author?.[authorKey] || '').toLowerCase()
}));
// A forge can return the same candidate set in a different order, especially
@@ -316,7 +315,13 @@ const normalizeIssues = (raw, numberKey, authorKey) => raw.map((r) => ({
// a canonical representation for the perpetual drain's set comparison.
const canonicalizeIds = (ids) => [...new Set(ids
.filter((id) => id != null)
- .map((id) => String(id)))].sort();
+ .map((id) => String(id)))].sort((a, b) => {
+ const numericA = Number(a);
+ const numericB = Number(b);
+ return Number.isFinite(numericA) && Number.isFinite(numericB)
+ ? numericA - numericB
+ : a.localeCompare(b);
+});
const GLAB_SELF_LOGIN_ARGS = ['api', 'user', '-q', '.username'];
@@ -351,7 +356,7 @@ const FORGE_ISSUE_CONFIG = {
// happens to be full of excluded/in-flight/decomposed-epic issues even
// though real work exists further down the queue. Matches the same
// tradeoff the /do:next auto-pick walk already makes for the same reason.
- listArgs: ['issue', 'list', '--state', 'open', '--search', 'sort:created-asc', '--json', 'number,assignees,labels,title,author,updatedAt', '--limit', '500'],
+ listArgs: ['issue', 'list', '--state', 'open', '--search', 'sort:created-asc', '--json', 'number,assignees,labels,title,author', '--limit', '500'],
listFail: 'gh-list-failed',
parseFail: 'gh-parse-failed',
// Park reason when the owner filter resolves to a non-authoring owner. On
@@ -663,11 +668,7 @@ async function detectForgeIssues(forgeKey, app, { issueAuthorFilter = 'self', is
// The perpetual drain uses the complete candidate set to detect a
// successful agent that exited without claiming anything. `sample` is
// intentionally capped for UI payloads, so it cannot serve as that brake.
- // updatedAt changes when the claim flow posts a partial-delivery comment
- // or releases its markers, so a same-issue continuation remains eligible.
- // The ID is retained as the primary identity for forge responses that omit
- // the timestamp (and for older test/mocked CLI output).
- signature: JSON.stringify(canonicalizeIds(actionable.map((i) => `${i.number}@${i.updatedAt || ''}`))),
+ signature: JSON.stringify(canonicalizeIds(actionable.map((i) => i.number))),
items: actionable.slice(0, WORK_ITEM_LIMIT).map((i) => ({ ref: String(i.number), title: i.title || '' }))
};
}
@@ -709,7 +710,9 @@ export async function detectPlanTask(app) {
count: available.length,
reason: pick ? 'actionable-plan-items' : 'no-actionable-plan-items',
// Keep the signature complete even though the picker payload is capped.
- signature: JSON.stringify(canonicalizeIds(available.map((it) => it.id))),
+ // PLAN.md order is meaningful because pickFirstAvailable chooses the first
+ // eligible item; unlike forge issue sets, preserve that order in the brake.
+ signature: JSON.stringify(available.map((it) => it.id)),
items: available.slice(0, WORK_ITEM_LIMIT).map((it) => ({ ref: it.id, title: planItemTitle(it) }))
};
}
diff --git a/server/services/perpetualWork.test.js b/server/services/perpetualWork.test.js
index 097ec00598..15152a63b9 100644
--- a/server/services/perpetualWork.test.js
+++ b/server/services/perpetualWork.test.js
@@ -250,7 +250,7 @@ describe('perpetualWork', () => {
{ ref: '1', title: 'plain' },
{ ref: '5', title: 'also plain' }
]);
- expect(out.signature).toBe('["1@","5@"]');
+ expect(out.signature).toBe('["1","5"]');
});
it('reports the "[Epic]"-prefixed issue as actionable while it is still undecomposed', async () => {
@@ -269,23 +269,23 @@ describe('perpetualWork', () => {
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
expect(out).toMatchObject({ actionable: true, count: 1, reason: 'actionable-issues', sample: [1] });
- expect(out.signature).toBe('["1@"]');
+ expect(out.signature).toBe('["1"]');
expect(out.filteredCount).toBe(2);
});
- it('canonicalizes candidate order and keeps forge updates in the signature', async () => {
+ it('canonicalizes candidate order and removes duplicate issue IDs from the signature', async () => {
routeSpawn({
'gh issue': { stdout: JSON.stringify([
- { number: 10, title: 'later', updatedAt: '2026-08-27T02:00:00Z', assignees: [], labels: [] },
- { number: 2, title: 'first', updatedAt: '2026-08-27T01:00:00Z', assignees: [], labels: [] },
- { number: 10, title: 'duplicate', updatedAt: '2026-08-27T02:00:00Z', assignees: [], labels: [] }
+ { number: 10, title: 'later', assignees: [], labels: [] },
+ { number: 2, title: 'first', assignees: [], labels: [] },
+ { number: 10, title: 'duplicate', assignees: [], labels: [] }
]) },
'git branch': { stdout: 'main\n' },
'gh pr': { stdout: '' }
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
expect(out.sample).toEqual([10, 2, 10]);
- expect(out.signature).toBe('["10@2026-08-27T02:00:00Z","2@2026-08-27T01:00:00Z"]');
+ expect(out.signature).toBe('["2","10"]');
});
it('converges (0 actionable) once that epic carries the decomposed label', async () => {