package cmd

import (
	"context"
	"encoding/json"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/require"

	agentapi "github.com/tidbcloud/AgentTeam/internal/api/agent"
	apidto "github.com/tidbcloud/AgentTeam/internal/api/dto"
	apitestkit "github.com/tidbcloud/AgentTeam/internal/api/testkit"
	"github.com/tidbcloud/AgentTeam/internal/core/secrets"
	"github.com/tidbcloud/AgentTeam/internal/schedule/manage"
	agentmanagement "github.com/tidbcloud/AgentTeam/internal/service/agentapproval"
	"github.com/tidbcloud/AgentTeam/internal/service/approvalapp"
	rolemanagement "github.com/tidbcloud/AgentTeam/internal/service/role/execution"
	teamroleproposal "github.com/tidbcloud/AgentTeam/internal/service/team/roleproposal"
	agentstore "github.com/tidbcloud/AgentTeam/internal/store/agent"

	agentteamexec "github.com/tidbcloud/AgentTeam/desktop/internal/api/exec"
	"github.com/tidbcloud/AgentTeam/desktop/internal/token"
	"github.com/tidbcloud/AgentTeam/desktop/internal/wire/apiclient"
)

// TestExecNonWorkflowMutationsUseProductionReceiptStores traverses the
// registered Exec daemon route, LocalClient/Cobra, and production Agent API
// handlers for Agent, Team, Role, and schedule mutation families. Replay is
// asserted from real approval/schedule rows; no in-test receipt map stands in
// for an upstream persistence boundary.
func TestExecNonWorkflowMutationsUseProductionReceiptStores(t *testing.T) {
	ctx := context.Background()
	runtime := apitestkit.StartRuntimeWithoutBackgroundWorkers(t)
	seedExecAgentManagementFixture(t, runtime)

	deps := runtime.Store.AgentStorePortsDeps()
	deps.AgentRuntime = runtime.AgentRuntime
	deps.AgentOps = runtime.Store.AgentOps()
	coreRole := rolemanagement.CoreSubmissionStore{DB: runtime.Pool, Approvals: runtime.Store.Graph.Approval}
	roleService := rolemanagement.NewService(rolemanagement.Dependencies{
		AuthenticateApplicant: coreRole.AuthenticateApplicant,
		LookupApproval:        coreRole.LookupApproval,
		ListAssignments:       coreRole.ListAssignments,
		ResolveManager:        coreRole.ResolveManager,
		Preflight:             func(context.Context, rolemanagement.PreflightCommand) error { return nil },
		CommitSubmission:      coreRole.CommitSubmission,
	})
	subjects := approvalapp.NewSubjectRegistry(runtime.Store.Graph.Approval)
	require.NoError(t, subjects.Register(approvalapp.NewAgentManagementSubjectHandler(
		runtime.Store.Graph.Approval,
		agentmanagement.New(runtime.Pool, runtime.Store.Graph.Approval, runtime.Store.AgentOps()),
		runtime.Store.ApprovalAppProjector(),
	)))
	require.NoError(t, subjects.Register(approvalapp.NewRoleManagementSubjectHandler(
		runtime.Store.Graph.Approval, roleService, runtime.Store.ApprovalAppProjector(),
	)))
	skillGateway := &execSkillGateway{skillID: execFixtureSkillID}
	require.NoError(t, subjects.Register(approvalapp.NewSkillDeleteSubjectHandler(
		runtime.Store.Graph.Approval,
		agentapi.NewAgentSkillDeleteAuthority(runtime.Store.App(), runtime.Store.App(), skillGateway),
		runtime.Store.ApprovalAppProjector(),
	)))
	require.NoError(t, subjects.Register(approvalapp.NewTeamRoleProposalSubjectHandler(
		runtime.Store.Graph.Approval, teamroleproposal.New(runtime.Pool), runtime.Store.ApprovalAppProjector(),
	)))
	subjects.Seal()
	deps.ApprovalSubjects = subjects
	apiDeps := agentapi.New(runtime.Logger, deps, runtime.Store.Attachment(), runtime.TaskBoard, runtime.Hub, nil)
	apiDeps.ApprovalSubjects = subjects
	apiDeps.RoleManagers = coreRole
	apiDeps.RoleReads = execRoleReads{}
	apiDeps.RoleRequests = roleService
	lifecycleCommands := &execLifecycleCommands{}
	lifecycleControl := &execLifecycleControl{}
	apiDeps.AgentLifecycleCommands = lifecycleCommands
	apiDeps.AgentRuntimeControl = lifecycleControl
	apiDeps.SkillOwners = runtime.Store.App()
	apiDeps.SkillWorkspace = runtime.Store.App()
	apiDeps.Skills = skillGateway
	apiDeps.ScheduleService = manage.New(runtime.Logger, runtime.Pool, runtime.Store.App(), manage.ServiceOptions{})
	gin.SetMode(gin.TestMode)
	upstreamRouter := gin.New()
	agentapi.RegisterRoutes(upstreamRouter, apiDeps)
	faults := []execResponseFault{
		{method: http.MethodPost, action: "/managed-agents/create"},
		{method: http.MethodPost, action: "/managed-agents/update"},
		{method: http.MethodPost, action: "/managed-agents/delete"},
		{method: http.MethodPost, action: "/managed-agents/duplicate"},
		{method: http.MethodPost, action: "/managed-agents/start"},
		{method: http.MethodPost, action: "/managed-agents/stop"},
		{method: http.MethodPost, action: "/managed-agents/restart"},
		{method: http.MethodPost, action: "/teams/update"},
		{method: http.MethodPost, action: "/roles/create"},
		{method: http.MethodPost, action: "/roles/update"},
		{method: http.MethodPost, action: "/roles/delete"},
		{method: http.MethodPost, action: "/roles/apply"},
		{method: http.MethodPost, action: "/skills/delete"},
		{method: http.MethodPost, action: "/schedules"},
		{method: http.MethodPatch, action: "/schedules/:id"},
	}
	upstreamDropper := &execDropFirstResponse{handler: upstreamRouter, faults: faults}
	upstream := httptest.NewServer(upstreamDropper)
	t.Cleanup(upstream.Close)

	keys, err := token.NewKeyManager(t.TempDir() + "/config.yaml")
	require.NoError(t, err)
	authorizations := agentteamexec.NewRuntimeAuthorizationStore(keys)
	lease, err := authorizations.Create(agentteamexec.RuntimeAuthorizationConfig{
		ServerID: "server-1", AgentID: execFixtureAgentID, SessionID: "session-1", RunID: "run-1",
		WorkDir: t.TempDir(), Server: &apiclient.Client{
			ServerURL: upstream.URL, AgentID: execFixtureAgentID, AuthToken: execFixtureAgentToken,
			RouteWorkspaceID: execFixtureWorkspaceID, HTTPClient: upstream.Client(),
		}, TokenTTL: time.Hour,
	})
	require.NoError(t, err)

	daemonRouter := gin.New()
	agentteamexec.RegisterRoutes(daemonRouter.Group("/api/internal/exec"), agentteamexec.RouteDependencies{
		Authorizations: authorizations,
	})
	daemon := httptest.NewServer(daemonRouter)
	t.Cleanup(daemon.Close)
	setExecCommandTokenFile(t, daemon.URL+"/api/internal/exec/servers/server-1/agents/"+execFixtureAgentID, lease.Token)

	input := `{"requestId":"req-real-agent-create","name":"created-agent","machineId":"` + execFixtureMachineID + `","runtime":"codex"}`
	first, stderr, err := executeCobra(newExecCommand(), "agent", "create", input)
	require.NoError(t, err, stderr)
	require.Empty(t, stderr)
	require.True(t, json.Valid([]byte(strings.TrimSpace(first))))
	second, stderr, err := executeCobra(newExecCommand(), "agent", "create", input)
	require.NoError(t, err, stderr)
	require.Equal(t, first, second, "exact request replay returns the persisted approval receipt")

	var firstResponse struct {
		Data struct {
			Status     string `json:"status"`
			ApprovalID string `json:"approvalId"`
		} `json:"data"`
	}
	require.NoError(t, json.Unmarshal([]byte(first), &firstResponse))
	require.Equal(t, "pending", firstResponse.Data.Status)
	require.NotEmpty(t, firstResponse.Data.ApprovalID)
	var approvals int
	require.NoError(t, runtime.Pool.QueryRow(ctx, `
SELECT COUNT(*) FROM approval_instances
WHERE workspace_id = $1 AND subject_type = 'agent_management'
`, execFixtureWorkspaceID).Scan(&approvals))
	require.Equal(t, 1, approvals, "the production approval store contains one request")

	_, stderr, err = executeCobra(newExecCommand(), "agent", "create", `{"requestId":"req-real-agent-create","name":"different-agent","machineId":"`+execFixtureMachineID+`","runtime":"codex"}`)
	require.Error(t, err)
	require.Contains(t, stderr, `"code":"conflict"`)
	exit, ok := ExecExitCode(err)
	require.True(t, ok)
	require.Equal(t, 1, exit)

	for _, lifecycleAction := range []string{"start", "stop", "restart"} {
		switch lifecycleAction {
		case "start":
			lifecycleControl.running = false
		case "stop", "restart":
			lifecycleControl.running = true
		}
		lifecycleInput := `{"requestId":"req-real-agent-` + lifecycleAction + `","agentId":"` + execFixtureAgentID + `"}`
		first, stderr, err := executeCobra(newExecCommand(), "agent", lifecycleAction, lifecycleInput)
		require.NoError(t, err, stderr)
		second, stderr, err := executeCobra(newExecCommand(), "agent", lifecycleAction, lifecycleInput)
		require.NoError(t, err, stderr)
		require.Equal(t, first, second, "exact Agent lifecycle %s replay", lifecycleAction)
		startsBefore, stopsBefore, restartsBefore := lifecycleCommands.starts, lifecycleCommands.stops, lifecycleControl.restarts
		_, stderr, err = executeCobra(newExecCommand(), "agent", lifecycleAction, `{"requestId":"req-real-agent-`+lifecycleAction+`","agentId":"`+execFixtureOtherAgentID+`"}`)
		require.Error(t, err)
		require.Contains(t, stderr, `"code":"conflict"`)
		otherAction := map[string]string{"start": "stop", "stop": "restart", "restart": "start"}[lifecycleAction]
		_, stderr, err = executeCobra(newExecCommand(), "agent", otherAction, lifecycleInput)
		require.Error(t, err)
		require.Contains(t, stderr, `"code":"conflict"`)
		require.Equal(t, startsBefore, lifecycleCommands.starts, "changed target/cross-action replay must not start runtime")
		require.Equal(t, stopsBefore, lifecycleCommands.stops, "changed target/cross-action replay must not stop runtime")
		require.Equal(t, restartsBefore, lifecycleControl.restarts, "changed target/cross-action replay must not restart runtime")
		var receipts int
		require.NoError(t, runtime.Pool.QueryRow(ctx, `
SELECT COUNT(*) FROM agent_lifecycle_receipts
WHERE workspace_id = $1 AND applicant_agent_id = $2 AND action = $3
`, execFixtureWorkspaceID, execFixtureAgentID, lifecycleAction).Scan(&receipts))
		require.Equal(t, 1, receipts, "one durable lifecycle receipt for %s", lifecycleAction)
		var selectors int
		require.NoError(t, runtime.Pool.QueryRow(ctx, `
SELECT COUNT(*) FROM agent_lifecycle_request_selectors
WHERE applicant_agent_id = $1 AND request_id = $2
`, execFixtureAgentID, "req-real-agent-"+lifecycleAction).Scan(&selectors))
		require.Equal(t, 1, selectors, "one action-independent lifecycle selector for %s", lifecycleAction)
		if lifecycleAction == "start" {
			lifecycleControl.running = true
		} else if lifecycleAction == "stop" {
			lifecycleControl.running = false
		}
	}
	require.Equal(t, 1, lifecycleCommands.starts)
	require.Equal(t, 1, lifecycleCommands.stops)
	require.Equal(t, 1, lifecycleControl.restarts)
	_, stderr, err = executeCobra(newExecCommand(), "agent", "stop", `{"requestId":"req-real-agent-start","agentId":"`+execFixtureAgentID+`"}`)
	require.Error(t, err)
	require.Contains(t, stderr, `"code":"conflict"`)
	var lifecycleReceipts int
	require.NoError(t, runtime.Pool.QueryRow(ctx, `
SELECT COUNT(*) FROM agent_lifecycle_receipts
WHERE workspace_id = $1 AND applicant_agent_id = $2
`, execFixtureWorkspaceID, execFixtureAgentID).Scan(&lifecycleReceipts))
	require.Equal(t, 3, lifecycleReceipts, "cross-action requestId conflict creates no second lifecycle receipt")

	for _, agentCase := range []struct {
		action string
		input  string
		other  string
	}{
		{"update", `{"requestId":"req-real-agent-update","agentId":"` + execFixtureAgentID + `","description":"Updated"}`, `{"requestId":"req-real-agent-update","agentId":"` + execFixtureAgentID + `","description":"Different"}`},
		{"duplicate", `{"requestId":"req-real-agent-duplicate","sourceAgentId":"` + execFixtureAgentID + `"}`, `{"requestId":"req-real-agent-duplicate","sourceAgentId":"agent_other"}`},
		{"delete", `{"requestId":"req-real-agent-delete","agentIds":["` + execFixtureAgentID + `"]}`, `{"requestId":"req-real-agent-delete","agentIds":["agent_other"]}`},
	} {
		first, stderr, err := executeCobra(newExecCommand(), "agent", agentCase.action, agentCase.input)
		require.NoError(t, err, stderr)
		second, stderr, err := executeCobra(newExecCommand(), "agent", agentCase.action, agentCase.input)
		require.NoError(t, err, stderr)
		require.Equal(t, first, second, "exact Agent %s replay", agentCase.action)
		_, stderr, err = executeCobra(newExecCommand(), "agent", agentCase.action, agentCase.other)
		require.Error(t, err)
		require.Contains(t, stderr, `"code":"conflict"`)
	}

	_, stderr, err = executeCobra(newExecCommand(), "agent", "create", `{"requestId":"req-real-cross-action","name":"cross-action","machineId":"`+execFixtureMachineID+`","runtime":"codex"}`)
	require.NoError(t, err, stderr)
	_, stderr, err = executeCobra(newExecCommand(), "agent", "update", `{"requestId":"req-real-cross-action","agentId":"`+execFixtureAgentID+`","description":"cross-action"}`)
	require.Error(t, err)
	require.Contains(t, stderr, `"code":"conflict"`)

	// The daemon validates body/header selector agreement before the production
	// Agent handler and therefore before a second Approval can be created.
	require.NoError(t, runtime.Pool.QueryRow(ctx, `
SELECT COUNT(*) FROM approval_instances
WHERE workspace_id = $1 AND subject_type = 'agent_management'
`, execFixtureWorkspaceID).Scan(&approvals))
	before := approvals
	request, err := http.NewRequest(http.MethodPost,
		daemon.URL+"/api/internal/exec/servers/server-1/agents/"+execFixtureAgentID+"/agent/create",
		strings.NewReader(input))
	require.NoError(t, err)
	request.Header.Set("Authorization", "Bearer "+lease.Token)
	request.Header.Set("Idempotency-Key", "header-selector")
	request.Header.Set("X-Request-ID", "header-selector")
	response, err := daemon.Client().Do(request)
	require.NoError(t, err)
	response.Body.Close()
	require.Equal(t, http.StatusConflict, response.StatusCode)
	require.NoError(t, runtime.Pool.QueryRow(ctx, `
SELECT COUNT(*) FROM approval_instances
WHERE workspace_id = $1 AND subject_type = 'agent_management'
`, execFixtureWorkspaceID).Scan(&approvals))
	require.Equal(t, before, approvals)

	roleInput := `{"requestId":"req-real-role-create","name":"reviewer","definition":"Review"}`
	roleFirst, stderr, err := executeCobra(newExecCommand(), "role", "create", roleInput)
	require.NoError(t, err, stderr)
	roleSecond, stderr, err := executeCobra(newExecCommand(), "role", "create", roleInput)
	require.NoError(t, err, stderr)
	require.Equal(t, roleFirst, roleSecond, "exact role request replay returns the persisted Approval")
	var roleApprovals int
	require.NoError(t, runtime.Pool.QueryRow(ctx, `
SELECT COUNT(*) FROM approval_instances
WHERE workspace_id = $1 AND subject_type = 'role_management'
`, execFixtureWorkspaceID).Scan(&roleApprovals))
	require.Equal(t, 1, roleApprovals)
	_, stderr, err = executeCobra(newExecCommand(), "role", "create", `{"requestId":"req-real-role-create","name":"different","definition":"Review"}`)
	require.Error(t, err)
	require.Contains(t, stderr, `"code":"conflict"`)

	for _, roleCase := range []struct {
		action string
		input  string
		other  string
	}{
		{"update", `{"requestId":"req-real-role-update","roleId":"role_missing","expectedRoleVersionId":"version_missing","name":"Reviewer"}`, `{"requestId":"req-real-role-update","roleId":"role_missing","expectedRoleVersionId":"version_missing","name":"Different"}`},
		{"delete", `{"requestId":"req-real-role-delete","roleId":"role_missing","expectedRoleVersionId":"version_missing"}`, `{"requestId":"req-real-role-delete","roleId":"role_other","expectedRoleVersionId":"version_missing"}`},
		{"apply", `{"requestId":"req-real-role-apply","roleId":"role_missing","roleVersionId":"version_missing","agentId":"` + execFixtureAgentID + `"}`, `{"requestId":"req-real-role-apply","roleId":"role_other","roleVersionId":"version_missing","agentId":"` + execFixtureAgentID + `"}`},
	} {
		first, stderr, err := executeCobra(newExecCommand(), "role", roleCase.action, roleCase.input)
		require.NoError(t, err, stderr)
		second, stderr, err := executeCobra(newExecCommand(), "role", roleCase.action, roleCase.input)
		require.NoError(t, err, stderr)
		require.Equal(t, first, second, "exact role %s replay", roleCase.action)
		_, stderr, err = executeCobra(newExecCommand(), "role", roleCase.action, roleCase.other)
		require.Error(t, err)
		require.Contains(t, stderr, `"code":"conflict"`)
	}

	skillInput := `{"requestId":"req-real-skill-delete","skillId":"` + execFixtureSkillID + `"}`
	skillFirst, stderr, err := executeCobra(newExecCommand(), "skill", "delete", skillInput)
	require.NoError(t, err, stderr)
	skillSecond, stderr, err := executeCobra(newExecCommand(), "skill", "delete", skillInput)
	require.NoError(t, err, stderr)
	require.Equal(t, skillFirst, skillSecond, "exact Skill delete replay returns the persisted Approval")
	var skillApprovals int
	require.NoError(t, runtime.Pool.QueryRow(ctx, `
SELECT COUNT(*) FROM approval_instances
WHERE workspace_id = $1 AND subject_type = 'skill_delete'
`, execFixtureWorkspaceID).Scan(&skillApprovals))
	require.Equal(t, 1, skillApprovals)
	_, stderr, err = executeCobra(newExecCommand(), "skill", "delete", `{"requestId":"req-real-skill-delete","skillId":"skill_other"}`)
	require.Error(t, err)
	require.Contains(t, stderr, `"code":"conflict"`)
	require.Len(t, skillGateway.deleted, 0, "pending replay does not perform a second effect")

	teamInput := `{"teamId":"` + execFixtureTeamID + `","requestId":"req-real-team-update","description":"Updated description"}`
	teamFirst, stderr, err := executeCobra(newExecCommand(), "team", "update", teamInput)
	require.NoError(t, err, stderr)
	teamSecond, stderr, err := executeCobra(newExecCommand(), "team", "update", teamInput)
	require.NoError(t, err, stderr)
	require.Equal(t, teamFirst, teamSecond, "exact Team request replay returns the persisted Approval")
	var teamApprovals int
	require.NoError(t, runtime.Pool.QueryRow(ctx, `
SELECT COUNT(*) FROM approval_instances
WHERE workspace_id = $1 AND subject_type = 'team_role_proposal'
`, execFixtureWorkspaceID).Scan(&teamApprovals))
	require.Equal(t, 1, teamApprovals)
	_, stderr, err = executeCobra(newExecCommand(), "team", "update", `{"teamId":"`+execFixtureTeamID+`","requestId":"req-real-team-update","description":"Different description"}`)
	require.Error(t, err)
	require.Contains(t, stderr, `"code":"conflict"`)

	_, err = runtime.Store.App().ResolveWritableAgentTargetScopeID(ctx, agentstore.AuthenticatedAgent{AgentID: execFixtureAgentID, WorkspaceID: execFixtureWorkspaceID, MemberID: execFixtureAgentMemberID, MachineID: execFixtureMachineID}, "#exec-receipt")
	require.NoError(t, err)
	scheduleCreate := `{"name":"Reminder","schedule":{"kind":"after","seconds":60},"target":"#exec-receipt","template":"Check build","idempotencyKey":"idem-real-schedule-create"}`
	scheduleFirst, stderr, err := executeCobra(newExecCommand(), "scheduled-message", "create", scheduleCreate)
	require.NoError(t, err, stderr)
	scheduleSecond, stderr, err := executeCobra(newExecCommand(), "scheduled-message", "create", scheduleCreate)
	require.NoError(t, err, stderr)
	require.Equal(t, scheduleFirst, scheduleSecond, "exact schedule create replay returns the persisted schedule")
	_, stderr, err = executeCobra(newExecCommand(), "scheduled-message", "create", `{"name":"Different","schedule":{"kind":"after","seconds":60},"target":"#exec-receipt","template":"Changed build","idempotencyKey":"idem-real-schedule-create"}`)
	require.Error(t, err)
	require.Contains(t, stderr, `"code":"conflict"`)
	var scheduleResponse struct {
		Data struct {
			ID string `json:"id"`
		} `json:"data"`
	}
	require.NoError(t, json.Unmarshal([]byte(scheduleFirst), &scheduleResponse))
	require.NotEmpty(t, scheduleResponse.Data.ID)
	var scheduleCreateRows int
	require.NoError(t, runtime.Pool.QueryRow(ctx, `
SELECT COUNT(*) FROM schedule_definitions
WHERE workspace_id = $1
`, execFixtureWorkspaceID).Scan(&scheduleCreateRows))
	require.Equal(t, 1, scheduleCreateRows, "changed create payload must not create a second schedule row")
	scheduleUpdate := `{"id":"` + scheduleResponse.Data.ID + `","name":"Reminder updated","schedule":{"kind":"after","seconds":120},"target":"#exec-receipt","template":"Updated build","idempotencyKey":"idem-real-schedule-update"}`
	updatedFirst, stderr, err := executeCobra(newExecCommand(), "scheduled-message", "update", scheduleUpdate)
	require.NoError(t, err, stderr)
	updatedSecond, stderr, err := executeCobra(newExecCommand(), "scheduled-message", "update", scheduleUpdate)
	require.NoError(t, err, stderr)
	require.Equal(t, updatedFirst, updatedSecond, "exact schedule update replay returns the persisted schedule")
	_, stderr, err = executeCobra(newExecCommand(), "scheduled-message", "update", `{"id":"`+scheduleResponse.Data.ID+`","name":"Different","schedule":{"kind":"after","seconds":120},"target":"#exec-receipt","template":"Updated build","idempotencyKey":"idem-real-schedule-update"}`)
	require.Error(t, err)
	require.Contains(t, stderr, `"code":"conflict"`)
	var scheduleRows int
	require.NoError(t, runtime.Pool.QueryRow(ctx, `
SELECT COUNT(*) FROM schedule_definitions
WHERE workspace_id = $1 AND id = $2
`, execFixtureWorkspaceID, scheduleResponse.Data.ID).Scan(&scheduleRows))
	require.Equal(t, 1, scheduleRows, "schedule create/update replay keeps one durable schedule row")
	upstreamDropper.requireConsumed(t)
}

