Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
Merge origin/dev into fix/desktop-app
Diego Zacarias8e9dee7d8c05
diff --cc control-api/src/routes/admin/agentGrants.tsindex 000000000,df195daa8..1ea23806fmode 000000,100644..100644--- a/control-api/src/routes/admin/agentGrants.ts+++ b/control-api/src/routes/admin/agentGrants.ts@@@ -1,0 -1,122 +1,132 @@@+ import { Router } from 'express'+ import type { K8sGateway } from '../../k8s.js'+ import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'+ import {+ DeletedAgentHistoryLimitError,+ MAX_DELETED_ACCESS_HISTORY,+ accessValueSetsEqual,+ mergeActiveAgentUpdateWithDeletedHistory,+ partitionAccessValues,+ } from '../../services/directory/accessReconciliation.js'+ import { AgentGrantPreconditionError } from '../../services/directory/index.js'-import { loadAdminActiveAgentNames, sendAdminAccessReconciliationError } from './accessReconciliationResponse.js'++import {++ loadAdminActiveAgentNames,++ sendAdminAccessReconciliationError,++} from './accessReconciliationResponse.js'++ type AgentGrantSnapshot = { agentNames: string[] } & Record<string, unknown>++ export type AgentGrantRouteDefinition = {+ path: string+ idParameter: string+ getCurrent: (id: string) => Promise<AgentGrantSnapshot>+ replace: (+ id: string,+ replacement: string[],+ operatorSub: string,+ expectedCurrent: string[]+ ) => Promise<AgentGrantSnapshot>+ }+-function readGrantRequest(body: unknown): { agentNames: string[]; expectedCurrent: string[] } | null {++function readGrantRequest(++ body: unknown++): { agentNames: string[]; expectedCurrent: string[] } | null {+ const value = body && typeof body === 'object' ? (body as Record<string, unknown>) : null- if (!value || !Object.prototype.hasOwnProperty.call(value, 'expectedCurrentAgentNames')) return null++ if (!value || !Object.prototype.hasOwnProperty.call(value, 'expectedCurrentAgentNames'))++ return null+ if (+ !Array.isArray(value.agentNames) ||+ !Array.isArray(value.expectedCurrentAgentNames) ||+ !value.agentNames.every(item => typeof item === 'string') ||+ !value.expectedCurrentAgentNames.every(item => typeof item === 'string')+ ) {+ throw new TypeError('invalid_agent_grant_precondition')+ }+ return { agentNames: value.agentNames, expectedCurrent: value.expectedCurrentAgentNames }+ }++ export function registerAdminAgentGrantRoutes(+ router: Router,+ gateway: K8sGateway,+ definition: AgentGrantRouteDefinition+ ): void {- const getId = (params: Record<string, string | undefined>) => String(params[definition.idParameter] || '')++ const getId = (params: Record<string, string | undefined>) =>++ String(params[definition.idParameter] || '')++ router.get(definition.path, async (req, res, next) => {+ try {+ const base = await definition.getCurrent(getId(req.params))- const partition = partitionAccessValues(base.agentNames, await loadAdminActiveAgentNames(gateway))++ const partition = partitionAccessValues(++ base.agentNames,++ await loadAdminActiveAgentNames(gateway)++ )+ res.status(200).json({+ ...base,+ agentNames: partition.active,+ deletedAgentNames: partition.deleted,+ deletedHistoryLimit: MAX_DELETED_ACCESS_HISTORY,+ })+ } catch (error) {+ if (sendAdminAccessReconciliationError(res, error)) return+ next(error)+ }+ })++ router.put(definition.path, async (req, res, next) => {+ try {+ const request = readGrantRequest(req.body)+ if (!request) {+ res.status(428).json({ error: 'agent_grant_precondition_required' })+ return+ }++ const id = getId(req.params)+ const [existing, activeAgentNames] = await Promise.all([+ definition.getCurrent(id),+ loadAdminActiveAgentNames(gateway),+ ])+ // This preliminary read supplies deleted-host history only after proving+ // it matches the complete client snapshot. The setter repeats the CAS+ // while holding the table lock, closing both ordinary races and ABA.+ if (!accessValueSetsEqual(existing.agentNames, request.expectedCurrent)) {+ throw new AgentGrantPreconditionError()+ }+ const replacement = mergeActiveAgentUpdateWithDeletedHistory(+ request.agentNames,+ activeAgentNames,+ partitionAccessValues(existing.agentNames, activeAgentNames).deleted+ )+ const updated = await definition.replace(+ id,+ replacement,+ (req as UiAuthedRequest).adminAuth!.sub,+ request.expectedCurrent+ )+ const partition = partitionAccessValues(updated.agentNames, activeAgentNames)+ res.status(200).json({+ ...updated,+ agentNames: partition.active,+ deletedAgentNames: partition.deleted,+ deletedHistoryLimit: MAX_DELETED_ACCESS_HISTORY,+ })+ } catch (error) {+ if (error instanceof TypeError && error.message === 'invalid_agent_grant_precondition') {+ res.status(400).json({ error: 'invalid_agent_grant_precondition' })+ return+ }+ if (error instanceof DeletedAgentHistoryLimitError) {+ res.status(409).json({+ error: 'deleted_agent_history_limit_exceeded',+ deletedHistoryLimit: error.limit,+ })+ return+ }+ if (error instanceof AgentGrantPreconditionError) {+ res.status(412).json({ error: 'precondition_failed' })+ return+ }+ if (sendAdminAccessReconciliationError(res, error)) return+ next(error)+ }+ })+ }diff --cc control-api/src/routes/admin/teamAccess.tsindex 000000000,9373667a6..6d4e4d04bmode 000000,100644..100644--- a/control-api/src/routes/admin/teamAccess.ts+++ b/control-api/src/routes/admin/teamAccess.ts@@@ -1,0 -1,57 +1,69 @@@+ import { Router } from 'express'+ import type { K8sGateway } from '../../k8s.js'+ import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'+ import {+ mergeActiveUpdateWithDeletedHistory,+ partitionAccessValues,+ } from '../../services/directory/accessReconciliation.js'-import { getTeamAgents, getTeamContexts, setTeamAgents, setTeamContexts } from '../../services/directory/index.js'++import {++ getTeamAgents,++ getTeamContexts,++ setTeamAgents,++ setTeamContexts,++} from '../../services/directory/index.js'+ import {+ loadAdminActiveContextIds,+ sendAdminAccessReconciliationError,+ } from './accessReconciliationResponse.js'+ import { registerAdminAgentGrantRoutes } from './agentGrants.js'++ export function registerAdminTeamAccessRoutes(router: Router, gateway: K8sGateway): void {+ router.get('/admin/teams/:teamId/contexts', async (req, res, next) => {+ try {+ const base = await getTeamContexts(req.params.teamId)- const partition = partitionAccessValues(base.contextIds, await loadAdminActiveContextIds(gateway))- res.status(200).json({ ...base, contextIds: partition.active, deletedContextIds: partition.deleted })++ const partition = partitionAccessValues(++ base.contextIds,++ await loadAdminActiveContextIds(gateway)++ )++ res++ .status(200)++ .json({ ...base, contextIds: partition.active, deletedContextIds: partition.deleted })+ } catch (error) {+ if (sendAdminAccessReconciliationError(res, error)) return+ next(error)+ }+ })++ router.put('/admin/teams/:teamId/contexts', async (req, res, next) => {+ try {+ const contextIds = Array.isArray(req.body?.contextIds) ? req.body.contextIds.map(String) : []+ const [existing, activeContextIds] = await Promise.all([+ getTeamContexts(req.params.teamId),+ loadAdminActiveContextIds(gateway),+ ])+ const updated = await setTeamContexts(+ req.params.teamId,+ mergeActiveUpdateWithDeletedHistory(+ contextIds,+ activeContextIds,+ partitionAccessValues(existing.contextIds, activeContextIds).deleted+ ),+ (req as UiAuthedRequest).adminAuth!.sub+ )+ const partition = partitionAccessValues(updated.contextIds, activeContextIds)- res.status(200).json({ ...updated, contextIds: partition.active, deletedContextIds: partition.deleted })++ res++ .status(200)++ .json({ ...updated, contextIds: partition.active, deletedContextIds: partition.deleted })+ } catch (error) {+ if (sendAdminAccessReconciliationError(res, error)) return+ next(error)+ }+ })++ registerAdminAgentGrantRoutes(router, gateway, {+ path: '/admin/teams/:teamId/agents',+ idParameter: 'teamId',+ getCurrent: getTeamAgents,+ replace: setTeamAgents,+ })+ }diff --cc control-api/src/routes/admin/teamInvitations.tsindex 000000000,f6dcf9c6b..26fad446bmode 000000,100644..100644--- a/control-api/src/routes/admin/teamInvitations.ts+++ b/control-api/src/routes/admin/teamInvitations.ts@@@ -1,0 -1,135 +1,149 @@@+ import { type Response, Router } from 'express'+ import {+ createInvitation,+ createInvitationForTeams,+ getTeamById,+ listPendingInvitationsForTeam,+ listUsers,+ resendInvitation,+ revokePendingInvitation,+ } from '../../services/directory/index.js'+ import { normalizeTeamRoleInput } from '../../services/directory/types.js'++ function isUuid(value: string): boolean {+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)+ }+-async function findExistingMemberByEmail(email: string): Promise<{ id: string; email: string } | null> {++async function findExistingMemberByEmail(++ email: string++): Promise<{ id: string; email: string } | null> {+ const normalizedEmail = email.trim().toLowerCase()+ if (!normalizedEmail) return null+ const matches = await listUsers(normalizedEmail)- return matches.find(member => String(member.email || '').toLowerCase() === normalizedEmail) || null++ return (++ matches.find(member => String(member.email || '').toLowerCase() === normalizedEmail) || null++ )+ }++ function sendExistingMemberConflict(res: Response, member: { id: string; email: string }): void {+ res.status(409).json({+ error: 'member_email_exists',+ message:+ 'A member with this email already exists. Open the existing member and add them to more teams instead.',+ memberId: member.id,+ email: member.email,+ })+ }++ export function registerAdminTeamInvitationRoutes(router: Router): void {+ router.post('/admin/invitations', async (req, res, next) => {+ try {+ const name = String(req.body?.name || '').trim()- const email = String(req.body?.email || '').trim().toLowerCase()++ const email = String(req.body?.email || '')++ .trim()++ .toLowerCase()+ const fallbackRole = normalizeTeamRoleInput(req.body?.role) || 'member'+ const teamsInput: unknown[] = Array.isArray(req.body?.teams) ? req.body.teams : []+ const teamAssignments = teamsInput+ .map((item: unknown) => {+ const row = item && typeof item === 'object' ? (item as Record<string, unknown>) : {}+ const teamId = String(row.teamId || row.id || '').trim()+ const role = normalizeTeamRoleInput(row.role) || fallbackRole+ return teamId ? { teamId, role } : null+ })- .filter((item): item is { teamId: string; role: 'admin' | 'inviter' | 'member' } => Boolean(item))++ .filter((item): item is { teamId: string; role: 'admin' | 'inviter' | 'member' } =>++ Boolean(item)++ )+ if (!name || !email) {+ res.status(400).json({ error: 'invalid invitation payload' })+ return+ }+ const existingMember = await findExistingMemberByEmail(email)+ if (existingMember) return sendExistingMemberConflict(res, existingMember)+ res.status(200).json(+ await createInvitationForTeams({+ inviteeName: name,+ email,+ purpose: 'member_invitation',+ teamAssignments,+ fallbackRole,+ })+ )+ } catch (error) {+ next(error)+ }+ })++ router.post('/admin/invitations/:invitationId/resend', async (req, res, next) => {+ try {+ const invitationId = String(req.params.invitationId || '').trim()- if (!isUuid(invitationId)) return void res.status(400).json({ error: 'invalid_invitation_id' })++ if (!isUuid(invitationId))++ return void res.status(400).json({ error: 'invalid_invitation_id' })+ const resent = await resendInvitation(null, invitationId)+ if (!resent) return void res.status(404).json({ error: 'not_found' })+ res.status(200).json({ sent: true, id: resent.id, email: resent.email })+ } catch (error) {+ next(error)+ }+ })++ router.delete('/admin/invitations/:invitationId', async (req, res, next) => {+ try {+ const invitationId = String(req.params.invitationId || '').trim()- if (!isUuid(invitationId)) return void res.status(400).json({ error: 'invalid_invitation_id' })++ if (!isUuid(invitationId))++ return void res.status(400).json({ error: 'invalid_invitation_id' })+ const revoked = await revokePendingInvitation(null, invitationId)+ if (!revoked) return void res.status(404).json({ error: 'not_found' })+ res.status(200).json({ revoked: true, id: revoked.id, email: revoked.email })+ } catch (error) {+ next(error)+ }+ })++ router.get('/admin/teams/:teamId/invitations', async (req, res, next) => {+ try {- if (!(await getTeamById(req.params.teamId))) return void res.status(404).json({ error: 'not_found' })++ if (!(await getTeamById(req.params.teamId)))++ return void res.status(404).json({ error: 'not_found' })+ res.status(200).json({ items: await listPendingInvitationsForTeam(req.params.teamId) })+ } catch (error) {+ next(error)+ }+ })++ router.post('/admin/teams/:teamId/invitations', async (req, res, next) => {+ try {+ const name = String(req.body?.name || '').trim()- const email = String(req.body?.email || '').trim().toLowerCase()++ const email = String(req.body?.email || '')++ .trim()++ .toLowerCase()+ const role = normalizeTeamRoleInput(req.body?.role)- if (!name || !email || !role) return void res.status(400).json({ error: 'invalid invitation payload' })++ if (!name || !email || !role)++ return void res.status(400).json({ error: 'invalid invitation payload' })+ const existingMember = await findExistingMemberByEmail(email)+ if (existingMember) return sendExistingMemberConflict(res, existingMember)+ res.status(200).json(await createInvitation(req.params.teamId, name, email, role))+ } catch (error) {+ next(error)+ }+ })++ router.post('/admin/teams/:teamId/invitations/:invitationId/resend', async (req, res, next) => {+ try {+ const resent = await resendInvitation(req.params.teamId, req.params.invitationId)+ if (!resent) return void res.status(404).json({ error: 'not_found' })+ res.status(200).json({ sent: true, id: resent.id, email: resent.email })+ } catch (error) {+ next(error)+ }+ })++ router.delete('/admin/teams/:teamId/invitations/:invitationId', async (req, res, next) => {+ try {+ const revoked = await revokePendingInvitation(req.params.teamId, req.params.invitationId)+ if (!revoked) return void res.status(404).json({ error: 'not_found' })+ res.status(200).json({ revoked: true, id: revoked.id, email: revoked.email })+ } catch (error) {+ next(error)+ }+ })+ }diff --cc control-api/src/routes/admin/userAccess.tsindex 000000000,12de1f835..3825aa546mode 000000,100644..100644--- a/control-api/src/routes/admin/userAccess.ts+++ b/control-api/src/routes/admin/userAccess.ts@@@ -1,0 -1,57 +1,69 @@@+ import { Router } from 'express'+ import type { K8sGateway } from '../../k8s.js'+ import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'+ import {+ mergeActiveUpdateWithDeletedHistory,+ partitionAccessValues,+ } from '../../services/directory/accessReconciliation.js'-import { getUserAgents, getUserContexts, setUserAgents, setUserContexts } from '../../services/directory/index.js'++import {++ getUserAgents,++ getUserContexts,++ setUserAgents,++ setUserContexts,++} from '../../services/directory/index.js'+ import {+ loadAdminActiveContextIds,+ sendAdminAccessReconciliationError,+ } from './accessReconciliationResponse.js'+ import { registerAdminAgentGrantRoutes } from './agentGrants.js'++ export function registerAdminUserAccessRoutes(router: Router, gateway: K8sGateway): void {+ router.get('/admin/users/:userId/contexts', async (req, res, next) => {+ try {+ const base = await getUserContexts(req.params.userId)- const partition = partitionAccessValues(base.contextIds, await loadAdminActiveContextIds(gateway))- res.status(200).json({ ...base, contextIds: partition.active, deletedContextIds: partition.deleted })++ const partition = partitionAccessValues(++ base.contextIds,++ await loadAdminActiveContextIds(gateway)++ )++ res++ .status(200)++ .json({ ...base, contextIds: partition.active, deletedContextIds: partition.deleted })+ } catch (error) {+ if (sendAdminAccessReconciliationError(res, error)) return+ next(error)+ }+ })++ router.put('/admin/users/:userId/contexts', async (req, res, next) => {+ try {+ const contextIds = Array.isArray(req.body?.contextIds) ? req.body.contextIds.map(String) : []+ const [existing, activeContextIds] = await Promise.all([+ getUserContexts(req.params.userId),+ loadAdminActiveContextIds(gateway),+ ])+ const updated = await setUserContexts(+ req.params.userId,+ mergeActiveUpdateWithDeletedHistory(+ contextIds,+ activeContextIds,+ partitionAccessValues(existing.contextIds, activeContextIds).deleted+ ),+ (req as UiAuthedRequest).adminAuth!.sub+ )+ const partition = partitionAccessValues(updated.contextIds, activeContextIds)- res.status(200).json({ ...updated, contextIds: partition.active, deletedContextIds: partition.deleted })++ res++ .status(200)++ .json({ ...updated, contextIds: partition.active, deletedContextIds: partition.deleted })+ } catch (error) {+ if (sendAdminAccessReconciliationError(res, error)) return+ next(error)+ }+ })++ registerAdminAgentGrantRoutes(router, gateway, {+ path: '/admin/users/:userId/agents',+ idParameter: 'userId',+ getCurrent: getUserAgents,+ replace: setUserAgents,+ })+ }diff --cc control-api/test/generics.precondition.test.tsindex 000000000,1b2457f4d..5ffec55admode 000000,100644..100644--- a/control-api/test/generics.precondition.test.ts+++ b/control-api/test/generics.precondition.test.ts@@@ -1,0 -1,29 +1,38 @@@+ import { describe, expect, it, vi } from 'vitest'++import { LinkedItemsPreconditionError, bulkSetLinkedItems } from '../src/shared/generics.js'++ const db = vi.hoisted(() => ({ query: vi.fn() }))+ const withTransaction = vi.hoisted(() => vi.fn(async work => work(db)))++ vi.mock('../src/db.js', () => ({ withTransaction }))+-import { LinkedItemsPreconditionError, bulkSetLinkedItems } from '../src/shared/generics.js'-+ describe('bulkSetLinkedItems optimistic concurrency', () => {+ it('locks the table and rejects a stale expected set before mutation', async () => {+ db.query.mockImplementation(async (statement: string) => {+ if (statement.includes('SELECT agent_name::text AS item')) {+ return { rows: [{ item: 'agent-current' }] }+ }+ return { rows: [] }+ })++ await expect(- bulkSetLinkedItems('user_agents', 'user_id', 'user-1', 'agent_name', ['agent-next'], undefined, {- expectedItems: ['agent-stale'],- })++ bulkSetLinkedItems(++ 'user_agents',++ 'user_id',++ 'user-1',++ 'agent_name',++ ['agent-next'],++ undefined,++ {++ expectedItems: ['agent-stale'],++ }++ )+ ).rejects.toBeInstanceOf(LinkedItemsPreconditionError)++ const statements = db.query.mock.calls.map(([statement]) => String(statement))+ expect(statements).toContain('LOCK TABLE user_agents IN SHARE ROW EXCLUSIVE MODE')- expect(statements.some(statement => statement.startsWith('DELETE FROM user_agents'))).toBe(false)++ expect(statements.some(statement => statement.startsWith('DELETE FROM user_agents'))).toBe(++ false++ )+ })+ })diff --cc control-api/test/routes.agentGrants.test.tsindex 000000000,23db94fe1..ff75a1d0dmode 000000,100644..100644--- a/control-api/test/routes.agentGrants.test.ts+++ b/control-api/test/routes.agentGrants.test.ts@@@ -1,0 -1,249 +1,255 @@@+ import { beforeEach, describe, expect, it, vi } from 'vitest'+ import express from 'express'+ import request from 'supertest'+ import type { K8sGateway } from '../src/k8s.js'+ import { createAdminTeamsRouter } from '../src/routes/admin/teams.js'+ import { createAdminUsersRouter } from '../src/routes/admin/users.js'+ import { MAX_DELETED_ACCESS_HISTORY } from '../src/services/directory/accessReconciliation.js'++ const svc = vi.hoisted(() => ({+ addMemberToTeam: vi.fn(),+ adminDeleteTeam: vi.fn(),+ adminDeleteUser: vi.fn(),+ createAdminUser: vi.fn(),+ createInvitation: vi.fn(),+ createInvitationForTeams: vi.fn(),+ createPasswordSetupInvitationForUser: vi.fn(),+ createTeam: vi.fn(),+ findMembership: vi.fn(),+ getAdminUserContext: vi.fn(),+ getTeamAgents: vi.fn(),+ getTeamById: vi.fn(),+ getTeamContexts: vi.fn(),+ getUserAgents: vi.fn(),+ getUserContexts: vi.fn(),+ listAllPendingInvitationsAdmin: vi.fn(),+ listAllTeams: vi.fn(),+ listMembers: vi.fn(),+ listPendingInvitationsForTeam: vi.fn(),+ listTeamAgentsByTeam: vi.fn(),+ listTeamContextsByTeam: vi.fn(),+ listTeams: vi.fn(),+ listUsers: vi.fn(),+ renameTeam: vi.fn(),+ resendInvitation: vi.fn(),+ revokePendingInvitation: vi.fn(),+ setTeamAgents: vi.fn(),+ setTeamContexts: vi.fn(),+ setUserAgents: vi.fn(),+ setUserContexts: vi.fn(),+ softDeleteMember: vi.fn(),+ updateAdminUserContext: vi.fn(),+ updateMemberRole: vi.fn(),+ }))++ const serviceErrors = vi.hoisted(() => ({+ AgentGrantPreconditionError: class AgentGrantPreconditionError extends Error {},+ }))++ vi.mock('../src/services/directory/index.js', () => ({+ ...svc,+ AgentGrantPreconditionError: serviceErrors.AgentGrantPreconditionError,+ }))++ const TEST_ADMIN_SUB = '11111111-1111-4111-8111-111111111111'+ const gatewayStub = { listResource: vi.fn(async () => []) }++ function createApp() {+ const app = express()+ const router = express.Router()+ router.use((req, _res, next) => {+ ;(req as unknown as { adminAuth: { sub: string } }).adminAuth = { sub: TEST_ADMIN_SUB }+ next()+ })+ router.use(createAdminUsersRouter(gatewayStub as unknown as K8sGateway))+ router.use(createAdminTeamsRouter(gatewayStub as unknown as K8sGateway))+ app.use(express.json())+ app.use(router)+ return app+ }++ describe('routes/admin agent grants', () => {+ beforeEach(() => {+ Object.values(svc).forEach(fn => fn.mockReset())+ gatewayStub.listResource.mockReset()+ gatewayStub.listResource.mockResolvedValue([])+ })++ it('returns deleted history and requires a complete, valid precondition', async () => {+ gatewayStub.listResource.mockImplementation(async plural =>+ plural === 'hosts' ? [{ metadata: { name: 'agent-live' } }] : []+ )+ svc.getUserAgents.mockResolvedValue({ userId: 'u1', agentNames: ['agent-live', 'agent-old'] })+ svc.getTeamAgents.mockResolvedValue({ teamId: 't1', agentNames: ['agent-live', 'agent-old'] })+ const app = createApp()++ await request(app)+ .get('/admin/users/u1/agents')+ .expect(200)+ .expect({+ userId: 'u1',+ agentNames: ['agent-live'],+ deletedAgentNames: ['agent-old'],+ deletedHistoryLimit: MAX_DELETED_ACCESS_HISTORY,+ })+ await request(app)+ .get('/admin/teams/t1/agents')+ .expect(200)+ .expect({+ teamId: 't1',+ agentNames: ['agent-live'],+ deletedAgentNames: ['agent-old'],+ deletedHistoryLimit: MAX_DELETED_ACCESS_HISTORY,+ })+ await request(app)+ .put('/admin/users/u1/agents')+ .send({ agentNames: ['agent-live'] })+ .expect(428, { error: 'agent_grant_precondition_required' })+ await request(app)+ .put('/admin/teams/t1/agents')+ .send({ agentNames: ['agent-live'], expectedCurrentAgentNames: 'agent-live' })+ .expect(400, { error: 'invalid_agent_grant_precondition' })+ })++ it('derives the durable replacement server-side and forwards the full CAS snapshot', async () => {+ gatewayStub.listResource.mockImplementation(async plural =>+ plural === 'hosts' ? [{ metadata: { name: 'agent-live' } }] : []+ )+ svc.getUserAgents.mockResolvedValue({ userId: 'u1', agentNames: ['agent-live', 'agent-old'] })+ svc.getTeamAgents.mockResolvedValue({ teamId: 't1', agentNames: ['agent-live', 'agent-old'] })+ svc.setUserAgents.mockResolvedValue({ userId: 'u1', agentNames: ['agent-live', 'agent-old'] })+ svc.setTeamAgents.mockResolvedValue({ teamId: 't1', agentNames: ['agent-live', 'agent-old'] })+ const body = {+ agentNames: ['agent-live'],+ replacementAgentNames: ['agent-live', 'forged-agent'],+ expectedCurrentAgentNames: ['agent-old', 'agent-live'],+ }+ const app = createApp()++ await request(app).put('/admin/users/u1/agents').send(body).expect(200)+ await request(app).put('/admin/teams/t1/agents').send(body).expect(200)++ expect(svc.setUserAgents).toHaveBeenCalledWith(+ 'u1',+ ['agent-live', 'agent-old'],+ TEST_ADMIN_SUB,+ body.expectedCurrentAgentNames+ )+ expect(svc.setTeamAgents).toHaveBeenCalledWith(+ 't1',+ ['agent-live', 'agent-old'],+ TEST_ADMIN_SUB,+ body.expectedCurrentAgentNames+ )+ })++ it('rejects stale and ABA snapshots before they can supply deleted history', async () => {+ gatewayStub.listResource.mockImplementation(async plural =>+ plural === 'hosts' ? [{ metadata: { name: 'agent-live' } }] : []+ )+ svc.getUserAgents.mockResolvedValue({+ userId: 'u1',+ agentNames: ['agent-live', 'deleted-from-a'],+ })+ svc.getTeamAgents.mockResolvedValue({+ teamId: 't1',+ agentNames: ['agent-live', 'deleted-from-a'],+ })+ const body = {+ agentNames: ['agent-live'],+ expectedCurrentAgentNames: ['agent-live', 'deleted-from-b'],+ }+ const app = createApp()++ await request(app)+ .put('/admin/users/u1/agents')+ .send(body)+ .expect(412, { error: 'precondition_failed' })+ await request(app)+ .put('/admin/teams/t1/agents')+ .send(body)+ .expect(412, { error: 'precondition_failed' })+ expect(svc.setUserAgents).not.toHaveBeenCalled()+ expect(svc.setTeamAgents).not.toHaveBeenCalled()+ })++ it('allows only one concurrent replacement for the same complete snapshot', async () => {+ gatewayStub.listResource.mockImplementation(async plural =>+ plural === 'hosts' ? [{ metadata: { name: 'agent-live' } }] : []+ )+ const app = createApp()+ const stale = ['agent-live', 'agent-deleted']++ for (const [path, getCurrent, replace, identity] of [+ ['/admin/users/u1/agents', svc.getUserAgents, svc.setUserAgents, 'userId'],+ ['/admin/teams/t1/agents', svc.getTeamAgents, svc.setTeamAgents, 'teamId'],+ ]) {+ let current = stale- getCurrent.mockImplementation(async () => ({ [identity]: path.includes('/users/') ? 'u1' : 't1', agentNames: current }))- replace.mockImplementation(async (_id: string, replacement: string[], _operator: string, expected: string[]) => {- if (!accessSetsEqual(expected, current)) throw new serviceErrors.AgentGrantPreconditionError()- current = replacement- return { [identity]: path.includes('/users/') ? 'u1' : 't1', agentNames: replacement }- })++ getCurrent.mockImplementation(async () => ({++ [identity]: path.includes('/users/') ? 'u1' : 't1',++ agentNames: current,++ }))++ replace.mockImplementation(++ async (_id: string, replacement: string[], _operator: string, expected: string[]) => {++ if (!accessSetsEqual(expected, current))++ throw new serviceErrors.AgentGrantPreconditionError()++ current = replacement++ return { [identity]: path.includes('/users/') ? 'u1' : 't1', agentNames: replacement }++ }++ )++ const responses = await Promise.all([+ request(app).put(path).send({ agentNames: [], expectedCurrentAgentNames: stale }),+ request(app).put(path).send({ agentNames: [], expectedCurrentAgentNames: stale }),+ ])+ expect(responses.map(response => response.status).sort()).toEqual([200, 412])+ expect(current).toEqual(['agent-deleted'])+ }+ })++ it('maps deleted-history overflow and the locked setter precondition to the public contract', async () => {+ const retained = Array.from(+ { length: MAX_DELETED_ACCESS_HISTORY + 1 },+ (_value, index) => `agent-deleted-${index}`+ )+ gatewayStub.listResource.mockImplementation(async plural =>+ plural === 'hosts' ? [{ metadata: { name: 'agent-live' } }] : []+ )+ svc.getUserAgents.mockResolvedValue({ userId: 'u1', agentNames: ['agent-live', ...retained] })+ svc.getTeamAgents.mockResolvedValue({ teamId: 't1', agentNames: ['agent-live'] })+ svc.setTeamAgents.mockRejectedValue(new serviceErrors.AgentGrantPreconditionError())+ const app = createApp()++ await request(app)+ .put('/admin/users/u1/agents')+ .send({ agentNames: ['agent-live'], expectedCurrentAgentNames: ['agent-live', ...retained] })+ .expect(409, {+ error: 'deleted_agent_history_limit_exceeded',+ deletedHistoryLimit: MAX_DELETED_ACCESS_HISTORY,+ })+ await request(app)+ .put('/admin/teams/t1/agents')+ .send({ agentNames: ['agent-live'], expectedCurrentAgentNames: ['agent-live'] })+ .expect(412, { error: 'precondition_failed' })+ expect(svc.setUserAgents).not.toHaveBeenCalled()+ })++ it('reports a reconciliation outage without attempting an agent-grant update', async () => {+ gatewayStub.listResource.mockRejectedValue(new Error('k8s unavailable'))+ svc.getUserContexts.mockResolvedValue({ userId: 'u1', contextIds: ['ctx-live'] })+ svc.getTeamAgents.mockResolvedValue({ teamId: 't1', agentNames: ['agent-live'] })+ const app = createApp()++ await request(app)+ .get('/admin/users/u1/contexts')+ .expect(503, { error: 'context_reconciliation_unavailable' })+ await request(app)+ .get('/admin/teams/t1/agents')+ .expect(503, { error: 'agent_reconciliation_unavailable' })+ expect(svc.setTeamAgents).not.toHaveBeenCalled()+ })+ })++ function accessSetsEqual(left: string[], right: string[]): boolean {+ return left.length === right.length && left.every(value => right.includes(value))+ }diff --cc control-ui/lib/__tests__/agentGrantApi.test.tsindex 000000000,52a580ca6..e6ee6a1c8mode 000000,100644..100644--- a/control-ui/lib/__tests__/agentGrantApi.test.ts+++ b/control-ui/lib/__tests__/agentGrantApi.test.ts@@@ -1,0 -1,71 +1,73 @@@+ import { afterEach, describe, expect, it, vi } from 'vitest'+ import { updateAdminTeamAgents, updateAdminUserAgents } from '../api'++ function jsonResponse(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { 'content-type': 'application/json' },+ })+ }++ afterEach(() => {+ vi.restoreAllMocks()+ })++ describe('agent grant replacement API helpers', () => {+ it('sends the complete observed active and deleted set for user replacement', async () => {+ const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(+ jsonResponse({+ userId: 'user-1',+ agentNames: ['active-agent'],+ deletedAgentNames: ['deleted-agent'],+ deletedHistoryLimit: 200,+ })+ )++ await updateAdminUserAgents('user-1', ['active-agent'], ['active-agent', 'deleted-agent'])++ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]+ expect(url).toContain('/api/v1/admin/users/user-1/agents')+ expect(init.method).toBe('PUT')+ expect(JSON.parse(String(init.body))).toEqual({+ agentNames: ['active-agent'],+ expectedCurrentAgentNames: ['active-agent', 'deleted-agent'],+ })+ })++ it('sends an explicit empty observed set for a new team replacement', async () => {+ const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(+ jsonResponse({+ teamId: 'team-1',+ agentNames: ['active-agent'],+ deletedAgentNames: [],+ deletedHistoryLimit: 200,+ })+ )++ await updateAdminTeamAgents('team-1', ['active-agent'], [])++ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]+ expect(url).toContain('/api/v1/admin/teams/team-1/agents')+ expect(init.method).toBe('PUT')+ expect(JSON.parse(String(init.body))).toEqual({+ agentNames: ['active-agent'],+ expectedCurrentAgentNames: [],+ })+ })++ it.each([+ [412, 'precondition_failed', 'This item changed since it was loaded.'],+ [409, 'deleted_agent_history_limit_exceeded', 'No existing history was removed.'],+ [428, 'agent_grant_precondition_required', 'Reload the page and try again.'],+ ])('keeps agent-grant conflicts actionable for status %i', async (status, code, message) => {+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(jsonResponse({ error: code }, status))+- await expect(updateAdminUserAgents('user-1', ['active-agent'], ['active-agent'])).rejects.toMatchObject({++ await expect(++ updateAdminUserAgents('user-1', ['active-agent'], ['active-agent'])++ ).rejects.toMatchObject({+ status,+ code,+ message: expect.stringContaining(message),+ })+ })+ })diff --cc control-ui/lib/api.tsindex b8df1b3c6,dc43c563f..cee917335--- a/control-ui/lib/api.ts+++ b/control-ui/lib/api.ts@@@ -102,16 -102,22 +102,22 @@@ function formatApiError(res: Response,? 'Desktop App password must be between 8 and 256 characters.': detail === 'password must be between 8 and 256 characters'? 'Password must be between 8 and 256 characters.'- : // Exact match is correct HERE: control-ui calls control-api directly,- // so a member-registration 503 arrives as the bare { error: '<code>' }- // body. profile-ui reaches these same codes through external-rest-api,- // whose error middleware wraps any 5xx into { message: '...: <code>' },- // so it must use .includes() instead β the two matchers differ on purpose.- detail === 'member_registration_unavailable'- ? "Invitations are unavailable β the member-registration service isn't configured or can't be reached. Check the server logs for details."- : detail === 'member_registration_misconfigured'- ? 'Invitations are unavailable β member registration is misconfigured. Check the server logs for details.'- : detail+ : detail === 'precondition_failed'+ ? 'This item changed since it was loaded. Reload the page, review the latest state, and try again.'+ : detail === 'agent_grant_precondition_required'+ ? 'Agent access could not be updated because the page did not include its current access state. Reload the page and try again.'+ : detail === 'deleted_agent_history_limit_exceeded'+ ? 'Agent access was not updated because the deleted-agent history limit was reached. No existing history was removed. Reload the page, review the current access, and try again.'+ : // Exact match is correct HERE: control-ui calls control-api directly,+ // so a member-registration 503 arrives as the bare { error: '<code>' }+ // body. profile-ui reaches these same codes through external-rest-api,+ // whose error middleware wraps any 5xx into { message: '...: <code>' },+ // so it must use .includes() instead β the two matchers differ on purpose.+ detail === 'member_registration_unavailable'- ? "Invitations are unavailable β the member-registration service isn't configured or can't be reached. Check the server logs for details."- : detail === 'member_registration_misconfigured'- ? 'Invitations are unavailable β member registration is misconfigured. Check the server logs for details.'- : detail++ ? "Invitations are unavailable β the member-registration service isn't configured or can't be reached. Check the server logs for details."++ : detail === 'member_registration_misconfigured'++ ? 'Invitations are unavailable β member registration is misconfigured. Check the server logs for details.'++ : detailconst error = new Error(`${res.status} ${res.statusText} - ${friendlyDetail}`);(error as Error & { status?: number }).status = res.status// Preserve the machine-readable error code and full JSON body so callers candiff --cc control-ui/package-lock.jsonindex ee91beb53,ee91beb53..aa10851df--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@@ -1,12 -1,12 +1,12 @@@{"name": "clerum-control-ui",-- "version": "0.1.351",++ "version": "0.1.352","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",-- "version": "0.1.351",++ "version": "0.1.352","dependencies": {"@clerum/llm-providers": "file:../packages/llm-providers","@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",diff --cc control-ui/package.jsonindex 3c22b8385,3c22b8385..2f7d71b2d--- a/control-ui/package.json+++ b/control-ui/package.json@@@ -1,6 -1,6 +1,6 @@@{"name": "clerum-control-ui",-- "version": "0.1.351",++ "version": "0.1.352","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",diff --cc desktop-app/package-lock.jsonindex f344dc192,4fcc2e210..9597b8544--- a/desktop-app/package-lock.json+++ b/desktop-app/package-lock.json@@@ -1,12 -1,12 +1,12 @@@{"name": "evenfire",- "version": "0.1.322",- "version": "0.1.318",++ "version": "0.1.323","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "evenfire",- "version": "0.1.322",- "version": "0.1.318",++ "version": "0.1.323","license": "MPL-2.0","dependencies": {"@tanstack/react-query": "5.100.10",diff --cc desktop-app/package.jsonindex 19b999f75,6803ebb82..f07aa132d--- a/desktop-app/package.json+++ b/desktop-app/package.json@@@ -1,7 -1,7 +1,7 @@@{"name": "evenfire","productName": "Evenfire",- "version": "0.1.322",- "version": "0.1.318",++ "version": "0.1.323","private": true,"license": "MPL-2.0","description": "Evenfire desktop client for secure agent and workflow access",