Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: claim on-demand runs before preparing agents (#9455)
[._.]/ Adam Eivy050b64577331
diff --git a/server/services/cosIdleReviewParity.test.js b/server/services/cosIdleReviewParity.test.jsindex fa084a9e55..50d6960b98 100644--- a/server/services/cosIdleReviewParity.test.js+++ b/server/services/cosIdleReviewParity.test.js@@ -66,7 +66,11 @@ vi.mock('./taskSchedule.js', async (importActual) => ({mocks.requestReads++;return mocks.requestsAfterPriority0 && mocks.requestReads === 1 ? [] : [...mocks.requests];},- clearOnDemandRequest: async (id) => { mocks.requests = mocks.requests.filter((r) => r.id !== id); },+ clearOnDemandRequest: async (id) => {+ const request = mocks.requests.find((r) => r.id === id);+ mocks.requests = mocks.requests.filter((r) => r.id !== id);+ return request ?? null;+ },applyOnDemandRunResets: async () => true,recordExecution: async (type, appId) => { mocks.executions.push({ type, appId }); },recordPerpetualDispatch: async (...args) => { mocks.perpetualDispatches.push(args); },@@ -237,7 +241,10 @@ describe.each(engines)('%s idle admission public boundary', (name, run) => {});it.each([false, true])('closes the correct stolen card after late request preparation (no-work: %s)', async (noWork) => {- mocks.requests = [request()];+ mocks.requests = [{+ ...request(), origin: 'user',+ providerOverride: { provider: 'example-provider', model: 'example-model', effort: 'high' },+ }];mocks.requestsAfterPriority0 = true;mocks.cards['preflight-demand-1'] = { outcome: 'waiting' };mocks.noWork = noWork;@@ -249,6 +256,10 @@ describe.each(engines)('%s idle admission public boundary', (name, run) => {outcome: noWork ? 'nothing-to-do' : 'handed-off', taskId: readyTasks()[0]?.id ?? null,});expect(mocks.perpetualDispatches).toHaveLength(noWork ? 0 : 1);+ if (!noWork) expect(readyTasks()[0].metadata).toMatchObject({+ onDemand: true, onDemandOrigin: 'user',+ provider: 'example-provider', model: 'example-model', effort: 'high',+ });if (!noWork) expect(mocks.perpetualDispatches[0]).toEqual(['code-quality', 'example-app', JSON.stringify({ taskType: 'code-quality', candidates: ['example-work'] })]);if (noWork) expect(mocks.activity['example-app'].activeAgentId).toBeUndefined();});diff --git a/server/services/cosTaskGenerator.idleReviewSteal.test.js b/server/services/cosTaskGenerator.idleReviewSteal.test.jsindex 8419aac2f2..ccc2416696 100644--- a/server/services/cosTaskGenerator.idleReviewSteal.test.js+++ b/server/services/cosTaskGenerator.idleReviewSteal.test.js@@ -22,7 +22,7 @@ const preflight = vi.hoisted(() => ({ reporter: vi.fn((cardId) => ({ boundTo: caconst pipeline = vi.hoisted(() => ({ securityPreflight: vi.fn(async () => ({ skipped: true, reason: 'no-external-open-prs' })) }));const scheduleMocks = vi.hoisted(() => ({requests: [],- clearOnDemandRequest: vi.fn(async () => ({})),+ clearOnDemandRequest: vi.fn(),}));vi.mock('./preflightTaskCard.js', async (importActual) => ({@@ -65,6 +65,7 @@ vi.mock('./taskSchedule.js', async (importActual) => ({getNextTaskType: vi.fn(async () => null),}));+const { applyOnDemandRunResets, recordExecution, getNextTaskType } = await import('./taskSchedule.js');const { generateIdleReviewTask, prepareManagedAppImprovementTask } = await import('./cosTaskGenerator.js');const STATE = { config: { improvementEnabled: true, appReviewCooldownMs: 0 }, stats: {} };@@ -76,9 +77,65 @@ beforeEach(() => {preflight.reporter.mockImplementation((cardId) => ({ boundTo: cardId }));pipeline.securityPreflight.mockResolvedValue({ skipped: true, reason: 'no-external-open-prs' });scheduleMocks.requests = [];+ scheduleMocks.clearOnDemandRequest.mockImplementation(async (id) => {+ const index = scheduleMocks.requests.findIndex(request => request.id === id);+ return index === -1 ? null : scheduleMocks.requests.splice(index, 1)[0];+ });});describe('idle review stealing a queued on-demand request', () => {+ it('leaves another owner or cancelled receipt alone', async () => {+ scheduleMocks.requests = [request()];+ scheduleMocks.clearOnDemandRequest.mockResolvedValue(null);+ const result = await generateIdleReviewTask(STATE);+ expect(result).toEqual({ task: null, pendingPerpetualDispatch: null, preflightCardId: null });+ expect(applyOnDemandRunResets).not.toHaveBeenCalled();+ expect(recordExecution).not.toHaveBeenCalled();+ expect(getNextTaskType).not.toHaveBeenCalled();+ expect(pipeline.securityPreflight).not.toHaveBeenCalled();+ expect(preflight.reporter).not.toHaveBeenCalled();+ });++ it.each([0, 1])('only idle consumer %i owns preparation and the card', async (winner) => {+ const receipt = request({ targetPullRequest: 42 });+ scheduleMocks.requests = [receipt];+ const firstClaimReady = Promise.withResolvers();+ const claimsReady = Promise.withResolvers();+ const claims = [Promise.withResolvers(), Promise.withResolvers()];+ const preflightEntered = Promise.withResolvers();+ const preflightRelease = Promise.withResolvers();+ let count = 0;+ const queue = [receipt];+ scheduleMocks.clearOnDemandRequest.mockImplementation(async () => {+ const index = count++;+ if (count === 1) firstClaimReady.resolve();+ if (count === 2) claimsReady.resolve();+ await claims[index].promise;+ return queue.shift() ?? null;+ });+ pipeline.securityPreflight.mockImplementation(async () => {+ preflightEntered.resolve();+ await preflightRelease.promise;+ return { skipped: true, reason: 'no-external-open-prs' };+ });+ const drains = [generateIdleReviewTask(STATE)];+ await firstClaimReady.promise;+ drains.push(generateIdleReviewTask(STATE));+ await claimsReady.promise;+ claims[winner].resolve();+ await preflightEntered.promise;+ claims[1 - winner].resolve();+ expect(await drains[1 - winner]).toEqual({+ task: null, pendingPerpetualDispatch: null, preflightCardId: null,+ });+ expect(applyOnDemandRunResets).toHaveBeenCalledTimes(1);+ expect(recordExecution).toHaveBeenCalledTimes(1);+ expect(pipeline.securityPreflight).toHaveBeenCalledTimes(1);+ preflightRelease.resolve();+ expect((await drains[winner]).preflightCardId).toBe('preflight-demand-1');+ expect(progressOf()).toEqual({ boundTo: 'preflight-demand-1' });+ });+it('carries the human Run card out to the tier that rules on the task', async () => {scheduleMocks.requests = [request()];const result = await generateIdleReviewTask(STATE);diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex d34b0a8126..47996367c9 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -34,7 +34,7 @@ import { applyAppPlaceholders } from '../lib/appPromptPlaceholders.js';import { renderOrPrependSection } from '../lib/promptSectionRenderer.js';import { currentTaskTypeName } from '../lib/scheduledTaskTypes.js';import { isPlainObject } from '../lib/objects.js';-import { hasQuotaBurnProvenance, isManualOnDemandRequest } from '../lib/quotaBurnOrigin.js';+import { hasQuotaBurnProvenance, isManualOnDemandRequest, onDemandRequestMetadata } from '../lib/quotaBurnOrigin.js';import { isAutoApprovableInvestigation } from '../lib/investigationTasks.js';import { parsePlanItems, extractAllIds, findInProgressIds, pickFirstAvailable, diagnoseUnpickablePlan } from '../lib/planIds.js';import { formatSkipCauses } from '../lib/perpetualSkipCauses.js';@@ -2011,14 +2011,20 @@ async function generateManagedAppImprovementTask(app, state, { ignoreTaskId = nu// A stolen request's run parameters (a quota-burn or maintenance step's// `params`), forwarded exactly as the on-demand drain forwards them.let stolenRunOverrides = null;+ let stolenRequest = null;if (appRequests.length > 0) {- const request = appRequests[0];+ const request = await taskSchedule.clearOnDemandRequest(appRequests[0].id);+ if (!request) {+ // Another drain (or cancellation) owns this receipt. Returning its card+ // would let the idle tier close the winner's still-running preflight.+ return { task: null, pendingPerpetualDispatch: null, preflightCardId: null };+ }+ stolenRequest = request;targetPullRequest = request.targetPullRequest ?? null;stolenRunOverrides = request.burn?.overrides?.params ?? null;const { cardIdForRequest } = await import('./preflightTaskCard.js');stolenCardId = cardIdForRequest(request);- await taskSchedule.clearOnDemandRequest(request.id);// Only a human "Run" may clear the drain's brakes (park state, dispatch// count); the policy lives in applyOnDemandRunResets so this idle-review// path can't drift from the shared on-demand drain — without it,@@ -2067,6 +2073,7 @@ async function generateManagedAppImprovementTask(app, state, { ignoreTaskId = nutargetPullRequest,onDemand: selectionReason === 'on-demand',runOverrides: stolenRunOverrides,+ providerOverride: stolenRequest?.providerOverride ?? null,// The deterministic pre-agent work (pr-reviewer's security preflight)// reports into the stolen Run's card as it runs, exactly as it does on the// on-demand drain — this is the whole reason the card is opened early.@@ -2075,7 +2082,10 @@ async function generateManagedAppImprovementTask(app, state, { ignoreTaskId = nuconst { task, pendingPerpetualDispatch } = prepared;// 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);+ if (stolenRequest) {+ applyOnDemandConsent(task);+ if (task) task.metadata = { ...(task.metadata || {}), ...onDemandRequestMetadata(stolenRequest) };+ }// The card is closed by whoever rules on the task (the spawn tier), not here:// a task this returns can still be refused a slot, and a card closed// `handed-off` would then name an agent that never started.@@ -2175,9 +2185,9 @@ export async function drainProgrammaticOnDemandRequests({ taskScheduleMod, reque// can hold the same request; `clearOnDemandRequest` is a serialized// read-modify-write that returns the record only to the caller that removed// it, and returns null to the loser. Without this check one "Run Now" would- // spend two describe/render batches and toast twice — the agent path gets- // the same protection from `addTask`'s duplicate detection, which a handler- // that queues nothing has no equivalent of.+ // spend two describe/render batches and toast twice. Agent preparation+ // takes the same claim before any preflight work; task-store deduplication+ // alone happens too late to protect either lane's preparation.const claimed = await taskScheduleMod.clearOnDemandRequest(request.id);if (!claimed) continue;diff --git a/server/services/onDemandDrain.js b/server/services/onDemandDrain.jsindex adf9b3fee4..c842287d7c 100644--- a/server/services/onDemandDrain.js+++ b/server/services/onDemandDrain.js@@ -101,7 +101,7 @@ export async function drainOnDemandRequests(ctx, adapter) {return { schedule };}- for (const request of onDemandRequests) {+ for (const queuedRequest of onDemandRequests) {// This request's programmatic-phase card, or null for the automated origins// that are never carded — `cardIdForRequest` owns that policy, so this// engine and the idle-review steal cannot disagree about who gets a card.@@ -110,43 +110,44 @@ export async function drainOnDemandRequests(ctx, adapter) {// BEFORE it reads the task file, which matters because an automated refill// drain would otherwise pay a cold whole-file parse per request just to// discover it has no card.- const cardId = cardIdForRequest(request);+ const queuedCardId = cardIdForRequest(queuedRequest);// Already handled above (and its request cleared) — `onDemandRequests` is// a snapshot taken before that drain.- if (handledProgrammatically.has(request.id)) {- await finishPreflightCard(cardId, { outcome: 'programmatic' });+ if (handledProgrammatically.has(queuedRequest.id)) {+ await finishPreflightCard(queuedCardId, { outcome: 'programmatic' });continue;}- // Open the card BEFORE the capacity check, so a Run that has to wait for a- // free slot still shows up on the Tasks page as waiting. Until this existed- // nothing appeared there until an agent task did — which for pr-reviewer is- // after the whole security preflight — and the click read as a no-op. Only- // a human's Run is carded: a drain refill or a quota-burn step has nobody- // waiting on it, and carding those would fill the page with noise. Repeat- // cycles re-enter here and `addTask` rejects the duplicate id, so a request- // that waits several cycles keeps ONE card rather than gaining one per tick.- if (cardId) {+ // Keep waiting requests visible without claiming capacity-deferred work.+ // Otherwise only the claim winner opens/reports into the card. Repeated+ // waiting cycles are idempotent: startPreflightCard deduplicates by id.+ const openCard = async (record = queuedRequest) => {+ if (!cardIdForRequest(record)) return;await startPreflightCard({- requestId: request.id,- taskType: request.taskType,- appId: request.appId ?? null,- appName: apps.find(app => app.id === request.appId)?.name || null,- targetPullRequest: request.targetPullRequest ?? null,+ requestId: record.id,+ taskType: record.taskType,+ appId: record.appId ?? null,+ appName: apps.find(app => app.id === record.appId)?.name || null,+ targetPullRequest: record.targetPullRequest ?? null,});- }+ };// Abandon this request: clear it from the queue and tell the user's card why.// One helper so the log line and the card can never name different reasons —// the same hand-mirroring this module's header exists to eliminate.const dropRequest = async (level, reason, note) => {- emitLog(level, `On-demand request dropped — ${note}`, { requestId: request.id, taskType: request.taskType });- await taskScheduleMod.clearOnDemandRequest(request.id);- await finishPreflightCard(cardId, { outcome: 'failed', reason, note });+ const claimed = await taskScheduleMod.clearOnDemandRequest(queuedRequest.id);+ if (!claimed) return;+ await openCard(claimed);+ emitLog(level, `On-demand request dropped — ${note}`, { requestId: queuedRequest.id, taskType: queuedRequest.taskType });+ await finishPreflightCard(cardIdForRequest(claimed), { outcome: 'failed', reason, note });};- if (capacityExhausted()) break;+ if (capacityExhausted()) {+ await openCard();+ break;+ }if (!isImprovementEnabled(state)) {await dropRequest('warn', 'improvement-disabled',@@ -155,9 +156,9 @@ export async function drainOnDemandRequests(ctx, adapter) {}// Removed tasks never run; only automated requests honor schedule disablement.- if (!schedule.tasks[request.taskType] || (!isManualOnDemandRequest(request) && !schedule.tasks[request.taskType].enabled)) {+ if (!schedule.tasks[queuedRequest.taskType] || (!isManualOnDemandRequest(queuedRequest) && !schedule.tasks[queuedRequest.taskType].enabled)) {await dropRequest('info', 'task-type-disabled',- `The scheduled task type '${request.taskType}' is disabled or no longer registered.`);+ `The scheduled task type '${queuedRequest.taskType}' is disabled or no longer registered.`);continue;}@@ -173,11 +174,11 @@ export async function drainOnDemandRequests(ctx, adapter) {// Determine target app (if any)let targetApp = null;- if (request.appId) {- targetApp = apps.find(a => a.id === request.appId);+ if (queuedRequest.appId) {+ targetApp = apps.find(a => a.id === queuedRequest.appId);if (!targetApp) {await dropRequest('warn', 'app-unknown',- `App '${request.appId}' is no longer active, so this run has nothing to target.`);+ `App '${queuedRequest.appId}' is no longer active, so this run has nothing to target.`);continue;}}@@ -187,15 +188,24 @@ export async function drainOnDemandRequests(ctx, adapter) {// safe only when the final `canSpawn` could not deny; per-project capacity// can deny while global slots remain, which discarded the prepared task and// closed the visible card without ever creating an agent task.- if (projectCapacityExhausted(targetApp?.id ?? request.appId ?? null)) {+ if (projectCapacityExhausted(targetApp?.id ?? queuedRequest.appId ?? null)) {+ await openCard();emitLog('debug', `On-demand request deferred — per-project agent limit reached`, {- requestId: request.id,- taskType: request.taskType,+ requestId: queuedRequest.id,+ taskType: queuedRequest.taskType,});continue;}- await taskScheduleMod.clearOnDemandRequest(request.id);+ // Both engines can hold this snapshot. Only the atomic removal winner+ // owns preparation, accounting, and the shared card's terminal outcome.+ const request = await taskScheduleMod.clearOnDemandRequest(queuedRequest.id);+ if (!request) continue;+ // Receipts are immutable while queued; resolve dispatch from the claimed+ // record as well, rather than keeping snapshot objects across ownership.+ targetApp = request.appId ? apps.find(app => app.id === request.appId) : null;+ const cardId = cardIdForRequest(request);+ await openCard(request);// Off the queue and into preparation. A task type with its own preflight// (pr-reviewer) has no `prepare` step and reports its real first step// moments later, so this is a no-op there rather than a competing claim.diff --git a/server/services/onDemandDrain.test.js b/server/services/onDemandDrain.test.jsindex d946adc422..eb4c2f169f 100644--- a/server/services/onDemandDrain.test.js+++ b/server/services/onDemandDrain.test.js@@ -31,7 +31,7 @@ const mocks = vi.hoisted(() => ({reviveBlockedTask: vi.fn(async () => {}),loadSchedule: vi.fn(async () => ({ tasks: { 'code-quality': { enabled: true } } })),getOnDemandRequests: vi.fn(async () => []),- clearOnDemandRequest: vi.fn(async () => {}),+ clearOnDemandRequest: vi.fn(),applyOnDemandRunResets: vi.fn(async () => true),recordExecution: vi.fn(async () => {}),prepareManagedAppImprovementTask: vi.fn(async () => ({ task: { id: 'gen-1', priority: 'HIGH' }, pendingPerpetualDispatch: null, skip: null })),@@ -144,6 +144,8 @@ beforeEach(() => {mocks.withStateLock.mockImplementation(async (fn) => fn());mocks.loadSchedule.mockResolvedValue({ tasks: { 'code-quality': { enabled: true } } });mocks.getOnDemandRequests.mockResolvedValue([]);+ mocks.clearOnDemandRequest.mockImplementation(async (id) =>+ (await mocks.getOnDemandRequests()).find(request => request.id === id) ?? null);mocks.applyOnDemandRunResets.mockResolvedValue(true);mocks.getActiveApps.mockResolvedValue([APP]);mocks.addTask.mockResolvedValue({ id: 'persisted-1' });@@ -608,3 +610,97 @@ describe('preflight task card', () => {expect(mocks.finishPreflightDispatch).toHaveBeenCalledWith('preflight-req-1');});});+++describe('atomic on-demand preparation ownership', () => {+ it.each([0, 1])('prepares once when engine %i wins overlapping snapshots', async (winner) => {+ const receipt = appRequest();+ const queue = [receipt];+ const firstClaimReady = Promise.withResolvers();+ const claimsReady = Promise.withResolvers();+ const claims = [Promise.withResolvers(), Promise.withResolvers()];+ const preparationEntered = Promise.withResolvers();+ const preparationRelease = Promise.withResolvers();+ let claimCount = 0;+ mocks.getOnDemandRequests.mockResolvedValue([receipt]);+ mocks.clearOnDemandRequest.mockImplementation(async () => {+ const index = claimCount++;+ if (claimCount === 1) firstClaimReady.resolve();+ if (claimCount === 2) claimsReady.resolve();+ await claims[index].promise;+ return queue.shift() ?? null;+ });+ mocks.prepareManagedAppImprovementTask.mockImplementation(async () => {+ preparationEntered.resolve();+ await preparationRelease.promise;+ return { task: { id: 'winner-task' }, pendingPerpetualDispatch: null };+ });+ const engines = [generatorAdapter(), dequeueAdapter()];+ const drains = [drainOnDemandRequests({ state: STATE }, engines[0].adapter)];+ await firstClaimReady.promise;+ drains.push(drainOnDemandRequests({ state: STATE }, engines[1].adapter));+ await claimsReady.promise;+ claims[winner].resolve();+ await preparationEntered.promise;+ claims[1 - winner].resolve();+ await drains[1 - winner];++ // A late loser must not close or reset a card while the winner is working.+ expect(mocks.prepareManagedAppImprovementTask).toHaveBeenCalledTimes(1);+ expect(mocks.applyOnDemandRunResets).toHaveBeenCalledTimes(1);+ expect(mocks.recordExecution).toHaveBeenCalledTimes(1);+ expect(mocks.startPreflightCard).toHaveBeenCalledTimes(1);+ expect(mocks.reportPreflightStep).toHaveBeenCalledTimes(1);+ expect(mocks.finishPreflightCard).not.toHaveBeenCalled();+ expect(mocks.finishPreflightDispatch).not.toHaveBeenCalled();++ preparationRelease.resolve();+ await Promise.all(drains);+ expect(mocks.addTask).toHaveBeenCalledTimes(1);+ expect(engines[winner].spawned).toHaveLength(1);+ expect(engines[1 - winner].spawned).toEqual([]);+ expect(queue).toEqual([]);+ });++ it('does not prepare install-wide work cancelled after the snapshot', async () => {+ mocks.getOnDemandRequests.mockResolvedValue([appRequest({ appId: null })]);+ mocks.clearOnDemandRequest.mockResolvedValue(null);+ await drainOnDemandRequests({ state: STATE }, generatorAdapter().adapter);+ expect(mocks.generateSelfImprovementTaskForType).not.toHaveBeenCalled();+ expect(mocks.applyOnDemandRunResets).not.toHaveBeenCalled();+ expect(mocks.recordExecution).not.toHaveBeenCalled();+ expect(mocks.startPreflightCard).not.toHaveBeenCalled();+ expect(mocks.finishPreflightDispatch).not.toHaveBeenCalled();+ expect(mocks.saveState).not.toHaveBeenCalled();+ });++ it("does not fail another owner's card when a stale snapshot hits a drop gate", async () => {+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);+ mocks.isImprovementEnabled.mockReturnValue(false);+ mocks.clearOnDemandRequest.mockResolvedValue(null);+ await drainOnDemandRequests({ state: STATE }, generatorAdapter().adapter);+ expect(mocks.startPreflightCard).not.toHaveBeenCalled();+ expect(mocks.finishPreflightCard).not.toHaveBeenCalled();+ });++ it('dispatches the claimed receipt with its scope and overrides', async () => {+ const claimed = appRequest({+ targetPullRequest: { number: 42, repo: 'example/repo' }, origin: 'user',+ providerOverride: { provider: 'example-provider', model: 'example-model' },+ burn: { overrides: { params: { mode: 'example-mode' } } },+ });+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);+ mocks.clearOnDemandRequest.mockResolvedValue(claimed);+ await drainOnDemandRequests({ state: STATE }, generatorAdapter().adapter);+ expect(mocks.applyOnDemandRunResets).toHaveBeenCalledWith(claimed, APP.id);+ expect(mocks.prepareManagedAppImprovementTask).toHaveBeenCalledWith('code-quality', APP, STATE,+ expect.objectContaining({+ targetPullRequest: claimed.targetPullRequest, providerOverride: claimed.providerOverride,+ runOverrides: { mode: 'example-mode' },+ }));+ expect(mocks.addTask.mock.calls[0][0].metadata.onDemandOrigin).toBe('user');+ expect(mocks.startPreflightCard).toHaveBeenCalledWith(expect.objectContaining({+ targetPullRequest: claimed.targetPullRequest,+ }));+ });+});