nyk commited on
Commit
e5ffe2d
·
unverified ·
2 Parent(s): fd791da7f29d16

Merge pull request #180 from bhavikprit/feat/159-agent-identity

Browse files
README.md CHANGED
@@ -210,6 +210,7 @@ All endpoints require authentication unless noted. Full reference below.
210
  | `GET` | `/api/agents` | viewer | List agents with task stats |
211
  | `POST` | `/api/agents` | operator | Register/update agent |
212
  | `GET` | `/api/agents/[id]` | viewer | Agent details |
 
213
  | `POST` | `/api/agents/sync` | operator | Sync agents from openclaw.json |
214
  | `GET/PUT` | `/api/agents/[id]/soul` | operator | Agent SOUL content (reads from workspace, writes to both) |
215
  | `GET/POST` | `/api/agents/comms` | operator | Agent inter-agent communication |
@@ -225,6 +226,14 @@ All endpoints require authentication unless noted. Full reference below.
225
 
226
  </details>
227
 
 
 
 
 
 
 
 
 
228
  <details>
229
  <summary><strong>Monitoring</strong></summary>
230
 
 
210
  | `GET` | `/api/agents` | viewer | List agents with task stats |
211
  | `POST` | `/api/agents` | operator | Register/update agent |
212
  | `GET` | `/api/agents/[id]` | viewer | Agent details |
213
+ | `GET` | `/api/agents/[id]/attribution` | viewer | Self-scope attribution/audit/cost report (`?privileged=1` admin override) |
214
  | `POST` | `/api/agents/sync` | operator | Sync agents from openclaw.json |
215
  | `GET/PUT` | `/api/agents/[id]/soul` | operator | Agent SOUL content (reads from workspace, writes to both) |
216
  | `GET/POST` | `/api/agents/comms` | operator | Agent inter-agent communication |
 
226
 
227
  </details>
228
 
229
+ ### Attribution Contract (`/api/agents/[id]/attribution`)
230
+
231
+ - Self-scope by default: requester identity must match target agent via `x-agent-name` (or matching authenticated username).
232
+ - Admin override requires explicit `?privileged=1`.
233
+ - Query params:
234
+ - `hours`: integer window `1..720` (default `24`)
235
+ - `section`: comma-separated subset of `identity,audit,mutations,cost` (default all)
236
+
237
  <details>
238
  <summary><strong>Monitoring</strong></summary>
239
 
openapi.json CHANGED
@@ -2917,6 +2917,86 @@
2917
  }
2918
  }
2919
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2920
  "/api/gateway-config": {
2921
  "get": {
2922
  "tags": [
 
2917
  }
2918
  }
2919
  },
2920
+ "/api/agents/{id}/attribution": {
2921
+ "get": {
2922
+ "tags": [
2923
+ "Agents"
2924
+ ],
2925
+ "summary": "Get attribution report for an agent",
2926
+ "description": "Self-scope by default. Requester must match target agent (`x-agent-name` or username), unless admin uses `?privileged=1`.",
2927
+ "operationId": "getAgentAttribution",
2928
+ "parameters": [
2929
+ {
2930
+ "name": "id",
2931
+ "in": "path",
2932
+ "required": true,
2933
+ "schema": {
2934
+ "type": "string"
2935
+ }
2936
+ },
2937
+ {
2938
+ "name": "hours",
2939
+ "in": "query",
2940
+ "required": false,
2941
+ "description": "Time window in hours, integer range 1..720. Defaults to 24.",
2942
+ "schema": {
2943
+ "type": "integer",
2944
+ "minimum": 1,
2945
+ "maximum": 720,
2946
+ "default": 24
2947
+ }
2948
+ },
2949
+ {
2950
+ "name": "section",
2951
+ "in": "query",
2952
+ "required": false,
2953
+ "description": "Comma-separated subset of identity,audit,mutations,cost. Defaults to all.",
2954
+ "schema": {
2955
+ "type": "string",
2956
+ "example": "identity,audit"
2957
+ }
2958
+ },
2959
+ {
2960
+ "name": "privileged",
2961
+ "in": "query",
2962
+ "required": false,
2963
+ "description": "Set to 1 for admin override of self-scope checks.",
2964
+ "schema": {
2965
+ "type": "string",
2966
+ "enum": [
2967
+ "1"
2968
+ ]
2969
+ }
2970
+ },
2971
+ {
2972
+ "name": "x-agent-name",
2973
+ "in": "header",
2974
+ "required": false,
2975
+ "description": "Attribution identity header used for self-scope authorization.",
2976
+ "schema": {
2977
+ "type": "string"
2978
+ }
2979
+ }
2980
+ ],
2981
+ "responses": {
2982
+ "200": {
2983
+ "description": "Attribution report"
2984
+ },
2985
+ "400": {
2986
+ "$ref": "#/components/responses/BadRequest"
2987
+ },
2988
+ "401": {
2989
+ "$ref": "#/components/responses/Unauthorized"
2990
+ },
2991
+ "403": {
2992
+ "$ref": "#/components/responses/Forbidden"
2993
+ },
2994
+ "404": {
2995
+ "$ref": "#/components/responses/NotFound"
2996
+ }
2997
+ }
2998
+ }
2999
+ },
3000
  "/api/gateway-config": {
3001
  "get": {
3002
  "tags": [
src/app/api/agents/[id]/attribution/route.ts ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = new Set(['identity', 'audit', 'mutations', 'cost']);
7
+
8
+ /**
9
+ * GET /api/agents/[id]/attribution - Agent-Level Identity & Attribution
10
+ *
11
+ * Returns a comprehensive audit trail and cost attribution report for
12
+ * a specific agent. Enables per-agent observability, debugging, and
13
+ * cost analysis in multi-agent environments.
14
+ *
15
+ * Query params:
16
+ * hours - Time window (default: 24, max: 720)
17
+ * section - Comma-separated: audit,cost,mutations,identity (default: all)
18
+ *
19
+ * Response:
20
+ * identity - Agent profile, status, and session info
21
+ * audit - Full audit trail of agent actions
22
+ * mutations - Task/memory/soul changes attributed to this agent
23
+ * cost - Token usage and cost breakdown per model
24
+ */
25
+ export async function GET(
26
+ request: NextRequest,
27
+ { params }: { params: Promise<{ id: string }> }
28
+ ) {
29
+ const auth = requireRole(request, 'viewer');
30
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
31
+
32
+ try {
33
+ const db = getDatabase();
34
+ const resolvedParams = await params;
35
+ const agentId = resolvedParams.id;
36
+ const workspaceId = auth.user.workspace_id ?? 1;
37
+
38
+ // Resolve agent
39
+ let agent: any;
40
+ if (/^\d+$/.test(agentId)) {
41
+ agent = db.prepare('SELECT * FROM agents WHERE id = ? AND workspace_id = ?').get(Number(agentId), workspaceId);
42
+ } else {
43
+ agent = db.prepare('SELECT * FROM agents WHERE name = ? AND workspace_id = ?').get(agentId, workspaceId);
44
+ }
45
+
46
+ if (!agent) {
47
+ return NextResponse.json({ error: 'Agent not found' }, { status: 404 });
48
+ }
49
+
50
+ const { searchParams } = new URL(request.url);
51
+ const privileged = searchParams.get('privileged') === '1';
52
+ const isSelfByHeader = auth.user.agent_name === agent.name;
53
+ const isSelfByUsername = auth.user.username === agent.name;
54
+ const isSelf = isSelfByHeader || isSelfByUsername;
55
+ const isPrivileged = auth.user.role === 'admin' && privileged;
56
+ if (!isSelf && !isPrivileged) {
57
+ return NextResponse.json(
58
+ { error: 'Forbidden: attribution is self-scope by default. Admin can use ?privileged=1 override.' },
59
+ { status: 403 }
60
+ );
61
+ }
62
+
63
+ const hoursRaw = searchParams.get('hours');
64
+ const hours = parseHours(hoursRaw);
65
+ if (!hours) {
66
+ return NextResponse.json({ error: 'Invalid hours. Expected integer 1..720.' }, { status: 400 });
67
+ }
68
+
69
+ const sections = parseSections(searchParams.get('section'));
70
+ if ('error' in sections) {
71
+ return NextResponse.json({ error: sections.error }, { status: 400 });
72
+ }
73
+
74
+ const now = Math.floor(Date.now() / 1000);
75
+ const since = now - hours * 3600;
76
+
77
+ const result: Record<string, any> = {
78
+ agent_name: agent.name,
79
+ timeframe: { hours, since, until: now },
80
+ access_scope: isSelf ? 'self' : 'privileged',
81
+ };
82
+
83
+ if (sections.sections.has('identity')) {
84
+ result.identity = buildIdentity(db, agent, workspaceId);
85
+ }
86
+
87
+ if (sections.sections.has('audit')) {
88
+ result.audit = buildAuditTrail(db, agent.name, workspaceId, since);
89
+ }
90
+
91
+ if (sections.sections.has('mutations')) {
92
+ result.mutations = buildMutations(db, agent.name, workspaceId, since);
93
+ }
94
+
95
+ if (sections.sections.has('cost')) {
96
+ result.cost = buildCostAttribution(db, agent.name, workspaceId, since);
97
+ }
98
+
99
+ return NextResponse.json(result);
100
+ } catch (error) {
101
+ logger.error({ err: error }, 'GET /api/agents/[id]/attribution error');
102
+ return NextResponse.json({ error: 'Failed to fetch attribution data' }, { status: 500 });
103
+ }
104
+ }
105
+
106
+ /** Agent identity and profile info */
107
+ function buildIdentity(db: any, agent: any, workspaceId: number) {
108
+ const config = safeParseJson(agent.config, {});
109
+
110
+ // Count total tasks ever assigned
111
+ const taskStats = db.prepare(`
112
+ SELECT
113
+ COUNT(*) as total,
114
+ SUM(CASE WHEN status = 'done' THEN 1 ELSE 0 END) as completed,
115
+ SUM(CASE WHEN status IN ('assigned', 'in_progress') THEN 1 ELSE 0 END) as active
116
+ FROM tasks WHERE assigned_to = ? AND workspace_id = ?
117
+ `).get(agent.name, workspaceId) as any;
118
+
119
+ // Count comments authored
120
+ const commentCount = (db.prepare(
121
+ `SELECT COUNT(*) as c FROM comments WHERE author = ? AND workspace_id = ?`
122
+ ).get(agent.name, workspaceId) as any).c;
123
+
124
+ return {
125
+ id: agent.id,
126
+ name: agent.name,
127
+ role: agent.role,
128
+ status: agent.status,
129
+ last_seen: agent.last_seen,
130
+ last_activity: agent.last_activity,
131
+ created_at: agent.created_at,
132
+ session_key: agent.session_key ? '***' : null, // Masked for security
133
+ has_soul: !!agent.soul_content,
134
+ config_keys: Object.keys(config),
135
+ lifetime_stats: {
136
+ tasks_total: taskStats?.total || 0,
137
+ tasks_completed: taskStats?.completed || 0,
138
+ tasks_active: taskStats?.active || 0,
139
+ comments_authored: commentCount,
140
+ },
141
+ };
142
+ }
143
+
144
+ /** Audit trail — all activities attributed to this agent */
145
+ function buildAuditTrail(db: any, agentName: string, workspaceId: number, since: number) {
146
+ // Activities where this agent is the actor
147
+ const activities = db.prepare(`
148
+ SELECT id, type, entity_type, entity_id, description, data, created_at
149
+ FROM activities
150
+ WHERE actor = ? AND workspace_id = ? AND created_at >= ?
151
+ ORDER BY created_at DESC
152
+ LIMIT 200
153
+ `).all(agentName, workspaceId, since) as any[];
154
+
155
+ // Audit log entries (system-wide, may reference agent)
156
+ let auditEntries: any[] = [];
157
+ try {
158
+ auditEntries = db.prepare(`
159
+ SELECT id, action, actor, detail, created_at
160
+ FROM audit_log
161
+ WHERE (actor = ? OR detail LIKE ?) AND created_at >= ?
162
+ ORDER BY created_at DESC
163
+ LIMIT 100
164
+ `).all(agentName, `%${agentName}%`, since) as any[];
165
+ } catch {
166
+ // audit_log table may not exist
167
+ }
168
+
169
+ // Group activities by type for summary
170
+ const byType: Record<string, number> = {};
171
+ for (const a of activities) {
172
+ byType[a.type] = (byType[a.type] || 0) + 1;
173
+ }
174
+
175
+ return {
176
+ total_activities: activities.length,
177
+ by_type: byType,
178
+ activities: activities.map(a => ({
179
+ ...a,
180
+ data: safeParseJson(a.data, null),
181
+ })),
182
+ audit_log_entries: auditEntries.map(e => ({
183
+ ...e,
184
+ detail: safeParseJson(e.detail, null),
185
+ })),
186
+ };
187
+ }
188
+
189
+ /** Mutations — task changes, comments, status transitions */
190
+ function buildMutations(db: any, agentName: string, workspaceId: number, since: number) {
191
+ // Task mutations (created, updated, status changes)
192
+ const taskMutations = db.prepare(`
193
+ SELECT id, type, entity_type, entity_id, description, data, created_at
194
+ FROM activities
195
+ WHERE actor = ? AND workspace_id = ? AND created_at >= ?
196
+ AND entity_type = 'task'
197
+ AND type IN ('task_created', 'task_updated', 'task_status_change', 'task_assigned')
198
+ ORDER BY created_at DESC
199
+ LIMIT 100
200
+ `).all(agentName, workspaceId, since) as any[];
201
+
202
+ // Comments authored
203
+ const comments = db.prepare(`
204
+ SELECT c.id, c.task_id, c.content, c.created_at, c.mentions, t.title as task_title
205
+ FROM comments c
206
+ LEFT JOIN tasks t ON c.task_id = t.id AND t.workspace_id = ?
207
+ WHERE c.author = ? AND c.workspace_id = ? AND c.created_at >= ?
208
+ ORDER BY c.created_at DESC
209
+ LIMIT 50
210
+ `).all(workspaceId, agentName, workspaceId, since) as any[];
211
+
212
+ // Agent status changes (by heartbeat or others)
213
+ const statusChanges = db.prepare(`
214
+ SELECT id, type, description, data, created_at
215
+ FROM activities
216
+ WHERE entity_type = 'agent' AND workspace_id = ?
217
+ AND created_at >= ?
218
+ AND (actor = ? OR description LIKE ?)
219
+ ORDER BY created_at DESC
220
+ LIMIT 50
221
+ `).all(workspaceId, since, agentName, `%${agentName}%`) as any[];
222
+
223
+ return {
224
+ task_mutations: taskMutations.map(m => ({
225
+ ...m,
226
+ data: safeParseJson(m.data, null),
227
+ })),
228
+ comments: comments.map(c => ({
229
+ ...c,
230
+ mentions: safeParseJson(c.mentions, []),
231
+ content_preview: c.content?.substring(0, 200) || '',
232
+ })),
233
+ status_changes: statusChanges.map(s => ({
234
+ ...s,
235
+ data: safeParseJson(s.data, null),
236
+ })),
237
+ summary: {
238
+ task_mutations_count: taskMutations.length,
239
+ comments_count: comments.length,
240
+ status_changes_count: statusChanges.length,
241
+ },
242
+ };
243
+ }
244
+
245
+ /** Cost attribution — token usage per model */
246
+ function buildCostAttribution(db: any, agentName: string, workspaceId: number, since: number) {
247
+ try {
248
+ const byModel = db.prepare(`
249
+ SELECT model,
250
+ COUNT(*) as request_count,
251
+ SUM(input_tokens) as input_tokens,
252
+ SUM(output_tokens) as output_tokens
253
+ FROM token_usage
254
+ WHERE session_id = ? AND workspace_id = ? AND created_at >= ?
255
+ GROUP BY model
256
+ ORDER BY (input_tokens + output_tokens) DESC
257
+ `).all(agentName, workspaceId, since) as Array<{
258
+ model: string; request_count: number; input_tokens: number; output_tokens: number
259
+ }>;
260
+
261
+ // Also check session IDs that contain the agent name (e.g. "agentname:cli")
262
+ const byModelAlt = db.prepare(`
263
+ SELECT model,
264
+ COUNT(*) as request_count,
265
+ SUM(input_tokens) as input_tokens,
266
+ SUM(output_tokens) as output_tokens
267
+ FROM token_usage
268
+ WHERE session_id LIKE ? AND session_id != ? AND workspace_id = ? AND created_at >= ?
269
+ GROUP BY model
270
+ ORDER BY (input_tokens + output_tokens) DESC
271
+ `).all(`${agentName}:%`, agentName, workspaceId, since) as Array<{
272
+ model: string; request_count: number; input_tokens: number; output_tokens: number
273
+ }>;
274
+
275
+ // Merge results
276
+ const merged = new Map<string, { model: string; request_count: number; input_tokens: number; output_tokens: number }>();
277
+ for (const row of [...byModel, ...byModelAlt]) {
278
+ const existing = merged.get(row.model);
279
+ if (existing) {
280
+ existing.request_count += row.request_count;
281
+ existing.input_tokens += row.input_tokens;
282
+ existing.output_tokens += row.output_tokens;
283
+ } else {
284
+ merged.set(row.model, { ...row });
285
+ }
286
+ }
287
+
288
+ const models = Array.from(merged.values());
289
+ const total = models.reduce((acc, r) => ({
290
+ input_tokens: acc.input_tokens + r.input_tokens,
291
+ output_tokens: acc.output_tokens + r.output_tokens,
292
+ requests: acc.requests + r.request_count,
293
+ }), { input_tokens: 0, output_tokens: 0, requests: 0 });
294
+
295
+ // Daily breakdown for trend
296
+ const daily = db.prepare(`
297
+ SELECT (created_at / 86400) * 86400 as day_bucket,
298
+ SUM(input_tokens) as input_tokens,
299
+ SUM(output_tokens) as output_tokens,
300
+ COUNT(*) as requests
301
+ FROM token_usage
302
+ WHERE (session_id = ? OR session_id LIKE ?) AND workspace_id = ? AND created_at >= ?
303
+ GROUP BY day_bucket
304
+ ORDER BY day_bucket ASC
305
+ `).all(agentName, `${agentName}:%`, workspaceId, since) as any[];
306
+
307
+ return {
308
+ by_model: models,
309
+ total,
310
+ daily_trend: daily.map(d => ({
311
+ date: new Date(d.day_bucket * 1000).toISOString().split('T')[0],
312
+ ...d,
313
+ })),
314
+ };
315
+ } catch {
316
+ return { by_model: [], total: { input_tokens: 0, output_tokens: 0, requests: 0 }, daily_trend: [] };
317
+ }
318
+ }
319
+
320
+ function parseHours(hoursRaw: string | null): number | null {
321
+ if (!hoursRaw || hoursRaw.trim() === '') return 24;
322
+ if (!/^\d+$/.test(hoursRaw)) return null;
323
+ const hours = Number(hoursRaw);
324
+ if (!Number.isInteger(hours) || hours < 1 || hours > 720) return null;
325
+ return hours;
326
+ }
327
+
328
+ function parseSections(
329
+ sectionRaw: string | null
330
+ ): { sections: Set<string> } | { error: string } {
331
+ const value = (sectionRaw || 'identity,audit,mutations,cost').trim();
332
+ const parsed = value
333
+ .split(',')
334
+ .map((section) => section.trim())
335
+ .filter(Boolean);
336
+
337
+ if (parsed.length === 0) {
338
+ return { error: 'Invalid section. Expected one or more of identity,audit,mutations,cost.' };
339
+ }
340
+
341
+ const invalid = parsed.filter((section) => !ALLOWED_SECTIONS.has(section));
342
+ if (invalid.length > 0) {
343
+ return { error: `Invalid section value(s): ${invalid.join(', ')}` };
344
+ }
345
+
346
+ return { sections: new Set(parsed) };
347
+ }
348
+
349
+ function safeParseJson<T>(raw: string | null | undefined, fallback: T): T {
350
+ if (!raw) return fallback;
351
+ try {
352
+ return JSON.parse(raw) as T;
353
+ } catch {
354
+ return fallback;
355
+ }
356
+ }
src/lib/auth.ts CHANGED
@@ -31,6 +31,8 @@ export interface User {
31
  created_at: number
32
  updated_at: number
33
  last_login_at: number | null
 
 
34
  }
35
 
36
  export interface UserSession {
@@ -268,12 +270,15 @@ export function deleteUser(id: number): boolean {
268
  * For API key auth, returns a synthetic "api" user.
269
  */
270
  export function getUserFromRequest(request: Request): User | null {
 
 
 
271
  // Check session cookie
272
  const cookieHeader = request.headers.get('cookie') || ''
273
  const sessionToken = parseCookie(cookieHeader, 'mc-session')
274
  if (sessionToken) {
275
  const user = validateSession(sessionToken)
276
- if (user) return user
277
  }
278
 
279
  // Check API key - return synthetic user
@@ -289,6 +294,7 @@ export function getUserFromRequest(request: Request): User | null {
289
  created_at: 0,
290
  updated_at: 0,
291
  last_login_at: null,
 
292
  }
293
  }
294
 
 
31
  created_at: number
32
  updated_at: number
33
  last_login_at: number | null
34
+ /** Agent name when request is made on behalf of a specific agent (via X-Agent-Name header) */
35
+ agent_name?: string | null
36
  }
37
 
38
  export interface UserSession {
 
270
  * For API key auth, returns a synthetic "api" user.
271
  */
272
  export function getUserFromRequest(request: Request): User | null {
273
+ // Extract agent identity header (optional, for attribution)
274
+ const agentName = (request.headers.get('x-agent-name') || '').trim() || null
275
+
276
  // Check session cookie
277
  const cookieHeader = request.headers.get('cookie') || ''
278
  const sessionToken = parseCookie(cookieHeader, 'mc-session')
279
  if (sessionToken) {
280
  const user = validateSession(sessionToken)
281
+ if (user) return { ...user, agent_name: agentName }
282
  }
283
 
284
  // Check API key - return synthetic user
 
294
  created_at: 0,
295
  updated_at: 0,
296
  last_login_at: null,
297
+ agent_name: agentName,
298
  }
299
  }
300
 
tests/agent-attribution.spec.ts ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { expect, test } from '@playwright/test'
2
+ import { API_KEY_HEADER, createTestAgent, deleteTestAgent } from './helpers'
3
+
4
+ test.describe('Agent Attribution 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('allows self-scope access using x-agent-name attribution header', async ({ request }) => {
15
+ const { id, name } = await createTestAgent(request)
16
+ cleanup.push(id)
17
+
18
+ const res = await request.get(`/api/agents/${id}/attribution`, {
19
+ headers: { ...API_KEY_HEADER, 'x-agent-name': name },
20
+ })
21
+ expect(res.status()).toBe(200)
22
+ const body = await res.json()
23
+ expect(body.agent_name).toBe(name)
24
+ expect(body.access_scope).toBe('self')
25
+ })
26
+
27
+ test('denies cross-agent attribution access by default', async ({ request }) => {
28
+ const primary = await createTestAgent(request)
29
+ const other = await createTestAgent(request)
30
+ cleanup.push(primary.id, other.id)
31
+
32
+ const res = await request.get(`/api/agents/${primary.id}/attribution`, {
33
+ headers: { ...API_KEY_HEADER, 'x-agent-name': other.name },
34
+ })
35
+
36
+ expect(res.status()).toBe(403)
37
+ })
38
+
39
+ test('allows privileged override for admin caller', async ({ request }) => {
40
+ const primary = await createTestAgent(request)
41
+ const other = await createTestAgent(request)
42
+ cleanup.push(primary.id, other.id)
43
+
44
+ const res = await request.get(`/api/agents/${primary.id}/attribution?privileged=1`, {
45
+ headers: { ...API_KEY_HEADER, 'x-agent-name': other.name },
46
+ })
47
+ expect(res.status()).toBe(200)
48
+ const body = await res.json()
49
+ expect(body.access_scope).toBe('privileged')
50
+ })
51
+
52
+ test('validates section parameter and timeframe hours', async ({ request }) => {
53
+ const { id, name } = await createTestAgent(request)
54
+ cleanup.push(id)
55
+
56
+ const sectionRes = await request.get(`/api/agents/${id}/attribution?section=identity&hours=48`, {
57
+ headers: { ...API_KEY_HEADER, 'x-agent-name': name },
58
+ })
59
+ expect(sectionRes.status()).toBe(200)
60
+ const sectionBody = await sectionRes.json()
61
+ expect(sectionBody.timeframe.hours).toBe(48)
62
+ expect(sectionBody.identity).toBeDefined()
63
+ expect(sectionBody.audit).toBeUndefined()
64
+ expect(sectionBody.mutations).toBeUndefined()
65
+ expect(sectionBody.cost).toBeUndefined()
66
+
67
+ const invalidSection = await request.get(`/api/agents/${id}/attribution?section=unknown`, {
68
+ headers: { ...API_KEY_HEADER, 'x-agent-name': name },
69
+ })
70
+ expect(invalidSection.status()).toBe(400)
71
+
72
+ const invalidHours = await request.get(`/api/agents/${id}/attribution?hours=0`, {
73
+ headers: { ...API_KEY_HEADER, 'x-agent-name': name },
74
+ })
75
+ expect(invalidHours.status()).toBe(400)
76
+ })
77
+ })