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

feat([issue-711]): per-domain daily autonomy budgets (actions + minutes)

[._.]/ Adam Eivy644668d18f9e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f9eedc3358..f7946dd24d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,3 +1,7 @@
+## Added
+
+- **Daily budgets for the Chief of Staff's domains** — each domain (Brain auto-classify, Memory auto-extract, CoS auto-run, Messages auto-send) can now carry a daily cap on how many automatic actions it takes and how many minutes of work it does. When a domain reaches its cap it pauses that automatic work for the rest of the day and resumes after the counters reset at midnight; the Chief of Staff config panel shows each domain's usage so far today. Caps are off by default (blank means unlimited), so nothing changes until you set one. This rounds out the per-domain guardrails alongside the off / dry-run / execute controls.
+
## Changed
- Code quality: extracted the duplicated cron-expression validation in `cosJobRoutes.js` (job create/update) into a single `validateCronExpression()` helper, and unified the two slightly-divergent error messages.
diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.js
index 6000470cb0..26cf7db2ab 100644
--- a/client/src/components/cos/constants.js
+++ b/client/src/components/cos/constants.js
@@ -201,6 +201,31 @@ export const getDomainMode = (config, domainId) => {
return DOMAIN_AUTONOMY_MODES.some(m => m.id === candidate) ? candidate : DEFAULT_DOMAIN_MODE;
};
+// Per-domain daily autonomy budgets (#711). Mirrors server/lib/domainBudgets.js.
+// Each domain caps autonomous work on two measurable dimensions; an empty/0 cap
+// means unlimited. (No token/$ caps — CLI subscription providers expose no
+// per-run metering, so a money/token cap couldn't be enforced honestly.)
+export const DOMAIN_BUDGET_FIELDS = [
+ { id: 'maxActionsPerDay', label: 'Actions/day', usageKey: 'actions' },
+ { id: 'maxMinutesPerDay', label: 'Minutes/day', usageKey: 'minutes' }
+];
+
+// Coerce a cap to a positive integer or null (unlimited) — mirrors the server's
+// normalizeBudgetLimit so the UI's "is a cap set?" view matches enforcement.
+export const normalizeBudgetLimit = (value) => {
+ const n = typeof value === 'number' ? value : Number(value);
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : null;
+};
+
+// Resolve a domain's budget from config, tolerating absent/partial config.
+export const getDomainBudget = (config, domainId) => {
+ const b = config?.domainBudgets?.[domainId] || {};
+ return {
+ maxActionsPerDay: normalizeBudgetLimit(b.maxActionsPerDay),
+ maxMinutesPerDay: normalizeBudgetLimit(b.maxMinutesPerDay)
+ };
+};
+
// Autonomy level presets for CoS behavior
export const AUTONOMY_LEVELS = [
{
diff --git a/client/src/components/cos/constants.test.js b/client/src/components/cos/constants.test.js
new file mode 100644
index 0000000000..89fba1e215
--- /dev/null
+++ b/client/src/components/cos/constants.test.js
@@ -0,0 +1,51 @@
+import { describe, it, expect } from 'vitest';
+import {
+ DOMAIN_BUDGET_FIELDS,
+ normalizeBudgetLimit,
+ getDomainBudget,
+ getDomainMode,
+ DEFAULT_DOMAIN_MODE
+} from './constants';
+
+// These mirror the server's domainBudgets/domainAutonomy helpers so the UI's
+// "is a cap set?" / "what mode?" view never disagrees with enforcement.
+
+describe('cos budget constants', () => {
+ it('exposes the two cap dimensions with usage keys', () => {
+ expect(DOMAIN_BUDGET_FIELDS.map((f) => f.id)).toEqual(['maxActionsPerDay', 'maxMinutesPerDay']);
+ expect(DOMAIN_BUDGET_FIELDS.map((f) => f.usageKey)).toEqual(['actions', 'minutes']);
+ });
+});
+
+describe('normalizeBudgetLimit (client mirror)', () => {
+ it('keeps positive integers, floors fractions', () => {
+ expect(normalizeBudgetLimit(5)).toBe(5);
+ expect(normalizeBudgetLimit('7.9')).toBe(7);
+ });
+
+ it('treats 0 / negatives / garbage as unlimited (null)', () => {
+ for (const v of [0, -3, NaN, Infinity, '', 'x', null, undefined]) {
+ expect(normalizeBudgetLimit(v)).toBeNull();
+ }
+ });
+});
+
+describe('getDomainBudget (client mirror)', () => {
+ it('returns unlimited caps when config is absent/partial', () => {
+ expect(getDomainBudget(undefined, 'cos')).toEqual({ maxActionsPerDay: null, maxMinutesPerDay: null });
+ expect(getDomainBudget({}, 'brain')).toEqual({ maxActionsPerDay: null, maxMinutesPerDay: null });
+ });
+
+ it('reads and coerces stored caps', () => {
+ const config = { domainBudgets: { cos: { maxActionsPerDay: 10, maxMinutesPerDay: -1 } } };
+ expect(getDomainBudget(config, 'cos')).toEqual({ maxActionsPerDay: 10, maxMinutesPerDay: null });
+ });
+});
+
+describe('getDomainMode (existing helper, sanity)', () => {
+ it('defaults to execute for absent/invalid config', () => {
+ expect(getDomainMode(undefined, 'cos')).toBe(DEFAULT_DOMAIN_MODE);
+ expect(getDomainMode({ domainAutonomy: { cos: 'bogus' } }, 'cos')).toBe(DEFAULT_DOMAIN_MODE);
+ expect(getDomainMode({ domainAutonomy: { cos: 'off' } }, 'cos')).toBe('off');
+ });
+});
diff --git a/client/src/components/cos/tabs/ConfigTab.jsx b/client/src/components/cos/tabs/ConfigTab.jsx
index 06baf33f86..15e6fde8ac 100644
--- a/client/src/components/cos/tabs/ConfigTab.jsx
+++ b/client/src/components/cos/tabs/ConfigTab.jsx
@@ -1,9 +1,9 @@
-import { useState, useEffect } from 'react';
+import { useState, useEffect, useCallback } from 'react';
import { Settings, Activity, CheckCircle, FileText } from 'lucide-react';
import toast from '../../ui/Toast';
import * as api from '../../../services/api';
import ConfigRow from './ConfigRow';
-import { AUTONOMY_LEVELS, detectAutonomyLevel, formatInterval, AVATAR_STYLE_LABELS, AUTONOMY_DOMAINS, DOMAIN_AUTONOMY_MODES, getDomainMode } from '../constants';
+import { AUTONOMY_LEVELS, detectAutonomyLevel, formatInterval, AVATAR_STYLE_LABELS, AUTONOMY_DOMAINS, DOMAIN_AUTONOMY_MODES, getDomainMode, DOMAIN_BUDGET_FIELDS, getDomainBudget, normalizeBudgetLimit } from '../constants';
import ProviderModelSelector from '../../ProviderModelSelector';
import useProviderModels from '../../../hooks/useProviderModels';
@@ -189,6 +189,65 @@ function DomainAutonomyControl({ config, onDomainChange }) {
);
}
+// Per-domain daily budgets (#711) — caps on autonomous work per domain plus a
+// readout of today's usage. Each cap PATCHes only its field on blur (the server
+// field-merges). Blank/0 = unlimited. Token/$ caps are intentionally absent —
+// CLI subscription providers report no per-run cost to enforce against.
+function DomainBudgetControl({ config, usage, onBudgetChange }) {
+ return (
+ <div className="bg-port-card border border-port-border rounded-lg p-4 mb-6">
+ <h4 className="text-sm font-medium text-gray-400 mb-1">Domain Budgets</h4>
+ <p className="text-xs text-gray-600 mb-3">
+ Daily caps on autonomous work per domain — blank or 0 means unlimited. Once a
+ cap is reached the domain pauses until the counters reset at midnight (UTC).
+ </p>
+ <div className="space-y-3">
+ {AUTONOMY_DOMAINS.map((domain) => {
+ const budget = getDomainBudget(config, domain.id);
+ const u = usage?.[domain.id] || { actions: 0, ms: 0 };
+ const minutesUsed = Math.round((u.ms || 0) / 60000);
+ return (
+ <div key={domain.id} className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
+ <div className="min-w-0">
+ <span className="text-sm text-gray-300">{domain.label}</span>
+ <p className="text-xs text-gray-600">
+ Today: {u.actions || 0} actions · {minutesUsed} min
+ </p>
+ </div>
+ <div className="flex gap-3 shrink-0">
+ {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;
+ const over = cap != null && used >= cap;
+ return (
+ <div key={field.id} className="flex flex-col">
+ <label htmlFor={inputId} className="text-[10px] text-gray-500 mb-0.5">{field.label}</label>
+ <input
+ id={inputId}
+ // Remount when the persisted cap changes so the uncontrolled
+ // input reflects external updates without fighting typing.
+ key={`${inputId}-${cap ?? ''}`}
+ type="number"
+ min="0"
+ inputMode="numeric"
+ defaultValue={cap ?? ''}
+ placeholder="∞"
+ onBlur={(e) => onBudgetChange(domain.id, field.id, e.target.value, domain.label, field.label)}
+ className={`w-20 px-2 py-1 text-xs rounded-md border bg-port-bg text-gray-200 ${over ? 'border-port-warning text-port-warning' : 'border-port-border'}`}
+ />
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, setAvatarStyle, evalCountdown }) {
const { providers, availableModels, setSelectedProviderId: setProviderHook, setSelectedModel: setModelHook, selectedProviderId: hookProviderId, selectedModel: hookModel } = useProviderModels();
const [embeddingProviderId, setEmbeddingProviderId] = useState(config?.embeddingProviderId || 'lmstudio');
@@ -227,6 +286,15 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, s
onUpdate();
};
+ // Today's per-domain usage for the Domain Budgets readout (#711).
+ const [budgetUsage, setBudgetUsage] = useState({});
+ const refreshBudgetUsage = useCallback(() => {
+ api.getCosBudgetUsage({ silent: true })
+ .then((res) => setBudgetUsage(res?.usage || {}))
+ .catch(() => {});
+ }, []);
+ useEffect(() => { refreshBudgetUsage(); }, [refreshBudgetUsage]);
+
const handleDomainChange = async (domainId, mode, modeLabel, domainLabel) => {
// Custom error toast ⇒ pass { silent: true } so the helper doesn't also
// toast; and only show success / refresh AFTER the PUT actually resolves.
@@ -239,6 +307,21 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, s
}
};
+ const handleBudgetChange = async (domainId, field, rawValue, domainLabel, fieldLabel) => {
+ // Empty / 0 / NaN / negative → null (unlimited), mirroring the server.
+ const value = normalizeBudgetLimit(rawValue);
+ const current = getDomainBudget(config, domainId)[field];
+ if ((current ?? null) === value) return; // no-op (e.g. blur without edit)
+ try {
+ await api.updateCosConfig({ domainBudgets: { [domainId]: { [field]: value } } }, { silent: true });
+ toast.success(`${domainLabel} ${fieldLabel} ${value == null ? 'set to unlimited' : `capped at ${value}`}`);
+ onUpdate();
+ refreshBudgetUsage();
+ } catch (err) {
+ toast.error(err.message);
+ }
+ };
+
const handleSave = async () => {
await api.updateCosConfig(formData).catch(err => toast.error(err.message));
toast.success('Configuration updated');
@@ -285,6 +368,8 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, s
{/* Per-domain Autonomy Guardrails */}
<DomainAutonomyControl config={config} onDomainChange={handleDomainChange} />
+ <DomainBudgetControl config={config} usage={budgetUsage} onBudgetChange={handleBudgetChange} />
+
<div className="bg-port-card border border-port-border rounded-lg divide-y divide-port-border">
<ConfigRow
label="Evaluation Interval"
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index f3f72cb3d0..31a73139c6 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -50,6 +50,8 @@ export const updateCosConfig = (config, options = {}) => request('/cos/config',
body: JSON.stringify(config),
...options
});
+// Today's per-domain autonomy usage (#711) for the Domain Budgets panel.
+export const getCosBudgetUsage = (options = {}) => request('/cos/budget-usage', options);
export const getCosTasks = (options) => request('/cos/tasks', options);
export const addCosTask = (task) => request('/cos/tasks', {
method: 'POST',
diff --git a/server/lib/README.md b/server/lib/README.md
index 44fa8ee964..0bf3703425 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -198,6 +198,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `asyncMutex.js` | Promise-based async mutex. |
| `authGate.js` | Express + Socket.IO middleware that gates `/api/*` and `/data/*` behind the password set in `settings.secrets.auth`. No-op when auth is off; emits 401 `AUTH_REQUIRED` (or plain text for `/data/*`) when on and the request has no valid session token. |
| `domainAutonomy.js` | Per-domain autonomy guardrails (pure). `AUTONOMY_DOMAINS`/`DOMAIN_IDS`/`DOMAIN_MODES` (`off`/`dry-run`/`execute`), `getDomainMode(config, id)`, and `normalizeDomainAutonomy(raw)` to coerce a hand-edited/partial map. Default per domain is `execute` (reproduces pre-#711 behavior, so no migration needed). |
+| `domainBudgets.js` | Per-domain daily autonomy budgets (pure). `BUDGET_LIMIT_FIELDS` (`maxActionsPerDay`/`maxMinutesPerDay`), `getDomainBudget(config, id)`, `normalizeDomainBudgets(raw)`, `hasBudget(budget)`, and `evaluateBudget(budget, usage)` → `{ withinBudget, exceeded }`. A `null`/non-positive cap means unlimited (default per domain, so no migration needed). Token/$ caps are intentionally absent — CLI subscription providers expose no per-run metering. Usage ledger + gate wiring live in `services/domainUsage.js`. |
| `errorHandler.js` | `ServerError` + `asyncHandler` middleware. |
| `mapWithConcurrency.js` | Generic bounded-concurrency async mapper that preserves input order while capping in-flight work. |
| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). |
diff --git a/server/lib/domainBudgets.js b/server/lib/domainBudgets.js
new file mode 100644
index 0000000000..d3fafb8258
--- /dev/null
+++ b/server/lib/domainBudgets.js
@@ -0,0 +1,134 @@
+/**
+ * Per-domain autonomy budgets (pure helpers).
+ *
+ * The third slice of the #711 autonomy-guardrails umbrella. Where
+ * `domainAutonomy.js` answers "is this domain allowed to act automatically?",
+ * this module answers "has this domain done *too much* automatic work today?".
+ * Each of the four domains (brain / memory / cos / messages) can carry a daily
+ * cap on two measurable dimensions:
+ *
+ * - `maxActionsPerDay` — count of autonomous actions (thoughts classified,
+ * memories extracted, agents auto-run, messages sent).
+ * - `maxMinutesPerDay` — cumulative wall-clock minutes of autonomous work
+ * (dominated by CoS agent runtime; small but real for
+ * brain/memory LLM classification).
+ *
+ * Why only actions + minutes (not "spend" / "tokens")? PortOS runs its AI
+ * through CLI *subscription* providers (claude-code, codex, gemini-cli) whose
+ * runner returns `{ text, model }` with NO per-run token or cost metering — so a
+ * token/dollar cap would be inert (never trip) or require fabricated estimates.
+ * Actions and minutes are the dimensions we can measure honestly, so those are
+ * the dimensions we enforce.
+ *
+ * A cap of `null` (or any non-positive value) means *unlimited* — the default
+ * for every domain on every dimension, so an install with no stored
+ * `domainBudgets` config behaves exactly as before (no migration needed, mirrors
+ * the `domainAutonomy` default-of-`execute` pattern).
+ *
+ * These helpers are side-effect-free: the usage ledger I/O and the gate wiring
+ * live in `server/services/domainUsage.js` and at each domain's call site. This
+ * module owns the vocabulary, normalization, and the within-budget math.
+ */
+
+import { DOMAIN_IDS } from './domainAutonomy.js';
+
+// The budget dimensions a domain can cap. Kept as an enumerable list so the
+// route schema, the client UI, and the normalizer all agree on the field set.
+export const BUDGET_LIMIT_FIELDS = ['maxActionsPerDay', 'maxMinutesPerDay'];
+
+// A domain with no caps — unlimited on every dimension (historical behavior).
+export const DEFAULT_DOMAIN_BUDGET = Object.freeze(
+ Object.fromEntries(BUDGET_LIMIT_FIELDS.map((f) => [f, null]))
+);
+
+const MS_PER_MINUTE = 60_000;
+
+/**
+ * Coerce a single cap value into a positive integer or `null` (unlimited).
+ * `0`, negatives, NaN, non-numbers, and Infinity all mean unlimited — so the UI
+ * can clear a cap by emptying the field (which sends `null`/`0`/`''`).
+ *
+ * @param {unknown} value
+ * @returns {number|null}
+ */
+export function normalizeBudgetLimit(value) {
+ const n = typeof value === 'number' ? value : Number(value);
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : null;
+}
+
+/**
+ * Coerce a raw (possibly hand-edited / legacy / partial) domainBudgets map into
+ * a complete `{ [domainId]: { maxActionsPerDay, maxMinutesPerDay } }` object.
+ * Unknown domains are dropped; missing/invalid caps become `null` (unlimited).
+ *
+ * @param {unknown} raw
+ * @returns {Record<string, {maxActionsPerDay: number|null, maxMinutesPerDay: number|null}>}
+ */
+export function normalizeDomainBudgets(raw) {
+ const source = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
+ const normalized = {};
+ for (const id of DOMAIN_IDS) {
+ const domainRaw = source[id] && typeof source[id] === 'object' && !Array.isArray(source[id])
+ ? source[id]
+ : {};
+ normalized[id] = {};
+ for (const field of BUDGET_LIMIT_FIELDS) {
+ normalized[id][field] = normalizeBudgetLimit(domainRaw[field]);
+ }
+ }
+ return normalized;
+}
+
+/**
+ * Read a single domain's budget from a CoS config object. Tolerates a missing
+ * `config`, a missing `domainBudgets`, and partial/invalid stored values — all
+ * resolve to unlimited so absent config reproduces historical behavior.
+ *
+ * @param {object|null|undefined} config - CoS config (has optional `domainBudgets`)
+ * @param {string} domainId - one of DOMAIN_IDS
+ * @returns {{maxActionsPerDay: number|null, maxMinutesPerDay: number|null}}
+ */
+export function getDomainBudget(config, domainId) {
+ const domainRaw = config?.domainBudgets?.[domainId];
+ const source = domainRaw && typeof domainRaw === 'object' && !Array.isArray(domainRaw) ? domainRaw : {};
+ return Object.fromEntries(
+ BUDGET_LIMIT_FIELDS.map((field) => [field, normalizeBudgetLimit(source[field])])
+ );
+}
+
+/**
+ * `true` when a domain has at least one active cap. Unlimited-on-everything
+ * domains can skip the usage read entirely.
+ *
+ * @param {{maxActionsPerDay: number|null, maxMinutesPerDay: number|null}} budget
+ * @returns {boolean}
+ */
+export function hasBudget(budget) {
+ return budget?.maxActionsPerDay != null || budget?.maxMinutesPerDay != null;
+}
+
+/**
+ * Decide whether today's usage is still within a domain's budget. Pure: callers
+ * pass the normalized budget and the day's accumulated usage.
+ *
+ * Uses `>=` (not `>`) so a cap of N permits exactly N actions/minutes and blocks
+ * the N+1th — i.e. the cap is the count you're allowed to reach, and exhausting
+ * it stops further autonomous work for the rest of the day.
+ *
+ * @param {{maxActionsPerDay: number|null, maxMinutesPerDay: number|null}} budget
+ * @param {{actions?: number, ms?: number}} usage - today's accumulated usage
+ * @returns {{withinBudget: boolean, exceeded: 'actions'|'minutes'|null}}
+ */
+export function evaluateBudget(budget, usage) {
+ const actions = Number(usage?.actions) || 0;
+ const ms = Number(usage?.ms) || 0;
+ const { maxActionsPerDay, maxMinutesPerDay } = budget || DEFAULT_DOMAIN_BUDGET;
+
+ if (maxActionsPerDay != null && actions >= maxActionsPerDay) {
+ return { withinBudget: false, exceeded: 'actions' };
+ }
+ if (maxMinutesPerDay != null && ms / MS_PER_MINUTE >= maxMinutesPerDay) {
+ return { withinBudget: false, exceeded: 'minutes' };
+ }
+ return { withinBudget: true, exceeded: null };
+}
diff --git a/server/lib/domainBudgets.test.js b/server/lib/domainBudgets.test.js
new file mode 100644
index 0000000000..8b17710888
--- /dev/null
+++ b/server/lib/domainBudgets.test.js
@@ -0,0 +1,120 @@
+import { describe, it, expect } from 'vitest';
+import { DOMAIN_IDS } from './domainAutonomy.js';
+import {
+ BUDGET_LIMIT_FIELDS,
+ DEFAULT_DOMAIN_BUDGET,
+ normalizeBudgetLimit,
+ normalizeDomainBudgets,
+ getDomainBudget,
+ hasBudget,
+ evaluateBudget
+} from './domainBudgets.js';
+
+describe('domainBudgets constants', () => {
+ it('exposes the two measurable cap dimensions', () => {
+ expect(BUDGET_LIMIT_FIELDS).toEqual(['maxActionsPerDay', 'maxMinutesPerDay']);
+ });
+
+ it('defaults every dimension to unlimited (null)', () => {
+ expect(DEFAULT_DOMAIN_BUDGET).toEqual({ maxActionsPerDay: null, maxMinutesPerDay: null });
+ });
+});
+
+describe('normalizeBudgetLimit', () => {
+ it('keeps positive integers, flooring fractions', () => {
+ expect(normalizeBudgetLimit(5)).toBe(5);
+ expect(normalizeBudgetLimit(5.9)).toBe(5);
+ expect(normalizeBudgetLimit('12')).toBe(12);
+ });
+
+ it('treats zero / negatives / garbage / Infinity as unlimited (null)', () => {
+ for (const v of [0, -1, -100, NaN, Infinity, -Infinity, null, undefined, '', 'nope', {}, []]) {
+ expect(normalizeBudgetLimit(v)).toBeNull();
+ }
+ });
+});
+
+describe('normalizeDomainBudgets', () => {
+ it('fills every domain with an unlimited budget for empty/garbage input', () => {
+ for (const raw of [undefined, null, {}, [], 'nope', 42]) {
+ const out = normalizeDomainBudgets(raw);
+ expect(Object.keys(out).sort()).toEqual([...DOMAIN_IDS].sort());
+ for (const id of DOMAIN_IDS) {
+ expect(out[id]).toEqual({ maxActionsPerDay: null, maxMinutesPerDay: null });
+ }
+ }
+ });
+
+ it('keeps valid caps, coerces invalid ones, and drops unknown domains', () => {
+ const out = normalizeDomainBudgets({
+ brain: { maxActionsPerDay: 20, maxMinutesPerDay: 0 },
+ cos: { maxActionsPerDay: -3, maxMinutesPerDay: 90 },
+ bogus: { maxActionsPerDay: 99 }
+ });
+ expect(out.brain).toEqual({ maxActionsPerDay: 20, maxMinutesPerDay: null });
+ expect(out.cos).toEqual({ maxActionsPerDay: null, maxMinutesPerDay: 90 });
+ expect(out.memory).toEqual({ maxActionsPerDay: null, maxMinutesPerDay: null });
+ expect(out.bogus).toBeUndefined();
+ });
+
+ it('tolerates a non-object per-domain value', () => {
+ const out = normalizeDomainBudgets({ brain: 'nope', memory: 7 });
+ expect(out.brain).toEqual({ maxActionsPerDay: null, maxMinutesPerDay: null });
+ expect(out.memory).toEqual({ maxActionsPerDay: null, maxMinutesPerDay: null });
+ });
+});
+
+describe('getDomainBudget', () => {
+ it('reads a domain budget from config, tolerating absent config', () => {
+ expect(getDomainBudget(undefined, 'brain')).toEqual({ maxActionsPerDay: null, maxMinutesPerDay: null });
+ expect(getDomainBudget({}, 'cos')).toEqual({ maxActionsPerDay: null, maxMinutesPerDay: null });
+ expect(getDomainBudget({ domainBudgets: { cos: { maxActionsPerDay: 10 } } }, 'cos'))
+ .toEqual({ maxActionsPerDay: 10, maxMinutesPerDay: null });
+ });
+
+ it('coerces invalid stored caps to unlimited', () => {
+ expect(getDomainBudget({ domainBudgets: { cos: { maxActionsPerDay: -5, maxMinutesPerDay: 'x' } } }, 'cos'))
+ .toEqual({ maxActionsPerDay: null, maxMinutesPerDay: null });
+ });
+});
+
+describe('hasBudget', () => {
+ it('is false for an unlimited budget and true when any cap is set', () => {
+ expect(hasBudget(DEFAULT_DOMAIN_BUDGET)).toBe(false);
+ expect(hasBudget(undefined)).toBe(false);
+ expect(hasBudget({ maxActionsPerDay: 1, maxMinutesPerDay: null })).toBe(true);
+ expect(hasBudget({ maxActionsPerDay: null, maxMinutesPerDay: 1 })).toBe(true);
+ });
+});
+
+describe('evaluateBudget', () => {
+ it('is always within budget when unlimited', () => {
+ const r = evaluateBudget(DEFAULT_DOMAIN_BUDGET, { actions: 9999, ms: 9_999_999 });
+ expect(r).toEqual({ withinBudget: true, exceeded: null });
+ });
+
+ it('exceeds the actions cap at exactly N (>=), not N-1', () => {
+ const budget = { maxActionsPerDay: 3, maxMinutesPerDay: null };
+ expect(evaluateBudget(budget, { actions: 2 })).toEqual({ withinBudget: true, exceeded: null });
+ expect(evaluateBudget(budget, { actions: 3 })).toEqual({ withinBudget: false, exceeded: 'actions' });
+ expect(evaluateBudget(budget, { actions: 4 })).toEqual({ withinBudget: false, exceeded: 'actions' });
+ });
+
+ it('exceeds the minutes cap when accumulated ms reaches the cap', () => {
+ const budget = { maxActionsPerDay: null, maxMinutesPerDay: 10 };
+ expect(evaluateBudget(budget, { ms: 9 * 60_000 })).toEqual({ withinBudget: true, exceeded: null });
+ expect(evaluateBudget(budget, { ms: 10 * 60_000 })).toEqual({ withinBudget: false, exceeded: 'minutes' });
+ });
+
+ it('reports actions before minutes when both are exceeded', () => {
+ const budget = { maxActionsPerDay: 1, maxMinutesPerDay: 1 };
+ expect(evaluateBudget(budget, { actions: 5, ms: 5 * 60_000 }))
+ .toEqual({ withinBudget: false, exceeded: 'actions' });
+ });
+
+ it('treats missing usage fields as zero', () => {
+ const budget = { maxActionsPerDay: 1, maxMinutesPerDay: 1 };
+ expect(evaluateBudget(budget, {})).toEqual({ withinBudget: true, exceeded: null });
+ expect(evaluateBudget(budget, undefined)).toEqual({ withinBudget: true, exceeded: null });
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 467805974d..84b4b993b2 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -165,6 +165,7 @@ export * from './timezone.js';
export * from './asyncMutex.js';
export * from './authGate.js';
export * from './domainAutonomy.js';
+export * from './domainBudgets.js';
export * from './errorHandler.js';
export * from './mapWithConcurrency.js';
export * from './objects.js';
diff --git a/server/routes/cosStatusRoutes.js b/server/routes/cosStatusRoutes.js
index 67c9141843..64dc507a98 100644
--- a/server/routes/cosStatusRoutes.js
+++ b/server/routes/cosStatusRoutes.js
@@ -4,12 +4,14 @@
import { Router } from 'express';
import * as cos from '../services/cos.js';
+import { getAllDomainUsageToday } from '../services/domainUsage.js';
import * as taskWatcher from '../services/taskWatcher.js';
import { reinitialize as reinitializeEmbeddings } from '../services/memoryEmbeddings.js';
import { asyncHandler } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import { z } from 'zod';
import { DOMAIN_IDS, DOMAIN_MODES } from '../lib/domainAutonomy.js';
+import { BUDGET_LIMIT_FIELDS } from '../lib/domainBudgets.js';
const router = Router();
@@ -48,6 +50,17 @@ export const cosConfigSchema = z.object({
domainAutonomy: z.object(
Object.fromEntries(DOMAIN_IDS.map((id) => [id, z.enum(DOMAIN_MODES).optional()]))
).strict().optional(),
+ // Per-domain daily budgets (#711): partial map of domainId → { cap → value }.
+ // Each cap is a non-negative integer or null (clear). Partial is fine —
+ // updateConfig() field-merges it over the stored map. 0/null = unlimited.
+ domainBudgets: z.object(
+ Object.fromEntries(DOMAIN_IDS.map((id) => [
+ id,
+ z.object(
+ Object.fromEntries(BUDGET_LIMIT_FIELDS.map((f) => [f, z.number().int().min(0).nullable().optional()]))
+ ).strict().optional()
+ ]))
+ ).strict().optional(),
rehabilitationGracePeriodDays: z.number().int().min(1).optional(),
completedAgentRetentionMs: z.number().int().min(0).optional(),
embeddingProviderId: z.string().optional(),
@@ -97,6 +110,13 @@ router.get('/config', asyncHandler(async (req, res) => {
res.json(config);
}));
+// GET /api/cos/budget-usage - Today's per-domain autonomy usage (for the
+// Domain Budgets panel). Reflects the rolling daily ledger that budgets gate on.
+router.get('/budget-usage', asyncHandler(async (req, res) => {
+ const usage = await getAllDomainUsageToday();
+ res.json(usage);
+}));
+
// PUT /api/cos/config - Update configuration
router.put('/config', asyncHandler(async (req, res) => {
const validated = validateRequest(cosConfigSchema, req.body);
diff --git a/server/services/brain.js b/server/services/brain.js
index 77cd7cd09d..1951b1bc78 100644
--- a/server/services/brain.js
+++ b/server/services/brain.js
@@ -16,6 +16,7 @@ import { validate } from '../lib/validation.js';
import { safeJSONParse } from '../lib/fileUtils.js';
import { runPromptThroughProvider } from '../lib/promptRunner.js';
import { getDomainAutonomyMode } from './cosState.js';
+import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';
import {
classifierOutputSchema,
digestOutputSchema,
@@ -138,7 +139,20 @@ export async function captureThought(text, providerOverride, modelOverride) {
// Per-domain autonomy gate: `off` captures the thought but skips auto-classify
// entirely (it lands in the inbox for manual review); `dry-run` classifies and
// surfaces the suggestion but doesn't auto-file it.
- const mode = await getDomainAutonomyMode('brain');
+ let mode = await getDomainAutonomyMode('brain');
+
+ // Daily brain budget (#711): when today's auto-classify actions/minutes reach
+ // the cap, fall back to `off` for the rest of the day — the thought is still
+ // captured for manual review, just not auto-classified. A manual retry
+ // (retryClassification) is user-initiated and never gated or counted.
+ let budgetPaused = false;
+ if (mode !== 'off') {
+ const budget = await getDomainBudgetStatus('brain');
+ if (!budget.withinBudget) {
+ mode = 'off';
+ budgetPaused = true;
+ }
+ }
// Create initial inbox log entry. When auto-classify is off the entry goes
// straight to needs_review rather than the transient classifying state — and
@@ -153,10 +167,12 @@ export async function captureThought(text, providerOverride, modelOverride) {
});
if (mode === 'off') {
- console.log(`🧠 Thought captured, auto-classify is OFF — left for manual review: ${inboxEntry.id}`);
+ console.log(`🧠 Thought captured, ${budgetPaused ? 'auto-classify daily budget reached' : 'auto-classify is OFF'} — left for manual review: ${inboxEntry.id}`);
return {
inboxLog: inboxEntry,
- message: 'Thought captured! Auto-classify is off — review it in the inbox.'
+ message: budgetPaused
+ ? 'Thought captured! Auto-classify daily budget reached — review it in the inbox.'
+ : 'Thought captured! Auto-classify is off — review it in the inbox.'
};
}
@@ -164,7 +180,7 @@ export async function captureThought(text, providerOverride, modelOverride) {
// Run AI classification in background (don't await)
// Pass resolved provider/model so callAI uses brain's configured provider, not the system active one
- classifyInBackground(inboxEntry.id, text, meta, provider, model, mode)
+ classifyInBackground(inboxEntry.id, text, meta, provider, model, mode, true)
.catch(err => console.error(`❌ Background classification failed for ${inboxEntry.id}: ${err.message}`));
return {
@@ -179,7 +195,7 @@ export async function captureThought(text, providerOverride, modelOverride) {
* Background AI classification for a captured thought.
* Updates the inbox entry and emits a brain:classified event when done.
*/
-async function classifyInBackground(entryId, text, meta, providerOverride, modelOverride, mode = 'execute') {
+async function classifyInBackground(entryId, text, meta, providerOverride, modelOverride, mode = 'execute', recordBudget = false) {
let classification = null;
let aiError = null;
@@ -194,7 +210,16 @@ async function classifyInBackground(entryId, text, meta, providerOverride, model
return null;
});
- const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
+ const durationMs = Date.now() - startTime;
+ const elapsed = (durationMs / 1000).toFixed(1);
+
+ // Daily brain budget accounting (#711): an auto-classify consumed compute
+ // whether or not it parsed, so count the attempt + its time. Only the auto
+ // path (captureThought) passes recordBudget — a manual retry doesn't count.
+ if (recordBudget) {
+ await recordDomainUsage('brain', { actions: 1, ms: durationMs })
+ .catch(err => console.error(`❌ Failed to record brain budget usage for ${entryId}: ${err.message}`));
+ }
const aiResponse = aiResult?.content;
// Patch ai metadata so the inbox entry reflects the model actually invoked
// (captureThought/retryClassification stored the pre-resolved value, which may
diff --git a/server/services/cos.js b/server/services/cos.js
index c468779200..2cfab46fbc 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -28,6 +28,7 @@ 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';
// 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';
@@ -154,6 +155,9 @@ export async function updateConfig(updates) {
// Capture the prior map BEFORE the spread clobbers it, then normalize the
// merge so an unknown/invalid stored value resolves to the `execute` default.
const priorDomainAutonomy = state.config.domainAutonomy;
+ // Same for domainBudgets — a PATCH naming one domain (or one cap on one
+ // domain) must merge field-by-field over the rest, not replace the map.
+ const priorDomainBudgets = state.config.domainBudgets;
state.config = { ...state.config, ...updates };
if (updates.domainAutonomy !== undefined) {
state.config.domainAutonomy = normalizeDomainAutonomy({
@@ -161,6 +165,13 @@ export async function updateConfig(updates) {
...updates.domainAutonomy
});
}
+ if (updates.domainBudgets !== undefined) {
+ const mergedBudgets = { ...priorDomainBudgets };
+ for (const [id, caps] of Object.entries(updates.domainBudgets)) {
+ mergedBudgets[id] = { ...(priorDomainBudgets?.[id] || {}), ...caps };
+ }
+ state.config.domainBudgets = normalizeDomainBudgets(mergedBudgets);
+ }
await saveState(state);
return state.config;
});
diff --git a/server/services/cosAgents.js b/server/services/cosAgents.js
index 7e66c1ba0d..64052cd5d1 100644
--- a/server/services/cosAgents.js
+++ b/server/services/cosAgents.js
@@ -12,6 +12,7 @@ import { join } from 'path';
import { cosEvents, emitLog } from './cosEvents.js';
import { loadState, saveState, withStateLock, AGENTS_DIR } from './cosState.js';
import { atomicWrite, ensureDir, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
+import { recordDomainUsage } from './domainUsage.js';
import { repairCodexTaskSummary } from './codexSummaryRepair.js';
const INDEX_FILE = join(AGENTS_DIR, 'index.json');
@@ -270,7 +271,7 @@ export async function updateAgent(agentId, updates) {
}
export async function completeAgent(agentId, result = {}) {
- return withStateLock(async () => {
+ const completed = await withStateLock(async () => {
const state = await loadState();
if (!state.agents[agentId]) {
@@ -329,6 +330,17 @@ export async function completeAgent(agentId, result = {}) {
return state.agents[agentId];
});
+
+ // Daily CoS budget accounting (#711): count only AUTONOMOUS runs (non-user
+ // tasks) — the same set the CoS auto-run gate withholds when over budget —
+ // toward the domain's actions/minutes ledger. Recorded outside the state lock
+ // (separate ledger file + write tail) so it never serializes against state.json.
+ if (completed?.metadata?.taskType && completed.metadata.taskType !== 'user') {
+ await recordDomainUsage('cos', { actions: 1, ms: Number(result.duration) || 0 })
+ .catch(err => console.error(`❌ Failed to record CoS budget usage for ${agentId}: ${err.message}`));
+ }
+
+ return completed;
}
export async function appendAgentOutput(agentId, line) {
diff --git a/server/services/cosJobScheduler.js b/server/services/cosJobScheduler.js
index 9124654024..f2fe09daf9 100644
--- a/server/services/cosJobScheduler.js
+++ b/server/services/cosJobScheduler.js
@@ -26,6 +26,7 @@ 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 { cosEvents, emitLog } from './cosEvents.js';
import { getCosTasks } from './cosTaskStore.js';
import { queueEligibleImprovementTasks } from './cosTaskGenerator.js';
@@ -182,7 +183,18 @@ export async function executeScheduledJob(jobId) {
// re-registration computes a FUTURE fire time — re-registering a past-due job
// with stale lastRun would refire every second (the same 1s-loop the spawn
// branch's comment warns about).
- const cosAutonomyMode = getDomainMode(state.config, 'cos');
+ 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.
+ 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 !== 'execute') {
if (cosAutonomyMode === 'dry-run') {
emitLog('info', `[dry-run] CoS auto-run would fire scheduled job: ${job.name}`, { jobId, domainAutonomy: 'cos' });
diff --git a/server/services/cosState.js b/server/services/cosState.js
index 29afc06f37..65688125ac 100644
--- a/server/services/cosState.js
+++ b/server/services/cosState.js
@@ -10,6 +10,7 @@ import { join, dirname } from 'path';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { ensureDirs, safeJSONParse, PATHS, atomicWrite } from '../lib/fileUtils.js';
import { normalizeDomainAutonomy, getDomainMode } from '../lib/domainAutonomy.js';
+import { normalizeDomainBudgets } from '../lib/domainBudgets.js';
export const STATE_FILE = join(PATHS.cos, 'state.json');
export const AGENTS_DIR = join(PATHS.cos, 'agents');
@@ -61,6 +62,10 @@ export const DEFAULT_CONFIG = {
// Default is `execute` for every domain, reproducing pre-#711 behavior so no
// migration is needed — an install with no stored value reads `execute`.
domainAutonomy: normalizeDomainAutonomy({}),
+ // Per-domain daily autonomy budgets (#711). Each domain caps maxActionsPerDay
+ // and maxMinutesPerDay; `null` = unlimited, which is the default for every
+ // domain — so an install with no stored value enforces nothing (no migration).
+ domainBudgets: normalizeDomainBudgets({}),
rehabilitationGracePeriodDays: 7,
completedAgentRetentionMs: 86400000,
embeddingProviderId: 'lmstudio',
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 9afb2f7314..893ec25e2c 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 { getDomainBudgetStatus } from './domainUsage.js';
import { cosEvents, emitLog } from './cosEvents.js';
import { addTask, updateTask, getAllTasks, getCosTasks, firstLine, PRIORITY_VALUES } from './cosTaskStore.js';
import { recordDecision, DECISION_TYPES } from './decisionLog.js';
@@ -314,7 +315,18 @@ export async function evaluateTasks(options) {
// spawns (auto-approved system tasks, mission, feature-agent, idle-review);
// user and on-demand tasks are unaffected. dry-run logs the concrete already-
// queued auto-approved tasks it would have spawned without emitting them.
- const cosAutonomyMode = getDomainMode(state.config, 'cos');
+ 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.
+ 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';
+ }
// Helper: check if a task can spawn (within both global and per-project limits)
const canSpawnTask = (task) => {
diff --git a/server/services/domainUsage.js b/server/services/domainUsage.js
new file mode 100644
index 0000000000..6491ba007b
--- /dev/null
+++ b/server/services/domainUsage.js
@@ -0,0 +1,114 @@
+/**
+ * Per-domain autonomy usage ledger (#711, budgets slice).
+ *
+ * Tracks how much autonomous work each domain has done *today* so the gate
+ * sites can compare it against the per-domain caps in `lib/domainBudgets.js`.
+ * Where `domainAutonomy` answers "may this domain act?" and `domainBudgets`
+ * defines the caps, this service is the running tally that makes the caps bite.
+ *
+ * Storage is one small rolling-day JSON file (`data/cos/domain-usage.json`):
+ * `{ date: 'YYYY-MM-DD', usage: { brain: { actions, ms }, ... } }`. When the
+ * stored date isn't today the ledger resets to zero on the next read or write —
+ * so "daily" budgets reset at UTC midnight, matching how `cosAgents` buckets
+ * completed agents by `toISOString().slice(0,10)` (budgets and agent archives
+ * roll over together). All writes serialize on a single file write tail.
+ */
+
+import { join } from 'path';
+import { PATHS, atomicWrite, readJSONFile } from '../lib/fileUtils.js';
+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+import { DOMAIN_IDS } from '../lib/domainAutonomy.js';
+import { getDomainBudget, hasBudget, evaluateBudget } from '../lib/domainBudgets.js';
+import { loadState } from './cosState.js';
+
+export const USAGE_FILE = join(PATHS.cos, 'domain-usage.json');
+
+// Single tail so two concurrent record calls can't read-modify-write the same
+// ledger file and clobber each other (same convention as cosState's withStateLock).
+const usageWriteTail = createFileWriteQueue();
+
+// The UTC calendar day key the ledger buckets against. Exported for tests.
+export function todayKey() {
+ return new Date().toISOString().slice(0, 10);
+}
+
+function emptyUsageMap() {
+ return Object.fromEntries(DOMAIN_IDS.map((id) => [id, { actions: 0, ms: 0 }]));
+}
+
+// Read the ledger from disk, rolling it to a fresh empty map when the stored
+// date isn't today (or the file is missing / hand-edited into a bad shape).
+async function readFreshLedger() {
+ const today = todayKey();
+ const stored = await readJSONFile(USAGE_FILE, null, { logError: false });
+ if (!stored || stored.date !== today || typeof stored.usage !== 'object' || stored.usage === null) {
+ return { date: today, usage: emptyUsageMap() };
+ }
+ // Backfill any domain missing from an older-shape / partial file, and coerce
+ // non-numeric tallies to 0 so a hand edit can't poison the math.
+ const usage = emptyUsageMap();
+ for (const id of DOMAIN_IDS) {
+ const u = stored.usage[id];
+ if (u && typeof u === 'object') {
+ usage[id] = { actions: Number(u.actions) || 0, ms: Number(u.ms) || 0 };
+ }
+ }
+ return { date: today, usage };
+}
+
+/**
+ * Add to a domain's usage for today (rolling the ledger to a new day if needed).
+ * No-op for unknown domains or an empty delta.
+ *
+ * @param {string} domainId - one of DOMAIN_IDS
+ * @param {{actions?: number, ms?: number}} delta
+ */
+export async function recordDomainUsage(domainId, { actions = 0, ms = 0 } = {}) {
+ if (!DOMAIN_IDS.includes(domainId)) return;
+ const addActions = Number(actions) || 0;
+ const addMs = Number(ms) || 0;
+ if (!addActions && !addMs) return;
+ await usageWriteTail(async () => {
+ const ledger = await readFreshLedger();
+ ledger.usage[domainId].actions += addActions;
+ ledger.usage[domainId].ms += addMs;
+ await atomicWrite(USAGE_FILE, ledger);
+ });
+}
+
+/**
+ * Today's accumulated usage for one domain.
+ * @returns {Promise<{actions: number, ms: number}>}
+ */
+export async function getDomainUsageToday(domainId) {
+ const ledger = await readFreshLedger();
+ return ledger.usage[domainId] || { actions: 0, ms: 0 };
+}
+
+/**
+ * Today's usage for every domain (for the settings UI).
+ * @returns {Promise<{date: string, usage: Record<string, {actions: number, ms: number}>}>}
+ */
+export async function getAllDomainUsageToday() {
+ return readFreshLedger();
+}
+
+/**
+ * Resolve a domain's live budget status from the stored CoS config + today's
+ * usage. Domains with no caps short-circuit without reading the ledger. Returns
+ * the budget and usage too, so the gate sites can log/display specifics.
+ *
+ * @param {string} domainId - one of DOMAIN_IDS
+ * @returns {Promise<{withinBudget: boolean, exceeded: 'actions'|'minutes'|null,
+ * budget: object, usage: {actions: number, ms: number}}>}
+ */
+export async function getDomainBudgetStatus(domainId) {
+ const state = await loadState();
+ const budget = getDomainBudget(state.config, domainId);
+ if (!hasBudget(budget)) {
+ return { withinBudget: true, exceeded: null, budget, usage: { actions: 0, ms: 0 } };
+ }
+ const usage = await getDomainUsageToday(domainId);
+ const { withinBudget, exceeded } = evaluateBudget(budget, usage);
+ return { withinBudget, exceeded, budget, usage };
+}
diff --git a/server/services/domainUsage.test.js b/server/services/domainUsage.test.js
new file mode 100644
index 0000000000..a072eabf9b
--- /dev/null
+++ b/server/services/domainUsage.test.js
@@ -0,0 +1,105 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+// In-memory file store so the ledger reads/writes hit no real disk.
+let store = new Map();
+let mockConfig = {};
+
+vi.mock('../lib/fileUtils.js', () => ({
+ PATHS: { cos: '/tmp/portos-test-cos' },
+ atomicWrite: vi.fn(async (path, data) => { store.set(path, structuredClone(data)); }),
+ readJSONFile: vi.fn(async (path, def = null) => (store.has(path) ? structuredClone(store.get(path)) : def))
+}));
+
+vi.mock('./cosState.js', () => ({
+ loadState: vi.fn(async () => ({ config: mockConfig }))
+}));
+
+const {
+ USAGE_FILE,
+ todayKey,
+ recordDomainUsage,
+ getDomainUsageToday,
+ getAllDomainUsageToday,
+ getDomainBudgetStatus
+} = await import('./domainUsage.js');
+
+beforeEach(() => {
+ store = new Map();
+ mockConfig = {};
+});
+
+describe('recordDomainUsage + getDomainUsageToday', () => {
+ it('accumulates actions and ms for a domain', async () => {
+ await recordDomainUsage('cos', { actions: 1, ms: 1000 });
+ await recordDomainUsage('cos', { actions: 2, ms: 500 });
+ expect(await getDomainUsageToday('cos')).toEqual({ actions: 3, ms: 1500 });
+ });
+
+ it('keeps domains independent', async () => {
+ await recordDomainUsage('brain', { actions: 5 });
+ await recordDomainUsage('messages', { actions: 2 });
+ expect(await getDomainUsageToday('brain')).toEqual({ actions: 5, ms: 0 });
+ expect(await getDomainUsageToday('messages')).toEqual({ actions: 2, ms: 0 });
+ expect(await getDomainUsageToday('cos')).toEqual({ actions: 0, ms: 0 });
+ });
+
+ it('ignores unknown domains and empty deltas', async () => {
+ await recordDomainUsage('bogus', { actions: 9 });
+ await recordDomainUsage('cos', { actions: 0, ms: 0 });
+ await recordDomainUsage('cos', {});
+ expect(store.has(USAGE_FILE)).toBe(false);
+ });
+
+ it('resets the ledger when the stored date is not today', async () => {
+ store.set(USAGE_FILE, {
+ date: '2000-01-01',
+ usage: { brain: { actions: 99, ms: 99 }, memory: { actions: 1, ms: 1 }, cos: { actions: 1, ms: 1 }, messages: { actions: 1, ms: 1 } }
+ });
+ // First read after a stale day shows zero...
+ expect(await getDomainUsageToday('brain')).toEqual({ actions: 0, ms: 0 });
+ // ...and a record stamps today's date with only the new delta.
+ await recordDomainUsage('brain', { actions: 3 });
+ const ledger = await getAllDomainUsageToday();
+ expect(ledger.date).toBe(todayKey());
+ expect(ledger.usage.brain).toEqual({ actions: 3, ms: 0 });
+ });
+
+ it('backfills missing domains and coerces bad tallies in a hand-edited file', async () => {
+ store.set(USAGE_FILE, { date: todayKey(), usage: { brain: { actions: 'x', ms: null } } });
+ expect(await getDomainUsageToday('brain')).toEqual({ actions: 0, ms: 0 });
+ expect(await getDomainUsageToday('cos')).toEqual({ actions: 0, ms: 0 });
+ });
+});
+
+describe('getDomainBudgetStatus', () => {
+ it('is within budget (no ledger read) when the domain has no caps', async () => {
+ mockConfig = {};
+ const status = await getDomainBudgetStatus('cos');
+ expect(status.withinBudget).toBe(true);
+ expect(status.exceeded).toBeNull();
+ });
+
+ it('reports within budget while under the actions cap', async () => {
+ mockConfig = { domainBudgets: { cos: { maxActionsPerDay: 3 } } };
+ await recordDomainUsage('cos', { actions: 2 });
+ const status = await getDomainBudgetStatus('cos');
+ expect(status.withinBudget).toBe(true);
+ expect(status.usage.actions).toBe(2);
+ });
+
+ it('reports exceeded once the actions cap is reached', async () => {
+ mockConfig = { domainBudgets: { cos: { maxActionsPerDay: 3 } } };
+ await recordDomainUsage('cos', { actions: 3 });
+ const status = await getDomainBudgetStatus('cos');
+ expect(status.withinBudget).toBe(false);
+ expect(status.exceeded).toBe('actions');
+ });
+
+ it('reports exceeded once the minutes cap is reached', async () => {
+ mockConfig = { domainBudgets: { cos: { maxMinutesPerDay: 5 } } };
+ await recordDomainUsage('cos', { ms: 5 * 60_000 });
+ const status = await getDomainBudgetStatus('cos');
+ expect(status.withinBudget).toBe(false);
+ expect(status.exceeded).toBe('minutes');
+ });
+});
diff --git a/server/services/memoryExtractor.js b/server/services/memoryExtractor.js
index c760a35b03..3e002a5711 100644
--- a/server/services/memoryExtractor.js
+++ b/server/services/memoryExtractor.js
@@ -11,6 +11,7 @@ import { cosEvents } from './cosEvents.js';
import * as notifications from './notifications.js';
import { classifyMemories, isAvailable as isClassifierAvailable } from './memoryClassifier.js';
import { getDomainAutonomyMode } from './cosState.js';
+import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';
const DEDUP_SIMILARITY_THRESHOLD = 0.82;
@@ -211,6 +212,16 @@ export async function extractAndStoreMemories(agentId, taskId, output, task = nu
return { created: 0, pendingApproval: 0, memories: [], pendingMemories: [], skipped: 'domain-off' };
}
+ // Daily memory budget (#711): once today's extraction actions/minutes reach the
+ // cap, skip for the rest of the day — same outcome as `off`, distinct reason.
+ const budget = await getDomainBudgetStatus('memory');
+ if (!budget.withinBudget) {
+ console.log(`🧠 Memory auto-extract daily ${budget.exceeded} budget reached — skipping extraction for agent ${agentId}`);
+ return { created: 0, pendingApproval: 0, memories: [], pendingMemories: [], skipped: 'domain-budget' };
+ }
+
+ // Time the extraction (incl. the LLM classify) for the minutes budget.
+ const startTime = Date.now();
const allMemories = [];
let usedLLM = false;
@@ -375,6 +386,10 @@ export async function extractAndStoreMemories(agentId, taskId, output, task = nu
skippedDuplicates
});
+ // Record the extraction against the memory domain's daily budget (#711).
+ await recordDomainUsage('memory', { actions: 1, ms: Date.now() - startTime })
+ .catch(err => console.error(`❌ Failed to record memory budget usage for agent ${agentId}: ${err.message}`));
+
return {
created: created.length,
pendingApproval: pendingMemories.length,
diff --git a/server/services/telegram.js b/server/services/telegram.js
index c51c45af06..4b8ed74214 100644
--- a/server/services/telegram.js
+++ b/server/services/telegram.js
@@ -11,6 +11,7 @@ import { v4 as uuidv4 } from '../lib/uuid.js';
import { getSettings } from './settings.js';
import { notificationEvents, NOTIFICATION_TYPES, getNotifications } from './notifications.js';
import { getDomainAutonomyMode } from './cosState.js';
+import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';
import { approveMemory, rejectMemory, peekMemory } from './memoryBackend.js';
import { ensureDir, PATHS, readJSONFile, formatDuration, atomicWrite } from '../lib/fileUtils.js';
import { getActiveAgents } from './subAgentSpawner.js';
@@ -388,6 +389,14 @@ async function forwardNotification(notification) {
return;
}
+ // Daily messages budget (#711): once today's auto-send count reaches the cap,
+ // suppress further forwarding for the rest of the day (acts like `off`).
+ const budget = await getDomainBudgetStatus('messages');
+ if (!budget.withinBudget) {
+ console.log(`📨 Messages auto-send daily ${budget.exceeded} budget reached — suppressing forward: ${notification.type} — "${notification.title}"`);
+ return;
+ }
+
const emoji = NOTIFICATION_EMOJI[notification.type] || '🔔';
const priorityEmoji = PRIORITY_EMOJI[notification.priority] || '';
const lines = [`${emoji} <b>${escapeHtml(notification.title)}</b>`];
@@ -415,6 +424,9 @@ async function forwardNotification(notification) {
if (notification.priority) lines.push(`Priority: ${priorityEmoji} ${notification.priority}`);
await sendMessage(lines.join('\n'), opts);
+ // Count the forward against the messages domain's daily budget (#711).
+ await recordDomainUsage('messages', { actions: 1 })
+ .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 38bea7f66f..f4d709d5fb 100644
--- a/server/services/telegramBridge.js
+++ b/server/services/telegramBridge.js
@@ -14,6 +14,7 @@ import { homedir } from 'os';
import { tryReadFile } from '../lib/fileUtils.js';
import { notificationEvents, NOTIFICATION_TYPES } from './notifications.js';
import { getDomainAutonomyMode } from './cosState.js';
+import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';
const CHANNELS_DIR = join(homedir(), '.claude', 'channels', 'telegram');
const ENV_FILE = join(CHANNELS_DIR, '.env');
@@ -240,6 +241,14 @@ async function forwardNotification(notification) {
return;
}
+ // Daily messages budget (#711, mirrors telegram.js): once today's auto-send
+ // count reaches the cap, suppress further forwarding for the rest of the day.
+ const budget = await getDomainBudgetStatus('messages');
+ if (!budget.withinBudget) {
+ console.log(`📨 Messages auto-send daily ${budget.exceeded} budget reached — suppressing forward: ${notification.type} — "${notification.title}"`);
+ return;
+ }
+
const emoji = NOTIFICATION_EMOJI[notification.type] || '🔔';
const priorityEmoji = PRIORITY_EMOJI[notification.priority] || '';
const lines = [`${emoji} <b>${escapeHtml(notification.title)}</b>`];
@@ -247,6 +256,9 @@ async function forwardNotification(notification) {
if (notification.priority) lines.push(`Priority: ${priorityEmoji} ${notification.priority}`);
await sendMessage(lines.join('\n'));
+ // Count the forward against the messages domain's daily budget (#711).
+ await recordDomainUsage('messages', { actions: 1 })
+ .catch(err => console.error(`❌ Failed to record messages budget usage: ${err.message}`));
}
/**
diff --git a/server/services/telegramBridge.test.js b/server/services/telegramBridge.test.js
index d845d42911..7d794290d1 100644
--- a/server/services/telegramBridge.test.js
+++ b/server/services/telegramBridge.test.js
@@ -29,6 +29,20 @@ vi.mock('./cosState.js', () => ({
getDomainAutonomyMode: vi.fn(async () => mockMessagesMode)
}));
+// The bridge also reads the messages daily budget; keep it always-within-budget
+// here (the budget math itself is covered by domainBudgets/domainUsage tests) so
+// these gate tests stay focused on the autonomy mode.
+let mockMessagesWithinBudget = true;
+vi.mock('./domainUsage.js', () => ({
+ getDomainBudgetStatus: vi.fn(async () => ({
+ withinBudget: mockMessagesWithinBudget,
+ exceeded: mockMessagesWithinBudget ? null : 'actions',
+ budget: { maxActionsPerDay: null, maxMinutesPerDay: null },
+ usage: { actions: 0, ms: 0 }
+ })),
+ recordDomainUsage: vi.fn().mockResolvedValue(undefined)
+}));
+
// We import the real notifications module so the bridge can subscribe to the
// event emitter — that's the spot where forwardNotification is exercised
// without poking at any private internal.
@@ -99,6 +113,7 @@ describe('telegramBridge service', () => {
await cleanup();
updateCachedForwardTypes(null);
mockMessagesMode = 'execute';
+ mockMessagesWithinBudget = true;
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllGlobals();
@@ -321,5 +336,26 @@ describe('telegramBridge service', () => {
await cleanup();
}
});
+
+ it('suppresses forwarding when the messages daily budget is exhausted (#711)', async () => {
+ mockMessagesWithinBudget = false; // over budget while mode stays execute
+ seedCredentials();
+ const fetchSpy = mockTelegramFetch();
+ vi.stubGlobal('fetch', fetchSpy);
+ await init();
+ fetchSpy.mockClear();
+
+ notificationEvents.emit('added', {
+ type: NOTIFICATION_TYPES.HEALTH_ISSUE,
+ title: 'Over budget',
+ priority: PRIORITY_LEVELS.HIGH
+ });
+ await flush();
+
+ expect(
+ fetchSpy.mock.calls.filter(([url]) => url.endsWith('/sendMessage')),
+ 'an exhausted messages budget must not forward to Telegram'
+ ).toHaveLength(0);
+ });
});
});