type execResponseFault struct {
	method string
	action string
}

type execDropFirstResponse struct {
	handler  http.Handler
	faults   []execResponseFault
	consumed []int
	attempts []int
}

func (dropper *execDropFirstResponse) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	captured := httptest.NewRecorder()
	dropper.handler.ServeHTTP(captured, request)
	canonicalAction := execCanonicalActionPath(request.URL.Path)
	faultIndex := -1
	for index, fault := range dropper.faults {
		if fault.method == request.Method && fault.action == canonicalAction {
			faultIndex = index
			break
		}
	}
	if faultIndex >= 0 {
		if dropper.consumed == nil {
			dropper.consumed = make([]int, len(dropper.faults))
			dropper.attempts = make([]int, len(dropper.faults))
		}
		dropper.attempts[faultIndex]++
		if dropper.consumed[faultIndex] == 0 {
			if hijacker, ok := writer.(http.Hijacker); ok {
				connection, _, err := hijacker.Hijack()
				if err == nil {
					dropper.consumed[faultIndex]++
					_ = connection.Close()
					return
				}
			}
		}
	}
	for key, values := range captured.Header() {
		for _, value := range values {
			writer.Header().Add(key, value)
		}
	}
	writer.WriteHeader(captured.Code)
	_, _ = writer.Write(captured.Body.Bytes())
}

