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

refactor: return the skip reason from prepareManagedAppImprovementTask instead of a side-channel Map (#9182)

[._.]/ Adam Eivy162b5692d226
diff --git a/server/services/cosTaskGenerator.idleReviewSteal.test.js b/server/services/cosTaskGenerator.idleReviewSteal.test.js
index b1261c1dd1..8419aac2f2 100644
--- a/server/services/cosTaskGenerator.idleReviewSteal.test.js
+++ b/server/services/cosTaskGenerator.idleReviewSteal.test.js
@@ -65,7 +65,7 @@ vi.mock('./taskSchedule.js', async (importActual) => ({
getNextTaskType: vi.fn(async () => null),
}));
-const { generateIdleReviewTask } = await import('./cosTaskGenerator.js');
+const { generateIdleReviewTask, prepareManagedAppImprovementTask } = 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 });
@@ -112,3 +112,15 @@ describe('idle review stealing a queued on-demand request', () => {
});
});
+
+describe('prepareManagedAppImprovementTask on a pr-reviewer preflight skip', () => {
+ it('returns the preflight reason on the skip, so a user Run can say why nothing started', async () => {
+ pipeline.securityPreflight.mockResolvedValue({ skipped: true, reason: 'security-guard-not-ready' });
+ const prepared = await prepareManagedAppImprovementTask('pr-reviewer', { id: 'example-app', name: 'Example App' }, STATE);
+ expect(prepared).toEqual({
+ task: null,
+ pendingPerpetualDispatch: null,
+ skip: { gate: 'security-preflight', reason: 'security-guard-not-ready', cli: null, remedy: null, detail: null },
+ });
+ });
+});
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index a02c9bf2a3..d79da23d2e 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -1613,7 +1613,7 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, { ignore
// returns null on plan-gate / precondition skip; we silently continue.
// Regression-pinned in cos.test.js.
const prepared = await prepareManagedAppImprovementTask(nextType, app, state, { ignoreTaskId });
- if (!prepared?.task) continue;
+ if (!prepared.task) continue;
const { task, pendingPerpetualDispatch } = prepared;
// Queue-path invariants override the generator's direct-spawn defaults
@@ -2083,8 +2083,7 @@ async function generateManagedAppImprovementTask(app, state, { ignoreTaskId = nu
// 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;
+ const { 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);
@@ -2103,71 +2102,35 @@ async function generateManagedAppImprovementTask(app, state, { ignoreTaskId = nu
* @param {Object} state - Current CoS state
* @returns {Object} Generated task
*/
-// Last transient (non-parking) detector verdict, keyed the same way a park is
-// (`taskType` + appId), so emitOnDemandEmpty can read it right beside
-// getPerpetualParkInfo. A transient skip deliberately does NOT park — there is no
-// park record to hang the reason on — so this is that path's reason channel.
-//
-// Deliberately in-memory and short-lived: the only consumer is the emit that
-// follows the gate a few frames later in the SAME drain, so a persisted schedule
-// field would have nothing left to read it after a restart. The TTL keeps a
-// verdict from a *previous* drain out of an unrelated later toast, and the read
-// consumes it so it can never be reported twice.
-const TRANSIENT_VERDICT_TTL_MS = 60_000;
-const transientVerdicts = new Map();
-const transientVerdictKey = (taskType, appId) => `${taskType}:${appId || 'global'}`;
-
-// How many CONSECUTIVE transient skips (across evaluations, not within any
-// single 60s window) applyPerpetualWorkGate tolerates at `debug` before
-// escalating to `warn` — see recordPerpetualTransient's return value.
+// How many CONSECUTIVE transient skips (across evaluations) applyPerpetualWorkGate
+// tolerates at `debug` before escalating to `warn` — see noteTransientProbe's
+// return value.
export const PERPETUAL_TRANSIENT_ESCALATION_THRESHOLD = 3;
-// Consecutive-transient-skip counters, keyed the same as transientVerdicts but
-// deliberately tracked SEPARATELY from it: this streak must survive across
-// evaluations more than 60s apart (it counts how many evaluations IN A ROW came
-// back transient, not how many landed inside one verdict's TTL window), and it
-// is reset — not just expired — the moment a probe stops being transient.
+// Consecutive-transient-skip counters, keyed `taskType:appId`. This is the ONLY
+// state that has to outlive a single evaluation (it counts how many evaluations
+// IN A ROW came back transient); the skip's REASON travels back explicitly on
+// prepareManagedAppImprovementTask's `skip` result instead of through a side
+// channel.
const transientStreaks = new Map();
+const transientStreakKey = (taskType, appId) => `${taskType}:${appId || 'global'}`;
/**
- * Record why a perpetual work gate skipped WITHOUT parking. `cli` is the forge
- * CLI whose probe failed (`gh` / `glab`), or null when no forge was involved.
- * Passing a null verdict clears any stale entry (the actionable / park paths)
- * AND resets the consecutive-transient streak — a successful probe means
- * whatever was stuck has cleared.
+ * Count one more consecutive transient (non-parking) probe failure for
+ * `taskType` + `appId`.
*
- * Also doubles as pr-reviewer's idle-skip reason channel: pr-reviewer is
- * on-demand, not perpetual, so its preflight skip (churn park, no external PRs,
- * a target PR that isn't reviewable, the security guard not being ready, …)
- * reaches emitOnDemandEmpty as a plain 'idle' outcome with no channel of its own
- * for WHY — the same gap this map already closes for 'transient'. The payload
- * shape here is a free-form object (`{ ...verdict }`), so a `{ reason }` payload
- * under the `taskType: 'pr-reviewer'` key needs no separate map or TTL logic.
- * pr-reviewer shares the streak counter too — harmless, since it is keyed
- * per-`taskType:appId` and nothing reads pr-reviewer's streak today.
- *
- * @returns {number} the new consecutive-transient count (0 once cleared).
+ * @returns {number} the new consecutive-transient count.
*/
-export function recordPerpetualTransient(taskType, appId, verdict) {
- const key = transientVerdictKey(taskType, appId);
- if (!verdict) {
- transientVerdicts.delete(key);
- transientStreaks.delete(key);
- return 0;
- }
- transientVerdicts.set(key, { ...verdict, at: Date.now() });
+export function noteTransientProbe(taskType, appId) {
+ const key = transientStreakKey(taskType, appId);
const count = (transientStreaks.get(key) || 0) + 1;
transientStreaks.set(key, count);
return count;
}
-/** Read-and-consume the recorded verdict; null when absent or past its TTL. */
-function takePerpetualTransient(taskType, appId) {
- const key = transientVerdictKey(taskType, appId);
- const verdict = transientVerdicts.get(key);
- transientVerdicts.delete(key);
- if (!verdict || (Date.now() - verdict.at) > TRANSIENT_VERDICT_TTL_MS) return null;
- return verdict;
+/** Reset the consecutive-transient streak — the probe stopped being transient. */
+export function clearTransientProbeStreak(taskType, appId) {
+ transientStreaks.delete(transientStreakKey(taskType, appId));
}
/**
@@ -2273,8 +2236,13 @@ export async function drainProgrammaticOnDemandRequests({ taskScheduleMod, reque
* passed in to avoid re-reading the schedule. The event fires ONLY on the
* user-initiated on-demand path, so the client can toast it without
* background-park noise.
+ *
+ * `skip` is the `skip` field of the prepareManagedAppImprovementTask result
+ * that produced no task (null when the caller had none, e.g. a global task): it
+ * carries pr-reviewer's preflight reason and the transient detector verdict
+ * (`cli` / `remedy`) that the outcome classification below explains.
*/
-export async function emitOnDemandEmpty({ taskScheduleMod, request, targetApp, taskConfig, preflightCardId = null }) {
+export async function emitOnDemandEmpty({ taskScheduleMod, request, targetApp, taskConfig, preflightCardId = null, skip = null }) {
const appId = targetApp?.id || null;
const parkInfo = await taskScheduleMod.getPerpetualParkInfo(request.taskType, appId).catch(() => null);
const isDetectorDriven = taskConfig?.perpetual === true;
@@ -2292,21 +2260,21 @@ export async function emitOnDemandEmpty({ taskScheduleMod, request, targetApp, t
reason = app?.layeredIntelligence?.lastRunReason || null;
}
if (outcome === 'idle' && request.taskType === 'pr-reviewer') {
- reason = takePerpetualTransient('pr-reviewer', appId)?.reason ?? null;
+ reason = skip?.gate === 'security-preflight' ? skip.reason : null;
}
// 'transient' says "the forge probe failed, try again shortly" — only true when
// the forge is momentarily flaky. A gh that is missing, unauthenticated, or
// blocked by an outbound firewall fails EVERY tick forever, so that advice sends
// the user in circles. Ask the CLI the detector actually ran (recorded by the
- // work gate moments ago — the task-type NAME can't answer this: `claim-work`
+ // work gate on `skip` — the task-type NAME can't answer this: `claim-work`
// resolves its forge internally, and branch-reconcile goes transient over
// git/provider faults with no forge involved) whether it is broken in a
// way that won't self-clear, and pass the remedy through. No verdict, an
// unprobeable CLI, or a healthy one all leave `forge` null and keep the
// generic copy — the failure really was a blip, or at least not one we can name.
let forge = null;
- const verdict = outcome === 'transient' ? takePerpetualTransient(request.taskType, appId) : null;
+ const verdict = outcome === 'transient' && skip?.gate === 'perpetual-work' ? skip : null;
if (verdict?.remedy) {
// The detector already knew the fault AND the way out — a per-repo permission
// the token lacks (e.g. the collaborators/members list behind the "Me +
@@ -2500,8 +2468,10 @@ async function resolveClaimWorkRouting(app, taskType, metadata, taskSchedule) {
* - unchanged actionable set → PARK after a successful no-progress run;
* - idle (definitive) → PARK on the recheck cadence, skip;
* - transient probe failure → skip WITHOUT parking so the next tick retries.
- * The detector keys on the RESOLVED promptTaskType. Returns `{ skip, spendDispatch,
- * signature }` and mutates `metadata.perpetual` on the actionable path.
+ * The detector keys on the RESOLVED promptTaskType. Returns `{ skip, verdict,
+ * spendDispatch, signature }` — `verdict` (`{ cli, reason, remedy, detail }`) is
+ * set only on the transient skip, so the caller can hand the reason to the
+ * user-facing "Run" toast — and mutates `metadata.perpetual` on the actionable path.
*
* `spendDispatch` is the caller's cue to call `recordPerpetualDispatch` (which
* clears the park and spends one unit of the type's `drainDispatchCap` budget in a
@@ -2529,7 +2499,7 @@ async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, i
// A probe that reports actionable work is, by definition, not stuck — clear
// both the transient streak and any persisted stall diagnostic before
// deciding whether THIS evaluation dispatches or parks on no-progress.
- recordPerpetualTransient(taskType, app.id, null);
+ clearTransientProbeStreak(taskType, app.id);
await taskSchedule.recordPerpetualStall(taskType, app.id, null);
// A successful claim/plan agent can still return without changing forge or
// PLAN state (for example, it decides not to pick the advertised item). The
@@ -2569,16 +2539,17 @@ async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, i
// stalled verdict — otherwise a perpetual drain whose forge CLI is broken
// produces zero console output, zero persisted state, and zero UI signal,
// indefinitely (#7551).
- const consecutive = recordPerpetualTransient(taskType, app.id, {
+ const verdict = {
cli: detection.cli || null, reason: detection.reason, remedy: detection.remedy || null, detail: detection.detail || null
- });
+ };
+ const consecutive = noteTransientProbe(taskType, app.id);
const detailSuffix = detection.detail ? ` — ${detection.detail}` : '';
const escalated = consecutive >= PERPETUAL_TRANSIENT_ESCALATION_THRESHOLD;
emitLog(escalated ? 'warn' : 'debug',
`Perpetual ${taskType} skip for ${app.name} (transient: ${detection.reason}${detailSuffix}, ${consecutive} consecutive)`,
{ appId: app.id, consecutive });
// The skip is silent by design at low counts (the next tick retries), but an
- // explicit user "Run" ends here too — record which CLI failed so
+ // explicit user "Run" ends here too — return which CLI failed (`verdict`) so
// emitOnDemandEmpty can tell the difference between a blip and a forge that
// is broken for good, plus any remedy the detector already named (a
// permission the token lacks, which no amount of retrying fixes).
@@ -2587,9 +2558,9 @@ async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, i
cli: detection.cli || null, reason: detection.reason, detail: detection.detail || null, consecutive
});
}
- return { skip: true };
+ return { skip: true, verdict };
}
- recordPerpetualTransient(taskType, app.id, null);
+ clearTransientProbeStreak(taskType, app.id);
await taskSchedule.recordPerpetualStall(taskType, app.id, null);
// Carry the detector's open/in-flight/filtered breakdown into the park so an
// explicit "Run" can explain WHY a non-empty queue yielded no work.
@@ -2738,6 +2709,12 @@ function applyProviderModelPins(metadata, interval, appPin, hookOverride, reques
}
}
+// The one "nothing to build" result of prepareManagedAppImprovementTask — every
+// skip exit returns this, so the one-shape rule is enforced in one place and the
+// reason for the skip travels with the answer instead of through a side channel.
+const skipped = (gate, { reason = null, cli = null, remedy = null, detail = null } = {}) =>
+ ({ task: null, pendingPerpetualDispatch: null, skip: { gate, reason, cli, remedy, detail } });
+
/**
* Decide whether a managed-app improvement task should be generated for
* `taskType`, and build it if so. Never records a perpetual-drain dispatch —
@@ -2749,7 +2726,14 @@ function applyProviderModelPins(metadata, interval, appPin, hookOverride, reques
* 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 }>}
+ * Always resolves to ONE shape, `{ task, pendingPerpetualDispatch, skip }`:
+ * `skip` is `null` when a task was built, otherwise
+ * `{ gate, reason, cli, remedy, detail }` (built by `skipped`) naming the exit
+ * that declined — `reason`/`cli`/`remedy`/`detail` are the operator-facing
+ * detail where the gate has one (pr-reviewer's security preflight, the transient
+ * work-detector verdict, the plan gate), null otherwise.
+ *
+ * @returns {Promise<{ task: Object|null, pendingPerpetualDispatch: Object|null, skip: { gate: string, reason: string|null, cli: string|null, remedy: string|null, detail: string|null }|null }>}
*/
export async function prepareManagedAppImprovementTask(taskType, app, state, {
skipPreconditions = false,
@@ -2771,7 +2755,7 @@ export async function prepareManagedAppImprovementTask(taskType, app, state, {
const { getTaskPrompt, getStagePrompt } = await import('./taskPromptService.js');
// Also protect requests queued before the target-scope gate was installed.
- if (requiresInstallWideTarget(taskType)) return null;
+ if (requiresInstallWideTarget(taskType)) return skipped('install-wide-target');
// NOTE: `updateAppActivity` + the "Generating improvement task" log are
// intentionally deferred until AFTER every gate returns non-null (see end
@@ -2785,7 +2769,7 @@ export async function prepareManagedAppImprovementTask(taskType, app, state, {
// also away from types that *could* run on a future tick) and (b) emit a
// misleading "Generating improvement task" line for skipped types. The
// single-call ordering at the bottom keeps both paths in sync — a returned
- // task means rotation advanced; a `return null` short-circuit means it
+ // task means rotation advanced; a `skipped(...)` short-circuit means it
// didn't.
// Get interval settings to determine provider/model and pipeline config.
@@ -2827,7 +2811,7 @@ export async function prepareManagedAppImprovementTask(taskType, app, state, {
// `resolveQuotaBurnStep` before they queue. `runInapplicableAudit` is the
// user's recorded override from the schedule form.
if (!skipPreconditions && !onDemand && isAuditTaskType(taskType) && metadata.runInapplicableAudit !== true
- && await skipInapplicableAudit(app, taskType, taskSchedule)) return null;
+ && await skipInapplicableAudit(app, taskType, taskSchedule)) return skipped('audit-inapplicable');
if (taskType === 'pr-reviewer') ensurePrReviewerPipeline(metadata);
initializePipelineMetadata(metadata);
@@ -2835,15 +2819,10 @@ export async function prepareManagedAppImprovementTask(taskType, app, state, {
const securityPreflight = await runPrReviewerSecurityPreflight(taskType, app, metadata, targetPullRequest, taskSchedule, {
progress: preflightReporter(preflightCardId),
});
- // Record (or clear a stale) skip reason in the SAME call: clearing on a passed
- // gate matters too, or an unrelated later idle outcome for this app (e.g. a
- // downstream precondition skip below) could read back a reason that no longer
- // applies.
- if (taskType === 'pr-reviewer') {
- recordPerpetualTransient('pr-reviewer', app.id, securityPreflight.skipped ? { reason: securityPreflight.reason || null } : null);
- }
- if (securityPreflight.skipped) return null;
- if (!skipPreconditions && shouldSkipForPrecondition(metadata, app, taskType)) return null;
+ // The preflight's reason rides the skip result to emitOnDemandEmpty, so a user
+ // "Run" of pr-reviewer that hits the security guard toasts WHY.
+ if (securityPreflight.skipped) return skipped('security-preflight', { reason: securityPreflight.reason || null });
+ if (!skipPreconditions && shouldSkipForPrecondition(metadata, app, taskType)) return skipped('precondition');
// Programmatic-I/O input hook. A task type may register a buildTaskInput hook
// (taskTypeHooks.js) that does deterministic pre-agent data collection and
@@ -2855,7 +2834,7 @@ export async function prepareManagedAppImprovementTask(taskType, app, state, {
// counts in-flight tasks against a budget must not count the run that just
// finished and already recorded itself (#3179).
const inputHook = await resolveTaskInputHook(app, taskType, taskSchedule, { ignoreTaskId });
- if (inputHook.skip) return null;
+ if (inputHook.skip) return skipped('input-hook');
const { hookPrompt, hookOverride, hookMetadata } = inputHook;
// claim-work single-source router: `taskType` stays 'claim-work' for
@@ -2867,18 +2846,18 @@ export async function prepareManagedAppImprovementTask(taskType, app, state, {
// capped drain must not pay for a work-detector probe or a reconcile git/gh scan
// it is only going to discard.
const drainCap = await applyPerpetualDrainCap(app, taskType, interval, taskSchedule);
- if (drainCap.skip) return null;
+ if (drainCap.skip) return skipped('drain-cap');
// Perpetual (drain-until-done) gate — probes for actionable work before
// building the prompt or burning an agent (branch-/issue-reconcile self-gate
// in their own blocks, so this excludes them).
const perpetualGate = await applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, interval, taskSchedule, { ignoreTaskId });
- if (perpetualGate.skip) return null;
+ if (perpetualGate.skip) return skipped('perpetual-work', perpetualGate.verdict);
// branch-reconcile: deterministic git/gh pre-step that carries the actionable
// in-flight set into the prompt via {inFlightBranches}.
const branchReconcile = await resolveBranchReconcileBlock(app, taskType, metadata, taskSchedule);
- if (branchReconcile.skip) return null;
+ if (branchReconcile.skip) return skipped('branch-reconcile');
const inFlightBranchesBlock = branchReconcile.block;
// repo-sync: deterministic git pre-step that syncs this app's checkout with
@@ -2887,13 +2866,13 @@ export async function prepareManagedAppImprovementTask(taskType, app, state, {
// generateSelfImprovementTaskForType — which is what "Run Now" with no app
// triggers; this branch covers a run scoped to one app.)
const repoSync = await resolveRepoSyncBlock(app, taskType, metadata);
- if (repoSync.skip) return null;
+ if (repoSync.skip) return skipped('repo-sync');
const repoSyncReportBlock = repoSync.block;
// issue-reconcile: deterministic forge pre-step that carries the zombie-issue
// set into the prompt via {zombieIssues}.
const issueReconcile = await resolveIssueReconcileBlock(app, taskType, metadata, taskSchedule);
- if (issueReconcile.skip) return null;
+ if (issueReconcile.skip) return skipped('issue-reconcile');
const zombieIssuesBlock = issueReconcile.block;
// Honor a direct claim-work prompt customization if the user set one;
@@ -2918,7 +2897,7 @@ export async function prepareManagedAppImprovementTask(taskType, app, state, {
// reference-watch: dynamically inject {referenceData} — a Markdown chunk
// describing each ref configured on the app + commits since lastReviewedSha.
const referenceWatch = await resolveReferenceWatchBlock(app, taskType);
- if (referenceWatch.skip) return null;
+ if (referenceWatch.skip) return skipped('reference-watch');
const referenceDataBlock = referenceWatch.block;
// Tracker-filing types (reference-watch, or an audit type with fileIssues):
@@ -2942,7 +2921,7 @@ export async function prepareManagedAppImprovementTask(taskType, app, state, {
// pr-watcher: poll the app's GitHub repo for PRs newly opened against the
// default branch; injects {prData}/{repoFullName}/{defaultBranch}.
const prWatch = await resolvePrWatcherBlock(app, taskType, metadata, taskSchedule);
- if (prWatch.skip) return null;
+ if (prWatch.skip) return skipped('pr-watcher');
const prDataBlock = prWatch.block;
const prRepoFullName = prWatch.repoFullName;
const prDefaultBranch = prWatch.defaultBranch;
@@ -2953,7 +2932,7 @@ export async function prepareManagedAppImprovementTask(taskType, app, state, {
const planMeta = await applyPlanIdMetadata(promptTaskType, app.repoPath, metadata);
if (planMeta.skipReason) {
emitLog('info', `Skipping ${taskType} for ${app.name}: ${planMeta.skipReason}`, { appId: app.id });
- return null;
+ return skipped('plan-gate', { reason: planMeta.skipReason });
}
const planConstraintBlock = buildPlanConstraintBlock(metadata.planId);
@@ -3015,12 +2994,12 @@ export async function prepareManagedAppImprovementTask(taskType, app, state, {
// All gates passed — stamp the buildTaskInput hook's metadata bag, record the
// rotation-pointer advance, and emit the generation log. Deferred from the top
- // of the function (see note there); every `return null` above this point
+ // of the function (see note there); every `skipped(...)` exit above this point
// intentionally leaves all three untouched.
//
// The hook bag lands HERE, below the last gate, precisely so a hook can defer a
// side effect keyed on it until the task is certain to exist. Several gates
- // below `resolveTaskInputHook` can still `return null` with no agent ever
+ // below `resolveTaskInputHook` can still `return skipped(...)` with no agent ever
// spawned, so a hook that charged a spend ledger from `buildTaskInput` would
// burn budget on a dispatch that never happened (#3179).
//
@@ -3061,7 +3040,7 @@ export async function prepareManagedAppImprovementTask(taskType, app, state, {
? { taskType, appId: app.id, signature: perpetualGate.signature ?? null }
: null;
- return { task, pendingPerpetualDispatch };
+ return { task, pendingPerpetualDispatch, skip: null };
}
/**
@@ -3083,10 +3062,10 @@ export async function prepareManagedAppImprovementTask(taskType, app, state, {
export async function generateManagedAppImprovementTaskForType(taskType, app, state, opts = {}) {
const taskSchedule = await import('./taskSchedule.js');
const prepared = await prepareManagedAppImprovementTask(taskType, app, state, opts);
- // Guard on `prepared?.task`, matching every other caller of prepare — task
+ // Guard on `prepared.task`, matching every other caller of prepare — task
// and pendingPerpetualDispatch are always constructed together, but this
// keeps the guard from silently drifting if that ever changes.
- if (!prepared?.task) return null;
+ if (!prepared.task) return null;
await recordDeferredPerpetualDispatch(prepared.pendingPerpetualDispatch, taskSchedule);
return prepared.task;
}
diff --git a/server/services/cosTaskGenerator.providerPin.test.js b/server/services/cosTaskGenerator.providerPin.test.js
index cfb92e260c..7955e9d08c 100644
--- a/server/services/cosTaskGenerator.providerPin.test.js
+++ b/server/services/cosTaskGenerator.providerPin.test.js
@@ -65,6 +65,8 @@ vi.mock('./perpetualWork.js', async importOriginal => ({
detectActionableWork: vi.fn(async () => ({ actionable: true, count: 3, signature: '42,43,44' })),
}));
+import { detectActionableWork } from './perpetualWork.js';
+import { recordPerpetualStall } from './taskSchedule.js';
import { generateManagedAppImprovementTaskForType, prepareManagedAppImprovementTask, resolveClaimWorkMetadata } from './cosTaskGenerator.js';
const APP = { id: 'app-1', name: 'Example App', repoPath: '/tmp/example-repo' };
@@ -184,3 +186,52 @@ it('prepares a scheduled perpetual swarm with matching filters and per-app execu
expect(prepared.task.description).toContain('effort:');
expect(prepared.pendingPerpetualDispatch).toMatchObject({ taskType: 'claim-issue', appId: APP.id });
});
+
+// A skipped prepare hands back WHY through its `skip` field — the one shape of
+// "nothing", instead of a bare null plus a module-level side channel (#9182).
+describe('prepareManagedAppImprovementTask skip result', () => {
+ const transient = { actionable: false, transient: true, cli: 'gh', reason: 'gh-list-failed' };
+ const prepareClaim = (appId) => prepareManagedAppImprovementTask('claim-issue', { ...APP, id: appId }, STATE);
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getTaskIntervalMock.mockResolvedValue({ type: 'on-demand', perpetual: true, taskMetadata: {} });
+ getAppTaskTypeOverridesMock.mockResolvedValue({});
+ });
+
+ it('carries the transient detector verdict on the skip and leaves the streak below the stall threshold quiet', async () => {
+ vi.mocked(detectActionableWork).mockResolvedValue({ ...transient, remedy: 'Allow gh outbound.', detail: 'bad fd' });
+ const prepared = await prepareClaim('app-skip-verdict');
+ expect(prepared).toEqual({
+ task: null,
+ pendingPerpetualDispatch: null,
+ skip: { gate: 'perpetual-work', reason: 'gh-list-failed', cli: 'gh', remedy: 'Allow gh outbound.', detail: 'bad fd' },
+ });
+ expect(recordPerpetualStall).not.toHaveBeenCalled();
+ });
+
+ it('persists a stall on the 3rd CONSECUTIVE transient probe, and an actionable probe in between restarts the count', async () => {
+ const appId = 'app-skip-streak';
+ vi.mocked(detectActionableWork).mockResolvedValue(transient);
+ await prepareClaim(appId);
+ await prepareClaim(appId);
+ expect(recordPerpetualStall).not.toHaveBeenCalled();
+
+ // Recovery: the probe reports work again, which must clear the streak.
+ vi.mocked(detectActionableWork).mockResolvedValue({ actionable: true, count: 1, signature: null });
+ expect((await prepareClaim(appId)).skip).toBeNull();
+ recordPerpetualStall.mockClear();
+
+ vi.mocked(detectActionableWork).mockResolvedValue(transient);
+ await prepareClaim(appId);
+ await prepareClaim(appId);
+ expect(recordPerpetualStall).not.toHaveBeenCalled();
+ await prepareClaim(appId);
+ expect(recordPerpetualStall).toHaveBeenCalledWith('claim-issue', appId, expect.objectContaining({ consecutive: 3, cli: 'gh' }));
+ });
+
+ it('names the gate for an install-wide target request that has no managed app to run on', async () => {
+ const prepared = await prepareManagedAppImprovementTask('model-comparison-refresh', APP, STATE);
+ expect(prepared).toMatchObject({ task: null, pendingPerpetualDispatch: null, skip: { gate: 'install-wide-target', reason: null } });
+ });
+});
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index bbe65805ec..86f1c163ef 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -76,7 +76,8 @@ import {
emitOnDemandEmpty,
applyOnDemandConsent,
isConfiguredApprovalRequired,
- recordPerpetualTransient,
+ noteTransientProbe,
+ clearTransientProbeStreak,
PERPETUAL_TRANSIENT_ESCALATION_THRESHOLD,
buildJiraTicketTask,
buildClaimWorkTask,
@@ -370,11 +371,11 @@ describe('isConfiguredApprovalRequired', () => {
const selfStart = GEN_SRC.indexOf('export async function generateSelfImprovementTaskForType');
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, pendingPerpetualDispatch };`
+ // Bounded by the function's own `return { task, pendingPerpetualDispatch, skip: null };`
// 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));
+ const appBody = GEN_SRC.slice(appStart, GEN_SRC.indexOf('\n return { task, pendingPerpetualDispatch, skip: null };', appStart));
expect(appBody).toContain('stampApprovalReason(metadata, approval)');
});
@@ -414,7 +415,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, pendingPerpetualDispatch };', start));
+ const body = GEN_SRC.slice(start, GEN_SRC.indexOf('\n return { task, pendingPerpetualDispatch, skip: null };', start));
expect(body).toMatch(/selectionReason === 'on-demand'\) applyOnDemandConsent\(task\)/);
});
});
@@ -1187,7 +1188,7 @@ describe('emitOnDemandEmpty', () => {
ghHealth.mockResolvedValue({ status: 'ok', ok: true, detail: null, remedy: null });
});
- const emitTransient = async (taskType) => {
+ const emitTransient = async (taskType, skip = null) => {
const events = [];
const handler = (d) => events.push(d);
cosEvents.on('schedule:on-demand-empty', handler);
@@ -1196,7 +1197,8 @@ describe('emitOnDemandEmpty', () => {
taskScheduleMod: stubMod,
request: { id: 'req-2', taskType },
targetApp: { id: 'app-1', name: 'App One' },
- taskConfig: { type: 'on-demand', perpetual: true }
+ taskConfig: { type: 'on-demand', perpetual: true },
+ skip
});
} finally {
cosEvents.off('schedule:on-demand-empty', handler);
@@ -1211,21 +1213,8 @@ describe('emitOnDemandEmpty', () => {
});
it('treats a perpetual on-demand drain as detector-driven for transient feedback', async () => {
- recordPerpetualTransient('branch-reconcile', 'app-1', { cli: null, reason: 'probe-failed' });
- const events = [];
- const handler = (data) => events.push(data);
- cosEvents.on('schedule:on-demand-empty', handler);
- try {
- await emitOnDemandEmpty({
- taskScheduleMod: stubMod,
- request: { id: 'req-reconcile', taskType: 'branch-reconcile' },
- targetApp: { id: 'app-1', name: 'App One' },
- taskConfig: { type: 'on-demand', perpetual: true }
- });
- } finally {
- cosEvents.off('schedule:on-demand-empty', handler);
- }
- expect(events[0]).toMatchObject({ taskType: 'branch-reconcile', outcome: 'transient' });
+ const skip = { gate: 'perpetual-work', cli: null, reason: 'probe-failed', remedy: null, detail: null };
+ expect(await emitTransient('branch-reconcile', skip)).toMatchObject({ taskType: 'branch-reconcile', outcome: 'transient', forge: null });
});
it('skips the gh probe for a non-gh transient verdict, so a glab/git fault never toasts a gh remedy', async () => {
@@ -1233,76 +1222,60 @@ describe('emitOnDemandEmpty', () => {
// no forge at all (cli: null); claim-issue-gitlab fails on glab. None of them
// should be attributed to gh — the pre-fix suffix check got all three wrong.
for (const [taskType, cli] of [['claim-issue-gitlab', 'glab'], ['branch-reconcile', null], ['quota-burn', null]]) {
- recordPerpetualTransient(taskType, 'app-1', { cli, reason: 'probe-failed' });
- expect(await emitTransient(taskType)).toMatchObject({ outcome: 'transient', forge: null });
+ const skip = { gate: 'perpetual-work', cli, reason: 'probe-failed', remedy: null, detail: null };
+ expect(await emitTransient(taskType, skip)).toMatchObject({ outcome: 'transient', forge: null });
}
+ expect(ghHealth).not.toHaveBeenCalled();
});
it('names gh + its remedy when a gh verdict meets a gh that is broken for good', async () => {
ghHealth.mockResolvedValueOnce({
status: 'unreachable', ok: false, detail: 'bad file descriptor', remedy: 'Allow the gh binary outbound.'
});
- recordPerpetualTransient('claim-issue', 'app-1', { cli: 'gh', reason: 'gh-list-failed' });
- expect(await emitTransient('claim-issue')).toMatchObject({
+ expect(await emitTransient('claim-issue', { gate: 'perpetual-work', cli: 'gh', reason: 'gh-list-failed', remedy: null, detail: null })).toMatchObject({
outcome: 'transient',
forge: { cli: 'gh', remedy: 'Allow the gh binary outbound.' }
});
});
it('stays generic when gh itself is healthy — that failure really was a blip', async () => {
- recordPerpetualTransient('claim-issue', 'app-1', { cli: 'gh', reason: 'gh-list-failed' });
- expect(await emitTransient('claim-issue')).toMatchObject({ forge: null });
- });
-
- it('consumes the verdict on read, so a stale one cannot be reported twice', async () => {
- ghHealth.mockResolvedValue({ status: 'not-installed', ok: false, detail: null, remedy: 'Install gh.' });
- recordPerpetualTransient('claim-issue', 'app-1', { cli: 'gh', reason: 'gh-list-failed' });
- expect(await emitTransient('claim-issue')).toMatchObject({ forge: { cli: 'gh' } });
- // Second emit finds nothing recorded — the verdict belonged to the first run.
- expect(await emitTransient('claim-issue')).toMatchObject({ forge: null });
+ expect(await emitTransient('claim-issue', { gate: 'perpetual-work', cli: 'gh', reason: 'gh-list-failed', remedy: null, detail: null })).toMatchObject({ forge: null });
});
- it('keys the verdict by task type + app, so one type never consumes another\'s', async () => {
- ghHealth.mockResolvedValue({ status: 'not-installed', ok: false, detail: null, remedy: 'Install gh.' });
- recordPerpetualTransient('claim-issue', 'app-1', { cli: 'gh', reason: 'gh-list-failed' });
- // A different task type on the same app must not read claim-issue's verdict…
- expect(await emitTransient('pr-watcher')).toMatchObject({ forge: null });
- // …and it is still intact for the type that recorded it.
- expect(await emitTransient('claim-issue')).toMatchObject({ forge: { cli: 'gh' } });
+ it('passes a remedy the detector already named straight through, without asking gh', async () => {
+ // A per-repo permission the token lacks passes checkGhHealth's global-auth
+ // probe, so consulting it would drop the remedy this channel exists to carry.
+ expect(await emitTransient('claim-issue', { gate: 'perpetual-work', cli: 'gh', reason: 'gh-list-failed', remedy: null, detail: null, remedy: 'Grant the token collaborator read.' })).toMatchObject({
+ forge: { cli: 'gh', remedy: 'Grant the token collaborator read.' }
+ });
+ expect(ghHealth).not.toHaveBeenCalled();
});
- it('drops a verdict older than its TTL rather than explaining an unrelated run', async () => {
+ it('ignores a skip from a different gate, so only the work detector\'s verdict names a forge fault', async () => {
ghHealth.mockResolvedValue({ status: 'not-installed', ok: false, detail: null, remedy: 'Install gh.' });
- recordPerpetualTransient('claim-issue', 'app-1', { cli: 'gh', reason: 'gh-list-failed' });
- vi.useFakeTimers({ shouldAdvanceTime: true });
- vi.setSystemTime(Date.now() + 61_000);
- try {
- expect(await emitTransient('claim-issue')).toMatchObject({ forge: null });
- } finally {
- vi.useRealTimers();
- }
+ expect(await emitTransient('claim-issue', { gate: 'precondition', cli: 'gh', reason: null, remedy: null, detail: null })).toMatchObject({ forge: null });
+ expect(ghHealth).not.toHaveBeenCalled();
});
- it('recordPerpetualTransient counts CONSECUTIVE transient verdicts for the same taskType+app', () => {
- expect(recordPerpetualTransient('claim-issue', 'app-streak', { cli: 'gh', reason: 'gh-list-failed' })).toBe(1);
- expect(recordPerpetualTransient('claim-issue', 'app-streak', { cli: 'gh', reason: 'gh-list-failed' })).toBe(2);
- expect(recordPerpetualTransient('claim-issue', 'app-streak', { cli: 'gh', reason: 'gh-list-failed' })).toBe(3);
- expect(recordPerpetualTransient('claim-issue', 'app-streak', { cli: 'gh', reason: 'gh-list-failed' })).toBe(4);
+ it('noteTransientProbe counts CONSECUTIVE transient probes for the same taskType+app', () => {
+ expect(noteTransientProbe('claim-issue', 'app-streak')).toBe(1);
+ expect(noteTransientProbe('claim-issue', 'app-streak')).toBe(2);
+ expect(noteTransientProbe('claim-issue', 'app-streak')).toBe(3);
+ expect(noteTransientProbe('claim-issue', 'app-streak')).toBe(4);
});
- it('recordPerpetualTransient resets the streak to 0 on a null (actionable/idle) verdict', () => {
- recordPerpetualTransient('claim-issue', 'app-streak-2', { cli: 'gh', reason: 'gh-list-failed' });
- recordPerpetualTransient('claim-issue', 'app-streak-2', { cli: 'gh', reason: 'gh-list-failed' });
- expect(recordPerpetualTransient('claim-issue', 'app-streak-2', null)).toBe(0);
- // The next transient verdict after a reset starts the streak over at 1, not
- // where it left off — a recovered probe means the escalation clock restarts.
- expect(recordPerpetualTransient('claim-issue', 'app-streak-2', { cli: 'gh', reason: 'gh-list-failed' })).toBe(1);
+ it('clearTransientProbeStreak restarts the count, so a recovered probe resets the escalation clock', () => {
+ noteTransientProbe('claim-issue', 'app-streak-2');
+ noteTransientProbe('claim-issue', 'app-streak-2');
+ clearTransientProbeStreak('claim-issue', 'app-streak-2');
+ expect(noteTransientProbe('claim-issue', 'app-streak-2')).toBe(1);
});
- it('recordPerpetualTransient keys the streak by taskType+app, so one app never inherits another\'s count', () => {
- recordPerpetualTransient('claim-issue', 'app-streak-a', { cli: 'gh', reason: 'gh-list-failed' });
- recordPerpetualTransient('claim-issue', 'app-streak-a', { cli: 'gh', reason: 'gh-list-failed' });
- expect(recordPerpetualTransient('claim-issue', 'app-streak-b', { cli: 'gh', reason: 'gh-list-failed' })).toBe(1);
+ it('noteTransientProbe keys the streak by taskType+app, so one app never inherits another\'s count', () => {
+ noteTransientProbe('claim-issue', 'app-streak-a');
+ noteTransientProbe('claim-issue', 'app-streak-a');
+ expect(noteTransientProbe('claim-issue', 'app-streak-b')).toBe(1);
+ expect(noteTransientProbe('pr-watcher', 'app-streak-a')).toBe(1);
});
it('the escalation threshold is exported and applyPerpetualWorkGate levels its skip log against it, persisting a stall once escalated', () => {
@@ -1314,20 +1287,8 @@ describe('emitOnDemandEmpty', () => {
expect(gate).toContain('taskSchedule.recordPerpetualStall(taskType, app.id,');
});
- it('the actionable path resets both the transient streak and the persisted stall before deciding to dispatch or no-progress-park', () => {
- const start = GEN_SRC.indexOf('async function applyPerpetualWorkGate');
- const gate = GEN_SRC.slice(start, GEN_SRC.indexOf('\n}', start));
- const actionableIdx = gate.indexOf('if (detection.actionable) {');
- const resetIdx = gate.indexOf('recordPerpetualTransient(taskType, app.id, null);');
- const stallClearIdx = gate.indexOf('taskSchedule.recordPerpetualStall(taskType, app.id, null);');
- expect(actionableIdx).toBeGreaterThan(-1);
- expect(resetIdx).toBeGreaterThan(actionableIdx);
- expect(stallClearIdx).toBeGreaterThan(actionableIdx);
- });
-
- it("surfaces the pr-reviewer preflight's recorded skip reason on an idle outcome", async () => {
+ it("surfaces the pr-reviewer preflight's skip reason on an idle outcome", async () => {
const persist = vi.spyOn(taskStore, 'addTask').mockResolvedValue({ id: 'diagnostic' });
- recordPerpetualTransient('pr-reviewer', 'app-1', { reason: 'security-guard-not-ready' });
const events = [];
const handler = (d) => events.push(d);
cosEvents.on('schedule:on-demand-empty', handler);
@@ -1336,7 +1297,8 @@ describe('emitOnDemandEmpty', () => {
taskScheduleMod: stubMod,
request: { id: 'req-pr-reviewer', taskType: 'pr-reviewer' },
targetApp: { id: 'app-1', name: 'PortOS' },
- taskConfig: { type: 'on-demand', perpetual: false }
+ taskConfig: { type: 'on-demand', perpetual: false },
+ skip: { gate: 'security-preflight', reason: 'security-guard-not-ready', cli: null, remedy: null, detail: null }
});
} finally {
cosEvents.off('schedule:on-demand-empty', handler);
@@ -1349,37 +1311,26 @@ describe('emitOnDemandEmpty', () => {
persist.mockRestore();
});
- it('consumes the pr-reviewer skip reason on read, so a stale one cannot be reported twice', async () => {
- recordPerpetualTransient('pr-reviewer', 'app-1', { reason: 'no-external-open-prs' });
- const first = [];
- let handler = (d) => first.push(d);
- cosEvents.on('schedule:on-demand-empty', handler);
- try {
- await emitOnDemandEmpty({
- taskScheduleMod: stubMod,
- request: { id: 'req-a', taskType: 'pr-reviewer' },
- targetApp: { id: 'app-1', name: 'PortOS' },
- taskConfig: { type: 'on-demand', perpetual: false }
- });
- } finally {
- cosEvents.off('schedule:on-demand-empty', handler);
- }
- expect(first[0]).toMatchObject({ reason: 'no-external-open-prs' });
-
- const second = [];
- handler = (d) => second.push(d);
- cosEvents.on('schedule:on-demand-empty', handler);
- try {
- await emitOnDemandEmpty({
- taskScheduleMod: stubMod,
- request: { id: 'req-b', taskType: 'pr-reviewer' },
- targetApp: { id: 'app-1', name: 'PortOS' },
- taskConfig: { type: 'on-demand', perpetual: false }
- });
- } finally {
- cosEvents.off('schedule:on-demand-empty', handler);
- }
- expect(second[0]).toMatchObject({ reason: null });
+ it('reports no pr-reviewer reason when the skip came from a later gate or there was none', async () => {
+ const reasonFor = async (skip) => {
+ const events = [];
+ const handler = (d) => events.push(d);
+ cosEvents.on('schedule:on-demand-empty', handler);
+ try {
+ await emitOnDemandEmpty({
+ taskScheduleMod: stubMod,
+ request: { id: 'req-b', taskType: 'pr-reviewer' },
+ targetApp: { id: 'app-1', name: 'PortOS' },
+ taskConfig: { type: 'on-demand', perpetual: false },
+ skip
+ });
+ } finally {
+ cosEvents.off('schedule:on-demand-empty', handler);
+ }
+ return events[0].reason;
+ };
+ expect(await reasonFor(null)).toBeNull();
+ expect(await reasonFor({ gate: 'precondition', reason: 'ignored', cli: null, remedy: null, detail: null })).toBeNull();
});
it('reads the LI last-run reason only for the layered-intelligence task type', () => {
@@ -1719,7 +1670,7 @@ describe('resolveTaskInputHook — hookMetadata threading (#3179)', () => {
// 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 prepareManagedAppImprovementTask');
- const body = GEN_SRC.slice(start, GEN_SRC.indexOf('return { task, pendingPerpetualDispatch };', start));
+ const body = GEN_SRC.slice(start, GEN_SRC.indexOf('return { task, pendingPerpetualDispatch, skip: null };', 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.
@@ -1729,15 +1680,15 @@ describe('resolveTaskInputHook — hookMetadata threading (#3179)', () => {
it('stamps the bag onto metadata BELOW every gate that can still skip task creation', () => {
// The ordering IS the fix. Source-pinned because it is invisible to a unit
// 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
+ // `return skipped(...)` 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 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, pendingPerpetualDispatch };` ends it.
- const lastGateAt = body.slice(0, body.indexOf('return { task, pendingPerpetualDispatch };')).lastIndexOf('return null;');
+ // Bound the scan to this function: `return { task, pendingPerpetualDispatch, skip: null };` ends it.
+ const lastGateAt = body.slice(0, body.indexOf('return { task, pendingPerpetualDispatch, skip: null };')).lastIndexOf('return skipped(');
expect(lastGateAt, 'the gate chain must exist').toBeGreaterThan(-1);
expect(stampAt).toBeGreaterThan(lastGateAt);
});
@@ -1752,7 +1703,7 @@ describe('resolveTaskInputHook — hookMetadata threading (#3179)', () => {
describe('ignoreTaskId reaches the in-flight-counting gates (#3179)', () => {
const body = () => {
const start = GEN_SRC.indexOf('export async function prepareManagedAppImprovementTask');
- return GEN_SRC.slice(start, GEN_SRC.indexOf('return { task, pendingPerpetualDispatch };', start));
+ return GEN_SRC.slice(start, GEN_SRC.indexOf('return { task, pendingPerpetualDispatch, skip: null };', start));
};
it('accepts ignoreTaskId and forwards it to the input hook and the perpetual gate', () => {
@@ -1816,7 +1767,7 @@ describe('ignoreTaskId reaches BOTH completion-continuation generators (#3179)',
describe('the drain cap has exactly one implementation, at the choke point', () => {
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 body = GEN_SRC.slice(start, GEN_SRC.indexOf('return { task, pendingPerpetualDispatch, skip: null };', 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('));
@@ -1857,7 +1808,7 @@ describe('the drain cap has exactly one implementation, at the choke point', ()
// (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));
+ const body = GEN_SRC.slice(genStart, GEN_SRC.indexOf('return { task, pendingPerpetualDispatch, skip: null };', 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);
@@ -1918,7 +1869,7 @@ describe('pr-reviewer security preflight wiring', () => {
// 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 prepareManagedAppImprovementTask');
- const body = GEN_SRC.slice(start, GEN_SRC.indexOf('return { task, pendingPerpetualDispatch };', start));
+ const body = GEN_SRC.slice(start, GEN_SRC.indexOf('return { task, pendingPerpetualDispatch, skip: null };', 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)');
@@ -1927,11 +1878,8 @@ describe('pr-reviewer security preflight wiring', () => {
expect(preconditionAt, 'the ordinary stage gate must remain in the generator').toBeGreaterThan(-1);
expect(preflightAt).toBeLessThan(preconditionAt);
expect(promptAt, 'a passed preflight must select the current pipeline stage body').toBeGreaterThan(-1);
- // The skip reason must be recorded before the `return null;` — otherwise a
- // user-initiated "Review this PR" that hits the security guard, an unreviewable
- // target PR, etc. reports the generic "nothing to do" toast instead of why.
- expect(body).toContain("recordPerpetualTransient('pr-reviewer', app.id, securityPreflight.skipped ? { reason: securityPreflight.reason || null } : null)");
- expect(body).toContain('if (securityPreflight.skipped) return null;');
+ // The skip reason rides the returned `skip` (behavioral test in
+ // cosTaskGenerator.idleReviewSteal.test.js) — nothing is recorded on the side.
});
it('carries a stolen on-demand request\'s PR target through the idle-review path', () => {
@@ -1945,7 +1893,7 @@ describe('pr-reviewer security preflight wiring', () => {
it('keeps a targeted run distinguishable from the sweep in the duplicate guard', () => {
const genStart = GEN_SRC.indexOf('export async function prepareManagedAppImprovementTask');
- const body = GEN_SRC.slice(genStart, GEN_SRC.indexOf('return { task, pendingPerpetualDispatch };', genStart));
+ const body = GEN_SRC.slice(genStart, GEN_SRC.indexOf('return { task, pendingPerpetualDispatch, skip: null };', genStart));
expect(body).toContain('scopeDescriptionToPullRequest(');
});
});
diff --git a/server/services/developmentWatchdog.js b/server/services/developmentWatchdog.js
index dc90c8a0c5..dc30bfc964 100644
--- a/server/services/developmentWatchdog.js
+++ b/server/services/developmentWatchdog.js
@@ -244,7 +244,7 @@ async function dispatch(app, decision) {
if (owner) return { taskId: owner.id, duplicate: true };
const { prepareManagedAppImprovementTask, recordDeferredPerpetualDispatch } = await import('./cosTaskGenerator.js');
const prepared = await prepareManagedAppImprovementTask('claim-issue', app, current);
- if (!prepared?.task) return { reason: 'claim-schedule-no-work' };
+ if (!prepared.task) return { reason: 'claim-schedule-no-work' };
const finalState = await loadState();
if (authorityLost(finalState, app.id) || !isImprovementEnabled(finalState)) return { reason: 'authority-changed' };
const task = await addTask({ ...prepared.task, metadata: { ...prepared.task.metadata,
diff --git a/server/services/developmentWatchdog.test.js b/server/services/developmentWatchdog.test.js
index 94952cf916..bedc7408fb 100644
--- a/server/services/developmentWatchdog.test.js
+++ b/server/services/developmentWatchdog.test.js
@@ -300,7 +300,7 @@ it('leaves scheduled brakes intact and does not spend dispatches on rejected wor
expect((await runDevelopmentWatchdog({ force: true })).decisions[0].outcome).toBe('already-owned');
expect(m.record).not.toHaveBeenCalled(); expect(m.execution).not.toHaveBeenCalled();
m.duplicate = false;
- m.prepare.mockResolvedValue(null);
+ m.prepare.mockResolvedValue({ task: null, pendingPerpetualDispatch: null, skip: { gate: 'perpetual-work', reason: null, cli: null, remedy: null, detail: null } });
expect((await runDevelopmentWatchdog({ force: true })).decisions[0].reason).toBe('claim-schedule-no-work');
expect(m.adds).toEqual([]); expect(m.record).not.toHaveBeenCalled();
});
diff --git a/server/services/onDemandDrain.js b/server/services/onDemandDrain.js
index e412055ddc..adf9b3fee4 100644
--- a/server/services/onDemandDrain.js
+++ b/server/services/onDemandDrain.js
@@ -167,6 +167,9 @@ export async function drainOnDemandRequests(ctx, adapter) {
// discovered by re-finding the task object, so it survives regardless of
// which task-object variant `addTask` below hands back (#6871).
let pendingPerpetualDispatch = null;
+ // Why prepare declined to build a task (null when it built one or there was
+ // no managed app) — handed to emitOnDemandEmpty so the toast can say why.
+ let skip = null;
// Determine target app (if any)
let targetApp = null;
@@ -236,8 +239,9 @@ 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;
+ task = prepared.task;
+ pendingPerpetualDispatch = prepared.pendingPerpetualDispatch;
+ skip = prepared.skip;
if (task) {
await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);
}
@@ -295,7 +299,7 @@ export async function drainOnDemandRequests(ctx, adapter) {
// `userInitiated` only: a drain refill ends by converging (that's the point),
// and nobody is waiting on it, so toasting "nothing to do" for every automated
// hop would turn a healthy overnight drain into a pile of notifications.
- await emitOnDemandEmpty({ taskScheduleMod, request, targetApp, taskConfig: schedule.tasks[request.taskType], preflightCardId: cardId });
+ await emitOnDemandEmpty({ taskScheduleMod, request, targetApp, taskConfig: schedule.tasks[request.taskType], preflightCardId: cardId, skip });
}
// Every other exit from this iteration (a task that capacity refused, or a
// refill with no task) still owes the card a close — a card left open would
diff --git a/server/services/onDemandDrain.test.js b/server/services/onDemandDrain.test.js
index e132599c22..d946adc422 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 () => {}),
- prepareManagedAppImprovementTask: vi.fn(async () => ({ task: { id: 'gen-1', priority: 'HIGH' }, pendingPerpetualDispatch: null })),
+ prepareManagedAppImprovementTask: vi.fn(async () => ({ task: { id: 'gen-1', priority: 'HIGH' }, pendingPerpetualDispatch: null, skip: null })),
generateSelfImprovementTaskForType: vi.fn(async () => ({ id: 'self-1', priority: 'HIGH' })),
recordDeferredPerpetualDispatch: vi.fn(async () => {}),
applyOnDemandConsent: vi.fn((t) => t),
@@ -147,7 +147,7 @@ beforeEach(() => {
mocks.applyOnDemandRunResets.mockResolvedValue(true);
mocks.getActiveApps.mockResolvedValue([APP]);
mocks.addTask.mockResolvedValue({ id: 'persisted-1' });
- mocks.prepareManagedAppImprovementTask.mockResolvedValue({ task: { id: 'gen-1', priority: 'HIGH' }, pendingPerpetualDispatch: null });
+ mocks.prepareManagedAppImprovementTask.mockResolvedValue({ task: { id: 'gen-1', priority: 'HIGH' }, pendingPerpetualDispatch: null, skip: null });
mocks.generateSelfImprovementTaskForType.mockResolvedValue({ id: 'self-1', priority: 'HIGH' });
mocks.drainProgrammaticOnDemandRequests.mockResolvedValue(new Set());
mocks.applyOnDemandConsent.mockImplementation((t) => t);
@@ -241,18 +241,19 @@ 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.prepareManagedAppImprovementTask.mockResolvedValue(null);
+ mocks.prepareManagedAppImprovementTask.mockResolvedValue({ task: null, pendingPerpetualDispatch: null, skip: { gate: 'security-preflight', reason: 'no-external-open-prs', cli: null, remedy: null, detail: null } });
mocks.applyOnDemandRunResets.mockResolvedValue(true);
const { adapter } = makeAdapter();
await drainOnDemandRequests({ state: STATE }, adapter);
expect(mocks.emitOnDemandEmpty).toHaveBeenCalledTimes(1);
- expect(mocks.emitOnDemandEmpty.mock.calls[0][0]).toMatchObject({ targetApp: APP });
+ // The skip is handed over explicitly — no side channel to read back later.
+ expect(mocks.emitOnDemandEmpty.mock.calls[0][0]).toMatchObject({ targetApp: APP, skip: { gate: 'security-preflight', reason: 'no-external-open-prs' } });
});
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.prepareManagedAppImprovementTask.mockResolvedValue(null);
+ mocks.prepareManagedAppImprovementTask.mockResolvedValue({ task: null, pendingPerpetualDispatch: null, skip: { gate: 'security-preflight', reason: 'no-external-open-prs', cli: null, remedy: null, detail: null } });
mocks.applyOnDemandRunResets.mockResolvedValue(false);
const { adapter } = makeAdapter();
await drainOnDemandRequests({ state: STATE }, adapter);
@@ -401,7 +402,7 @@ describe.each(ENGINES)('%s — app-review marker discipline (#978)', (_name, mak
it('binds the active agent only once a task actually exists', async () => {
mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);
- mocks.prepareManagedAppImprovementTask.mockResolvedValue(null);
+ mocks.prepareManagedAppImprovementTask.mockResolvedValue({ task: null, pendingPerpetualDispatch: null, skip: { gate: 'security-preflight', reason: 'no-external-open-prs', cli: null, remedy: null, detail: null } });
const { adapter } = makeAdapter();
await drainOnDemandRequests({ state: STATE }, adapter);
// The cooldown still advanced — only the bind is deferred, so a null
@@ -599,7 +600,7 @@ describe('preflight task card', () => {
it('leaves no card open when the run produces nothing', async () => {
mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);
- mocks.prepareManagedAppImprovementTask.mockResolvedValue({ task: null, pendingPerpetualDispatch: null });
+ mocks.prepareManagedAppImprovementTask.mockResolvedValue({ task: null, pendingPerpetualDispatch: null, skip: null });
const { adapter } = generatorAdapter();
await drainOnDemandRequests({ state: STATE }, adapter);
// emitOnDemandEmpty owns the specific reason; this is the backstop close.