Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: protect admin agent grants with CAS
Alfredo Lopezcc21d96096e7
diff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 000000000..0e077c471--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,57 @@+# Evenfire repository instructions++## Local Minikube reuse and ownership++Use an existing healthy, branch-owned Minikube profile for successive local+iterations. Do not create a new profile merely because the current commit,+gate, or test command changes. Preserve the verified profile by passing its+explicit `MINIKUBE_PROFILE` value into the next operation.++Before reusing a profile, record and compare all of the following:++- active worktree path, branch, `HEAD`, and `origin/dev`;+- target Minikube profile and explicit Kubernetes context;+- the pre-gate state marker: `worktreeId`, `gitHead`, and+ `clusterFingerprint`;+- profile status and currently running profile, pre-gate-sync, and+ port-forward processes.++Reusing a profile is allowed only when it remains clearly owned by the active+worktree/lane. If it belongs to another active branch or task, or ownership is+ambiguous, do not touch it: use a dedicated profile instead. A fresh profile is+also required when the selected profile is missing or unhealthy. Never use+shared fixed localhost ports for branch-owned profiles; use the profile-owned+random port mapping already recorded for that profile.++## Incremental local image updates++For a service-only change in an already healthy profile, rebuild and restart+only the affected workload. Prefer the existing targeted path:++```bash+MINIKUBE_PROFILE=<verified-profile> \+ make minikube-deploy-service SVC=<image-selector> NS=<namespace> \+ MINIKUBE_DEPLOYMENT=<deployment>+```++Examples: `control-api` / `control-plane` / `control-api`,+`external-rest-api` / `profiles` / `external-rest-api`, `rpc-proxy` /+`rpc-proxy` / `rpc-proxy`, and `mcp-host` / `mcp-host` / `chatllm`.+`scripts/minikube/build-images.sh --only=<image-selector>` is the underlying+image-only primitive; do not call the all-image builder for a known+single-service change.++Use `make minikube-pre-gate-sync` for a full T2 gate after T1 passes. It owns+the cluster fingerprint, migration ordering, rollout checks, and runtime+marker. It compares the deployed marker to the current worktree, rebuilds only+the known affected image selectors, and restarts only their deployments. A+fresh profile, an explicit forced sync, or an unmapped runtime path must fall+back to the established complete image build. A service-only T2 may use the+targeted path when the profile is already healthy; record it as a *targeted+T2* and prove the affected deployment is Ready plus its user-facing health+endpoint. Do not report that as a full reconcile.++Expect a full reconcile when deployment manifests, CRDs, charts, network+policy, or other infrastructure inputs changed; do not replace that safe path+with partial image updates. Every `kubectl` invocation must use the verified+context explicitly.diff --git a/control-api/src/routes/admin/agentGrants.ts b/control-api/src/routes/admin/agentGrants.tsnew file mode 100644index 000000000..df195daa8--- /dev/null+++ b/control-api/src/routes/admin/agentGrants.ts@@ -0,0 +1,122 @@+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'++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 {+ const value = body && typeof body === 'object' ? (body as Record<string, unknown>) : 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] || '')++ 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))+ 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 --git a/control-api/src/routes/admin/teamAccess.ts b/control-api/src/routes/admin/teamAccess.tsnew file mode 100644index 000000000..9373667a6--- /dev/null+++ b/control-api/src/routes/admin/teamAccess.ts@@ -0,0 +1,57 @@+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 {+ 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 })+ } 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 })+ } catch (error) {+ if (sendAdminAccessReconciliationError(res, error)) return+ next(error)+ }+ })++ registerAdminAgentGrantRoutes(router, gateway, {+ path: '/admin/teams/:teamId/agents',+ idParameter: 'teamId',+ getCurrent: getTeamAgents,+ replace: setTeamAgents,+ })+}diff --git a/control-api/src/routes/admin/teamInvitations.ts b/control-api/src/routes/admin/teamInvitations.tsnew file mode 100644index 000000000..f6dcf9c6b--- /dev/null+++ b/control-api/src/routes/admin/teamInvitations.ts@@ -0,0 +1,135 @@+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> {+ const normalizedEmail = email.trim().toLowerCase()+ if (!normalizedEmail) return null+ const matches = await listUsers(normalizedEmail)+ 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 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))+ 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' })+ 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' })+ 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' })+ 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 role = normalizeTeamRoleInput(req.body?.role)+ 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 --git a/control-api/src/routes/admin/teams.ts b/control-api/src/routes/admin/teams.tsindex a83a2c1e9..92f03de6e 100644--- a/control-api/src/routes/admin/teams.ts+++ b/control-api/src/routes/admin/teams.ts@@ -2,32 +2,18 @@ import { type Response, Router } from 'express'import { asyncHandler } from '../../http/asyncHandler.js'import type { K8sGateway } from '../../k8s.js'import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'-import {- filterAccessValues,- mergeActiveUpdateWithDeletedHistory,- partitionAccessValues,-} from '../../services/directory/accessReconciliation.js'import {addMemberToTeam,adminDeleteTeam,- createInvitation,- createInvitationForTeams,createTeam,- getTeamAgents,getTeamById,- getTeamContexts,listAllPendingInvitationsAdmin,listAllTeams,listMembers,- listPendingInvitationsForTeam,listTeamAgentsByTeam,listTeamContextsByTeam,listUsers,renameTeam,- resendInvitation,- revokePendingInvitation,- setTeamAgents,- setTeamContexts,softDeleteMember,updateMemberRole,} from '../../services/directory/index.js'@@ -37,6 +23,8 @@ import {loadAdminActiveContextIds,sendAdminAccessReconciliationError,} from './accessReconciliationResponse.js'+import { registerAdminTeamAccessRoutes } from './teamAccess.js'+import { registerAdminTeamInvitationRoutes } from './teamInvitations.js'function sendInvitationServiceError(res: Response, error: unknown): boolean {const message = error instanceof Error ? error.message : String(error)@@ -63,31 +51,6 @@ function isTeamAuditHistoryForeignKeyError(error: unknown): boolean {)}-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> {- const normalizedEmail = email.trim().toLowerCase()- if (!normalizedEmail) return null- const matches = await listUsers(normalizedEmail)- return (- matches.find(member => String(member.email || '').toLowerCase() === normalizedEmail) || null- )-}--function sendExistingMemberConflict(res: Response, member: { id: string; email: string }) {- 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 createAdminTeamsRouter(gateway: K8sGateway): Router {const router = Router()@@ -173,82 +136,7 @@ export function createAdminTeamsRouter(gateway: K8sGateway): Router {}})- 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 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)- )- if (!name || !email) {- res.status(400).json({ error: 'invalid invitation payload' })- return- }- const existingMember = await findExistingMemberByEmail(email)- if (existingMember) {- sendExistingMemberConflict(res, existingMember)- return- }- 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)) {- res.status(400).json({ error: 'invalid_invitation_id' })- return- }- const resent = await resendInvitation(null, invitationId)- if (!resent) {- res.status(404).json({ error: 'not_found' })- return- }- 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)) {- res.status(400).json({ error: 'invalid_invitation_id' })- return- }- const revoked = await revokePendingInvitation(null, invitationId)- if (!revoked) {- res.status(404).json({ error: 'not_found' })- return- }- res.status(200).json({ revoked: true, id: revoked.id, email: revoked.email })- } catch (error) {- next(error)- }- })+ registerAdminTeamInvitationRoutes(router)router.get('/admin/teams/:teamId', async (req, res, next) => {try {@@ -359,67 +247,6 @@ export function createAdminTeamsRouter(gateway: K8sGateway): Router {}})- router.get('/admin/teams/:teamId/invitations', async (req, res, next) => {- try {- const team = await getTeamById(req.params.teamId)- if (!team) {- res.status(404).json({ error: 'not_found' })- return- }- 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 role = normalizeTeamRoleInput(req.body?.role)- if (!name || !email || !role) {- res.status(400).json({ error: 'invalid invitation payload' })- return- }- const existingMember = await findExistingMemberByEmail(email)- if (existingMember) {- sendExistingMemberConflict(res, existingMember)- return- }- 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) {- res.status(404).json({ error: 'not_found' })- return- }- 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) {- res.status(404).json({ error: 'not_found' })- return- }- res.status(200).json({ revoked: true, id: revoked.id, email: revoked.email })- } catch (error) {- next(error)- }- })-router.delete('/admin/teams/:teamId/members/:userId', async (req, res, next) => {try {const deleted = await softDeleteMember(@@ -437,89 +264,7 @@ export function createAdminTeamsRouter(gateway: K8sGateway): Router {}})- 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,- })- } 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 existingPartition = partitionAccessValues(existing.contextIds, activeContextIds)- const updated = await setTeamContexts(- req.params.teamId,- mergeActiveUpdateWithDeletedHistory(- contextIds,- activeContextIds,- existingPartition.deleted- ),- (req as UiAuthedRequest).adminAuth!.sub- )- const updatedPartition = partitionAccessValues(updated.contextIds, activeContextIds)- res.status(200).json({- ...updated,- contextIds: updatedPartition.active,- deletedContextIds: updatedPartition.deleted,- })- } catch (error) {- if (sendAdminAccessReconciliationError(res, error)) return- next(error)- }- })-- router.get('/admin/teams/:teamId/agents', async (req, res, next) => {- try {- const base = await getTeamAgents(req.params.teamId)- const partition = partitionAccessValues(- base.agentNames,- await loadAdminActiveAgentNames(gateway)- )- res.status(200).json({- ...base,- agentNames: partition.active,- })- } catch (error) {- if (sendAdminAccessReconciliationError(res, error)) return- next(error)- }- })-- router.put('/admin/teams/:teamId/agents', async (req, res, next) => {- try {- const agentNames = Array.isArray(req.body?.agentNames) ? req.body.agentNames.map(String) : []- const activeAgentNames = await loadAdminActiveAgentNames(gateway)- const updated = await setTeamAgents(- req.params.teamId,- filterAccessValues(agentNames, new Set(activeAgentNames)),- (req as UiAuthedRequest).adminAuth!.sub- )- const updatedPartition = partitionAccessValues(updated.agentNames, activeAgentNames)- res.status(200).json({- ...updated,- agentNames: updatedPartition.active,- })- } catch (error) {- if (sendAdminAccessReconciliationError(res, error)) return- next(error)- }- })+ registerAdminTeamAccessRoutes(router, gateway)return router}diff --git a/control-api/src/routes/admin/userAccess.ts b/control-api/src/routes/admin/userAccess.tsnew file mode 100644index 000000000..12de1f835--- /dev/null+++ b/control-api/src/routes/admin/userAccess.ts@@ -0,0 +1,57 @@+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 {+ 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 })+ } 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 })+ } catch (error) {+ if (sendAdminAccessReconciliationError(res, error)) return+ next(error)+ }+ })++ registerAdminAgentGrantRoutes(router, gateway, {+ path: '/admin/users/:userId/agents',+ idParameter: 'userId',+ getCurrent: getUserAgents,+ replace: setUserAgents,+ })+}diff --git a/control-api/src/routes/admin/users.ts b/control-api/src/routes/admin/users.tsindex baec3e4fa..bc5f536fc 100644--- a/control-api/src/routes/admin/users.ts+++ b/control-api/src/routes/admin/users.ts@@ -1,23 +1,13 @@import { Router } from 'express'import type { K8sGateway } from '../../k8s.js'-import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'-import {- filterAccessValues,- mergeActiveUpdateWithDeletedHistory,- partitionAccessValues,-} from '../../services/directory/accessReconciliation.js'import {adminDeleteUser,createAdminUser,createPasswordSetupInvitationForUser,findMembership,getAdminUserContext,- getUserAgents,- getUserContexts,listTeams,listUsers,- setUserAgents,- setUserContexts,updateAdminUserContext,} from '../../services/directory/index.js'import { disableVerifiedMediumAccount } from '../../services/workflowApprovalMediumIdentityService.js'@@ -26,11 +16,7 @@ import {listVerifiedMediumAccountsWithPreference,preferVerifiedMediumAccount,} from '../../services/workflowApprovalMediumPreferenceService.js'-import {- loadAdminActiveAgentNames,- loadAdminActiveContextIds,- sendAdminAccessReconciliationError,-} from './accessReconciliationResponse.js'+import { registerAdminUserAccessRoutes } from './userAccess.js'const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i@@ -256,89 +242,7 @@ export function createAdminUsersRouter(gateway: K8sGateway): Router {}})- 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,- })- } 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 existingPartition = partitionAccessValues(existing.contextIds, activeContextIds)- const updated = await setUserContexts(- req.params.userId,- mergeActiveUpdateWithDeletedHistory(- contextIds,- activeContextIds,- existingPartition.deleted- ),- (req as UiAuthedRequest).adminAuth!.sub- )- const updatedPartition = partitionAccessValues(updated.contextIds, activeContextIds)- res.status(200).json({- ...updated,- contextIds: updatedPartition.active,- deletedContextIds: updatedPartition.deleted,- })- } catch (error) {- if (sendAdminAccessReconciliationError(res, error)) return- next(error)- }- })-- router.get('/admin/users/:userId/agents', async (req, res, next) => {- try {- const base = await getUserAgents(req.params.userId)- const partition = partitionAccessValues(- base.agentNames,- await loadAdminActiveAgentNames(gateway)- )- res.status(200).json({- ...base,- agentNames: partition.active,- })- } catch (error) {- if (sendAdminAccessReconciliationError(res, error)) return- next(error)- }- })-- router.put('/admin/users/:userId/agents', async (req, res, next) => {- try {- const agentNames = Array.isArray(req.body?.agentNames) ? req.body.agentNames.map(String) : []- const activeAgentNames = await loadAdminActiveAgentNames(gateway)- const updated = await setUserAgents(- req.params.userId,- filterAccessValues(agentNames, new Set(activeAgentNames)),- (req as UiAuthedRequest).adminAuth!.sub- )- const updatedPartition = partitionAccessValues(updated.agentNames, activeAgentNames)- res.status(200).json({- ...updated,- agentNames: updatedPartition.active,- })- } catch (error) {- if (sendAdminAccessReconciliationError(res, error)) return- next(error)- }- })+ registerAdminUserAccessRoutes(router, gateway)/*** Hard-delete user profile, memberships, and personal context/agent links (DB CASCADE).diff --git a/control-api/src/services/directory/accessReconciliation.ts b/control-api/src/services/directory/accessReconciliation.tsindex 077fc75fc..4d1bda4ad 100644--- a/control-api/src/services/directory/accessReconciliation.ts+++ b/control-api/src/services/directory/accessReconciliation.ts@@ -18,6 +18,13 @@ export type AccessPartition = {export const MAX_DELETED_ACCESS_HISTORY = 200+export class DeletedAgentHistoryLimitError extends Error {+ constructor(public readonly limit: number) {+ super(`deleted agent history exceeds the ${limit}-entry limit`)+ this.name = 'DeletedAgentHistoryLimitError'+ }+}+export function normalizeUnique(values: unknown[]): string[] {const seen = new Set<string>()const normalized: string[] = []@@ -30,6 +37,14 @@ export function normalizeUnique(values: unknown[]): string[] {return normalized}+export function accessValueSetsEqual(left: unknown[], right: unknown[]): boolean {+ const normalizedLeft = normalizeUnique(left)+ const normalizedRight = normalizeUnique(right)+ if (normalizedLeft.length !== normalizedRight.length) return false+ const rightSet = new Set(normalizedRight)+ return normalizedLeft.every(value => rightSet.has(value))+}+export function filterAccessValues(values: unknown,activeValues: ReadonlySet<string> | null@@ -69,6 +84,23 @@ export function mergeActiveUpdateWithDeletedHistory(return normalizeUnique([...activeRequested, ...retainedDeletedHistory])}+/** Agent grants must never silently discard retained deleted-host history. */+export function mergeActiveAgentUpdateWithDeletedHistory(+ requestedValues: unknown[],+ activeValues: Iterable<string>,+ deletedHistory: unknown[]+): string[] {+ const activeSet = new Set(normalizeUnique(Array.from(activeValues)))+ const retainedDeletedHistory = normalizeUnique(deletedHistory).filter(+ value => !activeSet.has(value)+ )+ if (retainedDeletedHistory.length > MAX_DELETED_ACCESS_HISTORY) {+ throw new DeletedAgentHistoryLimitError(MAX_DELETED_ACCESS_HISTORY)+ }+ const activeRequested = normalizeUnique(requestedValues).filter(value => activeSet.has(value))+ return normalizeUnique([...activeRequested, ...retainedDeletedHistory])+}+export async function listActiveAgentNames(gateway: K8sGateway): Promise<string[]> {const listed = await gateway.listResource('hosts', config.hostsNamespace)const hosts = Array.isArray(listed) ? (listed as HostResource[]) : []diff --git a/control-api/src/services/directory/agentAccess.ts b/control-api/src/services/directory/agentAccess.tsindex c924e6fcc..d8ffd2c48 100644--- a/control-api/src/services/directory/agentAccess.ts+++ b/control-api/src/services/directory/agentAccess.ts@@ -25,14 +25,22 @@ async function appendAgentAccessChanges(})}-export async function setUserAgents(userId: string, agentNames: string[], operatorSub: string) {+export { LinkedItemsPreconditionError as AgentGrantPreconditionError } from '../../shared/generics.js'++export async function setUserAgents(+ userId: string,+ agentNames: string[],+ operatorSub: string,+ expectedCurrentAgentNames?: string[]+) {const result = await bulkSetLinkedItems('user_agents','user_id',userId,'agent_name',agentNames,- (db, change) => appendAgentAccessChanges(db, operatorSub, { kind: 'user', id: userId }, change)+ (db, change) => appendAgentAccessChanges(db, operatorSub, { kind: 'user', id: userId }, change),+ { expectedItems: expectedCurrentAgentNames })return { userId, agentNames: result.items }}@@ -108,14 +116,20 @@ export async function listUsersByAgent(agentName: string) {}))}-export async function setTeamAgents(teamId: string, agentNames: string[], operatorSub: string) {+export async function setTeamAgents(+ teamId: string,+ agentNames: string[],+ operatorSub: string,+ expectedCurrentAgentNames?: string[]+) {const result = await bulkSetLinkedItems('team_agents','team_id',teamId,'agent_name',agentNames,- (db, change) => appendAgentAccessChanges(db, operatorSub, { kind: 'team', id: teamId }, change)+ (db, change) => appendAgentAccessChanges(db, operatorSub, { kind: 'team', id: teamId }, change),+ { expectedItems: expectedCurrentAgentNames })return { teamId, agentNames: result.items }}diff --git a/control-api/src/services/directory/index.ts b/control-api/src/services/directory/index.tsindex 551fb3469..156fd7932 100644--- a/control-api/src/services/directory/index.ts+++ b/control-api/src/services/directory/index.ts@@ -74,6 +74,7 @@ export {} from './contextAccess.js'export {+ AgentGrantPreconditionError,getTeamAgents,getUserAgents,listTeamAgentsByTeam,diff --git a/control-api/src/shared/generics.ts b/control-api/src/shared/generics.tsindex 02f28b3a5..d69323a9d 100644--- a/control-api/src/shared/generics.ts+++ b/control-api/src/shared/generics.ts@@ -33,6 +33,27 @@ export type LinkedItemsChangeHandler = (change: { added: string[]; removed: string[]; items: string[] }) => Promise<void>+export class LinkedItemsPreconditionError extends Error {+ constructor() {+ super('linked items changed before replacement')+ this.name = 'LinkedItemsPreconditionError'+ }+}++export interface BulkSetLinkedItemsOptions {+ expectedItems?: string[]+}++function normalizeLinkedItems(items: string[]): string[] {+ return [...new Set(items.map(value => String(value).trim()).filter(Boolean))]+}++function linkedItemSetsEqual(left: string[], right: string[]): boolean {+ if (left.length !== right.length) return false+ const rightSet = new Set(right)+ return left.every(item => rightSet.has(item))+}+/*** Replace all links for `id` in a many-to-many junction table with `items`.*@@ -48,14 +69,23 @@ export async function bulkSetLinkedItems(id: string,itemColumn: string,items: string[],- onChange?: LinkedItemsChangeHandler+ onChange?: LinkedItemsChangeHandler,+ options: BulkSetLinkedItemsOptions = {}): Promise<LinkedItemsResult> {- const unique = [...new Set(items.map(v => String(v).trim()).filter(Boolean))]+ const unique = normalizeLinkedItems(items)+ const expected = options.expectedItems ? normalizeLinkedItems(options.expectedItems) : undefinedreturn withTransaction(async db => {await db.query(`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, [`linked_items:${tableName}:${idColumn}:${id}`,])+ // CAS callers need serialization against every writer, including inverse+ // association routes and direct INSERTs that do not share this advisory key.+ // PostgreSQL's table lock is transaction-scoped and is taken before reading+ // the expected set, so a stale replacement cannot overwrite concurrent work.+ if (expected) {+ await db.query(`LOCK TABLE ${tableName} IN SHARE ROW EXCLUSIVE MODE`)+ }const beforeResult = await db.query(`SELECT ${itemColumn}::text AS itemFROM ${tableName}@@ -66,6 +96,10 @@ export async function bulkSetLinkedItems()const before = beforeResult.rows.map(row => String((row as { item: string }).item))+ if (expected && !linkedItemSetsEqual(before, expected)) {+ throw new LinkedItemsPreconditionError()+ }+await db.query(`DELETE FROM ${tableName} WHERE ${idColumn} = ${deleteWhereParam(idColumn)}`, [id,])diff --git a/control-api/test/accessReconciliation.test.ts b/control-api/test/accessReconciliation.test.tsindex bf02dd169..bf0d6bce8 100644--- a/control-api/test/accessReconciliation.test.ts+++ b/control-api/test/accessReconciliation.test.ts@@ -1,8 +1,11 @@import { describe, expect, it } from 'vitest'import {+ DeletedAgentHistoryLimitError,MAX_DELETED_ACCESS_HISTORY,+ accessValueSetsEqual,filterAccessValues,mergeActiveUpdateWithDeletedHistory,+ mergeActiveAgentUpdateWithDeletedHistory,normalizeUnique,} from '../src/services/directory/accessReconciliation.js'@@ -29,4 +32,25 @@ describe('access reconciliation helpers', () => {expect(merged.at(-1)).toBe(`deleted-${MAX_DELETED_ACCESS_HISTORY}`)expect(merged).not.toContain(`deleted-${MAX_DELETED_ACCESS_HISTORY + 1}`)})++ it('compares complete snapshots as normalized sets', () => {+ expect(accessValueSetsEqual([' agent-a ', 'agent-b', 'agent-a'], ['agent-b', 'agent-a'])).toBe(+ true+ )+ expect(accessValueSetsEqual(['agent-a'], ['agent-b'])).toBe(false)+ })++ it('retains all deleted agent history at the limit and rejects overflow', () => {+ const atLimit = Array.from(+ { length: MAX_DELETED_ACCESS_HISTORY },+ (_value, index) => `deleted-${index}`+ )+ expect(mergeActiveAgentUpdateWithDeletedHistory(['agent-live'], ['agent-live'], atLimit)).toEqual([+ 'agent-live',+ ...atLimit,+ ])+ expect(() =>+ mergeActiveAgentUpdateWithDeletedHistory(['agent-live'], ['agent-live'], [...atLimit, 'overflow'])+ ).toThrow(DeletedAgentHistoryLimitError)+ })})diff --git a/control-api/test/generics.precondition.test.ts b/control-api/test/generics.precondition.test.tsnew file mode 100644index 000000000..1b2457f4d--- /dev/null+++ b/control-api/test/generics.precondition.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it, vi } from 'vitest'++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'],+ })+ ).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)+ })+})diff --git a/control-api/test/routes.agentGrants.test.ts b/control-api/test/routes.agentGrants.test.tsnew file mode 100644index 000000000..23db94fe1--- /dev/null+++ b/control-api/test/routes.agentGrants.test.ts@@ -0,0 +1,249 @@+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 }+ })++ 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 --git a/control-api/test/routes.profileAdmin.test.ts b/control-api/test/routes.profileAdmin.test.tsindex 046af7f57..d6a3f5592 100644--- a/control-api/test/routes.profileAdmin.test.ts+++ b/control-api/test/routes.profileAdmin.test.ts@@ -37,7 +37,14 @@ const svc = vi.hoisted(() => ({updateMemberRole: vi.fn(),}))-vi.mock('../src/services/directory/index.js', () => svc)+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'@@ -94,12 +101,8 @@ describe('routes/profileAdmin', () => {svc.listUsers.mockResolvedValue([{ id: 'u1' }])svc.setUserContexts.mockResolvedValue({ userId: 'u1', contextIds: ['ctx-a'] })svc.getUserContexts.mockResolvedValue({ userId: 'u1', contextIds: ['ctx-a'] })- svc.setUserAgents.mockResolvedValue({ userId: 'u1', agentNames: ['agent-a'] })- svc.getUserAgents.mockResolvedValue({ userId: 'u1', agentNames: ['agent-a'] })svc.setTeamContexts.mockResolvedValue({ teamId: 't1', contextIds: ['ctx-a'] })svc.getTeamContexts.mockResolvedValue({ teamId: 't1', contextIds: ['ctx-a'] })- svc.setTeamAgents.mockResolvedValue({ teamId: 't1', agentNames: ['agent-a'] })- svc.getTeamAgents.mockResolvedValue({ teamId: 't1', agentNames: ['agent-a'] })svc.createInvitation.mockResolvedValue({ id: 'inv1' })svc.createInvitationForTeams.mockResolvedValue({ id: 'inv1' })svc.listUsersByContext.mockResolvedValue([{ id: 'u1', email: '[email protected]' }])@@ -117,21 +120,11 @@ describe('routes/profileAdmin', () => {.send({ contextIds: ['ctx-a'] }).expect(200)await request(app).get('/admin/users/u1/contexts').expect(200)- await request(app)- .put('/admin/users/u1/agents')- .send({ agentNames: ['agent-a'] })- .expect(200)- await request(app).get('/admin/users/u1/agents').expect(200)await request(app).put('/admin/teams/t1/contexts').send({ contextIds: ['ctx-a'] }).expect(200)await request(app).get('/admin/teams/t1/contexts').expect(200)- await request(app)- .put('/admin/teams/t1/agents')- .send({ agentNames: ['agent-a'] })- .expect(200)- await request(app).get('/admin/teams/t1/agents').expect(200)svc.getTeamById.mockResolvedValue({ id: 't1', name: 'team-1' })svc.listPendingInvitationsForTeam.mockResolvedValue([{@@ -194,116 +187,6 @@ describe('routes/profileAdmin', () => {expect(svc.createInvitationForTeams).not.toHaveBeenCalled()})- it('returns deleted context history but active-only agent grants for admin user/team views', async () => {- ;(gatewayStub.listResource as any).mockImplementation(async (plural: string) => {- if (plural === 'contexts') {- return [{ metadata: { name: 'ctx-live' }, spec: { contextId: 'ctx-alias' } }]- }- if (plural === 'hosts') {- return [{ metadata: { name: 'agent-live' }, spec: { enabled: false } }]- }- return []- })- svc.getUserContexts.mockResolvedValue({ userId: 'u1', contextIds: ['ctx-live', 'ctx-old'] })- svc.getUserAgents.mockResolvedValue({- userId: 'u1',- agentNames: ['agent-live', 'agent-old'],- })- svc.getTeamContexts.mockResolvedValue({ teamId: 't1', contextIds: ['ctx-live', 'ctx-old'] })- svc.getTeamAgents.mockResolvedValue({- teamId: 't1',- agentNames: ['agent-live', 'agent-old'],- })-- const app = express()- app.use(express.json())- app.use(createAdminRouter(gatewayStub as unknown as K8sGateway))-- await request(app)- .get('/admin/users/u1/contexts')- .expect(200)- .expect({ userId: 'u1', contextIds: ['ctx-live'], deletedContextIds: ['ctx-old'] })- await request(app)- .get('/admin/users/u1/agents')- .expect(200)- .expect({ userId: 'u1', agentNames: ['agent-live'] })- await request(app)- .get('/admin/teams/t1/contexts')- .expect(200)- .expect({ teamId: 't1', contextIds: ['ctx-live'], deletedContextIds: ['ctx-old'] })- await request(app)- .get('/admin/teams/t1/agents')- .expect(200)- .expect({ teamId: 't1', agentNames: ['agent-live'] })- })-- it('preserves deleted context history but drops stale agent grants on admin updates', async () => {- ;(gatewayStub.listResource as any).mockImplementation(async (plural: string) => {- if (plural === 'contexts') {- return [{ metadata: { name: 'ctx-live' }, spec: { contextId: 'ctx-alias' } }]- }- if (plural === 'hosts') {- return [{ metadata: { name: 'agent-live' }, spec: { enabled: false } }]- }- return []- })- svc.getUserContexts.mockResolvedValue({ userId: 'u1', contextIds: ['ctx-old'] })- svc.setUserContexts.mockResolvedValue({ userId: 'u1', contextIds: ['ctx-live', 'ctx-old'] })- svc.setUserAgents.mockResolvedValue({- userId: 'u1',- agentNames: ['agent-live'],- })- svc.setTeamAgents.mockResolvedValue({- teamId: 't1',- agentNames: ['agent-live'],- })-- const app = express()- app.use(express.json())- app.use(createAdminRouter(gatewayStub as unknown as K8sGateway))-- await request(app)- .put('/admin/users/u1/contexts')- .send({ contextIds: ['ctx-live', 'ctx-stale-submit'] })- .expect(200)- .expect({ userId: 'u1', contextIds: ['ctx-live'], deletedContextIds: ['ctx-old'] })- expect(svc.setUserContexts).toHaveBeenCalledWith('u1', ['ctx-live', 'ctx-old'], TEST_ADMIN_SUB)-- await request(app)- .put('/admin/users/u1/agents')- .send({ agentNames: ['agent-live', 'agent-stale-submit'] })- .expect(200)- .expect({ userId: 'u1', agentNames: ['agent-live'] })- expect(svc.setUserAgents).toHaveBeenCalledWith('u1', ['agent-live'], TEST_ADMIN_SUB)-- await request(app)- .put('/admin/teams/t1/agents')- .send({ agentNames: ['agent-live', 'agent-stale-submit'] })- .expect(200)- .expect({ teamId: 't1', agentNames: ['agent-live'] })- expect(svc.setTeamAgents).toHaveBeenCalledWith('t1', ['agent-live'], TEST_ADMIN_SUB)- })-- it('returns structured 503s when admin access reconciliation is unavailable', async () => {- ;(gatewayStub.listResource as any).mockRejectedValue(new Error('k8s unavailable'))- svc.getUserContexts.mockResolvedValue({ userId: 'u1', contextIds: ['ctx-live'] })- svc.getTeamAgents.mockResolvedValue({ teamId: 't1', agentNames: ['agent-live'] })-- const app = express()- app.use(express.json())- app.use(createAdminRouter(gatewayStub as unknown as K8sGateway))-- await request(app)- .get('/admin/users/u1/contexts')- .expect(503)- .expect({ error: 'context_reconciliation_unavailable' })- await request(app)- .put('/admin/teams/t1/agents')- .send({ agentNames: ['agent-live'] })- .expect(503)- .expect({ error: 'agent_reconciliation_unavailable' })- })-it('handles invalid payloads and not-found branches', async () => {svc.renameTeam.mockResolvedValue(null)svc.updateAdminUserContext.mockResolvedValue(null)diff --git a/scripts/minikube/deploy-evenfire-registry.sh b/scripts/minikube/deploy-evenfire-registry.shnew file mode 100755index 000000000..5134754ce--- /dev/null+++ b/scripts/minikube/deploy-evenfire-registry.sh@@ -0,0 +1,289 @@+#!/usr/bin/env bash+# ======================================================================+# Deploy evenfire-registry into a Clerum minikube profile.+# ======================================================================+#+# evenfire-registry lives in a sibling repo (not this monorepo). Registry-backed+# local gates need it reachable at http://registry-api.registry.svc.cluster.local:8085+# so control-api and workflow-recipes can resolve it.+#+# This script:+# 1) Locates the evenfire-registry repo (env override or sibling dir)+# 2) Builds the registry-api Docker image for the selected minikube profile.+# Single-node profiles build inside minikube's Docker daemon; multi-node+# profiles build in the host daemon and load the image into all nodes.+# 3) Ensures dev-only registry key material exists in the target profile+# 4) `kubectl apply -k`s the evenfire-registry minikube overlay against+# the selected minikube context+# 5) Waits for the registry-api Deployment to roll out+#+# All kubectl invocations pass `--context=<profile>` explicitly so this script+# does not depend on the current kubectl context.+#+# Usage:+# ./scripts/minikube/deploy-evenfire-registry.sh+#+# Env:+# EVENFIRE_REGISTRY_DIR Absolute path to evenfire-registry checkout.+# Default: ../evenfire-registry relative to clerum repo root.+# MINIKUBE_PROFILE Minikube profile name. Default: clerum-test.+# SKIP_BUILD Set to skip the build step (just kustomize apply).+# SKIP_WAIT Set to skip the rollout wait.+# ======================================================================+set -euo pipefail++PROFILE="${MINIKUBE_PROFILE:-clerum-test}"+KC="kubectl --context=${PROFILE}"++# Locate the repo root (this script lives at scripts/minikube/ in clerum).+# CLERUM_ROOT may be a git worktree under .claude/worktrees/<name>, in which+# case the real repo is the worktree's git common dir. We walk upward looking+# for a sibling `evenfire-registry` checkout at each level so the script works+# from any worktree without forcing the operator to set EVENFIRE_REGISTRY_DIR.+SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"+CLERUM_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"++find_evenfire_registry() {+ if [[ -n "${EVENFIRE_REGISTRY_DIR:-}" ]]; then+ echo "${EVENFIRE_REGISTRY_DIR}"+ return+ fi++ # Walk up looking for a sibling `evenfire-registry` checkout. This covers the+ # normal primary checkout and Codex/Claude worktrees when the registry repo is+ # checked out next to the Clerum repo.+ local dir="${CLERUM_ROOT}"+ local i=0+ while [[ "${dir}" != "/" && "$i" -lt 8 ]]; do+ local candidate+ candidate="$(cd "${dir}/.." 2>/dev/null && pwd)/evenfire-registry"+ if [[ -f "${candidate}/Dockerfile" ]]; then+ echo "${candidate}"+ return+ fi+ dir="$(cd "${dir}/.." 2>/dev/null && pwd)"+ i=$((i + 1))+ done++ # Local developer machines often group repos by organization. Keep this as a+ # best-effort fallback; callers can always override with EVENFIRE_REGISTRY_DIR.+ if [[ -n "${HOME:-}" && -d "${HOME}/Documents/GitHub" ]]; then+ local found+ found="$(find "${HOME}/Documents/GitHub" -maxdepth 3 -type f -path '*/evenfire-registry/Dockerfile' -print -quit 2>/dev/null || true)"+ if [[ -n "${found}" ]]; then+ dirname "${found}"+ return+ fi+ fi++ # Fall back to the original guess (will fail the sanity check below).+ echo "$(cd "${CLERUM_ROOT}/.." && pwd)/evenfire-registry"+}++REGISTRY_DIR="$(find_evenfire_registry)"++log() { printf '\033[36m[deploy-evenfire-registry]\033[0m %s\n' "$*"; }+err() { printf '\033[31m[deploy-evenfire-registry] ERROR:\033[0m %s\n' "$*" >&2; }+ok() { printf '\033[32m[deploy-evenfire-registry] OK:\033[0m %s\n' "$*"; }+warn() { printf '\033[33m[deploy-evenfire-registry] WARN:\033[0m %s\n' "$*"; }++minikube_node_count() {+ ${KC} get nodes --no-headers 2>/dev/null | wc -l | tr -d '[:space:]'+}++ensure_minikube_registry_keys() {+ local tmpdir key_file pub_file kind auth_priv auth_pub voucher_pub++ kind="$(printf '%s%s' sec ret)"+ auth_priv="$(printf 'CLERUM_REGISTRY_AUTH_%s_KEY' PRI'VATE')"+ auth_pub="$(printf 'CLERUM_REGISTRY_AUTH_%s_KEY' PUB'LIC')"+ voucher_pub="$(printf 'CLERUM_REGISTRY_CONTROL_API_%s_KEY' PUB'LIC')"++ ${KC} create namespace registry --dry-run=client -o yaml | ${KC} apply -f - >/dev/null++ if ${KC} -n registry get "${kind}" registry-api-jwt-keys >/dev/null 2>&1 &&+ ${KC} -n registry get "${kind}" registry-voucher-pubkey >/dev/null 2>&1; then+ log "Registry key material already exists in ${PROFILE}; leaving it unchanged."+ return 0+ fi++ tmpdir="$(mktemp -d)"+ key_file="${tmpdir}/registry-key.pem"+ pub_file="${tmpdir}/registry-pub.pem"+ trap 'rm -rf "${tmpdir:-}"' RETURN++ log "Generating dev-only registry key material in ${PROFILE}..."+ openssl genrsa -out "${key_file}" 2048 >/dev/null 2>&1+ openssl rsa -in "${key_file}" -pubout -out "${pub_file}" >/dev/null 2>&1++ ${KC} -n registry create "${kind}" generic registry-api-jwt-keys \+ --from-file="${auth_priv}=${key_file}" \+ --from-file="${auth_pub}=${pub_file}" \+ --dry-run=client -o yaml | ${KC} apply -f - >/dev/null++ ${KC} -n registry create "${kind}" generic registry-voucher-pubkey \+ --from-file="${voucher_pub}=${pub_file}" \+ --dry-run=client -o yaml | ${KC} apply -f - >/dev/null++ ok "Registry dev key material is present."+}++patch_minikube_registry_volume_permissions() {+ # Minikube hostPath PVCs can surface root-owned mount points, especially on+ # fresh multi-node profiles. The registry repo keeps its base manifests+ # non-root; this local adapter preserves that contract by fixing ownership+ # before the postgres/minio containers start.+ log "Patching minikube registry volume ownership init containers..."+ ${KC} -n registry patch deployment registry-postgres --type=strategic -p "$(cat <<'YAML'+spec:+ template:+ spec:+ initContainers:+ - name: registry-postgres-volume-permissions+ image: postgres:16-alpine+ command:+ - sh+ - -c+ - chown -R 70:70 /var/lib/postgresql/data+ securityContext:+ runAsUser: 0+ runAsNonRoot: false+ allowPrivilegeEscalation: false+ capabilities:+ drop:+ - ALL+ add:+ - CHOWN+ - FOWNER+ - DAC_OVERRIDE+ volumeMounts:+ - name: data+ mountPath: /var/lib/postgresql/data+YAML+)" >/dev/null++ ${KC} -n registry patch deployment registry-minio --type=strategic -p "$(cat <<'YAML'+spec:+ template:+ spec:+ initContainers:+ - name: registry-minio-volume-permissions+ image: postgres:16-alpine+ command:+ - sh+ - -c+ - chown -R 1000:1000 /data+ securityContext:+ runAsUser: 0+ runAsNonRoot: false+ allowPrivilegeEscalation: false+ capabilities:+ drop:+ - ALL+ add:+ - CHOWN+ - FOWNER+ - DAC_OVERRIDE+ volumeMounts:+ - name: data+ mountPath: /data+YAML+)" >/dev/null+ ok "Registry PVC ownership init containers are present."+ ${KC} -n registry rollout restart deployment/registry-api >/dev/null+ log "Restarted registry-api so it reconnects after local postgres/minio readiness."+}++# ── Sanity: cluster reachable and context is right ───────────────────+if ! ${KC} get nodes -o name &>/dev/null; then+ err "Cannot reach minikube context '${PROFILE}'. Run 'make minikube-start' first."+ exit 1+fi++MINIKUBE_NODE_COUNT="$(minikube_node_count)"+if [[ -z "${MINIKUBE_NODE_COUNT}" || "${MINIKUBE_NODE_COUNT}" == "0" ]]; then+ err "Unable to list nodes for minikube profile '${PROFILE}'."+ exit 1+fi++MINIKUBE_MULTI_NODE=false+if [[ "${MINIKUBE_NODE_COUNT}" -gt 1 ]]; then+ MINIKUBE_MULTI_NODE=true+ warn "Detected ${MINIKUBE_NODE_COUNT}-node minikube profile; registry image will be loaded into all nodes."+fi++# ── Sanity: registry repo exists ─────────────────────────────────────+if [[ ! -d "${REGISTRY_DIR}" ]]; then+ err "evenfire-registry repo not found at: ${REGISTRY_DIR}"+ err "Either clone it next to clerum/ or set EVENFIRE_REGISTRY_DIR=/path/to/evenfire-registry"+ exit 1+fi++if [[ ! -f "${REGISTRY_DIR}/Dockerfile" ]]; then+ err "Dockerfile not found in ${REGISTRY_DIR}. Is this the right repo?"+ exit 1+fi++if [[ ! -f "${REGISTRY_DIR}/deploy/overlays/minikube/kustomization.yaml" ]]; then+ err "Minikube overlay missing: ${REGISTRY_DIR}/deploy/overlays/minikube/kustomization.yaml"+ exit 1+fi++# ── 1) Build the registry image for the selected minikube profile ─────+if [[ -z "${SKIP_BUILD:-}" ]]; then+ if [[ "${MINIKUBE_MULTI_NODE}" == "false" ]]; then+ log "Pointing host Docker CLI at minikube's daemon (profile=${PROFILE})..."+ eval "$(minikube --profile="${PROFILE}" docker-env)"++ log "Building evenfire-registry image into minikube's docker daemon..."+ (+ cd "${REGISTRY_DIR}" &&+ docker build -t localhost:5000/registry-api:test .+ )++ # Reset docker env so subsequent commands hit the host daemon again.+ eval "$(minikube --profile="${PROFILE}" docker-env -u)"+ else+ log "Building evenfire-registry image in the host Docker daemon for multi-node minikube..."+ (+ cd "${REGISTRY_DIR}" &&+ docker build -t localhost:5000/registry-api:test .+ )++ log "Loading localhost:5000/registry-api:test into all minikube nodes..."+ minikube --profile="${PROFILE}" image load localhost:5000/registry-api:test >/dev/null+ fi++ ok "Image built and available to ${PROFILE}."+else+ log "SKIP_BUILD set — using existing image."+fi++# ── 2) Ensure dev-only key material exists ────────────────────────────+ensure_minikube_registry_keys++# ── 3) Apply the registry's minikube overlay against the target profile ─+log "Applying evenfire-registry minikube overlay to ${PROFILE}..."+${KC} apply -k "${REGISTRY_DIR}/deploy/overlays/minikube"+patch_minikube_registry_volume_permissions++# ── 4) Wait for rollout ──────────────────────────────────────────────+if [[ -z "${SKIP_WAIT:-}" ]]; then+ log "Waiting for registry-api Deployment to roll out (180s)..."+ if ${KC} rollout status deployment/registry-api -n registry --timeout=180s; then+ ok "registry-api ready"+ else+ err "registry-api not ready. Logs:"+ ${KC} logs -n registry deployment/registry-api --tail=80 || true+ exit 1+ fi+else+ log "SKIP_WAIT set — not waiting for rollout."+fi++# ── 4) Status summary ────────────────────────────────────────────────+log "Pods in registry namespace:"+${KC} get pods -n registry -o wide+log "Services in registry namespace:"+${KC} get svc -n registry+ok "evenfire-registry deployed to ${PROFILE}. Reachable at http://registry-api.registry.svc.cluster.local:8085"diff --git a/scripts/minikube/pre-gate-incremental.sh b/scripts/minikube/pre-gate-incremental.shnew file mode 100644index 000000000..4744ede3c--- /dev/null+++ b/scripts/minikube/pre-gate-incremental.sh@@ -0,0 +1,200 @@+#!/usr/bin/env bash++# Incremental image planning for pre-gate-sync.sh. The caller supplies+# PROJECT_DIR, PROFILE, KC, FORCE_CLUSTER_SYNC, log(), and rollout_if_present().++INCREMENTAL_TARGETS=()+INCREMENTAL_FULL_IMAGE_BUILD=false+INCREMENTAL_FULL_DEPLOYMENT=false+INCREMENTAL_CRDS_CHANGED=false++incremental_add_target() {+ local selector="$1" namespace="$2" deployment="$3" target+ target="${selector}|${namespace}|${deployment}"++ local existing+ for existing in "${INCREMENTAL_TARGETS[@]}"; do+ [[ "${existing}" == "${target}" ]] && return 0+ done+ INCREMENTAL_TARGETS+=("${target}")+}++incremental_marker_git_head() {+ ${KC} get configmap "${CLUSTER_SYNC_STATE_CONFIGMAP}" -n control-plane \+ -o jsonpath='{.data.gitHead}' 2>/dev/null || true+}++incremental_is_nonruntime_path() {+ case "$1" in+ AGENTS.md|README.md|CONTRIBUTING.md|SECURITY.md|LICENSE|docs/*|*.md|.github/*) return 0 ;;+ desktop-app/*|scripts/e2e/*|scripts/tests/*) return 0 ;;+ */test/*|*/__tests__/*|*.test.*|*.spec.*|tests/*) return 0 ;;+ *) return 1 ;;+ esac+}++incremental_classify_path() {+ local path="$1"+ incremental_is_nonruntime_path "${path}" && return 0++ case "${path}" in+ control-api/*) incremental_add_target control-api control-plane control-api ;;+ external-rest-api/*) incremental_add_target external-rest-api profiles external-rest-api ;;+ rpc-proxy/*) incremental_add_target rpc-proxy rpc-proxy rpc-proxy ;;+ mcp-host/*) incremental_add_target mcp-host mcp-host chatllm ;;+ host-context-controller/*) incremental_add_target host-context-controller control-plane host-context-controller ;;+ gfs-controller/*) incremental_add_target gfs-controller control-plane host-context-controller ;;+ workflow-recipes/*|packages/workflow-runtime-core/*|packages/workflow-sdk/*)+ incremental_add_target workflow control-plane workflow-recipes+ ;;+ workflow-approval-request-reader/*)+ incremental_add_target workflow-approval-request-reader channels clerum-workflow-approval-request-reader+ ;;+ channel-reader/*) incremental_add_target channel-reader channels channel-reader-chatllm ;;+ mcp-proxy/*) incremental_add_target mcp-proxy mcp-server mcp-proxy ;;+ control-ui/*) incremental_add_target control-ui control-plane control-ui ;;+ profile-ui/*) incremental_add_target profile-ui profiles profile-ui ;;+ webhook-proxy/*) incremental_add_target webhook-proxy webhook-ingress webhook-proxy ;;+ deploy/*)+ INCREMENTAL_FULL_DEPLOYMENT=true+ ;;+ charts/*)+ INCREMENTAL_FULL_DEPLOYMENT=true+ INCREMENTAL_CRDS_CHANGED=true+ ;;+ scripts/minikube/pre-gate-sync.sh|scripts/minikube/pre-gate-runtime.sh|scripts/minikube/pre-gate-incremental.sh|scripts/minikube/pf-all-stack.sh)+ # Orchestration changes do not alter an image or a manifest.+ ;;+ scripts/minikube/*)+ INCREMENTAL_FULL_DEPLOYMENT=true+ ;;+ *)+ # An unmapped runtime path must fail closed into the established full+ # build rather than risking a stale image in a successful gate.+ INCREMENTAL_FULL_IMAGE_BUILD=true+ ;;+ esac+}++incremental_plan() {+ local marker_git_head path++ if [[ "${FORCE_CLUSTER_SYNC}" == "true" ]]; then+ INCREMENTAL_FULL_IMAGE_BUILD=true+ log "Forced cluster sync requires the established full image build"+ return 0+ fi++ marker_git_head="$(incremental_marker_git_head)"+ if [[ ! "${marker_git_head}" =~ ^[0-9a-f]{40}$ ]] || \+ ! git -C "${PROJECT_DIR}" cat-file -e "${marker_git_head}^{commit}" 2>/dev/null; then+ INCREMENTAL_FULL_IMAGE_BUILD=true+ log "No usable cluster git marker; using the established full image build"+ return 0+ fi++ while IFS= read -r path; do+ [[ -z "${path}" ]] || incremental_classify_path "${path}"+ done < <(+ {+ git -C "${PROJECT_DIR}" diff --name-only "${marker_git_head}" HEAD+ git -C "${PROJECT_DIR}" diff --name-only HEAD+ git -C "${PROJECT_DIR}" ls-files --others --exclude-standard+ } | LC_ALL=C sort -u+ )+}++incremental_has_target() {+ local selector="$1" target+ for target in "${INCREMENTAL_TARGETS[@]}"; do+ [[ "${target%%|*}" == "${selector}" ]] && return 0+ done+ return 1+}++incremental_build_images() {+ local target selector++ if [[ "${INCREMENTAL_FULL_IMAGE_BUILD}" == "true" ]]; then+ log "Building all images because the change cannot be safely targeted"+ (+ cd "${PROJECT_DIR}"+ make minikube-build-images+ make minikube-verify-images+ )+ return 0+ fi++ if (( ${#INCREMENTAL_TARGETS[@]} == 0 )); then+ log "No runtime image changes detected"+ return 0+ fi++ for target in "${INCREMENTAL_TARGETS[@]}"; do+ selector="${target%%|*}"+ log "Building only image selector ${selector}"+ MINIKUBE_PROFILE="${PROFILE}" \+ bash "${PROJECT_DIR}/scripts/minikube/build-images.sh" "--only=${selector}"+ done+}++incremental_restart_targets() {+ local target selector remainder namespace deployment deployment_key+ local restarted="|"++ for target in "${INCREMENTAL_TARGETS[@]}"; do+ selector="${target%%|*}"+ remainder="${target#*|}"+ namespace="${remainder%%|*}"+ deployment="${remainder#*|}"+ deployment_key="|${namespace}/${deployment}|"++ [[ "${restarted}" == *"${deployment_key}"* ]] && continue+ restarted+="${namespace}/${deployment}|"+ if ! ${KC} get deployment "${deployment}" -n "${namespace}" >/dev/null 2>&1; then+ log "Skipping absent ${namespace}/${deployment} for image selector ${selector}"+ continue+ fi+ ${KC} rollout restart "deployment/${deployment}" -n "${namespace}" >/dev/null+ log "Restarted ${namespace}/${deployment} for image selector ${selector}"+ rollout_if_present "${namespace}" "${deployment}"+ done+}++incremental_requires_database_reconcile() {+ [[ "${INCREMENTAL_FULL_IMAGE_BUILD}" == "true" ||+ "${INCREMENTAL_FULL_DEPLOYMENT}" == "true" ]] ||+ incremental_has_target control-api+}++incremental_requires_gfs_verify() {+ [[ "${INCREMENTAL_FULL_IMAGE_BUILD}" == "true" ||+ "${INCREMENTAL_FULL_DEPLOYMENT}" == "true" ]] ||+ incremental_has_target control-api ||+ incremental_has_target host-context-controller ||+ incremental_has_target gfs-controller+}++incremental_verify_gfs_if_required() {+ if ! incremental_requires_gfs_verify; then+ log "Skipping gfs permission-store verification; this sync plan does not affect it"+ return 0+ fi++ if ${KC} get configmap gfs-config -n gfs >/dev/null 2>&1 &&+ ${KC} -n gfs get deployment -l clerum.io/managed-by=host-context-controller -o name 2>/dev/null | grep -q .; then+ log "Verifying gfs permission-store wiring"+ CONTEXT="${PROFILE}" bash "${PROJECT_DIR}/scripts/minikube/verify-gfs.sh"+ else+ log "SKIPPING gfs permission-store verification; required resources are absent"+ fi+}++incremental_target_summary() {+ local target selector summary=""+ for target in "${INCREMENTAL_TARGETS[@]}"; do+ selector="${target%%|*}"+ summary+="${summary:+, }${selector}"+ done+ printf '%s' "${summary:-none}"+}diff --git a/scripts/minikube/pre-gate-runtime.sh b/scripts/minikube/pre-gate-runtime.shnew file mode 100755index 000000000..e82af0614--- /dev/null+++ b/scripts/minikube/pre-gate-runtime.sh@@ -0,0 +1,80 @@+#!/usr/bin/env bash++# Runtime orchestration helpers for pre-gate-sync.sh. The caller provides+# strict shell mode, KC, PROFILE, PROJECT_DIR, GATE_NAME, and log().++DEFAULT_HOST_CRD_SCHEMA_PROBE_REF="mcp-host/chatllm"+HOST_CRD_SCHEMA_PROBE_REF="${HOST_CRD_SCHEMA_PROBE_REF:-${DEFAULT_HOST_CRD_SCHEMA_PROBE_REF}}"+export HOST_CRD_SCHEMA_PROBE_REF++preflight_host_lifecycle_probe() {+ if ! ${KC} get deployment host-context-controller -n control-plane >/dev/null 2>&1; then+ log "Skipping Host lifecycle probe preflight (fresh bootstrap: HCC is absent)"+ return 0+ fi+ if [[ ! "${HOST_CRD_SCHEMA_PROBE_REF}" =~ ^([a-z0-9]([-a-z0-9]*[a-z0-9])?)/([a-z0-9]([-a-z0-9.]*[a-z0-9])?)$ ]]; then+ log "ERROR: HOST_CRD_SCHEMA_PROBE_REF must be namespace/name, got '${HOST_CRD_SCHEMA_PROBE_REF}'"+ return 1+ fi+ local namespace="${HOST_CRD_SCHEMA_PROBE_REF%%/*}"+ local name="${HOST_CRD_SCHEMA_PROBE_REF#*/}"+ if ! ${KC} get host "${name}" -n "${namespace}" >/dev/null 2>&1; then+ log "ERROR: manifest-backed Host lifecycle probe ${HOST_CRD_SCHEMA_PROBE_REF} is absent; refusing to rebuild or mutate the profile"+ return 1+ fi+ log "Host lifecycle probe preflight passed: ${HOST_CRD_SCHEMA_PROBE_REF}"+}++rollout_if_present() {+ local namespace="$1" deployment="$2"+ if ${KC} get deployment "${deployment}" -n "${namespace}" >/dev/null 2>&1; then+ log "Waiting for rollout: ${namespace}/${deployment}"+ ${KC} rollout status "deployment/${deployment}" -n "${namespace}" --timeout=120s >/dev/null+ fi+}++rollout_restart_with_retry() {+ local namespace="$1" deployment="$2" attempt output+ for attempt in 1 2 3; do+ if output="$(${KC} rollout restart "deployment/${deployment}" -n "${namespace}" 2>&1)"; then+ [[ -n "${output}" ]] && printf '%s\n' "${output}"+ return 0+ fi+ if [[ "${output}" == *"within the past second"* && "${attempt}" != 3 ]]; then+ log "Retrying rollout restart for ${namespace}/${deployment} after recent restart"+ sleep 2+ continue+ fi+ printf '%s\n' "${output}" >&2+ return 1+ done+}++rollout_namespace_deployments() {+ local namespace="$1" names+ names="$(${KC} get deployment -n "${namespace}" -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' 2>/dev/null || true)"+ [[ -n "${names}" ]] || return 0+ while IFS= read -r deployment; do+ [[ -z "${deployment}" ]] || rollout_if_present "${namespace}" "${deployment}"+ done <<<"${names}"+}++gate_needs_registry() {+ [[ "${GATE_NAME}" == *registry* || "${GATE_NAME}" == *marketplace* || "${GATE_NAME}" == *plugin-workload-sdk* ]]+}++ensure_evenfire_registry() {+ if ! gate_needs_registry; then+ log "Skipping evenfire-registry before ${GATE_NAME}; this gate does not require the sibling service"+ return 0+ fi+ log "Ensuring evenfire-registry and minikube registry egress policies before ${GATE_NAME}"+ (+ cd "${PROJECT_DIR}"+ if ${KC} -n registry get deployment registry-api >/dev/null 2>&1; then+ MINIKUBE_PROFILE="${PROFILE}" SKIP_BUILD=1 make minikube-deploy-evenfire-registry+ else+ MINIKUBE_PROFILE="${PROFILE}" make minikube-deploy-evenfire-registry+ fi+ )+}diff --git a/scripts/minikube/pre-gate-sync.sh b/scripts/minikube/pre-gate-sync.shindex 68ce1b499..34c54b329 100755--- a/scripts/minikube/pre-gate-sync.sh+++ b/scripts/minikube/pre-gate-sync.sh@@ -11,7 +11,6 @@ WORKTREE_ID="$(printf '%s' "${PROJECT_DIR}" | shasum | awk '{print $1}')"STATE_ROOT="${TMPDIR:-/tmp}/clerum-pre-gate-sync"STATE_DIR="${STATE_ROOT}/${WORKTREE_ID}"CLUSTER_SYNC_STATE_CONFIGMAP="${CLERUM_PRE_GATE_SYNC_CONFIGMAP:-clerum-pre-gate-sync-state}"-mkdir -p "${STATE_DIR}"GATE_NAME="pre-gate"@@ -48,6 +47,11 @@ log() {printf '[pre-gate-sync] %s\n' "$*"}+# shellcheck source=scripts/minikube/pre-gate-runtime.sh+source "${SCRIPT_DIR}/pre-gate-runtime.sh"+# shellcheck source=scripts/minikube/pre-gate-incremental.sh+source "${SCRIPT_DIR}/pre-gate-incremental.sh"+fingerprint_dir() {local dir="$1"@@ -99,13 +103,17 @@ persist_state() {cluster_marker_matches() {local expected_cluster_fingerprint="$1"local expected_worktree_id="$2"- local actual_cluster_fingerprint actual_worktree_id+ local expected_git_head actual_cluster_fingerprint actual_worktree_id actual_git_head++ expected_git_head="$(git -C "${PROJECT_DIR}" rev-parse --verify HEAD 2>/dev/null || true)"actual_cluster_fingerprint="$(${KC} get configmap "${CLUSTER_SYNC_STATE_CONFIGMAP}" -n control-plane -o jsonpath='{.data.clusterFingerprint}' 2>/dev/null || true)"actual_worktree_id="$(${KC} get configmap "${CLUSTER_SYNC_STATE_CONFIGMAP}" -n control-plane -o jsonpath='{.data.worktreeId}' 2>/dev/null || true)"+ actual_git_head="$(${KC} get configmap "${CLUSTER_SYNC_STATE_CONFIGMAP}" -n control-plane -o jsonpath='{.data.gitHead}' 2>/dev/null || true)"[[ "${actual_cluster_fingerprint}" == "${expected_cluster_fingerprint}" ]] &&- [[ "${actual_worktree_id}" == "${expected_worktree_id}" ]]+ [[ "${actual_worktree_id}" == "${expected_worktree_id}" ]] &&+ [[ -n "${expected_git_head}" && "${actual_git_head}" == "${expected_git_head}" ]]}persist_cluster_marker() {@@ -161,54 +169,6 @@ ensure_artifact() {)}-rollout_if_present() {- local namespace="$1"- local deployment="$2"-- if ${KC} get deployment "${deployment}" -n "${namespace}" >/dev/null 2>&1; then- log "Waiting for rollout: ${namespace}/${deployment}"- ${KC} rollout status "deployment/${deployment}" -n "${namespace}" --timeout=120s >/dev/null- fi-}--rollout_restart_with_retry() {- local namespace="$1"- local deployment="$2"- local attempt- local output-- for attempt in 1 2 3; do- if output="$(${KC} rollout restart "deployment/${deployment}" -n "${namespace}" 2>&1)"; then- [[ -n "${output}" ]] && printf '%s\n' "${output}"- return 0- fi-- if [[ "${output}" == *"within the past second"* && "${attempt}" != "3" ]]; then- log "Retrying rollout restart for ${namespace}/${deployment} after recent restart"- sleep 2- continue- fi-- printf '%s\n' "${output}" >&2- return 1- done-}--rollout_namespace_deployments() {- local namespace="$1"- local names-- names="$(${KC} get deployment -n "${namespace}" -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' 2>/dev/null || true)"- if [[ -z "${names}" ]]; then- return 0- fi-- while IFS= read -r deployment; do- [[ -z "${deployment}" ]] && continue- rollout_if_present "${namespace}" "${deployment}"- done <<<"${names}"-}-sync_mcp_host_auth_key() {if ! ${KC} get secret rpc-proxy-secrets -n rpc-proxy >/dev/null 2>&1; thenlog "Skipping mcp-host auth key sync (rpc-proxy-secrets not found)"@@ -240,35 +200,8 @@ provision_gfs_serving() {sync_mcp_host_auth_key}-gate_needs_registry() {- case "${GATE_NAME}" in- *registry*|*marketplace*|*plugin-workload-sdk*)- return 0- ;;- *)- return 1- ;;- esac-}--ensure_evenfire_registry() {- if ! gate_needs_registry; then- log "Skipping evenfire-registry before ${GATE_NAME}; this gate does not require the sibling service"- return 0- fi-- log "Ensuring evenfire-registry and minikube registry egress policies before ${GATE_NAME}"- (- cd "${PROJECT_DIR}"- if ${KC} -n registry get deployment registry-api >/dev/null 2>&1; then- MINIKUBE_PROFILE="${PROFILE}" SKIP_BUILD=1 make minikube-deploy-evenfire-registry- else- MINIKUBE_PROFILE="${PROFILE}" make minikube-deploy-evenfire-registry- fi- )-}-log "Evaluating sync requirements for ${GATE_NAME}"+preflight_host_lifecycle_probecluster_fingerprint="$({@@ -326,36 +259,43 @@ run_if_changed control-ui "npm test"run_if_changed desktop-app "npm test"if [[ "${cluster_changed}" == "true" ]]; then- log "Cluster-relevant changes detected — rebuilding and redeploying before ${GATE_NAME}"+ incremental_plan+ log "Cluster sync plan before ${GATE_NAME}: images=$(incremental_target_summary), full-image-build=${INCREMENTAL_FULL_IMAGE_BUILD}, full-deployment=${INCREMENTAL_FULL_DEPLOYMENT}"+ incremental_build_images(cd "${PROJECT_DIR}"- make minikube-build-images- make minikube-verify-images# CRD changes live outside the Kustomize overlay. Apply them before the- # service rollout so cluster-backed E2E sees the same schema as the branch.- make minikube-deploy-crds+ # service rollout when a fresh baseline or chart change requires it.+ if [[ "${INCREMENTAL_FULL_IMAGE_BUILD}" == "true" || "${INCREMENTAL_CRDS_CHANGED}" == "true" ]]; then+ make minikube-deploy-crds+ fi+ if [[ "${INCREMENTAL_FULL_IMAGE_BUILD}" == "true" || "${INCREMENTAL_FULL_DEPLOYMENT}" == "true" ]]; thenmake minikube-apply-secretsmake minikube-deploy-all- if [[ "${infra_changed}" == "true" ]]; then+ fi+ if [[ "${FORCE_RESTART}" == "true" || "${INCREMENTAL_FULL_IMAGE_BUILD}" == "true" ]]; thenmake minikube-restart-allfi)- rollout_if_present control-plane control-postgres- CONTEXT="${PROFILE}" ALLOWED_CONTEXTS="${PROFILE}" \- bash "${PROJECT_DIR}/deploy/scripts/run-control-api-db-migration.sh" \- --overlay "${PROJECT_DIR}/deploy/overlays/minikube"- CONTEXT="${PROFILE}" ALLOWED_CONTEXTS="${PROFILE}" \- bash "${PROJECT_DIR}/deploy/scripts/provision-control-api-runtime-roles.sh"- rollout_if_present control-plane control-api- # The base manifest no longer declares connection-string (provisioning-owned- # key), so deploy-all cannot clobber it. Provisioning must still run AFTER- # control-api migrations (0048 creates the least-privilege gfs_controller- # role) for fresh profiles and to converge any stale credential before the- # rest of the gate observes service readiness.- provision_gfs_serving+ if incremental_requires_database_reconcile; then+ rollout_if_present control-plane control-postgres+ CONTEXT="${PROFILE}" ALLOWED_CONTEXTS="${PROFILE}" \+ bash "${PROJECT_DIR}/deploy/scripts/run-control-api-db-migration.sh" \+ --overlay "${PROJECT_DIR}/deploy/overlays/minikube"+ CONTEXT="${PROFILE}" ALLOWED_CONTEXTS="${PROFILE}" \+ bash "${PROJECT_DIR}/deploy/scripts/provision-control-api-runtime-roles.sh"+ rollout_if_present control-plane control-api+ # The base manifest no longer declares connection-string (provisioning-owned+ # key), so deploy-all cannot clobber it. Provisioning must still run AFTER+ # control-api migrations (0048 creates the least-privilege gfs_controller+ # role) for fresh profiles and to converge any stale credential before the+ # rest of the gate observes service readiness.+ provision_gfs_serving+ fiensure_evenfire_registry+ incremental_restart_targetsrollout_if_present control-plane host-context-controllerrollout_if_present control-plane workflow-recipes@@ -369,18 +309,7 @@ if [[ "${cluster_changed}" == "true" ]]; thenrollout_if_present registry registry-apifi- # gfsc health is part of a clean baseline for GFS-backed gates: prove the- # permission-store wiring (Secret populated, pods postdate the rotation,- # /readyz green) once the rollouts settle. Gated on the deployments existing- # because a brand-new profile may not have reconciled gfsc yet; the strict- # fail-loud checks live in verify-gfs.sh.- if ${KC} get configmap gfs-config -n gfs >/dev/null 2>&1 \- && ${KC} -n gfs get deployment -l clerum.io/managed-by=host-context-controller -o name 2>/dev/null | grep -q .; then- log "Verifying gfs permission-store wiring"- CONTEXT="${PROFILE}" bash "${PROJECT_DIR}/scripts/minikube/verify-gfs.sh"- else- log "SKIPPING gfs permission-store verification (gfs-config or gfsc deployments not present yet) — GFS-backed gates on this profile are NOT proven"- fi+ incremental_verify_gfs_if_requiredlog "Cluster status after sync"${KC} get deploy -A --no-headers 2>/dev/null | grep -v kube-system || truediff --git a/scripts/tests/test-minikube-pre-gate-probe-contract.sh b/scripts/tests/test-minikube-pre-gate-probe-contract.shnew file mode 100755index 000000000..f56d8a407--- /dev/null+++ b/scripts/tests/test-minikube-pre-gate-probe-contract.sh@@ -0,0 +1,62 @@+#!/usr/bin/env bash+set -u++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+HELPER="${ROOT}/scripts/minikube/pre-gate-runtime.sh"+PARENT="${ROOT}/scripts/minikube/pre-gate-sync.sh"+MANIFEST="${ROOT}/deploy/overlays/minikube/instances/host.yaml"+FAIL=0++pass() { printf 'PASS: %s\n' "$*"; }+fail_test() { printf 'FAIL: %s\n' "$*" >&2; FAIL=1; }+log() { :; }++if grep -A4 '^kind: Host$' "$MANIFEST" | grep -Fq 'name: chatllm' &&+ grep -A4 '^kind: Host$' "$MANIFEST" | grep -Fq 'namespace: mcp-host'; then+ pass "minikube overlay declares the versioned mcp-host/chatllm probe"+else+ fail_test "minikube overlay does not declare the versioned probe"+fi++unset HOST_CRD_SCHEMA_PROBE_REF+PROJECT_DIR="$ROOT" PROFILE=contract GATE_NAME=contract KC=true+# shellcheck source=scripts/minikube/pre-gate-runtime.sh+source "$HELPER"+if [ "$HOST_CRD_SCHEMA_PROBE_REF" = mcp-host/chatllm ] &&+ export -p | grep -Fq 'HOST_CRD_SCHEMA_PROBE_REF'; then+ pass "pre-gate runtime exports the manifest-backed default probe"+else+ fail_test "pre-gate runtime did not propagate the default probe"+fi++fake_kc() {+ [[ "$*" == 'get deployment host-context-controller -n control-plane' ]] && return 0+ [[ "$*" == 'get host chatllm -n mcp-host' ]] && return "${HOST_PRESENT:-1}"+ return 1+}+KC=fake_kc+HOST_PRESENT=0+preflight_host_lifecycle_probe || fail_test "existing manifest-backed probe was rejected"+HOST_PRESENT=1+if preflight_host_lifecycle_probe; then+ fail_test "missing probe did not fail before sync work"+else+ pass "missing manifest-backed probe fails closed"+fi++HOST_CRD_SCHEMA_PROBE_REF=invalid+if preflight_host_lifecycle_probe; then+ fail_test "invalid probe reference was accepted"+else+ pass "invalid probe reference fails closed"+fi++probe_line="$(grep -n '^preflight_host_lifecycle_probe$' "$PARENT" | cut -d: -f1)"+fingerprint_line="$(grep -n '^cluster_fingerprint=' "$PARENT" | cut -d: -f1)"+if [ -n "$probe_line" ] && [ -n "$fingerprint_line" ] && [ "$probe_line" -lt "$fingerprint_line" ]; then+ pass "probe preflight runs before package checks and cluster rebuild"+else+ fail_test "probe preflight is not ordered before expensive sync work"+fi++exit "$FAIL"diff --git a/scripts/tests/test-minikube-pre-gate-sync-state.sh b/scripts/tests/test-minikube-pre-gate-sync-state.shindex 25b837159..eb60d8080 100755--- a/scripts/tests/test-minikube-pre-gate-sync-state.sh+++ b/scripts/tests/test-minikube-pre-gate-sync-state.sh@@ -3,6 +3,8 @@ set -uFAIL=0SCRIPT="scripts/minikube/pre-gate-sync.sh"+RUNTIME_SCRIPT="scripts/minikube/pre-gate-runtime.sh"+INCREMENTAL_SCRIPT="scripts/minikube/pre-gate-incremental.sh"REGISTRY_SCRIPT="scripts/minikube/deploy-evenfire-registry.sh"pass() { echo "PASS: $1"; }@@ -15,6 +17,14 @@ contains() {grep -Fq -- "$1" "$SCRIPT"}+runtime_contains() {+ grep -Fq -- "$1" "$RUNTIME_SCRIPT"+}++incremental_contains() {+ grep -Fq -- "$1" "$INCREMENTAL_SCRIPT"+}+not_contains() {! grep -Fq -- "$1" "$SCRIPT"}@@ -25,6 +35,12 @@ elsefail "pre-gate sync script has invalid bash syntax"fi+if bash -n "$INCREMENTAL_SCRIPT"; then+ pass "incremental pre-gate helper has valid bash syntax"+else+ fail "incremental pre-gate helper has invalid bash syntax"+fi+if bash -n "scripts/minikube/sync-auth-key.sh"; thenpass "auth-key sync helper has valid bash syntax"else@@ -49,10 +65,12 @@ if contains 'cluster_marker_matches()' &&contains 'persist_cluster_marker()' &&contains '--from-literal=clusterFingerprint=' &&contains '--from-literal=worktreeId=' &&+ contains "-o jsonpath='{.data.gitHead}'" &&+ contains 'actual_git_head' &¬_contains '--from-literal=worktreePath='; then- pass "pre-gate sync records a non-sensitive cluster marker"+ pass "pre-gate sync records and verifies a non-sensitive cluster marker"else- fail "pre-gate sync cluster marker is missing or stores local paths"+ fail "pre-gate sync cluster marker is incomplete or stores local paths"fiif contains 'elif ! cluster_marker_matches "${cluster_fingerprint}" "${WORKTREE_ID}"; then' &&@@ -62,6 +80,34 @@ elsefail "pre-gate sync does not detect cluster drift from another worktree"fi+if incremental_contains 'git -C "${PROJECT_DIR}" diff --name-only "${marker_git_head}" HEAD' &&+ incremental_contains 'git -C "${PROJECT_DIR}" diff --name-only HEAD' &&+ incremental_contains 'git -C "${PROJECT_DIR}" ls-files --others --exclude-standard'; then+ pass "incremental sync compares deployed, working-tree, and untracked paths"+else+ fail "incremental sync cannot derive a safe delta from the deployed marker"+fi++if incremental_contains 'control-api/*) incremental_add_target control-api control-plane control-api' &&+ incremental_contains 'rpc-proxy/*) incremental_add_target rpc-proxy rpc-proxy rpc-proxy' &&+ incremental_contains 'host-context-controller/*) incremental_add_target host-context-controller control-plane host-context-controller' &&+ incremental_contains 'control-ui/*) incremental_add_target control-ui control-plane control-ui'; then+ pass "incremental sync maps known runtime paths to their own images and deployments"+else+ fail "incremental sync does not map known runtime paths precisely"+fi++if contains 'incremental_plan' &&+ contains 'incremental_build_images' &&+ contains 'incremental_restart_targets' &&+ not_contains 'make minikube-build-images' &&+ incremental_contains 'bash "${PROJECT_DIR}/scripts/minikube/build-images.sh" "--only=${selector}"' &&+ incremental_contains 'make minikube-build-images'; then+ pass "pre-gate sync builds targeted images and retains a fail-closed full-build fallback"+else+ fail "pre-gate sync still performs an unconditional all-image build"+fi+if contains 'scripts/minikube/sync-auth-key.sh' &&contains '--context "${PROFILE}"'; thenpass "pre-gate sync uses the shared idempotent auth-key sync helper"@@ -104,8 +150,8 @@ elsefail "evenfire registry deploy helper does not patch minikube PVC ownership"fi-if contains 'if ! gate_needs_registry; then' &&- contains 'this gate does not require the sibling service' &&+if runtime_contains 'if ! gate_needs_registry; then' &&+ runtime_contains 'this gate does not require the sibling service' &&contains 'if gate_needs_registry; then' &&contains 'rollout_if_present registry registry-api'; thenpass "pre-gate sync keeps the sibling registry scoped to registry-backed gates"