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): budget-gate the event-driven dequeue + count script/shell jobs

[._.]/ Adam Eivyb1fabde96dd0
diff --git a/server/services/cos.js b/server/services/cos.js
index 2cfab46fbc..be9fef9d2a 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -28,7 +28,8 @@ import { safeJSONParse } from '../lib/fileUtils.js';
import { addNotification, NOTIFICATION_TYPES } from './notifications.js';
import { getUserTimezone, todayInTimezone } from '../lib/timezone.js';
import { normalizeDomainAutonomy, getDomainMode } from '../lib/domainAutonomy.js';
-import { normalizeDomainBudgets } from '../lib/domainBudgets.js';
+import { normalizeDomainBudgets, remainingActionBudget } from '../lib/domainBudgets.js';
+import { getDomainBudgetStatus } from './domainUsage.js';
// Shared state management (extracted to avoid circular deps)
import { loadState, saveState, withStateLock, ensureDirectories, isImprovementEnabled, AGENTS_DIR, REPORTS_DIR, SCRIPTS_DIR, ROOT_DIR, isDaemonRunning, setDaemonRunning } from './cosState.js';
@@ -662,8 +663,10 @@ async function dequeueNextTask() {
const spawnProjectCounts = { ...agentsByProject };
let spawned = 0;
- const canSpawn = (task) => {
- if (spawned >= availableSlots) return false;
+ // `ceiling` defaults to the global slot count; autonomous sections pass the
+ // lower `autonomousSpawnCeiling` so the CoS daily action budget (#711) caps them.
+ const canSpawn = (task, ceiling = availableSlots) => {
+ if (spawned >= ceiling) return false;
const project = task.metadata?.app || '_self';
return (spawnProjectCounts[project] || 0) < perProjectLimit;
};
@@ -760,7 +763,33 @@ async function dequeueNextTask() {
// have run so the user can see the plan without it executing.
const cosTaskData = await getCosTasks();
const autoApproved = cosTaskData.autoApproved || [];
- const cosAutonomyMode = getDomainMode(state.config, 'cos');
+ let cosAutonomyMode = getDomainMode(state.config, 'cos');
+
+ // Daily CoS budget (#711) — same enforcement as the periodic evaluator
+ // (cosTaskGenerator.evaluateTasks). This is the event-driven primary spawn
+ // path, so the budget MUST be applied here too. Minutes is a binary off-gate
+ // (a run's duration is unknown at spawn); actions cap THIS cycle's autonomous
+ // admissions to the remaining daily allowance (completed + in-flight runs),
+ // surfaced as `autonomousSpawnCeiling` below. On-demand (Priority 0) and user
+ // (Priority 1) tasks are already spawned above and never count against it.
+ const cosBudget = await getDomainBudgetStatus('cos');
+ 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 = Object.values(state.agents).filter(
+ (a) => a.status === 'running' && 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';
+ }
+ }
+ }
+ const autonomousSpawnCeiling = Math.min(availableSlots, spawned + autonomousActionsRemaining);
// Engine-specific gate shared by execute and dry-run: improvement tasks whose
// task type was disabled after queuing are skipped.
@@ -776,7 +805,7 @@ async function dequeueNextTask() {
// rather than every auto-approved task regardless of eligibility.
if (cosAutonomyMode === 'dry-run') {
const wouldSpawn = await selectDryRunAutoApproved(autoApproved, {
- availableSlots,
+ availableSlots: autonomousSpawnCeiling,
alreadySpawned: spawned,
perProjectLimit,
spawnProjectCounts,
@@ -789,7 +818,7 @@ async function dequeueNextTask() {
}
} else {
for (const task of autoApproved) {
- if (spawned >= availableSlots) break;
+ if (spawned >= autonomousSpawnCeiling) break;
if (await blockIfExceedsMaxSpawns(task, 'internal')) continue;
// Skip improvement tasks whose type was disabled after queuing
if (isDisabledAnalysisType(task)) {
@@ -803,7 +832,7 @@ async function dequeueNextTask() {
if (onCooldown) continue;
}
const sysTask = { ...task, taskType: 'internal' };
- if (!canSpawn(sysTask)) continue;
+ if (!canSpawn(sysTask, autonomousSpawnCeiling)) continue;
cosEvents.emit('task:ready', sysTask);
trackSpawn(sysTask);
}
@@ -815,14 +844,14 @@ async function dequeueNextTask() {
// spawns — when CoS auto-run isn't `execute`, skip generating them entirely
// (off and dry-run both withhold autonomous spawns; only the concrete already-
// queued auto-approved tasks above are surfaced for dry-run).
- if (spawned < availableSlots && !hasPendingUserTasks && state.config.proactiveMode && cosAutonomyMode === 'execute') {
- const missionTasks = await generateMissionTasks({ maxTasks: availableSlots - spawned }).catch(err => {
+ if (spawned < autonomousSpawnCeiling && !hasPendingUserTasks && state.config.proactiveMode && cosAutonomyMode === 'execute') {
+ const missionTasks = await generateMissionTasks({ maxTasks: autonomousSpawnCeiling - spawned }).catch(err => {
emitLog('debug', `Mission task generation failed: ${err.message}`);
return [];
});
for (const missionTask of missionTasks) {
- if (spawned >= availableSlots) break;
+ if (spawned >= autonomousSpawnCeiling) break;
const cosTask = {
id: missionTask.id,
description: missionTask.description,
@@ -832,7 +861,7 @@ async function dequeueNextTask() {
taskType: 'internal',
approvalRequired: !missionTask.autoApprove
};
- if (!canSpawn(cosTask)) continue;
+ if (!canSpawn(cosTask, autonomousSpawnCeiling)) continue;
cosEvents.emit('task:ready', cosTask);
trackSpawn(cosTask);
emitLog('info', `Generated mission task: ${missionTask.id}`, {
@@ -848,7 +877,7 @@ async function dequeueNextTask() {
const pendingSystemTasks = freshCosTasks.autoApproved?.length || 0;
if (pendingSystemTasks === 0) {
const idleTask = await generateIdleReviewTask(state);
- if (idleTask && canSpawn(idleTask)) {
+ if (idleTask && canSpawn(idleTask, autonomousSpawnCeiling)) {
cosEvents.emit('task:ready', idleTask);
trackSpawn(idleTask);
}
diff --git a/server/services/cosJobScheduler.js b/server/services/cosJobScheduler.js
index f2fe09daf9..f55a4096ba 100644
--- a/server/services/cosJobScheduler.js
+++ b/server/services/cosJobScheduler.js
@@ -26,7 +26,8 @@ import { getUserTimezone, getLocalParts, nextLocalTime } from '../lib/timezone.j
import { formatDuration } from '../lib/fileUtils.js';
import { loadState, isDaemonRunning } from './cosState.js';
import { getDomainMode } from '../lib/domainAutonomy.js';
-import { getDomainBudgetStatus } from './domainUsage.js';
+import { remainingActionBudget } from '../lib/domainBudgets.js';
+import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';
import { cosEvents, emitLog } from './cosEvents.js';
import { getCosTasks } from './cosTaskStore.js';
import { queueEligibleImprovementTasks } from './cosTaskGenerator.js';
@@ -185,14 +186,27 @@ export async function executeScheduledJob(jobId) {
// branch's comment warns about).
let cosAutonomyMode = getDomainMode(state.config, 'cos');
- // Daily CoS budget (#711): a scheduled job firing is an autonomous run, so
- // once today's actions/minutes cap is hit, withhold it like `off` (and skip
- // the dry-run "would fire" log — over budget means stop, not narrate). Same
- // gate-skip bookkeeping below advances lastRun so re-registration is future-dated.
+ // Daily CoS budget (#711): a scheduled job firing is one autonomous action, so
+ // once today's actions/minutes cap is hit, withhold it like `off` (and skip the
+ // dry-run "would fire" log — over budget means stop, not narrate). The action
+ // check counts in-flight autonomous runs too (recorded usage lags behind spawn),
+ // so concurrent scheduled jobs can't slip past a small cap. Same gate-skip
+ // bookkeeping below advances lastRun so re-registration is future-dated.
const cosBudget = await getDomainBudgetStatus('cos');
- if (cosAutonomyMode !== 'off' && !cosBudget.withinBudget) {
- emitLog('info', `CoS auto-run paused — daily ${cosBudget.exceeded} budget reached, withholding scheduled job: ${job.name}`, { jobId, domainBudget: 'cos', exceeded: cosBudget.exceeded });
- cosAutonomyMode = 'off';
+ if (cosAutonomyMode !== 'off') {
+ let overBudget = false;
+ if (cosBudget.exceeded === 'minutes') {
+ overBudget = true;
+ } else if (cosBudget.budget?.maxActionsPerDay != null) {
+ const runningAutonomous = Object.values(state.agents).filter(
+ (a) => a.status === 'running' && a.metadata?.taskType && a.metadata.taskType !== 'user'
+ ).length;
+ if (remainingActionBudget(cosBudget.budget, cosBudget.usage, runningAutonomous) < 1) overBudget = true;
+ }
+ if (overBudget) {
+ emitLog('info', `CoS auto-run paused — daily ${cosBudget.exceeded || 'actions'} budget reached, withholding scheduled job: ${job.name}`, { jobId, domainBudget: 'cos', exceeded: cosBudget.exceeded || 'actions' });
+ cosAutonomyMode = 'off';
+ }
}
if (cosAutonomyMode !== 'execute') {
@@ -206,19 +220,32 @@ export async function executeScheduledJob(jobId) {
return;
}
- // Script jobs and shell jobs execute directly without spawning an AI agent
+ // Script jobs and shell jobs execute directly without spawning an AI agent —
+ // so they never reach completeAgent's budget tally. Record them against the CoS
+ // daily budget (#711) here on success, since a fired scheduled job is exactly
+ // the autonomous action the gate above withholds when over budget.
if (isScriptJob(job)) {
+ const startedAt = Date.now();
const scriptOk = await executeScriptJob(job).then(() => true, err => {
emitLog('error', `Script job failed: ${job.name} - ${err.message}`, { jobId: job.id });
return false;
});
- if (scriptOk) emitLog('info', `Script job executed: ${job.name}`, { jobId: job.id });
+ if (scriptOk) {
+ emitLog('info', `Script job executed: ${job.name}`, { jobId: job.id });
+ await recordDomainUsage('cos', { actions: 1, ms: Date.now() - startedAt })
+ .catch(err => console.error(`❌ Failed to record CoS budget usage for script job ${job.id}: ${err.message}`));
+ }
} else if (isShellJob(job)) {
+ const startedAt = Date.now();
const shellOk = await executeShellJob(job).then(() => true, err => {
emitLog('error', `Shell job failed: ${job.name} - ${err.message}`, { jobId: job.id });
return false;
});
- if (shellOk) emitLog('info', `Shell job executed: ${job.name}`, { jobId: job.id });
+ if (shellOk) {
+ emitLog('info', `Shell job executed: ${job.name}`, { jobId: job.id });
+ await recordDomainUsage('cos', { actions: 1, ms: Date.now() - startedAt })
+ .catch(err => console.error(`❌ Failed to record CoS budget usage for shell job ${job.id}: ${err.message}`));
+ }
} else {
// Check if this job is already being spawned or has a running agent.
// Don't re-register the timer here — the job:spawned handler will do it