nyk commited on
Commit
1474302
·
unverified ·
2 Parent(s): e5ffe2df3f9fd2

Merge pull request #178 from bhavikprit/feat/160-workload-signals

Browse files
README.md CHANGED
@@ -449,6 +449,32 @@ pnpm test:e2e # Playwright E2E
449
  pnpm quality:gate # All checks
450
  ```
451
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
452
  ## Agent Diagnostics Contract
453
 
454
  `GET /api/agents/{id}/diagnostics` is self-scoped by default.
 
449
  pnpm quality:gate # All checks
450
  ```
451
 
452
+ ## Workload Signals Contract
453
+
454
+ `GET /api/workload` returns a workload snapshot and one recommendation:
455
+
456
+ - `normal`: system healthy, submit freely
457
+ - `throttle`: reduce submission rate / defer non-critical work
458
+ - `shed`: submit only critical work
459
+ - `pause`: hold submissions until capacity returns
460
+
461
+ Low-signal behavior:
462
+
463
+ - `capacity.error_rate_5m` is clamped to `[0,1]`
464
+ - `queue.estimated_wait_confidence` is `calculated` or `unknown`
465
+ - queue breakdown maps include stable keys even when counts are zero
466
+
467
+ Runtime-tunable thresholds:
468
+
469
+ - `MC_WORKLOAD_QUEUE_DEPTH_NORMAL`
470
+ - `MC_WORKLOAD_QUEUE_DEPTH_THROTTLE`
471
+ - `MC_WORKLOAD_QUEUE_DEPTH_SHED`
472
+ - `MC_WORKLOAD_BUSY_RATIO_THROTTLE`
473
+ - `MC_WORKLOAD_BUSY_RATIO_SHED`
474
+ - `MC_WORKLOAD_ERROR_RATE_THROTTLE`
475
+ - `MC_WORKLOAD_ERROR_RATE_SHED`
476
+ - `MC_WORKLOAD_RECENT_WINDOW_SECONDS`
477
+
478
  ## Agent Diagnostics Contract
479
 
480
  `GET /api/agents/{id}/diagnostics` is self-scoped by default.
openapi.json CHANGED
@@ -2834,6 +2834,93 @@
2834
  }
2835
  }
2836
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2837
  "/api/events": {
2838
  "get": {
2839
  "tags": [
 
2834
  }
2835
  }
2836
  },