func execCanonicalActionPath(path string) string {
	parts := strings.Split(strings.Trim(path, "/"), "/")
	for index, part := range parts {
		if part != "runtime" || index+1 >= len(parts) {
			continue
		}
		tail := parts[index+1:]
		if len(tail) == 2 && tail[0] == "schedules" {
			return "/schedules/:id"
		}
		return "/" + strings.Join(tail, "/")
	}
	return ""
}

func (dropper *execDropFirstResponse) requireConsumed(t *testing.T) {
	t.Helper()
	require.Len(t, dropper.consumed, len(dropper.faults), "fault harness must observe every configured action")
	for index, fault := range dropper.faults {
		require.Equal(t, 1, dropper.consumed[index], "fault %s %s must be consumed exactly once", fault.method, fault.action)
		require.GreaterOrEqual(t, dropper.attempts[index], 2, "fault %s %s must retry after the committed response was lost", fault.method, fault.action)
	}
}

type execLifecycleCommands struct {
	starts, stops, restarts int
}

func (commands *execLifecycleCommands) StartAgentRuntimeForUser(context.Context, string, string, string) (agentstore.AgentView, error) {
	commands.starts++
	return agentstore.AgentView{}, nil
}

func (commands *execLifecycleCommands) StopAgentRuntimeForUser(context.Context, string, string, string) (agentstore.AgentView, error) {
	commands.stops++
	return agentstore.AgentView{}, nil
}

