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
return the deferred perpetual-dispatch record instead of a WeakMap keyed on the task object (#6871)
[._.]/ Adam Eivy663e3499cccf
diff --git a/server/lib/quotaBurnOrigin.js b/server/lib/quotaBurnOrigin.jsindex 4fef30c684..fbfa2f591b 100644--- a/server/lib/quotaBurnOrigin.js+++ b/server/lib/quotaBurnOrigin.js@@ -181,7 +181,7 @@ const scalarParams = (raw) => {* The params are here for a reason the other three are not: they have to reach* the PROMPT, so they cannot ride the post-generation* `onDemandRequestMetadata` stamp below. Both on-demand engines pull them off- * the request and hand them to `generateManagedAppImprovementTaskForType` as+ * the request and hand them to `prepareManagedAppImprovementTask` as* `runOverrides`, which layers them over the task's saved `taskMetadata` BEFORE* the mode banner is chosen and the prompt is rendered. That is what lets a step* migrated from an issues-only burn preset pin `fileIssues: true` explicitly anddiff --git a/server/services/cos.js b/server/services/cos.jsindex 7fee8e33d1..e370be98fa 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -1097,13 +1097,13 @@ async function spawnDequeuePriority3IdleReview(ctx) {const freshCosTasks = await getCosTasks();const pendingSystemTasks = freshCosTasks.autoApproved?.length || 0;if (pendingSystemTasks === 0) {- const idleTask = await generateIdleReviewTask(state, { ignoreTaskId });+ const { task: idleTask, pendingPerpetualDispatch } = await generateIdleReviewTask(state, { ignoreTaskId });// Committed tier — `generateIdleReviewTask` has already bound the app-review// marker and advanced the 30-minute cooldown, and only `holdTask` releases// 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'));+ await recordDeferredPerpetualDispatch(pendingPerpetualDispatch, await import('./taskSchedule.js'));cosEvents.emit('task:ready', idleTask);capacity.trackSpawn(idleTask);}diff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex d8416adf17..308ec06307 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -1621,7 +1621,7 @@ describe('cos.js source — priority + capacity invariants', () => {expect(GEN_SRC).toMatch(/getTaskInputHook/);});- it('queueEligibleImprovementTasks routes through generateManagedAppImprovementTaskForType', () => {+ it('queueEligibleImprovementTasks routes through prepareManagedAppImprovementTask', () => {// Regression guard: a 2026-05-21 incident saw two `plan-task` agents both// open PRs for the same PLAN.md slug because the queue path was writing// a one-line stub description with no `analysisType` / `planId`. The@@ -1636,8 +1636,8 @@ describe('cos.js source — priority + capacity invariants', () => {expect(fnBody,- 'queue path must call generateManagedAppImprovementTaskForType so applyPlanIdMetadata runs + the full prompt is used'- ).toMatch(/generateManagedAppImprovementTaskForType\s*\(/);+ 'queue path must call prepareManagedAppImprovementTask so applyPlanIdMetadata runs + the full prompt is used'+ ).toMatch(/prepareManagedAppImprovementTask\s*\(/);// Match the call shape, not the specific variable name — `task` could// legitimately be renamed (e.g. `queuedTask`) in a behavior-preserving@@ -1720,7 +1720,7 @@ describe('cos.js source — priority + capacity invariants', () => {).toMatch(/getNextTaskType\([^)]*\{\s*perpetualOnly:\s*onCooldown\s*[,}]/);});- it('generateManagedAppImprovementTaskForType defers updateAppActivity until after gates', () => {+ it('prepareManagedAppImprovementTask defers updateAppActivity until after gates', () => {// Regression guard: the rotation pointer + "Generating improvement task"// log must only advance when a real task is queued. The eager call at// the top of the function was tolerable when only the on-demand path@@ -1736,8 +1736,8 @@ describe('cos.js source — priority + capacity invariants', () => {// contains a `for (...) { try { ... } catch }` block and the// brace-balanced scanner doesn't always match the right closer when// there are template-literal braces nested inside.- const fnStart = GEN_SRC.indexOf('async function generateManagedAppImprovementTaskForType');- expect(fnStart, 'generateManagedAppImprovementTaskForType must exist').toBeGreaterThan(-1);+ const fnStart = GEN_SRC.indexOf('async function prepareManagedAppImprovementTask');+ expect(fnStart, 'prepareManagedAppImprovementTask must exist').toBeGreaterThan(-1);const fnEnd = GEN_SRC.indexOf('\nasync function ', fnStart + 1);const fnBody = GEN_SRC.slice(fnStart, fnEnd === -1 ? undefined : fnEnd);diff --git a/server/services/cosTaskGenerator.auditMode.test.js b/server/services/cosTaskGenerator.auditMode.test.jsindex 8ed69c5c4e..9e5d23487c 100644--- a/server/services/cosTaskGenerator.auditMode.test.js+++ b/server/services/cosTaskGenerator.auditMode.test.js@@ -297,8 +297,8 @@ describe('mode is honored identically from schedule, manual run, and quota burn'it.each([['ordinary schedule', {}],- ['manual run / on-demand', { skipPreconditions: true, deferPerpetualDispatch: true, targetPullRequest: null, runOverrides: null }],- ['quota burn (no param override)', { skipPreconditions: true, deferPerpetualDispatch: true, targetPullRequest: null, runOverrides: {} }],+ ['manual run / on-demand', { skipPreconditions: true, targetPullRequest: null, runOverrides: null }],+ ['quota burn (no param override)', { skipPreconditions: true, targetPullRequest: null, runOverrides: {} }],])('%s renders the same file-issues prompt and settings', async (_lane, options) => {const { getTaskInterval } = await import('./taskSchedule.js');getTaskInterval.mockResolvedValue({ type: 'weekly', taskMetadata: { fileIssues: true } });diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex edf4618eea..7bf3911e19 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -209,16 +209,19 @@ export function shouldParkUnchangedPerpetualWork(detection, lastSignature, dispa&& 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);+// The generator can be called before either spawn engine admits its result, so+// the drain signature travels as a plain data record returned alongside the+// task (`pendingPerpetualDispatch`, see `prepareManagedAppImprovementTask`)+// instead of being parked in a WeakMap keyed on the task object. The object-+// identity version required every admission site to keep re-finding the EXACT+// object the generator returned; `cosTaskStore.addTask` hands back a DIFFERENT+// object whenever the description is multi-line, which is the normal case, so+// a caller that naturally kept using the store's returned object instead of+// the generator's recorded nothing, silently (#6871).+export async function recordDeferredPerpetualDispatch(pendingPerpetualDispatch, taskSchedule) {+ if (!pendingPerpetualDispatch) return false;+ const { taskType, appId, signature } = pendingPerpetualDispatch;+ await taskSchedule.recordPerpetualDispatch(taskType, appId, signature);return true;}@@ -1018,9 +1021,9 @@ async function spawnPriority4IdleReview(ctx) {const freshCosTasks = await getCosTasks();const pendingSystemTasks = freshCosTasks.autoApproved?.length || 0;if (pendingSystemTasks === 0) {- const idleTask = await generateIdleReviewTask(state);+ const { task: idleTask, pendingPerpetualDispatch } = await generateIdleReviewTask(state);if (idleTask && canSpawnTask(idleTask, autonomousSlotCeiling)) {- await recordDeferredPerpetualDispatch(idleTask, await import('./taskSchedule.js'));+ await recordDeferredPerpetualDispatch(pendingPerpetualDispatch, await import('./taskSchedule.js'));tasksToSpawn.push(idleTask);trackSpawn(idleTask);}@@ -1264,7 +1267,7 @@ export async function evaluateTasks(options) {export async function generateIdleReviewTask(state, { ignoreTaskId = null } = {}) {if (!isImprovementEnabled(state)) {emitLog('debug', 'Improvement tasks are disabled');- return null;+ return { task: null, pendingPerpetualDispatch: null };}// Get all active (non-archived) managed apps (including PortOS)@@ -1292,17 +1295,17 @@ export async function generateIdleReviewTask(state, { ignoreTaskId = null } = {}});emitLog('info', `Generating improvement task for ${nextApp.name}`, { appId: nextApp.id });- const idleTask = await generateManagedAppImprovementTask(nextApp, state, { ignoreTaskId });+ const { task: idleTask, pendingPerpetualDispatch } = await generateManagedAppImprovementTask(nextApp, state, { ignoreTaskId });// Only bind the active marker once a real task exists.if (idleTask) {await bindAppReviewAgent(nextApp.id, `idle-review-${Date.now()}`);}- return idleTask;+ return { task: idleTask, pendingPerpetualDispatch };}}emitLog('debug', 'No idle tasks available');- return null;+ return { task: null, pendingPerpetualDispatch: null };}/**@@ -1536,11 +1539,9 @@ 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,- deferPerpetualDispatch: true- });- if (!task) continue;+ const prepared = await prepareManagedAppImprovementTask(nextType, app, state, { ignoreTaskId });+ if (!prepared?.task) continue;+ const { task, pendingPerpetualDispatch } = prepared;// Queue-path invariants override the generator's direct-spawn defaults// (which use MEDIUM priority + `app-improve-*` id).@@ -1554,7 +1555,11 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, { ignore// task:ready, renders full description via getTaskPrompt.const newTask = await addTask(task, 'internal', { raw: true, ignoreTaskId, suppressDequeue: true });if (newTask?.duplicate) continue;- await recordDeferredPerpetualDispatch(task, taskSchedule);+ // Recorded from `pendingPerpetualDispatch` — the RECORD prepare returned —+ // never from `task` or `newTask`: addTask hands back a different object+ // whenever the description is multi-line, so recording must not depend on+ // which one the caller is holding (#6871).+ await recordDeferredPerpetualDispatch(pendingPerpetualDispatch, taskSchedule);if (wakeAfterRecord) cosEvents.emit('cos:dequeue-requested');await recordExecution(`task:${nextType}`, app.id);@@ -1955,7 +1960,7 @@ async function generateManagedAppImprovementTask(app, state, { ignoreTaskId = nuif (!nextTypeResult) {emitLog('info', `No app improvement tasks are eligible for ${app.name} based on schedule`);- return null;+ return { task: null, pendingPerpetualDispatch: null };}nextType = nextTypeResult.taskType;@@ -1980,15 +1985,16 @@ 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, {+ const prepared = await prepareManagedAppImprovementTask(nextType, app, state, {ignoreTaskId,- deferPerpetualDispatch: true,targetPullRequest});+ const task = prepared?.task ?? null;+ const pendingPerpetualDispatch = prepared?.pendingPerpetualDispatch ?? null;// 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);- return task;+ return { task, pendingPerpetualDispatch };}/**@@ -2525,10 +2531,22 @@ function applyProviderModelPins(metadata, interval, appPin, hookOverride, reques}}-export async function generateManagedAppImprovementTaskForType(taskType, app, state, {+/**+ * Decide whether a managed-app improvement task should be generated for+ * `taskType`, and build it if so. Never records a perpetual-drain dispatch —+ * that is returned as `pendingPerpetualDispatch` (`null`, or+ * `{ taskType, appId, signature }`) alongside the task, so the caller can+ * record it (via `recordDeferredPerpetualDispatch`) at whatever point the+ * task's admission is certain. `generateManagedAppImprovementTaskForType`+ * below is the thin direct-caller wrapper that records immediately; the+ * queue, on-demand, and idle-review paths call this function directly and+ * defer the record until their own spawn-engine admission succeeds (#6871).+ *+ * @returns {Promise<{ task: Object|null, pendingPerpetualDispatch: Object|null }>}+ */+export async function prepareManagedAppImprovementTask(taskType, app, state, {skipPreconditions = false,ignoreTaskId = null,- deferPerpetualDispatch = false,targetPullRequest = null,// Per-request provider/model/effort pin — see applyProviderModelPins.providerOverride = null,@@ -2802,22 +2820,39 @@ 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);- }- }+ // The drain signature returns alongside the task instead of being recorded+ // here — every caller sits between task construction and spawn-engine+ // admission, and recordDeferredPerpetualDispatch is the one choke point+ // that may spend the budget, once admission is certain (#6871).+ const pendingPerpetualDispatch = perpetualGate.spendDispatch+ ? { taskType, appId: app.id, signature: perpetualGate.signature ?? null }+ : null;- return task;+ return { task, pendingPerpetualDispatch };+}++/**+ * Generate a managed app improvement task for a specific type.+ * Used by on-demand task processing and can be called directly.+ *+ * Thin wrapper over `prepareManagedAppImprovementTask` (above) that records+ * any deferred perpetual-dispatch signature immediately — the shape every+ * direct caller got before the queue, on-demand, and idle-review paths needed+ * to defer that record until their own admission gate passes. Those three+ * callers use `prepareManagedAppImprovementTask` directly instead (see+ * `queueEligibleImprovementTasks`, `onDemandDrain.js`, `generateIdleReviewTask`).+ *+ * @param {string} taskType - The type of improvement task (e.g., 'security-audit', 'code-quality')+ * @param {Object} app - The managed app object+ * @param {Object} state - Current CoS state+ * @returns {Promise<Object|null>} Generated task, or null when nothing is eligible.+ */+export async function generateManagedAppImprovementTaskForType(taskType, app, state, opts = {}) {+ const taskSchedule = await import('./taskSchedule.js');+ const prepared = await prepareManagedAppImprovementTask(taskType, app, state, opts);+ if (!prepared) return null;+ await recordDeferredPerpetualDispatch(prepared.pendingPerpetualDispatch, taskSchedule);+ return prepared.task;}// `normalizeClaimReviewers` moved to server/lib/reviewerConfig.js (#4770, #5702): the// prompt builder needs the same copilot guard when it re-resolves reviewers offdiff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex 5b06eafa71..0023ae3e3d 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -81,6 +81,7 @@ import {buildImprovementDedupSets,queueDueInstallWideImprovementTasks,generateManagedAppImprovementTaskForType,+ recordDeferredPerpetualDispatch,normalizeWorkItemRef,buildTargetWorkItemBlock,buildPrefetchedIssueContextBlock,@@ -347,13 +348,13 @@ describe('isConfiguredApprovalRequired', () => {it('both generators stamp approvalReason onto metadata so the hint survives COS-TASKS.md', () => {const selfStart = GEN_SRC.indexOf('export async function generateSelfImprovementTaskForType');- const appStart = GEN_SRC.indexOf('export async function generateManagedAppImprovementTaskForType');+ const appStart = GEN_SRC.indexOf('export async function prepareManagedAppImprovementTask');expect(GEN_SRC.slice(selfStart, appStart)).toContain('stampApprovalReason(metadata, approval)');- // Bounded by the function's own `return task;` rather than a character- // count: a magic window makes this guard fire on any commit that adds a- // comment above the stamp, which says nothing about whether the stamp is- // still there.- const appBody = GEN_SRC.slice(appStart, GEN_SRC.indexOf('\n return task;', appStart));+ // Bounded by the function's own `return { task, pendingPerpetualDispatch };`+ // rather than a character count: a magic window makes this guard fire on+ // any commit that adds a comment above the stamp, which says nothing about+ // whether the stamp is still there.+ const appBody = GEN_SRC.slice(appStart, GEN_SRC.indexOf('\n return { task, pendingPerpetualDispatch };', appStart));expect(appBody).toContain('stampApprovalReason(metadata, approval)');});@@ -393,7 +394,7 @@ describe('the on-demand consent flip reaches every drain path', () => {// Slice to the end of the function, not a fixed byte window: the consent line// sits at the bottom of a body that grows, so a magic number makes an// unrelated comment above it read as a missing consent call.- const body = GEN_SRC.slice(start, GEN_SRC.indexOf('\n return task;', start));+ const body = GEN_SRC.slice(start, GEN_SRC.indexOf('\n return { task, pendingPerpetualDispatch };', start));expect(body).toMatch(/selectionReason === 'on-demand'\) applyOnDemandConsent\(task\)/);});});@@ -1533,8 +1534,8 @@ describe('resolveTaskInputHook — hookMetadata threading (#3179)', () => {// win over a decision made a few lines earlier. `analysisType` is the sharp// edge: resolveTaskHookType reads it to dispatch the output hook, so a// collision would stop the very hook that asked for the bag from running.- const start = GEN_SRC.indexOf('export async function generateManagedAppImprovementTaskForType');- const body = GEN_SRC.slice(start, GEN_SRC.indexOf('return task;', start));+ const start = GEN_SRC.indexOf('export async function prepareManagedAppImprovementTask');+ const body = GEN_SRC.slice(start, GEN_SRC.indexOf('return { task, pendingPerpetualDispatch };', start));expect(body).toContain('for (const [key, value] of Object.entries(hookMetadata || {}))');expect(body).toContain('if (key in metadata)');// A plain merge would reintroduce the clobber.@@ -1546,13 +1547,13 @@ describe('resolveTaskInputHook — hookMetadata threading (#3179)', () => {// test of the generator's happy path: moving the Object.assign above any// `return null` would silently restore the #3179 bug — a hook side effect// keyed on the stamped metadata would fire for a task that is never built.- const start = GEN_SRC.indexOf('export async function generateManagedAppImprovementTaskForType');- expect(start, 'generateManagedAppImprovementTaskForType must exist').toBeGreaterThan(-1);+ const start = GEN_SRC.indexOf('export async function prepareManagedAppImprovementTask');+ expect(start, 'prepareManagedAppImprovementTask must exist').toBeGreaterThan(-1);const body = GEN_SRC.slice(start);const stampAt = body.indexOf('Object.entries(hookMetadata || {})');expect(stampAt, 'the hookMetadata stamp must exist').toBeGreaterThan(-1);- // Bound the scan to this function: `return task;` ends it.- const lastGateAt = body.slice(0, body.indexOf('return task;')).lastIndexOf('return null;');+ // Bound the scan to this function: `return { task, pendingPerpetualDispatch };` ends it.+ const lastGateAt = body.slice(0, body.indexOf('return { task, pendingPerpetualDispatch };')).lastIndexOf('return null;');expect(lastGateAt, 'the gate chain must exist').toBeGreaterThan(-1);expect(stampAt).toBeGreaterThan(lastGateAt);});@@ -1566,12 +1567,12 @@ describe('resolveTaskInputHook — hookMetadata threading (#3179)', () => {*/describe('ignoreTaskId reaches the in-flight-counting gates (#3179)', () => {const body = () => {- const start = GEN_SRC.indexOf('export async function generateManagedAppImprovementTaskForType');- return GEN_SRC.slice(start, GEN_SRC.indexOf('return task;', start));+ const start = GEN_SRC.indexOf('export async function prepareManagedAppImprovementTask');+ return GEN_SRC.slice(start, GEN_SRC.indexOf('return { task, pendingPerpetualDispatch };', start));};it('accepts ignoreTaskId and forwards it to the input hook and the perpetual gate', () => {- expect(GEN_SRC).toMatch(/generateManagedAppImprovementTaskForType\(taskType, app, state, \{\s*skipPreconditions = false,\s*ignoreTaskId = null/);+ expect(GEN_SRC).toMatch(/prepareManagedAppImprovementTask\(taskType, app, state, \{\s*skipPreconditions = false,\s*ignoreTaskId = null/);expect(body()).toContain('resolveTaskInputHook(app, taskType, taskSchedule, { ignoreTaskId })');expect(body()).toContain('applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, interval, taskSchedule, { ignoreTaskId })');});@@ -1579,7 +1580,7 @@ describe('ignoreTaskId reaches the in-flight-counting gates (#3179)', () => {it('queueEligibleImprovementTasks passes its ignoreTaskId down to the generator', () => {// It already forwards the same id to addTask and buildImprovementDedupSets;// the generator was the one path that dropped it.- expect(GEN_SRC).toMatch(/generateManagedAppImprovementTaskForType\(nextType, app, state, \{[\s\S]*ignoreTaskId[\s\S]*deferPerpetualDispatch: true[\s\S]*\}\)/);+ expect(GEN_SRC).toMatch(/prepareManagedAppImprovementTask\(nextType, app, state, \{[\s\S]*ignoreTaskId[\s\S]*\}\)/);});it('the perpetual gate hands ignoreTaskId to the work detector', () => {@@ -1614,7 +1615,7 @@ describe('ignoreTaskId reaches BOTH completion-continuation generators (#3179)',expect(GEN_SRC).toMatch(/export async function generateIdleReviewTask\(state, \{ ignoreTaskId = null \} = \{\}\)/);expect(GEN_SRC).toContain('generateManagedAppImprovementTask(nextApp, state, { ignoreTaskId })');expect(GEN_SRC).toMatch(/async function generateManagedAppImprovementTask\(app, state, \{ ignoreTaskId = null \} = \{\}\)/);- expect(GEN_SRC).toMatch(/generateManagedAppImprovementTaskForType\(nextType, app, state, \{[\s\S]*ignoreTaskId[\s\S]*deferPerpetualDispatch: true[\s\S]*\}\)/);+ expect(GEN_SRC).toMatch(/prepareManagedAppImprovementTask\(nextType, app, state, \{[\s\S]*ignoreTaskId[\s\S]*\}\)/);});it('cos.js passes the completing task id into the dequeue that follows the refill', () => {@@ -1629,9 +1630,9 @@ describe('ignoreTaskId reaches BOTH completion-continuation generators (#3179)',* through, and BEFORE the detectors/scans it would only discard the results of.*/describe('the drain cap has exactly one implementation, at the choke point', () => {- it('generateManagedAppImprovementTaskForType applies it ahead of the work gate and the reconcile scans', () => {- const start = GEN_SRC.indexOf('export async function generateManagedAppImprovementTaskForType');- const body = GEN_SRC.slice(start, GEN_SRC.indexOf('return task;', start));+ it('prepareManagedAppImprovementTask applies it ahead of the work gate and the reconcile scans', () => {+ const start = GEN_SRC.indexOf('export async function prepareManagedAppImprovementTask');+ const body = GEN_SRC.slice(start, GEN_SRC.indexOf('return { task, pendingPerpetualDispatch };', start));const capIdx = body.indexOf('applyPerpetualDrainCap(app, taskType, interval, taskSchedule)');expect(capIdx, 'the choke point must apply the per-type drain cap').toBeGreaterThan(-1);expect(capIdx).toBeLessThan(body.indexOf('applyPerpetualWorkGate('));@@ -1666,12 +1667,54 @@ describe('the drain cap has exactly one implementation, at the choke point', ()expect(gate).toContain('spendDispatch: true');expect(gate, 'the gate must not charge the budget itself').not.toContain('recordPerpetualDispatch');- const genStart = GEN_SRC.indexOf('export async function generateManagedAppImprovementTaskForType');- const body = GEN_SRC.slice(genStart, GEN_SRC.indexOf('return task;', genStart));- const spendIdx = body.search(/if \(perpetualGate\.spendDispatch\) \{[\s\S]*recordPerpetualDispatch\(taskType, app\.id, perpetualGate\.signature \?\? null\)/);- expect(spendIdx, 'the choke point must spend the deferred dispatch').toBeGreaterThan(-1);+ // prepareManagedAppImprovementTask computes the deferred-dispatch RECORD —+ // it never spends the budget itself. recordDeferredPerpetualDispatch is the+ // one choke point that does, shared by the immediate-record wrapper+ // (generateManagedAppImprovementTaskForType) and the deferred queue/+ // on-demand/idle callers alike (#6871).+ const genStart = GEN_SRC.indexOf('export async function prepareManagedAppImprovementTask');+ const body = GEN_SRC.slice(genStart, GEN_SRC.indexOf('return { task, pendingPerpetualDispatch };', genStart));+ expect(body, 'prepare must not charge the budget itself').not.toContain('recordPerpetualDispatch(');+ const pendingIdx = body.indexOf('perpetualGate.spendDispatch');+ expect(pendingIdx, 'the choke point must compute the deferred-dispatch record from the gate result').toBeGreaterThan(-1);+ expect(body).toContain('signature: perpetualGate.signature ?? null');// Every `return null` gate must precede it — planId is the last one.- expect(body.indexOf('planMeta.skipReason')).toBeLessThan(spendIdx);+ expect(body.indexOf('planMeta.skipReason')).toBeLessThan(pendingIdx);++ const recordStart = GEN_SRC.indexOf('export async function recordDeferredPerpetualDispatch');+ expect(recordStart, 'recordDeferredPerpetualDispatch must exist').toBeGreaterThan(-1);+ const recordBody = GEN_SRC.slice(recordStart, GEN_SRC.indexOf('\n}', recordStart));+ expect(recordBody, 'recordDeferredPerpetualDispatch is the one choke point that spends the budget').toContain('recordPerpetualDispatch(taskType, appId, signature)');+ });+});++/**+ * recordDeferredPerpetualDispatch used to be keyed on the GENERATOR's task+ * object via a WeakMap — a caller that recorded against any other object (the+ * store's re-wrapped multi-line-description task, a clone, a stub) missed+ * silently. The record is now a plain `{ taskType, appId, signature }` value+ * threaded through the return, so recording no longer depends on which+ * task-object variant the caller happens to be holding (#6871). The+ * admission-site behavior (a re-wrapped addTask result still gets recorded; a+ * duplicate result records nothing) is pinned at the boundary in+ * onDemandDrain.test.js — this is the helper's own direct contract.+ */+describe('recordDeferredPerpetualDispatch (#6871)', () => {+ it('spends the budget from the record, independent of any task object', async () => {+ const recordPerpetualDispatch = vi.fn(async () => 1);+ const pendingPerpetualDispatch = { taskType: 'code-quality', appId: 'app-1', signature: 'sig-abc' };++ const recorded = await recordDeferredPerpetualDispatch(pendingPerpetualDispatch, { recordPerpetualDispatch });++ expect(recorded).toBe(true);+ expect(recordPerpetualDispatch).toHaveBeenCalledWith('code-quality', 'app-1', 'sig-abc');+ });++ it('is a no-op when there is nothing to record', async () => {+ const recordPerpetualDispatch = vi.fn(async () => 1);++ expect(await recordDeferredPerpetualDispatch(null, { recordPerpetualDispatch })).toBe(false);+ expect(recordPerpetualDispatch).not.toHaveBeenCalled();});});@@ -1690,8 +1733,8 @@ describe('pr-reviewer security preflight wiring', () => {// composes it: the call sits before the ordinary stage gate, its skip reason// is recorded, and a passed preflight selects the current stage's prompt.it('runs the direct preflight before stage gates and resolves the next-stage prompt', () => {- const start = GEN_SRC.indexOf('export async function generateManagedAppImprovementTaskForType');- const body = GEN_SRC.slice(start, GEN_SRC.indexOf('return task;', start));+ const start = GEN_SRC.indexOf('export async function prepareManagedAppImprovementTask');+ const body = GEN_SRC.slice(start, GEN_SRC.indexOf('return { task, pendingPerpetualDispatch };', start));const preflightAt = body.indexOf('runPrReviewerSecurityPreflight(taskType, app, metadata, targetPullRequest, taskSchedule)');const preconditionAt = body.indexOf('shouldSkipForPrecondition(metadata, app, taskType)');const promptAt = body.indexOf('getStagePrompt(taskType, currentStageIndex)');@@ -1709,16 +1752,16 @@ describe('pr-reviewer security preflight wiring', () => {it('carries a stolen on-demand request\'s PR target through the idle-review path', () => {const start = GEN_SRC.indexOf('const appRequests = onDemandRequests.filter(');- const body = GEN_SRC.slice(start, GEN_SRC.indexOf('\n return task;', start));+ const body = GEN_SRC.slice(start, GEN_SRC.indexOf('\n return { task, pendingPerpetualDispatch };', start));// The idle tier can consume a queued on-demand request instead of Priority 0.// Dropping the target there re-widens a one-row click into a full sweep.expect(body).toContain('targetPullRequest = request.targetPullRequest ?? null');- expect(body).toMatch(/generateManagedAppImprovementTaskForType\([\s\S]*?targetPullRequest\n/);+ expect(body).toMatch(/prepareManagedAppImprovementTask\([\s\S]*?targetPullRequest\n/);});it('keeps a targeted run distinguishable from the sweep in the duplicate guard', () => {- const genStart = GEN_SRC.indexOf('export async function generateManagedAppImprovementTaskForType');- const body = GEN_SRC.slice(genStart, GEN_SRC.indexOf('return task;', genStart));+ const genStart = GEN_SRC.indexOf('export async function prepareManagedAppImprovementTask');+ const body = GEN_SRC.slice(genStart, GEN_SRC.indexOf('return { task, pendingPerpetualDispatch };', genStart));expect(body).toContain('scopeDescriptionToPullRequest(');});});diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsindex f9422fd891..17eddd8126 100644--- a/server/services/cosTaskStore.test.js+++ b/server/services/cosTaskStore.test.js@@ -887,7 +887,7 @@ describe('cosTaskStore.addTask', () => {});it('rejects a raw duplicate whose app lives in metadata.app (queue-path improvement tasks)', async () => {- // Queue-path improvement tasks (generateManagedAppImprovementTaskForType) arrive+ // Queue-path improvement tasks (prepareManagedAppImprovementTask) arrive// pre-built with `raw: true` and carry the app in `metadata.app`, NOT top-level// `taskData.app`. Two concurrent queueEligibleImprovementTasks snapshots each add// an identical `[Improvement: PortOS] …` task; the second must be rejected as adiff --git a/server/services/onDemandDrain.js b/server/services/onDemandDrain.jsindex 681e7d58c2..ed3678ec57 100644--- a/server/services/onDemandDrain.js+++ b/server/services/onDemandDrain.js@@ -58,7 +58,7 @@ export async function drainOnDemandRequests(ctx, adapter) {// imports THIS module, and these six helpers are declared there. Deferring to// call time is the same idiom the engines already use for taskSchedule.js.const {- generateManagedAppImprovementTaskForType,+ prepareManagedAppImprovementTask,generateSelfImprovementTaskForType,recordDeferredPerpetualDispatch,applyOnDemandConsent,@@ -112,6 +112,11 @@ export async function drainOnDemandRequests(ctx, adapter) {}let task = null;+ // The perpetual drain signature `prepareManagedAppImprovementTask` decided+ // to record for this task, if any — returned as a plain record rather than+ // discovered by re-finding the task object, so it survives regardless of+ // which task-object variant `addTask` below hands back (#6871).+ let pendingPerpetualDispatch = null;// Determine target app (if any)let targetApp = null;@@ -143,9 +148,8 @@ export async function drainOnDemandRequests(ctx, adapter) {reviewStartedApps.add(targetApp.id);}await taskScheduleMod.recordExecution(`task:${request.taskType}`, targetApp.id);- task = await generateManagedAppImprovementTaskForType(request.taskType, targetApp, state, {+ const prepared = await prepareManagedAppImprovementTask(request.taskType, targetApp, state, {skipPreconditions: true,- deferPerpetualDispatch: true,targetPullRequest: request.targetPullRequest ?? null,providerOverride: request.providerOverride ?? null,// A quota-burn step's per-invocation run parameters. They must reach@@ -158,6 +162,8 @@ export async function drainOnDemandRequests(ctx, adapter) {// for every step until the migration starts pinning one.runOverrides: request.burn?.overrides?.params ?? null});+ task = prepared?.task ?? null;+ pendingPerpetualDispatch = prepared?.pendingPerpetualDispatch ?? null;if (task) {await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);}@@ -193,14 +199,14 @@ export async function drainOnDemandRequests(ctx, adapter) {// rejected as a duplicate of the run that just finished and the drain stalls.const persisted = await addTask(task, 'internal', { raw: true, ...addTaskOptions, suppressDequeue: true });if (!persisted?.duplicate) {- await recordDeferredPerpetualDispatch(task, taskScheduleMod);+ await recordDeferredPerpetualDispatch(pendingPerpetualDispatch, taskScheduleMod);emitSpawn(task);} else if (persisted.status === 'blocked') {// Explicit user Run colliding with a failure-blocked twin (#2614):// revive the existing task instead of silently dropping the Run and// stranding the bound on-demand review marker.await reviveBlockedTask(persisted.id, { priority: task.priority, metadata: task.metadata }, 'internal', { suppressDequeue: true });- await recordDeferredPerpetualDispatch(task, taskScheduleMod);+ await recordDeferredPerpetualDispatch(pendingPerpetualDispatch, taskScheduleMod);const revived = { ...task, id: persisted.id };emitSpawn(revived);emitLog('info', `🔁 On-demand ${request.taskType} revived blocked task ${persisted.id}`, { taskId: persisted.id });diff --git a/server/services/onDemandDrain.test.js b/server/services/onDemandDrain.test.jsindex a6fe2d1929..ea7958e81d 100644--- a/server/services/onDemandDrain.test.js+++ b/server/services/onDemandDrain.test.js@@ -34,7 +34,7 @@ const mocks = vi.hoisted(() => ({clearOnDemandRequest: vi.fn(async () => {}),applyOnDemandRunResets: vi.fn(async () => true),recordExecution: vi.fn(async () => {}),- generateManagedAppImprovementTaskForType: vi.fn(async () => ({ id: 'gen-1', priority: 'HIGH' })),+ prepareManagedAppImprovementTask: vi.fn(async () => ({ task: { id: 'gen-1', priority: 'HIGH' }, pendingPerpetualDispatch: null })),generateSelfImprovementTaskForType: vi.fn(async () => ({ id: 'self-1', priority: 'HIGH' })),recordDeferredPerpetualDispatch: vi.fn(async () => {}),applyOnDemandConsent: vi.fn((t) => t),@@ -65,7 +65,7 @@ vi.mock('./taskSchedule.js', () => ({recordExecution: (...a) => mocks.recordExecution(...a),}));vi.mock('./cosTaskGenerator.js', () => ({- generateManagedAppImprovementTaskForType: (...a) => mocks.generateManagedAppImprovementTaskForType(...a),+ prepareManagedAppImprovementTask: (...a) => mocks.prepareManagedAppImprovementTask(...a),generateSelfImprovementTaskForType: (...a) => mocks.generateSelfImprovementTaskForType(...a),recordDeferredPerpetualDispatch: (...a) => mocks.recordDeferredPerpetualDispatch(...a),applyOnDemandConsent: (...a) => mocks.applyOnDemandConsent(...a),@@ -125,7 +125,7 @@ beforeEach(() => {mocks.applyOnDemandRunResets.mockResolvedValue(true);mocks.getActiveApps.mockResolvedValue([APP]);mocks.addTask.mockResolvedValue({ id: 'persisted-1' });- mocks.generateManagedAppImprovementTaskForType.mockResolvedValue({ id: 'gen-1', priority: 'HIGH' });+ mocks.prepareManagedAppImprovementTask.mockResolvedValue({ task: { id: 'gen-1', priority: 'HIGH' }, pendingPerpetualDispatch: null });mocks.generateSelfImprovementTaskForType.mockResolvedValue({ id: 'self-1', priority: 'HIGH' });mocks.drainProgrammaticOnDemandRequests.mockResolvedValue(new Set());mocks.applyOnDemandConsent.mockImplementation((t) => t);@@ -150,7 +150,7 @@ describe.each(ENGINES)('%s — a failing app registry defers, never clears', (_nconst { spawned, adapter } = makeAdapter();await drainOnDemandRequests({ state: STATE }, adapter);expect(spawned).toEqual([]);- expect(mocks.generateManagedAppImprovementTaskForType).not.toHaveBeenCalled();+ expect(mocks.prepareManagedAppImprovementTask).not.toHaveBeenCalled();expect(mocks.addTask).not.toHaveBeenCalled();});@@ -219,7 +219,7 @@ describe.each(ENGINES)('%s — on-demand metadata stamp', (_name, makeAdapter) =describe.each(ENGINES)('%s — empty-result feedback', (_name, makeAdapter) => {it('reports an empty result for a user-initiated Run', async () => {mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);- mocks.generateManagedAppImprovementTaskForType.mockResolvedValue(null);+ mocks.prepareManagedAppImprovementTask.mockResolvedValue(null);mocks.applyOnDemandRunResets.mockResolvedValue(true);const { adapter } = makeAdapter();await drainOnDemandRequests({ state: STATE }, adapter);@@ -230,7 +230,7 @@ describe.each(ENGINES)('%s — empty-result feedback', (_name, makeAdapter) => {it('stays silent for an automated drain refill', async () => {// A converging overnight drain must not turn into a pile of toasts.mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);- mocks.generateManagedAppImprovementTaskForType.mockResolvedValue(null);+ mocks.prepareManagedAppImprovementTask.mockResolvedValue(null);mocks.applyOnDemandRunResets.mockResolvedValue(false);const { adapter } = makeAdapter();await drainOnDemandRequests({ state: STATE }, adapter);@@ -272,6 +272,63 @@ describe.each(ENGINES)('%s — blocked-duplicate revive (#2614)', (_name, makeAd});});+// ── The dispatch-signature hand-off (#6871) ─────────────────────────────────+// prepareManagedAppImprovementTask returns the deferred perpetual-dispatch+// record ALONGSIDE the task instead of parking it in a WeakMap keyed on the+// task object — addTask's raw branch (cosTaskStore.js) re-wraps a multi-line+// description into a brand-new object, so the old identity-keyed record would+// silently miss unless the caller kept using the exact object the generator+// returned. These pin that the record travels through the return value+// regardless of which task-object variant addTask hands back.+describe.each(ENGINES)('%s — deferred perpetual-dispatch recording', (_name, makeAdapter) => {+ it('records the dispatch from the returned record even when addTask hands back a different task object', async () => {+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);+ mocks.prepareManagedAppImprovementTask.mockResolvedValue({+ task: { id: 'gen-1', priority: 'HIGH' },+ pendingPerpetualDispatch: { taskType: 'code-quality', appId: 'acme', signature: 'sig-1' }+ });+ // Not === the task prepare returned — the normal shape of a multi-line+ // description surviving addTask's raw branch.+ mocks.addTask.mockResolvedValue({ id: 'gen-1', priority: 'HIGH', description: 'line one' });+ const { adapter } = makeAdapter();+ await drainOnDemandRequests({ state: STATE }, adapter);++ expect(mocks.recordDeferredPerpetualDispatch).toHaveBeenCalledWith(+ { taskType: 'code-quality', appId: 'acme', signature: 'sig-1' },+ expect.anything()+ );+ });++ it('also records on the blocked-duplicate revive branch', async () => {+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);+ mocks.prepareManagedAppImprovementTask.mockResolvedValue({+ task: { id: 'gen-1', priority: 'HIGH' },+ pendingPerpetualDispatch: { taskType: 'code-quality', appId: 'acme', signature: 'sig-2' }+ });+ mocks.addTask.mockResolvedValue({ id: 'blocked-7', duplicate: true, status: 'blocked' });+ const { adapter } = makeAdapter();+ await drainOnDemandRequests({ state: STATE }, adapter);++ expect(mocks.recordDeferredPerpetualDispatch).toHaveBeenCalledWith(+ { taskType: 'code-quality', appId: 'acme', signature: 'sig-2' },+ expect.anything()+ );+ });++ it('records nothing for a non-blocked duplicate', async () => {+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);+ mocks.prepareManagedAppImprovementTask.mockResolvedValue({+ task: { id: 'gen-1', priority: 'HIGH' },+ pendingPerpetualDispatch: { taskType: 'code-quality', appId: 'acme', signature: 'sig-3' }+ });+ mocks.addTask.mockResolvedValue({ id: 'dup-1', duplicate: true, status: 'pending' });+ const { adapter } = makeAdapter();+ await drainOnDemandRequests({ state: STATE }, adapter);++ expect(mocks.recordDeferredPerpetualDispatch).not.toHaveBeenCalled();+ });+});+describe.each(ENGINES)('%s — app-review marker discipline (#978)', (_name, makeAdapter) => {it('advances one app cooldown per cycle no matter how many requests name it', async () => {mocks.getOnDemandRequests.mockResolvedValue([@@ -285,7 +342,7 @@ describe.each(ENGINES)('%s — app-review marker discipline (#978)', (_name, makit('binds the active agent only once a task actually exists', async () => {mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);- mocks.generateManagedAppImprovementTaskForType.mockResolvedValue(null);+ mocks.prepareManagedAppImprovementTask.mockResolvedValue(null);const { adapter } = makeAdapter();await drainOnDemandRequests({ state: STATE }, adapter);// The cooldown still advanced — only the bind is deferred, so a nulldiff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex b9d05151f0..7c23a7f5d2 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -16,7 +16,7 @@* drains start only on explicit dispatch and never wake on a recheck timer.* Omitted autoStart preserves legacy automatic on-demand drains.* See server/services/perpetualWork.js for the detector registry and the- * perpetual gate in cosTaskGenerator.generateManagedAppImprovementTaskForType.+ * perpetual gate in cosTaskGenerator.prepareManagedAppImprovementTask.*/import { cosEvents, emitLog } from './cosEvents.js';@@ -1084,7 +1084,7 @@ export async function triggerOnDemandTask(taskType, appId = null, {}// Optional per-request provider/model/effort pin (the PR/MR row's "Run with"// picker) — layered onto the task's metadata by- // generateManagedAppImprovementTaskForType as the MOST specific pin, above+ // prepareManagedAppImprovementTask as the MOST specific pin, above// the schedule interval and the app's own per-app override.const providerOverride = (provider || model || effort) ? { provider, model, effort } : null;const request = await updateSchedule(async (schedule) => {diff --git a/server/services/taskTypeHooks.js b/server/services/taskTypeHooks.jsindex 7125b4cac9..5c84bf2a77 100644--- a/server/services/taskTypeHooks.js+++ b/server/services/taskTypeHooks.js@@ -223,7 +223,7 @@ export function isNonCommittingCoordinatorTask(task) {* `worktreeChangesExpected` is a user-settable per-app taskMetadata override* accepted for EVERY task type (`cosValidation.js` ALLOWED keys → `POST* /api/apps/:id/task-types` → merged into `metadata` in- * cosTaskGenerator.js#generateManagedAppImprovementTaskForType). It exists to+ * cosTaskGenerator.js#prepareManagedAppImprovementTask). It exists to* mark a run's deliverable as outside the worktree; someone setting it there is* not asking to disable success validation. Ungated, a `security` task* carrying it would exit 0 having committed nothing and be recorded as a pass