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

fix: record CoS action usage before agent:completed so the daily budget gate can't overshoot by one

[._.]/ Adam Eivy5ab25f6faf73
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 74b16a8035..1758e6ffc0 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,9 @@
# Unreleased
+## Chief of Staff
+
+- **[issue-1683] CoS daily action-budget can no longer overshoot by one at the boundary.** `completeAgent()` emitted `agent:completed` — whose handler schedules `dequeueNextTask()` and its daily action-budget gate — *before* recording the just-finished action via `recordDomainUsage('cos', …)`. At the exact `maxActionsPerDay` boundary the dequeue read stale usage that didn't yet include the completing action (which was already `status: 'completed'`, so it wasn't counted as in-flight either), admitting one autonomous spawn past the cap. The usage ledger is now written before the `agent:completed` emit so the gate always counts the completing action. (`server/services/cosAgents.js`)
+
## Editorial checks
- **[issue-1697] Health-panel deep-links now honor the triage's session-local check mute.** Muting a check from the Editorial Findings triage (#1602) hid its findings group but the health panel kept advertising that check/category row as clickable — clicking it scrolled to an empty filtered view. The session mute state (`hiddenCheckIds`) was lifted from `EditorialFindingsTriage` up to `PipelineEditorialChecks`, which now subtracts muted checks from the filterable sets the health panel receives; a category stays clickable only while a non-muted check still contributes an open finding to it. (`client/src/pages/PipelineEditorialChecks.jsx`, `client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx`)
diff --git a/server/services/cosAgents.js b/server/services/cosAgents.js
index f93afd92cd..b720a8a330 100644
--- a/server/services/cosAgents.js
+++ b/server/services/cosAgents.js
@@ -292,7 +292,10 @@ export async function completeAgent(agentId, result = {}) {
}
await saveState(state);
- cosEvents.emit('agent:completed', state.agents[agentId]);
+ // `agent:completed` is intentionally emitted later, after the domain-usage
+ // ledger is updated (see the recordDomainUsage block below, #1683). Do NOT
+ // move it back here. `agent:updated` carries no scheduling side effect, so it
+ // stays inside the lock.
cosEvents.emit('agent:updated', state.agents[agentId]);
// Determine date bucket from completedAt
@@ -335,11 +338,23 @@ export async function completeAgent(agentId, result = {}) {
// 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.
+ //
+ // This MUST land before the `agent:completed` emit below: that event's handler
+ // schedules `dequeueNextTask()`, whose daily action-budget gate reads this
+ // ledger. Recording first ensures the gate counts the just-finished action, so
+ // a perpetual drain can't admit one spawn past `maxActionsPerDay` at the
+ // boundary (#1683).
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}`));
}
+ // Emit now that the ledger reflects this action (#1683). Fires for every
+ // completed agent, matching prior behavior — only the timing moved.
+ if (completed) {
+ cosEvents.emit('agent:completed', completed);
+ }
+
return completed;
}
diff --git a/server/services/cosAgents.test.js b/server/services/cosAgents.test.js
index 93782b0760..f594cf5869 100644
--- a/server/services/cosAgents.test.js
+++ b/server/services/cosAgents.test.js
@@ -19,8 +19,14 @@ vi.mock('./cosState.js', () => ({
withStateLock: async (fn) => fn()
}));
-import { getAgent, createAgentOutputBatcher } from './cosAgents.js';
+vi.mock('./domainUsage.js', () => ({
+ recordDomainUsage: vi.fn(async () => {})
+}));
+
+import { getAgent, createAgentOutputBatcher, completeAgent } from './cosAgents.js';
import { saveState } from './cosState.js';
+import { recordDomainUsage } from './domainUsage.js';
+import { cosEvents } from './cosEvents.js';
describe('cosAgents', () => {
beforeEach(async () => {
@@ -56,6 +62,57 @@ describe('cosAgents', () => {
});
});
+describe('completeAgent budget-ledger ordering (#1683)', () => {
+ beforeEach(async () => {
+ await rm(mockCosState.agentsDir, { recursive: true, force: true });
+ await mkdir(mockCosState.agentsDir, { recursive: true });
+ mockCosState.state = { agents: {}, stats: { tasksCompleted: 0, errors: 0 } };
+ recordDomainUsage.mockClear();
+ });
+
+ afterEach(async () => {
+ await rm(mockCosState.agentsDir, { recursive: true, force: true });
+ cosEvents.removeAllListeners('agent:completed');
+ });
+
+ it('records the autonomous action usage BEFORE emitting agent:completed', async () => {
+ // The agent:completed handler schedules dequeueNextTask(), whose daily
+ // action-budget gate reads the usage ledger. If the emit beats the ledger
+ // write, the gate counts stale usage and can admit one spawn past the cap.
+ const order = [];
+ recordDomainUsage.mockImplementation(async () => { order.push('usage'); });
+ cosEvents.on('agent:completed', () => { order.push('completed'); });
+
+ const agentId = 'agent-autonomous';
+ mockCosState.state.agents[agentId] = {
+ id: agentId,
+ status: 'running',
+ metadata: { taskType: 'scheduled' }
+ };
+
+ await completeAgent(agentId, { success: true, duration: 1200 });
+
+ expect(recordDomainUsage).toHaveBeenCalledWith('cos', { actions: 1, ms: 1200 });
+ expect(order).toEqual(['usage', 'completed']);
+ });
+
+ it('skips usage accounting for user tasks but still emits agent:completed', async () => {
+ const agentId = 'agent-user';
+ mockCosState.state.agents[agentId] = {
+ id: agentId,
+ status: 'running',
+ metadata: { taskType: 'user' }
+ };
+ let emitted = false;
+ cosEvents.on('agent:completed', () => { emitted = true; });
+
+ await completeAgent(agentId, { success: true });
+
+ expect(recordDomainUsage).not.toHaveBeenCalled();
+ expect(emitted).toBe(true);
+ });
+});
+
describe('createAgentOutputBatcher', () => {
const agentId = 'agent-batch';