2837
+ "/api/workload": {
2838
+ "get": {
2839
+ "tags": [
2840
+ "Monitoring"
2841
+ ],
2842
+ "summary": "Get real-time workload recommendation",
2843
+ "description": "Returns system workload metrics and an actionable recommendation: `normal`, `throttle`, `shed`, or `pause`. Thresholds are runtime-configurable via `MC_WORKLOAD_*` environment variables.",
2844
+ "operationId": "getWorkloadSignals",
2845
+ "responses": {
2846
+ "200": {
2847
+ "description": "Workload snapshot and recommendation",
2848
+ "content": {
2849
+ "application/json": {
2850
+ "schema": {
2851
+ "type": "object",
2852
+ "properties": {
2853
+ "timestamp": { "type": "integer" },
2854
+ "workspace_id": { "type": "integer" },
2855
+ "capacity": {
2856
+ "type": "object",
2857
+ "properties": {
2858
+ "active_tasks": { "type": "integer" },
2859
+ "tasks_last_5m": { "type": "integer" },
2860
+ "errors_last_5m": { "type": "integer" },
2861
+ "error_rate_5m": { "type": "number", "minimum": 0, "maximum": 1 },
2862
+ "completions_last_hour": { "type": "integer" },
2863
+ "avg_completion_rate_per_hour": { "type": "number" }
2864
+ }
2865
+ },
2866
+ "queue": {
2867
+ "type": "object",
2868
+ "properties": {
2869
+ "total_pending": { "type": "integer" },
2870
+ "by_status": { "type": "object", "additionalProperties": { "type": "integer" } },
2871
+ "by_priority": { "type": "object", "additionalProperties": { "type": "integer" } },
2872
+ "oldest_pending_age_seconds": { "type": ["integer", "null"] },
2873
+ "estimated_wait_seconds": { "type": ["integer", "null"] },
2874
+ "estimated_wait_confidence": { "type": "string", "enum": ["calculated", "unknown"] }
2875
+ }
2876
+ },
2877
+ "agents": {
2878
+ "type": "object",
2879
+ "properties": {
2880
+ "total": { "type": "integer" },
2881
+ "online": { "type": "integer" },
2882
+ "busy": { "type": "integer" },
2883
+ "idle": { "type": "integer" },
2884
+ "offline": { "type": "integer" },
2885
+ "busy_ratio": { "type": "number", "minimum": 0, "maximum": 1 },
2886
+ "load_distribution": {
2887
+ "type": "array",
2888
+ "items": {
2889
+ "type": "object",
2890
+ "properties": {
2891
+ "agent": { "type": "string" },
2892
+ "assigned": { "type": "integer" },
2893
+ "in_progress": { "type": "integer" }
2894
+ }
2895
+ }
2896
+ }
2897
+ }
2898
+ },
2899
+ "recommendation": {
2900
+ "type": "object",
2901
+ "properties": {
2902
+ "action": { "type": "string", "enum": ["normal", "throttle", "shed", "pause"] },
2903
+ "reason": { "type": "string" },
2904
+ "details": { "type": "array", "items": { "type": "string" } },
2905
+ "submit_ok": { "type": "boolean" },
2906
+ "suggested_delay_ms": { "type": "integer" }
2907
+ }
2908
+ },
2909
+ "thresholds": {
2910
+ "type": "object",
2911
+ "description": "Effective runtime thresholds after environment overrides."
2912
+ }
2913
+ }
2914
+ }
2915
+ }
2916
+ }
2917
+ },
2918
+ "401": {
2919
+ "$ref": "#/components/responses/Unauthorized"
2920
+ }
2921
+ }
2922
+ }
2923
+ },
2924
  "/api/events": {
2925
  "get": {
2926
  "tags": [
playwright.config.ts CHANGED
@@ -27,6 +27,10 @@ export default defineConfig({
27
  HOSTNAME: process.env.HOSTNAME || '127.0.0.1',
28
  PORT: process.env.PORT || '3005',
29
  MC_DISABLE_RATE_LIMIT: process.env.MC_DISABLE_RATE_LIMIT || '1',
 
 
 
 
30
  API_KEY: process.env.API_KEY || 'test-api-key-e2e-12345',
31
  AUTH_USER: process.env.AUTH_USER || 'testadmin',
32
  AUTH_PASS: process.env.AUTH_PASS || 'testpass1234!',
 
27
  HOSTNAME: process.env.HOSTNAME || '127.0.0.1',
28
  PORT: process.env.PORT || '3005',
29
  MC_DISABLE_RATE_LIMIT: process.env.MC_DISABLE_RATE_LIMIT || '1',
30
+ MC_WORKLOAD_QUEUE_DEPTH_THROTTLE: process.env.MC_WORKLOAD_QUEUE_DEPTH_THROTTLE || '1000',
31
+ MC_WORKLOAD_QUEUE_DEPTH_SHED: process.env.MC_WORKLOAD_QUEUE_DEPTH_SHED || '2000',
32
+ MC_WORKLOAD_ERROR_RATE_THROTTLE: process.env.MC_WORKLOAD_ERROR_RATE_THROTTLE || '1',
33
+ MC_WORKLOAD_ERROR_RATE_SHED: process.env.MC_WORKLOAD_ERROR_RATE_SHED || '1',
34
  API_KEY: process.env.API_KEY || 'test-api-key-e2e-12345',
35
  AUTH_USER: process.env.AUTH_USER || 'testadmin',
36
  AUTH_PASS: process.env.AUTH_PASS || 'testpass1234!',
src/app/api/workload/route.ts ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ import { getDatabase } from '@/lib/db';
3
+ import { requireRole } from '@/lib/auth';
4
+ import { logger } from '@/lib/logger';
5
+
6
+ /**
7
+ * GET /api/workload - Real-Time Workload Signals
8
+ *
9
+ * Provides system-wide capacity metrics and throttle recommendations
10
+ * so agents can make informed decisions about work submission.
11
+ *
12
+ * Response:
13
+ * capacity - Current system capacity metrics
14
+ * queue - Task queue depth and breakdown
15
+ * agents - Agent availability and load distribution
16
+ * recommendation - Actionable signal: normal | throttle | shed | pause
17
+ * thresholds - Current threshold configuration
18
+ *
19
+ * Agents should call this before submitting new work to avoid
20
+ * cascading failures and SLO breaches.
21
+ */
22
+ export async function GET(request: NextRequest) {
23
+ const auth = requireRole(request, 'viewer');
24
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
25
+
26
+ try {
27
+ const db = getDatabase();
28
+ const workspaceId = auth.user.workspace_id ?? 1;
29
+ const now = Math.floor(Date.now() / 1000);
30
+
31
+ // --- Capacity metrics ---
32
+ const capacity = buildCapacityMetrics(db, workspaceId, now);
33
+
34
+ // --- Queue depth ---
35
+ const queue = buildQueueMetrics(db, workspaceId);
36
+
37
+ // --- Agent availability ---
38
+ const agents = buildAgentMetrics(db, workspaceId, now);
39
+
40
+ // --- Recommendation ---
41
+ const recommendation = computeRecommendation(capacity, queue, agents);
42
+
43
+ return NextResponse.json({
44
+ timestamp: now,
45
+ workspace_id: workspaceId,
46
+ capacity,
47
+ queue,
48
+ agents,
49
+ recommendation,
50
+ thresholds: THRESHOLDS,
51
+ });
52
+ } catch (error) {
53
+ logger.error({ err: error }, 'GET /api/workload error');
54
+ return NextResponse.json({ error: 'Failed to fetch workload signals' }, { status: 500 });
55
+ }
56
+ }
57
+
58
+ // Configurable thresholds for recommendation engine
59
+ function numEnv(name: string, fallback: number): number {
60
+ const raw = process.env[name];
61
+ if (!raw || raw.trim().length === 0) return fallback;
62
+ const parsed = Number(raw);
63
+ return Number.isFinite(parsed) ? parsed : fallback;
64
+ }
65
+
66
+ function buildThresholds() {
67
+ return {
68
+ queue_depth_normal: numEnv('MC_WORKLOAD_QUEUE_DEPTH_NORMAL', 20),
69
+ queue_depth_throttle: numEnv('MC_WORKLOAD_QUEUE_DEPTH_THROTTLE', 50),
70
+ queue_depth_shed: numEnv('MC_WORKLOAD_QUEUE_DEPTH_SHED', 100),
71
+ busy_agent_ratio_throttle: numEnv('MC_WORKLOAD_BUSY_RATIO_THROTTLE', 0.8),
72
+ busy_agent_ratio_shed: numEnv('MC_WORKLOAD_BUSY_RATIO_SHED', 0.95),
73
+ error_rate_throttle: numEnv('MC_WORKLOAD_ERROR_RATE_THROTTLE', 0.1),
74
+ error_rate_shed: numEnv('MC_WORKLOAD_ERROR_RATE_SHED', 0.25),
75
+ recent_window_seconds: Math.max(1, Math.floor(numEnv('MC_WORKLOAD_RECENT_WINDOW_SECONDS', 300))),
76
+ };
77
+ }
78
+
79
+ const THRESHOLDS = buildThresholds();
80
+
81
+ interface CapacityMetrics {
82
+ active_tasks: number;
83
+ tasks_last_5m: number;
84
+ errors_last_5m: number;
85
+ error_rate_5m: number;
86
+ completions_last_hour: number;
87
+ avg_completion_rate_per_hour: number;
88
+ }
89
+
90
+ interface QueueMetrics {
91
+ total_pending: number;
92
+ by_status: Record<string, number>;
93
+ by_priority: Record<string, number>;
94
+ oldest_pending_age_seconds: number | null;
95
+ estimated_wait_seconds: number | null;
96
+ estimated_wait_confidence: 'calculated' | 'unknown';
97
+ }
98
+
99
+ interface AgentMetrics {
100
+ total: number;
101
+ online: number;
102
+ busy: number;
103
+ idle: number;
104
+ offline: number;
105
+ busy_ratio: number;
106
+ load_distribution: Array<{ agent: string; assigned: number; in_progress: number }>;
107
+ }
108
+
109
+ function buildCapacityMetrics(db: any, workspaceId: number, now: number): CapacityMetrics {
110
+ const recentWindow = now - THRESHOLDS.recent_window_seconds;
111
+ const hourAgo = now - 3600;
112
+
113
+ const activeTasks = (db.prepare(
114
+ `SELECT COUNT(*) as c FROM tasks WHERE workspace_id = ? AND status IN ('assigned', 'in_progress', 'review', 'quality_review')`
115
+ ).get(workspaceId) as any).c;
116
+
117
+ const tasksLast5m = (db.prepare(
118
+ `SELECT COUNT(*) as c FROM activities WHERE workspace_id = ? AND created_at >= ? AND type IN ('task_created', 'task_assigned')`
119
+ ).get(workspaceId, recentWindow) as any).c;
120
+
121
+ const errorsLast5m = (db.prepare(
122
+ `SELECT COUNT(*) as c FROM activities WHERE workspace_id = ? AND created_at >= ? AND (type LIKE '%error%' OR type LIKE '%fail%')`
123
+ ).get(workspaceId, recentWindow) as any).c;
124
+
125
+ const totalLast5m = (db.prepare(
126
+ `SELECT COUNT(*) as c FROM activities WHERE workspace_id = ? AND created_at >= ?`
127
+ ).get(workspaceId, recentWindow) as any).c;
128
+
129
+ const completionsLastHour = (db.prepare(
130
+ `SELECT COUNT(*) as c FROM tasks WHERE workspace_id = ? AND status = 'done' AND updated_at >= ?`
131
+ ).get(workspaceId, hourAgo) as any).c;
132
+
133
+ // Average completion rate over last 24h
134
+ const dayAgo = now - 86400;
135
+ const completionsLastDay = (db.prepare(
136
+ `SELECT COUNT(*) as c FROM tasks WHERE workspace_id = ? AND status = 'done' AND updated_at >= ?`
137
+ ).get(workspaceId, dayAgo) as any).c;
138
+
139
+ const safeErrorRate = totalLast5m > 0 ? errorsLast5m / totalLast5m : 0;
140
+
141
+ return {
142
+ active_tasks: activeTasks,
143
+ tasks_last_5m: tasksLast5m,
144
+ errors_last_5m: errorsLast5m,
145
+ error_rate_5m: Math.max(0, Math.min(1, Math.round(safeErrorRate * 10000) / 10000)),
146
+ completions_last_hour: completionsLastHour,
147
+ avg_completion_rate_per_hour: Math.round((completionsLastDay / 24) * 100) / 100,
148
+ };
149
+ }
150
+
151
+ function buildQueueMetrics(db: any, workspaceId: number): QueueMetrics {
152
+ const now = Math.floor(Date.now() / 1000);
153
+
154
+ const pendingStatuses = ['inbox', 'assigned', 'in_progress', 'review', 'quality_review'];
155
+
156
+ const byStatus = db.prepare(
157
+ `SELECT status, COUNT(*) as count FROM tasks WHERE workspace_id = ? AND status IN (${pendingStatuses.map(() => '?').join(',')}) GROUP BY status`
158
+ ).all(workspaceId, ...pendingStatuses) as Array<{ status: string; count: number }>;
159
+
160
+ const byPriority = db.prepare(
161
+ `SELECT priority, COUNT(*) as count FROM tasks WHERE workspace_id = ? AND status IN (${pendingStatuses.map(() => '?').join(',')}) GROUP BY priority`
162
+ ).all(workspaceId, ...pendingStatuses) as Array<{ priority: string; count: number }>;
163
+
164
+ const totalPending = byStatus.reduce((sum, r) => sum + r.count, 0);
165
+
166
+ const oldest = db.prepare(
167
+ `SELECT MIN(created_at) as oldest FROM tasks WHERE workspace_id = ? AND status IN ('inbox', 'assigned')`
168
+ ).get(workspaceId) as any;
169
+
170
+ const oldestAge = oldest?.oldest ? now - oldest.oldest : null;
171
+
172
+ // Estimate wait: pending tasks / completion rate per hour * 3600
173
+ const hourAgo = now - 3600;
174
+ const completionsLastHour = (db.prepare(
175
+ `SELECT COUNT(*) as c FROM tasks WHERE workspace_id = ? AND status = 'done' AND updated_at >= ?`
176
+ ).get(workspaceId, hourAgo) as any).c;
177
+
178
+ const estimatedWait = completionsLastHour > 0
179
+ ? Math.round((totalPending / completionsLastHour) * 3600)
180
+ : null;
181
+
182
+ const statusMap = Object.fromEntries(byStatus.map(r => [r.status, r.count]));
183
+ for (const status of pendingStatuses) {
184
+ if (typeof statusMap[status] !== 'number') statusMap[status] = 0;
185
+ }
186
+
187
+ const priorityMap = Object.fromEntries(byPriority.map(r => [r.priority, r.count]));
188
+ for (const priority of ['low', 'medium', 'high', 'critical', 'urgent']) {
189
+ if (typeof priorityMap[priority] !== 'number') priorityMap[priority] = 0;
190
+ }
191
+
192
+ return {
193
+ total_pending: totalPending,
194
+ by_status: statusMap,
195
+ by_priority: priorityMap,
196
+ oldest_pending_age_seconds: oldestAge,
197
+ estimated_wait_seconds: estimatedWait,
198
+ estimated_wait_confidence: estimatedWait === null ? 'unknown' : 'calculated',
199
+ };
200
+ }
201
+
202
+ function buildAgentMetrics(db: any, workspaceId: number, now: number): AgentMetrics {
203
+ const agentStatuses = db.prepare(
204
+ `SELECT status, COUNT(*) as count FROM agents WHERE workspace_id = ? GROUP BY status`
205
+ ).all(workspaceId) as Array<{ status: string; count: number }>;
206
+
207
+ const statusMap: Record<string, number> = {};
208
+ let total = 0;
209
+ for (const row of agentStatuses) {
210
+ statusMap[row.status] = row.count;
211
+ total += row.count;
212
+ }
213
+
214
+ const online = (statusMap['idle'] || 0) + (statusMap['busy'] || 0);
215
+ const busy = statusMap['busy'] || 0;
216
+ const idle = statusMap['idle'] || 0;
217
+ const offline = statusMap['offline'] || 0;
218
+
219
+ // Load distribution per agent
220
+ const loadDist = db.prepare(`
221
+ SELECT a.name as agent,
222
+ SUM(CASE WHEN t.status = 'assigned' THEN 1 ELSE 0 END) as assigned,
223
+ SUM(CASE WHEN t.status = 'in_progress' THEN 1 ELSE 0 END) as in_progress
224
+ FROM agents a
225
+ LEFT JOIN tasks t ON t.assigned_to = a.name AND t.workspace_id = a.workspace_id AND t.status IN ('assigned', 'in_progress')
226
+ WHERE a.workspace_id = ? AND a.status != 'offline'
227
+ GROUP BY a.name
228
+ ORDER BY (assigned + in_progress) DESC
229
+ `).all(workspaceId) as Array<{ agent: string; assigned: number; in_progress: number }>;
230
+
231
+ return {
232
+ total,
233
+ online,
234
+ busy,
235
+ idle,
236
+ offline,
237
+ busy_ratio: online > 0 ? Math.round((busy / online) * 100) / 100 : 0,
238
+ load_distribution: loadDist,
239
+ };
240
+ }
241
+
242
+ type RecommendationLevel = 'normal' | 'throttle' | 'shed' | 'pause';
243
+
244
+ interface Recommendation {
245
+ action: RecommendationLevel;
246
+ reason: string;
247
+ details: string[];
248
+ submit_ok: boolean;
249
+ suggested_delay_ms: number;
250
+ }
251
+
252
+ function computeRecommendation(
253
+ capacity: CapacityMetrics,
254
+ queue: QueueMetrics,
255
+ agents: AgentMetrics
256
+ ): Recommendation {
257
+ const reasons: string[] = [];
258
+ let level: RecommendationLevel = 'normal';
259
+
260
+ // Check error rate
261
+ if (capacity.error_rate_5m >= THRESHOLDS.error_rate_shed) {
262
+ level = escalate(level, 'shed');
263
+ reasons.push(`High error rate: ${(capacity.error_rate_5m * 100).toFixed(1)}%`);
264
+ } else if (capacity.error_rate_5m >= THRESHOLDS.error_rate_throttle) {
265
+ level = escalate(level, 'throttle');
266
+ reasons.push(`Elevated error rate: ${(capacity.error_rate_5m * 100).toFixed(1)}%`);
267
+ }
268
+
269
+ // Check queue depth
270
+ if (queue.total_pending >= THRESHOLDS.queue_depth_shed) {
271
+ level = escalate(level, 'shed');
272
+ reasons.push(`Queue depth critical: ${queue.total_pending} pending tasks`);
273
+ } else if (queue.total_pending >= THRESHOLDS.queue_depth_throttle) {
274
+ level = escalate(level, 'throttle');
275
+ reasons.push(`Queue depth high: ${queue.total_pending} pending tasks`);
276
+ }
277
+
278
+ // Check agent saturation
279
+ if (agents.busy_ratio >= THRESHOLDS.busy_agent_ratio_shed) {
280
+ level = escalate(level, 'shed');
281
+ reasons.push(`Agent saturation critical: ${(agents.busy_ratio * 100).toFixed(0)}% busy`);
282
+ } else if (agents.busy_ratio >= THRESHOLDS.busy_agent_ratio_throttle) {
283
+ level = escalate(level, 'throttle');
284
+ reasons.push(`Agent saturation high: ${(agents.busy_ratio * 100).toFixed(0)}% busy`);
285
+ }
286
+
287
+ // No online agents = pause
288
+ if (agents.online === 0) {
289
+ level = 'pause';
290
+ reasons.push(agents.total > 0 ? 'No agents online' : 'No agents registered');
291
+ }
292
+
293
+ const delayMap: Record<RecommendationLevel, number> = {
294
+ normal: 0,
295
+ throttle: 2000,
296
+ shed: 10000,
297
+ pause: 30000,
298
+ };
299
+
300
+ const actionDescriptions: Record<RecommendationLevel, string> = {
301
+ normal: 'System healthy — submit work freely',
302
+ throttle: 'System under load — reduce submission rate and defer non-critical work',
303
+ shed: 'System overloaded — submit only critical/high-priority work, defer everything else',
304
+ pause: 'System unavailable — hold all submissions until capacity returns',
305
+ };
306
+
307
+ return {
308
+ action: level,
309
+ reason: actionDescriptions[level],
310
+ details: reasons.length > 0 ? reasons : ['All metrics within normal bounds'],
311
+ submit_ok: level === 'normal' || level === 'throttle',
312
+ suggested_delay_ms: delayMap[level],
313
+ };
314
+ }
315
+
316
+ function escalate(current: RecommendationLevel, proposed: RecommendationLevel): RecommendationLevel {
317
+ const order: RecommendationLevel[] = ['normal', 'throttle', 'shed', 'pause'];
318
+ return order.indexOf(proposed) > order.indexOf(current) ? proposed : current;
319
+ }
tests/workload-signals.spec.ts ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { test, expect } from '@playwright/test'
2
+ import { API_KEY_HEADER, createTestAgent, deleteTestAgent, createTestTask, deleteTestTask } from './helpers'
3
+
4
+ test.describe('Workload Signals API', () => {
5
+ const agentCleanup: number[] = []
6
+ const taskCleanup: number[] = []
7
+
8
+ test.afterEach(async ({ request }) => {
9
+ for (const id of taskCleanup) {
10
+ await deleteTestTask(request, id).catch(() => {})
11
+ }
12
+ taskCleanup.length = 0
13
+
14
+ for (const id of agentCleanup) {
15
+ await deleteTestAgent(request, id).catch(() => {})
16
+ }
17
+ agentCleanup.length = 0
18
+ })
19
+
20
+ test('returns normal recommendation under light load', async ({ request }) => {
21
+ const { id } = await createTestAgent(request, { status: 'idle' })
22
+ agentCleanup.push(id)
23
+
24
+ const res = await request.get('/api/workload', { headers: API_KEY_HEADER })
25
+ expect(res.status()).toBe(200)
26
+ const body = await res.json()
27
+
28
+ expect(body.recommendation.action).toBe('normal')
29
+ expect(body.recommendation.submit_ok).toBe(true)
30
+ })
31
+
32
+ test('returns throttle recommendation at high busy ratio', async ({ request }) => {
33
+ const idleAgent = await createTestAgent(request, { status: 'idle' })
34
+ agentCleanup.push(idleAgent.id)
35
+ for (let i = 0; i < 4; i++) {
36
+ const busyAgent = await createTestAgent(request, { status: 'busy' })
37
+ agentCleanup.push(busyAgent.id)
38
+ }
39
+
40
+ const res = await request.get('/api/workload', { headers: API_KEY_HEADER })
41
+ expect(res.status()).toBe(200)
42
+ const body = await res.json()
43
+
44
+ expect(body.recommendation.action).toBe('throttle')
45
+ expect(body.recommendation.submit_ok).toBe(true)
46
+ })
47
+
48
+ test('returns shed recommendation at critical busy ratio', async ({ request }) => {
49
+ const idleAgent = await createTestAgent(request, { status: 'idle' })
50
+ agentCleanup.push(idleAgent.id)
51
+ for (let i = 0; i < 19; i++) {
52
+ const busyAgent = await createTestAgent(request, { status: 'busy' })
53
+ agentCleanup.push(busyAgent.id)
54
+ }
55
+
56
+ const res = await request.get('/api/workload', { headers: API_KEY_HEADER })
57
+ expect(res.status()).toBe(200)
58
+ const body = await res.json()
59
+
60
+ expect(body.recommendation.action).toBe('shed')
61
+ expect(body.recommendation.submit_ok).toBe(false)
62
+ })
63
+
64
+ test('returns pause recommendation when no agents are online', async ({ request }) => {
65
+ const res = await request.get('/api/workload', { headers: API_KEY_HEADER })
66
+ expect(res.status()).toBe(200)
67
+ const body = await res.json()
68
+
69
+ expect(body.agents.online).toBe(0)
70
+ expect(body.recommendation.action).toBe('pause')
71
+ expect(body.recommendation.submit_ok).toBe(false)
72
+ })
73
+
74
+ test('returns consistent response for low-signal conditions', async ({ request }) => {
75
+ const { id } = await createTestAgent(request, { status: 'idle' })
76
+ agentCleanup.push(id)
77
+
78
+ const task = await createTestTask(request, { status: 'inbox' })
79
+ taskCleanup.push(task.id)
80
+
81
+ const res = await request.get('/api/workload', { headers: API_KEY_HEADER })
82
+ expect(res.status()).toBe(200)
83
+ const body = await res.json()
84
+
85
+ expect(body.capacity.error_rate_5m).toBeGreaterThanOrEqual(0)
86
+ expect(body.capacity.error_rate_5m).toBeLessThanOrEqual(1)
87
+ expect(body.queue.by_status).toHaveProperty('inbox')
88
+ expect(body.queue.by_status).toHaveProperty('assigned')
89
+ expect(body.queue.by_status).toHaveProperty('in_progress')
90
+ expect(body.queue.by_priority).toHaveProperty('critical')
91
+ expect(body.queue.by_priority).toHaveProperty('high')
92
+ expect(body.queue.by_priority).toHaveProperty('medium')
93
+ expect(body.queue.by_priority).toHaveProperty('low')
94
+ expect(['calculated', 'unknown']).toContain(body.queue.estimated_wait_confidence)
95
+ })
96
+ })