Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: let a maintenance run dispatch on a provider with no subscription family (#7416)
Adam Eivyb6b132bff607
diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.mdindex f3b41739f0..2ca6bd4506 100644--- a/docs/QUOTA-BURN.md+++ b/docs/QUOTA-BURN.md@@ -636,8 +636,14 @@ in `server/lib/maintenanceSequence.js` and can be run two ways:NOT a burn: it needs no Quota Burn master switch, faces no reset-window /reserve / dispatch-cap gates, writes nothing into any family plan, and hasnothing to re-arm — every "Run now" is a fresh run with its own completion- ledger. Pick the app, a subscription CLI/TUI provider, a model and an optional- effort; every step is pinned to them. Each audit is dispatched when the+ ledger. Pick the app, any enabled CLI/TUI provider, a model and an optional+ effort; every step is pinned to them. A provider that belongs to a+ subscription family carries that family along, so a refusal is credited to the+ window it actually spent; one that belongs to none — an OpenCode TUI, an+ Ollama- or LM-Studio-backed wrapper — runs **unfamilied** and credits nothing,+ because it spends no window. That relaxation is the manual run's alone: the+ automatic sweep below still resolves strictly by family and will not spend a+ provider outside its plan's named one. Each audit is dispatched when theprevious step finishes and each drain repeats until the app's issue backlogis empty, so the run walks to the end on its own. A step that cannot go out(a task disabled since, a blocked task, a transient claim probe) HOLDS the rundiff --git a/server/lib/quotaBurnOrigin.js b/server/lib/quotaBurnOrigin.jsindex 04ec72c767..58d2a3aa7d 100644--- a/server/lib/quotaBurnOrigin.js+++ b/server/lib/quotaBurnOrigin.js@@ -77,9 +77,11 @@ const asEpochMs = (value) => {};export const QUOTA_BURN_PROVENANCE_FIELDS = Object.freeze([- // Which provider family's window this run is spending. The one field a burn- // cannot be attributed without — `isCooldownExemptTask` and the denial ledger- // both key on it.+ // Which provider family's window this run is spending, and the key the denial+ // ledger and the plan walk attribute a finished run by. ABSENT — never a+ // placeholder — on a manual maintenance run pinned to a provider outside every+ // subscription family, which spends no window at all; `maintenanceRunId` below+ // is that run's attribution instead (see `normalizeQuotaBurnProvenance`).{ field: 'family', taskKey: 'quotaBurnFamily', agentKey: 'taskQuotaBurnFamily', read: asId },// The reset of the SHORT rolling window that will refuse first, so a refused// run blocks the family until that window rolls rather than re-dispatching@@ -96,6 +98,8 @@ export const QUOTA_BURN_PROVENANCE_FIELDS = Object.freeze([// run's agents alone — the run walks its own ladder, outside the family's// plan, its completion ledger and its window gates — while the family// attribution above still credits a refusal to the window it actually spent.+ // It is also the ONLY attribution a family-less manual run has, which is why+ // `hasQuotaBurnProvenance` accepts either key.{ field: 'maintenanceRunId', taskKey: 'quotaBurnMaintenanceRunId', agentKey: 'taskQuotaBurnMaintenanceRunId', read: asId },].map(Object.freeze));@@ -142,8 +146,20 @@ export function quotaBurnAgentMetadata(taskMetadata) {);}-/** Whether a task carries attributable burn provenance at all. */-export const hasQuotaBurnProvenance = (taskMetadata) => Boolean(quotaBurnProvenance(taskMetadata).family);+/**+ * Whether a task carries attributable burn provenance at all.+ *+ * EITHER attribution key is enough. A family says which subscription window the+ * run spends; a `maintenanceRunId` says which manual ladder asked. A manual run+ * pinned to a provider that belongs to no subscription family (an OpenCode TUI,+ * a local-model wrapper) carries only the second — it is fully attributable,+ * just not to a window — and it must still be cooldown-exempt, or the ladder's+ * own steps queue behind the app cooldown every other CoS task re-stamps.+ */+export const hasQuotaBurnProvenance = (taskMetadata) => {+ const block = quotaBurnProvenance(taskMetadata);+ return Boolean(block.family || block.maintenanceRunId);+};/*** Whether the family's burn PLAN owns this task: burn-provenanced, and not a@@ -174,11 +190,21 @@ const scalarParams = (raw) => {/*** Normalize the `burn` block of an on-demand request. Returns `null` unless it- * names BOTH the family whose window is being spent and the burn step that asked- * — without either, nothing downstream can attribute the run, and an- * unattributable burn is worse than no burn: `isCooldownExemptTask` would treat- * an ordinary task as burn-exempt, and the denial ledger would credit a refusal- * to the wrong family.+ * names the burn step that asked AND an attribution for the run — without both,+ * nothing downstream can attribute it, and an unattributable burn is worse than+ * no burn: `isCooldownExemptTask` would treat an ordinary task as burn-exempt,+ * and the denial ledger would credit a refusal to the wrong family.+ *+ * Attribution is the family whose window is being spent OR the manual+ * maintenance run that asked. An AUTOMATIC burn never carries a run id, so for+ * it the family stays strictly required, exactly as before — it exists to draw+ * down one named window and a family-less automatic burn would spend whatever+ * the daemon picked. A MANUAL run pinned to a provider outside every+ * subscription family (`services/maintenanceRun.js`) has no window to name and+ * says so by omitting `family` rather than borrowing a real one: `null` here is+ * "this run spends no subscription", not "we could not work it out". That is+ * what keeps `recordBurnAgentCompletion` and the quota-burn plan walk from+ * crediting its refusals and completions to a subscription it never touched.** `overrides` carries the three per-invocation settings the generated task can* absorb AFTER generation — the provider, model and reasoning effort the spawner@@ -205,14 +231,15 @@ export function normalizeQuotaBurnProvenance(raw) {if (!isPlainObject(raw)) return null;const family = trimTo(raw.family, MAX_FIELD);const stepId = trimTo(raw.stepId, MAX_FIELD);- if (!family || !stepId) return null;+ const maintenanceRunId = nullable(raw.maintenanceRunId);+ if (!stepId || (!family && !maintenanceRunId)) return null;const limitingResetAt = Number(raw.limitingResetAt);const overrides = isPlainObject(raw.overrides) ? raw.overrides : {};return {- family,+ ...(family ? { family } : {}),stepId,limitingResetAt: Number.isFinite(limitingResetAt) ? limitingResetAt : null,- ...(nullable(raw.maintenanceRunId) ? { maintenanceRunId: nullable(raw.maintenanceRunId) } : {}),+ ...(maintenanceRunId ? { maintenanceRunId } : {}),overrides: {providerId: nullable(overrides.providerId),model: nullable(overrides.model),diff --git a/server/lib/quotaBurnOrigin.test.js b/server/lib/quotaBurnOrigin.test.jsindex 02a81ab014..6f30eaaeb4 100644--- a/server/lib/quotaBurnOrigin.test.js+++ b/server/lib/quotaBurnOrigin.test.js@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import {QUOTA_BURN_PROVENANCE_FIELDS,+ burnPlanOwnsTask,hasQuotaBurnProvenance,normalizeQuotaBurnProvenance,onDemandRequestMetadata,@@ -43,14 +44,38 @@ describe('normalizeQuotaBurnProvenance', () => {});it('rejects a block that cannot attribute the burn', () => {- // Family AND step are both required: without the family nothing can credit a- // provider refusal, and without the step the run log cannot say what ran.+ // The step is always required — without it the run log cannot say what ran —+ // and so is an attribution: an AUTOMATIC burn has only its family, so a block+ // with no family and no run id credits a provider refusal to nobody.expect(normalizeQuotaBurnProvenance({ stepId: 'step-1' })).toBeNull();expect(normalizeQuotaBurnProvenance({ family: 'grok' })).toBeNull();+ expect(normalizeQuotaBurnProvenance({ maintenanceRunId: 'maint-1' })).toBeNull();expect(normalizeQuotaBurnProvenance(null)).toBeNull();expect(normalizeQuotaBurnProvenance('grok')).toBeNull();});+ // A manual maintenance run may be pinned to a provider outside every+ // subscription family (an OpenCode TUI, a local-model wrapper). It spends no+ // window, so it names no family — and the run id is what attributes it+ // instead. Before this, the whole block failed to normalize, `triggerOnDemandTask`+ // refused the request, and the run never paced because the maintenanceRunId+ // its evaluation looks for never reached the task.+ it('accepts a family-less MANUAL run, attributed by its run id alone', () => {+ const block = normalizeQuotaBurnProvenance({ stepId: 'step-1', maintenanceRunId: 'maint-1' });+ expect(block).toMatchObject({ stepId: 'step-1', maintenanceRunId: 'maint-1' });+ // Omitted, never a placeholder: a synthetic family would send this run's+ // refusals to the denial ledger of a subscription it never touched.+ expect(block).not.toHaveProperty('family');+ const metadata = onDemandRequestMetadata({ id: 'demand-9', origin: 'quota-burn', burn: block });+ expect(metadata.quotaBurnMaintenanceRunId).toBe('maint-1');+ expect(metadata).not.toHaveProperty('quotaBurnFamily');+ // Still cooldown-exempt: the ladder's own steps must not queue behind the+ // app cooldown every other CoS task on that app re-stamps.+ expect(hasQuotaBurnProvenance(metadata)).toBe(true);+ // And still not the burn PLAN's to walk or wait for.+ expect(burnPlanOwnsTask(metadata)).toBe(false);+ });+it('nulls an unreadable limiting reset rather than passing NaN downstream', () => {expect(normalizeQuotaBurnProvenance(provenance({ limitingResetAt: 'soon' })).limitingResetAt).toBeNull();expect(normalizeQuotaBurnProvenance(provenance()).limitingResetAt).toBeNull();diff --git a/server/routes/cosScheduleRoutes.js b/server/routes/cosScheduleRoutes.jsindex 89a7685333..9a663785e8 100644--- a/server/routes/cosScheduleRoutes.js+++ b/server/routes/cosScheduleRoutes.js@@ -32,9 +32,12 @@ const scheduleLabelsSchema = z.array(z.string().trim().min(1).max(40)).max(20)// so the storage rules live with the field's own helper, not in the route.const suggestedAfterSchema = z.array(z.string()).max(SUGGESTED_AFTER_MAX);-// A manual maintenance run names the app, the subscription provider and the-// model up front (AGENTS.md AI-policy: the click IS the consent). Blank effort-// inherits each scheduled task's saved effort.+// A manual maintenance run names the app, the provider and the model up front+// (AGENTS.md AI-policy: the click IS the consent). Any enabled CLI/TUI provider+// is accepted — one outside every subscription family runs unfamilied, see+// `maintenanceRun.js#manualBurnFamily` — so the family check belongs to the+// service's live provider gate, not to this schema. Blank effort inherits each+// scheduled task's saved effort.const maintenanceRunStartSchema = z.object({taskTypes: z.array(z.enum(Object.keys(AUDIT_DEFINITIONS))).min(1).max(Object.keys(AUDIT_DEFINITIONS).length).optional(),mode: z.enum(['file-issues', 'fix']).optional(),diff --git a/server/services/maintenanceRun.js b/server/services/maintenanceRun.jsindex 31d9d31e44..02f860ccf6 100644--- a/server/services/maintenanceRun.js+++ b/server/services/maintenanceRun.js@@ -19,11 +19,16 @@** What it shares with a burn is the INVOCATION: every step is dispatched through* `quotaBurnInvoke.invokeQuotaBurnStep`. Manual runs bypass schedule switches;- * master Improve, target scope and duplicate-request guards still apply, each handler is pinned to the family the user named, and the- * task carries the family provenance that makes it cooldown-exempt and lets an- * observed refusal be credited to the right window. The `maintenanceRunId`- * provenance field is what tells the quota-burn loop to leave these agents- * alone (`quotaBurnRunner.js#onBurnAgentCompleted`).+ * master Improve, target scope and duplicate-request guards still apply, each+ * handler is pinned to the provider the user named, and the task carries the+ * provenance that makes it cooldown-exempt. When that provider belongs to a+ * subscription family the family rides along too, so an observed refusal is+ * credited to the window it actually spent; when it belongs to none — an+ * OpenCode TUI, a local-model wrapper — the run dispatches UNFAMILIED and+ * credits nothing, because it spent no window (`manualBurnFamily`). The+ * `maintenanceRunId` provenance field is what tells the quota-burn loop to leave+ * these agents alone (`quotaBurnRunner.js#onBurnAgentCompleted`), and on an+ * unfamilied run it is also the only attribution the task carries.** Pacing is by completion: `agent:completed` for one of the run's tasks* re-evaluates the run, and a slow interval re-evaluates every running run as@@ -65,6 +70,36 @@ export const MAINTENANCE_RUN_STATUS = Object.freeze({ RUNNING: 'running', COMPLEconst activeRunError = (appId, runId) => new ServerError(`a maintenance run is already in progress for "${appId}" (${runId})`, { status: 409, code: 'MAINTENANCE_RUN_ACTIVE' });+/**+ * The burn identity one step of THIS run dispatches under.+ *+ * A manual run is not a burn: it walks a ladder the user asked for, on the+ * provider the user named. Most of the time that provider belongs to a+ * subscription family and the family rides along, so a refusal is still credited+ * to the window it actually spent. But the picker offers every enabled process+ * provider (`enabledProcessProviderFilter`), and an OpenCode TUI or a+ * local-model wrapper belongs to no family at all — there is no window, so there+ * is nothing to credit. That is a legitimate state, not a failed resolution, and+ * this is the ONLY place that says so: the automatic burn sweep hands+ * `providerForFamily` a plan's family record and can never construct this.+ */+const manualBurnFamily = (familyId) => (familyId ? { id: familyId } : { id: null, unfamilied: true });++/** One wording for the refusal, whichever of the three gates raised it. */+const unavailableProvider = (providerId) => `provider "${providerId}" is not an enabled CLI/TUI provider`;++/**+ * A run/step's own family, read by PRESENCE rather than truthiness.+ *+ * `null` means "this one is pinned outside every family"; only an ABSENT key+ * means "nothing recorded here, inherit". Collapsing the two with `||` would+ * make a step edited onto a family-less provider silently inherit the run's real+ * family — and then be refused for not belonging to it.+ */+const inherited = (record, key, fallback) => (record && Object.hasOwn(record, key) ? record[key] : fallback);+const stepBurnFamily = (step, run) => manualBurnFamily(inherited(step, 'familyId',+ step.drain ? inherited(run, 'claimFamilyId', run.familyId) : run.familyId));+const writeQueue = createFileWriteQueue();// One operation at a time PER RUN — evaluations, the completion ledger, stop// and resume all queue here. A completion and the interval can land together,@@ -129,10 +164,12 @@ async function assertNoRunningRun(appId) {/*** Start a run. Refused (with a thrown, coded error the route maps to a 4xx)- * when the app is unknown or archived, the provider is not an enabled- * subscription CLI/TUI provider in a known family — the SAME gate every dispatch- * re-applies (`resolveBurnProvider`), so a run can never start on a provider- * its steps would then refuse — or a full ladder targets an app with a running run.+ * when the app is unknown or archived, the provider is not an enabled CLI/TUI+ * provider — the SAME gate every dispatch re-applies (`resolveBurnProvider`), so+ * a run can never start on a provider its steps would then refuse — or a full+ * ladder targets an app with a running run. Belonging to a subscription family+ * is NOT part of that gate: the picker offers every enabled process provider,+ * and one outside every family runs unfamilied (see `manualBurnFamily`).* Explicit quality selections may run alongside other runs; they never claim backlog issues.** The first evaluation runs before this returns, so the caller learns whether@@ -145,15 +182,15 @@ export async function startMaintenanceRun({ appId, providerId, model = null, effconst [app, provider] = await Promise.all([getAppById(appId), getProviderById(providerId)]);if (!app || app.archived === true) throw new ServerError(`managed app "${appId}" is not available`, { status: 400, code: 'MAINTENANCE_RUN_APP_UNAVAILABLE' });const familyId = familyForProvider(provider);- const pinned = familyId ? await resolveBurnProvider({ job: { providerId }, family: { id: familyId } }) : null;- if (!pinned) throw new ServerError(`provider "${providerId}" is not an enabled subscription CLI/TUI provider`, { status: 400, code: 'MAINTENANCE_RUN_PROVIDER_UNAVAILABLE' });+ const pinned = await resolveBurnProvider({ job: { providerId }, family: manualBurnFamily(familyId) });+ if (!pinned) throw new ServerError(unavailableProvider(providerId), { status: 400, code: 'MAINTENANCE_RUN_PROVIDER_UNAVAILABLE' });// File-only runs never validate or retain a hidden claim selection.const effectiveClaimHandler = !taskTypes && (mode === 'fix' || claimBetweenAudits) ? claimHandler : null;let claimFamilyId = familyId;if (effectiveClaimHandler) {claimFamilyId = familyForProvider(await getProviderById(effectiveClaimHandler.providerId));- const claimProvider = claimFamilyId ? await resolveBurnProvider({ job: effectiveClaimHandler, family: { id: claimFamilyId } }) : null;- if (!claimProvider) throw new ServerError(`provider "${effectiveClaimHandler.providerId}" is not an enabled subscription CLI/TUI provider`, { status: 400, code: 'MAINTENANCE_RUN_PROVIDER_UNAVAILABLE' });+ const claimProvider = await resolveBurnProvider({ job: effectiveClaimHandler, family: manualBurnFamily(claimFamilyId) });+ if (!claimProvider) throw new ServerError(unavailableProvider(effectiveClaimHandler.providerId), { status: 400, code: 'MAINTENANCE_RUN_PROVIDER_UNAVAILABLE' });}if (!taskTypes) await assertNoRunningRun(appId);@@ -215,8 +252,12 @@ export function updateMaintenanceStep(id, stepId, { providerId, model, effort =import('./providers.js'), import('./scheduledHandlers/providerPick.js'),]);const familyId = familyForProvider(await getProviderById(providerId));- const provider = familyId ? await resolveBurnProvider({ job: { providerId }, family: { id: familyId } }) : null;- if (!provider) throw new ServerError(`provider "${providerId}" is not an enabled subscription CLI/TUI provider`, { status: 400, code: 'MAINTENANCE_RUN_PROVIDER_UNAVAILABLE' });+ const provider = await resolveBurnProvider({ job: { providerId }, family: manualBurnFamily(familyId) });+ if (!provider) throw new ServerError(unavailableProvider(providerId), { status: 400, code: 'MAINTENANCE_RUN_PROVIDER_UNAVAILABLE' });+ // `familyId` is written even when null (`familyForProvider` returns string+ // or null, never undefined) — the step is now pinned OUTSIDE every family,+ // and `stepBurnFamily` reads a present-but-null key as that decision rather+ // than as "nothing recorded here, inherit the run's family".return patchRun(id, { steps: run.steps.map(entry => entry.id === stepId? { ...entry, familyId, overrides: { ...entry.overrides, providerId, model, effort } }: entry) });@@ -288,7 +329,7 @@ async function evaluate(id, { ignoreTaskId }) {}if (!probe.job) return hold(probe.reason);}- const result = await invokeQuotaBurnStep({ step, family: { id: step.familyId || (step.drain ? (run.claimFamilyId || run.familyId) : run.familyId) }, catalog, maintenanceRunId: id });+ const result = await invokeQuotaBurnStep({ step, family: stepBurnFamily(step, run), catalog, maintenanceRunId: id });if (!result.dispatched) return hold(result.reason, { completed });const taskType = step.taskRef.taskType;await patchRun(id, {diff --git a/server/services/maintenanceRun.test.js b/server/services/maintenanceRun.test.jsindex 8c8357789f..f570f35fd0 100644--- a/server/services/maintenanceRun.test.js+++ b/server/services/maintenanceRun.test.js@@ -12,8 +12,23 @@ vi.mock('./cosState.js', () => ({ loadState: vi.fn(async () => ({ agents: {} }))vi.mock('./cosTaskStore.js', () => ({ getAllTasks: vi.fn(async () => ({ cos: { tasks: state.tasks }, user: { tasks: [] } })) }));vi.mock('./taskSchedule.js', () => ({ getOnDemandRequests: vi.fn(async () => state.requests) }));vi.mock('./apps.js', () => ({ getAppById: vi.fn(async (id) => (id === 'app-1' ? { id, name: 'Example App' } : null)) }));-vi.mock('./providers.js', () => ({ getProviderById: vi.fn(async (id) => (id === 'codex' ? { id, type: 'cli', command: 'codex', enabled: true } : null)) }));-vi.mock('./scheduledHandlers/providerPick.js', () => ({ resolveBurnProvider: vi.fn(async ({ job, family }) => (job.providerId === 'codex' && family.id === 'codex' ? { id: 'codex' } : null)) }));+// The registry a run's provider gate resolves against. `opencode-tui` belongs to+// no subscription family — the case #7416 is about — and `off-tui` is the+// registered-but-disabled control.+const PROVIDERS = [+ { id: 'codex', type: 'cli', command: 'codex', enabled: true },+ { id: 'claude', type: 'cli', command: 'claude', enabled: true },+ { id: 'opencode-tui', type: 'tui', command: 'opencode', enabled: true },+ { id: 'off-tui', type: 'tui', command: 'opencode', enabled: false },+];+vi.mock('./providers.js', () => ({+ getProviderById: vi.fn(async (id) => PROVIDERS.find((provider) => provider.id === id) || null),+ getAllProviders: vi.fn(async () => PROVIDERS),+}));+// The REAL resolver over that registry, not a hand-rolled stand-in: the whole+// point of these cases is which pins the shared gate accepts, and a double would+// only assert what the double was told.+vi.mock('./scheduledHandlers/providerPick.js', async (importActual) => await importActual());vi.mock('./quotaBurnInvoke.js', () => ({getQuotaBurnTaskCatalog: vi.fn(async () => ({ builtin: {}, custom: {} })),invokeQuotaBurnStep: vi.fn(async (call) => {@@ -67,10 +82,6 @@ describe('manual maintenance run', () => {it('dispatches an edited stage through its own provider family', async () => {const { run } = await start();- const { getProviderById } = await import('./providers.js');- const { resolveBurnProvider } = await import('./scheduledHandlers/providerPick.js');- getProviderById.mockResolvedValueOnce({ id: 'claude', command: 'claude', type: 'cli', enabled: true });- resolveBurnProvider.mockResolvedValueOnce({ id: 'claude' });await updateMaintenanceStep(run.id, run.steps[1].id, { providerId: 'claude', model: 'example-model', effort: 'low' });await __onMaintenanceAgentCompleted(agentFor(run, 0));expect(state.invoked.at(-1)).toMatchObject({ family: { id: 'claude' }, step: { overrides: { providerId: 'claude', effort: 'low' } } });@@ -198,12 +209,54 @@ describe('manual maintenance run', () => {expect(run).toMatchObject({ status: 'running', reason: 'schedule unreadable' });});- it('refuses an unknown app or a provider outside every subscription family before writing anything', async () => {+ it('refuses an unknown app, and an unregistered or disabled provider, before writing anything', async () => {await expect(startMaintenanceRun({ appId: 'nope', providerId: 'codex', model: 'gpt-5' })).rejects.toMatchObject({ status: 400, code: 'MAINTENANCE_RUN_APP_UNAVAILABLE' });- await expect(startMaintenanceRun({ appId: 'app-1', providerId: 'ollama', model: 'llama' })).rejects.toMatchObject({ status: 400, code: 'MAINTENANCE_RUN_PROVIDER_UNAVAILABLE' });+ for (const providerId of ['not-registered', 'off-tui']) {+ await expect(startMaintenanceRun({ appId: 'app-1', providerId, model: 'llama' })).rejects.toMatchObject({ status: 400, code: 'MAINTENANCE_RUN_PROVIDER_UNAVAILABLE' });+ }expect(await listMaintenanceRuns()).toEqual([]);expect(state.invoked).toEqual([]);});++ // #7416. The picker offers every enabled process provider, but the dispatch+ // path required a subscription family end to end, so "Run now" on an OpenCode+ // TUI or a local-model wrapper failed with MAINTENANCE_RUN_PROVIDER_UNAVAILABLE.+ describe('a provider outside every subscription family', () => {+ it('starts a run and dispatches it unfamilied, crediting no window', async () => {+ const { run, result } = await startMaintenanceRun({ appId: 'app-1', providerId: 'opencode-tui', model: 'local-model' });+ expect(result).toMatchObject({ dispatched: true, taskType: 'better-structural-drift' });+ expect(run).toMatchObject({ status: 'running', familyId: null, claimFamilyId: null });+ expect(state.invoked.at(-1)).toMatchObject({+ maintenanceRunId: run.id,+ family: { id: null, unfamilied: true },+ step: expect.objectContaining({ overrides: expect.objectContaining({ providerId: 'opencode-tui' }) }),+ });+ });++ it('accepts a per-step edit onto one, without the step inheriting the run\'s family', async () => {+ // The regression a truthiness fallback reintroduces: a step whose own+ // family is legitimately null would read as "nothing recorded, inherit",+ // pick up `codex`, and then be refused for not belonging to it.+ const { run } = await start();+ await updateMaintenanceStep(run.id, run.steps[1].id, { providerId: 'opencode-tui', model: 'local-model', effort: null });+ await __onMaintenanceAgentCompleted(agentFor(run, 0));+ expect(state.invoked.at(-1)).toMatchObject({+ family: { id: null, unfamilied: true },+ step: { overrides: { providerId: 'opencode-tui' } },+ });+ });++ it('accepts it as the claim handler while the audits stay on their own family', async () => {+ const { run } = await startMaintenanceRun({ appId: 'app-1', providerId: 'codex', model: 'gpt-5', claimHandler: { providerId: 'opencode-tui', model: 'local-model', effort: null } });+ expect(run).toMatchObject({ familyId: 'codex', claimFamilyId: null });+ expect(state.invoked.at(-1).family).toEqual({ id: 'codex' });+ await __onMaintenanceAgentCompleted(agentFor(run, 0));+ expect(state.invoked.at(-1)).toMatchObject({+ family: { id: null, unfamilied: true },+ step: { drain: true, overrides: expect.objectContaining({ providerId: 'opencode-tui' }) },+ });+ });+ });});// Regression: queued maintenance must identify its real agent immediately and@@ -254,12 +307,6 @@ it('files findings consecutively and finishes without claiming when claims are d// A different subscription family must survive storage and dispatch, including// repeated claim passes, without changing the audit pins.it('dispatches claims with their own provider family, model and effort', async () => {- const { getProviderById } = await import('./providers.js');- const { resolveBurnProvider } = await import('./scheduledHandlers/providerPick.js');- getProviderById.mockImplementationOnce(async id => ({ id, type: 'cli', command: id, enabled: true }));- getProviderById.mockImplementationOnce(async id => ({ id, type: 'cli', command: id, enabled: true }));- resolveBurnProvider.mockResolvedValueOnce({ id: 'codex' });- resolveBurnProvider.mockImplementationOnce(async ({ job, family }) => job.providerId === family.id ? { id: job.providerId } : null);const claimHandler = { providerId: 'claude', model: 'sonnet', effort: 'low' };const { run } = await startMaintenanceRun({ appId: 'app-1', providerId: 'codex', model: 'gpt-5', effort: 'high', claimHandler });expect((await getMaintenanceRun(run.id)).steps[1].overrides).toEqual({ ...claimHandler, params: {} });diff --git a/server/services/quotaBurnInvoke.js b/server/services/quotaBurnInvoke.jsindex eb4b67ba23..7a058afb8e 100644--- a/server/services/quotaBurnInvoke.js+++ b/server/services/quotaBurnInvoke.js@@ -64,6 +64,8 @@ import { ON_DEMAND_ORIGINS } from './taskScheduleConstants.js';const UNATTENDED_AUTONOMY_LEVEL = 'yolo';const declined = (reason) => ({ dispatched: false, reason });+/** What a log line calls the thing being spent — a family, or nothing at all. */+const burnLabel = (family) => family?.id || 'no subscription family';const noWork = (detail) => ({ count: 0, detail });// `Object.hasOwn`, not a truthiness check, so a reference naming an inherited// key like `constructor` cannot resolve to anything.@@ -304,9 +306,17 @@ export async function countQuotaBurnStepPending({ step, family, catalog = null }* Programmatic handlers do NOT come through here — each resolves its own* backend from the `family` it is handed (`prefer: 'cli'`, and the render* backend is not always a provider at all).+ *+ * An UNFAMILIED run is the one case with no family to check against, and it is+ * not an exception to the rule above so much as the absence of its premise: a+ * manual maintenance run pinned to a provider outside every subscription family+ * spends no window, so there is no wrong window for it to spend. Only+ * `maintenanceRun.js` can construct that identity, and `providerForFamily`+ * still requires the pin to name an ENABLED, process-capable provider — so the+ * resolved provider is always exactly the one the user picked.*/async function resolveStepProvider(effective, family) {- const { noProviderReason, matchesFamily, resolveBurnProvider } = await import('./scheduledHandlers/providerPick.js');+ const { noProviderReason, matchesFamily, isUnfamiliedBurn, resolveBurnProvider } = await import('./scheduledHandlers/providerPick.js');const provider = await resolveBurnProvider({ job: { providerId: effective.providerId }, family });if (!provider) {return {@@ -315,7 +325,7 @@ async function resolveStepProvider(effective, family) {: noProviderReason(family),};}- if (!matchesFamily(provider, family.id)) {+ if (!isUnfamiliedBurn(family) && !matchesFamily(provider, family.id)) {return { error: `pinned provider "${provider.id}" does not belong to the ${family.id} family` };}return { provider };@@ -447,7 +457,11 @@ async function runBuiltinTaskStep({ resolved, step, family, candidate, maintenanconst request = await triggerOnDemandTask(resolved.ref.taskType, resolved.ref.appId, {origin: ON_DEMAND_ORIGINS.QUOTA_BURN,burn: {- family: family.id,+ // Omitted, not null, when the run spends no subscription window at all —+ // `normalizeQuotaBurnProvenance` accepts `maintenanceRunId` as the+ // attribution instead, and a placeholder here would credit this run's+ // refusals to a family it never touched.+ ...(family.id ? { family: family.id } : {}),stepId: step.id,limitingResetAt: candidate?.limitingResetAt ?? null,// Set only by a MANUAL maintenance run (`maintenanceRun.js`): the mark@@ -475,7 +489,7 @@ async function runBuiltinTaskStep({ resolved, step, family, candidate, maintenan});if (request?.error) return declined(request.error);- console.log(`🔥 Quota-burn requested scheduled task ${resolved.ref.taskType} for ${family.id} (${request.id})`);+ console.log(`🔥 Quota-burn requested scheduled task ${resolved.ref.taskType} for ${burnLabel(family)} (${request.id})`);return {dispatched: true,// The ONLY lane whose acceptance is asynchronous: the request is recorded@@ -528,7 +542,7 @@ async function runCustomJobStep({ resolved, step, family, candidate, maintenance// other. Everything below OVERRIDES it — that is where the two legitimately// differ....generatedJobTaskFields(generated),- context: `Quota burn (${family.id}): ${resolved.job.name}`,+ context: `Quota burn (${burnLabel(family)}): ${resolved.job.name}`,approvalRequired: !generated.autoApprove,// The step's overrides win over the job's saved pins (see effectiveSettings),// and an unpinned step still lands on THIS family's provider.@@ -541,7 +555,8 @@ async function runCustomJobStep({ resolved, step, family, candidate, maintenance// `quotaBurnRequestId`: this lane queues the task synchronously, so no// request ever exists to name — that key records the ASYNC hop, and minting// a fake one would make a join over it silently wrong.- quotaBurnFamily: family.id,+ // Same "omit, never placeholder" rule as the built-in lane's burn block.+ ...(family.id ? { quotaBurnFamily: family.id } : {}),quotaBurnLimitingResetAt: candidate?.limitingResetAt ?? null,quotaBurnStepId: step.id,...(maintenanceRunId ? { quotaBurnMaintenanceRunId: maintenanceRunId } : {}),@@ -552,7 +567,7 @@ async function runCustomJobStep({ resolved, step, family, candidate, maintenance// retry, and an unattended burn has no such intent to express.if (persisted.duplicate) return declined(`an identical "${resolved.job.name}" task is already ${persisted.status}`);- console.log(`🔥 Quota-burn queued custom job ${resolved.job.id} as task ${persisted.id} for ${family.id}`);+ console.log(`🔥 Quota-burn queued custom job ${resolved.job.id} as task ${persisted.id} for ${burnLabel(family)}`);return {dispatched: true,summary: `Queued "${resolved.job.name}" via ${picked.provider.id}`,diff --git a/server/services/quotaBurnInvoke.test.js b/server/services/quotaBurnInvoke.test.jsindex e0906af9a2..45113dc16f 100644--- a/server/services/quotaBurnInvoke.test.js+++ b/server/services/quotaBurnInvoke.test.js@@ -285,6 +285,56 @@ describe('refusal paths', () => {dispatchedNothing();});+ // #7416. The Quality-page runner and the Schedule tab's maintenance-run form+ // offer every enabled process provider, but a manual run pinned to one outside+ // every subscription family used to die here with+ // MAINTENANCE_RUN_PROVIDER_UNAVAILABLE. Only `maintenanceRun.js` constructs+ // this identity; the automatic sweep hands over a plan's family record.+ describe('a manual run pinned outside every subscription family', () => {+ const unfamilied = { id: null, unfamilied: true };+ const uxStep = (providerId) => step({ taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' }, overrides: { providerId } });++ beforeEach(() => {+ state.providers.push(+ { id: 'opencode-tui', command: '/usr/local/bin/opencode', type: 'tui', enabled: true },+ { id: 'claude-ollama-tui', command: '/usr/local/bin/claude', type: 'tui', enabled: true, ollamaBacked: true },+ );+ });++ it.each(['opencode-tui', 'claude-ollama-tui'])('dispatches on the pinned %s and attributes the run, not a window', async (providerId) => {+ const result = await invokeQuotaBurnStep({ step: uxStep(providerId), family: unfamilied, catalog: null, maintenanceRunId: 'maint-1' });+ expect(result.dispatched).toBe(true);+ expect(state.triggered[0].options.burn.overrides.providerId).toBe(providerId);+ expect(state.triggered[0].options.burn.maintenanceRunId).toBe('maint-1');+ // No placeholder family: the denial ledger and the plan walk both key on+ // it, and a synthetic value would send this run's refusals to a real+ // subscription's bookkeeping.+ expect(state.triggered[0].options.burn).not.toHaveProperty('family');+ });++ it('still refuses a provider that is disabled, absent, or not a process provider', async () => {+ state.providers.push({ id: 'opencode-api', type: 'api', enabled: true }, { id: 'off-tui', command: 'opencode', type: 'tui', enabled: false });+ for (const providerId of ['opencode-api', 'off-tui', 'not-registered']) {+ expect(await invokeQuotaBurnStep({ step: uxStep(providerId), family: unfamilied, maintenanceRunId: 'maint-1' }))+ .toMatchObject({ dispatched: false, reason: expect.stringContaining('is not an enabled CLI/TUI provider') });+ }+ // With nothing pinned there is no family left to resolve against either.+ expect(await invokeQuotaBurnStep({ step: uxStep(null), family: unfamilied, maintenanceRunId: 'maint-1' }))+ .toMatchObject({ dispatched: false, reason: expect.stringContaining('must name the provider') });+ expect(state.triggered).toEqual([]);+ });++ // The guarantee the relaxation must not weaken: an AUTOMATIC burn carries a+ // real family and can only ever spend that family's window.+ it('leaves the automatic sweep refusing an out-of-family and a local-runtime pin', async () => {+ expect(await invokeQuotaBurnStep({ step: uxStep('opencode-tui'), family: grok, candidate }))+ .toMatchObject({ dispatched: false, reason: expect.stringContaining('does not belong to the grok family') });+ expect(await invokeQuotaBurnStep({ step: uxStep('claude-ollama-tui'), family: grok, candidate }))+ .toMatchObject({ dispatched: false, reason: expect.stringContaining('is not an enabled CLI/TUI provider') });+ expect(state.triggered).toEqual([]);+ });+ });+it('still refuses an ineligible or unapproved task under force', async () => {// `force` means "past the QUOTA gates" (window / reserve / cap / denial) and// nothing more — eligibility and approval are facts about whether the workdiff --git a/server/services/scheduledHandlers/providerPick.js b/server/services/scheduledHandlers/providerPick.jsindex c9b588e0b5..89c7a53c58 100644--- a/server/services/scheduledHandlers/providerPick.js+++ b/server/services/scheduledHandlers/providerPick.js@@ -12,6 +12,21 @@ import { isProcessProvider } from '../../lib/providerTypes.js';import { getAllProviders } from '../providers.js';import { commandBasename } from '../../lib/providerModels.js';+/**+ * Is this the "no subscription family" identity?+ *+ * A MANUAL maintenance run (`services/maintenanceRun.js`) may be pinned to a+ * provider that belongs to no family at all — an OpenCode TUI, an Ollama- or+ * LM-Studio-backed wrapper — because the run is a ladder of audits the user+ * asked for, not an attempt to drain a window before it expires. That run+ * constructs this identity explicitly; every other caller hands over a family+ * record from a burn plan, which always names a real family. Recognizing the+ * state HERE (rather than inferring it from a falsy `familyId`) is what keeps+ * the automatic burn sweep out of it: a sweep whose family id somehow came+ * through empty still resolves nothing, exactly as before.+ */+export const isUnfamiliedBurn = (family) => family?.unfamilied === true && !family.id;+/*** An agent-capable provider in the burning family. A job's explicit* `providerId` wins; otherwise match the family id against the enabled@@ -38,10 +53,21 @@ import { commandBasename } from '../../lib/providerModels.js';* burning through one accomplishes nothing. `resolveEnabledFamilies` drops* them from the quota cards for exactly this reason; a `claude-ollama-tui`* would otherwise be a perfectly good match for the `claude` family.+ *+ * `unfamilied` lifts the SECOND exclusion, and only together with an explicit+ * `providerId`. It says the caller is not burning a window at all — it is a+ * manual maintenance run dispatching the ladder onto the one provider the user+ * named — so "this model is local and free" stops being a disqualification and+ * becomes the whole point. The API-type exclusion stays: `isProcessProvider`+ * still has to hold, because the ladder spawns a CLI/TUI agent. A caller that+ * sets the flag without naming a provider resolves nothing, since there is no+ * family left to match against.*/-export function providerForFamily(providers, { familyId, providerId, prefer = 'tui' }) {+export function providerForFamily(providers, { familyId, providerId, prefer = 'tui', unfamilied = false }) {+ const localRuntimeAllowed = unfamilied === true && !familyId && Boolean(providerId);const available = (providers || []).filter((provider) =>- provider?.enabled && provider.ollamaBacked !== true && provider.lmstudioBacked !== true && provider.mtplxBacked !== true && provider.llamaBacked !== true && provider.vllmBacked !== true && provider.sglangBacked !== true+ provider?.enabled+ && (localRuntimeAllowed || (provider.ollamaBacked !== true && provider.lmstudioBacked !== true && provider.mtplxBacked !== true && provider.llamaBacked !== true && provider.vllmBacked !== true && provider.sglangBacked !== true))&& isProcessProvider(provider));if (providerId) return available.find((provider) => provider.id === providerId) || null;const inFamily = available.filter((provider) => matchesFamily(provider, familyId));@@ -74,8 +100,14 @@ export const matchesFamily = (provider, familyId) => {|| String(provider.id || '').toLowerCase().includes(needle);};-/** The reason a job reports when its family has nothing it is allowed to spend. */-export const noProviderReason = (family) => `no enabled CLI/TUI provider in the ${family?.id} family`;+/**+ * The reason a job reports when its family has nothing it is allowed to spend.+ * An unfamilied run has no family to name, and reaches here only when it was+ * given no provider to pin — so it says that instead.+ */+export const noProviderReason = (family) => (isUnfamiliedBurn(family)+ ? 'a run outside every subscription family must name the provider to use'+ : `no enabled CLI/TUI provider in the ${family?.id} family`);/** `providerForFamily` against the live provider list. */export async function resolveBurnProvider({ job, family, prefer }) {@@ -84,5 +116,6 @@ export async function resolveBurnProvider({ job, family, prefer }) {familyId: family?.id,providerId: job?.providerId || null,prefer,+ unfamilied: isUnfamiliedBurn(family),});}diff --git a/server/services/scheduledHandlers/providerPick.test.js b/server/services/scheduledHandlers/providerPick.test.jsindex 87e4a0d3f4..1d3e3ab91f 100644--- a/server/services/scheduledHandlers/providerPick.test.js+++ b/server/services/scheduledHandlers/providerPick.test.js@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { noProviderReason, providerForFamily } from './providerPick.js';+import { isUnfamiliedBurn, noProviderReason, providerForFamily } from './providerPick.js';const cliProviders = [{ id: 'grok-cli', type: 'cli', enabled: true },@@ -94,6 +94,52 @@ describe('providerForFamily', () => {});+// A MANUAL maintenance run is not burning a window — it walks the ladder the+// user asked for, on the provider the user picked, and that picker offers every+// enabled process provider. So a provider in no family at all (an OpenCode TUI,+// a local-model wrapper) has to resolve, while the automatic sweep's guarantee+// that a step only ever spends its own family's window stays exactly as it was.+describe('an explicit pin outside every subscription family', () => {+ const providers = [+ { id: 'opencode-tui', type: 'tui', enabled: true, command: 'opencode' },+ { id: 'claude-ollama-tui', type: 'tui', enabled: true, command: 'claude', ollamaBacked: true },+ { id: 'opencode-lmstudio-tui', type: 'tui', enabled: false, command: 'opencode', lmstudioBacked: true },+ { id: 'claude-code-tui', type: 'tui', enabled: true, command: 'claude' },+ { id: 'grok-api', type: 'api', enabled: true },+ ];+ const pick = (providerId) => providerForFamily(providers, { familyId: null, providerId, unfamilied: true });++ it('resolves a family-less provider, including a local-runtime wrapper', () => {+ expect(pick('opencode-tui')?.id).toBe('opencode-tui');+ // The whole point of the mode: a local model has no window, which is a+ // disqualification for a burn and irrelevant to a maintenance ladder.+ expect(pick('claude-ollama-tui')?.id).toBe('claude-ollama-tui');+ });++ it('still requires an ENABLED, process-capable provider', () => {+ expect(pick('opencode-lmstudio-tui')).toBeNull();+ expect(pick('grok-api')).toBeNull();+ expect(pick('not-registered')).toBeNull();+ });++ it('resolves nothing without an explicit pin — there is no family left to match', () => {+ expect(providerForFamily(providers, { familyId: null, unfamilied: true })).toBeNull();+ expect(noProviderReason({ id: null, unfamilied: true })).toContain('must name the provider');+ });++ // The regression the mode must never become: the automatic sweep hands over a+ // real family record and never sets the flag, so a local wrapper stays refused+ // there however it is pinned.+ it('does not relax anything for a familied caller', () => {+ expect(providerForFamily(providers, { familyId: 'claude', providerId: 'claude-ollama-tui' })).toBeNull();+ expect(providerForFamily(providers, { familyId: 'claude', providerId: 'claude-ollama-tui', unfamilied: true })).toBeNull();+ expect(isUnfamiliedBurn({ id: 'claude' })).toBe(false);+ expect(isUnfamiliedBurn({ id: 'claude', unfamilied: true })).toBe(false);+ expect(isUnfamiliedBurn(undefined)).toBe(false);+ expect(isUnfamiliedBurn({ id: null, unfamilied: true })).toBe(true);+ });+});+describe('the cli preference for programmatic jobs', () => {it('flips the default without forking the helper', () => {// A programmatic job sends one headless prompt through the stage runner: