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
collapse the preflight-card close into one shared body and one write
[._.]/ Adam Eivy7fce51588b6f
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex 5051ad2961..a1fae2ad29 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -458,10 +458,13 @@ describe('deferred imports stay deferred (#6156)', () => {// module-organization rule requires, instantiates one more module in every// closure that reaches the barrel. There is nothing to narrow — the leaf pulls// nothing — so raise by exactly that delta and keep the existing headroom.-// The idle-review steal's card hand-off adds one test file and no module: it+// The idle-review steal's card hand-off measures +1: one new test file, which// reaches cosTaskGenerator.js through `await import()` (after its vi.mocks, as-// that suite must), so its static closure is itself alone and the measured-// delta is +1. Nothing to narrow — a deferred import IS the narrow form.+// that suite must), so its static closure is itself alone. Its one new module+// edge — preflightTaskCard.js → taskScheduleConstants.js, for the "only a USER+// origin is carded" policy — is free: onDemandDrain.js already reached that+// leaf directly, and gave up its own edge to the same shared helper. Nothing to+// narrow — a deferred import IS the narrow form.const MAX_STATIC_INSTANTIATIONS = 103521;diff --git a/server/services/cos.js b/server/services/cos.jsindex 9c92b039fb..e0688cc8fe 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -159,7 +159,7 @@ import {// predicate are shared with the scheduler unit tests so they exercise the real// guards instead of a local replica. The async tiers stay here as// `spawnDequeuePriorityN(ctx)` helpers.-import { createDequeueCapacity, countRunningAgentsByLocalEndpoint, isIdleTierEligible } from './cosDequeue.js';+import { closeStolenIdleReviewCard, createDequeueCapacity, countRunningAgentsByLocalEndpoint, isIdleTierEligible } from './cosDequeue.js';import { buildLocalEndpointSlotContext, localEndpointCapacityError } from './cosLocalEndpointSlots.js';import {initializePersistentMindSupervisor,@@ -1125,14 +1125,9 @@ async function spawnDequeuePriority3IdleReview(ctx) {cosEvents.emit('task:ready', idleTask);capacity.trackSpawn(idleTask);}- // This tier may have STOLEN a human's on-demand request (see- // generateManagedAppImprovementTask). Closing its card is this tier's job- // because only here is the spawn decision final. Guarded so an ordinary- // idle tick — which has no card — pays neither the import nor a task read.- if (preflightCardId) {- const { finishPreflightDispatch } = await import('./preflightTaskCard.js');- await finishPreflightDispatch(preflightCardId, admitted ? idleTask.id : null);- }+ // This tier may have STOLEN a human's on-demand request. Closing its card is+ // the tier's job because only here is the admission decision final.+ await closeStolenIdleReviewCard(preflightCardId, admitted ? idleTask : null);}}diff --git a/server/services/cosDequeue.js b/server/services/cosDequeue.jsindex fd259eb2fe..089b11db55 100644--- a/server/services/cosDequeue.js+++ b/server/services/cosDequeue.js@@ -155,3 +155,20 @@ export function isIdleTierEligible({ spawned, hasPendingUserTasks, idleReviewEna&& !hasPendingUserTasks&& autonomyMode === 'execute';}++/**+ * Close the preflight card of a human "Run" this tier STOLE, now that the+ * admission decision on the task it produced is final (`admittedTask` is that+ * task, or null when none will run).+ *+ * Lives beside `isIdleTierEligible` for the same reason: both spawn engines run+ * their own copy of the idle-review tier, and anything the two must agree on+ * belongs in ONE body rather than in a pair of blocks a grep test has to police.+ * The import is deferred so the far more common uncarded tick — every idle tick+ * that did not steal a request — pays neither the module nor a task read.+ */+export async function closeStolenIdleReviewCard(cardId, admittedTask) {+ if (!cardId) return null;+ const { finishPreflightDispatch } = await import('./preflightTaskCard.js');+ return finishPreflightDispatch(cardId, admittedTask?.id ?? null);+}diff --git a/server/services/cosTaskGenerator.idleReviewSteal.test.js b/server/services/cosTaskGenerator.idleReviewSteal.test.jsindex fa279a6bfd..b1261c1dd1 100644--- a/server/services/cosTaskGenerator.idleReviewSteal.test.js+++ b/server/services/cosTaskGenerator.idleReviewSteal.test.js@@ -11,8 +11,9 @@* 15-minute orphan sweep mislabelled it `interrupted`.** These pin the hand-off: the steal binds the pre-agent progress reporter to- * that card, and carries the card id out to the tier — the only place the spawn- * decision is final, and therefore the only place that may close it.+ * that card, and carries the card id out to the tier — the only place the+ * admission decision is final, and therefore the only place that may close it+ * (cosDequeue#closeStolenIdleReviewCard).*/import { describe, it, expect, vi, beforeEach } from 'vitest';@@ -68,7 +69,7 @@ const { generateIdleReviewTask } = await import('./cosTaskGenerator.js');const STATE = { config: { improvementEnabled: true, appReviewCooldownMs: 0 }, stats: {} };const request = (overrides = {}) => ({ id: 'demand-1', appId: 'example-app', taskType: 'pr-reviewer', ...overrides });-const progressOf = () => pipeline.securityPreflight.mock.calls.at(-1)?.[5]?.progress;+const progressOf = () => pipeline.securityPreflight.mock.calls.at(-1)?.at(-1)?.progress;beforeEach(() => {vi.clearAllMocks();@@ -93,7 +94,6 @@ describe('idle review stealing a queued on-demand request', () => {it('binds the pre-agent progress reporter to that card', async () => {scheduleMocks.requests = [request()];await generateIdleReviewTask(STATE);- expect(preflight.reporter).toHaveBeenCalledWith('preflight-demand-1');expect(progressOf()).toEqual({ boundTo: 'preflight-demand-1' });});@@ -112,32 +112,3 @@ describe('idle review stealing a queued on-demand request', () => {});});-/**- * Both spawn engines have their own idle-review tier — `dequeueNextTask`'s in- * cos.js and `evaluateTasks`' here — and each rules on the task the steal- * produced independently. A tier that forgets the close leaves exactly the card- * this file exists for, so pin that neither can drift away from it.- */-const tierBody = (source, name) => {- const start = source.indexOf(`async function ${name}(`);- expect(start, `${name} must exist`).toBeGreaterThan(-1);- const next = source.indexOf('\n}\n', start);- return source.slice(start, next);-};--describe('both idle-review tiers close the stolen card', () => {- it.each([- ['cos.js', 'spawnDequeuePriority3IdleReview'],- ['cosTaskGenerator.js', 'spawnPriority4IdleReview'],- ])('%s#%s', async (file, name) => {- const { readFileSync } = await import('fs');- const { fileURLToPath } = await import('url');- const { dirname, join } = await import('path');- const body = tierBody(readFileSync(join(dirname(fileURLToPath(import.meta.url)), file), 'utf-8'), name);- expect(body).toContain('finishPreflightDispatch');- // The close must report the ADMISSION, not merely that a task was built:- // a card closed `handed-off` for a task the tier then refused names an- // agent that never started.- expect(body).toMatch(/finishPreflightDispatch\(preflightCardId, admitted \? idleTask\.id : null\)/);- });-});diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 6043f67b7d..f742148ddd 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -48,7 +48,7 @@ import { getActiveApps, getAppTaskTypeOverrides } from './apps.js';// The single Priority-0 on-demand loop body, shared with the dequeueNextTask// engine in cos.js so the two can no longer drift (#6618).import { drainOnDemandRequests } from './onDemandDrain.js';-import { isIdleTierEligible } from './cosDequeue.js';+import { closeStolenIdleReviewCard, isIdleTierEligible } from './cosDequeue.js';import { resolveAgentProviderPin } from './appTaskProviderPin.js';import { getTaskTypeConfidence } from './taskLearning.js';import { classifySafetyKind, requiresSafetyApproval } from './taskLearning/safetyKind.js';@@ -72,7 +72,7 @@ import { TIMED_COOLDOWN_BLOCKED_CATEGORIES } from '../lib/taskBlockCategories.js// reads the same set back via isClaimFlowTask().import { CLAIM_FLOW_TASK_TYPES } from '../lib/claimFlowTaskTypes.js';import { ServerError } from '../lib/errorHandler.js';-import { isReconcileDrainTaskType, isUserOriginRequest } from './taskScheduleConstants.js';+import { isReconcileDrainTaskType } from './taskScheduleConstants.js';import { isProgrammaticScheduledTaskType, requiresInstallWideTarget } from './taskScheduleRegistry.js';import {appendClaimOverrideContext,@@ -1033,14 +1033,9 @@ async function spawnPriority4IdleReview(ctx) {tasksToSpawn.push(idleTask);trackSpawn(idleTask);}- // This tier may have STOLEN a human's on-demand request (see- // generateManagedAppImprovementTask). Closing its card is this tier's job- // because only here is the spawn decision final. Guarded so an ordinary- // idle tick — which has no card — pays neither the import nor a task read.- if (preflightCardId) {- const { finishPreflightDispatch } = await import('./preflightTaskCard.js');- await finishPreflightDispatch(preflightCardId, admitted ? idleTask.id : null);- }+ // This tier may have STOLEN a human's on-demand request. Closing its card is+ // the tier's job because only here is the admission decision final.+ await closeStolenIdleReviewCard(preflightCardId, admitted ? idleTask : null);}}}@@ -1954,19 +1949,16 @@ async function generateManagedAppImprovementTask(app, state, { ignoreTaskId = nu// silently promote the user's one-row click into a full-repo review — the// same widening the perpetual-refill skip guards against on the other side.let targetPullRequest = null;- // The programmatic-phase card a human's "Run" already opened, when this path- // is the one that ends up serving that Run. Stealing the request means- // inheriting its card: the on-demand drain will never see the request again,- // so if this path reports nothing the card is stranded at "Waiting for a free- // task slot" — while the agent it produced is visibly already working — until- // the orphan sweep mislabels it `interrupted` 15 minutes later.+ // The card a human's "Run" already opened, when this steal is serving one —+ // stealing the request means inheriting its card, because the on-demand drain+ // will never see that request again. See `finishPreflightDispatch`.let stolenCardId = null;if (appRequests.length > 0) {const request = appRequests[0];targetPullRequest = request.targetPullRequest ?? null;- const { preflightCardId } = await import('./preflightTaskCard.js');- stolenCardId = isUserOriginRequest(request) ? preflightCardId(request.id) : 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@@ -1983,7 +1975,10 @@ async function generateManagedAppImprovementTask(app, state, { ignoreTaskId = nuif (!nextTypeResult) {emitLog('info', `No app improvement tasks are eligible for ${app.name} based on schedule`);- return { task: null, pendingPerpetualDispatch: null, preflightCardId: null };+ // `stolenCardId`, never a literal null: this branch happens to be the one+ // where no steal occurred, but a later early return added above it would+ // strand the card all over again.+ return { task: null, pendingPerpetualDispatch: null, preflightCardId: stolenCardId };}nextType = nextTypeResult.taskType;diff --git a/server/services/onDemandDrain.js b/server/services/onDemandDrain.jsindex 159bf2af23..009a03b9c3 100644--- a/server/services/onDemandDrain.js+++ b/server/services/onDemandDrain.js@@ -33,9 +33,8 @@ import { getActiveApps } from './apps.js';import { loadState, saveState, withStateLock, isImprovementEnabled } from './cosState.js';import { markAppReviewCooldown, bindAppReviewAgent } from './appActivity.js';import { isManualOnDemandRequest, onDemandRequestMetadata } from '../lib/quotaBurnOrigin.js';-import { isUserOriginRequest } from './taskScheduleConstants.js';import { addTask, reviveBlockedTask } from './cosTaskStore.js';-import { finishPreflightCard, finishPreflightDispatch, preflightCardId, reportPreflightStep, startPreflightCard } from './preflightTaskCard.js';+import { cardIdForRequest, finishPreflightCard, finishPreflightDispatch, reportPreflightStep, startPreflightCard } from './preflightTaskCard.js';/*** Drain the on-demand request queue, generating + persisting a task per request@@ -96,13 +95,14 @@ export async function drainOnDemandRequests(ctx, adapter) {for (const request of onDemandRequests) {// This request's programmatic-phase card, or null for the automated origins- // that are never carded. Derived rather than stamped on the request: the id- // is a pure function of the request id, so every report and close site below- // needs no branch of its own — a null id short-circuits each of them 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 = isUserOriginRequest(request) ? preflightCardId(request.id) : null;+ // that are never carded — `cardIdForRequest` owns that policy, so this+ // engine and the idle-review steal cannot disagree about who gets a card.+ // Derived rather than stamped on the request, so every report and close site+ // below needs no branch of its own: a null id short-circuits each of them+ // 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);// Already handled above (and its request cleared) — `onDemandRequests` is// a snapshot taken before that drain.@@ -280,7 +280,7 @@ export async function drainOnDemandRequests(ctx, adapter) {// refill with no task) still owes the card a close — a card left open would// keep animating until the orphan sweep reaped it. Already-closed cards are// a no-op, so the specific reason each path recorded above survives.- await finishPreflightCard(cardId, { outcome: 'nothing-to-do' });+ await finishPreflightDispatch(cardId);if (userInitiated) {const preparationMs = Math.round(performance.now() - preparationStartedAt);emitLog('info', `On-demand preparation finished: ${request.taskType} (${request.id}) — queue wait ${queueWaitMs ?? 'unknown'}ms, preparation ${preparationMs}ms, ${task ? 'task generated' : 'no task generated'}`, {diff --git a/server/services/onDemandDrain.test.js b/server/services/onDemandDrain.test.jsindex 0cf2ce7c3c..a2dc89e3bb 100644--- a/server/services/onDemandDrain.test.js+++ b/server/services/onDemandDrain.test.js@@ -69,14 +69,21 @@ vi.mock('./taskSchedule.js', () => ({applyOnDemandRunResets: (...a) => mocks.applyOnDemandRunResets(...a),recordExecution: (...a) => mocks.recordExecution(...a),}));-vi.mock('./preflightTaskCard.js', () => ({- preflightCardId: (requestId) => `preflight-${requestId}`,- startPreflightCard: (...a) => mocks.startPreflightCard(...a),- recordPreflightOutcome: (...a) => mocks.recordPreflightOutcome(...a),- reportPreflightStep: (...a) => mocks.reportPreflightStep(...a),- finishPreflightCard: (...a) => mocks.finishPreflightCard(...a),- finishPreflightDispatch: (...a) => mocks.finishPreflightDispatch(...a),-}));+// Only the card's I/O is doubled. `cardIdForRequest` keeps the REAL origin+// policy (`isUserOriginRequest` is a pure leaf), so the 'opens no card for an+// automated origin' tests below still exercise the decision, not a stub of it.+vi.mock('./preflightTaskCard.js', async () => {+ const { isUserOriginRequest } = await vi.importActual('./taskScheduleConstants.js');+ return {+ preflightCardId: (requestId) => `preflight-${requestId}`,+ cardIdForRequest: (request) => (isUserOriginRequest(request) ? `preflight-${request.id}` : null),+ startPreflightCard: (...a) => mocks.startPreflightCard(...a),+ recordPreflightOutcome: (...a) => mocks.recordPreflightOutcome(...a),+ reportPreflightStep: (...a) => mocks.reportPreflightStep(...a),+ finishPreflightCard: (...a) => mocks.finishPreflightCard(...a),+ finishPreflightDispatch: (...a) => mocks.finishPreflightDispatch(...a),+ };+});vi.mock('./cosTaskGenerator.js', () => ({prepareManagedAppImprovementTask: (...a) => mocks.prepareManagedAppImprovementTask(...a),generateSelfImprovementTaskForType: (...a) => mocks.generateSelfImprovementTaskForType(...a),@@ -558,6 +565,6 @@ describe('preflight task card', () => {await drainOnDemandRequests({ state: STATE }, adapter);// emitOnDemandEmpty owns the specific reason; this is the backstop close.expect(mocks.emitOnDemandEmpty).toHaveBeenCalledWith(expect.objectContaining({ preflightCardId: 'preflight-req-1' }));- expect(mocks.finishPreflightCard).toHaveBeenCalledWith('preflight-req-1', { outcome: 'nothing-to-do' });+ expect(mocks.finishPreflightDispatch).toHaveBeenCalledWith('preflight-req-1');});});diff --git a/server/services/preflightTaskCard.js b/server/services/preflightTaskCard.jsindex 74228a7cd9..51f8d0d178 100644--- a/server/services/preflightTaskCard.js+++ b/server/services/preflightTaskCard.js@@ -28,6 +28,7 @@import { applyPreflightStep, createPreflightState, finalizePreflight, preflightHeadline } from '../lib/preflightPlan.js';import { addTask, getTaskById, updateTask } from './cosTaskStore.js';+import { isUserOriginRequest } from './taskScheduleConstants.js';/*** How long a card may sit `in_progress` before the orphan sweep calls it@@ -125,9 +126,18 @@ export function preflightReporter(cardId) {* row reads that key to paint its "review failed" state — the same contract the* standalone failure task used before the card existed.*/-export async function finishPreflightCard(cardId, { outcome, reason = null, note = null, resultTaskId = null } = {}) {+export async function finishPreflightCard(cardId, options = {}) {const preflight = await readPreflight(cardId);if (!preflight) return null;+ return closeReadPreflight(cardId, preflight, options);+}++/**+ * The close itself, against a preflight the caller has ALREADY read — so a+ * caller that advanced a step first persists the step and the close as one+ * write rather than re-reading the card it just wrote.+ */+async function closeReadPreflight(cardId, preflight, { outcome, reason = null, note = null, resultTaskId = null } = {}) {const next = finalizePreflight(preflight, { outcome, reason, note, resultTaskId });// `finalizePreflight` returns the same object for an already-closed card, and// a second close is expected: the drain closes generically after a path that@@ -154,22 +164,39 @@ export async function finishPreflightCard(cardId, { outcome, reason = null, note* final. `resultTaskId` names the task that will run, or is null when the run* produced none — a gate skipped it, or the spawn tier declined it.*- * One helper because two engines reach this same point: the on-demand drain,- * and the idle-review path that STEALS a queued request for its app- * (cosTaskGenerator#generateManagedAppImprovementTask). The steal used to- * report nothing at all, so a card opened by a human's "Run" sat at "Waiting- * for a free task slot" — with its own agent visibly already working — until- * the 15-minute orphan sweep mislabelled it `interrupted`. Keeping the- * `dispatch` step and the `handed-off` close in ONE place is what stops the- * two engines drifting into telling different stories about the same run.+ * THE reason this is one helper: every engine that serves a user's on-demand+ * request reaches this same point, and each used to spell it out for itself.+ * The idle-review path that STEALS a queued request+ * (cosTaskGenerator#generateManagedAppImprovementTask) spelled out nothing at+ * all, so a card opened by a human's "Run" sat at "Waiting for a free task+ * slot" — with its own agent visibly already working — until the orphan sweep+ * mislabelled it `interrupted` (PREFLIGHT_CARD_STALE_MS later). Marking+ * `dispatch` and closing `handed-off` in ONE place is what stops the engines+ * drifting into telling different stories about the same run.+ *+ * One read-modify-write, not two: the step and the close land in the same+ * persisted card, so the Tasks page never renders the frame in between.*/export async function finishPreflightDispatch(cardId, resultTaskId = null) {- if (!cardId) return null;- if (!resultTaskId) return finishPreflightCard(cardId, { outcome: 'nothing-to-do' });- await reportPreflightStep(cardId, 'dispatch');- return finishPreflightCard(cardId, { outcome: 'handed-off', resultTaskId });+ const preflight = await readPreflight(cardId);+ if (!preflight) return null;+ return resultTaskId+ ? closeReadPreflight(cardId, applyPreflightStep(preflight, 'dispatch'), { outcome: 'handed-off', resultTaskId })+ : closeReadPreflight(cardId, preflight, { outcome: 'nothing-to-do' });}+/**+ * The card id for a request, or null when the request is not a human's Run.+ *+ * Derived rather than stamped on the request (see `startPreflightCard`), and+ * one export rather than the ternary at each engine: "only a USER origin is+ * carded" is a policy the card owner decides, and it has to match the gate+ * `startPreflightCard` is called behind or an engine reports into a card that+ * was never opened.+ */+export const cardIdForRequest = (request) =>+ (isUserOriginRequest(request) ? preflightCardId(request.id) : null);+/*** Record a terminal preflight outcome whether or not a card was ever opened.*diff --git a/server/services/preflightTaskCard.test.js b/server/services/preflightTaskCard.test.jsindex 1f682ee2ab..85ee841f56 100644--- a/server/services/preflightTaskCard.test.js+++ b/server/services/preflightTaskCard.test.js@@ -103,27 +103,20 @@ describe('preflightTaskCard', () => {expect(addTask).not.toHaveBeenCalled();});- it('marks dispatch and hands off in one step, so the two engines cannot tell different stories', async () => {+ it('marks dispatch and hands off in a SINGLE write, so the card never renders a half-done frame', async () => {const { createPreflightState } = await import('../lib/preflightPlan.js');- // Read-back reflects the last write, as the real store does: the close reads- // the card the dispatch report just persisted, which is the whole point of- // the two happening in one helper.- let stored = createPreflightState({ requestId: 'demand-1', taskType: 'pr-reviewer' });- getTaskById.mockImplementation(async () => cardFor(stored));- updateTask.mockImplementation(async (id, updates) => {- stored = updates.metadata.preflight;- return cardFor(stored);- });+ getTaskById.mockResolvedValue(cardFor(createPreflightState({ requestId: 'demand-1', taskType: 'pr-reviewer' })));await finishPreflightDispatch(preflightCardId('demand-1'), 'app-improve-1');- // The dispatch report and the close are two writes; what matters is that the- // closed card carries BOTH — a handed-off card whose dispatch step never ran- // renders as a run that skipped its last step.- const [, closed] = updateTask.mock.calls.at(-1);+ // One read-modify-write: a second one would re-read the card it just wrote+ // and emit a second tasks:changed showing a dispatched-but-unfinished card.+ expect(updateTask).toHaveBeenCalledTimes(1);+ const [, closed] = updateTask.mock.calls[0];expect(closed.status).toBe('completed');expect(closed.metadata.preflight.outcome).toBe('handed-off');expect(closed.metadata.preflightResultTaskId).toBe('app-improve-1');- const dispatchStep = closed.metadata.preflight.steps.find(step => step.key === 'dispatch');- expect(dispatchStep.status).toBe('done');+ // The dispatch step is DONE in that same write — a handed-off card whose+ // last step never ran renders as a run that skipped it.+ expect(closed.metadata.preflight.steps.find(step => step.key === 'dispatch').status).toBe('done');});it('closes as nothing-to-do when the run produced no task, rather than naming an agent that never started', async () => {