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: share one on-demand eligibility ladder between triggerOnDemandTask and the quota-burn catalog

[._.]/ Adam Eivy7b2a4df58af4
diff --git a/server/lib/README.md b/server/lib/README.md
index 65dcc95f68..88b34dea94 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -68,6 +68,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `quotaBurnPresets.js` | `QUOTA_BURN_PROMPT_PRESETS` — ready-made single-focus audit prompts for `agent-prompt` burn jobs (UX, a11y, mobile, failure paths, perf, test gaps, dead code, data safety, docs, security), each filing GitHub issues and changing no code. Templates: picking one COPIES its prompt into the job, so editing them never rewrites a configured job. `findQuotaBurnPreset(id)`. |
| `auditCatalog.js` | Shared catalog of scheduled AUDIT task types (`AUDIT_DEFINITIONS` / `AUDIT_TASK_TYPES`) that can either implement a fix or file tracker issues. `isFileIssuesMode`, `isExplicitFileIssuesRequest`, `FILE_ISSUES_DELIVERY_SETTINGS` (the one delivery posture every file-issues lane stamps), `auditDoWorkRequiresWorktree`, `getAuditFilingPreset`, `modeContractFor`, `applyAuditModeWrapper`. Each quota-burn audit preset maps to a scheduled type here (guarded by `auditCatalog.test.js`). Pure — no I/O. |
| `quotaBurnTaskRef.js` | The quota-burn STEP model: a discriminated scheduled-task reference (`builtin` task type + validated target app, or `custom` app-job id whose own scope is authoritative) plus the per-invocation `overrides` bag (provider/model/effort/params — unset inherits the task's saved settings, and nothing written here edits the schedule). `normalizeQuotaBurnTaskRef` / `normalizeQuotaBurnOverrides` / `normalizeQuotaBurnParams`, the `QUOTA_BURN_UNAVAILABLE` reason codes, `resolveQuotaBurnStepAvailability` (catalog passed IN, so this stays pure) / `applyQuotaBurnAvailability`, and `quotaBurnStepIsDispatchable`. |
+| `auditCatalog.js` | Shared catalog of scheduled AUDIT task types (`AUDIT_DEFINITIONS` / `AUDIT_TASK_TYPES`) that can either implement a fix or file tracker issues. `isFileIssuesMode`, `auditDoWorkRequiresWorktree`, `getAuditFilingPreset`, `modeContractFor`, `applyAuditModeWrapper`. Each quota-burn audit preset maps to a scheduled type here (guarded by `auditCatalog.test.js`). Pure — no I/O. |
+| `quotaBurnTaskRef.js` | The quota-burn STEP model: a discriminated scheduled-task reference (`builtin` task type + validated target app, or `custom` app-job id whose own scope is authoritative) plus the per-invocation `overrides` bag (provider/model/effort/params — unset inherits the task's saved settings, and nothing written here edits the schedule). `normalizeQuotaBurnTaskRef` / `normalizeQuotaBurnOverrides` / `normalizeQuotaBurnParams`, the `QUOTA_BURN_UNAVAILABLE` reason codes, `resolveQuotaBurnStepAvailability` (catalog passed IN, so this stays pure) / `applyQuotaBurnAvailability`, `quotaBurnStepIsDispatchable`, and `evaluateOnDemandEligibility` — the ONE on-demand gate ladder (`enabled` / instance feature / invocation eligibility / target scope / per-app switch / master Improve) shared with `taskSchedule.triggerOnDemandTask`, with `enabledAppIdsByTaskType` deriving its per-app input. |
| `quotaBurnValidation.js` | Zod schemas for the Quota Burn routes (partial config PUT, manual-run body, `run once` re-arm body). |
| `quotaReset.js` | `parseHumanReset` turns a provider CLI's human reset string into ISO 8601 (call it from the adapter); `normalizeResetAt`/`hoursUntilReset` compute time remaining without treating unknown values as imminent resets; `parseObservedReset` pulls the reset a provider stated in its own refusal text, and `isObservedBlockActive` is the shared "is that refusal still holding?" predicate every observed-refusal ledger uses. |
| `quotaWindows.js` | Classifies a quota window by PERIOD (`windowPeriodHours`); `classifyWindows` splits one card's windows into the weekly allowance that expires unused and the 5-hour one that refuses first, in one pass. `windowLabelOf` names a window. Pure. |
diff --git a/server/lib/quotaBurnTaskRef.js b/server/lib/quotaBurnTaskRef.js
index de55d8c46d..0bffb8aec6 100644
--- a/server/lib/quotaBurnTaskRef.js
+++ b/server/lib/quotaBurnTaskRef.js
@@ -23,6 +23,14 @@
*
* Pure: shape, normalization, and a resolver that takes the catalog as an
* argument. No storage, no provider I/O, no imports out of `lib/`.
+ *
+ * `evaluateOnDemandEligibility` below is deliberately WIDER than the burn: it is
+ * the one gate ladder for invoking a built-in scheduled task on demand, read
+ * both by this module's resolver (so the page can say why a step cannot run) and
+ * by `taskSchedule.triggerOnDemandTask` (so dispatch refuses for the same
+ * reasons). It lives here because the reason codes and their prose already do,
+ * and because a `lib/` module is the only place both a service and a display
+ * path can share without one importing the other (#6405).
*/
import { isPlainObject, POLLUTING_KEYS } from './objects.js';
@@ -58,6 +66,14 @@ export const QUOTA_BURN_UNAVAILABLE = Object.freeze({
WRONG_SCOPE: 'wrong-scope',
/** The task exists and is enabled, but is not something a burn may invoke. */
INCOMPATIBLE: 'incompatible',
+ /**
+ * The master CoS Improve switch is off — or its state could not be read, which
+ * fails closed into the same verdict. Its own code rather than `DISABLED`: the
+ * referenced task is not switched off and telling the user to re-enable it in
+ * Scheduled Tasks would send them to a toggle that is already on. The fix
+ * lives in CoS → Config, and every step reports it at once.
+ */
+ IMPROVEMENT_DISABLED: 'improvement-disabled',
});
const MAX_REF_FIELD = 64;
@@ -130,6 +146,102 @@ export function normalizeQuotaBurnParams(raw, maxParamLength) {
const unavailable = (code, reason) => ({ code, reason });
+/**
+ * The master Improve rung, shared by every kind of step and by the schedule's
+ * own on-demand lane so the switch is read the same way everywhere.
+ *
+ * Three input states, per the sentinel rule: `undefined` is "the caller did not
+ * check" and goes unjudged, `null` is "checked and could not tell" and fails
+ * CLOSED, a boolean is the answer.
+ */
+function improvementVerdict(improvementEnabled) {
+ if (improvementEnabled === undefined || improvementEnabled === true) return null;
+ return unavailable(
+ QUOTA_BURN_UNAVAILABLE.IMPROVEMENT_DISABLED,
+ improvementEnabled === null
+ ? 'CoS state could not be read, so Improvement cannot be confirmed'
+ : 'Improvement is disabled — enable it in CoS → Config to run on-demand tasks',
+ );
+}
+
+/**
+ * The ONE gate ladder deciding whether a built-in scheduled task may be invoked
+ * on demand — read by `taskSchedule.triggerOnDemandTask` before it queues a
+ * request, and by the quota-burn catalog to say why a step cannot run. Two
+ * consumers, one ladder: a gate added here reaches dispatch and the page in the
+ * same change, which is the step-level version of what `evaluateFamily` already
+ * does for a burn family (docs/QUOTA-BURN.md).
+ *
+ * Pure, and the catalog is an ARGUMENT: the facts about a task type live in the
+ * schedule store, the instance-feature service and the app store, so the caller
+ * resolves them and hands them in as `entry`.
+ *
+ * entry === undefined the caller has no catalog — every per-type rung goes
+ * unjudged, so a read taken before the schedule store is
+ * up cannot mass-orphan a user's plan.
+ * entry === null the catalog was read and this type is not on it.
+ * entry === object `{ enabled, featureEnabled, feature, eligible, appIds }`,
+ * each key `undefined` when that fact is unknown.
+ * `eligible` — false for a type another automation owns
+ * (`invocation.userInvokable === false`).
+ * `appIds` — the managed apps with this type switched ON. Supplied
+ * only by a caller that ENFORCES per-app enablement (see
+ * `enabledAppIdsByTaskType`); omitted, the rung is
+ * skipped, which is how a human "Run Now" keeps its
+ * deliberate override of the app's cadence switch.
+ *
+ * Target SCOPE is judged with or without an entry, deliberately: it is a
+ * property of the reference itself, so a hand-edited step that dropped its
+ * required app is broken whether or not a catalog is to hand.
+ */
+export function evaluateOnDemandEligibility({ taskType, appId = null, entry, improvementEnabled } = {}) {
+ if (entry === null) return unavailable(QUOTA_BURN_UNAVAILABLE.UNKNOWN_TASK, `Unknown task type '${taskType}'`);
+ if (isPlainObject(entry)) {
+ if (entry.enabled === false) {
+ return unavailable(QUOTA_BURN_UNAVAILABLE.DISABLED, `Task type '${taskType}' is disabled`);
+ }
+ if (entry.featureEnabled === false) {
+ return unavailable(QUOTA_BURN_UNAVAILABLE.DISABLED, `Task type '${taskType}' requires the '${entry.feature}' feature`);
+ }
+ if (entry.eligible === false) {
+ return unavailable(QUOTA_BURN_UNAVAILABLE.INCOMPATIBLE, `Task type '${taskType}' is managed by another automation and cannot be invoked on demand`);
+ }
+ }
+
+ if (requiresManagedAppTarget(taskType) && !appId) {
+ return unavailable(QUOTA_BURN_UNAVAILABLE.MISSING_APP, `Task type '${taskType}' requires a managed app target`);
+ }
+ if (requiresInstallWideTarget(taskType) && appId) {
+ return unavailable(QUOTA_BURN_UNAVAILABLE.WRONG_SCOPE, `Task type '${taskType}' requires an install-wide target (no app)`);
+ }
+ if (appId && Array.isArray(entry?.appIds) && !entry.appIds.includes(appId)) {
+ return unavailable(QUOTA_BURN_UNAVAILABLE.WRONG_SCOPE, `Task type '${taskType}' is not enabled for app '${appId}'`);
+ }
+
+ return improvementVerdict(improvementEnabled);
+}
+
+/**
+ * `Map<taskType, appId[]>` of the managed apps that have each built-in type
+ * switched ON, derived from app records the caller already loaded.
+ *
+ * An app with no override for a type is NOT in its list: no override means
+ * disabled (`apps.isTaskTypeEnabledForApp`), which is the same reading the
+ * scheduled fire applies. Shared so the burn catalog and the schedule's own
+ * on-demand lane cannot disagree about which apps a type may target.
+ */
+export function enabledAppIdsByTaskType(apps) {
+ const byTaskType = new Map();
+ for (const app of apps || []) {
+ for (const [taskType, override] of Object.entries(app?.taskTypeOverrides || {})) {
+ if (override?.enabled !== true) continue;
+ if (!byTaskType.has(taskType)) byTaskType.set(taskType, []);
+ byTaskType.get(taskType).push(app.id);
+ }
+ }
+ return byTaskType;
+}
+
/**
* Resolve one normalized step against the live task catalog and return its
* `{ code, reason }` unavailability, or `null` when the step is good to run.
@@ -138,19 +250,19 @@ const unavailable = (code, reason) => ({ code, reason });
* store and the per-app job store, which are services, and this module must
* stay in `lib/`. Callers pass plain lookup maps:
*
- * builtin: { [taskType]: { enabled, eligible, appIds } }
- * `appIds` — the managed apps this type may target, or `null`/absent for
- * "any app on the install". `eligible` — false for a type a burn may not
- * invoke (shell jobs, system-managed-only actions); absent reads as true.
+ * builtin: { [taskType]: { enabled, featureEnabled, feature, eligible, appIds } }
+ * — the `entry` shape `evaluateOnDemandEligibility` reads, which is
+ * where every built-in rung is decided.
* custom: { [jobId]: { enabled, eligible, appId } }
+ * improvementEnabled: the master CoS Improve switch (`null` = unreadable).
*
* An EMPTY catalog answers only the questions that need one. Existence, enabled
- * state and eligibility all go unjudged — with no `builtin`/`custom` map the
- * step keeps whatever the normalizer already decided rather than being declared
- * dangling, so a caller reading the plan before the schedule store is up cannot
- * mass-orphan a user's plan. Target SCOPE is the exception, and deliberately so:
- * it is a property of the reference itself, decidable from the payload alone, so
- * it is judged either way.
+ * state, eligibility and the Improve switch all go unjudged — with no
+ * `builtin`/`custom` map the step keeps whatever the normalizer already decided
+ * rather than being declared dangling, so a caller reading the plan before the
+ * schedule store is up cannot mass-orphan a user's plan. Target SCOPE is the
+ * exception, and deliberately so: it is a property of the reference itself,
+ * decidable from the payload alone, so it is judged either way.
*/
export function resolveQuotaBurnStepAvailability(step, catalog = {}) {
// A legacy step's verdict is decided by the payload itself, not by the
@@ -159,36 +271,33 @@ export function resolveQuotaBurnStepAvailability(step, catalog = {}) {
const ref = step?.taskRef;
if (!ref) return step?.unavailable || null;
- if (ref.kind === QUOTA_BURN_TASK_REF_KIND.CUSTOM) {
- const jobs = isPlainObject(catalog.custom) ? catalog.custom : null;
- if (!jobs) return null;
- const job = Object.hasOwn(jobs, ref.jobId) ? jobs[ref.jobId] : null;
- if (!job) return unavailable(QUOTA_BURN_UNAVAILABLE.DANGLING_JOB, `custom scheduled job "${ref.jobId}" no longer exists`);
- if (job.eligible === false) return unavailable(QUOTA_BURN_UNAVAILABLE.INCOMPATIBLE, `custom scheduled job "${ref.jobId}" cannot be invoked by a quota burn`);
- if (job.enabled === false) return unavailable(QUOTA_BURN_UNAVAILABLE.DISABLED, `custom scheduled job "${ref.jobId}" is disabled`);
- return null;
- }
-
- // Scope runs BEFORE the catalog lookup so a hand-edited config that dropped a
- // required app reports the missing app rather than a confusing "unknown task"
- // — the type is fine, the target is not — and so it still reports at all when
- // the caller has no catalog to hand.
- if (requiresManagedAppTarget(ref.taskType) && !ref.appId) {
- return unavailable(QUOTA_BURN_UNAVAILABLE.MISSING_APP, `scheduled task "${ref.taskType}" must name a managed app`);
- }
- if (requiresInstallWideTarget(ref.taskType) && ref.appId) {
- return unavailable(QUOTA_BURN_UNAVAILABLE.WRONG_SCOPE, `scheduled task "${ref.taskType}" runs install-wide and cannot target one app`);
- }
+ // The reference's OWN problems outrank the master switch: a user who turns
+ // Improve back on should not then discover a dangling job the page could have
+ // named all along.
+ const specific = ref.kind === QUOTA_BURN_TASK_REF_KIND.CUSTOM
+ ? customJobAvailability(ref, catalog)
+ : evaluateOnDemandEligibility({
+ taskType: ref.taskType,
+ appId: ref.appId,
+ entry: builtinEntry(ref.taskType, catalog),
+ });
+ return specific || improvementVerdict(catalog.improvementEnabled);
+}
+/** `undefined` when the caller passed no built-in map, `null` when it has no such type. */
+function builtinEntry(taskType, catalog) {
const types = isPlainObject(catalog.builtin) ? catalog.builtin : null;
- if (!types) return null;
- const entry = Object.hasOwn(types, ref.taskType) ? types[ref.taskType] : null;
- if (!entry) return unavailable(QUOTA_BURN_UNAVAILABLE.UNKNOWN_TASK, `scheduled task "${ref.taskType}" is not available on this install`);
- if (entry.eligible === false) return unavailable(QUOTA_BURN_UNAVAILABLE.INCOMPATIBLE, `scheduled task "${ref.taskType}" cannot be invoked by a quota burn`);
- if (entry.enabled === false) return unavailable(QUOTA_BURN_UNAVAILABLE.DISABLED, `scheduled task "${ref.taskType}" is disabled`);
- if (ref.appId && Array.isArray(entry.appIds) && !entry.appIds.includes(ref.appId)) {
- return unavailable(QUOTA_BURN_UNAVAILABLE.WRONG_SCOPE, `scheduled task "${ref.taskType}" is not configured for app "${ref.appId}"`);
- }
+ if (!types) return undefined;
+ return Object.hasOwn(types, taskType) ? types[taskType] : null;
+}
+
+function customJobAvailability(ref, catalog) {
+ const jobs = isPlainObject(catalog.custom) ? catalog.custom : null;
+ if (!jobs) return null;
+ const job = Object.hasOwn(jobs, ref.jobId) ? jobs[ref.jobId] : null;
+ if (!job) return unavailable(QUOTA_BURN_UNAVAILABLE.DANGLING_JOB, `custom scheduled job "${ref.jobId}" no longer exists`);
+ if (job.eligible === false) return unavailable(QUOTA_BURN_UNAVAILABLE.INCOMPATIBLE, `custom scheduled job "${ref.jobId}" cannot be invoked by a quota burn`);
+ if (job.enabled === false) return unavailable(QUOTA_BURN_UNAVAILABLE.DISABLED, `custom scheduled job "${ref.jobId}" is disabled`);
return null;
}
diff --git a/server/services/onDemandEligibilityAgreement.test.js b/server/services/onDemandEligibilityAgreement.test.js
new file mode 100644
index 0000000000..491f7f37d0
--- /dev/null
+++ b/server/services/onDemandEligibilityAgreement.test.js
@@ -0,0 +1,143 @@
+/**
+ * The Quota Burn page and the schedule's on-demand lane must give the SAME
+ * answer about the SAME task, rung for rung (#6405).
+ *
+ * Both sides read one ladder now (`evaluateOnDemandEligibility`), but they fill
+ * its inputs from different places — the page through
+ * `getQuotaBurnTaskCatalog`, dispatch through the live schedule — and that is
+ * where a drift would reappear. So this suite runs BOTH real implementations
+ * over one mocked world and asserts they agree: the page's `reason` is exactly
+ * the error `triggerOnDemandTask` refuses with, and a step the page clears is a
+ * request the schedule actually queues.
+ *
+ * It exists as its own file because no single module owns the contract: the
+ * ladder is in `lib/`, one consumer is `taskSchedule.js` and the other is
+ * `quotaBurnInvoke.js`, and only the store boundary underneath all three is
+ * doubled.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const world = {
+ tasks: {},
+ apps: [],
+ features: {},
+ improvementEnabled: true,
+};
+
+vi.mock('./taskScheduleStore.js', () => ({
+ loadSchedule: vi.fn(async () => world.schedule),
+ updateSchedule: vi.fn(async (mutate) => (await mutate(world.schedule)).result),
+}));
+
+vi.mock('./apps.js', () => ({
+ getActiveApps: vi.fn(async () => world.apps),
+ getAppTaskTypeOverrides: vi.fn(async (id) => world.apps.find((app) => app.id === id)?.taskTypeOverrides || {}),
+ isTaskTypeEnabledForApp: vi.fn(async () => true),
+ getAppTaskTypeInterval: vi.fn(async () => null),
+ getAppTaskTypeIntervalMs: vi.fn(async () => null),
+ clearAllPrWatcherState: vi.fn(async () => ({ changed: false })),
+ clearAllIssueWatcherState: vi.fn(async () => ({ changed: false })),
+}));
+
+vi.mock('./instanceFeatures.js', () => ({
+ isInstanceFeatureEnabled: vi.fn(async (feature) => world.features[feature] !== false),
+}));
+
+vi.mock('./cosState.js', async () => {
+ const actual = await vi.importActual('./cosState.js');
+ return { ...actual, loadState: vi.fn(async () => ({ config: { improvementEnabled: world.improvementEnabled } })) };
+});
+
+vi.mock('./autonomousJobs.js', () => ({ getAllJobs: vi.fn(async () => []) }));
+vi.mock('./cosEvents.js', () => ({ cosEvents: { emit: vi.fn() }, emitLog: vi.fn() }));
+vi.mock('./userActions.js', () => ({ recordUserAction: vi.fn() }));
+vi.mock('./taskLearning.js', () => ({
+ getAdaptiveCooldownMultiplier: vi.fn(async () => ({ multiplier: 1, reason: 'insufficient-data', skip: false })),
+}));
+
+const { ON_DEMAND_ORIGINS, triggerOnDemandTask } = await import('./taskSchedule.js');
+const { getQuotaBurnTaskCatalog } = await import('./quotaBurnInvoke.js');
+const { resolveQuotaBurnStepAvailability } = await import('../lib/quotaBurnTaskRef.js');
+
+const burn = { family: 'grok', stepId: 'step-1', limitingResetAt: 1700000000000, overrides: { providerId: 'grok-tui', model: null, effort: null } };
+const burnStep = (taskType, appId = null) => ({
+ id: 'step-1', enabled: true, unavailable: null,
+ taskRef: { kind: 'builtin', taskType, appId },
+});
+
+/**
+ * Run one task type past both surfaces and return their verdicts, having
+ * already asserted that they say the same thing. `null` on both sides means
+ * "runnable", and the schedule proves it by queueing a request.
+ */
+async function agreedVerdict(taskType, appId = null, { origin = ON_DEMAND_ORIGINS.QUOTA_BURN } = {}) {
+ const page = resolveQuotaBurnStepAvailability(burnStep(taskType, appId), await getQuotaBurnTaskCatalog());
+ const dispatch = await triggerOnDemandTask(taskType, appId, { emit: false, origin, burn });
+ expect(dispatch.error ?? null).toBe(page?.reason ?? null);
+ expect(Boolean(dispatch.id)).toBe(!page);
+ return page;
+}
+
+beforeEach(() => {
+ world.tasks = {
+ security: { type: 'on-demand', enabled: true },
+ 'pr-reviewer': { type: 'on-demand', enabled: true },
+ 'model-comparison-refresh': { type: 'on-demand', enabled: true },
+ 'jira-sprint-manager': { type: 'on-demand', enabled: true, feature: 'jira' },
+ };
+ world.apps = [{ id: 'app-1', taskTypeOverrides: { 'pr-reviewer': { enabled: true } } }];
+ world.features = {};
+ world.improvementEnabled = true;
+ world.schedule = { tasks: world.tasks, executions: {}, onDemandRequests: [] };
+ vi.clearAllMocks();
+});
+
+describe('on-demand eligibility, page vs schedule', () => {
+ it('agrees on every rung the two surfaces already shared', async () => {
+ expect(await agreedVerdict('security')).toBeNull();
+ expect((await agreedVerdict('not-a-task'))?.code).toBe('unknown-task');
+ world.tasks.security.enabled = false;
+ expect((await agreedVerdict('security'))?.code).toBe('disabled');
+ world.features.jira = false;
+ expect((await agreedVerdict('jira-sprint-manager'))?.reason).toContain("requires the 'jira' feature");
+ expect((await agreedVerdict('pr-reviewer'))?.code).toBe('missing-app');
+ expect((await agreedVerdict('model-comparison-refresh', 'app-1'))?.code).toBe('wrong-scope');
+ });
+
+ // Disagreement #1 before this ladder: the catalog refused an app the type was
+ // switched off for, the schedule queued the request anyway. Decided in favour
+ // of the catalog — an unattended burn picks its own step and must respect the
+ // per-app switch the user set.
+ it('agrees that a burn may not run a type an app has switched off', async () => {
+ const verdict = await agreedVerdict('pr-reviewer', 'app-2');
+ expect(verdict).toMatchObject({ code: 'wrong-scope', reason: expect.stringContaining("not enabled for app 'app-2'") });
+ expect(await agreedVerdict('pr-reviewer', 'app-1')).toBeNull();
+ });
+
+ // A human pressing Run is the deliberate exception: the drain's
+ // applyOnDemandRunResets exists precisely so an explicit Run overrides the
+ // app's cadence switch, so that origin is not handed the rung's input.
+ it('still lets a human Run Now override an app-level switch', async () => {
+ const request = await triggerOnDemandTask('pr-reviewer', 'app-2', { emit: false, origin: ON_DEMAND_ORIGINS.USER });
+ expect(request.error).toBeUndefined();
+ expect(request.appId).toBe('app-2');
+ });
+
+ // Disagreement #2 before this ladder: the schedule refused while master
+ // Improve was off, the page rendered the step as ready to run. Decided in
+ // favour of the schedule, with its own reason code — "disabled" would have
+ // sent the user to a task toggle that is already on.
+ it('agrees that nothing runs while master Improve is off', async () => {
+ world.improvementEnabled = false;
+ const verdict = await agreedVerdict('security');
+ expect(verdict).toMatchObject({ code: 'improvement-disabled', reason: expect.stringContaining('CoS → Config') });
+ });
+
+ // The reference's own problem outranks the master switch: a user who turns
+ // Improve back on should not then discover a second, different reason.
+ it('names the task-level problem first when Improve is also off', async () => {
+ world.improvementEnabled = false;
+ world.tasks.security.enabled = false;
+ expect((await agreedVerdict('security'))?.code).toBe('disabled');
+ });
+});
diff --git a/server/services/quotaBurnInvoke.js b/server/services/quotaBurnInvoke.js
index 51f1969f1f..be883558c8 100644
--- a/server/services/quotaBurnInvoke.js
+++ b/server/services/quotaBurnInvoke.js
@@ -52,6 +52,7 @@
import {
QUOTA_BURN_TASK_REF_KIND,
QUOTA_BURN_UNAVAILABLE,
+ enabledAppIdsByTaskType,
resolveQuotaBurnStepAvailability,
} from '../lib/quotaBurnTaskRef.js';
import { generatedJobTaskFields } from '../lib/autonomousJobTask.js';
@@ -69,12 +70,15 @@ const entryOf = (map, key) => (map && Object.hasOwn(map, key) ? map[key] : null)
/**
* The live task catalog `resolveQuotaBurnStepAvailability` resolves a reference
- * against: `{ builtin: { [taskType]: { enabled, eligible, appIds } },
- * custom: { [jobId]: { enabled, eligible, appId } } }`.
+ * against: `{ builtin: { [taskType]: { enabled, featureEnabled, feature,
+ * eligible, appIds } }, custom: { [jobId]: { enabled, eligible, appId } },
+ * improvementEnabled }`.
*
- * `enabled` folds the instance-FEATURE gate in with the user's switch, because a
- * feature-off task is equally un-runnable and the reason codes carry no separate
- * verdict for it; the invocation path re-checks both and reports the precise one.
+ * The built-in entry is exactly the `entry` shape `evaluateOnDemandEligibility`
+ * reads, so the page's verdict is produced by the same ladder that decides the
+ * dispatch — every rung is filled here and judged there, never re-derived. That
+ * is why the instance-FEATURE gate is a field of its own rather than folded into
+ * `enabled`: the ladder can then say which of the two switches is off.
* `eligible` is the picker restriction: a type another automation owns
* (`userInvokable: false`) and a custom job that is not an agent job — a shell
* command or a built-in script handler — are not things a burn may invoke.
@@ -83,6 +87,10 @@ const entryOf = (map, key) => (map && Object.hasOwn(map, key) ? map[key] : null)
* type switched on, so a reference to an app that was removed (or had the type
* turned off) resolves as wrong-scope instead of silently dispatching nothing.
*
+ * `improvementEnabled` is the master CoS Improve switch, `null` when the state
+ * could not be read — which fails CLOSED, because "we could not check" is not
+ * "it is on".
+ *
* Each entry also carries the record it was derived from — the task's schedule
* config, the custom job — and the catalog carries the `queued` set of on-demand
* requests already waiting, all read off the SAME schedule/app/job snapshot.
@@ -92,19 +100,21 @@ const entryOf = (map, key) => (map && Object.hasOwn(map, key) ? map[key] : null)
* key it does not know.
*/
export async function getQuotaBurnTaskCatalog() {
- const [{ loadSchedule }, { getTaskTypeInvocation }, { getActiveApps }, { createFeatureGate }, { getAllJobs }] =
+ const [{ loadSchedule }, { getTaskTypeInvocation }, { getActiveApps }, { createFeatureGate }, { getAllJobs }, { isImprovementEnabled, loadState }] =
await Promise.all([
import('./taskScheduleStore.js'),
import('./taskScheduleRegistry.js'),
import('./apps.js'),
import('./taskSchedule.js'),
import('./autonomousJobs.js'),
+ import('./cosState.js'),
]);
- const [schedule, apps, jobs] = await Promise.all([
+ const [schedule, apps, jobs, state] = await Promise.all([
loadSchedule(),
getActiveApps().catch(() => []),
getAllJobs().catch(() => []),
+ loadState().catch(() => null),
]);
// The overrides come off the app records `getActiveApps` already returned.
@@ -112,23 +122,18 @@ export async function getQuotaBurnTaskCatalog() {
// produce the same answer for this filter — the legacy migration it also runs
// only ever synthesizes `{ enabled: false }` entries, which are exactly what
// gets discarded here. Other callers still perform that migration.
- const appIdsByTaskType = new Map();
- for (const app of apps) {
- for (const [taskType, override] of Object.entries(app.taskTypeOverrides || {})) {
- if (override?.enabled !== true) continue;
- if (!appIdsByTaskType.has(taskType)) appIdsByTaskType.set(taskType, []);
- appIdsByTaskType.get(taskType).push(app.id);
- }
- }
+ const appIdsByTaskType = enabledAppIdsByTaskType(apps);
// The schedule's own memoized gate, not a second copy: the burn catalog's
- // `enabled` verdict has to agree with the one `triggerOnDemandTask` applies,
+ // feature verdict has to agree with the one `triggerOnDemandTask` applies,
// and two implementations of one rule drift silently.
const featureEnabled = createFeatureGate();
const builtin = {};
await Promise.all(Object.entries(schedule?.tasks || {}).map(async ([taskType, config]) => {
builtin[taskType] = {
- enabled: config?.enabled === true && await featureEnabled(config),
+ enabled: config?.enabled === true,
+ featureEnabled: await featureEnabled(config),
+ feature: config?.feature || null,
eligible: getTaskTypeInvocation(taskType).userInvokable !== false,
appIds: appIdsByTaskType.get(taskType) || [],
config,
@@ -142,7 +147,12 @@ export async function getQuotaBurnTaskCatalog() {
job,
}]));
- return { builtin, custom, queued: queuedOnDemandKeys(schedule) };
+ return {
+ builtin,
+ custom,
+ improvementEnabled: state ? isImprovementEnabled(state) : null,
+ queued: queuedOnDemandKeys(schedule),
+ };
}
/** `taskType` + app scope of every on-demand request already waiting to drain. */
@@ -309,25 +319,6 @@ async function resolveStepProvider(effective, family) {
return { provider };
}
-/**
- * Why the master Improve switch forbids this dispatch, or null.
- *
- * The built-in lane inherits this gate from `triggerOnDemandTask`; the custom
- * and programmatic lanes never reach it, so they ask here. Every OTHER way those
- * two run — the scheduled custom-job fire, the programmatic on-demand drain —
- * is gated on it, and a burn that ignored it would be the one path that spends a
- * subscription while the user has CoS improvement switched off.
- */
-async function improvementRefusal() {
- const { isImprovementEnabled, loadState } = await import('./cosState.js');
- const state = await loadState().catch(() => null);
- // Unreadable state fails CLOSED: "we could not check" is not "it is on".
- if (!state) return 'CoS state could not be read';
- return isImprovementEnabled(state)
- ? null
- : 'Improvement is disabled — enable it in CoS → Config to run scheduled tasks';
-}
-
/**
* Why an unattended burn may not run this custom job, or null.
*
@@ -390,6 +381,11 @@ async function queuedOnDemandReason(queued, taskType, appId) {
*
* A decline is reported, never thrown: work that failed to start must not
* charge the window's cap.
+ *
+ * The master Improve switch is refused HERE, in the shared resolution, for all
+ * three lanes: the catalog carries the switch, so the page reports it on the
+ * same step the dispatch would refuse — and a burn cannot be the one path that
+ * spends a subscription while the user has CoS improvement switched off.
*/
export async function invokeQuotaBurnStep({ step, family, candidate, context, force = false, catalog = null } = {}) {
const resolved = await resolveQuotaBurnStep(step, catalog);
@@ -407,9 +403,6 @@ export async function invokeQuotaBurnStep({ step, family, candidate, context, fo
* drained (see `scheduledHandlers/index.js`).
*/
async function runProgrammaticStep({ resolved, family, context, force }) {
- const improve = await improvementRefusal();
- if (improve) return declined(improve);
-
const { runScheduledHandler } = await import('./scheduledHandlers/index.js');
return runScheduledHandler({
taskType: resolved.ref.taskType,
@@ -423,9 +416,11 @@ async function runProgrammaticStep({ resolved, family, context, force }) {
/**
* A built-in agent task goes through the schedule's own on-demand lane, so the
- * master Improve gate, the enabled + instance-feature gates, target scope and
- * invocation eligibility are all enforced by `triggerOnDemandTask` itself rather
- * than restated here — one ladder, not two.
+ * master Improve gate, the enabled + instance-feature gates, target scope, the
+ * per-app switch and invocation eligibility are all enforced by
+ * `triggerOnDemandTask` itself rather than restated here — and it reaches them
+ * through `evaluateOnDemandEligibility`, the same ladder `resolveQuotaBurnStep`
+ * already ran against the catalog. One ladder, two consumers.
*
* `force` is NOT passed through: it means "past the quota gates", and the
* schedule's gates are not quota gates.
@@ -490,8 +485,6 @@ async function runBuiltinTaskStep({ resolved, step, family, candidate }) {
async function runCustomJobStep({ resolved, step, family, candidate }) {
const approval = unattendedApprovalRefusal(resolved.job);
if (approval) return declined(approval);
- const improve = await improvementRefusal();
- if (improve) return declined(improve);
// `addTask`'s duplicate detection catches an identical QUEUED twin below, but
// not one already mid-spawn — and a forced run reaches here with no probe.
const active = await activeCustomJobReason(resolved.job);
diff --git a/server/services/quotaBurnInvoke.test.js b/server/services/quotaBurnInvoke.test.js
index 89d4945dbb..9fef1081e7 100644
--- a/server/services/quotaBurnInvoke.test.js
+++ b/server/services/quotaBurnInvoke.test.js
@@ -152,10 +152,14 @@ beforeEach(() => {
});
describe('getQuotaBurnTaskCatalog', () => {
- it('reports a feature-gated task as unavailable while its feature is off', async () => {
- expect((await getQuotaBurnTaskCatalog()).builtin['jira-sprint-manager'].enabled).toBe(true);
+ it('carries the instance-feature verdict beside the user switch, not folded into it', async () => {
+ // Two switches, two fields: the shared ladder needs them apart to say WHICH
+ // one is off, and a task whose feature is disabled is still `enabled: true`.
+ expect((await getQuotaBurnTaskCatalog()).builtin['jira-sprint-manager'])
+ .toMatchObject({ enabled: true, featureEnabled: true, feature: 'jira' });
state.features.jira = false;
- expect((await getQuotaBurnTaskCatalog()).builtin['jira-sprint-manager'].enabled).toBe(false);
+ expect((await getQuotaBurnTaskCatalog()).builtin['jira-sprint-manager'])
+ .toMatchObject({ enabled: true, featureEnabled: false });
});
it('lists only the apps that have a built-in type switched on', async () => {
@@ -215,31 +219,34 @@ describe('refusal paths', () => {
dispatchedNothing();
});
- it('refuses a task whose instance feature is off', async () => {
+ // The instance-feature gate is its OWN rung now rather than being folded into
+ // `enabled`: telling a user to re-enable a task whose toggle is already on
+ // sends them to the wrong switch, so the ladder names the feature instead.
+ it('refuses a task whose instance feature is off, naming the feature', async () => {
state.features.jira = false;
const result = await refuse({ taskRef: { kind: 'builtin', taskType: 'jira-sprint-manager' } });
expect(result.dispatched).toBe(false);
- expect(result.reason).toContain('is disabled');
+ expect(result.reason).toContain("requires the 'jira' feature");
dispatchedNothing();
});
it('refuses a built-in reference this install does not ship', async () => {
const result = await refuse({ taskRef: { kind: 'builtin', taskType: 'not-a-task' } });
- expect(result.reason).toContain('is not available on this install');
+ expect(result.reason).toContain("Unknown task type 'not-a-task'");
dispatchedNothing();
});
it('refuses a managed-app type with no app named, and an install-wide type with one', async () => {
expect((await refuse({ taskRef: { kind: 'builtin', taskType: 'pr-reviewer' } })).reason)
- .toContain('must name a managed app');
+ .toContain('requires a managed app target');
expect((await refuse({ taskRef: { kind: 'builtin', taskType: 'model-comparison-refresh', appId: 'app-1' } })).reason)
- .toContain('runs install-wide');
+ .toContain('requires an install-wide target');
dispatchedNothing();
});
it('refuses an app the type is not configured for', async () => {
const result = await refuse({ taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-9' } });
- expect(result.reason).toContain('not configured for app "app-9"');
+ expect(result.reason).toContain("is not enabled for app 'app-9'");
dispatchedNothing();
});
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 9cfc815a2b..1f9a639bf9 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -44,7 +44,6 @@ import {
getTaskTypeDescription,
getTaskTypeInvocation,
getTaskTypePromptInfo,
- requiresManagedAppTarget,
requiresInstallWideTarget,
isProgrammaticScheduledTaskType,
enforceBranchReconcileBatch,
@@ -55,6 +54,7 @@ import { isInstanceFeatureEnabled } from './instanceFeatures.js';
import { recordUserAction } from './userActions.js';
import { getTaskDataInputCatalog } from '../lib/taskDataInputCatalog.js';
import { normalizeQuotaBurnProvenance } from '../lib/quotaBurnOrigin.js';
+import { enabledAppIdsByTaskType, evaluateOnDemandEligibility } from '../lib/quotaBurnTaskRef.js';
import {
clearFailureLedgerFields,
clearTaskTypeFailurePark,
@@ -1121,37 +1121,40 @@ export async function triggerOnDemandTask(taskType, appId = null, {
// the schedule interval and the app's own per-app override.
const providerOverride = (provider || model || effort) ? { provider, model, effort } : null;
const request = await updateSchedule(async (schedule) => {
- // Cheap per-task-type check first; the master-flag check pays a state.json read.
const tasks = schedule.tasks || {};
- if (!Object.prototype.hasOwnProperty.call(tasks, taskType)) {
- return { result: { error: `Unknown task type '${taskType}'` }, changed: false };
- }
- if (!tasks[taskType].enabled) {
- return { result: { error: `Task type '${taskType}' is disabled` }, changed: false };
- }
- if (!(await createFeatureGate()(tasks[taskType]))) {
- return { result: { error: `Task type '${taskType}' requires the '${tasks[taskType].feature}' feature` }, changed: false };
- }
- const invocation = getTaskTypeInvocation(taskType);
- // A quota burn faces this gate alongside a human Run: a type owned by
- // another automation is not something an unattended burn may commandeer
- // either. Only the drain's own REFILL is exempt — it is that automation
- // re-issuing itself.
- if (origin !== ON_DEMAND_ORIGINS.REFILL && !invocation.userInvokable) {
- return { result: { error: `Task type '${taskType}' is managed by another automation and cannot be invoked on demand` }, changed: false };
- }
- if (requiresManagedAppTarget(taskType) && !appId) {
- return { result: { error: `Task type '${taskType}' requires a managed app target` }, changed: false };
- }
- if (appId && requiresInstallWideTarget(taskType)) {
- return { result: { error: `Task type '${taskType}' requires an install-wide target (no app)` }, changed: false };
- }
-
- // Reject if the master Improve toggle is off — request would be silently dropped downstream
- const state = await loadState();
- if (!isImprovementEnabled(state)) {
- return { result: { error: 'Improvement is disabled — enable it in CoS → Config to run on-demand tasks' }, changed: false };
- }
+ const config = Object.prototype.hasOwnProperty.call(tasks, taskType) ? tasks[taskType] : null;
+ const entry = config ? {
+ enabled: config.enabled === true,
+ featureEnabled: await createFeatureGate()(config),
+ feature: config.feature || null,
+ // A quota burn faces this gate alongside a human Run: a type owned by
+ // another automation is not something an unattended burn may commandeer
+ // either. Only the drain's own REFILL is exempt — it is that automation
+ // re-issuing itself.
+ eligible: origin === ON_DEMAND_ORIGINS.REFILL || getTaskTypeInvocation(taskType).userInvokable !== false,
+ // Per-app enablement is a rung for an UNATTENDED origin only. A human
+ // pressing Run is deliberately overriding the app's cadence switch — the
+ // drain's applyOnDemandRunResets exists for exactly that — while a burn
+ // picks its own step and must respect the switch the user set. Omitted,
+ // the ladder skips the rung.
+ appIds: origin === ON_DEMAND_ORIGINS.QUOTA_BURN
+ ? enabledAppIdsByTaskType(await getActiveApps().catch(() => [])).get(taskType) || []
+ : undefined,
+ } : null;
+
+ // The ladder itself lives in lib/quotaBurnTaskRef.js so the Quota Burn page
+ // renders exactly the verdict this dispatch would produce (#6405).
+ const gate = evaluateOnDemandEligibility({ taskType, appId, entry });
+ if (gate) return { result: { error: gate.reason }, changed: false };
+
+ // The master Improve switch is the one ladder input that pays a state.json
+ // read, so it is resolved only once the cheap rungs pass and then fed back
+ // through the SAME ladder — the rung is never restated here. Rejecting on it
+ // matters: the request would be silently dropped downstream.
+ const improvement = evaluateOnDemandEligibility({
+ taskType, appId, entry, improvementEnabled: isImprovementEnabled(await loadState()),
+ });
+ if (improvement) return { result: { error: improvement.reason }, changed: false };
if (!schedule.onDemandRequests) {
schedule.onDemandRequests = [];
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index d692e751e1..0b35ef266f 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -2303,7 +2303,9 @@ describe('taskSchedule', () => {
// `fs` is doubled for this suite, so read through the real one.
const { readFileSync } = await vi.importActual('node:fs')
const src = readFileSync(new URL('./taskSchedule.js', import.meta.url), 'utf8')
- expect(src).toMatch(/if \(origin !== ON_DEMAND_ORIGINS\.REFILL && !invocation\.userInvokable\)/)
+ // The rung itself lives in `evaluateOnDemandEligibility`; what this file
+ // still owns is which origins are exempt, so that is what is pinned.
+ expect(src).toMatch(/eligible: origin === ON_DEMAND_ORIGINS\.REFILL \|\| getTaskTypeInvocation\(taskType\)\.userInvokable !== false/)
// Probe: the previous, narrower gate must be gone, or the assertion above
// could pass on a file that still only checks USER somewhere else.
expect(src).not.toMatch(/origin === ON_DEMAND_ORIGINS\.USER && !invocation\.userInvokable/)