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: make quota-burn recovery idempotent (#3182)
[._.]/ Adam Eivyb44e64b7310e
diff --git a/server/services/autonomousJobs/quotaBurnHooks.js b/server/services/autonomousJobs/quotaBurnHooks.jsindex 4849a76b6c..7e61416660 100644--- a/server/services/autonomousJobs/quotaBurnHooks.js+++ b/server/services/autonomousJobs/quotaBurnHooks.js@@ -96,12 +96,12 @@ export async function buildTaskInput({ app, ignoreTaskId = null } = {}) {* write is environmental, not a bad run; log and move on, exactly as the* verdict's own docstring prescribes for a hook whose side effect couldn't land.*/-export async function processTaskOutput({ task } = {}) {+export async function processTaskOutput({ agentId, task } = {}) {const dispatchKey = task?.metadata?.[QUOTA_BURN_DISPATCH_KEY_FIELD];// Absent key = this task predates the metadata thread, or generation never// resolved a candidate. Nothing to record; never invent a ledger entry.if (typeof dispatchKey !== 'string' || !dispatchKey) return;- await recordQuotaBurnDispatch(dispatchKey)+ await recordQuotaBurnDispatch(dispatchKey, { agentId }).then(() => console.log(`🔥 Recorded quota-burn dispatch for ${dispatchKey}`)).catch((err) => console.error(`❌ Failed to record quota-burn dispatch for ${dispatchKey}: ${err.message}`));}diff --git a/server/services/autonomousJobs/quotaBurnHooks.test.js b/server/services/autonomousJobs/quotaBurnHooks.test.jsindex c78f22ae5d..33a1cfcfc3 100644--- a/server/services/autonomousJobs/quotaBurnHooks.test.js+++ b/server/services/autonomousJobs/quotaBurnHooks.test.js@@ -99,10 +99,10 @@ describe('processTaskOutput (post-agent)', () => {// The quota was consumed the moment the agent ran, so a failed run counts too.it.each([true, false])('records the dispatch exactly once on a run with success=%s', async (success) => {- await processTaskOutput({ appId: 'app-1', success, payload: null, task });+ await processTaskOutput({ appId: 'app-1', agentId: 'agent-1', success, payload: null, task });expect(recordQuotaBurnDispatch).toHaveBeenCalledTimes(1);- expect(recordQuotaBurnDispatch).toHaveBeenCalledWith(DISPATCH_KEY);+ expect(recordQuotaBurnDispatch).toHaveBeenCalledWith(DISPATCH_KEY, { agentId: 'agent-1' });});it('swallows a ledger write failure instead of throwing', async () => {@@ -140,8 +140,8 @@ describe('processTaskOutput (post-agent)', () => {expect(reparsed.metadata[QUOTA_BURN_DISPATCH_KEY_FIELD]).toBe(DISPATCH_KEY);- await processTaskOutput({ appId: 'app-1', success: true, task: reparsed });- expect(recordQuotaBurnDispatch).toHaveBeenCalledWith(DISPATCH_KEY);+ await processTaskOutput({ appId: 'app-1', agentId: 'agent-1', success: true, task: reparsed });+ expect(recordQuotaBurnDispatch).toHaveBeenCalledWith(DISPATCH_KEY, { agentId: 'agent-1' });});it('returns no structured outcome, so quota-burn stays exit-code-judged', async () => {diff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.jsindex d84f72de51..88a4c67398 100644--- a/server/services/quotaBurn.js+++ b/server/services/quotaBurn.js@@ -6,6 +6,7 @@ import { hoursUntilReset, normalizeResetAt } from '../lib/quotaReset.js';export const QUOTA_BURN_TASK_TYPE = 'quota-burn';const LEDGER_FILE = join(PATHS.cos, 'quota-burn-dispatches.json');+const AGENT_DISPATCH_LEDGER_KEY = '__agentDispatches';export const DEFAULT_QUOTA_BURN_FAMILY = {enabled: false,providerId: null,@@ -23,11 +24,16 @@ export function quotaBurnConfig(app) {return metadata && typeof metadata === 'object' ? metadata : { families: {} };}-export async function getQuotaBurnDispatches() {+async function readQuotaBurnLedger() {const loaded = await readJSONFile(LEDGER_FILE, {});return loaded && typeof loaded === 'object' ? loaded : {};}+export async function getQuotaBurnDispatches() {+ const { [AGENT_DISPATCH_LEDGER_KEY]: _agentDispatches, ...counts } = await readQuotaBurnLedger();+ return counts;+}+// Single-tail queue for the dispatch ledger's read-modify-write. Two quota-burn// agents (one per app) can finalize concurrently, and each finalization records a// dispatch — unserialized, both would read the same count and write the same@@ -36,12 +42,26 @@ export async function getQuotaBurnDispatches() {// the "serialize two write paths that mutate the same record" case, not a// defense against competing users. It only became reachable when the write moved// from generation (sequential, one app at a time) to finalize (#3179).+//+// `__agentDispatches` keeps the increment idempotent across a crash between the+// hook side effect and finalizeAgent's separate agent-marker write (#3182). It+// lives in this SAME atomic ledger write and leaves window counts as top-level+// numbers, so an older PortOS version still reads and updates the file safely.const ledgerWriteQueue = createFileWriteQueue();-export async function recordQuotaBurnDispatch(key) {+export async function recordQuotaBurnDispatch(key, { agentId = null } = {}) {return ledgerWriteQueue(async () => {- const ledger = await getQuotaBurnDispatches();- const next = { ...ledger, [key]: Number(ledger[key] || 0) + 1 };+ const ledger = await readQuotaBurnLedger();+ const agentDispatches = ledger[AGENT_DISPATCH_LEDGER_KEY];+ const seenAgents = agentDispatches && typeof agentDispatches === 'object' ? agentDispatches : {};+ if (agentId && seenAgents[agentId]) return ledger;+ const next = {+ ...ledger,+ [key]: Number(ledger[key] || 0) + 1,+ ...(agentId ? {+ [AGENT_DISPATCH_LEDGER_KEY]: { ...seenAgents, [agentId]: key }+ } : {}),+ };await atomicWrite(LEDGER_FILE, next);return next;});diff --git a/server/services/quotaBurn.test.js b/server/services/quotaBurn.test.jsindex 8d7623b3e2..b329395f1c 100644--- a/server/services/quotaBurn.test.js+++ b/server/services/quotaBurn.test.js@@ -151,4 +151,25 @@ describe('recordQuotaBurnDispatch serialization', () => {await expect(getQuotaBurnDispatches()).resolves.toEqual({ 'grok:1': 2, 'codex:2': 1 });});++ it('deduplicates an agent replay in the same atomic ledger write as the increment', async () => {+ vi.resetModules();+ let stored = {};+ vi.doMock('../lib/fileUtils.js', async (importActual) => ({+ ...(await importActual()),+ readJSONFile: async () => ({ ...stored }),+ atomicWrite: async (_file, data) => { stored = structuredClone(data); },+ }));+ const { recordQuotaBurnDispatch, getQuotaBurnDispatches } = await import('./quotaBurn.js');++ await recordQuotaBurnDispatch('grok:1', { agentId: 'agent-1' });+ await recordQuotaBurnDispatch('grok:1', { agentId: 'agent-1' });+ await recordQuotaBurnDispatch('grok:1', { agentId: 'agent-2' });++ await expect(getQuotaBurnDispatches()).resolves.toEqual({ 'grok:1': 2 });+ expect(stored.__agentDispatches).toEqual({+ 'agent-1': 'grok:1',+ 'agent-2': 'grok:1',+ });+ });});