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

address review (codex): cap CoS action overshoot + enforce messages minutes budget

[._.]/ Adam Eivy24f220e69f9b
diff --git a/client/src/components/cos/tabs/ConfigTab.jsx b/client/src/components/cos/tabs/ConfigTab.jsx
index 15e6fde8ac..d716882d8d 100644
--- a/client/src/components/cos/tabs/ConfigTab.jsx
+++ b/client/src/components/cos/tabs/ConfigTab.jsx
@@ -218,7 +218,9 @@ function DomainBudgetControl({ config, usage, onBudgetChange }) {
{DOMAIN_BUDGET_FIELDS.map((field) => {
const inputId = `budget-${domain.id}-${field.id}`;
const cap = budget[field.id];
- const used = field.usageKey === 'actions' ? (u.actions || 0) : minutesUsed;
+ // Compare exact minutes (not the rounded display) so the
+ // highlight matches server enforcement, which gates on raw ms.
+ const used = field.usageKey === 'actions' ? (u.actions || 0) : (u.ms || 0) / 60000;
const over = cap != null && used >= cap;
return (
<div key={field.id} className="flex flex-col">
diff --git a/server/lib/domainBudgets.js b/server/lib/domainBudgets.js
index d3fafb8258..ece1bbb622 100644
--- a/server/lib/domainBudgets.js
+++ b/server/lib/domainBudgets.js
@@ -119,6 +119,25 @@ export function hasBudget(budget) {
* @param {{actions?: number, ms?: number}} usage - today's accumulated usage
* @returns {{withinBudget: boolean, exceeded: 'actions'|'minutes'|null}}
*/
+/**
+ * How many more autonomous actions a domain may take today, given its budget,
+ * today's recorded usage, and the count of in-flight (spawned-but-not-yet-
+ * recorded) autonomous runs. Returns `Infinity` when no action cap is set, and
+ * never goes negative. Used by the CoS evaluator to cap a single cycle's
+ * autonomous admissions so a small cap can't be overshot by a concurrent batch.
+ *
+ * @param {{maxActionsPerDay: number|null}} budget
+ * @param {{actions?: number}} usage - today's recorded usage
+ * @param {number} [inFlight=0] - autonomous runs spawned today but not yet recorded
+ * @returns {number}
+ */
+export function remainingActionBudget(budget, usage, inFlight = 0) {
+ const max = budget?.maxActionsPerDay;
+ if (max == null) return Infinity;
+ const used = (Number(usage?.actions) || 0) + (Number(inFlight) || 0);
+ return Math.max(0, max - used);
+}
+
export function evaluateBudget(budget, usage) {
const actions = Number(usage?.actions) || 0;
const ms = Number(usage?.ms) || 0;
diff --git a/server/lib/domainBudgets.test.js b/server/lib/domainBudgets.test.js
index 8b17710888..bc1cb87984 100644
--- a/server/lib/domainBudgets.test.js
+++ b/server/lib/domainBudgets.test.js
@@ -7,7 +7,8 @@ import {
normalizeDomainBudgets,
getDomainBudget,
hasBudget,
- evaluateBudget
+ evaluateBudget,
+ remainingActionBudget
} from './domainBudgets.js';
describe('domainBudgets constants', () => {
@@ -118,3 +119,25 @@ describe('evaluateBudget', () => {
expect(evaluateBudget(budget, undefined)).toEqual({ withinBudget: true, exceeded: null });
});
});
+
+describe('remainingActionBudget', () => {
+ it('is Infinity when no action cap is set', () => {
+ expect(remainingActionBudget({ maxActionsPerDay: null }, { actions: 100 }, 50)).toBe(Infinity);
+ expect(remainingActionBudget({}, { actions: 5 })).toBe(Infinity);
+ });
+
+ it('subtracts both recorded usage and in-flight runs from the cap', () => {
+ // cap 5, 2 completed, 1 in-flight → 2 remaining (prevents a 3-slot batch
+ // from overshooting when only 2 actions are actually left).
+ expect(remainingActionBudget({ maxActionsPerDay: 5 }, { actions: 2 }, 1)).toBe(2);
+ });
+
+ it('never goes negative even when usage already exceeds the cap', () => {
+ expect(remainingActionBudget({ maxActionsPerDay: 1 }, { actions: 3 }, 2)).toBe(0);
+ });
+
+ it('defaults in-flight to 0 and tolerates missing usage', () => {
+ expect(remainingActionBudget({ maxActionsPerDay: 4 }, {})).toBe(4);
+ expect(remainingActionBudget({ maxActionsPerDay: 4 }, undefined)).toBe(4);
+ });
+});
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 893ec25e2c..e17c0748fb 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -26,6 +26,7 @@ import { sanitizeTaskMetadata, PIPELINE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS, normal
import { parsePlanItems, extractAllIds, findInProgressIds, pickFirstAvailable, diagnoseUnpickablePlan } from '../lib/planIds.js';
import { loadState, saveState, withStateLock, isImprovementEnabled, isDaemonRunning } from './cosState.js';
import { getDomainMode } from '../lib/domainAutonomy.js';
+import { remainingActionBudget } from '../lib/domainBudgets.js';
import { getDomainBudgetStatus } from './domainUsage.js';
import { cosEvents, emitLog } from './cosEvents.js';
import { addTask, updateTask, getAllTasks, getCosTasks, firstLine, PRIORITY_VALUES } from './cosTaskStore.js';
@@ -317,20 +318,39 @@ export async function evaluateTasks(options) {
// queued auto-approved tasks it would have spawned without emitting them.
let cosAutonomyMode = getDomainMode(state.config, 'cos');
- // Daily CoS budget (#711): once today's autonomous-run actions/minutes reach
- // the cap, hold all automatic spawns for the rest of the day — treat it as
- // `off`. Usage is tallied in completeAgent (autonomous runs only), so a pure
- // dry-run never accrues and never trips this; user/on-demand spawns above are
- // already past this gate and stay unaffected.
+ // Daily CoS budget (#711). Two dimensions, handled differently so a single
+ // evaluation can't overshoot a small cap by spawning a whole concurrent batch:
+ // - minutes: binary — a run's wall-clock isn't known at spawn time, so once
+ // today's autonomous minutes reach the cap we withhold all automatic spawns
+ // (treat as `off`); a single in-flight run's overshoot is unavoidable.
+ // - actions: precise — cap THIS cycle's autonomous admissions to the remaining
+ // daily allowance, counting both completed (ledger) and in-flight autonomous
+ // runs. `autonomousActionsRemaining` flows into `autonomousSlotCeiling` below.
+ // Usage is tallied in completeAgent for autonomous runs only, so a pure dry-run
+ // never accrues; user/on-demand spawns above are already past this gate.
const cosBudget = await getDomainBudgetStatus('cos');
- if (cosAutonomyMode !== 'off' && !cosBudget.withinBudget) {
- emitLog('info', `CoS auto-run paused — daily ${cosBudget.exceeded} budget reached`, { domainBudget: 'cos', exceeded: cosBudget.exceeded });
- cosAutonomyMode = 'off';
+ let autonomousActionsRemaining = Infinity;
+ if (cosAutonomyMode !== 'off') {
+ if (cosBudget.exceeded === 'minutes') {
+ emitLog('info', `CoS auto-run paused — daily minutes budget reached`, { domainBudget: 'cos', exceeded: 'minutes' });
+ cosAutonomyMode = 'off';
+ } else if (cosBudget.budget?.maxActionsPerDay != null) {
+ const runningAutonomous = runningAgentEntries.filter(
+ (a) => a.metadata?.taskType && a.metadata.taskType !== 'user'
+ ).length;
+ autonomousActionsRemaining = remainingActionBudget(cosBudget.budget, cosBudget.usage, runningAutonomous);
+ if (autonomousActionsRemaining === 0) {
+ emitLog('info', `CoS auto-run paused — daily actions budget reached`, { domainBudget: 'cos', exceeded: 'actions' });
+ cosAutonomyMode = 'off';
+ }
+ }
}
- // Helper: check if a task can spawn (within both global and per-project limits)
- const canSpawnTask = (task) => {
- if (tasksToSpawn.length >= availableSlots) return false;
+ // Helper: check if a task can spawn (within both global and per-project limits).
+ // `ceiling` defaults to the global slot count; autonomous sections pass the
+ // lower `autonomousSlotCeiling` so the CoS action budget (#711) caps them.
+ const canSpawnTask = (task, ceiling = availableSlots) => {
+ if (tasksToSpawn.length >= ceiling) return false;
const project = task.metadata?.app || '_self';
return (spawnProjectCounts[project] || 0) < perProjectLimit;
};
@@ -431,16 +451,23 @@ export async function evaluateTasks(options) {
trackSpawn(userTask);
}
+ // Ceiling for AUTONOMOUS admissions this cycle (#711). On-demand + user tasks
+ // are already in `tasksToSpawn` and never count against the CoS action budget,
+ // so the autonomous sections below may add at most `autonomousActionsRemaining`
+ // more. With no action cap this equals `availableSlots`, so the default path is
+ // unchanged. The autonomous sections use this in place of `availableSlots`.
+ const autonomousSlotCeiling = Math.min(availableSlots, tasksToSpawn.length + autonomousActionsRemaining);
+
// Priority 2: Auto-approved system tasks (if slots available) — gated by the
// CoS auto-run domain. off/dry-run withhold the unattended spawn; dry-run logs
// what would have run so the user can see the plan without it executing.
- if (tasksToSpawn.length < availableSlots && cosTaskData.exists && cosAutonomyMode !== 'execute') {
+ if (tasksToSpawn.length < autonomousSlotCeiling && cosTaskData.exists && cosAutonomyMode !== 'execute') {
if (cosAutonomyMode === 'dry-run') {
// Log only the tasks execute mode would ACTUALLY spawn — applying the same
// max-spawns / cooldown / per-project gates against virtual capacity —
// rather than every auto-approved task regardless of eligibility.
const wouldSpawn = await selectDryRunAutoApproved(cosTaskData.autoApproved || [], {
- availableSlots,
+ availableSlots: autonomousSlotCeiling,
alreadySpawned: tasksToSpawn.length,
perProjectLimit,
spawnProjectCounts,
@@ -451,10 +478,10 @@ export async function evaluateTasks(options) {
emitLog('info', `[dry-run] CoS auto-run would spawn system task: ${task.id}`, { taskId: task.id, domainAutonomy: 'cos' });
}
}
- } else if (tasksToSpawn.length < availableSlots && cosTaskData.exists) {
+ } else if (tasksToSpawn.length < autonomousSlotCeiling && cosTaskData.exists) {
const autoApproved = cosTaskData.autoApproved || [];
for (const task of autoApproved) {
- if (tasksToSpawn.length >= availableSlots) break;
+ if (tasksToSpawn.length >= autonomousSlotCeiling) break;
if (await blockIfExceedsMaxSpawns(task, 'internal')) continue;
@@ -475,7 +502,7 @@ export async function evaluateTasks(options) {
}
const sysTask = { ...task, taskType: 'internal' };
- if (!canSpawnTask(sysTask)) {
+ if (!canSpawnTask(sysTask, autonomousSlotCeiling)) {
const sysProject = appId || '_self';
emitLog('debug', `⏳ Queued system task ${task.id} - per-project limit reached for ${sysProject}`);
await recordDecision(
@@ -504,14 +531,14 @@ export async function evaluateTasks(options) {
// Priority 3: Mission-driven proactive tasks (if no user tasks). Autonomous —
// gated by the CoS auto-run domain (off/dry-run skip generation entirely).
- if (tasksToSpawn.length < availableSlots && !hasPendingUserTasks && state.config.proactiveMode && cosAutonomyMode === 'execute') {
- const missionTasks = await generateMissionTasks({ maxTasks: availableSlots - tasksToSpawn.length }).catch(err => {
+ if (tasksToSpawn.length < autonomousSlotCeiling && !hasPendingUserTasks && state.config.proactiveMode && cosAutonomyMode === 'execute') {
+ const missionTasks = await generateMissionTasks({ maxTasks: autonomousSlotCeiling - tasksToSpawn.length }).catch(err => {
emitLog('debug', `Mission task generation failed: ${err.message}`);
return [];
});
for (const missionTask of missionTasks) {
- if (tasksToSpawn.length >= availableSlots) break;
+ if (tasksToSpawn.length >= autonomousSlotCeiling) break;
// Convert mission task to COS task format
const cosTask = {
id: missionTask.id,
@@ -522,7 +549,7 @@ export async function evaluateTasks(options) {
taskType: 'internal',
approvalRequired: !missionTask.autoApprove
};
- if (!canSpawnTask(cosTask)) continue;
+ if (!canSpawnTask(cosTask, autonomousSlotCeiling)) continue;
tasksToSpawn.push(cosTask);
trackSpawn(cosTask);
emitLog('info', `Generated mission task: ${missionTask.id} (${missionTask.metadata?.missionName})`, {
@@ -540,16 +567,16 @@ export async function evaluateTasks(options) {
// Priority 3.6: Feature Agents (after autonomous jobs, yield to user tasks).
// Autonomous — gated by the CoS auto-run domain.
- if (tasksToSpawn.length < availableSlots && !hasPendingUserTasks && cosAutonomyMode === 'execute') {
+ if (tasksToSpawn.length < autonomousSlotCeiling && !hasPendingUserTasks && cosAutonomyMode === 'execute') {
const { getDueFeatureAgents, generateTaskFromFeatureAgent, setCurrentAgent } = await import('./featureAgents.js');
const dueAgents = await getDueFeatureAgents().catch(err => {
emitLog('debug', `Feature agents check failed: ${err.message}`);
return [];
});
for (const fa of dueAgents) {
- if (tasksToSpawn.length >= availableSlots) break;
+ if (tasksToSpawn.length >= autonomousSlotCeiling) break;
const task = generateTaskFromFeatureAgent(fa);
- if (!canSpawnTask(task)) continue;
+ if (!canSpawnTask(task, autonomousSlotCeiling)) continue;
tasksToSpawn.push(task);
trackSpawn(task);
// Mark agent as having a pending task to prevent duplicate spawns
@@ -567,7 +594,7 @@ export async function evaluateTasks(options) {
const pendingSystemTasks = freshCosTasks.autoApproved?.length || 0;
if (pendingSystemTasks === 0) {
const idleTask = await generateIdleReviewTask(state);
- if (idleTask && canSpawnTask(idleTask)) {
+ if (idleTask && canSpawnTask(idleTask, autonomousSlotCeiling)) {
tasksToSpawn.push(idleTask);
trackSpawn(idleTask);
}
diff --git a/server/services/telegram.js b/server/services/telegram.js
index 4b8ed74214..06d903868c 100644
--- a/server/services/telegram.js
+++ b/server/services/telegram.js
@@ -423,9 +423,11 @@ async function forwardNotification(notification) {
}
if (notification.priority) lines.push(`Priority: ${priorityEmoji} ${notification.priority}`);
+ const startTime = Date.now();
await sendMessage(lines.join('\n'), opts);
- // Count the forward against the messages domain's daily budget (#711).
- await recordDomainUsage('messages', { actions: 1 })
+ // Count the forward (and its wall-clock) against the messages daily budget
+ // (#711) so both the actions and minutes caps are enforced for this domain.
+ await recordDomainUsage('messages', { actions: 1, ms: Date.now() - startTime })
.catch(err => console.error(`❌ Failed to record messages budget usage: ${err.message}`));
}
diff --git a/server/services/telegramBridge.js b/server/services/telegramBridge.js
index f4d709d5fb..c89c19bb0b 100644
--- a/server/services/telegramBridge.js
+++ b/server/services/telegramBridge.js
@@ -255,9 +255,11 @@ async function forwardNotification(notification) {
if (notification.description) lines.push(escapeHtml(notification.description));
if (notification.priority) lines.push(`Priority: ${priorityEmoji} ${notification.priority}`);
+ const startTime = Date.now();
await sendMessage(lines.join('\n'));
- // Count the forward against the messages domain's daily budget (#711).
- await recordDomainUsage('messages', { actions: 1 })
+ // Count the forward (and its wall-clock) against the messages daily budget
+ // (#711) so both the actions and minutes caps are enforced for this domain.
+ await recordDomainUsage('messages', { actions: 1, ms: Date.now() - startTime })
.catch(err => console.error(`❌ Failed to record messages budget usage: ${err.message}`));
}