Spaces:
Runtime error
Runtime error
Merge pull request #177 from bhavikprit/feat/163-agent-diagnostics
Browse files- README.md +18 -0
- openapi.json +120 -0
- src/app/api/agents/[id]/diagnostics/route.ts +343 -0
- tests/agent-diagnostics.spec.ts +76 -0
README.md
CHANGED
|
@@ -440,6 +440,24 @@ pnpm test:e2e # Playwright E2E
|
|
| 440 |
pnpm quality:gate # All checks
|
| 441 |
```
|
| 442 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 443 |
## Roadmap
|
| 444 |
|
| 445 |
See [open issues](https://github.com/builderz-labs/mission-control/issues) for planned work and the [v1.0.0 release notes](https://github.com/builderz-labs/mission-control/releases/tag/v1.0.0) for what shipped.
|
|
|
|
| 440 |
pnpm quality:gate # All checks
|
| 441 |
```
|
| 442 |
|
| 443 |
+
## Agent Diagnostics Contract
|
| 444 |
+
|
| 445 |
+
`GET /api/agents/{id}/diagnostics` is self-scoped by default.
|
| 446 |
+
|
| 447 |
+
- Self access:
|
| 448 |
+
- Session user where `username === agent.name`, or
|
| 449 |
+
- API-key request with `x-agent-name` matching `{id}` agent name
|
| 450 |
+
- Cross-agent access:
|
| 451 |
+
- Allowed only with explicit `?privileged=1` and admin auth
|
| 452 |
+
- Query validation:
|
| 453 |
+
- `hours` must be an integer between `1` and `720`
|
| 454 |
+
- `section` must be a comma-separated subset of `summary,tasks,errors,activity,trends,tokens`
|
| 455 |
+
|
| 456 |
+
Trend alerts in the `trends.alerts` response are derived from current-vs-previous window comparisons:
|
| 457 |
+
|
| 458 |
+
- `warning`: error spikes or severe activity drop
|
| 459 |
+
- `info`: throughput drops or potential stall patterns
|
| 460 |
+
|
| 461 |
## Roadmap
|
| 462 |
|
| 463 |
See [open issues](https://github.com/builderz-labs/mission-control/issues) for planned work and the [v1.0.0 release notes](https://github.com/builderz-labs/mission-control/releases/tag/v1.0.0) for what shipped.
|
openapi.json
CHANGED
|
@@ -3726,6 +3726,126 @@
|
|
| 3726 |
}
|
| 3727 |
}
|
| 3728 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3729 |
"/api/notifications/deliver": {
|
| 3730 |
"post": {
|
| 3731 |
"tags": [
|
|
|
|
| 3726 |
}
|
| 3727 |
}
|
| 3728 |
},
|
| 3729 |
+
"/api/agents/{id}/diagnostics": {
|
| 3730 |
+
"get": {
|
| 3731 |
+
"tags": [
|
| 3732 |
+
"Agents"
|
| 3733 |
+
],
|
| 3734 |
+
"summary": "Get self diagnostics for an agent",
|
| 3735 |
+
"description": "Self-scoped diagnostics by default. Cross-agent access requires `privileged=1` with admin credentials. Trend alerts are informational signals derived from current-vs-previous window deltas (error spikes, throughput drops, activity stalls).",
|
| 3736 |
+
"operationId": "getAgentDiagnostics",
|
| 3737 |
+
"parameters": [
|
| 3738 |
+
{
|
| 3739 |
+
"name": "id",
|
| 3740 |
+
"in": "path",
|
| 3741 |
+
"required": true,
|
| 3742 |
+
"schema": {
|
| 3743 |
+
"type": "string"
|
| 3744 |
+
},
|
| 3745 |
+
"description": "Agent numeric ID or name."
|
| 3746 |
+
},
|
| 3747 |
+
{
|
| 3748 |
+
"name": "hours",
|
| 3749 |
+
"in": "query",
|
| 3750 |
+
"required": false,
|
| 3751 |
+
"schema": {
|
| 3752 |
+
"type": "integer",
|
| 3753 |
+
"minimum": 1,
|
| 3754 |
+
"maximum": 720,
|
| 3755 |
+
"default": 24
|
| 3756 |
+
},
|
| 3757 |
+
"description": "Diagnostics window in hours."
|
| 3758 |
+
},
|
| 3759 |
+
{
|
| 3760 |
+
"name": "section",
|
| 3761 |
+
"in": "query",
|
| 3762 |
+
"required": false,
|
| 3763 |
+
"schema": {
|
| 3764 |
+
"type": "string"
|
| 3765 |
+
},
|
| 3766 |
+
"description": "Comma-separated sections: summary,tasks,errors,activity,trends,tokens."
|
| 3767 |
+
},
|
| 3768 |
+
{
|
| 3769 |
+
"name": "privileged",
|
| 3770 |
+
"in": "query",
|
| 3771 |
+
"required": false,
|
| 3772 |
+
"schema": {
|
| 3773 |
+
"type": "string",
|
| 3774 |
+
"enum": [
|
| 3775 |
+
"1"
|
| 3776 |
+
]
|
| 3777 |
+
},
|
| 3778 |
+
"description": "Set to `1` to allow explicit admin cross-agent diagnostics access."
|
| 3779 |
+
}
|
| 3780 |
+
],
|
| 3781 |
+
"responses": {
|
| 3782 |
+
"200": {
|
| 3783 |
+
"description": "Diagnostics payload",
|
| 3784 |
+
"content": {
|
| 3785 |
+
"application/json": {
|
| 3786 |
+
"schema": {
|
| 3787 |
+
"type": "object",
|
| 3788 |
+
"properties": {
|
| 3789 |
+
"agent": {
|
| 3790 |
+
"type": "object",
|
| 3791 |
+
"properties": {
|
| 3792 |
+
"id": { "type": "integer" },
|
| 3793 |
+
"name": { "type": "string" },
|
| 3794 |
+
"role": { "type": "string" },
|
| 3795 |
+
"status": { "type": "string" }
|
| 3796 |
+
}
|
| 3797 |
+
},
|
| 3798 |
+
"timeframe": {
|
| 3799 |
+
"type": "object",
|
| 3800 |
+
"properties": {
|
| 3801 |
+
"hours": { "type": "integer" },
|
| 3802 |
+
"since": { "type": "integer" },
|
| 3803 |
+
"until": { "type": "integer" }
|
| 3804 |
+
}
|
| 3805 |
+
},
|
| 3806 |
+
"summary": { "type": "object" },
|
| 3807 |
+
"tasks": { "type": "object" },
|
| 3808 |
+
"errors": { "type": "object" },
|
| 3809 |
+
"activity": { "type": "object" },
|
| 3810 |
+
"trends": {
|
| 3811 |
+
"type": "object",
|
| 3812 |
+
"properties": {
|
| 3813 |
+
"current_period": { "type": "object" },
|
| 3814 |
+
"previous_period": { "type": "object" },
|
| 3815 |
+
"change": { "type": "object" },
|
| 3816 |
+
"alerts": {
|
| 3817 |
+
"type": "array",
|
| 3818 |
+
"items": {
|
| 3819 |
+
"type": "object",
|
| 3820 |
+
"properties": {
|
| 3821 |
+
"level": { "type": "string", "enum": ["info", "warning"] },
|
| 3822 |
+
"message": { "type": "string" }
|
| 3823 |
+
}
|
| 3824 |
+
}
|
| 3825 |
+
}
|
| 3826 |
+
}
|
| 3827 |
+
},
|
| 3828 |
+
"tokens": { "type": "object" }
|
| 3829 |
+
}
|
| 3830 |
+
}
|
| 3831 |
+
}
|
| 3832 |
+
}
|
| 3833 |
+
},
|
| 3834 |
+
"400": {
|
| 3835 |
+
"$ref": "#/components/responses/BadRequest"
|
| 3836 |
+
},
|
| 3837 |
+
"401": {
|
| 3838 |
+
"$ref": "#/components/responses/Unauthorized"
|
| 3839 |
+
},
|
| 3840 |
+
"403": {
|
| 3841 |
+
"$ref": "#/components/responses/Forbidden"
|
| 3842 |
+
},
|
| 3843 |
+
"404": {
|
| 3844 |
+
"$ref": "#/components/responses/NotFound"
|
| 3845 |
+
}
|
| 3846 |
+
}
|
| 3847 |
+
}
|
| 3848 |
+
},
|
| 3849 |
"/api/notifications/deliver": {
|
| 3850 |
"post": {
|
| 3851 |
"tags": [
|
src/app/api/agents/[id]/diagnostics/route.ts
ADDED
|
@@ -0,0 +1,343 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
const ALLOWED_SECTIONS = ['summary', 'tasks', 'errors', 'activity', 'trends', 'tokens'] as const;
|
| 7 |
+
type DiagnosticsSection = (typeof ALLOWED_SECTIONS)[number];
|
| 8 |
+
|
| 9 |
+
function parseHoursParam(raw: string | null): { value?: number; error?: string } {
|
| 10 |
+
if (raw === null) return { value: 24 };
|
| 11 |
+
const parsed = Number(raw);
|
| 12 |
+
if (!Number.isInteger(parsed)) {
|
| 13 |
+
return { error: 'hours must be an integer between 1 and 720' };
|
| 14 |
+
}
|
| 15 |
+
if (parsed < 1 || parsed > 720) {
|
| 16 |
+
return { error: 'hours must be between 1 and 720' };
|
| 17 |
+
}
|
| 18 |
+
return { value: parsed };
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
function parseSectionsParam(raw: string | null): { value?: Set<DiagnosticsSection>; error?: string } {
|
| 22 |
+
if (!raw || raw.trim().length === 0) {
|
| 23 |
+
return { value: new Set(ALLOWED_SECTIONS) };
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
const requested = raw
|
| 27 |
+
.split(',')
|
| 28 |
+
.map((section) => section.trim())
|
| 29 |
+
.filter(Boolean);
|
| 30 |
+
|
| 31 |
+
if (requested.length === 0) {
|
| 32 |
+
return { error: 'section must include at least one valid value' };
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
const invalid = requested.filter((section) => !ALLOWED_SECTIONS.includes(section as DiagnosticsSection));
|
| 36 |
+
if (invalid.length > 0) {
|
| 37 |
+
return { error: `Invalid section value(s): ${invalid.join(', ')}` };
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
return { value: new Set(requested as DiagnosticsSection[]) };
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
/**
|
| 44 |
+
* GET /api/agents/[id]/diagnostics - Agent Self-Diagnostics API
|
| 45 |
+
*
|
| 46 |
+
* Provides an agent with its own performance metrics, error analysis,
|
| 47 |
+
* and trend data so it can self-optimize.
|
| 48 |
+
*
|
| 49 |
+
* Query params:
|
| 50 |
+
* hours - Time window in hours (default: 24, max: 720 = 30 days)
|
| 51 |
+
* section - Comma-separated sections to include (default: all)
|
| 52 |
+
* Options: summary, tasks, errors, activity, trends, tokens
|
| 53 |
+
*
|
| 54 |
+
* Response includes:
|
| 55 |
+
* summary - High-level KPIs (throughput, error rate, activity count)
|
| 56 |
+
* tasks - Task completion breakdown by status and priority
|
| 57 |
+
* errors - Error frequency, types, and recent error details
|
| 58 |
+
* activity - Activity breakdown by type with hourly timeline
|
| 59 |
+
* trends - Multi-period comparison for trend detection
|
| 60 |
+
* tokens - Token usage by model with cost estimates
|
| 61 |
+
*/
|
| 62 |
+
export async function GET(
|
| 63 |
+
request: NextRequest,
|
| 64 |
+
{ params }: { params: Promise<{ id: string }> }
|
| 65 |
+
) {
|
| 66 |
+
const auth = requireRole(request, 'viewer');
|
| 67 |
+
if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
|
| 68 |
+
|
| 69 |
+
try {
|
| 70 |
+
const db = getDatabase();
|
| 71 |
+
const resolvedParams = await params;
|
| 72 |
+
const agentId = resolvedParams.id;
|
| 73 |
+
const workspaceId = auth.user.workspace_id ?? 1;
|
| 74 |
+
|
| 75 |
+
// Resolve agent by ID or name
|
| 76 |
+
let agent: any;
|
| 77 |
+
if (/^\d+$/.test(agentId)) {
|
| 78 |
+
agent = db.prepare('SELECT id, name, role, status, last_seen, created_at FROM agents WHERE id = ? AND workspace_id = ?').get(Number(agentId), workspaceId);
|
| 79 |
+
} else {
|
| 80 |
+
agent = db.prepare('SELECT id, name, role, status, last_seen, created_at FROM agents WHERE name = ? AND workspace_id = ?').get(agentId, workspaceId);
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
if (!agent) {
|
| 84 |
+
return NextResponse.json({ error: 'Agent not found' }, { status: 404 });
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
const { searchParams } = new URL(request.url);
|
| 88 |
+
const requesterAgentName = (request.headers.get('x-agent-name') || '').trim();
|
| 89 |
+
const privileged = searchParams.get('privileged') === '1';
|
| 90 |
+
const isSelfRequest = (requesterAgentName || auth.user.username) === agent.name;
|
| 91 |
+
|
| 92 |
+
// Self-only by default. Cross-agent access requires explicit privileged override.
|
| 93 |
+
if (!isSelfRequest && !(privileged && auth.user.role === 'admin')) {
|
| 94 |
+
return NextResponse.json(
|
| 95 |
+
{ error: 'Diagnostics are self-scoped. Use privileged=1 with admin role for cross-agent access.' },
|
| 96 |
+
{ status: 403 }
|
| 97 |
+
);
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
const parsedHours = parseHoursParam(searchParams.get('hours'));
|
| 101 |
+
if (parsedHours.error) {
|
| 102 |
+
return NextResponse.json({ error: parsedHours.error }, { status: 400 });
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
const parsedSections = parseSectionsParam(searchParams.get('section'));
|
| 106 |
+
if (parsedSections.error) {
|
| 107 |
+
return NextResponse.json({ error: parsedSections.error }, { status: 400 });
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
const hours = parsedHours.value as number;
|
| 111 |
+
const sections = parsedSections.value as Set<DiagnosticsSection>;
|
| 112 |
+
|
| 113 |
+
const now = Math.floor(Date.now() / 1000);
|
| 114 |
+
const since = now - hours * 3600;
|
| 115 |
+
|
| 116 |
+
const result: Record<string, any> = {
|
| 117 |
+
agent: { id: agent.id, name: agent.name, role: agent.role, status: agent.status },
|
| 118 |
+
timeframe: { hours, since, until: now },
|
| 119 |
+
};
|
| 120 |
+
|
| 121 |
+
if (sections.has('summary')) {
|
| 122 |
+
result.summary = buildSummary(db, agent.name, workspaceId, since);
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
if (sections.has('tasks')) {
|
| 126 |
+
result.tasks = buildTaskMetrics(db, agent.name, workspaceId, since);
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
if (sections.has('errors')) {
|
| 130 |
+
result.errors = buildErrorAnalysis(db, agent.name, workspaceId, since);
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
if (sections.has('activity')) {
|
| 134 |
+
result.activity = buildActivityBreakdown(db, agent.name, workspaceId, since);
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
if (sections.has('trends')) {
|
| 138 |
+
result.trends = buildTrends(db, agent.name, workspaceId, hours);
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
if (sections.has('tokens')) {
|
| 142 |
+
result.tokens = buildTokenMetrics(db, agent.name, workspaceId, since);
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
return NextResponse.json(result);
|
| 146 |
+
} catch (error) {
|
| 147 |
+
logger.error({ err: error }, 'GET /api/agents/[id]/diagnostics error');
|
| 148 |
+
return NextResponse.json({ error: 'Failed to fetch diagnostics' }, { status: 500 });
|
| 149 |
+
}
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
/** High-level KPIs */
|
| 153 |
+
function buildSummary(db: any, agentName: string, workspaceId: number, since: number) {
|
| 154 |
+
const tasksDone = (db.prepare(
|
| 155 |
+
`SELECT COUNT(*) as c FROM tasks WHERE assigned_to = ? AND workspace_id = ? AND status = 'done' AND updated_at >= ?`
|
| 156 |
+
).get(agentName, workspaceId, since) as any).c;
|
| 157 |
+
|
| 158 |
+
const tasksTotal = (db.prepare(
|
| 159 |
+
`SELECT COUNT(*) as c FROM tasks WHERE assigned_to = ? AND workspace_id = ?`
|
| 160 |
+
).get(agentName, workspaceId) as any).c;
|
| 161 |
+
|
| 162 |
+
const activityCount = (db.prepare(
|
| 163 |
+
`SELECT COUNT(*) as c FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ?`
|
| 164 |
+
).get(agentName, workspaceId, since) as any).c;
|
| 165 |
+
|
| 166 |
+
const errorCount = (db.prepare(
|
| 167 |
+
`SELECT COUNT(*) as c FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? AND type LIKE '%error%'`
|
| 168 |
+
).get(agentName, workspaceId, since) as any).c;
|
| 169 |
+
|
| 170 |
+
const errorRate = activityCount > 0 ? Math.round((errorCount / activityCount) * 10000) / 100 : 0;
|
| 171 |
+
|
| 172 |
+
return {
|
| 173 |
+
tasks_completed: tasksDone,
|
| 174 |
+
tasks_total: tasksTotal,
|
| 175 |
+
activity_count: activityCount,
|
| 176 |
+
error_count: errorCount,
|
| 177 |
+
error_rate_percent: errorRate,
|
| 178 |
+
};
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
/** Task completion breakdown */
|
| 182 |
+
function buildTaskMetrics(db: any, agentName: string, workspaceId: number, since: number) {
|
| 183 |
+
const byStatus = db.prepare(
|
| 184 |
+
`SELECT status, COUNT(*) as count FROM tasks WHERE assigned_to = ? AND workspace_id = ? GROUP BY status`
|
| 185 |
+
).all(agentName, workspaceId) as Array<{ status: string; count: number }>;
|
| 186 |
+
|
| 187 |
+
const byPriority = db.prepare(
|
| 188 |
+
`SELECT priority, COUNT(*) as count FROM tasks WHERE assigned_to = ? AND workspace_id = ? GROUP BY priority`
|
| 189 |
+
).all(agentName, workspaceId) as Array<{ priority: string; count: number }>;
|
| 190 |
+
|
| 191 |
+
const recentCompleted = db.prepare(
|
| 192 |
+
`SELECT id, title, priority, updated_at FROM tasks WHERE assigned_to = ? AND workspace_id = ? AND status = 'done' AND updated_at >= ? ORDER BY updated_at DESC LIMIT 10`
|
| 193 |
+
).all(agentName, workspaceId, since) as any[];
|
| 194 |
+
|
| 195 |
+
// Estimate throughput: tasks completed per day in the window
|
| 196 |
+
const windowDays = Math.max((Math.floor(Date.now() / 1000) - since) / 86400, 1);
|
| 197 |
+
const completedInWindow = recentCompleted.length;
|
| 198 |
+
const throughputPerDay = Math.round((completedInWindow / windowDays) * 100) / 100;
|
| 199 |
+
|
| 200 |
+
return {
|
| 201 |
+
by_status: Object.fromEntries(byStatus.map(r => [r.status, r.count])),
|
| 202 |
+
by_priority: Object.fromEntries(byPriority.map(r => [r.priority, r.count])),
|
| 203 |
+
recent_completed: recentCompleted,
|
| 204 |
+
throughput_per_day: throughputPerDay,
|
| 205 |
+
};
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
/** Error frequency and analysis */
|
| 209 |
+
function buildErrorAnalysis(db: any, agentName: string, workspaceId: number, since: number) {
|
| 210 |
+
const errorActivities = db.prepare(
|
| 211 |
+
`SELECT type, COUNT(*) as count FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? AND (type LIKE '%error%' OR type LIKE '%fail%') GROUP BY type ORDER BY count DESC`
|
| 212 |
+
).all(agentName, workspaceId, since) as Array<{ type: string; count: number }>;
|
| 213 |
+
|
| 214 |
+
const recentErrors = db.prepare(
|
| 215 |
+
`SELECT id, type, description, data, created_at FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? AND (type LIKE '%error%' OR type LIKE '%fail%') ORDER BY created_at DESC LIMIT 20`
|
| 216 |
+
).all(agentName, workspaceId, since) as any[];
|
| 217 |
+
|
| 218 |
+
return {
|
| 219 |
+
by_type: errorActivities,
|
| 220 |
+
total: errorActivities.reduce((sum, e) => sum + e.count, 0),
|
| 221 |
+
recent: recentErrors.map(e => ({
|
| 222 |
+
...e,
|
| 223 |
+
data: e.data ? JSON.parse(e.data) : null,
|
| 224 |
+
})),
|
| 225 |
+
};
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
/** Activity breakdown with hourly timeline */
|
| 229 |
+
function buildActivityBreakdown(db: any, agentName: string, workspaceId: number, since: number) {
|
| 230 |
+
const byType = db.prepare(
|
| 231 |
+
`SELECT type, COUNT(*) as count FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? GROUP BY type ORDER BY count DESC`
|
| 232 |
+
).all(agentName, workspaceId, since) as Array<{ type: string; count: number }>;
|
| 233 |
+
|
| 234 |
+
const timeline = db.prepare(
|
| 235 |
+
`SELECT (created_at / 3600) * 3600 as hour_bucket, COUNT(*) as count FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? GROUP BY hour_bucket ORDER BY hour_bucket ASC`
|
| 236 |
+
).all(agentName, workspaceId, since) as Array<{ hour_bucket: number; count: number }>;
|
| 237 |
+
|
| 238 |
+
return {
|
| 239 |
+
by_type: byType,
|
| 240 |
+
timeline: timeline.map(t => ({
|
| 241 |
+
timestamp: t.hour_bucket,
|
| 242 |
+
hour: new Date(t.hour_bucket * 1000).toISOString(),
|
| 243 |
+
count: t.count,
|
| 244 |
+
})),
|
| 245 |
+
};
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
/** Multi-period trend comparison for anomaly/trend detection */
|
| 249 |
+
function buildTrends(db: any, agentName: string, workspaceId: number, hours: number) {
|
| 250 |
+
const now = Math.floor(Date.now() / 1000);
|
| 251 |
+
|
| 252 |
+
// Compare current period vs previous period of same length
|
| 253 |
+
const currentSince = now - hours * 3600;
|
| 254 |
+
const previousSince = currentSince - hours * 3600;
|
| 255 |
+
|
| 256 |
+
const periodMetrics = (since: number, until: number) => {
|
| 257 |
+
const activities = (db.prepare(
|
| 258 |
+
`SELECT COUNT(*) as c FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? AND created_at < ?`
|
| 259 |
+
).get(agentName, workspaceId, since, until) as any).c;
|
| 260 |
+
|
| 261 |
+
const errors = (db.prepare(
|
| 262 |
+
`SELECT COUNT(*) as c FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? AND created_at < ? AND (type LIKE '%error%' OR type LIKE '%fail%')`
|
| 263 |
+
).get(agentName, workspaceId, since, until) as any).c;
|
| 264 |
+
|
| 265 |
+
const tasksCompleted = (db.prepare(
|
| 266 |
+
`SELECT COUNT(*) as c FROM tasks WHERE assigned_to = ? AND workspace_id = ? AND status = 'done' AND updated_at >= ? AND updated_at < ?`
|
| 267 |
+
).get(agentName, workspaceId, since, until) as any).c;
|
| 268 |
+
|
| 269 |
+
return { activities, errors, tasks_completed: tasksCompleted };
|
| 270 |
+
};
|
| 271 |
+
|
| 272 |
+
const current = periodMetrics(currentSince, now);
|
| 273 |
+
const previous = periodMetrics(previousSince, currentSince);
|
| 274 |
+
|
| 275 |
+
const pctChange = (cur: number, prev: number) => {
|
| 276 |
+
if (prev === 0) return cur > 0 ? 100 : 0;
|
| 277 |
+
return Math.round(((cur - prev) / prev) * 10000) / 100;
|
| 278 |
+
};
|
| 279 |
+
|
| 280 |
+
return {
|
| 281 |
+
current_period: { since: currentSince, until: now, ...current },
|
| 282 |
+
previous_period: { since: previousSince, until: currentSince, ...previous },
|
| 283 |
+
change: {
|
| 284 |
+
activities_pct: pctChange(current.activities, previous.activities),
|
| 285 |
+
errors_pct: pctChange(current.errors, previous.errors),
|
| 286 |
+
tasks_completed_pct: pctChange(current.tasks_completed, previous.tasks_completed),
|
| 287 |
+
},
|
| 288 |
+
alerts: buildTrendAlerts(current, previous),
|
| 289 |
+
};
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
/** Generate automatic alerts from trend data */
|
| 293 |
+
function buildTrendAlerts(current: { activities: number; errors: number; tasks_completed: number }, previous: { activities: number; errors: number; tasks_completed: number }) {
|
| 294 |
+
const alerts: Array<{ level: string; message: string }> = [];
|
| 295 |
+
|
| 296 |
+
// Error rate spike
|
| 297 |
+
if (current.errors > 0 && previous.errors > 0) {
|
| 298 |
+
const errorIncrease = (current.errors - previous.errors) / previous.errors;
|
| 299 |
+
if (errorIncrease > 0.5) {
|
| 300 |
+
alerts.push({ level: 'warning', message: `Error count increased ${Math.round(errorIncrease * 100)}% vs previous period` });
|
| 301 |
+
}
|
| 302 |
+
} else if (current.errors > 3 && previous.errors === 0) {
|
| 303 |
+
alerts.push({ level: 'warning', message: `New error pattern: ${current.errors} errors (none in previous period)` });
|
| 304 |
+
}
|
| 305 |
+
|
| 306 |
+
// Throughput drop
|
| 307 |
+
if (previous.tasks_completed > 0 && current.tasks_completed === 0) {
|
| 308 |
+
alerts.push({ level: 'info', message: 'No tasks completed in current period (possible stall)' });
|
| 309 |
+
} else if (previous.tasks_completed > 2 && current.tasks_completed < previous.tasks_completed * 0.5) {
|
| 310 |
+
alerts.push({ level: 'info', message: `Task throughput dropped ${Math.round((1 - current.tasks_completed / previous.tasks_completed) * 100)}%` });
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
// Activity drop (possible offline)
|
| 314 |
+
if (previous.activities > 5 && current.activities < previous.activities * 0.25) {
|
| 315 |
+
alerts.push({ level: 'warning', message: `Activity dropped ${Math.round((1 - current.activities / previous.activities) * 100)}% — agent may be stalled` });
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
return alerts;
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
/** Token usage by model */
|
| 322 |
+
function buildTokenMetrics(db: any, agentName: string, workspaceId: number, since: number) {
|
| 323 |
+
try {
|
| 324 |
+
// session_id on token_usage may store agent name or session key
|
| 325 |
+
const byModel = db.prepare(
|
| 326 |
+
`SELECT model, SUM(input_tokens) as input_tokens, SUM(output_tokens) as output_tokens, COUNT(*) as request_count FROM token_usage WHERE session_id = ? AND workspace_id = ? AND created_at >= ? GROUP BY model ORDER BY (input_tokens + output_tokens) DESC`
|
| 327 |
+
).all(agentName, workspaceId, since) as Array<{ model: string; input_tokens: number; output_tokens: number; request_count: number }>;
|
| 328 |
+
|
| 329 |
+
const total = byModel.reduce((acc, r) => ({
|
| 330 |
+
input_tokens: acc.input_tokens + r.input_tokens,
|
| 331 |
+
output_tokens: acc.output_tokens + r.output_tokens,
|
| 332 |
+
requests: acc.requests + r.request_count,
|
| 333 |
+
}), { input_tokens: 0, output_tokens: 0, requests: 0 });
|
| 334 |
+
|
| 335 |
+
return {
|
| 336 |
+
by_model: byModel,
|
| 337 |
+
total,
|
| 338 |
+
};
|
| 339 |
+
} catch {
|
| 340 |
+
// token_usage table may not exist
|
| 341 |
+
return { by_model: [], total: { input_tokens: 0, output_tokens: 0, requests: 0 } };
|
| 342 |
+
}
|
| 343 |
+
}
|
tests/agent-diagnostics.spec.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { test, expect } from '@playwright/test'
|
| 2 |
+
import { API_KEY_HEADER, createTestAgent, deleteTestAgent } from './helpers'
|
| 3 |
+
|
| 4 |
+
test.describe('Agent Diagnostics API', () => {
|
| 5 |
+
const cleanup: number[] = []
|
| 6 |
+
|
| 7 |
+
test.afterEach(async ({ request }) => {
|
| 8 |
+
for (const id of cleanup) {
|
| 9 |
+
await deleteTestAgent(request, id).catch(() => {})
|
| 10 |
+
}
|
| 11 |
+
cleanup.length = 0
|
| 12 |
+
})
|
| 13 |
+
|
| 14 |
+
test('self access is allowed with x-agent-name', async ({ request }) => {
|
| 15 |
+
const { id, name } = await createTestAgent(request)
|
| 16 |
+
cleanup.push(id)
|
| 17 |
+
|
| 18 |
+
const res = await request.get(`/api/agents/${name}/diagnostics?section=summary`, {
|
| 19 |
+
headers: { ...API_KEY_HEADER, 'x-agent-name': name },
|
| 20 |
+
})
|
| 21 |
+
|
| 22 |
+
expect(res.status()).toBe(200)
|
| 23 |
+
const body = await res.json()
|
| 24 |
+
expect(body.agent.name).toBe(name)
|
| 25 |
+
expect(body.summary).toBeDefined()
|
| 26 |
+
})
|
| 27 |
+
|
| 28 |
+
test('cross-agent access is denied by default', async ({ request }) => {
|
| 29 |
+
const a = await createTestAgent(request)
|
| 30 |
+
const b = await createTestAgent(request)
|
| 31 |
+
cleanup.push(a.id, b.id)
|
| 32 |
+
|
| 33 |
+
const res = await request.get(`/api/agents/${a.name}/diagnostics?section=summary`, {
|
| 34 |
+
headers: { ...API_KEY_HEADER, 'x-agent-name': b.name },
|
| 35 |
+
})
|
| 36 |
+
|
| 37 |
+
expect(res.status()).toBe(403)
|
| 38 |
+
})
|
| 39 |
+
|
| 40 |
+
test('cross-agent access is allowed with privileged=1 for admin', async ({ request }) => {
|
| 41 |
+
const a = await createTestAgent(request)
|
| 42 |
+
const b = await createTestAgent(request)
|
| 43 |
+
cleanup.push(a.id, b.id)
|
| 44 |
+
|
| 45 |
+
const res = await request.get(`/api/agents/${a.name}/diagnostics?section=summary&privileged=1`, {
|
| 46 |
+
headers: { ...API_KEY_HEADER, 'x-agent-name': b.name },
|
| 47 |
+
})
|
| 48 |
+
|
| 49 |
+
expect(res.status()).toBe(200)
|
| 50 |
+
const body = await res.json()
|
| 51 |
+
expect(body.agent.name).toBe(a.name)
|
| 52 |
+
expect(body.summary).toBeDefined()
|
| 53 |
+
})
|
| 54 |
+
|
| 55 |
+
test('invalid section query is rejected', async ({ request }) => {
|
| 56 |
+
const { id, name } = await createTestAgent(request)
|
| 57 |
+
cleanup.push(id)
|
| 58 |
+
|
| 59 |
+
const res = await request.get(`/api/agents/${name}/diagnostics?section=summary,invalid`, {
|
| 60 |
+
headers: { ...API_KEY_HEADER, 'x-agent-name': name },
|
| 61 |
+
})
|
| 62 |
+
|
| 63 |
+
expect(res.status()).toBe(400)
|
| 64 |
+
})
|
| 65 |
+
|
| 66 |
+
test('invalid hours query is rejected', async ({ request }) => {
|
| 67 |
+
const { id, name } = await createTestAgent(request)
|
| 68 |
+
cleanup.push(id)
|
| 69 |
+
|
| 70 |
+
const res = await request.get(`/api/agents/${name}/diagnostics?hours=0`, {
|
| 71 |
+
headers: { ...API_KEY_HEADER, 'x-agent-name': name },
|
| 72 |
+
})
|
| 73 |
+
|
| 74 |
+
expect(res.status()).toBe(400)
|
| 75 |
+
})
|
| 76 |
+
})
|