type execLifecycleControl struct {
	restarts int
	running  bool
}

func (execLifecycleControl) MachineConnected(string) bool { return true }
func (control *execLifecycleControl) AgentRuntimeRunning(string, string) bool {
	return control.running
}
func (control *execLifecycleControl) RestartAgent(context.Context, string, string) error {
	control.restarts++
	return nil
}

type execSkillGateway struct {
	skillID string
	deleted []string
}

func (gateway *execSkillGateway) List(context.Context, agentapi.AgentSkillPrincipal, agentapi.AgentSkillListInput) (apidto.SkillListResponse, error) {
	return apidto.SkillListResponse{}, nil
}

func (gateway *execSkillGateway) Get(_ context.Context, principal agentapi.AgentSkillPrincipal, skillID string) (apidto.Skill, error) {
	return apidto.Skill{ID: skillID, WorkspaceID: principal.WorkspaceID, Name: "Exec Skill", CanManage: skillID == gateway.skillID}, nil
}

func (gateway *execSkillGateway) Create(context.Context, agentapi.AgentSkillPrincipal, apidto.SkillCreateRequest) (apidto.Skill, error) {
	return apidto.Skill{}, nil
}

func (gateway *execSkillGateway) Update(context.Context, agentapi.AgentSkillPrincipal, string, agentapi.AgentSkillUpdateInput) (apidto.Skill, error) {
	return apidto.Skill{}, nil
}

