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
gate the burn's custom and programmatic lanes on master Improve, and dedupe under force
[._.]/ Adam Eivycae2702fa478
diff --git a/server/lib/quotaBurnOrigin.js b/server/lib/quotaBurnOrigin.jsindex 3ed4005cab..8111a3c3d4 100644--- a/server/lib/quotaBurnOrigin.js+++ b/server/lib/quotaBurnOrigin.js@@ -26,6 +26,14 @@import { isPlainObject } from './objects.js';+/**+ * The `origin` a quota-burn on-demand request carries. Declared here rather+ * than in `taskScheduleConstants.js` so the stamp below can gate on it without+ * importing upward out of `lib/`; that module re-exports it as+ * `ON_DEMAND_ORIGINS.QUOTA_BURN`, so there is still exactly one literal.+ */+export const QUOTA_BURN_REQUEST_ORIGIN = 'quota-burn';+const MAX_FIELD = 64;const trimmed = (value, max = MAX_FIELD) => (typeof value === 'string' ? value.trim().slice(0, max) : '');@@ -84,9 +92,18 @@ export function normalizeQuotaBurnProvenance(raw) {** `null` origin means "not recorded", which every reader treats as a human Run:* that is what a request queued before the field existed is.+ *+ * The burn keys are gated on the ORIGIN, not merely on a `burn` block that+ * parses. `triggerOnDemandTask` refuses to persist one on any other origin, so+ * the two can only disagree in a hand-edited schedule — and stamping there would+ * be the worst of both: `isCooldownExemptTask` would treat an ordinary human Run+ * as burn-exempt and the denial ledger would credit its refusal to a family that+ * never dispatched it, while the refill planner still drained it as a human Run.*/export function onDemandRequestMetadata(request) {- const burn = normalizeQuotaBurnProvenance(request?.burn);+ const burn = request?.origin === QUOTA_BURN_REQUEST_ORIGIN+ ? normalizeQuotaBurnProvenance(request.burn)+ : null;const requestId = trimmed(request?.id, 128);return {onDemand: true,diff --git a/server/lib/quotaBurnOrigin.test.js b/server/lib/quotaBurnOrigin.test.jsindex 3e7ccd3760..0abf07d828 100644--- a/server/lib/quotaBurnOrigin.test.js+++ b/server/lib/quotaBurnOrigin.test.js@@ -73,4 +73,13 @@ describe('onDemandRequestMetadata', () => {expect(onDemandRequestMetadata({ id: 'demand-8', origin: 'quota-burn', burn: { family: 'grok' } })).toEqual({ onDemand: true, onDemandOrigin: 'quota-burn' });});++ it('adds no burn keys to a request that is not a burn, however well-formed its block', () => {+ // `triggerOnDemandTask` refuses to persist a `burn` block on any other+ // origin, so the two can only disagree in a hand-edited schedule — where+ // stamping would make a human Run read as cooldown-exempt and credit its+ // refusal to a family that never dispatched it.+ expect(onDemandRequestMetadata({ id: 'demand-9', origin: 'user', burn: provenance() }))+ .toEqual({ onDemand: true, onDemandOrigin: 'user' });+ });});diff --git a/server/services/quotaBurnInvoke.js b/server/services/quotaBurnInvoke.jsindex 57d18ea88b..51f1969f1f 100644--- a/server/services/quotaBurnInvoke.js+++ b/server/services/quotaBurnInvoke.js@@ -38,10 +38,15 @@* than parked awaiting approval — parking one would consume the family's* dispatch budget for work that spends nothing.*- * `force` reaches here already meaning "the user clicked ▶": it bypasses the- * QUOTA gates in `quotaBurn.js#evaluateFamily`, and nothing else. Task- * eligibility, approval, scope and enabled state all still hold — those are- * facts about whether the work may run at all, not about this window's budget.+ * `force` reaches here already meaning "the user clicked ▶". It bypasses the+ * QUOTA gates in `quotaBurn.js#evaluateFamily`, and it is threaded into a+ * programmatic handler so that handler can relax its OWN in-flight cooldown —+ * which is the whole point of the button on a `universe-bible-images` row whose+ * probe reports zero for entries that are merely already queued. What it never+ * relaxes: task eligibility, approval, target scope, enabled state, the master+ * Improve gate, and the duplicate checks below. Those are facts about whether+ * the work may run at all, not about this window's budget — and a duplicate in+ * particular is not "declined because of a gate", it is the same work twice.*/import {@@ -304,6 +309,25 @@ 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.*@@ -383,6 +407,9 @@ 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,@@ -404,6 +431,15 @@ async function runProgrammaticStep({ resolved, family, context, force }) {* schedule's gates are not quota gates.*/async function runBuiltinTaskStep({ resolved, step, family, candidate }) {+ // Re-checked HERE, not left to the probe: a forced run of a named step skips+ // the probe entirely (the click IS the selection), and `triggerOnDemandTask`+ // appends unconditionally — so without this, two forced clicks queue the same+ // task twice and charge the window's cap twice for one piece of work. The+ // legacy executor never had this hole because `addTask` deduplicated one step+ // further down; a request has no such backstop.+ const queued = await queuedOnDemandReason(resolved.catalog?.queued, resolved.ref.taskType, resolved.ref.appId);+ if (queued) return declined(queued);+const picked = await resolveStepProvider(resolved.effective, family);if (picked.error) return declined(picked.error);@@ -454,6 +490,12 @@ 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);+ if (active) return declined(active);const picked = await resolveStepProvider(resolved.effective, family);if (picked.error) return declined(picked.error);@@ -475,9 +517,12 @@ async function runCustomJobStep({ resolved, step, family, candidate }) {provider: picked.provider.id,model: resolved.effective.model || undefined,effort: resolved.effective.effort || undefined,- // Same provenance keys the built-in lane stamps via the request, so+ // The attribution keys the built-in lane stamps via its request, so// `isCooldownExemptTask`, the completion continuation and the denial ledger- // cannot tell the two lanes apart.+ // cannot tell the two lanes apart. There is deliberately no+ // `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,quotaBurnLimitingResetAt: candidate?.limitingResetAt ?? null,quotaBurnStepId: step.id,diff --git a/server/services/quotaBurnInvoke.test.js b/server/services/quotaBurnInvoke.test.jsindex e26fa5ae57..89d4945dbb 100644--- a/server/services/quotaBurnInvoke.test.js+++ b/server/services/quotaBurnInvoke.test.js@@ -21,6 +21,8 @@ const state = {onDemandRequests: [],inFlightJobIds: [],agents: {},+ improveEnabled: true,+ cosStateReadable: true,triggered: [],triggerResult: null,added: [],@@ -62,7 +64,8 @@ vi.mock('./providers.js', () => ({}));vi.mock('./cosState.js', () => ({- loadState: vi.fn(async () => ({ agents: state.agents })),+ loadState: vi.fn(async () => (state.cosStateReadable ? { agents: state.agents } : null)),+ isImprovementEnabled: vi.fn(() => state.improveEnabled),}));vi.mock('./cosTaskStore.js', () => ({@@ -135,6 +138,8 @@ beforeEach(() => {state.onDemandRequests = [];state.inFlightJobIds = [];state.agents = {};+ state.improveEnabled = true;+ state.cosStateReadable = true;state.triggered = [];state.triggerResult = null;state.added = [];@@ -299,6 +304,40 @@ describe('refusal paths', () => {dispatchedNothing();});+ // Both the custom and the programmatic lane run WITHOUT reaching+ // `triggerOnDemandTask`, which is where the built-in lane inherits this gate.+ // Every other way those two fire is gated on it, so a burn that ignored it+ // would be the one path that spends a subscription while the user has CoS+ // improvement switched off.+ it('refuses the custom and programmatic lanes while master Improve is off', async () => {+ state.improveEnabled = false;+ expect((await refuse({ taskRef: { kind: 'custom', jobId: 'job-a' } })).reason).toContain('Improvement is disabled');+ expect((await refuse({ taskRef: { kind: 'builtin', taskType: 'universe-bible-images' } })).reason).toContain('Improvement is disabled');+ dispatchedNothing();+ });++ it('fails closed when CoS state cannot be read at all', async () => {+ state.cosStateReadable = false;+ expect((await refuse({ taskRef: { kind: 'custom', jobId: 'job-a' } })).reason).toContain('could not be read');+ dispatchedNothing();+ });++ // A forced run of a NAMED step skips the probe (the click IS the selection),+ // so the duplicate checks have to live on the RUN path too. The built-in lane+ // has no backstop at all — `triggerOnDemandTask` appends unconditionally — so+ // without this two clicks queue the same task twice and charge the cap twice.+ it('refuses a duplicate even under force, on both agent lanes', async () => {+ state.onDemandRequests = [{ id: 'demand-0', taskType: 'ux', appId: 'app-1' }];+ state.inFlightJobIds = ['job-a'];+ const forced = (raw) => invokeQuotaBurnStep({ step: step(raw), family: grok, candidate, force: true });++ expect((await forced({ taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } })).reason)+ .toContain('already queued');+ expect((await forced({ taskRef: { kind: 'custom', jobId: 'job-a' } })).reason)+ .toContain('already in flight');+ dispatchedNothing();+ });+it('refuses an un-migrated legacy step rather than guessing a reference for it', async () => {const result = await refuse({ jobType: 'agent-prompt', params: { appId: 'app-1', prompt: 'go' } });expect(result.reason).toContain('waiting to be migrated');diff --git a/server/services/taskScheduleConstants.js b/server/services/taskScheduleConstants.jsindex 1040614954..62056a4383 100644--- a/server/services/taskScheduleConstants.js+++ b/server/services/taskScheduleConstants.js@@ -1,5 +1,7 @@/** Dependency-free task scheduling constants shared by registry and runtime modules. */+import { QUOTA_BURN_REQUEST_ORIGIN } from '../lib/quotaBurnOrigin.js';+const MINUTE_MS = 60 * 1000;const HOUR_MS = 60 * MINUTE_MS;const DAY_MS = 24 * HOUR_MS;@@ -53,7 +55,7 @@ export const FAILURE_PARK_THRESHOLD = 5;** A request written before `origin` existed carries none, which reads as USER.*/-export const ON_DEMAND_ORIGINS = { USER: 'user', REFILL: 'refill', QUOTA_BURN: 'quota-burn' };+export const ON_DEMAND_ORIGINS = { USER: 'user', REFILL: 'refill', QUOTA_BURN: QUOTA_BURN_REQUEST_ORIGIN };export const isRefillRequest = (request) => request?.origin === ON_DEMAND_ORIGINS.REFILL;/*** Whether a human asked for this run. Absent origin reads as USER (see above),