diff --git a/apps/backend/internal/mcp/handlers/create_task_initial_prompt_workflow_test.go b/apps/backend/internal/mcp/handlers/create_task_initial_prompt_workflow_test.go new file mode 100644 index 0000000000..34eb7895cb --- /dev/null +++ b/apps/backend/internal/mcp/handlers/create_task_initial_prompt_workflow_test.go @@ -0,0 +1,164 @@ +package handlers + +import ( + "context" + "encoding/json" + "testing" + "time" + + "github.com/kandev/kandev/internal/orchestrator" + "github.com/kandev/kandev/internal/task/models" + "github.com/kandev/kandev/internal/task/service" + usermodels "github.com/kandev/kandev/internal/user/models" + workflowmodels "github.com/kandev/kandev/internal/workflow/models" + ws "github.com/kandev/kandev/pkg/websocket" + "github.com/stretchr/testify/require" +) + +func TestHandleCreateTask_InitialPromptUsesRequestedWorkflowStepMode(t *testing.T) { + for _, tc := range []struct { + name string + explicitStep bool + wantIntent string + wantInitialPrompt bool + wantDeferredStart bool + wantRequestCount int + }{ + { + name: "explicit step admits turn before start", + explicitStep: true, + wantIntent: "start_created", + wantInitialPrompt: true, + wantDeferredStart: true, + wantRequestCount: 2, + }, + { + name: "omitted step uses destination auto start", + explicitStep: false, + wantIntent: "start", + wantRequestCount: 1, + }, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + taskSvc, repo, workflowCtrl, workflowRepo := newTestTaskServiceWithWorkflow(t) + workspace, workflow := defaultWorkspaceAndWorkflow(t, ctx, taskSvc) + seedWorkflowStep(t, ctx, workflowRepo, &workflowmodels.WorkflowStep{ + ID: "step-backlog-" + tc.name, + WorkflowID: workflow.ID, + Name: "Backlog", + Position: 0, + IsStartStep: true, + AgentProfileID: "profile-backlog", + }) + destination := seedWorkflowStep(t, ctx, workflowRepo, &workflowmodels.WorkflowStep{ + ID: "step-spec-" + tc.name, + WorkflowID: workflow.ID, + Name: "Spec", + Position: 1, + AgentProfileID: "profile-destination", + Events: workflowmodels.StepEvents{ + OnEnter: []workflowmodels.OnEnterAction{{Type: workflowmodels.OnEnterAutoStartAgent}}, + }, + }) + taskSvc.SetWorkflowStepGetter(&staticWorkflowStepGetter{steps: map[string]*workflowmodels.WorkflowStep{ + "step-backlog-" + tc.name: { + ID: "step-backlog-" + tc.name, WorkflowID: workflow.ID, Name: "Backlog", Position: 0, + IsStartStep: true, AgentProfileID: "profile-backlog", + }, + destination.ID: destination, + }}) + + source, err := taskSvc.CreateTask(ctx, &service.CreateTaskRequest{ + WorkspaceID: workspace.ID, + WorkflowID: workflow.ID, + WorkflowStepID: "step-backlog-" + tc.name, + Title: "Source task", + }) + require.NoError(t, err) + require.NoError(t, repo.CreateTaskSession(ctx, &models.TaskSession{ + ID: "source-session-" + tc.name, + TaskID: source.Task.ID, + AgentProfileID: "profile-source", + ExecutorProfileID: "executor-source", + State: models.TaskSessionStateWaitingForInput, + IsPrimary: true, + StartedAt: time.Now().UTC(), + })) + + launcher := newMockSessionLauncher() + launcher.calls = make(chan struct{}, tc.wantRequestCount) + h := NewHandlers(taskSvc, workflowCtrl, nil, nil, nil, repo, repo, nil, nil, nil, launcher, nil, testLogger(t)) + settings := &mcpUserSettingsProvider{settings: &usermodels.UserSettings{ + MCPTaskAgentProfileDefault: usermodels.MCPTaskAgentProfileDefaultCurrentTask, + }} + h.SetUserSettingsProvider(settings) + + payload := map[string]interface{}{ + "source_task_id": source.Task.ID, + "source_session_id": "source-session-" + tc.name, + "workspace_id": workspace.ID, + "workflow_id": workflow.ID, + "title": "Created task", + "description": "write the specification", + } + if tc.explicitStep { + payload["workflow_step_id"] = destination.ID + } + + resp, err := h.handleCreateTask( + mcpTestKanbanContext(ctx, workspace.ID, source.Task.ID, "source-session-"+tc.name), + makeWSMessage(t, ws.ActionMCPCreateTask, payload), + ) + require.NoError(t, err) + require.Equal(t, ws.MessageTypeResponse, resp.Type, "payload: %s", string(resp.Payload)) + + for index := 0; index < tc.wantRequestCount; index++ { + select { + case <-launcher.calls: + case <-time.After(2 * time.Second): + t.Fatalf("LaunchSession call %d did not complete", index+1) + } + } + launcher.mu.Lock() + requests := append([]*orchestrator.LaunchSessionRequest(nil), launcher.requests...) + launcher.mu.Unlock() + require.Len(t, requests, tc.wantRequestCount) + require.Equal(t, orchestrator.SessionIntent(tc.wantIntent), requests[len(requests)-1].Intent) + require.Equal(t, tc.wantInitialPrompt, requests[len(requests)-1].InitialCreatePrompt) + require.Equal(t, tc.wantDeferredStart, requests[0].DeferredStart) + + if tc.explicitStep { + require.Equal(t, orchestrator.IntentPrepare, requests[0].Intent) + require.True(t, requests[0].DeferredStart) + require.Equal(t, destination.ID, requests[0].WorkflowStepID) + require.Equal(t, orchestrator.IntentStartCreated, requests[1].Intent) + require.Equal(t, "session-1", requests[1].SessionID) + require.True(t, requests[1].InitialCreatePrompt) + require.Equal(t, "write the specification", requests[1].Prompt) + } else { + require.Equal(t, orchestrator.IntentStart, requests[0].Intent) + require.Equal(t, destination.ID, requests[0].WorkflowStepID) + require.False(t, requests[0].InitialCreatePrompt) + require.Equal(t, "write the specification", requests[0].Prompt) + } + for _, request := range requests { + require.Equal(t, "profile-destination", request.AgentProfileID, + "the destination step profile must override source task settings") + require.Equal(t, "executor-source", request.ExecutorProfileID, + "the verified source session must supply the inherited executor setting") + } + require.GreaterOrEqual(t, settings.calls, 1, "MCP user settings must participate in profile resolution") + + var result struct { + ID string `json:"id"` + WorkflowStepID string `json:"workflow_step_id"` + } + require.NoError(t, json.Unmarshal(resp.Payload, &result)) + require.Equal(t, destination.ID, result.WorkflowStepID) + rows := ledgerRowsForTask(t, repo, result.ID) + require.Equal(t, "source-session-"+tc.name, *rows[0].actorID, + "the original MCP request session must remain the creation actor") + }) + } +} diff --git a/apps/backend/internal/mcp/handlers/handlers.go b/apps/backend/internal/mcp/handlers/handlers.go index 31b5ae47b7..5545e0e122 100644 --- a/apps/backend/internal/mcp/handlers/handlers.go +++ b/apps/backend/internal/mcp/handlers/handlers.go @@ -799,6 +799,7 @@ func (h *Handlers) handleCreateTask(ctx context.Context, msg *ws.Message) (*ws.M startAgent := req.StartAgent == nil || *req.StartAgent explicitWorkspaceID := req.WorkspaceID != "" explicitWorkflowID := req.WorkflowID != "" + explicitWorkflowStep := req.WorkflowStepID != "" // Only require description for subtasks if we're starting an agent if req.ParentID != "" && req.Description == "" && startAgent { @@ -910,6 +911,7 @@ func (h *Handlers) handleCreateTask(ctx context.Context, msg *ws.Message) (*ws.M } return ws.NewError(msg.ID, msg.Action, code, err.Error(), nil) } + launchConfig.InitialCreatePrompt = startAgent && explicitWorkflowStep && req.WorkflowStepID != "" && strings.TrimSpace(req.Description) != "" metadata = workspacePolicy.MergeMetadataBlock(metadata) var deferredLaunch map[string]interface{} if startAgent { @@ -1370,6 +1372,7 @@ type mcpAutoStartConfig struct { ExecutorID string ExecutorProfileID string InitialRuntimeConfig *models.SessionRuntimeConfig + InitialCreatePrompt bool } var errMCPAgentProfileRequired = errors.New("agent_profile_id is required because the selected task profile policy, workflow, and workspace defaults did not resolve a profile") @@ -1734,7 +1737,7 @@ func (h *Handlers) launchAutoStartTask(ctx context.Context, task *models.Task, c ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), constants.AgentLaunchTimeout) defer cancel() - resp, err := h.sessionLauncher.LaunchSession(ctx, &orchestrator.LaunchSessionRequest{ + launchReq := &orchestrator.LaunchSessionRequest{ TaskID: task.ID, Intent: orchestrator.IntentStart, AgentProfileID: config.AgentProfileID, @@ -1742,12 +1745,52 @@ func (h *Handlers) launchAutoStartTask(ctx context.Context, task *models.Task, c ExecutorProfileID: config.ExecutorProfileID, WorkflowStepID: task.WorkflowStepID, Prompt: task.Description, - }) + } + if config.InitialCreatePrompt { + prepResp, prepErr := h.sessionLauncher.LaunchSession(ctx, &orchestrator.LaunchSessionRequest{ + TaskID: task.ID, + Intent: orchestrator.IntentPrepare, + AgentProfileID: config.AgentProfileID, + ExecutorID: config.ExecutorID, + ExecutorProfileID: config.ExecutorProfileID, + WorkflowStepID: task.WorkflowStepID, + InitialPromptPreview: models.NewInitialPromptPreview(strings.TrimSpace(task.Description), nil), + DeferredStart: true, + }) + if prepErr != nil { + h.logger.Error("failed to prepare initial MCP creation prompt", + zap.String("task_id", task.ID), zap.Error(prepErr)) + return + } + if prepResp == nil || prepResp.SessionID == "" { + h.logger.Error("initial MCP creation prompt preparation returned no session", + zap.String("task_id", task.ID)) + return + } + launchReq = &orchestrator.LaunchSessionRequest{ + TaskID: task.ID, + Intent: orchestrator.IntentStartCreated, + SessionID: prepResp.SessionID, + AgentProfileID: config.AgentProfileID, + ExecutorID: config.ExecutorID, + ExecutorProfileID: config.ExecutorProfileID, + WorkflowStepID: task.WorkflowStepID, + Prompt: task.Description, + InitialCreatePrompt: true, + } + } + + resp, err := h.sessionLauncher.LaunchSession(ctx, launchReq) if err != nil { h.logger.Error("failed to auto-start task", zap.String("task_id", task.ID), zap.Error(err)) return } + if resp == nil { + h.logger.Error("auto-start returned no response", + zap.String("task_id", task.ID)) + return + } h.logger.Info("auto-started agent for MCP-created task", zap.String("task_id", task.ID), zap.String("session_id", resp.SessionID)) diff --git a/apps/backend/internal/mcp/handlers/handlers_test.go b/apps/backend/internal/mcp/handlers/handlers_test.go index a3995dfa59..cda8eaf77a 100644 --- a/apps/backend/internal/mcp/handlers/handlers_test.go +++ b/apps/backend/internal/mcp/handlers/handlers_test.go @@ -2150,10 +2150,13 @@ func seedWorkflowStep(t *testing.T, ctx context.Context, repo *workflowrepo.Repo // mockSessionLauncher captures LaunchSession calls for testing autoStartTask. type mockSessionLauncher struct { - mu sync.Mutex - req *orchestrator.LaunchSessionRequest - called chan struct{} - inspect func(context.Context) + mu sync.Mutex + req *orchestrator.LaunchSessionRequest + requests []*orchestrator.LaunchSessionRequest + called chan struct{} + calls chan struct{} + calledOnce sync.Once + inspect func(context.Context) } func newMockSessionLauncher() *mockSessionLauncher { @@ -2163,11 +2166,15 @@ func newMockSessionLauncher() *mockSessionLauncher { func (m *mockSessionLauncher) LaunchSession(ctx context.Context, req *orchestrator.LaunchSessionRequest) (*orchestrator.LaunchSessionResponse, error) { m.mu.Lock() m.req = req + m.requests = append(m.requests, req) m.mu.Unlock() if m.inspect != nil { m.inspect(ctx) } - close(m.called) + m.calledOnce.Do(func() { close(m.called) }) + if m.calls != nil { + m.calls <- struct{}{} + } return &orchestrator.LaunchSessionResponse{ Success: true, TaskID: req.TaskID, @@ -2271,6 +2278,41 @@ func TestAutoStartTask_ExplicitExecutorProfilePreserved(t *testing.T) { assert.Equal(t, "", req.ExecutorID, "executorID should be empty when profile is set") } +func TestLaunchAutoStartTask_ExplicitCreatePromptUsesPreparedStart(t *testing.T) { + launcher := newMockSessionLauncher() + launcher.calls = make(chan struct{}, 2) + h := &Handlers{ + sessionLauncher: launcher, + logger: testLogger(t), + } + + h.launchAutoStartTask(context.Background(), &models.Task{ + ID: "task-1", WorkflowStepID: "step-explicit", Description: "initial request", + }, mcpAutoStartConfig{ + AgentProfileID: "agent-profile-1", + ExecutorID: models.ExecutorIDWorktree, + InitialCreatePrompt: true, + }) + + for i := 0; i < 2; i++ { + select { + case <-launcher.calls: + case <-time.After(2 * time.Second): + t.Fatalf("LaunchSession call %d did not complete", i+1) + } + } + + launcher.mu.Lock() + requests := append([]*orchestrator.LaunchSessionRequest(nil), launcher.requests...) + launcher.mu.Unlock() + require.Len(t, requests, 2) + assert.Equal(t, orchestrator.IntentPrepare, requests[0].Intent) + assert.True(t, requests[0].DeferredStart) + assert.Equal(t, orchestrator.IntentStartCreated, requests[1].Intent) + assert.Equal(t, "session-1", requests[1].SessionID) + assert.True(t, requests[1].InitialCreatePrompt) +} + func TestLaunchAutoStartTask_PreservesContextValuesWithoutCallerCancellation(t *testing.T) { type contextKey string diff --git a/apps/backend/internal/orchestrator/coordinator_stop_edges_test.go b/apps/backend/internal/orchestrator/coordinator_stop_edges_test.go index 5390dbe6bb..73bf8113b7 100644 --- a/apps/backend/internal/orchestrator/coordinator_stop_edges_test.go +++ b/apps/backend/internal/orchestrator/coordinator_stop_edges_test.go @@ -212,6 +212,7 @@ func TestFallbackFreshLaunch_CoordinatorCancellationWinsBeforeResetWrite(t *test false, "", false, + false, nil, nil, nil, @@ -267,6 +268,7 @@ func TestFallbackFreshLaunch_DoesNotResetCancellationObservedBeforeGuard(t *test false, "", false, + false, nil, nil, nil, diff --git a/apps/backend/internal/orchestrator/event_handlers_agent.go b/apps/backend/internal/orchestrator/event_handlers_agent.go index eb7ac8d691..5e9c261124 100644 --- a/apps/backend/internal/orchestrator/event_handlers_agent.go +++ b/apps/backend/internal/orchestrator/event_handlers_agent.go @@ -104,6 +104,19 @@ func (s *Service) handleAgentRunning(ctx context.Context, data watcher.AgentEven zap.String("session_state", string(session.State))) return } + switch s.consumeInitialCreatePromptPassthrough(ctx, session, data) { + case initialCreatePromptPassthroughSuppressed: + // The marked creation path already admitted this exact initial turn. + // Passthrough emits agent.running for the same launch, so only settle + // the runtime state here and leave workflow evaluation to the admission + // boundary. + s.setSessionRunning(ctx, data.TaskID, data.SessionID, session) + return + case initialCreatePromptPassthroughStale: + // A delayed event from a predecessor execution must not evaluate the + // successor's on_turn_start workflow or consume its admission evidence. + return + } s.processOnTurnStartViaEngine(ctx, data.TaskID, session) // Move session to running and task to in progress. @@ -1350,10 +1363,13 @@ func (s *Service) executeQueuedPassthroughMessageWithReservation( } type queuedPassthroughExecutionState struct { - userMessageRecorded bool - deliveryAttempted bool - dispatchErr error - finishRunning func() + userMessageRecorded bool + deliveryAttempted bool + dispatchErr error + finishRunning func() + initialCreatePromptExecutionID string + initialCreatePromptTurnID string + initialCreatePromptGeneration uint64 } func (s *Service) finishQueuedPassthroughExecution( @@ -1365,6 +1381,16 @@ func (s *Service) finishQueuedPassthroughExecution( ) { if state.dispatchErr != nil { s.reconcileQueuedCIAutoFixDispatchFailure(ctx, queuedMsg) + if initialCreatePromptPassthroughQueued(queuedMsg.Metadata) { + s.retireInitialCreatePromptPassthroughForQueueEvent( + ctx, + queuedMsg.SessionID, + identity.SessionIncarnationID, + state.initialCreatePromptExecutionID, + state.initialCreatePromptTurnID, + state.initialCreatePromptGeneration, + ) + } } s.finishQueuedMessageExecution( ctx, identity.SessionID, identity.SessionID, queuedMsg, reservation, @@ -1435,13 +1461,25 @@ func (s *Service) deliverQueuedPassthroughPrompt( return } state.userMessageRecorded, _ = queuedMsg.Metadata[metaKeyUserMessageRecorded].(bool) - if preparer, ok := s.agentManager.(passthroughRunningPreparer); ok { state.finishRunning, state.dispatchErr = preparer.PreparePassthroughRunning(identity.SessionID) if state.dispatchErr != nil { return } } + // PreparePassthroughRunning has claimed the execution that will publish the + // running event. Bind evidence only after that claim, so a replacement or a + // delayed predecessor cannot consume the marker during queue replay. + if initialCreatePromptPassthroughQueued(queuedMsg.Metadata) { + s.armQueuedInitialCreatePromptPassthrough(ctx, queuedMsg, identity) + state.initialCreatePromptTurnID = s.initialCreatePromptCurrentTurnID(ctx, queuedMsg.SessionID) + state.initialCreatePromptGeneration = s.promptGenerationForSession(ctx, queuedMsg.SessionID) + if s.agentManager != nil { + state.initialCreatePromptExecutionID, _ = s.agentManager.GetExecutionIDForSession( + ctx, queuedMsg.SessionID, + ) + } + } if state.dispatchErr = s.markQueuedPassthroughDeliveryAttempt( ctx, identity, queuedMsg, state, ); state.dispatchErr != nil { @@ -1601,6 +1639,16 @@ func (s *Service) executeQueuedMessageWithReservation( }) if err != nil { s.reconcileQueuedCIAutoFixDispatchFailure(promptCtx, queuedMsg) + if initialCreatePromptPassthroughQueued(queuedMsg.Metadata) { + s.retireInitialCreatePromptPassthroughForQueueEvent( + promptCtx, + queuedMsg.SessionID, + dispatchIdentity.SessionIncarnationID, + "", + "", + 0, + ) + } } s.finishQueuedMessageExecution( promptCtx, callerSessionID, reservedSessionID, queuedMsg, reservation, @@ -1652,6 +1700,7 @@ func (s *Service) queuedMessageAfterClaim( !turnStartAlreadyProcessed(queuedMsg.Metadata) { s.processOnTurnStartViaEngine(ctx, queuedMsg.TaskID, session) } + s.armQueuedInitialCreatePromptPassthroughForLaunch(ctx, queuedMsg, identity) return nil } } @@ -2280,6 +2329,7 @@ func (s *Service) handleAgentCompletedLocked(ctx context.Context, data watcher.A return } + s.retireInitialCreatePromptPassthroughForEvent(ctx, data) s.finishAgentCompleted(ctx, data, session, guard) } @@ -2467,7 +2517,6 @@ func (s *Service) handleAgentFailedLocked(ctx context.Context, data watcher.Agen ) return nil } - // Short transient provider errors get a paced, visible retry-with-backoff // before any red banner. This is the ONLY non-terminal // failure path, so it runs before automation finalization below — otherwise @@ -2478,6 +2527,7 @@ func (s *Service) handleAgentFailedLocked(ctx context.Context, data watcher.Agen if data.SessionID != "" && s.handleTransientFailure(ctx, data) { return nil } + s.retireInitialCreatePromptPassthroughForEvent(ctx, data) if data.SessionID != "" && s.routeDynamicAgentFailure(ctx, data, classifyKanbanFailure(data)) { return nil } @@ -3716,6 +3766,7 @@ func (s *Service) handleAgentStoppedLocked(ctx context.Context, data watcher.Age return } } + s.retireInitialCreatePromptPassthroughForEvent(ctx, data) // Don't override WAITING_FOR_INPUT or IDLE — these are "stopped on // purpose" states the caller already set. WAITING_FOR_INPUT comes from diff --git a/apps/backend/internal/orchestrator/event_handlers_test.go b/apps/backend/internal/orchestrator/event_handlers_test.go index 8f376a9146..9e65b5dc3f 100644 --- a/apps/backend/internal/orchestrator/event_handlers_test.go +++ b/apps/backend/internal/orchestrator/event_handlers_test.go @@ -409,15 +409,16 @@ type mockAgentManager struct { // set_session_mode tracking (issue #1183). Records (sessionID, modeID) for // every SetSessionModeBySessionID call. setSessionModeErr, when set, is // returned to simulate "no running agent". - setSessionModeCalls []sessionModeCall - setSessionModeErr error - mcpModeCalls []sessionModeCall - setSessionModelCalls []sessionModelCall - setSessionModelSupported bool - setSessionModelErr error - setSessionConfigCalls []sessionConfigCall - setSessionConfigSupported bool - setSessionConfigErr error + setSessionModeCalls []sessionModeCall + setSessionModeErr error + mcpModeCalls []sessionModeCall + setSessionModelCalls []sessionModelCall + setSessionModelSupported bool + setSessionModelErr error + setSessionConfigCalls []sessionConfigCall + setSessionConfigSupported bool + setSessionConfigErr error + getPromptGenerationForSessionFunc func(context.Context, string) (uint64, error) } type sessionModelCall struct { @@ -658,7 +659,10 @@ func (m *mockAgentManager) OwnsPromptActivity( activityEpoch == m.currentPromptActivityEpoch.Load() } -func (m *mockAgentManager) GetPromptGenerationForSession(_ context.Context, _ string) (uint64, error) { +func (m *mockAgentManager) GetPromptGenerationForSession(ctx context.Context, sessionID string) (uint64, error) { + if m.getPromptGenerationForSessionFunc != nil { + return m.getPromptGenerationForSessionFunc(ctx, sessionID) + } return m.currentPromptGeneration.Load(), nil } diff --git a/apps/backend/internal/orchestrator/event_handlers_transient.go b/apps/backend/internal/orchestrator/event_handlers_transient.go index 3da401b82b..6261eb06ca 100644 --- a/apps/backend/internal/orchestrator/event_handlers_transient.go +++ b/apps/backend/internal/orchestrator/event_handlers_transient.go @@ -522,6 +522,10 @@ func (s *Service) retryTransientPrompt(ctx context.Context, taskID, sessionID, e return } cp, _ := v.(capturedPrompt) + initialCreatePromptPassthrough := false + if session, sessionErr := s.repo.GetTaskSession(ctx, sessionID); sessionErr == nil && session != nil { + _, initialCreatePromptPassthrough = s.hydrateInitialCreatePromptPassthrough(session) + } if execID != "" { if !s.claimForcedExecutionCleanup(sessionID, execID) { @@ -556,7 +560,8 @@ func (s *Service) retryTransientPrompt(ctx context.Context, taskID, sessionID, e } if _, err := s.promptTask(ctx, taskID, sessionID, cp.text, cp.model, cp.planMode, cp.attachments, false, launchOriginAutomatic, promptTaskOptions{ - onAccepted: cp.onAccepted, + onAccepted: cp.onAccepted, + initialCreatePromptPassthrough: initialCreatePromptPassthrough, }); err != nil { if ctx.Err() != nil { return diff --git a/apps/backend/internal/orchestrator/event_handlers_workflow.go b/apps/backend/internal/orchestrator/event_handlers_workflow.go index 9749c722b3..b2ec6b4255 100644 --- a/apps/backend/internal/orchestrator/event_handlers_workflow.go +++ b/apps/backend/internal/orchestrator/event_handlers_workflow.go @@ -381,6 +381,14 @@ type ProcessOnTurnStartResult struct { // ProcessOnTurnStart is the public API for triggering on_turn_start events. // Called by message handlers before sending a prompt to the agent. func (s *Service) ProcessOnTurnStart(ctx context.Context, taskID, sessionID string) (ProcessOnTurnStartResult, error) { + return s.processOnTurnStartAdmission(ctx, taskID, sessionID, false) +} + +func (s *Service) processOnTurnStartAdmission( + ctx context.Context, + taskID, sessionID string, + strict bool, +) (ProcessOnTurnStartResult, error) { lock, release := s.acquireCancelInFlightGuard(sessionID) defer release() lock.Lock() @@ -394,6 +402,7 @@ func (s *Service) ProcessOnTurnStart(ctx context.Context, taskID, sessionID stri if err != nil { return ProcessOnTurnStartResult{}, fmt.Errorf("load session for on_turn_start: %w", err) } + s.clearInitialCreatePromptPassthroughForAcceptedUserTurn(ctx, session) if isTerminalSessionState(session.State) { return ProcessOnTurnStartResult{}, &executor.SessionStateSupersededError{ SessionID: session.ID, @@ -417,7 +426,13 @@ func (s *Service) ProcessOnTurnStart(ctx context.Context, taskID, sessionID stri // transition has fired cancels the signal (re-open semantics). The // user is continuing the conversation; this step is no longer "done". s.clearPendingStepSignal(ctx, session) - s.processOnTurnStartViaEngine(ctx, taskID, session) + if strict { + if _, err := s.processOnTurnStartViaEngineResult(ctx, taskID, session); err != nil { + return ProcessOnTurnStartResult{}, fmt.Errorf("evaluate on_turn_start: %w", err) + } + } else { + s.processOnTurnStartViaEngine(ctx, taskID, session) + } task, err = s.repo.GetTask(ctx, taskID) if err != nil { // Do not let a read race turn an unknown admission state into an @@ -4385,6 +4400,14 @@ func (s *Service) launchAfterOnEnterDispatch( switch { case hasAutoStart && isPassthrough && session.State != models.TaskSessionStateCreated: + if s.initialCreatePromptPassthroughQueuePending(ctx, sessionID) { + // Queue promotion enters the destination step before its queued + // creation prompt is delivered. Let the guarded queue worker send + // that prompt once; the destination's automatic prompt must not + // create a competing passthrough turn. + s.drainQueuedMessageForPromptableSessionWithHandoff(ctx, taskID, sessionID, step.ID, handoffOnce) + return + } // Started passthrough path: write prompt directly to PTY stdin. // By the time processOnEnter runs (from an on_turn_complete transition), // the agent has finished its previous turn and the PTY is waiting for input. @@ -5740,12 +5763,17 @@ func (s *Service) handleCreatedAutoStartLaunchFailure( references []v1.EntityReference, takenMsg *messagequeue.QueuedMessage, handoffText string, + initialCreatePromptPassthrough bool, ) { + queueCtx := ctx + if initialCreatePromptPassthrough { + queueCtx = withInitialCreatePromptPassthroughQueue(ctx) + } promptQueued := false if shouldQueueIfBusy && (isAgentAlreadyRunningError(launchErr) || isSessionBusyError(launchErr) || isTransientPromptError(launchErr)) { if queueErr := s.queueAutoStartPrompt( - ctx, taskID, sessionID, prompt, planMode, + queueCtx, taskID, sessionID, prompt, planMode, attachments, origin, userMessageRecorded, references, handoffText, ); queueErr != nil { s.logger.Warn("failed to queue auto-start prompt after launch failure", @@ -5785,6 +5813,11 @@ func (s *Service) autoStartStepPrompt( // Track the original message so terminal failure paths can restore it // instead of dropping the user's prompt or attachments on the floor. takenMsg, mergedPrompt, attachments, references, queuedHandoff := s.takeAndMergeHandoffMessage(ctx, sessionID, prompt) + initialCreatePromptPassthrough := takenMsg != nil && initialCreatePromptPassthroughQueued(takenMsg.Metadata) + queueCtx := ctx + if initialCreatePromptPassthrough { + queueCtx = withInitialCreatePromptPassthroughQueue(ctx) + } prompt = mergedPrompt agentPrompt := AppendEntityReferenceContext(prompt, references) effectiveAgentPrompt := s.effectivePromptForSession(sessionID, agentPrompt, planMode, session) @@ -5825,7 +5858,7 @@ func (s *Service) autoStartStepPrompt( // userMessageRecorded=false: recordAutoStartMessage has not run yet — // the drain side (executeQueuedMessage) is responsible for inserting // the chat-history row. - queued, err := s.queueAutoStartPromptIfRunning(ctx, taskID, session, prompt, planMode, attachments, origin, false, references, handoffForQueue) + queued, err := s.queueAutoStartPromptIfRunning(queueCtx, taskID, session, prompt, planMode, attachments, origin, false, references, handoffForQueue) if err != nil { requeueTaken() return err @@ -5915,6 +5948,9 @@ func (s *Service) autoStartStepPrompt( dispatchInputPresent := strings.TrimSpace(recordedPrompt) != "" || strings.TrimSpace(dispatchPrompt) != "" || len(attachments) > 0 userMsgRecorded := s.recordAutoStartMessage(ctx, taskID, sessionID, recordedPrompt, planMode, origin, references, attachments) + if initialCreatePromptPassthrough && session.IsPassthrough && session.State != models.TaskSessionStateCreated { + s.armInitialCreatePromptPassthrough(ctx, session, s.initialCreatePromptCurrentTurnID(ctx, sessionID)) + } // If the session is in CREATED state, the agent was never started (e.g. workspace-only // preparation from a blocked auto-start). PromptTask will reject CREATED sessions, @@ -5971,7 +6007,7 @@ func (s *Service) autoStartStepPrompt( launchCtx := withWorkflowStartPromptAttempt(ctx, workflowAttempt) execution, err := s.startCreatedSessionWithComposedPrompt( launchCtx, taskID, sessionID, session.AgentProfileID, - recordedPrompt, agentPrompt, true, planMode, true, attachments, references, + recordedPrompt, agentPrompt, true, planMode, true, initialCreatePromptPassthrough, attachments, references, ) if execution == nil { workflowAttempt.retire() @@ -5985,6 +6021,7 @@ func (s *Service) autoStartStepPrompt( ctx, taskID, sessionID, stepName, prompt, err, planMode, shouldQueueIfBusy, userMsgRecorded, attachments, origin, references, takenMsg, handoffForQueue, + initialCreatePromptPassthrough, ) } return err @@ -6038,7 +6075,8 @@ func (s *Service) autoStartStepPrompt( zap.String("session_id", sessionID), zap.String("step_name", stepName)) return s.fallbackFreshLaunchOnMissingExecution( - ctx, taskID, sessionID, recordedPrompt, true, dispatchPrompt, planMode, takenMsg, attachments, references, + ctx, taskID, sessionID, recordedPrompt, true, dispatchPrompt, planMode, + initialCreatePromptPassthrough, takenMsg, attachments, references, ) } @@ -6049,7 +6087,7 @@ func (s *Service) autoStartStepPrompt( // chat row was successfully inserted above; a failed write passes false, // letting the drain re-attempt insertion. if isAgentAlreadyRunningError(err) && shouldQueueIfBusy { - if queueErr := s.queueAutoStartPrompt(ctx, taskID, sessionID, prompt, planMode, attachments, origin, userMsgRecorded, references, handoffForQueue); queueErr != nil { + if queueErr := s.queueAutoStartPrompt(queueCtx, taskID, sessionID, prompt, planMode, attachments, origin, userMsgRecorded, references, handoffForQueue); queueErr != nil { requeueTaken() return queueErr } @@ -6064,7 +6102,7 @@ func (s *Service) autoStartStepPrompt( if shouldQueueIfBusy { // Pass userMsgRecorded so the drain skips CreateUserMessage only when // the chat row was successfully inserted above by recordAutoStartMessage. - if queueErr := s.queueAutoStartPrompt(ctx, taskID, sessionID, prompt, planMode, attachments, origin, userMsgRecorded, references, handoffForQueue); queueErr != nil { + if queueErr := s.queueAutoStartPrompt(queueCtx, taskID, sessionID, prompt, planMode, attachments, origin, userMsgRecorded, references, handoffForQueue); queueErr != nil { requeueTaken() return queueErr } @@ -6107,6 +6145,7 @@ func (s *Service) fallbackFreshLaunchOnMissingExecution( promptAlreadyComposed bool, retryPrompt string, planMode bool, + initialCreatePromptPassthrough bool, takenMsg *messagequeue.QueuedMessage, attachments []v1.MessageAttachment, references []v1.EntityReference, @@ -6141,7 +6180,7 @@ func (s *Service) fallbackFreshLaunchOnMissingExecution( if promptAlreadyComposed { _, launchErr = s.startCreatedSessionWithComposedPrompt( ctx, taskID, sessionID, fresh.AgentProfileID, - prompt, retryPrompt, true, planMode, true, attachments, references, + prompt, retryPrompt, true, planMode, true, initialCreatePromptPassthrough, attachments, references, ) } else { _, launchErr = s.StartCreatedSession( @@ -6438,6 +6477,9 @@ func (s *Service) persistAutoStartPromptWithAdmission( return nil, fmt.Errorf("message queue is not configured") } meta := workflowMessageMetadata(planMode, origin, references) + if initialCreatePromptPassthroughQueueFromContext(ctx) { + meta[metaKeyInitialCreatePromptPassthrough] = true + } if userMessageRecorded { meta[metaKeyUserMessageRecorded] = true } @@ -7580,6 +7622,7 @@ func (s *Service) applyEngineTransitionWithCommitMode( // (e.g., a template-level alias like "review" that doesn't resolve to a real UUID). targetStep, err := s.workflowStepGetter.GetStep(ctx, result.ToStepID) if err != nil { + recordWorkflowTransitionError(ctx, err) s.logger.Warn("target step not found, skipping transition", zap.String("step_id", result.ToStepID), zap.Error(err)) @@ -7590,6 +7633,7 @@ func (s *Service) applyEngineTransitionWithCommitMode( } if sessionLifecycle { if err := s.preflightWorkflowStepCredentials(ctx, taskID, session, targetStep); err != nil { + recordWorkflowTransitionError(ctx, err) s.logger.Warn("target profile credential preflight failed, skipping transition", zap.String("task_id", taskID), zap.String("step_id", result.ToStepID), @@ -7602,6 +7646,7 @@ func (s *Service) applyEngineTransitionWithCommitMode( fromStep, err := s.loadWorkflowStepForLifecycle(ctx, result.FromStepID, "transition source") if err != nil { + recordWorkflowTransitionError(ctx, err) s.logger.Warn("failed to load from-step for on_exit", zap.String("step_id", result.FromStepID), zap.Error(err)) @@ -7626,6 +7671,7 @@ func (s *Service) applyEngineTransitionWithCommitMode( } applied, err := commit(applyCtx) if err != nil { + recordWorkflowTransitionError(ctx, err) s.logger.Error("failed to apply engine transition", zap.String("task_id", taskID), zap.String("session_id", session.ID), @@ -7636,6 +7682,7 @@ func (s *Service) applyEngineTransitionWithCommitMode( return false } if !applied { + recordWorkflowTransitionError(ctx, errors.New("workflow transition commit was not applied")) return false } @@ -7699,6 +7746,7 @@ func (s *Service) applyEngineTransitionWithCommitMode( // to the correct agent. effectiveSession, ok := s.maybySwitchSessionForProfile(ctx, taskID, session, targetStep, fromStep) if !ok { + recordWorkflowTransitionError(ctx, errors.New("workflow on_turn_start session preparation failed")) return false } // A queued prompt has already claimed RUNNING before its turn-start @@ -7774,31 +7822,40 @@ func (s *Service) launchProcessOnEnter( // actions. Falls back to the legacy method when the engine is not initialized. // Returns true if a step transition occurred. func (s *Service) processOnTurnStartViaEngine(ctx context.Context, taskID string, session *models.TaskSession) bool { + transitioned, _ := s.processOnTurnStartViaEngineResult(ctx, taskID, session) + return transitioned +} + +func (s *Service) processOnTurnStartViaEngineResult( + ctx context.Context, + taskID string, + session *models.TaskSession, +) (bool, error) { if session == nil || models.IsCompletionFollowUpSession(session.Metadata) { - return false + return false, nil } task, err := s.repo.GetTask(ctx, taskID) if err != nil { s.logger.Warn("failed to load task for on_turn_start", zap.String("task_id", taskID), zap.Error(err)) - return false + return false, err } if s.workflowEngine == nil { - return s.processOnTurnStart(ctx, task, session) + return s.processOnTurnStart(ctx, task, session), nil } if session.ID == "" || s.workflowStepGetter == nil { - return false + return false, nil } if task.WorkflowStepID == "" { - return false + return false, nil } // Skip workflow step actions for ephemeral tasks (quick chat) - they have no workflow if task.IsEphemeral { - return false + return false, nil } state := s.buildMachineState(ctx, task, session) @@ -7814,11 +7871,11 @@ func (s *Service) processOnTurnStartViaEngine(ctx context.Context, taskID string zap.String("task_id", taskID), zap.String("session_id", session.ID), zap.Error(err)) - return false + return false, err } if !result.Transitioned { - return false + return false, nil } s.logger.Info("engine: on_turn_start transition", @@ -7828,5 +7885,14 @@ func (s *Service) processOnTurnStartViaEngine(ctx context.Context, taskID string zap.String("to_step_id", result.ToStepID)) // on_turn_start does NOT trigger on_enter (user's message is the next prompt). - return s.applyEngineTransitionWithMode(ctx, taskID, session, result, engine.TriggerOnTurnStart, "", transitionLifecycleOnTurnStart) + transitionCapture := &workflowTransitionErrorCapture{} + transitionCtx := withWorkflowTransitionErrorCapture(ctx, transitionCapture) + transitioned := s.applyEngineTransitionWithMode(transitionCtx, taskID, session, result, engine.TriggerOnTurnStart, "", transitionLifecycleOnTurnStart) + if transitionCapture.err != nil { + return false, transitionCapture.err + } + if !transitioned { + return false, errors.New("workflow on_turn_start transition was not applied") + } + return true, nil } diff --git a/apps/backend/internal/orchestrator/executor/executor.go b/apps/backend/internal/orchestrator/executor/executor.go index a3481514e9..ded5cbb637 100644 --- a/apps/backend/internal/orchestrator/executor/executor.go +++ b/apps/backend/internal/orchestrator/executor/executor.go @@ -661,14 +661,19 @@ type LaunchOptions struct { OfficeAgentProfileID string ExecutorID string TurnID string - Prompt string - PriorACPSession string // ACP session ID to resume for the same concrete profile - WorkflowStepID string - StartAgent bool - McpMode string // MCP tool mode: empty task default, McpModeTaskTitlePending, McpModeConfig, McpModeOffice, or McpModeAutomation - McpProfile *mcpprofile.Context - Attachments []v1.MessageAttachment - Env map[string]string + // OnExecutionAdmitted runs after the launch path has identified and + // persisted the execution that will receive this turn, but before its + // process is started. Callers use this boundary to bind turn-scoped + // evidence to the execution that actually won admission. + OnExecutionAdmitted func(executionID string) + Prompt string + PriorACPSession string // ACP session ID to resume for the same concrete profile + WorkflowStepID string + StartAgent bool + McpMode string // MCP tool mode: empty task default, McpModeTaskTitlePending, McpModeConfig, McpModeOffice, or McpModeAutomation + McpProfile *mcpprofile.Context + Attachments []v1.MessageAttachment + Env map[string]string // AdditionalSkillSlugs are materialized for this launch in addition to the // durable profile selection. AdditionalSkillSlugs []string diff --git a/apps/backend/internal/orchestrator/executor/executor_execute.go b/apps/backend/internal/orchestrator/executor/executor_execute.go index c134e2ce3f..a088b40bbf 100644 --- a/apps/backend/internal/orchestrator/executor/executor_execute.go +++ b/apps/backend/internal/orchestrator/executor/executor_execute.go @@ -1668,7 +1668,7 @@ func (e *Executor) LaunchPreparedSession(ctx context.Context, task *v1.Task, ses return nil, fmt.Errorf("check runtime inventory for session %q: %w", sessionID, hasRunningErr) } if hasRunning { - result, existingErr := e.startAgentOnExistingWorkspaceWithRequest(launchCtx, task, session, prompt, startAgent, opts.McpMode, req, opts.TurnID) + result, existingErr := e.startAgentOnExistingWorkspaceWithRequest(launchCtx, task, session, prompt, startAgent, opts.McpMode, req, opts.OnExecutionAdmitted, opts.TurnID) if !errors.Is(existingErr, ErrStaleExecution) && !errors.Is(existingErr, ErrAgentCommandMissing) { if releaseErr := releaseSelectedWorktreeRecovery(ctx, &recoveryAdmission); releaseErr != nil { return nil, errors.Join(existingErr, fmt.Errorf("release worktree recovery admission: %w", releaseErr)) @@ -1706,6 +1706,9 @@ func (e *Executor) LaunchPreparedSession(ctx context.Context, task *v1.Task, ses repositoryID, taskRepositoryID := failingLaunchRepositoryIdentity(req, err) return nil, e.handleLaunchFailure(launchCtx, task.ID, sessionID, repositoryID, taskRepositoryID, err) } + if startAgent && opts.OnExecutionAdmitted != nil { + opts.OnExecutionAdmitted(resp.AgentExecutionID) + } // Capture the current HEAD commit as the base commit for this session asynchronously. // This allows us to filter git log to only show commits made during the session. @@ -2366,7 +2369,7 @@ func (e *Executor) startAgentOnExistingWorkspace(ctx context.Context, task *v1.T SessionID: session.ID, Env: cloneStringMap(env), } - return e.startAgentOnExistingWorkspaceWithRequest(ctx, task, session, prompt, startAgent, mcpMode, request, turnIDs...) + return e.startAgentOnExistingWorkspaceWithRequest(ctx, task, session, prompt, startAgent, mcpMode, request, nil, turnIDs...) } func (e *Executor) startAgentOnExistingWorkspaceWithRequest( @@ -2377,6 +2380,7 @@ func (e *Executor) startAgentOnExistingWorkspaceWithRequest( startAgent bool, mcpMode string, request *LaunchAgentRequest, + onExecutionAdmitted func(string), turnIDs ...string, ) (*TaskExecution, error) { executionID, err := e.agentManager.GetExecutionIDForSession(ctx, session.ID) @@ -2451,6 +2455,9 @@ func (e *Executor) startAgentOnExistingWorkspaceWithRequest( LastUpdate: now, SessionID: session.ID, } + if onExecutionAdmitted != nil { + onExecutionAdmitted(executionID) + } // Start the agent process asynchronously e.startAgentProcessAsync(ctx, task.ID, session.ID, executionID) diff --git a/apps/backend/internal/orchestrator/fallback_fresh_launch_handoff_test.go b/apps/backend/internal/orchestrator/fallback_fresh_launch_handoff_test.go index 145e56322f..bd681e5947 100644 --- a/apps/backend/internal/orchestrator/fallback_fresh_launch_handoff_test.go +++ b/apps/backend/internal/orchestrator/fallback_fresh_launch_handoff_test.go @@ -62,7 +62,7 @@ func TestFallbackFreshLaunch_ComposedPromptSurvivesStepRecomposition(t *testing. composedPrompt := "Run the next workflow step.\n\n" + stepHandoffPromptHeading + "\n\n" + handoff err = svc.fallbackFreshLaunchOnMissingExecution( - ctx, taskID, sessionID, composedPrompt, true, composedPrompt, false, nil, nil, nil, + ctx, taskID, sessionID, composedPrompt, true, composedPrompt, false, false, nil, nil, nil, ) require.NoError(t, err) require.Contains(t, launchedDescription, handoff, diff --git a/apps/backend/internal/orchestrator/service.go b/apps/backend/internal/orchestrator/service.go index dc6deb22ce..3c496bf213 100644 --- a/apps/backend/internal/orchestrator/service.go +++ b/apps/backend/internal/orchestrator/service.go @@ -695,9 +695,11 @@ type Service struct { watcher *watcher.Watcher // Message queue service for queueing messages while agent is running - messageQueue *messagequeue.Service - passthroughDispatchMu sync.Mutex - passthroughDispatches map[string]map[*passthroughDispatchToken]struct{} + messageQueue *messagequeue.Service + passthroughDispatchMu sync.Mutex + passthroughDispatches map[string]map[*passthroughDispatchToken]struct{} + initialCreatePromptMu sync.Mutex + initialCreatePromptPassthrough map[string]initialCreatePromptPassthroughEvidence // autoStartOnCreateMu serializes the local ownership hand-off for the // durable auto-start-on-create marker. The database marker survives a @@ -2591,6 +2593,7 @@ func (s *Service) startTurnForSessionWithOwnershipChecked( if turnIDVal, ok := s.activeTurns.Load(sessionID); ok { if turnID, ok := turnIDVal.(string); ok && turnID != "" { + s.clearInitialCreatePromptPassthroughForNewTurnInMemory(sessionID, turnID) s.bindAcceptedDispatchTurn(sessionID, turnID) return turnID, false, nil, nil } @@ -2602,6 +2605,7 @@ func (s *Service) startTurnForSessionWithOwnershipChecked( } if turn != nil { s.activeTurns.Store(sessionID, turn.ID) + s.clearInitialCreatePromptPassthroughForNewTurnInMemory(sessionID, turn.ID) s.bindAcceptedDispatchTurn(sessionID, turn.ID) return turn.ID, false, nil, nil } @@ -2617,9 +2621,11 @@ func (s *Service) startTurnForSessionWithOwnershipChecked( if reserve { s.reservedPromptTurns.Store(sessionID, newReservedPromptTurn(turn.ID)) + s.clearInitialCreatePromptPassthroughForNewTurnInMemory(sessionID, turn.ID) return turn.ID, true, turn, nil } s.activeTurns.Store(sessionID, turn.ID) + s.clearInitialCreatePromptPassthroughForNewTurnInMemory(sessionID, turn.ID) s.bindAcceptedDispatchTurn(sessionID, turn.ID) return turn.ID, true, nil, nil } @@ -4080,7 +4086,7 @@ func (s *Service) NotifyQueuedUserPrompt(ctx context.Context, taskID, sessionID go func(profileID string) { _, launchErr := s.startCreatedSessionWithComposedPrompt( context.WithoutCancel(ctx), taskID, sessionID, profileID, - "", "", true, false, false, nil, nil, + "", "", true, false, false, false, nil, nil, ) if launchErr != nil && !errors.Is(launchErr, ErrAgentPromptInProgress) { s.logger.Warn("failed to start session for durable queued prompt", diff --git a/apps/backend/internal/orchestrator/session_launch.go b/apps/backend/internal/orchestrator/session_launch.go index 3739e89d72..f4fa76c83b 100644 --- a/apps/backend/internal/orchestrator/session_launch.go +++ b/apps/backend/internal/orchestrator/session_launch.go @@ -106,6 +106,10 @@ type LaunchSessionRequest struct { // kept off the wire protocol (`json:"-"`) — a client must not be able to // suppress the upgrade and strand a passthrough session without a PTY. DeferredStart bool `json:"-"` + // InitialCreatePrompt marks the one eligible, prompt-bearing explicit-step + // create flow. It is server-side provenance, so clients cannot turn the + // generic launch path into a workflow turn-start admission. + InitialCreatePrompt bool `json:"-"` // InitialPromptPreview is supplied only by task creation after attachment claim. InitialPromptPreview *models.InitialPromptPreview `json:"-"` Attachments []v1.MessageAttachment `json:"attachments,omitempty"` @@ -492,6 +496,9 @@ func (s *Service) shouldBlockAutoStart(ctx context.Context, req *LaunchSessionRe // launchStartCreated starts agent execution on an existing CREATED session. func (s *Service) launchStartCreated(ctx context.Context, req *LaunchSessionRequest) (*LaunchSessionResponse, error) { + if req.InitialCreatePrompt { + return s.launchInitialCreatePrompt(ctx, req) + } autoStart := req.AutoStart || req.ActivationSource == LaunchActivationSourceSessionOpen parkingStamp := s.captureWorkflowParkingStamp(ctx, req.SessionID) execution, err := s.StartCreatedSession( diff --git a/apps/backend/internal/orchestrator/task_create_prompt.go b/apps/backend/internal/orchestrator/task_create_prompt.go new file mode 100644 index 0000000000..550aacfa6b --- /dev/null +++ b/apps/backend/internal/orchestrator/task_create_prompt.go @@ -0,0 +1,834 @@ +package orchestrator + +import ( + "context" + "encoding/json" + "fmt" + "strings" + + "github.com/kandev/kandev/internal/orchestrator/messagequeue" + "github.com/kandev/kandev/internal/orchestrator/watcher" + "github.com/kandev/kandev/internal/task/models" + "go.uber.org/zap" +) + +const metaKeyInitialCreatePromptPassthrough = models.SessionMetaKeyInitialCreatePromptPassthrough + +type initialCreatePromptPassthroughQueueContextKey struct{} + +func withInitialCreatePromptPassthroughQueue(ctx context.Context) context.Context { + return context.WithValue(ctx, initialCreatePromptPassthroughQueueContextKey{}, true) +} + +func initialCreatePromptPassthroughQueueFromContext(ctx context.Context) bool { + marked, _ := ctx.Value(initialCreatePromptPassthroughQueueContextKey{}).(bool) + return marked +} + +func initialCreatePromptPassthroughQueued(metadata map[string]interface{}) bool { + marked, _ := metadata[metaKeyInitialCreatePromptPassthrough].(bool) + return marked +} + +type initialCreatePromptAdmission struct { + SessionID string + Queued bool +} + +// initialCreatePromptPassthroughEvidence binds creation-admission evidence to +// the execution and turn that admitted the prompt. Queue incarnation alone is +// insufficient because an execution can be replaced without replacing the +// session. +type initialCreatePromptPassthroughEvidence struct { + QueueIncarnationID string `json:"queue_incarnation_id,omitempty"` + ExecutionID string `json:"execution_id,omitempty"` + ExecutionBound bool `json:"execution_bound"` + TurnID string `json:"turn_id,omitempty"` + PromptGeneration uint64 `json:"prompt_generation,omitempty"` + Consumed bool `json:"consumed,omitempty"` +} + +type initialCreatePromptPassthroughDisposition uint8 + +const ( + initialCreatePromptPassthroughAbsent initialCreatePromptPassthroughDisposition = iota + initialCreatePromptPassthroughSuppressed + initialCreatePromptPassthroughStale + initialCreatePromptPassthroughNewTurn +) + +type workflowTransitionErrorContextKey struct{} + +type workflowTransitionErrorCapture struct { + err error +} + +func withWorkflowTransitionErrorCapture(ctx context.Context, capture *workflowTransitionErrorCapture) context.Context { + return context.WithValue(ctx, workflowTransitionErrorContextKey{}, capture) +} + +func recordWorkflowTransitionError(ctx context.Context, err error) { + if err == nil { + return + } + capture, _ := ctx.Value(workflowTransitionErrorContextKey{}).(*workflowTransitionErrorCapture) + if capture != nil && capture.err == nil { + capture.err = err + } +} + +func (s *Service) armInitialCreatePromptPassthrough( + ctx context.Context, + session *models.TaskSession, + turnIDs ...string, +) { + s.armInitialCreatePromptPassthroughWithExecution(ctx, session, true, turnIDs...) +} + +// armInitialCreatePromptPassthroughForLaunch leaves execution identity +// unbound until the executor admits the execution that will receive the +// prompt. This prevents a delayed predecessor event from consuming or +// retiring the marker while a prepared workspace is being replaced. +func (s *Service) armInitialCreatePromptPassthroughForLaunch( + ctx context.Context, + session *models.TaskSession, + turnIDs ...string, +) { + s.armInitialCreatePromptPassthroughWithExecution(ctx, session, false, turnIDs...) +} + +func (s *Service) armInitialCreatePromptPassthroughWithExecution( + ctx context.Context, + session *models.TaskSession, + bindExecution bool, + turnIDs ...string, +) { + if session == nil || session.ID == "" { + return + } + turnID := "" + if len(turnIDs) > 0 { + turnID = turnIDs[0] + } + if turnID == "" { + turnID = s.initialCreatePromptCurrentTurnID(ctx, session.ID) + } + executionID := "" + if bindExecution && s.agentManager != nil { + executionID, _ = s.agentManager.GetExecutionIDForSession(ctx, session.ID) + } + s.initialCreatePromptMu.Lock() + defer s.initialCreatePromptMu.Unlock() + if s.initialCreatePromptPassthrough == nil { + s.initialCreatePromptPassthrough = make(map[string]initialCreatePromptPassthroughEvidence) + } + evidence := initialCreatePromptPassthroughEvidence{ + QueueIncarnationID: session.QueueIncarnationID, + ExecutionID: executionID, + ExecutionBound: bindExecution && executionID != "", + TurnID: turnID, + PromptGeneration: s.promptGenerationForSession(ctx, session.ID), + } + s.initialCreatePromptPassthrough[session.ID] = evidence + s.persistInitialCreatePromptPassthroughLocked(ctx, session.ID, &evidence) +} + +func (s *Service) bindInitialCreatePromptPassthroughExecution( + ctx context.Context, + sessionID, turnID, executionID string, +) { + if sessionID == "" { + return + } + s.initialCreatePromptMu.Lock() + defer s.initialCreatePromptMu.Unlock() + if s.initialCreatePromptPassthrough == nil { + s.initialCreatePromptPassthrough = make(map[string]initialCreatePromptPassthroughEvidence) + } + evidence, ok := s.initialCreatePromptPassthrough[sessionID] + if !ok { + return + } + if evidence.TurnID != "" && turnID != "" && evidence.TurnID != turnID { + return + } + if evidence.TurnID == "" { + evidence.TurnID = turnID + } + if executionID != "" && evidence.ExecutionID != executionID { + // The executor calls this at the admission boundary. A prepared + // workspace can be replaced while retaining the session and queue + // incarnation, so the admitted execution supersedes any predecessor + // identity captured while the marker was armed. + evidence.ExecutionID = executionID + evidence.Consumed = false + } + if executionID != "" { + evidence.ExecutionBound = true + } + if evidence.PromptGeneration == 0 { + evidence.PromptGeneration = s.promptGenerationForSession(ctx, sessionID) + } + s.initialCreatePromptPassthrough[sessionID] = evidence + s.persistInitialCreatePromptPassthroughLocked(ctx, sessionID, &evidence) +} + +func (s *Service) persistInitialCreatePromptPassthroughLocked( + ctx context.Context, + sessionID string, + evidence *initialCreatePromptPassthroughEvidence, +) { + if s.repo == nil || sessionID == "" { + return + } + if err := s.repo.SetSessionMetadataKey( + context.WithoutCancel(ctx), + sessionID, + models.SessionMetaKeyInitialCreatePromptPassthrough, + evidence, + ); err != nil && s.logger != nil { + s.logger.Warn("failed to persist initial creation prompt passthrough evidence", + zap.String("session_id", sessionID), zap.Error(err)) + } +} + +func (s *Service) clearInitialCreatePromptPassthroughLocked(ctx context.Context, sessionID string) { + if s.repo == nil || sessionID == "" { + return + } + if err := s.repo.SetSessionMetadataKey( + context.WithoutCancel(ctx), + sessionID, + models.SessionMetaKeyInitialCreatePromptPassthrough, + nil, + ); err != nil && s.logger != nil { + s.logger.Warn("failed to clear initial creation prompt passthrough evidence", + zap.String("session_id", sessionID), zap.Error(err)) + } +} + +func initialCreatePromptPassthroughEvidenceFromMetadata( + metadata map[string]interface{}, +) (initialCreatePromptPassthroughEvidence, bool) { + if metadata == nil { + return initialCreatePromptPassthroughEvidence{}, false + } + raw, ok := metadata[models.SessionMetaKeyInitialCreatePromptPassthrough] + if !ok || raw == nil { + return initialCreatePromptPassthroughEvidence{}, false + } + data, err := json.Marshal(raw) + if err != nil { + return initialCreatePromptPassthroughEvidence{}, false + } + var evidence initialCreatePromptPassthroughEvidence + if err := json.Unmarshal(data, &evidence); err != nil { + return initialCreatePromptPassthroughEvidence{}, false + } + return evidence, true +} + +func (s *Service) hydrateInitialCreatePromptPassthrough( + session *models.TaskSession, +) (initialCreatePromptPassthroughEvidence, bool) { + if session == nil || session.ID == "" { + return initialCreatePromptPassthroughEvidence{}, false + } + s.initialCreatePromptMu.Lock() + defer s.initialCreatePromptMu.Unlock() + if evidence, ok := s.initialCreatePromptPassthrough[session.ID]; ok { + return evidence, true + } + evidence, ok := initialCreatePromptPassthroughEvidenceFromMetadata(session.Metadata) + if !ok { + return initialCreatePromptPassthroughEvidence{}, false + } + if s.initialCreatePromptPassthrough == nil { + s.initialCreatePromptPassthrough = make(map[string]initialCreatePromptPassthroughEvidence) + } + s.initialCreatePromptPassthrough[session.ID] = evidence + return evidence, true +} + +// initialCreatePromptCurrentTurnID reads the current turn without creating a +// turn. Creating one while validating a lifecycle event would make a delayed +// event look like a new user turn. +func (s *Service) initialCreatePromptCurrentTurnID(ctx context.Context, sessionID string) string { + if sessionID == "" { + return "" + } + if value, ok := s.activeTurns.Load(sessionID); ok { + if turnID, ok := value.(string); ok && turnID != "" { + return turnID + } + } + turnID, _ := s.peekActiveTurnID(ctx, sessionID) + return turnID +} + +// consumeInitialCreatePromptPassthrough classifies one agent.running event. +// A stale event is handled, but deliberately does not mutate the evidence. +// Once the matching event is seen, the evidence remains consumed until the +// matching execution/turn ends, so duplicate running notifications cannot be +// mistaken for another user turn. +func (s *Service) consumeInitialCreatePromptPassthrough( + ctx context.Context, + session *models.TaskSession, + data watcher.AgentEventData, +) initialCreatePromptPassthroughDisposition { + if session == nil || session.ID == "" { + return initialCreatePromptPassthroughAbsent + } + liveExecutionID := "" + if s.agentManager != nil { + liveExecutionID, _ = s.agentManager.GetExecutionIDForSession(ctx, session.ID) + } + currentTurnID := s.initialCreatePromptCurrentTurnID(ctx, session.ID) + currentGeneration := s.promptGenerationForSession(ctx, session.ID) + + evidence, ok := s.hydrateInitialCreatePromptPassthrough(session) + if !ok { + return initialCreatePromptPassthroughAbsent + } + disposition := initialCreatePromptEvidenceDisposition( + evidence, + session.QueueIncarnationID, + data, + liveExecutionID, + currentTurnID, + currentGeneration, + ) + if disposition == initialCreatePromptPassthroughNewTurn { + s.initialCreatePromptMu.Lock() + delete(s.initialCreatePromptPassthrough, session.ID) + s.clearInitialCreatePromptPassthroughLocked(ctx, session.ID) + s.initialCreatePromptMu.Unlock() + return disposition + } + if disposition != initialCreatePromptPassthroughAbsent { + return disposition + } + bindInitialCreatePromptEventIdentity(&evidence, data, liveExecutionID, currentTurnID, currentGeneration) + s.initialCreatePromptMu.Lock() + if evidence.Consumed { + s.initialCreatePromptPassthrough[session.ID] = evidence + s.persistInitialCreatePromptPassthroughLocked(ctx, session.ID, &evidence) + s.initialCreatePromptMu.Unlock() + return initialCreatePromptPassthroughSuppressed + } + evidence.Consumed = true + s.initialCreatePromptPassthrough[session.ID] = evidence + s.persistInitialCreatePromptPassthroughLocked(ctx, session.ID, &evidence) + s.initialCreatePromptMu.Unlock() + return initialCreatePromptPassthroughSuppressed +} + +func initialCreatePromptEvidenceDisposition( + evidence initialCreatePromptPassthroughEvidence, + queueIncarnationID string, + data watcher.AgentEventData, + liveExecutionID, currentTurnID string, + currentGeneration uint64, +) initialCreatePromptPassthroughDisposition { + if evidence.QueueIncarnationID != "" && evidence.QueueIncarnationID != queueIncarnationID { + return initialCreatePromptPassthroughStale + } + if evidence.ExecutionBound { + if !initialCreatePromptExecutionMatches( + evidence.ExecutionID, data.AgentExecutionID, liveExecutionID, + ) { + return initialCreatePromptPassthroughStale + } + } else if data.AgentExecutionID == "" || liveExecutionID == "" || data.AgentExecutionID != liveExecutionID { + // Queue admission can arm the marker before the passthrough runtime has + // claimed an execution. The first running event may race the callback + // that normally binds it, so accept only the event whose identity also + // matches the live execution lookup. + return initialCreatePromptPassthroughStale + } + if initialCreatePromptGenerationMatches(evidence.PromptGeneration, data.PromptGeneration, currentGeneration) { + if evidence.TurnID != "" && currentTurnID != "" && evidence.TurnID != currentTurnID { + // Running events carry no turn ID. A turn change is actionable only + // when its prompt generation identifies the new turn. Otherwise this + // can be a duplicate or delayed event for the old turn. + return initialCreatePromptPassthroughStale + } + return initialCreatePromptPassthroughAbsent + } + if evidence.PromptGeneration != 0 && currentGeneration == data.PromptGeneration && data.PromptGeneration != 0 { + return initialCreatePromptPassthroughNewTurn + } + return initialCreatePromptPassthroughStale +} + +func bindInitialCreatePromptEventIdentity( + evidence *initialCreatePromptPassthroughEvidence, + data watcher.AgentEventData, + liveExecutionID, currentTurnID string, + currentGeneration uint64, +) { + if evidence.TurnID == "" { + evidence.TurnID = currentTurnID + } + if evidence.ExecutionID == "" { + evidence.ExecutionID = data.AgentExecutionID + if evidence.ExecutionID == "" { + evidence.ExecutionID = liveExecutionID + } + } + if evidence.ExecutionID != "" { + evidence.ExecutionBound = true + } + if evidence.PromptGeneration == 0 { + evidence.PromptGeneration = data.PromptGeneration + if evidence.PromptGeneration == 0 { + evidence.PromptGeneration = currentGeneration + } + } +} + +func initialCreatePromptExecutionMatches(expected, event, live string) bool { + // A bound marker is consumed only by an event that carries the exact + // admitted execution. The live lookup is a second consistency check; it + // cannot substitute for an event identity because a delayed predecessor + // notification may arrive while the successor is live. + if expected == "" || event == "" || event != expected { + return false + } + return live == "" || live == event +} + +func initialCreatePromptGenerationMatches(expected, event, current uint64) bool { + if expected == 0 { + return event == 0 || current == 0 || event == current + } + if event != 0 && event != expected { + return false + } + return event != 0 || current == 0 || current == expected +} + +func initialCreatePromptTerminalEventMatches( + evidence initialCreatePromptPassthroughEvidence, + data watcher.AgentEventData, + liveExecutionID, currentTurnID string, +) bool { + if !initialCreatePromptExecutionMatches(evidence.ExecutionID, data.AgentExecutionID, liveExecutionID) { + return false + } + // Terminal lifecycle events are published while the lifecycle manager may + // still hold its prompt-generation lock. The event's generation is the + // authoritative identity when present; a zero-generation event still has + // the exact execution and current turn checks above, so do not synchronously + // query the manager and risk deadlocking the publisher. + if evidence.PromptGeneration != 0 && data.PromptGeneration != 0 && + evidence.PromptGeneration != data.PromptGeneration { + return false + } + return evidence.TurnID == "" || currentTurnID == "" || evidence.TurnID == currentTurnID +} + +func (s *Service) retireInitialCreatePromptPassthroughForEvent( + ctx context.Context, + data watcher.AgentEventData, +) { + if data.SessionID == "" { + return + } + session, err := s.repo.GetTaskSession(ctx, data.SessionID) + if err != nil || session == nil { + return + } + s.hydrateInitialCreatePromptPassthrough(session) + liveExecutionID := "" + if s.agentManager != nil { + liveExecutionID, _ = s.agentManager.GetExecutionIDForSession(ctx, data.SessionID) + } + currentTurnID := s.initialCreatePromptCurrentTurnID(ctx, data.SessionID) + + s.initialCreatePromptMu.Lock() + defer s.initialCreatePromptMu.Unlock() + evidence, ok := s.initialCreatePromptPassthrough[data.SessionID] + if !ok || (evidence.QueueIncarnationID != "" && evidence.QueueIncarnationID != session.QueueIncarnationID) { + return + } + if !evidence.ExecutionBound { + return + } + if !initialCreatePromptTerminalEventMatches(evidence, data, liveExecutionID, currentTurnID) { + return + } + delete(s.initialCreatePromptPassthrough, data.SessionID) + s.clearInitialCreatePromptPassthroughLocked(ctx, data.SessionID) +} + +func (s *Service) retireInitialCreatePromptPassthroughForQueue( + sessionID, queueIncarnationID, turnID string, + promptGeneration uint64, +) { + if sessionID == "" { + return + } + s.initialCreatePromptMu.Lock() + defer s.initialCreatePromptMu.Unlock() + evidence, ok := s.initialCreatePromptPassthrough[sessionID] + if !ok || (evidence.QueueIncarnationID != "" && + (queueIncarnationID == "" || evidence.QueueIncarnationID != queueIncarnationID)) { + return + } + if evidence.ExecutionBound || (evidence.TurnID != "" && + (turnID == "" || evidence.TurnID != turnID)) { + return + } + if evidence.PromptGeneration != 0 && promptGeneration != 0 && + evidence.PromptGeneration != promptGeneration { + return + } + delete(s.initialCreatePromptPassthrough, sessionID) + s.clearInitialCreatePromptPassthroughLocked(context.Background(), sessionID) +} + +func (s *Service) retireInitialCreatePromptPassthroughForQueueEvent( + ctx context.Context, + sessionID, queueIncarnationID, executionID, turnID string, + promptGeneration uint64, +) { + if sessionID == "" || executionID == "" { + return + } + session, err := s.repo.GetTaskSession(ctx, sessionID) + if err != nil || session == nil { + return + } + if queueIncarnationID == "" { + queueIncarnationID = session.QueueIncarnationID + } + s.hydrateInitialCreatePromptPassthrough(session) + s.initialCreatePromptMu.Lock() + defer s.initialCreatePromptMu.Unlock() + evidence, ok := s.initialCreatePromptPassthrough[sessionID] + if !ok || !initialCreatePromptQueueEventMatchesEvidence( + evidence, queueIncarnationID, executionID, turnID, promptGeneration, + ) { + return + } + delete(s.initialCreatePromptPassthrough, sessionID) + s.clearInitialCreatePromptPassthroughLocked(ctx, sessionID) +} + +func initialCreatePromptQueueEventMatchesEvidence( + evidence initialCreatePromptPassthroughEvidence, + queueIncarnationID, executionID, turnID string, + promptGeneration uint64, +) bool { + if evidence.QueueIncarnationID != "" && + (evidence.QueueIncarnationID != queueIncarnationID || queueIncarnationID == "") { + return false + } + if !evidence.ExecutionBound || evidence.ExecutionID != executionID { + return false + } + if evidence.TurnID != "" && (turnID == "" || evidence.TurnID != turnID) { + return false + } + return evidence.PromptGeneration == 0 || promptGeneration == 0 || + evidence.PromptGeneration == promptGeneration +} + +func (s *Service) clearInitialCreatePromptPassthroughForNewTurn(sessionID, turnID string) { + if sessionID == "" || turnID == "" { + return + } + // A service restart can leave only the durable marker in the session row. + // Hydrate it before comparing turns so the first accepted later turn also + // clears evidence that was not present in the new process's memory. + s.initialCreatePromptMu.Lock() + _, inMemory := s.initialCreatePromptPassthrough[sessionID] + s.initialCreatePromptMu.Unlock() + if !inMemory && s.repo != nil { + if session, err := s.repo.GetTaskSession(context.Background(), sessionID); err == nil { + s.hydrateInitialCreatePromptPassthrough(session) + } + } + s.clearInitialCreatePromptPassthroughForNewTurnInMemory(sessionID, turnID) +} + +func (s *Service) clearInitialCreatePromptPassthroughForNewTurnInMemory(sessionID, turnID string) { + if sessionID == "" || turnID == "" { + return + } + s.initialCreatePromptMu.Lock() + defer s.initialCreatePromptMu.Unlock() + evidence, ok := s.initialCreatePromptPassthrough[sessionID] + if ok && evidence.TurnID != "" && evidence.TurnID != turnID { + delete(s.initialCreatePromptPassthrough, sessionID) + s.clearInitialCreatePromptPassthroughLocked(context.Background(), sessionID) + } +} + +func (s *Service) clearInitialCreatePromptPassthroughForAcceptedUserTurn( + ctx context.Context, + session *models.TaskSession, +) { + if session == nil || session.ID == "" { + return + } + s.hydrateInitialCreatePromptPassthrough(session) + s.initialCreatePromptMu.Lock() + defer s.initialCreatePromptMu.Unlock() + if _, ok := s.initialCreatePromptPassthrough[session.ID]; !ok { + return + } + delete(s.initialCreatePromptPassthrough, session.ID) + s.clearInitialCreatePromptPassthroughLocked(ctx, session.ID) +} + +func (s *Service) armQueuedInitialCreatePromptPassthrough( + ctx context.Context, + queuedMsg *messagequeue.QueuedMessage, + identity messagequeue.QueueSessionIdentity, +) { + if queuedMsg == nil || !initialCreatePromptPassthroughQueued(queuedMsg.Metadata) || s.agentManager == nil { + return + } + session, err := s.repo.GetTaskSession(ctx, queuedMsg.SessionID) + if err != nil || !s.queuedSessionMatchesIdentity(session, identity) || + !s.agentManager.IsPassthroughSession(ctx, session.ID) { + return + } + s.armInitialCreatePromptPassthrough(ctx, session, s.initialCreatePromptCurrentTurnID(ctx, session.ID)) +} + +func (s *Service) armQueuedInitialCreatePromptPassthroughForLaunch( + ctx context.Context, + queuedMsg *messagequeue.QueuedMessage, + identity messagequeue.QueueSessionIdentity, +) { + if queuedMsg == nil || !initialCreatePromptPassthroughQueued(queuedMsg.Metadata) || s.agentManager == nil { + return + } + session, err := s.repo.GetTaskSession(ctx, queuedMsg.SessionID) + if err != nil || !s.queuedSessionMatchesIdentity(session, identity) || + !s.agentManager.IsPassthroughSession(ctx, session.ID) { + return + } + // Queue admission has accepted the message, but the passthrough runtime + // that will publish agent.running has not been claimed yet. Keep the marker + // inert until deliverQueuedPassthroughPrompt binds that exact execution. + s.armInitialCreatePromptPassthroughForLaunch(ctx, session, s.initialCreatePromptCurrentTurnID(ctx, session.ID)) +} + +// initialCreatePromptPassthroughQueuePending reports whether a destination +// on_enter must wait for the admitted creation prompt. Queue promotion can run +// on the passthrough path before the ordinary queue worker claims its row; an +// automatic step prompt in that gap would otherwise become a second user turn. +func (s *Service) initialCreatePromptPassthroughQueuePending( + ctx context.Context, + sessionID string, +) bool { + if sessionID == "" || s.messageQueue == nil { + return false + } + session, err := s.repo.GetTaskSession(ctx, sessionID) + if err != nil || session == nil { + return false + } + _, ok := s.hydrateInitialCreatePromptPassthrough(session) + if !ok { + return false + } + status := s.messageQueue.GetStatus(ctx, sessionID) + for _, entry := range status.Entries { + if initialCreatePromptPassthroughQueued(entry.Metadata) { + return true + } + } + return s.isQueuedDispatchInFlight(sessionID) +} + +// admitInitialCreatePrompt runs the explicit creation prompt through the same +// turn-start boundary as an ordinary user message and resolves the session that +// owns the resulting workflow step. The caller must pass the original prepared +// session; a profile switch may retire that session during admission. +func (s *Service) admitInitialCreatePrompt( + ctx context.Context, + taskID, sessionID string, +) (initialCreatePromptAdmission, error) { + initialWorkflowStepID := "" + if task, taskErr := s.repo.GetTask(ctx, taskID); taskErr == nil && task != nil { + initialWorkflowStepID = task.WorkflowStepID + } + failure := func(err error) (initialCreatePromptAdmission, error) { + return initialCreatePromptAdmission{ + SessionID: s.resolveInitialCreatePromptFailureSession( + ctx, taskID, sessionID, initialWorkflowStepID, + ), + }, err + } + result, err := s.processOnTurnStartAdmission(ctx, taskID, sessionID, true) + if err != nil { + return failure(fmt.Errorf("process initial creation prompt turn start: %w", err)) + } + + activeSession, err := s.repo.GetTaskSession(ctx, sessionID) + if err != nil { + return failure(fmt.Errorf("reload initial creation prompt session: %w", err)) + } + if activeSession == nil { + return failure(fmt.Errorf("initial creation prompt session %q was not found", sessionID)) + } + // Profile routing can park the source instead of completing it. Resolve the + // task's newest active session whenever the prepared session is no longer the + // primary owner, so the prompt cannot be delivered to a parked predecessor. + if activeSession.State == models.TaskSessionStateCompleted || !activeSession.IsPrimary { + activeSession, err = s.repo.GetActiveTaskSessionByTaskID(ctx, taskID) + if err != nil { + return failure(fmt.Errorf("resolve initial creation prompt replacement session: %w", err)) + } + if activeSession == nil { + return failure(fmt.Errorf("initial creation prompt session %q was replaced without an active session", sessionID)) + } + } + if activeSession.TaskID != taskID { + return failure(fmt.Errorf("initial creation prompt session does not belong to task")) + } + return initialCreatePromptAdmission{ + SessionID: activeSession.ID, + Queued: result.Queued, + }, nil +} + +// resolveInitialCreatePromptFailureSession returns the session that still owns +// a failed strict admission. A source that was parked or completed during the +// transition no longer owns the prompt; only a nonterminal primary successor +// whose workflow step changed during this admission can receive the error. If +// the source was independently cancelled or superseded, return no owner so a +// stale creation error cannot terminalize an unrelated successor. +func (s *Service) resolveInitialCreatePromptFailureSession( + ctx context.Context, + taskID, sourceSessionID, initialWorkflowStepID string, +) string { + source, err := s.repo.GetTaskSession(ctx, sourceSessionID) + if err != nil || source == nil { + return "" + } + if source.TaskID != taskID { + return "" + } + task, err := s.repo.GetTask(ctx, taskID) + if err != nil || task == nil { + return "" + } + if initialCreatePromptSourceOwnsFailure(source, task.WorkflowStepID, initialWorkflowStepID) { + return source.ID + } + if task.WorkflowStepID == initialWorkflowStepID { + return "" + } + active, err := s.repo.GetActiveTaskSessionByTaskID(ctx, taskID) + if err != nil || !initialCreatePromptSuccessorOwnsFailure(active, source.ID, taskID) { + return "" + } + return active.ID +} + +func initialCreatePromptSourceOwnsFailure( + source *models.TaskSession, + currentWorkflowStepID, initialWorkflowStepID string, +) bool { + return models.IsTaskLookupActiveSessionState(source.State) && + (currentWorkflowStepID == initialWorkflowStepID || source.IsPrimary) +} + +func initialCreatePromptSuccessorOwnsFailure( + active *models.TaskSession, sourceSessionID, taskID string, +) bool { + return active != nil && active.ID != sourceSessionID && active.TaskID == taskID && + active.IsPrimary && models.IsTaskLookupActiveSessionState(active.State) +} + +func (s *Service) launchInitialCreatePrompt( + ctx context.Context, + req *LaunchSessionRequest, +) (*LaunchSessionResponse, error) { + if strings.TrimSpace(req.Prompt) == "" { + return nil, fmt.Errorf("initial creation prompt requires non-empty prompt") + } + parkingStamp := s.captureWorkflowParkingStamp(ctx, req.SessionID) + admission, err := s.admitInitialCreatePrompt(ctx, req.TaskID, req.SessionID) + if err != nil { + return nil, s.handleSessionLaunchFailure(ctx, req.TaskID, admission.SessionID, err) + } + + if admission.Queued { + return s.queueInitialCreatePrompt(ctx, req, admission.SessionID) + } + + initialReq := *req + initialReq.SessionID = admission.SessionID + initialReq.InitialCreatePrompt = false + autoStart := initialReq.AutoStart || initialReq.ActivationSource == LaunchActivationSourceSessionOpen + execution, err := s.startCreatedSession( + ctx, + initialReq.TaskID, + initialReq.SessionID, + initialReq.AgentProfileID, + initialReq.Prompt, + initialReq.SkipMessageRecord, + initialReq.PlanMode, + autoStart, + initialReq.Attachments, + nil, + "", + startCreatedSessionOptions{initialCreatePrompt: true}, + ) + if err != nil { + return nil, s.handleSessionLaunchFailure(ctx, req.TaskID, admission.SessionID, err) + } + if execution != nil { + s.bindInitialCreatePromptPassthroughExecution( + ctx, + admission.SessionID, + s.initialCreatePromptCurrentTurnID(ctx, admission.SessionID), + execution.AgentExecutionID, + ) + s.clearWorkflowParkingForSession(ctx, admission.SessionID, parkingStamp) + } + return executionToLaunchResponse(req.TaskID, execution), nil +} + +func (s *Service) queueInitialCreatePrompt( + ctx context.Context, + req *LaunchSessionRequest, + sessionID string, +) (*LaunchSessionResponse, error) { + if err := s.QueueUserPrompt( + ctx, req.TaskID, sessionID, req.Prompt, "", req.PlanMode, req.Attachments, + map[string]interface{}{ + MetaKeyTurnStartAlreadyProcessed: true, + metaKeyInitialCreatePromptPassthrough: true, + }, false, + ); err != nil { + return nil, s.handleSessionLaunchFailure( + ctx, req.TaskID, sessionID, fmt.Errorf("queue initial creation prompt: %w", err), + ) + } + if session, sessionErr := s.repo.GetTaskSession(ctx, sessionID); sessionErr == nil && session != nil { + s.armInitialCreatePromptPassthroughForLaunch( + ctx, session, s.initialCreatePromptCurrentTurnID(ctx, sessionID), + ) + } + session, err := s.repo.GetTaskSession(ctx, sessionID) + if err != nil { + return nil, s.handleSessionLaunchFailure( + ctx, req.TaskID, sessionID, + fmt.Errorf("reload queued initial creation prompt session: %w", err), + ) + } + return &LaunchSessionResponse{ + Success: true, + TaskID: req.TaskID, + SessionID: sessionID, + State: string(session.State), + }, nil +} diff --git a/apps/backend/internal/orchestrator/task_create_prompt_test.go b/apps/backend/internal/orchestrator/task_create_prompt_test.go new file mode 100644 index 0000000000..8d7cb57b62 --- /dev/null +++ b/apps/backend/internal/orchestrator/task_create_prompt_test.go @@ -0,0 +1,759 @@ +package orchestrator + +import ( + "context" + "errors" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/kandev/kandev/internal/agent/runtime/lifecycle" + "github.com/kandev/kandev/internal/orchestrator/executor" + "github.com/kandev/kandev/internal/orchestrator/messagequeue" + "github.com/kandev/kandev/internal/orchestrator/watcher" + "github.com/kandev/kandev/internal/task/models" + wfmodels "github.com/kandev/kandev/internal/workflow/models" + v1 "github.com/kandev/kandev/pkg/api/v1" +) + +type initialCreatePromptQueueFailureRepository struct { + messagequeue.Repository + err error +} + +func (r *initialCreatePromptQueueFailureRepository) Insert( + ctx context.Context, + msg *messagequeue.QueuedMessage, + maxPerSession int, +) error { + return r.err +} + +func (r *initialCreatePromptQueueFailureRepository) InsertForSession( + ctx context.Context, + identity messagequeue.QueueSessionIdentity, + msg *messagequeue.QueuedMessage, + maxPerSession int, +) error { + return r.err +} + +func TestInitialCreatePrompt_TransitionsBeforeDispatch(t *testing.T) { + ctx := context.Background() + repo := setupTestRepo(t) + seedSession(t, repo, "task-create-prompt", "session-create-prompt", "step-backlog") + require.NoError(t, repo.UpdateTaskSessionState(ctx, "session-create-prompt", models.TaskSessionStateCreated, "")) + + stepGetter := newMockStepGetter() + stepGetter.steps["step-backlog"] = &wfmodels.WorkflowStep{ + ID: "step-backlog", WorkflowID: "wf1", Name: "Backlog", Position: 0, + Events: wfmodels.StepEvents{ + OnTurnStart: []wfmodels.OnTurnStartAction{{Type: wfmodels.OnTurnStartMoveToNext}}, + }, + } + stepGetter.steps["step-spec"] = &wfmodels.WorkflowStep{ + ID: "step-spec", WorkflowID: "wf1", Name: "Spec", Position: 1, + } + + seedExecutorRunning(t, repo, "session-create-prompt", "task-create-prompt", "execution-create-prompt") + taskRepo := newMockTaskRepo() + taskRepo.tasks["task-create-prompt"] = &v1.Task{ + ID: "task-create-prompt", Title: "Create prompt", Description: "initial prompt", + State: v1.TaskStateInProgress, + } + agentMgr := &mockAgentManager{isAgentRunning: true, repoForExecutionLookup: repo} + var providerDispatches atomic.Int32 + dispatchObserved := make(chan string, 1) + agentMgr.launchAgentFunc = func(_ context.Context, _ *executor.LaunchAgentRequest) (*executor.LaunchAgentResponse, error) { + return &executor.LaunchAgentResponse{AgentExecutionID: "execution-create-prompt-dispatch"}, nil + } + agentMgr.startAgentProcessFunc = func(_ context.Context, executionID string) error { + providerDispatches.Add(1) + dispatchObserved <- executionID + return nil + } + svc := createEngineServiceWithScheduler(t, repo, stepGetter, taskRepo, agentMgr) + messages := &mockMessageCreator{} + svc.messageCreator = messages + + _, err := svc.LaunchSession(ctx, &LaunchSessionRequest{ + TaskID: "task-create-prompt", + SessionID: "session-create-prompt", + Intent: IntentStartCreated, + AgentProfileID: "profile-create-prompt", + Prompt: "initial prompt", + InitialCreatePrompt: true, + }) + require.NoError(t, err) + select { + case executionID := <-dispatchObserved: + require.Equal(t, "execution-create-prompt", executionID) + case <-time.After(time.Second): + t.Fatal("timed out waiting for the initial provider dispatch") + } + + task, err := repo.GetTask(ctx, "task-create-prompt") + require.NoError(t, err) + require.Equal(t, "step-spec", task.WorkflowStepID) + require.Len(t, messages.userMessages, 1) + require.Contains(t, messages.userMessages[0].content, "initial prompt") + require.Equal(t, int32(1), providerDispatches.Load(), + "the initial prompt must cross one provider dispatch boundary") +} + +func TestInitialCreatePrompt_TransitionFailurePreventsLaunch(t *testing.T) { + ctx := context.Background() + repo := setupTestRepo(t) + seedSession(t, repo, "task-create-failure", "session-create-failure", "step-backlog") + require.NoError(t, repo.UpdateTaskSessionState(ctx, "session-create-failure", models.TaskSessionStateCreated, "")) + + stepGetter := newMockStepGetter() + stepGetter.steps["step-backlog"] = &wfmodels.WorkflowStep{ + ID: "step-backlog", WorkflowID: "wf1", Name: "Backlog", Position: 0, + Events: wfmodels.StepEvents{ + OnTurnStart: []wfmodels.OnTurnStartAction{{Type: wfmodels.OnTurnStartMoveToNext}}, + }, + } + taskRepo := newMockTaskRepo() + seedMockTaskState(taskRepo, "task-create-failure", v1.TaskStateInProgress) + svc := createEngineServiceWithScheduler(t, repo, stepGetter, taskRepo, &mockAgentManager{}) + + _, err := svc.LaunchSession(ctx, &LaunchSessionRequest{ + TaskID: "task-create-failure", + SessionID: "session-create-failure", + Intent: IntentStartCreated, + AgentProfileID: "profile-create-failure", + Prompt: "initial prompt", + InitialCreatePrompt: true, + }) + require.Error(t, err) + + task, err := repo.GetTask(ctx, "task-create-failure") + require.NoError(t, err) + require.Equal(t, "step-backlog", task.WorkflowStepID) + session, err := repo.GetTaskSession(ctx, "session-create-failure") + require.NoError(t, err) + require.Equal(t, models.TaskSessionStateFailed, session.State) + require.Contains(t, session.ErrorMessage, "on_turn_start") +} + +func TestInitialCreatePrompt_AdmissionFailureDoesNotFailSupersededSuccessor(t *testing.T) { + ctx := context.Background() + repo := setupTestRepo(t) + seedSession(t, repo, "task-create-superseded", "session-create-superseded", "step-backlog") + require.NoError(t, repo.UpdateTaskSessionState( + ctx, "session-create-superseded", models.TaskSessionStateCancelled, "operator stopped", + )) + source, err := repo.GetTaskSession(ctx, "session-create-superseded") + require.NoError(t, err) + source.IsPrimary = false + require.NoError(t, repo.UpdateTaskSession(ctx, source)) + require.NoError(t, repo.CreateTaskSession(ctx, &models.TaskSession{ + ID: "session-create-successor", + TaskID: "task-create-superseded", + State: models.TaskSessionStateCreated, + IsPrimary: true, + StartedAt: time.Now().UTC(), + })) + + stepGetter := newMockStepGetter() + stepGetter.steps["step-backlog"] = &wfmodels.WorkflowStep{ + ID: "step-backlog", WorkflowID: "wf1", Name: "Backlog", Position: 0, + } + taskRepo := newMockTaskRepo() + seedMockTaskState(taskRepo, "task-create-superseded", v1.TaskStateInProgress) + launchCalls := 0 + agentMgr := &mockAgentManager{ + launchAgentFunc: func(context.Context, *executor.LaunchAgentRequest) (*executor.LaunchAgentResponse, error) { + launchCalls++ + return nil, errors.New("unexpected launch") + }, + } + svc := createEngineServiceWithScheduler(t, repo, stepGetter, taskRepo, agentMgr) + + _, err = svc.LaunchSession(ctx, &LaunchSessionRequest{ + TaskID: "task-create-superseded", SessionID: "session-create-superseded", + Intent: IntentStartCreated, AgentProfileID: "profile-create-superseded", + Prompt: "initial prompt", InitialCreatePrompt: true, + }) + require.Error(t, err) + require.Zero(t, launchCalls, "a superseded admission must not dispatch a provider launch") + + failedSource, err := repo.GetTaskSession(ctx, "session-create-superseded") + require.NoError(t, err) + require.Equal(t, models.TaskSessionStateCancelled, failedSource.State) + successor, err := repo.GetTaskSession(ctx, "session-create-successor") + require.NoError(t, err) + require.Equal(t, models.TaskSessionStateCreated, successor.State, + "a successor that did not own this creation attempt must remain launchable") +} + +func TestInitialCreatePrompt_LaunchFailureUsesReplacementSession(t *testing.T) { + ctx := context.Background() + repo := setupTestRepo(t) + seedSession(t, repo, "task-create-replacement-failure", "session-create-replacement-source", "step-backlog") + require.NoError(t, repo.UpdateTaskSessionState( + ctx, "session-create-replacement-source", models.TaskSessionStateCreated, "", + )) + source, err := repo.GetTaskSession(ctx, "session-create-replacement-source") + require.NoError(t, err) + source.AgentProfileID = "profile-source" + source.ExecutorID = models.ExecutorIDLocal + source.TaskEnvironmentID = "environment-create-replacement" + require.NoError(t, repo.UpdateTaskSession(ctx, source)) + require.NoError(t, repo.CreateTaskEnvironment(ctx, &models.TaskEnvironment{ + ID: source.TaskEnvironmentID, + TaskID: source.TaskID, + ExecutorType: string(models.ExecutorTypeLocal), + Status: models.TaskEnvironmentStatusReady, + })) + + stepGetter := newMockStepGetter() + stepGetter.steps["step-backlog"] = &wfmodels.WorkflowStep{ + ID: "step-backlog", WorkflowID: "wf1", Name: "Backlog", Position: 0, + Events: wfmodels.StepEvents{ + OnTurnStart: []wfmodels.OnTurnStartAction{{Type: wfmodels.OnTurnStartMoveToNext}}, + }, + } + stepGetter.steps["step-spec"] = &wfmodels.WorkflowStep{ + ID: "step-spec", WorkflowID: "wf1", Name: "Spec", Position: 1, + AgentProfileID: "profile-destination", + } + taskRepo := newMockTaskRepo() + taskRepo.tasks["task-create-replacement-failure"] = &v1.Task{ + ID: "task-create-replacement-failure", WorkspaceID: "ws1", WorkflowID: "wf1", + Title: "Replacement failure", Description: "initial prompt", + State: v1.TaskStateInProgress, + } + launchCalls := 0 + agentMgr := &mockAgentManager{ + getExecutionIDForSessionFunc: func(_ context.Context, sessionID string) (string, error) { + if sessionID == source.ID { + return "", lifecycle.ErrNoExecutionForSession + } + return "", errors.New("execution intentionally unavailable") + }, + launchAgentFunc: func(context.Context, *executor.LaunchAgentRequest) (*executor.LaunchAgentResponse, error) { + launchCalls++ + if launchCalls == 1 { + return &executor.LaunchAgentResponse{AgentExecutionID: "replacement-workspace"}, nil + } + return nil, errors.New("destination launch failed") + }, + } + svc := createEngineServiceWithScheduler(t, repo, stepGetter, taskRepo, agentMgr) + + _, err = svc.LaunchSession(ctx, &LaunchSessionRequest{ + TaskID: "task-create-replacement-failure", SessionID: source.ID, + Intent: IntentStartCreated, AgentProfileID: "profile-source", + Prompt: "initial prompt", InitialCreatePrompt: true, + }) + require.Error(t, err) + require.Contains(t, err.Error(), "destination launch failed") + require.Equal(t, 2, launchCalls, "workspace preparation and the actual prompt launch must both be attempted") + + original, err := repo.GetTaskSession(ctx, source.ID) + require.NoError(t, err) + require.Equal(t, models.TaskSessionStateWaitingForInput, original.State, + "the parked source must remain available without owning the new prompt") + sessions, err := repo.ListTaskSessions(ctx, "task-create-replacement-failure") + require.NoError(t, err) + require.Len(t, sessions, 2) + var replacement *models.TaskSession + for _, candidate := range sessions { + if candidate.ID != source.ID { + replacement = candidate + break + } + } + require.NotNil(t, replacement) + require.Equal(t, "profile-destination", replacement.AgentProfileID) + require.Equal(t, models.TaskSessionStateFailed, replacement.State, + "the launch error belongs to the replacement that received the prompt") + require.Contains(t, replacement.ErrorMessage, "destination launch failed") +} + +func TestInitialCreatePrompt_PassthroughRunningDoesNotRepeatTurnStart(t *testing.T) { + ctx := context.Background() + repo := setupTestRepo(t) + seedSession(t, repo, "task-create-passthrough", "session-create-passthrough", "step-backlog") + require.NoError(t, repo.UpdateTaskSessionState(ctx, "session-create-passthrough", models.TaskSessionStateWaitingForInput, "")) + + stepGetter := newMockStepGetter() + stepGetter.steps["step-backlog"] = &wfmodels.WorkflowStep{ + ID: "step-backlog", WorkflowID: "wf1", Name: "Backlog", Position: 0, + Events: wfmodels.StepEvents{ + OnTurnStart: []wfmodels.OnTurnStartAction{{Type: wfmodels.OnTurnStartMoveToNext}}, + }, + } + stepGetter.steps["step-spec"] = &wfmodels.WorkflowStep{ + ID: "step-spec", WorkflowID: "wf1", Name: "Spec", Position: 1, + } + seedExecutorRunning(t, repo, "session-create-passthrough", "task-create-passthrough", "execution-create-passthrough") + agentMgr := &mockAgentManager{isPassthrough: true, repoForExecutionLookup: repo} + taskRepo := newMockTaskRepo() + seedMockTaskState(taskRepo, "task-create-passthrough", v1.TaskStateInProgress) + svc := createTestServiceWithAgent(repo, stepGetter, taskRepo, agentMgr) + session, err := repo.GetTaskSession(ctx, "session-create-passthrough") + require.NoError(t, err) + svc.activeTurns.Store(session.ID, "turn-create-initial") + svc.armInitialCreatePromptPassthrough(ctx, session, "turn-create-initial") + + svc.handleAgentRunning(ctx, watcher.AgentEventData{ + TaskID: "task-create-passthrough", SessionID: "session-create-passthrough", + AgentExecutionID: "execution-create-passthrough", + }) + task, err := repo.GetTask(ctx, "task-create-passthrough") + require.NoError(t, err) + require.Equal(t, "step-backlog", task.WorkflowStepID, + "the passthrough running event must not repeat the already-admitted trigger") + + svc.handleAgentRunning(ctx, watcher.AgentEventData{ + TaskID: "task-create-passthrough", SessionID: "session-create-passthrough", + AgentExecutionID: "execution-create-passthrough", + }) + task, err = repo.GetTask(ctx, "task-create-passthrough") + require.NoError(t, err) + require.Equal(t, "step-backlog", task.WorkflowStepID, + "a duplicate running event must not imply a later user turn") + + // A later user turn clears the old admission evidence when its turn is + // accepted. The following running event can then evaluate on_turn_start. + svc.activeTurns.Store(session.ID, "turn-create-later") + svc.clearInitialCreatePromptPassthroughForNewTurn(session.ID, "turn-create-later") + svc.handleAgentRunning(ctx, watcher.AgentEventData{ + TaskID: "task-create-passthrough", SessionID: "session-create-passthrough", + AgentExecutionID: "execution-create-passthrough", + }) + task, err = repo.GetTask(ctx, "task-create-passthrough") + require.NoError(t, err) + require.Equal(t, "step-spec", task.WorkflowStepID, + "a real later passthrough turn must still evaluate on_turn_start") +} + +func TestInitialCreatePrompt_PassthroughEvidenceSurvivesProcessRestart(t *testing.T) { + ctx := context.Background() + repo := setupTestRepo(t) + seedSession(t, repo, "task-create-passthrough-restart", "session-create-passthrough-restart", "step-backlog") + require.NoError(t, repo.UpdateTaskSessionState( + ctx, "session-create-passthrough-restart", models.TaskSessionStateWaitingForInput, "", + )) + seedExecutorRunning(t, repo, "session-create-passthrough-restart", "task-create-passthrough-restart", "execution-create-passthrough-restart") + + stepGetter := newMockStepGetter() + stepGetter.steps["step-backlog"] = &wfmodels.WorkflowStep{ + ID: "step-backlog", WorkflowID: "wf1", Name: "Backlog", Position: 0, + Events: wfmodels.StepEvents{ + OnTurnStart: []wfmodels.OnTurnStartAction{{Type: wfmodels.OnTurnStartMoveToNext}}, + }, + } + stepGetter.steps["step-spec"] = &wfmodels.WorkflowStep{ + ID: "step-spec", WorkflowID: "wf1", Name: "Spec", Position: 1, + } + taskRepo := newMockTaskRepo() + seedMockTaskState(taskRepo, "task-create-passthrough-restart", v1.TaskStateInProgress) + agentMgr := &mockAgentManager{isPassthrough: true, repoForExecutionLookup: repo} + svc := createTestServiceWithAgent(repo, stepGetter, taskRepo, agentMgr) + session, err := repo.GetTaskSession(ctx, "session-create-passthrough-restart") + require.NoError(t, err) + svc.activeTurns.Store(session.ID, "turn-create-restart") + svc.armInitialCreatePromptPassthrough(ctx, session, "turn-create-restart") + + persisted, err := repo.GetTaskSession(ctx, session.ID) + require.NoError(t, err) + require.Contains(t, persisted.Metadata, models.SessionMetaKeyInitialCreatePromptPassthrough, + "the admission evidence must survive a process restart") + + // A restarted service has no in-memory evidence map. Hydration from the + // session row must still suppress the exact initial running event. + svc.initialCreatePromptMu.Lock() + svc.initialCreatePromptPassthrough = nil + svc.initialCreatePromptMu.Unlock() + svc.handleAgentRunning(ctx, watcher.AgentEventData{ + TaskID: "task-create-passthrough-restart", SessionID: session.ID, + AgentExecutionID: "execution-create-passthrough-restart", + }) + task, err := repo.GetTask(ctx, "task-create-passthrough-restart") + require.NoError(t, err) + require.Equal(t, "step-backlog", task.WorkflowStepID, + "restart recovery must suppress the already-admitted turn") + + // Duplicate running events remain suppressed, while an explicitly accepted + // later turn clears the durable evidence and restores ordinary behavior. + svc.handleAgentRunning(ctx, watcher.AgentEventData{ + TaskID: "task-create-passthrough-restart", SessionID: session.ID, + AgentExecutionID: "execution-create-passthrough-restart", + }) + task, err = repo.GetTask(ctx, "task-create-passthrough-restart") + require.NoError(t, err) + require.Equal(t, "step-backlog", task.WorkflowStepID) + svc.activeTurns.Store(session.ID, "turn-create-restart-later") + svc.clearInitialCreatePromptPassthroughForNewTurn(session.ID, "turn-create-restart-later") + svc.handleAgentRunning(ctx, watcher.AgentEventData{ + TaskID: "task-create-passthrough-restart", SessionID: session.ID, + AgentExecutionID: "execution-create-passthrough-restart", + }) + task, err = repo.GetTask(ctx, "task-create-passthrough-restart") + require.NoError(t, err) + require.Equal(t, "step-spec", task.WorkflowStepID, + "a later user turn must evaluate on_turn_start after restart recovery") +} + +func TestInitialCreatePrompt_PassthroughEvidenceSurvivesPredecessorTerminalEvents(t *testing.T) { + ctx := context.Background() + repo := setupTestRepo(t) + seedSession(t, repo, "task-create-successor", "session-create-successor", "step-backlog") + require.NoError(t, repo.UpdateTaskSessionState(ctx, "session-create-successor", models.TaskSessionStateWaitingForInput, "")) + seedExecutorRunning(t, repo, "session-create-successor", "task-create-successor", "execution-successor") + + stepGetter := newMockStepGetter() + stepGetter.steps["step-backlog"] = &wfmodels.WorkflowStep{ + ID: "step-backlog", WorkflowID: "wf1", Name: "Backlog", Position: 0, + Events: wfmodels.StepEvents{ + OnTurnStart: []wfmodels.OnTurnStartAction{{Type: wfmodels.OnTurnStartMoveToNext}}, + }, + } + stepGetter.steps["step-spec"] = &wfmodels.WorkflowStep{ + ID: "step-spec", WorkflowID: "wf1", Name: "Spec", Position: 1, + } + taskRepo := newMockTaskRepo() + seedMockTaskState(taskRepo, "task-create-successor", v1.TaskStateInProgress) + agentMgr := &mockAgentManager{isPassthrough: true, repoForExecutionLookup: repo} + svc := createTestServiceWithAgent(repo, stepGetter, taskRepo, agentMgr) + svc.executor = executor.NewExecutor(agentMgr, repo, testLogger(), executor.ExecutorConfig{}) + session, err := repo.GetTaskSession(ctx, "session-create-successor") + require.NoError(t, err) + svc.activeTurns.Store(session.ID, "turn-successor") + svc.armInitialCreatePromptPassthroughForLaunch(ctx, session, "turn-successor") + + predecessor := watcher.AgentEventData{ + TaskID: "task-create-successor", SessionID: session.ID, AgentExecutionID: "execution-predecessor", + PromptGeneration: 1, + } + svc.handleAgentRunning(ctx, predecessor) + svc.retireInitialCreatePromptPassthroughForEvent(ctx, predecessor) + svc.handleAgentCompleted(ctx, predecessor) + svc.handleAgentFailed(ctx, predecessor) + svc.handleAgentStopped(ctx, predecessor) + svc.bindInitialCreatePromptPassthroughExecution(ctx, session.ID, "turn-successor", "execution-successor") + svc.retireInitialCreatePromptPassthroughForEvent(ctx, predecessor) + + task, err := repo.GetTask(ctx, "task-create-successor") + require.NoError(t, err) + require.Equal(t, "step-backlog", task.WorkflowStepID) + + svc.handleAgentRunning(ctx, watcher.AgentEventData{ + TaskID: "task-create-successor", SessionID: session.ID, AgentExecutionID: "execution-successor", + }) + task, err = repo.GetTask(ctx, "task-create-successor") + require.NoError(t, err) + require.Equal(t, "step-backlog", task.WorkflowStepID, + "the successor running event must still consume the initial admission evidence") +} + +func TestInitialCreatePrompt_TerminalRetirementDoesNotReadPromptGeneration(t *testing.T) { + ctx := context.Background() + repo := setupTestRepo(t) + seedSession(t, repo, "task-create-retirement", "session-create-retirement", "step-backlog") + require.NoError(t, repo.UpdateTaskSessionState( + ctx, "session-create-retirement", models.TaskSessionStateWaitingForInput, "", + )) + seedExecutorRunning(t, repo, "session-create-retirement", "task-create-retirement", "execution-create-retirement") + + stepGetter := newMockStepGetter() + stepGetter.steps["step-backlog"] = &wfmodels.WorkflowStep{ + ID: "step-backlog", WorkflowID: "wf1", Name: "Backlog", + } + taskRepo := newMockTaskRepo() + seedMockTaskState(taskRepo, "task-create-retirement", v1.TaskStateInProgress) + agentMgr := &mockAgentManager{ + currentPromptExecutionID: "execution-create-retirement", + repoForExecutionLookup: repo, + } + agentMgr.currentPromptGeneration.Store(1) + svc := createTestServiceWithAgent(repo, stepGetter, taskRepo, agentMgr) + session, err := repo.GetTaskSession(ctx, "session-create-retirement") + require.NoError(t, err) + svc.activeTurns.Store(session.ID, "turn-create-retirement") + svc.armInitialCreatePromptPassthrough(ctx, session, "turn-create-retirement") + + generationReadStarted := make(chan struct{}) + releaseGenerationRead := make(chan struct{}) + agentMgr.getPromptGenerationForSessionFunc = func(context.Context, string) (uint64, error) { + close(generationReadStarted) + <-releaseGenerationRead + return 1, nil + } + defer close(releaseGenerationRead) + + retirementDone := make(chan struct{}) + go func() { + svc.retireInitialCreatePromptPassthroughForEvent(ctx, watcher.AgentEventData{ + TaskID: "task-create-retirement", + SessionID: session.ID, + AgentExecutionID: "execution-create-retirement", + PromptGeneration: 1, + }) + close(retirementDone) + }() + + select { + case <-retirementDone: + case <-time.After(time.Second): + select { + case <-generationReadStarted: + t.Fatal("terminal evidence retirement synchronously reread prompt generation") + default: + t.Fatal("terminal evidence retirement did not complete") + } + } + select { + case <-generationReadStarted: + t.Fatal("terminal evidence retirement must use the event identity") + default: + } +} + +func TestInitialCreatePrompt_QueueReplayTransfersPassthroughEvidence(t *testing.T) { + ctx := context.Background() + repo := setupTestRepo(t) + seedSession(t, repo, "task-create-queue-passthrough", "session-create-queue-passthrough", "step-backlog") + require.NoError(t, repo.UpdateTaskSessionState(ctx, "session-create-queue-passthrough", models.TaskSessionStateWaitingForInput, "")) + + stepGetter := newMockStepGetter() + stepGetter.steps["step-backlog"] = &wfmodels.WorkflowStep{ + ID: "step-backlog", WorkflowID: "wf1", Name: "Backlog", Position: 0, + Events: wfmodels.StepEvents{ + OnTurnStart: []wfmodels.OnTurnStartAction{{Type: wfmodels.OnTurnStartMoveToNext}}, + }, + } + stepGetter.steps["step-spec"] = &wfmodels.WorkflowStep{ + ID: "step-spec", WorkflowID: "wf1", Name: "Spec", Position: 1, + } + taskRepo := newMockTaskRepo() + seedMockTaskState(taskRepo, "task-create-queue-passthrough", v1.TaskStateInProgress) + seedExecutorRunning(t, repo, "session-create-queue-passthrough", "task-create-queue-passthrough", "execution-create-queue-passthrough") + agentMgr := &mockAgentManager{isPassthrough: true, repoForExecutionLookup: repo} + svc := createTestServiceWithAgent(repo, stepGetter, taskRepo, agentMgr) + + session, err := repo.GetTaskSession(ctx, "session-create-queue-passthrough") + require.NoError(t, err) + identity, err := svc.messageQueue.ResolveSessionIdentity(ctx, "task-create-queue-passthrough", session.ID) + require.NoError(t, err) + queued := &messagequeue.QueuedMessage{ + ID: "queue-create-passthrough", + TaskID: "task-create-queue-passthrough", + SessionID: session.ID, + Content: "initial prompt", + Metadata: map[string]interface{}{ + MetaKeyTurnStartAlreadyProcessed: true, + metaKeyInitialCreatePromptPassthrough: true, + }, + } + svc.activeTurns.Store(session.ID, "turn-create-queue-initial") + + afterClaim := svc.queuedMessageAfterClaim(ctx, identity, queued, nil, false, nil) + require.NoError(t, afterClaim()) + // The production passthrough worker binds this evidence immediately after + // PreparePassthroughRunning claims the successor execution. Model that + // boundary here so the successor event proves suppression, rather than only + // proving that an unbound marker rejects every event. + svc.bindInitialCreatePromptPassthroughExecution( + ctx, session.ID, "turn-create-queue-initial", "execution-create-queue-passthrough", + ) + + // The predecessor event arrives after the successor's admission evidence + // is armed. It must be side-effect free. + svc.retireInitialCreatePromptPassthroughForQueueEvent( + ctx, + session.ID, + identity.SessionIncarnationID, + "execution-predecessor", + "turn-create-queue-initial", + 0, + ) + svc.handleAgentRunning(ctx, watcher.AgentEventData{ + TaskID: "task-create-queue-passthrough", SessionID: session.ID, + AgentExecutionID: "execution-predecessor", + }) + task, err := repo.GetTask(ctx, "task-create-queue-passthrough") + require.NoError(t, err) + require.Equal(t, "step-backlog", task.WorkflowStepID, + "a predecessor running event must not consume queued successor evidence") + + svc.handleAgentRunning(ctx, watcher.AgentEventData{ + TaskID: "task-create-queue-passthrough", SessionID: session.ID, + AgentExecutionID: "execution-create-queue-passthrough", + }) + task, err = repo.GetTask(ctx, "task-create-queue-passthrough") + require.NoError(t, err) + require.Equal(t, "step-backlog", task.WorkflowStepID, + "a duplicate queued running event must not imply a later user turn") + svc.initialCreatePromptMu.Lock() + evidence := svc.initialCreatePromptPassthrough[session.ID] + svc.initialCreatePromptMu.Unlock() + require.True(t, evidence.Consumed, "the admitted successor event must consume the marker") + + svc.activeTurns.Store(session.ID, "turn-create-queue-later") + svc.clearInitialCreatePromptPassthroughForNewTurn(session.ID, "turn-create-queue-later") + svc.handleAgentRunning(ctx, watcher.AgentEventData{ + TaskID: "task-create-queue-passthrough", SessionID: session.ID, + AgentExecutionID: "execution-create-queue-passthrough", + }) + task, err = repo.GetTask(ctx, "task-create-queue-passthrough") + require.NoError(t, err) + require.Equal(t, "step-spec", task.WorkflowStepID, + "a real later queued turn must still evaluate on_turn_start") +} + +func TestInitialCreatePrompt_QueuesAfterTurnStartAdmission(t *testing.T) { + ctx := context.Background() + repo := setupTestRepo(t) + seedSession(t, repo, "task-create-queued", "session-create-queued", "step-backlog") + require.NoError(t, repo.UpdateTaskSessionState(ctx, "session-create-queued", models.TaskSessionStateCreated, "")) + queuedSession, err := repo.GetTaskSession(ctx, "session-create-queued") + require.NoError(t, err) + queuedSession.IsPassthrough = true + require.NoError(t, repo.UpdateTaskSession(ctx, queuedSession)) + task, err := repo.GetTask(ctx, "task-create-queued") + require.NoError(t, err) + task.WIPAdmitted = true + require.NoError(t, repo.UpdateTask(ctx, task)) + require.NoError(t, repo.CreateTask(ctx, &models.Task{ + ID: "task-create-occupant", WorkspaceID: "ws1", WorkflowID: "wf1", + WorkflowStepID: "step-spec", Title: "Occupant", State: v1.TaskStateInProgress, + WIPAdmitted: true, + })) + + stepGetter := newMockStepGetter() + stepGetter.steps["step-backlog"] = &wfmodels.WorkflowStep{ + ID: "step-backlog", WorkflowID: "wf1", Name: "Backlog", Position: 0, + Events: wfmodels.StepEvents{ + OnTurnStart: []wfmodels.OnTurnStartAction{{Type: wfmodels.OnTurnStartMoveToNext}}, + }, + } + stepGetter.steps["step-spec"] = &wfmodels.WorkflowStep{ + ID: "step-spec", WorkflowID: "wf1", Name: "Spec", Position: 1, WIPLimit: 1, + Prompt: "destination automatic prompt", + Events: wfmodels.StepEvents{ + OnEnter: []wfmodels.OnEnterAction{{Type: wfmodels.OnEnterAutoStartAgent}}, + }, + } + taskRepo := newMockTaskRepo() + seedMockTaskState(taskRepo, "task-create-queued", v1.TaskStateInProgress) + seedExecutorRunning(t, repo, "session-create-queued", "task-create-queued", "execution-create-queued") + agentMgr := &mockAgentManager{isAgentRunning: true, isPassthrough: true, repoForExecutionLookup: repo} + svc := createEngineServiceWithScheduler(t, repo, stepGetter, taskRepo, agentMgr) + + response, err := svc.LaunchSession(ctx, &LaunchSessionRequest{ + TaskID: "task-create-queued", SessionID: "session-create-queued", + Intent: IntentStartCreated, Prompt: "initial queued prompt", + InitialCreatePrompt: true, + }) + require.NoError(t, err) + require.Equal(t, "session-create-queued", response.SessionID) + + status := svc.messageQueue.GetStatus(ctx, "session-create-queued") + require.Len(t, status.Entries, 1) + require.True(t, turnStartAlreadyProcessed(status.Entries[0].Metadata)) + updatedTask, err := repo.GetTask(ctx, "task-create-queued") + require.NoError(t, err) + require.Equal(t, "step-spec", updatedTask.WorkflowStepID) + require.False(t, updatedTask.WIPAdmitted) + + // Release the WIP slot and drain the durable entry through the production + // admission-gated queue path. The initial admission already moved the task + // to Spec, so delivery must not evaluate another on_turn_start transition. + occupant, err := repo.GetTask(ctx, "task-create-occupant") + require.NoError(t, err) + occupant.WIPAdmitted = false + require.NoError(t, repo.UpdateTask(ctx, occupant)) + updatedTask.WIPAdmitted = true + updatedTask.QueuedForStepID = "" + updatedTask.Metadata[models.MetaKeyQueuePromotionPending] = map[string]interface{}{"from_step_id": "step-backlog"} + require.NoError(t, repo.UpdateTask(ctx, updatedTask)) + require.NoError(t, repo.UpdateTaskSessionState(ctx, "session-create-queued", models.TaskSessionStateWaitingForInput, "")) + svc.handleTaskQueuePromoted(ctx, watcher.TaskEventData{TaskID: "task-create-queued"}) + require.Eventually(t, func() bool { + agentMgr.mu.Lock() + defer agentMgr.mu.Unlock() + return len(agentMgr.passthroughStdinCalls) == 1 && svc.messageQueue.GetStatus(ctx, "session-create-queued").Count == 0 + }, time.Second, 10*time.Millisecond) + agentMgr.mu.Lock() + passthroughPrompt := agentMgr.passthroughStdinCalls[0].Data + agentMgr.mu.Unlock() + require.True(t, strings.Contains(passthroughPrompt, "initial queued prompt")) + require.NotContains(t, passthroughPrompt, "destination automatic prompt") + finalTask, err := repo.GetTask(ctx, "task-create-queued") + require.NoError(t, err) + require.Equal(t, "step-spec", finalTask.WorkflowStepID) +} + +func TestInitialCreatePrompt_QueueAdmissionFailurePersistsLaunchError(t *testing.T) { + ctx := context.Background() + repo := setupTestRepo(t) + seedSession(t, repo, "task-create-queue-failure", "session-create-queue-failure", "step-backlog") + require.NoError(t, repo.UpdateTaskSessionState(ctx, "session-create-queue-failure", models.TaskSessionStateCreated, "")) + task, err := repo.GetTask(ctx, "task-create-queue-failure") + require.NoError(t, err) + task.WIPAdmitted = true + require.NoError(t, repo.UpdateTask(ctx, task)) + require.NoError(t, repo.CreateTask(ctx, &models.Task{ + ID: "task-create-queue-failure-occupant", WorkspaceID: "ws1", WorkflowID: "wf1", + WorkflowStepID: "step-spec", Title: "Occupant", State: v1.TaskStateInProgress, + WIPAdmitted: true, + })) + + stepGetter := newMockStepGetter() + stepGetter.steps["step-backlog"] = &wfmodels.WorkflowStep{ + ID: "step-backlog", WorkflowID: "wf1", Name: "Backlog", Position: 0, + Events: wfmodels.StepEvents{ + OnTurnStart: []wfmodels.OnTurnStartAction{{Type: wfmodels.OnTurnStartMoveToNext}}, + }, + } + stepGetter.steps["step-spec"] = &wfmodels.WorkflowStep{ + ID: "step-spec", WorkflowID: "wf1", Name: "Spec", Position: 1, WIPLimit: 1, + } + taskRepo := newMockTaskRepo() + seedMockTaskState(taskRepo, "task-create-queue-failure", v1.TaskStateInProgress) + launchCalls := 0 + agentMgr := &mockAgentManager{ + launchAgentFunc: func(context.Context, *executor.LaunchAgentRequest) (*executor.LaunchAgentResponse, error) { + launchCalls++ + return nil, errors.New("unexpected launch") + }, + } + svc := createEngineServiceWithScheduler(t, repo, stepGetter, taskRepo, agentMgr) + baseQueue := messagequeue.NewMemoryRepositoryWithAuthority(func(context.Context, string, string) (messagequeue.QueueSessionIdentity, error) { + return messagequeue.QueueSessionIdentity{ + TaskID: "task-create-queue-failure", + SessionID: "session-create-queue-failure", + SessionIncarnationID: "memory:session-create-queue-failure", + }, nil + }) + svc.messageQueue = messagequeue.NewService( + &initialCreatePromptQueueFailureRepository{Repository: baseQueue, err: errors.New("queue backend unavailable")}, + messagequeue.DefaultMaxPerSession, + testLogger(), + ) + + _, err = svc.LaunchSession(ctx, &LaunchSessionRequest{ + TaskID: "task-create-queue-failure", + SessionID: "session-create-queue-failure", + Intent: IntentStartCreated, + AgentProfileID: "profile-create-queue-failure", + Prompt: "initial queued prompt", + InitialCreatePrompt: true, + }) + require.Error(t, err) + require.Contains(t, err.Error(), "queue initial creation prompt") + require.Zero(t, launchCalls) + + failedSession, err := repo.GetTaskSession(ctx, "session-create-queue-failure") + require.NoError(t, err) + require.Equal(t, models.TaskSessionStateFailed, failedSession.State) + require.Contains(t, failedSession.ErrorMessage, "queue initial creation prompt") +} diff --git a/apps/backend/internal/orchestrator/task_operations.go b/apps/backend/internal/orchestrator/task_operations.go index 1c17643f07..96628cb27e 100644 --- a/apps/backend/internal/orchestrator/task_operations.go +++ b/apps/backend/internal/orchestrator/task_operations.go @@ -588,13 +588,14 @@ func (s *Service) startCreatedSessionWithComposedPrompt( ctx context.Context, taskID, sessionID, agentProfileID, prompt string, retryPrompt string, - skipMessageRecord, planMode, autoStart bool, + skipMessageRecord, planMode, autoStart, initialCreatePrompt bool, attachments []v1.MessageAttachment, references []v1.EntityReference, ) (*executor.TaskExecution, error) { return s.startCreatedSession( ctx, taskID, sessionID, agentProfileID, prompt, skipMessageRecord, planMode, autoStart, attachments, references, "", startCreatedSessionOptions{ + initialCreatePrompt: initialCreatePrompt, skipTaskDescriptionFallback: true, promptAlreadyComposed: true, retryPrompt: retryPrompt, @@ -603,6 +604,7 @@ func (s *Service) startCreatedSessionWithComposedPrompt( } type startCreatedSessionOptions struct { + initialCreatePrompt bool skipTaskDescriptionFallback bool promptAlreadyComposed bool retryPrompt string @@ -907,7 +909,34 @@ func (s *Service) startCreatedSession( } return nil, err } - execution, err := s.launchPreparedSessionWithDynamicFallback(ctx, task, sessionID, executor.LaunchOptions{AgentProfileID: effectiveProfileID, ExecutorID: executorID, Prompt: effectivePrompt, StartAgent: true, McpMode: mcpMode, Attachments: attachments, TurnID: initialTurnID}) + if options.initialCreatePrompt && session.IsPassthrough { + s.armInitialCreatePromptPassthroughForLaunch(ctx, session, initialTurnID) + defer func() { + if err != nil { + s.retireInitialCreatePromptPassthroughForQueue( + session.ID, + session.QueueIncarnationID, + initialTurnID, + s.promptGenerationForSession(ctx, session.ID), + ) + } + }() + } + launchOptions := executor.LaunchOptions{ + AgentProfileID: effectiveProfileID, + ExecutorID: executorID, + Prompt: effectivePrompt, + StartAgent: true, + McpMode: mcpMode, + Attachments: attachments, + TurnID: initialTurnID, + } + if options.initialCreatePrompt && session.IsPassthrough { + launchOptions.OnExecutionAdmitted = func(executionID string) { + s.bindInitialCreatePromptPassthroughExecution(ctx, sessionID, initialTurnID, executionID) + } + } + execution, err := s.launchPreparedSessionWithDynamicFallback(ctx, task, sessionID, launchOptions) if err != nil { // The executor persists LaunchAgent failures. Cover earlier prepared-session // failures here; the session-level claim makes either completion order safe. @@ -5680,6 +5709,10 @@ type promptTaskOptions struct { // (e.g. appending a claimed step handoff) is not silently recomposed from // the destination step's own template. promptAlreadyComposed bool + // initialCreatePromptPassthrough keeps a creation-admission marker alive + // while a transient retry creates the next turn, then rebinds it to the + // execution admitted for that retry before provider dispatch. + initialCreatePromptPassthrough bool // fallbackLaunchPrompt is the fully composed prompt for fresh-launch // recovery. The normal dispatch still receives the raw prompt so it can // apply session transforms exactly once. @@ -6611,6 +6644,12 @@ func (s *Service) claimAndGuardDispatch( if newDispatchGuard != nil { releaseDispatchGuard = newDispatchGuard } + if options.initialCreatePromptPassthrough && session != nil && session.IsPassthrough { + s.armInitialCreatePromptPassthrough(ctx, session, rollback.turnID) + if session.AgentExecutionID != "" { + s.bindInitialCreatePromptPassthroughExecution(ctx, session.ID, rollback.turnID, session.AgentExecutionID) + } + } return session, rollback, releaseDispatchGuard, nil } @@ -7311,7 +7350,7 @@ func (s *Service) handlePromptDispatchFailure( fallbackPrompt = fallbackLaunchPrompt } if freshErr := s.fallbackFreshLaunchOnMissingExecution( - ctx, taskID, sessionID, fallbackPrompt, promptAlreadyComposed, fallbackRetryPrompt, planMode, nil, attachments, nil, + ctx, taskID, sessionID, fallbackPrompt, promptAlreadyComposed, fallbackRetryPrompt, planMode, false, nil, attachments, nil, ); freshErr == nil { return &PromptResult{}, nil } else { diff --git a/apps/backend/internal/orchestrator/workflow_e2e_test.go b/apps/backend/internal/orchestrator/workflow_e2e_test.go index 2ab1228b0d..f8b543df2b 100644 --- a/apps/backend/internal/orchestrator/workflow_e2e_test.go +++ b/apps/backend/internal/orchestrator/workflow_e2e_test.go @@ -15,6 +15,7 @@ import ( sqliterepo "github.com/kandev/kandev/internal/task/repository/sqlite" "github.com/kandev/kandev/internal/workflow/engine" wfmodels "github.com/kandev/kandev/internal/workflow/models" + "github.com/stretchr/testify/require" ) // --- Test table types --- @@ -194,6 +195,118 @@ func TestWorkflowE2E(t *testing.T) { } } +func TestWorkflowE2E_InitialCreatePrompt(t *testing.T) { + ctx := context.Background() + workflowJSON := `{ + "version": 1, + "type": "kandev_workflow", + "workflows": [{ + "name": "Initial create prompt", + "steps": [ + {"name": "Backlog", "position": 0, "is_start_step": true, + "events": {"on_turn_start": [{"type": "move_to_next"}]}}, + {"name": "Spec", "position": 1, "agent_profile": {"agent_name": "profile-destination"}, + "events": {"on_enter": [{"type": "auto_start_agent"}], + "on_turn_complete": [{"type": "move_to_next"}]}}, + {"name": "Spec Review", "position": 2} + ] + }] +}` + + stepGetter, nameToID := buildWorkflowFromJSON(t, workflowJSON) + repo := setupTestRepo(t) + seedSession(t, repo, "task-initial-create-e2e", "session-initial-create-e2e", nameToID["Backlog"]) + require.NoError(t, repo.UpdateTaskSessionState(ctx, "session-initial-create-e2e", models.TaskSessionStateCreated, "")) + initialSession, err := repo.GetTaskSession(ctx, "session-initial-create-e2e") + require.NoError(t, err) + initialSession.AgentProfileID = "profile-source" + initialSession.ExecutorID = models.ExecutorIDLocal + initialSession.TaskEnvironmentID = "environment-initial-create-e2e" + require.NoError(t, repo.UpdateTaskSession(ctx, initialSession)) + require.NoError(t, repo.CreateTaskEnvironment(ctx, &models.TaskEnvironment{ + ID: initialSession.TaskEnvironmentID, + TaskID: initialSession.TaskID, + ExecutorType: string(models.ExecutorTypeLocal), + Status: models.TaskEnvironmentStatusReady, + })) + seedExecutorRunning(t, repo, initialSession.ID, initialSession.TaskID, "execution-initial-create-source") + + taskRepo := newMockTaskRepo() + taskRepo.tasks["task-initial-create-e2e"] = &v1.Task{ + ID: "task-initial-create-e2e", Title: "Initial create", Description: "write the specification", + State: v1.TaskStateInProgress, + } + agentMgr := &mockAgentManager{isAgentRunning: true, repoForExecutionLookup: repo} + svc := createEngineServiceWithScheduler(t, repo, stepGetter, taskRepo, agentMgr) + messages := &mockMessageCreator{} + svc.messageCreator = messages + var launches []executor.LaunchAgentRequest + dispatchStarted := make(chan string, 1) + agentMgr.launchAgentFunc = func(_ context.Context, req *executor.LaunchAgentRequest) (*executor.LaunchAgentResponse, error) { + launches = append(launches, *req) + observedTask, loadErr := repo.GetTask(ctx, req.TaskID) + require.NoError(t, loadErr) + require.Equal(t, nameToID["Spec"], observedTask.WorkflowStepID, + "the provider must see the destination workflow step") + observedSession, loadErr := repo.GetTaskSession(ctx, req.SessionID) + require.NoError(t, loadErr) + require.Equal(t, "profile-destination", req.AgentProfileID) + require.Equal(t, "profile-destination", observedSession.AgentProfileID, + "the session settings must be updated before provider launch") + require.Equal(t, string(models.ExecutorTypeLocal), req.ExecutorType, + "the prepared executor setting must reach provider launch") + return &executor.LaunchAgentResponse{AgentExecutionID: "execution-initial-create-dispatch"}, nil + } + agentMgr.startAgentProcessFunc = func(_ context.Context, executionID string) error { + dispatchStarted <- executionID + return nil + } + + _, err = svc.LaunchSession(ctx, &LaunchSessionRequest{ + TaskID: "task-initial-create-e2e", + SessionID: "session-initial-create-e2e", + Intent: IntentStartCreated, + AgentProfileID: "profile-initial-create-e2e", + Prompt: "write the specification", + InitialCreatePrompt: true, + }) + require.NoError(t, err) + require.Len(t, launches, 2, "profile switching prepares the destination workspace once before the prompt launch") + var promptLaunches []executor.LaunchAgentRequest + for _, launch := range launches { + if launch.StartAgent { + promptLaunches = append(promptLaunches, launch) + } + } + require.Len(t, promptLaunches, 1, "the destination session must have one prompt-bearing provider launch") + require.Contains(t, promptLaunches[0].TaskDescription, "write the specification") + select { + case executionID := <-dispatchStarted: + require.Equal(t, "execution-initial-create-dispatch", executionID) + case <-time.After(time.Second): + t.Fatal("timed out waiting for the initial process dispatch") + } + activeSession, err := repo.GetActiveTaskSessionByTaskID(ctx, "task-initial-create-e2e") + require.NoError(t, err) + require.NotNil(t, activeSession) + require.Equal(t, "profile-destination", activeSession.AgentProfileID, + "the destination step profile must own the first process dispatch") + require.Equal(t, models.ExecutorIDLocal, activeSession.ExecutorID, + "the active session must retain the prepared executor setting") + + task, err := repo.GetTask(ctx, "task-initial-create-e2e") + require.NoError(t, err) + require.Equal(t, nameToID["Spec"], task.WorkflowStepID) + require.Len(t, messages.userMessages, 1) + + require.NoError(t, repo.UpdateTaskSessionState(ctx, activeSession.ID, models.TaskSessionStateRunning, "")) + require.True(t, svc.processOnTurnCompleteViaEngine(ctx, "task-initial-create-e2e", activeSession)) + + task, err = repo.GetTask(ctx, "task-initial-create-e2e") + require.NoError(t, err) + require.Equal(t, nameToID["Spec Review"], task.WorkflowStepID) +} + func runWorkflowTestCase(t *testing.T, tc workflowTestCase) { t.Helper() ctx := context.Background() @@ -298,9 +411,14 @@ func buildWorkflowFromJSON(t *testing.T, jsonStr string) (*mockStepGetter, map[s for _, sp := range steps { id := posToID[sp.Position] events := wfmodels.ConvertPositionToStepID(sp.Events, posToID) + agentProfileID := "" + if sp.AgentProfile != nil { + agentProfileID = sp.AgentProfile.AgentName + } sg.steps[id] = &wfmodels.WorkflowStep{ ID: id, WorkflowID: "wf1", Name: sp.Name, Position: sp.Position, - Prompt: sp.Prompt, Events: events, CompleteTaskOnEnter: sp.CompleteTaskOnEnter, + AgentProfileID: agentProfileID, Prompt: sp.Prompt, Events: events, + CompleteTaskOnEnter: sp.CompleteTaskOnEnter, } nameToID[sp.Name] = id } @@ -309,12 +427,33 @@ func buildWorkflowFromJSON(t *testing.T, jsonStr string) (*mockStepGetter, map[s // createEngineService creates a Service with the workflow engine initialized. func createEngineService(t *testing.T, repo *sqliterepo.Repository, sg *mockStepGetter, agentMgr *mockAgentManager) *Service { + return createEngineServiceWithTaskRepo(t, repo, sg, newMockTaskRepo(), agentMgr) +} + +// createEngineServiceWithScheduler keeps the scheduler/executor fixture used by +// launch tests while making the production workflow engine explicit. The +// lower-level scheduler helper assigns the getter directly for legacy tests; +// this helper is for tests that must observe strict engine admission. +func createEngineServiceWithScheduler( + t *testing.T, + repo *sqliterepo.Repository, + sg *mockStepGetter, + taskRepo *mockTaskRepo, + agentMgr *mockAgentManager, +) *Service { + t.Helper() + svc := createTestServiceWithScheduler(repo, sg, taskRepo, agentMgr) + svc.SetWorkflowStepGetter(sg) + return svc +} + +func createEngineServiceWithTaskRepo(t *testing.T, repo *sqliterepo.Repository, sg *mockStepGetter, taskRepo *mockTaskRepo, agentMgr *mockAgentManager) *Service { t.Helper() log := testLogger() svc := &Service{ logger: log, repo: repo, - taskRepo: newMockTaskRepo(), + taskRepo: taskRepo, agentManager: agentMgr, messageQueue: newAuthoritativeMemoryQueue(repo, log), executor: executor.NewExecutor(agentMgr, repo, log, executor.ExecutorConfig{}), diff --git a/apps/backend/internal/task/handlers/task_http_handlers.go b/apps/backend/internal/task/handlers/task_http_handlers.go index 1d8c06f6f0..8b3caac537 100644 --- a/apps/backend/internal/task/handlers/task_http_handlers.go +++ b/apps/backend/internal/task/handlers/task_http_handlers.go @@ -1424,7 +1424,12 @@ func (h *TaskHandlers) associatePRFromRepoInputs(taskID, sessionID string, repos // succeeded. A nil *startAgentDispatch means there is nothing to dispatch — // prepare-only, start_agent not requested, or prepare itself failed. type startAgentDispatch struct { - sessionID string + sessionID string + initialCreatePrompt bool +} + +func eligibleInitialCreatePrompt(body httpCreateTaskRequest) bool { + return body.StartAgent && body.WorkflowStepID != "" && strings.TrimSpace(body.Description) != "" } // prepareTaskSession runs the create sequence's synchronous session-setup @@ -1529,7 +1534,14 @@ func (h *TaskHandlers) prepareStartAgentSession( } else { response.State = updatedTask.State } - return &startAgentDispatch{sessionID: sessionID} + return &startAgentDispatch{ + sessionID: sessionID, + // body.WorkflowStepID is the caller's original explicit selection. + // resolvedStepID may have been inferred or normalized before this + // helper runs, so it cannot establish the provenance required for the + // initial creation-prompt path. + initialCreatePrompt: eligibleInitialCreatePrompt(body), + } } // dispatchTaskSession launches the agent asynchronously (create-sequence @@ -1551,14 +1563,15 @@ func (h *TaskHandlers) dispatchTaskSession( startCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), constants.AgentLaunchTimeout) defer cancel() launchResp, err := h.orchestrator.LaunchSession(startCtx, &orchestrator.LaunchSessionRequest{ - TaskID: taskID, - Intent: orchestrator.IntentStartCreated, - SessionID: sessionID, - AgentProfileID: body.AgentProfileID, - Prompt: description, - SkipMessageRecord: false, - PlanMode: body.PlanMode, - Attachments: body.Attachments, + TaskID: taskID, + Intent: orchestrator.IntentStartCreated, + SessionID: sessionID, + AgentProfileID: body.AgentProfileID, + Prompt: description, + SkipMessageRecord: false, + PlanMode: body.PlanMode, + Attachments: body.Attachments, + InitialCreatePrompt: dispatch.initialCreatePrompt, }) if err != nil { h.logger.Error("failed to start agent for task (async)", zap.Error(err), zap.String("task_id", taskID), zap.String("session_id", sessionID)) diff --git a/apps/backend/internal/task/handlers/task_http_handlers_test.go b/apps/backend/internal/task/handlers/task_http_handlers_test.go index eb5b2ac2fe..b2685e75be 100644 --- a/apps/backend/internal/task/handlers/task_http_handlers_test.go +++ b/apps/backend/internal/task/handlers/task_http_handlers_test.go @@ -307,6 +307,33 @@ func TestStartAgentForNewTask_SetsDeferredStart(t *testing.T) { "sync prepare must defer the start so the passthrough PTY is launched with the prompt by the follow-up IntentStartCreated") } +func TestDispatchTaskSessionMarksExplicitCreationPrompt(t *testing.T) { + called := make(chan struct{}, 1) + orch := &captureOrchestrator{ + startCreatedCalled: called, + startCreatedResponse: &orchestrator.LaunchSessionResponse{Success: true, SessionID: "session-1"}, + } + h := &TaskHandlers{orchestrator: orch, logger: newTestLogger(t)} + + h.dispatchTaskSession( + context.Background(), + "task-1", + "initial request", + httpCreateTaskRequest{WorkflowStepID: "step-explicit", AgentProfileID: "profile-1"}, + &startAgentDispatch{sessionID: "session-1", initialCreatePrompt: true}, + ) + select { + case <-called: + case <-time.After(time.Second): + t.Fatal("async IntentStartCreated launch did not complete") + } + + orch.mu.Lock() + defer orch.mu.Unlock() + require.Len(t, orch.requests, 1) + assert.True(t, orch.requests[0].InitialCreatePrompt) +} + func TestDispatchTaskSessionRecordsOnlyTheSuccessfulEffectiveProfile(t *testing.T) { t.Run("successful launch uses the resolved profile", func(t *testing.T) { recorder := &captureAgentProfileRecentUseRecorder{profileIDs: make(chan string, 1)} @@ -362,6 +389,24 @@ func TestDispatchTaskSessionRecordsOnlyTheSuccessfulEffectiveProfile(t *testing. }) } +func TestEligibleInitialCreatePromptRequiresOriginalExplicitStepAndText(t *testing.T) { + tests := []struct { + name string + body httpCreateTaskRequest + want bool + }{ + {name: "eligible", body: httpCreateTaskRequest{StartAgent: true, WorkflowStepID: "step-1", Description: "build"}, want: true}, + {name: "inferred step", body: httpCreateTaskRequest{StartAgent: true, Description: "build"}, want: false}, + {name: "empty text", body: httpCreateTaskRequest{StartAgent: true, WorkflowStepID: "step-1"}, want: false}, + {name: "prepare only", body: httpCreateTaskRequest{WorkflowStepID: "step-1", Description: "build"}, want: false}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, eligibleInitialCreatePrompt(tc.body)) + }) + } +} + // configChatRepo returns a non-nil workspace so resolveConfigChatDefaults does // not nil-deref; everything else inherits mockRepository's no-op stubs. type configChatRepo struct { diff --git a/apps/backend/internal/task/models/models.go b/apps/backend/internal/task/models/models.go index 2464a2880f..a95f6a22cc 100644 --- a/apps/backend/internal/task/models/models.go +++ b/apps/backend/internal/task/models/models.go @@ -400,6 +400,11 @@ const ( // latest successful agent boot. Recovery cards compare this timestamp with // their own creation time, so the result survives transcript write failures. SessionMetaKeyRecoveryResolvedAt = "recovery_resolved_at" + // SessionMetaKeyInitialCreatePromptPassthrough stores the durable + // execution and turn evidence for a creation prompt admitted before a + // passthrough agent.running event. It prevents recovery from evaluating + // the same on_turn_start transition a second time after restart. + SessionMetaKeyInitialCreatePromptPassthrough = "initial_create_prompt_passthrough" ) // IsCompletionFollowUpSession reports whether a session was explicitly diff --git a/docs/plans/task-create-initial-turn-start/plan.md b/docs/plans/task-create-initial-turn-start/plan.md new file mode 100644 index 0000000000..663360c02c --- /dev/null +++ b/docs/plans/task-create-initial-turn-start/plan.md @@ -0,0 +1,136 @@ +--- +created: 2026-09-18 +status: complete +requirements: + - REQ-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-004 + - REQ-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-006 +system_design: + - ../../specs/tasks/system-design/workflow-step-agent-start-ownership.md +legacy_specs: [] +--- + +# Implementation Plan: Initial creation prompt workflow transition + +## Overview + +Process the explicit starting step's `on_turn_start` before an immediate REST or MCP creation prompt reaches the agent. +One sequential work order owns the transport wiring, orchestration, regression tests, and public documentation. +Implementation is complete. + +## Evidence and root cause + +Source: [issue #3804](https://github.com/kdlbs/kandev/issues/3804), open with no comments or image attachments during investigation. +Investigated checkout: `33b7bd9bf0` on 2026-09-18. +The authenticated GitHub user is `carlosflorencio`; the issue was assigned to that account after reproduction. + +The current source confirms both missing paths: + +1. REST `prepareStartAgentSession` prepares a session. After settlement, `dispatchTaskSession` sends `IntentStartCreated` without turn-start processing. +2. MCP captures an explicit destination in `handleCreateTask`. `launchAutoStartTask` sends `IntentStart`, whose `startTask` path omits turn-start processing. +3. `StartCreatedSession` deliberately omits this trigger because ordinary messages already process it and workflow automatic starts must not cascade. +4. `handleAgentRunning` returns early for ACP sessions. No startup event repairs the missing transition. +5. Ordinary `wsAddMessage` calls `ProcessOnTurnStart` before composition and resolves the resulting session before dispatch. + +A temporary `TestReproIssue3804` exercised real `LaunchSession(IntentStartCreated)` with SQLite, workflow evaluation, and a mocked agent manager. +It prepared a task on Backlog with a move-to-Spec turn-start action. +Creation recorded one user message while the task remained on Backlog. +The positive control called `ProcessOnTurnStart` and observed Spec. + +```text +after creation dispatch: step=backlog user_messages=1 +after explicit turn-start: step=spec +PASS (package 0.086s) +``` + +Command: `(cd apps/backend && go test -tags fts5 ./internal/orchestrator -run '^TestReproIssue3804$' -count=1 -v)`. +The temporary test was removed after diagnosis. +This proves the orchestration omission; it does not reproduce the reporter's macOS runtime or provider transport. +MCP has a source trace at this stage, not an executed transport reproduction. + +## Scope + +### In scope + +- Explicit-step, immediate REST and MCP creation with non-empty text. +- One transition before first-prompt composition and dispatch. +- Destination session/profile/settings, WIP queue admission, and duplicate-trigger protection. +- Negative controls for ordinary messages, workflow automatic starts, omitted steps, and empty text. + +### Out of scope + +- Historical task repair, dependency-deferred creation, attachment-only creation, and new workflow actions. +- Provider changes, new UI, schema changes, and broader launch refactoring. +- Executing production changes during this design turn. + +## Requirement conformance + +Requirement `004`, especially `AC-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-004.3`, already preserves explicit initial placement. +The missing creation-prompt semantics are added as draft requirement `006` in the existing owner. +An explicit placement and a subsequent configured transition are separate operations; the fix preserves both. +No new architectural owner or ADR is required. The existing task-system trigger and prompt-admission boundaries remain authoritative. + +Companion packages were inventoried: start ownership, reset quiescence/failure containment, empty-prompt deduplication, initial task brief, and asynchronous prompt preservation. +Their existing scope and results remain unchanged. This work adds creation admission before their launch behavior. + +## Technical approach + +Follow [Initial creation prompt admission](../../specs/tasks/system-design/workflow-step-agent-start-ownership.md#initial-creation-prompt-admission). +Capture caller provenance before MCP resolves a destination. +Use an internal `InitialCreatePrompt` marker and a shared prepared-session helper. +For marked MCP requests, prepare without eager passthrough launch before processing the trigger. +For REST, use the prepared session already returned by creation. + +Reuse `ProcessOnTurnStart`, destination-session resolution, queue metadata, and first-prompt composition. +Do not add an unconditional trigger to either generic launch method. +The helper must finish transition and WIP admission decisions before provider dispatch. +Passthrough duplicate suppression belongs to the initial execution/turn, not the whole session. + +## Tests + +| Criteria | Permanent regression evidence | +| --- | --- | +| `006.1`, `006.2` | `task_create_prompt_test.go` and `workflow_e2e_test.go`: transition before dispatch, resulting step, one prompt, and completion transition | +| `006.3` | `TestInitialCreatePrompt_PassthroughRunningDoesNotRepeatTurnStart`, `TestInitialCreatePrompt_PassthroughEvidenceSurvivesPredecessorTerminalEvents`, and `TestInitialCreatePrompt_QueueReplayTransfersPassthroughEvidence`; later passthrough input still transitions | +| `006.4` | `TestInitialCreatePrompt_QueuesAfterTurnStartAdmission`; the initial prompt remains queued with processed-trigger metadata, then releases through the admission-gated queue path with one delivery and no second transition | +| `006.5`, `004.1` through `004.3` | REST provenance and MCP prepared-start tests cover explicit versus inferred destinations; existing unmarked launch and workflow suites remain unchanged | +| `006.6` | `TestInitialCreatePrompt_TransitionFailurePreventsLaunch`, `TestInitialCreatePrompt_AdmissionFailureDoesNotFailSupersededSuccessor`, `TestInitialCreatePrompt_LaunchFailureUsesReplacementSession`, and `TestInitialCreatePrompt_QueueAdmissionFailurePersistsLaunchError` cover durable errors, correct replacement ownership, and zero prompt dispatch on admission failure | +| `006.1`, `006.5`, `006.6` | REST and MCP handler tests prove original explicit-step provenance and no dispatch before settlement or while blocked | + +The primary regression must fail against the current implementation because the step remains Backlog at dispatch. +The temporary diagnosis asserted the defective behavior; it is not the permanent regression test. + +## E2E tests + +Use Go orchestration integration tests with the real workflow engine and SQLite plus an executor dispatch observer. +Extend `workflow_e2e_test.go` with `TestWorkflowE2E_InitialCreatePrompt` for Backlog -> Spec -> Spec Review. +Assert the destination step, replacement session profile, inherited executor settings, and one prompt-bearing process dispatch at provider launch, then Spec Review after eligible completion (`006.1` through `006.3`). +Adapter tests must connect both REST and MCP creation to the marked launch request. +An engine-only trigger table row is insufficient because it bypasses the missing creation call site. +No Playwright case is required: no rendered interface or browser interaction changes. + +## Work orders + +- [x] [Task 01: Admit the initial creation prompt through turn-start](task-01-initial-create-prompt.md) + +## Verification results + +- Diagnostic reproduction: passed, with the defective behavior and positive control recorded above. +- Permanent regression and implementation checks: passed. REST and MCP adapters, initial admission, WIP queueing, passthrough replay, transition failure containment, and workflow E2E coverage are implemented. +- A first combined race run exposed a transient suite failure; the isolated full orchestrator race run and the exact combined race command both passed on rerun. +- Backend build: passed with `make -C apps/backend build`. +- Backend lint: passed with `make -C apps/backend lint`. +- Public documentation checks: passed with the work order's Node validators. +- `python3 scripts/list-docs.py validate`: passed, 291 decisions and 1032 specifications. +- `python3 scripts/lint-spec-files.test.py`: passed, 36 tests. +- `python3 scripts/lint-spec-files.py --all`: passed. +- `git diff --check`: passed. +- Package status inspection confirmed both new plan files. The temporary reproduction was removed. + +## Risks + +- A global trigger call can skip the target step by cascading its automatic start. +- MCP's resolved step does not retain whether the caller explicitly selected it. +- Profile switching can replace the prepared session; stale session dispatch can fail or revive old work. +- WIP queue drain and passthrough running events can evaluate the trigger twice without scoped evidence. +- Engine helpers currently log some internal failures without returning them. Keep any error propagation change confined to the creation admission path. +- Concurrent cancellation or replacement must retire any initial-turn suppression evidence. diff --git a/docs/plans/task-create-initial-turn-start/task-01-initial-create-prompt.md b/docs/plans/task-create-initial-turn-start/task-01-initial-create-prompt.md new file mode 100644 index 0000000000..7c1b232306 --- /dev/null +++ b/docs/plans/task-create-initial-turn-start/task-01-initial-create-prompt.md @@ -0,0 +1,152 @@ +--- +id: "01-initial-create-prompt" +title: "Admit the initial creation prompt through turn-start" +status: done +wave: 1 +depends_on: [] +plan: "plan.md" +requirements: + - REQ-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-004 + - REQ-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-006 +acceptance_criteria: + - AC-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-004.1 + - AC-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-004.2 + - AC-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-004.3 + - AC-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-006.1 + - AC-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-006.2 + - AC-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-006.3 + - AC-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-006.4 + - AC-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-006.5 + - AC-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-006.6 +system_design: + - ../../specs/tasks/system-design/workflow-step-agent-start-ownership.md +--- + +# Task 01: Admit the initial creation prompt through turn-start + +## Summary + +Connect immediate explicit-step creation to the existing user-message transition boundary. +Keep one prompt owner through session replacement, WIP admission, and passthrough running notifications. + +## In scope + +- Add the private create-prompt marker before destination inference in REST and MCP adapters. +- Implement shared prepared-session admission in `task_create_prompt.go` and route marked launch requests through it. +- Process the trigger before composition; reload destination state, honor WIP queuing, and retain initial prompt metadata. +- Bind passthrough suppression to one initial execution/turn; retire it on completion, failure, cancellation, or replacement. +- Add all tests in the plan's matrix with TDD. Prove the primary regression fails before implementation. +- Update the `on_turn_start` explanation in `docs/public/workflow-tips.md` after behavior works. + This explanation page must distinguish initial explicit-step input from automatic workflow-entry prompts. + +## Out of scope + +Dependency-deferred creates, attachment-only creates, historical repair, provider changes, UI changes, and new public launch fields. +Do not change the original context-reset or asynchronous prompt-preservation packages. + +## Acceptance + +1. Both creation adapters select the corrected path only for eligible original requests, after existing settlement and admission gates. +2. The first prompt-bearing dispatch observes the destination step/session/settings and one message; queue replay and running notifications do not trigger another transition. +3. All negative controls retain their behavior, failures prevent stale dispatch, and the documented verification commands pass. + +## Implementation sequence + +1. Add `TestInitialCreatePrompt_TransitionsBeforeDispatch` using the existing scheduler, SQLite, workflow engine, and mock agent fixtures. +2. Observe its failure with a pinned Backlog task and a move-to-Spec action. +3. Add shared admission and transport wiring; avoid duplicating transition logic in handlers. +4. Add the queue, passthrough, profile-switch, failure, replacement, and non-eligible controls from the plan. +5. Add `TestWorkflowE2E_InitialCreatePrompt` with a dispatch observer and completion transition. +6. Update public documentation and run every verification command. + +## Verification + +Run from the repository root. The first command selects the new regression family during TDD. +The package command covers all modified Go suites and their existing creation, queue, and lifecycle regressions. + +```bash +(cd apps/backend && go test -tags fts5 ./internal/orchestrator -run 'TestInitialCreatePrompt_|TestWorkflowE2E_InitialCreatePrompt' -count=1 -v) +(cd apps/backend && go test -tags fts5 -race ./internal/orchestrator ./internal/task/handlers ./internal/mcp/handlers) +python3 scripts/list-docs.py validate +python3 scripts/lint-spec-files.test.py +python3 scripts/lint-spec-files.py --all +node --test scripts/validate-public-docs.test.mjs +node scripts/validate-public-docs.mjs +git diff --check +``` + +## Files likely touched + +- `apps/backend/internal/orchestrator/session_launch.go` +- `apps/backend/internal/orchestrator/task_create_prompt.go` (new) +- `apps/backend/internal/orchestrator/task_create_prompt_test.go` (new) +- `apps/backend/internal/orchestrator/task_operations.go` +- `apps/backend/internal/orchestrator/event_handlers_workflow.go` +- `apps/backend/internal/orchestrator/event_handlers_agent.go` +- `apps/backend/internal/orchestrator/event_handlers_queue_general_test.go` +- `apps/backend/internal/orchestrator/event_handlers_passthrough_lifecycle_test.go` +- `apps/backend/internal/orchestrator/workflow_e2e_test.go` +- `apps/backend/internal/task/handlers/task_http_handlers.go` +- `apps/backend/internal/task/handlers/task_http_handlers_test.go` +- `apps/backend/internal/mcp/handlers/handlers.go` +- `apps/backend/internal/mcp/handlers/handlers_test.go` +- `apps/backend/internal/mcp/handlers/create_task_external_id_test.go` +- `apps/backend/internal/mcp/handlers/destination_step_test.go` +- `docs/public/workflow-tips.md` +- This plan and work order, for implementation results. + +## Dependencies + +None. Execute in the primary session after a later implementation request. + +## Risks + +Do not hold the cancellation guard across another call that acquires it. +Do not infer explicit selection from the resolved MCP destination or the `AutoStart` flag. +Do not bypass launch ceilings, first-message admission, attachment claims, or session replacement checks. +If helpers hide an engine failure, return that failure before creation dispatch without changing unrelated callers' behavior. +Retain existing step-prompt composition; do not introduce a new prompt concatenation policy. + +## Parallelism + +`sequential` + +## Inputs + +- [Plan and diagnostic evidence](plan.md). +- [Requirements 004 and 006](../../specs/tasks/requirements/workflow-step-agent-start-ownership.md). +- [Initial creation prompt admission](../../specs/tasks/system-design/workflow-step-agent-start-ownership.md#initial-creation-prompt-admission). +- `wsAddMessage` in `message_handlers.go`: transition, resulting session, queue admission, and composition ordering. +- `TestStartCreatedSession_WrapsFirstPromptWithKandevSystemBlock` for prepared-launch fixtures. +- `TestExecuteQueuedMessage_SkipsOnTurnStartWhenAlreadyProcessed` for queue trigger ownership. +- Existing REST settlement and MCP external-ID tests for forbidden early dispatch. + +## Results + +Completed on 2026-09-19. + +- Added server-side eligibility provenance for explicit, prompt-bearing immediate creation in the REST and MCP adapters. +- Routed marked creation starts through the shared turn-start admission boundary before prompt composition and provider dispatch. +- Preserved destination session/profile resolution, WIP queueing, attachment and prompt handling, and one-message ownership. +- Added scoped passthrough evidence for direct and queued initial turns. Running, completion, failure, stop, replacement, and dispatch-failure paths retire the evidence. +- Persisted strict-admission and queue-insertion failures through guarded launch-error ownership. Superseded sources and unrelated successors are left unchanged, while a replacement that owns the changed workflow step receives the error. +- Updated the public `on_turn_start` workflow guidance. + +Verification passed: + +```text +go test -tags fts5 ./internal/orchestrator -count=1 +go test -tags fts5 ./internal/task/handlers ./internal/mcp/handlers -count=1 +go test -tags fts5 -race ./internal/orchestrator -run '^(TestInitialCreatePrompt_|TestWorkflowE2E_InitialCreatePrompt$)' -count=1 +go test -tags fts5 -race ./internal/orchestrator ./internal/task/handlers ./internal/mcp/handlers -count=1 +make -C apps/backend build +make -C apps/backend lint +python3 scripts/list-docs.py validate +python3 scripts/lint-spec-files.test.py +python3 scripts/lint-spec-files.py --all +node --test scripts/validate-public-docs.test.mjs +node scripts/validate-public-docs.mjs +git diff --check +``` + +The temporary diagnostic reproduction was removed. No schema, provider protocol, or UI changes were required. diff --git a/docs/public/workflow-tips.md b/docs/public/workflow-tips.md index f3b260f8e4..51641a3837 100644 --- a/docs/public/workflow-tips.md +++ b/docs/public/workflow-tips.md @@ -190,7 +190,7 @@ The standard Kanban editor exposes these events: | Event | When it runs | Editor actions | |-------|--------------|----------------| | `on_enter` | A task enters a step through normal step-entry processing. | Enable plan mode, auto-start agent, reset context. | -| `on_turn_start` | A user sends a message. The transition happens before that message is delivered. | Move next, previous, or to a selected step. | +| `on_turn_start` | A user sends a message, including the first non-empty prompt when a task is created with an explicit workflow step. The transition happens before that message is delivered. Prompts started automatically when a task enters a step do not run this event. | Move next, previous, or to a selected step. | | `on_turn_complete` | A normal agent turn finishes when its signal requirements are satisfied. An explicit user cancellation qualifies when the step enables its cancellation policy, even if the completion signal is absent. A pending clarification always blocks completion. | Move next, previous, or to a selected step; disable plan mode. | | `on_exit` | A task leaves a step. | Disable plan mode. | diff --git a/docs/specs/tasks/requirements/workflow-step-agent-start-ownership.md b/docs/specs/tasks/requirements/workflow-step-agent-start-ownership.md index 3ffb95c650..5b80a880f2 100644 --- a/docs/specs/tasks/requirements/workflow-step-agent-start-ownership.md +++ b/docs/specs/tasks/requirements/workflow-step-agent-start-ownership.md @@ -2,7 +2,7 @@ status: draft system: tasks created: 2026-08-05 -updated: 2026-09-17 +updated: 2026-09-18 owners: - Kandev --- @@ -123,6 +123,30 @@ This draft extension addresses [issue #3753](https://github.com/kdlbs/kandev/iss This extension excludes a backend crash before the asynchronous failure callback persists the prompt. It also excludes replay after ambiguous provider acceptance, automatic repair of historical orphaned messages, and new recovery controls. +### REQ-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-006: Initial user prompt on an explicit step + +**Intent:** Apply the selected step's user-message transition before an immediate creation prompt reaches the agent. +This draft extension addresses [issue #3804](https://github.com/kdlbs/kandev/issues/3804). + +#### Acceptance criteria + +- **AC-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-006.1:** When REST or MCP creation requests an immediate start with an explicit step and non-empty prompt, its `on_turn_start` transition shall precede prompt delivery. + Initial placement shall still use the explicit step. The configured transition determines the subsequent step. +- **AC-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-006.2:** The first prompt shall use the resulting step, session, profile, and applicable session settings. + Destination automatic start shall not send a competing prompt. The initial input shall retain existing prompt-composition and attachment behavior. +- **AC-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-006.3:** One initial user prompt shall evaluate the trigger once, including queue delivery and passthrough running notifications. + A later user turn shall retain ordinary trigger behavior. +- **AC-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-006.4:** When the transition queues the task for WIP admission, the initial prompt shall wait for admission. + It shall remain available for delivery without a second user message or repeated transition. +- **AC-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-006.5:** Creation without an explicit step shall retain automatic destination selection. + Creation without immediate start or non-empty text shall not gain an additional trigger from this change. + Workflow automatic starts and ordinary message submission shall not gain an additional trigger. +- **AC-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-006.6:** If turn-start processing or destination-session resolution fails, the creation prompt shall not launch against stale state. + Existing task/session error handling shall expose the failed start. Existing terminal-state and creation-settlement guards shall remain effective. + +The extension covers immediate REST and MCP dispatch. Dependency-deferred creation, historical stuck tasks, and changes to workflow action semantics are excluded. +The [initial creation prompt package](../../../plans/task-create-initial-turn-start/plan.md) owns implementation and regression evidence. + ## Migrated source detail ## Why diff --git a/docs/specs/tasks/system-design/workflow-step-agent-start-ownership.md b/docs/specs/tasks/system-design/workflow-step-agent-start-ownership.md index 55725a64f5..ca555dd711 100644 --- a/docs/specs/tasks/system-design/workflow-step-agent-start-ownership.md +++ b/docs/specs/tasks/system-design/workflow-step-agent-start-ownership.md @@ -7,6 +7,7 @@ requirements: - REQ-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-003 - REQ-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-004 - REQ-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-005 + - REQ-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-006 --- # Workflow Step Agent Start Ownership System Design @@ -28,6 +29,7 @@ The design preserves runtime configuration through the existing reset contract. | `REQ-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-003` | [Prompt fallback ownership](#prompt-fallback-ownership), [Prompt-history contract](#prompt-history-contract), [Workflow-entry prompt flow](#workflow-entry-prompt-flow) | | `REQ-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-004` | [Creation destination routing](#creation-destination-routing) | | `REQ-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-005` | [Asynchronous launch prompt preservation](#asynchronous-launch-prompt-preservation) | +| `REQ-TASKS-WORKFLOW-STEP-AGENT-START-OWNERSHIP-006` | [Initial creation prompt admission](#initial-creation-prompt-admission) | ## Components and responsibilities @@ -73,6 +75,71 @@ handler. The implementation does not change their layout, labels, touch targets, or navigation. Separate Playwright scenarios exercise the desktop split-menu action and the mobile plan-mode action. +## Initial creation prompt admission + +This draft extension preserves initial placement from requirement `004`. +The explicit step remains the source of the first user-message transition. +The task system already owns this transition through `ProcessOnTurnStart`. +The correction connects immediate REST and MCP creation to that existing boundary. + +### Eligibility and transport ownership + +Capture explicit step selection from the original create request before destination resolution. +MCP fills `WorkflowStepID` even when the caller omits it, so the resolved value cannot prove explicit selection. +Set a private `InitialCreatePrompt` marker on `LaunchSessionRequest` with `json:"-"`. +The marker applies only to an admitted immediate create with an explicit step and non-empty textual input. +It is not an agent-supplied or WebSocket-supplied launch option. + +REST preserves its synchronous `IntentPrepare` and asynchronous `IntentStartCreated` sequence. +MCP preserves its existing asynchronous boundary and creation-settlement checks. +For a marked MCP `IntentStart`, prepare a session through the existing prepare path with `DeferredStart: true`. +Then use the same marked prepared-session dispatch as REST. +Unmarked starts retain their current path. Do not infer eligibility from `AutoStart`, which has different workflow and scheduling semantics. + +Keep the shared orchestration in a focused helper, proposed as `task_create_prompt.go`. +Keep `StartCreatedSession` free of unconditional trigger processing because workflow automatic starts also call it. + +### Transition before composition + +After preparation and before prompt composition, call `ProcessOnTurnStart` once. +Use its existing transition lifecycle, which suppresses the destination's competing automatic prompt. +Do not invoke the full `on_enter` sequence separately. +Reload the task and resolve the resulting session using the same ownership rules as ordinary message submission. +Reject a terminal or superseded session instead of reviving it. + +Resolve the effective profile and session settings from the resulting route. +Build workflow content and the Kandev system block only after this resolution. +Retain initial-task-brief admission, attachments, saved prompt expansion, and the existing first-message record. +Do not duplicate the original description or persist two user messages. + +### Queues and running notifications + +If `ProcessOnTurnStartResult.Queued` is true, retain the input through the existing message queue and WIP admission path. +Set `MetaKeyTurnStartAlreadyProcessed` on that queued input. +Do not send the prompt or allocate a second session while WIP admission is pending. +Queue insertion must retain attachment ownership and existing session-incarnation checks. + +For passthrough, the initial running notification must not evaluate the same trigger again. +Bind the processed-trigger evidence to the admitted initial turn and execution identity. +Consume or retire it through the matching running, failure, cancellation, or replacement path. +A session-wide permanent skip flag would suppress later terminal input and is prohibited. +Unmarked passthrough launches retain their existing event-driven trigger behavior. +Queue replay must transfer the processed evidence to its actual dispatch identity. + +### Failures and verification + +Return processing and session-resolution errors before provider dispatch. +Use existing launch-error persistence so asynchronous failure remains visible. +Do not convert an error into a successful launch or bypass creation settlement, dependency, WIP, cancellation, or terminal-session gates. +The existing engine logs identify successful transitions; failure logs include task and session identity without prompt text. + +Test both transport adapters and the real orchestration/engine path with controlled executor callbacks. +At the first dispatch boundary, assert the step, session, profile, content, and dispatch count. +Cover WIP release, profile switching, passthrough duplicate events, and a subsequent user turn. +Keep automatic-entry and omitted-step controls to prevent cascading transitions. +This package changes no rendered UI, public request field, storage schema, or provider protocol. +The existing board projection shows the resulting step on desktop and phone. + ## Session states A `CREATED` session has no conversation to reset. The workflow reset skips provider work and leaves the first start to `auto_start_agent`.