func (gateway *execSkillGateway) Import(context.Context, agentapi.AgentSkillPrincipal, string, string, io.Reader) (apidto.SkillImportResponse, error) {
	return apidto.SkillImportResponse{}, nil
}

func (gateway *execSkillGateway) Delete(_ context.Context, _ agentapi.AgentSkillPrincipal, skillID string) error {
	gateway.deleted = append(gateway.deleted, skillID)
	return nil
}

type execRoleReads struct{}

func (execRoleReads) List(context.Context, rolemanagement.RoleReadPrincipal, rolemanagement.RoleListInput) (rolemanagement.RoleListResult, error) {
	return rolemanagement.RoleListResult{Roles: []rolemanagement.RoleSummary{}}, nil
}

func (execRoleReads) Get(context.Context, rolemanagement.RoleReadPrincipal, string) (rolemanagement.RoleDetail, error) {
	return rolemanagement.RoleDetail{}, nil
}

const (
	execFixtureWorkspaceID        = "wsp_exec_real_receipt"
	execFixtureOwnerUserID        = "usr_exec_real_receipt_owner"
	execFixtureOwnerMemberID      = "mem_exec_real_receipt_owner"
	execFixtureAgentMemberID      = "mem_exec_real_receipt_agent"
	execFixtureOtherAgentMemberID = "mem_exec_real_receipt_agent_2"
	execFixtureMachineID          = "mac_exec_real_receipt"
	execFixtureAgentID            = "agt_exec_real_receipt"
	execFixtureOtherAgentID       = "agt_exec_real_receipt_2"
	execFixtureAgentToken         = "exec-real-receipt-agent-token"
	execFixtureTeamID             = "team_exec_real_receipt"
	execFixtureTeamMemberID       = "wtm_exec_real_receipt"
	execFixtureChannelID          = "chn_exec_real_receipt"
	execFixtureSkillID            = "skill_exec_real_receipt"
)

