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

stop the idle-review tier stranding a Run Now preflight card

[._.]/ Adam Eivy92886804ead9
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index af8a9f63a1..5051ad2961 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -458,7 +458,11 @@ 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.
-const MAX_STATIC_INSTANTIATIONS = 103520;
+// The idle-review steal's card hand-off adds one test file and no module: it
+// 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.
+const MAX_STATIC_INSTANTIATIONS = 103521;
const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
diff --git a/server/services/cos.js b/server/services/cos.js
index bac9f3681f..9c92b039fb 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -1114,16 +1114,25 @@ async function spawnDequeuePriority3IdleReview(ctx) {
const freshCosTasks = await getCosTasks();
const pendingSystemTasks = freshCosTasks.autoApproved?.length || 0;
if (pendingSystemTasks === 0) {
- const { task: idleTask, pendingPerpetualDispatch } = await generateIdleReviewTask(state, { ignoreTaskId });
+ const { task: idleTask, pendingPerpetualDispatch, preflightCardId } = 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)) {
+ const admitted = idleTask && capacity.canSpawnCommitted(idleTask, ctx.autonomousSpawnCeiling);
+ if (admitted) {
await recordDeferredPerpetualDispatch(pendingPerpetualDispatch, await import('./taskSchedule.js'));
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);
+ }
}
}
diff --git a/server/services/cosTaskGenerator.idleReviewSteal.test.js b/server/services/cosTaskGenerator.idleReviewSteal.test.js
new file mode 100644
index 0000000000..fa279a6bfd
--- /dev/null
+++ b/server/services/cosTaskGenerator.idleReviewSteal.test.js
@@ -0,0 +1,143 @@
+/**
+ * The idle-review tier can STEAL a queued on-demand request for the app it
+ * picked (`generateManagedAppImprovementTask`), which takes the request off the
+ * queue for good — the on-demand drain never sees it again.
+ *
+ * That made a human's "Run" lie. The drain opens a programmatic-phase card the
+ * moment the request is queued (services/preflightTaskCard.js); the steal
+ * reported nothing into it and never closed it, so the card sat at "Waiting for
+ * a free task slot" with its pre-agent checks all pending — while the agent the
+ * steal produced was visibly already working two cards below — until the
+ * 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.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const preflight = vi.hoisted(() => ({ reporter: vi.fn((cardId) => ({ boundTo: cardId })) }));
+const pipeline = vi.hoisted(() => ({ securityPreflight: vi.fn(async () => ({ skipped: true, reason: 'no-external-open-prs' })) }));
+const scheduleMocks = vi.hoisted(() => ({
+ requests: [],
+ clearOnDemandRequest: vi.fn(async () => ({})),
+}));
+
+vi.mock('./preflightTaskCard.js', async (importActual) => ({
+ ...(await importActual()),
+ preflightReporter: (...args) => preflight.reporter(...args),
+}));
+// The security preflight is the deterministic phase whose progress the card
+// renders; skipping it keeps these tests on the wiring rather than on a real
+// forge scan.
+vi.mock('./prReviewerPipeline.js', async (importActual) => ({
+ ...(await importActual()),
+ runPrReviewerSecurityPreflight: (...args) => pipeline.securityPreflight(...args),
+}));
+vi.mock('./apps.js', async (importActual) => ({
+ ...(await importActual()),
+ getActiveApps: vi.fn(async () => [{ id: 'example-app', name: 'Example App' }]),
+ getAppTaskTypeOverrides: vi.fn(async () => ({})),
+}));
+vi.mock('./appActivity.js', async (importActual) => ({
+ ...(await importActual()),
+ getNextAppForReview: vi.fn(async () => ({ id: 'example-app', name: 'Example App' })),
+ markIdleReviewStarted: vi.fn(async () => {}),
+ markAppReviewCooldown: vi.fn(async () => {}),
+ bindAppReviewAgent: vi.fn(async () => {}),
+ updateAppActivity: vi.fn(async () => {}),
+}));
+vi.mock('./cosState.js', async (importActual) => ({
+ ...(await importActual()),
+ loadState: vi.fn(async () => ({ stats: {}, config: {} })),
+ saveState: vi.fn(async () => {}),
+ withStateLock: vi.fn(async (fn) => fn()),
+}));
+vi.mock('./taskSchedule.js', async (importActual) => ({
+ ...(await importActual()),
+ getOnDemandRequests: vi.fn(async () => scheduleMocks.requests),
+ clearOnDemandRequest: (...args) => scheduleMocks.clearOnDemandRequest(...args),
+ applyOnDemandRunResets: vi.fn(async () => true),
+ recordExecution: vi.fn(async () => {}),
+ getTaskInterval: vi.fn(async () => ({ prompt: null, taskMetadata: {} })),
+ getNextTaskType: vi.fn(async () => null),
+}));
+
+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;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ preflight.reporter.mockImplementation((cardId) => ({ boundTo: cardId }));
+ pipeline.securityPreflight.mockResolvedValue({ skipped: true, reason: 'no-external-open-prs' });
+ scheduleMocks.requests = [];
+});
+
+describe('idle review stealing a queued on-demand request', () => {
+ it('carries the human Run card out to the tier that rules on the task', async () => {
+ scheduleMocks.requests = [request()];
+ const result = await generateIdleReviewTask(STATE);
+ expect(scheduleMocks.clearOnDemandRequest).toHaveBeenCalledWith('demand-1');
+ // The card id the drain would have used, so the steal reports into the SAME
+ // record the user is already watching rather than opening a second one.
+ expect(result.preflightCardId).toBe('preflight-demand-1');
+ // Closing it belongs to the tier: this produced no task, and a card closed
+ // `handed-off` here would name an agent that never started.
+ expect(result.task).toBeNull();
+ });
+
+ 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' });
+ });
+
+ it('cards nothing for an automated origin, which has nobody waiting on it', async () => {
+ scheduleMocks.requests = [request({ origin: 'refill' })];
+ const result = await generateIdleReviewTask(STATE);
+ expect(result.preflightCardId).toBeNull();
+ expect(progressOf()).toEqual({ boundTo: null });
+ });
+
+ it('cards nothing when the tier picked its own work instead of stealing a Run', async () => {
+ scheduleMocks.requests = [request({ appId: 'other-app' })];
+ const result = await generateIdleReviewTask(STATE);
+ expect(scheduleMocks.clearOnDemandRequest).not.toHaveBeenCalled();
+ expect(result.preflightCardId).toBeNull();
+ });
+});
+
+/**
+ * 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.js
index d776a2e9e2..6043f67b7d 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.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 } from './taskScheduleConstants.js';
+import { isReconcileDrainTaskType, isUserOriginRequest } from './taskScheduleConstants.js';
import { isProgrammaticScheduledTaskType, requiresInstallWideTarget } from './taskScheduleRegistry.js';
import {
appendClaimOverrideContext,
@@ -1026,12 +1026,21 @@ async function spawnPriority4IdleReview(ctx) {
const freshCosTasks = await getCosTasks();
const pendingSystemTasks = freshCosTasks.autoApproved?.length || 0;
if (pendingSystemTasks === 0) {
- const { task: idleTask, pendingPerpetualDispatch } = await generateIdleReviewTask(state);
- if (idleTask && canSpawnTask(idleTask, autonomousSlotCeiling)) {
+ const { task: idleTask, pendingPerpetualDispatch, preflightCardId } = await generateIdleReviewTask(state);
+ const admitted = idleTask && canSpawnTask(idleTask, autonomousSlotCeiling);
+ if (admitted) {
await recordDeferredPerpetualDispatch(pendingPerpetualDispatch, await import('./taskSchedule.js'));
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);
+ }
}
}
}
@@ -1272,7 +1281,7 @@ export async function evaluateTasks(options) {
export async function generateIdleReviewTask(state, { ignoreTaskId = null } = {}) {
if (!isImprovementEnabled(state)) {
emitLog('debug', 'Improvement tasks are disabled');
- return { task: null, pendingPerpetualDispatch: null };
+ return { task: null, pendingPerpetualDispatch: null, preflightCardId: null };
}
// Get all active (non-archived) managed apps (including PortOS)
@@ -1300,17 +1309,17 @@ export async function generateIdleReviewTask(state, { ignoreTaskId = null } = {}
});
emitLog('info', `Generating improvement task for ${nextApp.name}`, { appId: nextApp.id });
- const { task: idleTask, pendingPerpetualDispatch } = await generateManagedAppImprovementTask(nextApp, state, { ignoreTaskId });
+ const { task: idleTask, pendingPerpetualDispatch, preflightCardId } = 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 { task: idleTask, pendingPerpetualDispatch };
+ return { task: idleTask, pendingPerpetualDispatch, preflightCardId };
}
}
emitLog('debug', 'No idle tasks available');
- return { task: null, pendingPerpetualDispatch: null };
+ return { task: null, pendingPerpetualDispatch: null, preflightCardId: null };
}
/**
@@ -1945,10 +1954,19 @@ 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.
+ 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;
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
@@ -1965,7 +1983,7 @@ async function generateManagedAppImprovementTask(app, state, { ignoreTaskId = nu
if (!nextTypeResult) {
emitLog('info', `No app improvement tasks are eligible for ${app.name} based on schedule`);
- return { task: null, pendingPerpetualDispatch: null };
+ return { task: null, pendingPerpetualDispatch: null, preflightCardId: null };
}
nextType = nextTypeResult.taskType;
@@ -1992,14 +2010,21 @@ async function generateManagedAppImprovementTask(app, state, { ignoreTaskId = nu
// spawn; the per-type generator does not record execution itself.
const prepared = await prepareManagedAppImprovementTask(nextType, app, state, {
ignoreTaskId,
- targetPullRequest
+ targetPullRequest,
+ // 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.
+ preflightCardId: stolenCardId
});
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, pendingPerpetualDispatch };
+ // 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.
+ return { task, pendingPerpetualDispatch, preflightCardId: stolenCardId };
}
/**
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 1ff0b248fa..bd25b7f8e5 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -1759,11 +1759,11 @@ 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, pendingPerpetualDispatch };', start));
+ const body = GEN_SRC.slice(start, GEN_SRC.indexOf('\n return { task, pendingPerpetualDispatch, preflightCardId: stolenCardId };', 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(/prepareManagedAppImprovementTask\([\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', () => {
diff --git a/server/services/onDemandDrain.js b/server/services/onDemandDrain.js
index 8241576b0b..159bf2af23 100644
--- a/server/services/onDemandDrain.js
+++ b/server/services/onDemandDrain.js
@@ -35,7 +35,7 @@ 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, preflightCardId, reportPreflightStep, startPreflightCard } from './preflightTaskCard.js';
+import { finishPreflightCard, finishPreflightDispatch, preflightCardId, reportPreflightStep, startPreflightCard } from './preflightTaskCard.js';
/**
* Drain the on-demand request queue, generating + persisting a task per request
@@ -251,8 +251,7 @@ export async function drainOnDemandRequests(ctx, adapter) {
// it to `completed` — so without excluding it the re-issued claim is
// 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 });
- await reportPreflightStep(cardId, 'dispatch');
- await finishPreflightCard(cardId, { outcome: 'handed-off', resultTaskId: persisted?.id || task.id });
+ await finishPreflightDispatch(cardId, persisted?.id || task.id);
if (!persisted?.duplicate) {
await recordDeferredPerpetualDispatch(pendingPerpetualDispatch, taskScheduleMod);
emitSpawn(task);
diff --git a/server/services/onDemandDrain.test.js b/server/services/onDemandDrain.test.js
index ff99e1619e..0cf2ce7c3c 100644
--- a/server/services/onDemandDrain.test.js
+++ b/server/services/onDemandDrain.test.js
@@ -44,6 +44,7 @@ const mocks = vi.hoisted(() => ({
recordPreflightOutcome: vi.fn(async () => null),
reportPreflightStep: vi.fn(async () => {}),
finishPreflightCard: vi.fn(async () => null),
+ finishPreflightDispatch: vi.fn(async () => null),
}));
vi.mock('./apps.js', () => ({ getActiveApps: (...a) => mocks.getActiveApps(...a) }));
@@ -74,6 +75,7 @@ vi.mock('./preflightTaskCard.js', () => ({
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),
@@ -523,10 +525,7 @@ describe('preflight task card', () => {
mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);
const { adapter } = generatorAdapter();
await drainOnDemandRequests({ state: STATE }, adapter);
- expect(mocks.reportPreflightStep).toHaveBeenCalledWith('preflight-req-1', 'dispatch');
- expect(mocks.finishPreflightCard).toHaveBeenCalledWith('preflight-req-1', {
- outcome: 'handed-off', resultTaskId: 'persisted-1',
- });
+ expect(mocks.finishPreflightDispatch).toHaveBeenCalledWith('preflight-req-1', 'persisted-1');
});
it.each([
diff --git a/server/services/preflightTaskCard.js b/server/services/preflightTaskCard.js
index bc77794bd7..74228a7cd9 100644
--- a/server/services/preflightTaskCard.js
+++ b/server/services/preflightTaskCard.js
@@ -149,6 +149,27 @@ export async function finishPreflightCard(cardId, { outcome, reason = null, note
});
}
+/**
+ * Close a card once the spawn decision on whatever its preflight produced is
+ * 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.
+ */
+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 });
+}
+
/**
* 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.js
index 6e9f9b5149..1f682ee2ab 100644
--- a/server/services/preflightTaskCard.test.js
+++ b/server/services/preflightTaskCard.test.js
@@ -10,6 +10,7 @@ const { addTask, getTaskById, updateTask } = await import('./cosTaskStore.js');
const {
PREFLIGHT_CARD_STALE_MS,
finishPreflightCard,
+ finishPreflightDispatch,
isPreflightCard,
isStalePreflightCard,
preflightCardId,
@@ -102,6 +103,45 @@ describe('preflightTaskCard', () => {
expect(addTask).not.toHaveBeenCalled();
});
+ it('marks dispatch and hands off in one step, so the two engines cannot tell different stories', 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);
+ });
+ 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);
+ 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');
+ });
+
+ it('closes as nothing-to-do when the run produced no task, rather than naming an agent that never started', async () => {
+ const { createPreflightState } = await import('../lib/preflightPlan.js');
+ getTaskById.mockResolvedValue(cardFor(createPreflightState({ requestId: 'demand-1', taskType: 'pr-reviewer' })));
+ await finishPreflightDispatch(preflightCardId('demand-1'), null);
+ const [, closed] = updateTask.mock.calls.at(-1);
+ expect(closed.metadata.preflight.outcome).toBe('nothing-to-do');
+ expect(closed.metadata.preflightResultTaskId).toBeUndefined();
+ expect(closed.metadata.preflight.steps.find(step => step.key === 'dispatch').status).toBe('skipped');
+ });
+
+ it('reads nothing for an uncarded run, so an automated origin pays no task lookup', async () => {
+ await finishPreflightDispatch(null, 'app-improve-1');
+ expect(getTaskById).not.toHaveBeenCalled();
+ expect(updateTask).not.toHaveBeenCalled();
+ });
+
it('treats a card as stale only once nothing could still be running it', async () => {
const { createPreflightState } = await import('../lib/preflightPlan.js');
const fresh = cardFor(createPreflightState({ requestId: 'demand-1', taskType: 'pr-reviewer' }));