func seedExecAgentManagementFixture(t *testing.T, runtime apitestkit.Runtime) {
	t.Helper()
	now := time.Date(2026, 8, 22, 0, 0, 0, 0, time.UTC)
	mustExecCmdFixture(t, runtime, `
INSERT INTO users (id, email, name, display_name, avatar_url, is_admin, password_hash, email_verified_at, created_at, updated_at)
VALUES ($1, 'exec-real-receipt@example.com', 'exec-real-receipt', 'Exec Receipt Owner', '', FALSE, 'hash', $2, $2, $2)
`, execFixtureOwnerUserID, now)
	organizationID := "org_exec_real_receipt"
	mustExecCmdFixture(t, runtime, `
INSERT INTO organizations (id, slug, name, created_by_user_id, created_at, updated_at)
VALUES ($1, 'exec-real-receipt', 'exec-real-receipt', $2, $3, $3)
`, organizationID, execFixtureOwnerUserID, now)
	mustExecCmdFixture(t, runtime, `
INSERT INTO workspaces (id, organization_id, slug, name, latest_message_seq, created_at, updated_at)
VALUES ($1, $2, 'exec-real-receipt', 'exec-real-receipt', 0, $3, $3)
`, execFixtureWorkspaceID, organizationID, now)
	mustExecCmdFixture(t, runtime, `
INSERT INTO members (id, workspace_id, type, display_name, user_id, workspace_role, status, created_at, updated_at)
VALUES ($1, $2, 'human', 'Owner', $3, 'owner', 'active', $4, $4)
`, execFixtureOwnerMemberID, execFixtureWorkspaceID, execFixtureOwnerUserID, now)
	mustExecCmdFixture(t, runtime, `
INSERT INTO members (id, workspace_id, type, display_name, status, created_at, updated_at)
VALUES ($1, $2, 'agent', 'Applicant', 'active', $3, $3)
`, execFixtureAgentMemberID, execFixtureWorkspaceID, now)
	mustExecCmdFixture(t, runtime, `
INSERT INTO machines (id, workspace_id, created_by_user_id, name, api_key, created_at, updated_at)
VALUES ($1, $2, $3, 'Exec receipt machine', 'machine-key', $4, $4)
`, execFixtureMachineID, execFixtureWorkspaceID, execFixtureOwnerUserID, now)
	mustExecCmdFixture(t, runtime, `
INSERT INTO agents (id, workspace_id, machine_id, member_id, name, runtime, model, description, auth_token_hash, status, activity_detail, created_at, updated_at)
VALUES ($1, $2, $3, $4, 'exec-applicant', 'codex', 'gpt-5', '', $5, 'active', '', $6, $6)
`, execFixtureAgentID, execFixtureWorkspaceID, execFixtureMachineID, execFixtureAgentMemberID, secrets.HashToken(execFixtureAgentToken), now)
	mustExecCmdFixture(t, runtime, `
INSERT INTO members (id, workspace_id, type, display_name, status, created_at, updated_at)
VALUES ($1, $2, 'agent', 'Second target', 'active', $3, $3)
`, execFixtureOtherAgentMemberID, execFixtureWorkspaceID, now)
	mustExecCmdFixture(t, runtime, `
INSERT INTO agents (id, workspace_id, machine_id, member_id, name, runtime, model, description, auth_token_hash, status, activity_detail, created_at, updated_at)
VALUES ($1, $2, $3, $4, 'exec-target', 'codex', 'gpt-5', '', $5, 'active', '', $6, $6)
`, execFixtureOtherAgentID, execFixtureWorkspaceID, execFixtureMachineID, execFixtureOtherAgentMemberID, secrets.HashToken("exec-real-target-agent-token"), now)
	mustExecCmdFixture(t, runtime, `
INSERT INTO scopes (id, workspace_id, type, identity_key, status, created_by_member_id, created_at, updated_at)
VALUES ($1, $2, 'channel', $3, 'active', $4, $5, $5)
`, execFixtureChannelID, execFixtureWorkspaceID, "channel:"+execFixtureChannelID, execFixtureOwnerMemberID, now)
	mustExecCmdFixture(t, runtime, `
INSERT INTO scope_channel_profiles (scope_id, workspace_id, slug, display_name, description, visibility, owner_member_id, created_at, updated_at)
VALUES ($1, $2, 'exec-receipt', 'Exec Receipt', '', 'public', $3, $4, $4)
`, execFixtureChannelID, execFixtureWorkspaceID, execFixtureOwnerMemberID, now)
	for _, memberID := range []string{execFixtureOwnerMemberID, execFixtureAgentMemberID} {
		mustExecCmdFixture(t, runtime, `
INSERT INTO scope_memberships (scope_id, member_id, visibility, last_read_seq, created_at, updated_at)
VALUES ($1, $2, 'public', 0, $3, $3)
`, execFixtureChannelID, memberID, now)
	}
	mustExecCmdFixture(t, runtime, `
INSERT INTO workspace_teams (
 id, workspace_id, handle, display_name, description, avatar_url, visibility, status,
 created_by_member_id, created_at, updated_at, archived_at, active_handle_key
) VALUES ($1, $2, 'exec-receipt-team', 'Exec Receipt Team', 'Original description', '', 'private', 'active', $3, $4, $4, NULL, $5)
`, execFixtureTeamID, execFixtureWorkspaceID, execFixtureOwnerMemberID, now, execFixtureWorkspaceID+":exec-receipt-team")
	mustExecCmdFixture(t, runtime, `
INSERT INTO workspace_team_members (
 id, workspace_id, team_id, actor_kind, actor_id, role, role_label,
 role_overlay_prompt, role_overlay_version, wake_on_team_mention, sort_order,
 added_by_member_id, added_at, updated_at, removed_at, active_member_key,
 active_agent_team_key, active_leader_key
) VALUES ($1, $2, $3, 'agent', $4, 'leader', '', 'Leader overlay', 1, TRUE, 10,
 $5, $6, $6, NULL, $7, $8, $9)
`, execFixtureTeamMemberID, execFixtureWorkspaceID, execFixtureTeamID, execFixtureAgentMemberID,
		execFixtureOwnerMemberID, now, execFixtureTeamID+":agent:"+execFixtureAgentMemberID,
		execFixtureWorkspaceID+":"+execFixtureAgentMemberID+":"+execFixtureTeamID,
		execFixtureWorkspaceID+":"+execFixtureTeamID)
}

func mustExecCmdFixture(t *testing.T, runtime apitestkit.Runtime, query string, args ...any) {
	t.Helper()
	_, err := runtime.Pool.Exec(context.Background(), query, args...)
	require.NoError(t, err)
}
