diff --git a/apps/backend/internal/mcp/handlers/handlers.go b/apps/backend/internal/mcp/handlers/handlers.go index dd83d2ce1b..1c55e7b49d 100644 --- a/apps/backend/internal/mcp/handlers/handlers.go +++ b/apps/backend/internal/mcp/handlers/handlers.go @@ -1322,12 +1322,13 @@ func (h *Handlers) handleUpdateTask(ctx context.Context, msg *ws.Message) (*ws.M } // handleSetTaskTitle resolves the one-shot provisional title created for a -// prompt-first task. The MCP server supplies the bound task ID; a missing -// pending marker makes the call an idempotent no-op so a human rename wins. +// prompt-first task. The MCP server supplies the bound task and session IDs; +// only the atomically claimed owner may resolve it. func (h *Handlers) handleSetTaskTitle(ctx context.Context, msg *ws.Message) (*ws.Message, error) { var req struct { - TaskID string `json:"task_id"` - Title string `json:"title"` + TaskID string `json:"task_id"` + SessionID string `json:"session_id"` + Title string `json:"title"` } if err := json.Unmarshal(msg.Payload, &req); err != nil { return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) @@ -1335,11 +1336,14 @@ func (h *Handlers) handleSetTaskTitle(ctx context.Context, msg *ws.Message) (*ws if req.TaskID == "" { return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "task_id is required", nil) } + if req.SessionID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "session_id is required", nil) + } if strings.TrimSpace(req.Title) == "" { return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "title is required", nil) } - task, accepted, err := h.taskSvc.SetPendingAgentTitle(ctx, req.TaskID, req.Title) + task, accepted, reason, err := h.taskSvc.SetPendingAgentTitle(ctx, req.TaskID, req.SessionID, req.Title) if err != nil { if errors.Is(err, taskrepo.ErrTaskNotFound) { return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeNotFound, "task not found", nil) @@ -1356,7 +1360,7 @@ func (h *Handlers) handleSetTaskTitle(ctx context.Context, msg *ws.Message) (*ws "title": task.Title, } if !accepted { - result["reason"] = "title_not_pending" + result["reason"] = reason } return ws.NewResponse(msg.ID, msg.Action, result) } diff --git a/apps/backend/internal/mcp/handlers/set_task_title_test.go b/apps/backend/internal/mcp/handlers/set_task_title_test.go index 2bb1836590..e3f3157850 100644 --- a/apps/backend/internal/mcp/handlers/set_task_title_test.go +++ b/apps/backend/internal/mcp/handlers/set_task_title_test.go @@ -27,15 +27,16 @@ func TestHandleSetTaskTitle_UpdatesPendingTitleOnce(t *testing.T) { Title: "Build the useful feature now", Description: "Build the useful feature now", State: v1.TaskStateInProgress, - Metadata: map[string]interface{}{models.MetaKeyAgentTitlePending: true}, + Metadata: map[string]interface{}{models.MetaKeyAgentTitlePending: true, models.MetaKeyAgentTitleOwnerSessionID: "session-title"}, CreatedAt: now, UpdatedAt: now, })) h := &Handlers{taskSvc: svc, logger: testLogger(t).WithFields()} resp, err := h.handleSetTaskTitle(ctx, makeWSMessage(t, ws.ActionMCPSetTaskTitle, map[string]interface{}{ - "task_id": "task-title", - "title": "Useful Feature", + "task_id": "task-title", + "session_id": "session-title", + "title": "Useful Feature", })) require.NoError(t, err) assertTaskTitleResponse(t, resp, map[string]interface{}{ @@ -50,8 +51,9 @@ func TestHandleSetTaskTitle_UpdatesPendingTitleOnce(t *testing.T) { assert.False(t, models.IsAgentTitlePending(updated.Metadata)) resp, err = h.handleSetTaskTitle(ctx, makeWSMessage(t, ws.ActionMCPSetTaskTitle, map[string]interface{}{ - "task_id": "task-title", - "title": "Late Agent Title", + "task_id": "task-title", + "session_id": "session-title", + "title": "Late Agent Title", })) require.NoError(t, err) assertTaskTitleResponse(t, resp, map[string]interface{}{ @@ -82,6 +84,37 @@ func TestHandleSetTaskTitle_ValidatesInput(t *testing.T) { assertWSError(t, resp, ws.ErrorCodeValidation) } +func TestHandleSetTaskTitleRejectsNonOwner(t *testing.T) { + svc, repo := newTestTaskService(t) + ctx := context.Background() + now := time.Now().UTC() + require.NoError(t, repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-title-owner", Name: "Titles", CreatedAt: now, UpdatedAt: now})) + require.NoError(t, repo.CreateTask(ctx, &models.Task{ + ID: "task-title-owner", + WorkspaceID: "ws-title-owner", + Title: "Temporary title", + Description: "Prompt", + State: v1.TaskStateInProgress, + Metadata: map[string]interface{}{models.MetaKeyAgentTitlePending: true, models.MetaKeyAgentTitleOwnerSessionID: "session-owner"}, + CreatedAt: now, + UpdatedAt: now, + })) + h := &Handlers{taskSvc: svc, logger: testLogger(t).WithFields()} + + resp, err := h.handleSetTaskTitle(ctx, makeWSMessage(t, ws.ActionMCPSetTaskTitle, map[string]interface{}{ + "task_id": "task-title-owner", + "session_id": "session-other", + "title": "Other title", + })) + require.NoError(t, err) + assertTaskTitleResponse(t, resp, map[string]interface{}{ + "accepted": false, + "task_id": "task-title-owner", + "title": "Temporary title", + "reason": "title_not_owner", + }) +} + func TestHandleSetTaskTitle_RejectsOverlongTitle(t *testing.T) { svc, repo := newTestTaskService(t) ctx := context.Background() @@ -95,15 +128,16 @@ func TestHandleSetTaskTitle_RejectsOverlongTitle(t *testing.T) { Title: "Temporary title", Description: "Prompt", State: v1.TaskStateInProgress, - Metadata: map[string]interface{}{models.MetaKeyAgentTitlePending: true}, + Metadata: map[string]interface{}{models.MetaKeyAgentTitlePending: true, models.MetaKeyAgentTitleOwnerSessionID: "session-title-long"}, CreatedAt: now, UpdatedAt: now, })) h := &Handlers{taskSvc: svc, logger: testLogger(t).WithFields()} resp, err := h.handleSetTaskTitle(ctx, makeWSMessage(t, ws.ActionMCPSetTaskTitle, map[string]interface{}{ - "task_id": "task-title-long", - "title": strings.Repeat("x", 501), + "task_id": "task-title-long", + "session_id": "session-title-long", + "title": strings.Repeat("x", 501), })) require.NoError(t, err) assertWSError(t, resp, ws.ErrorCodeValidation) diff --git a/apps/backend/internal/mcp/server/server.go b/apps/backend/internal/mcp/server/server.go index 309b96c1f5..0670a1b64c 100644 --- a/apps/backend/internal/mcp/server/server.go +++ b/apps/backend/internal/mcp/server/server.go @@ -1027,10 +1027,12 @@ Call this as your first action in the session, before planning, inspecting files or doing any other work. The task currently has a provisional title derived from the prompt; call this tool even when that provisional title looks usable. -Use a concise title targeting about 3 words (no more than 6 words when practical). -Write a short noun phrase, not a sentence or a progress update. Your title should -summarize the requested outcome and will replace the provisional title.`), - mcp.WithString(titleArg, mcp.Required(), mcp.Description("Short task title targeting about 3 words; use no more than 6 words when practical.")), +Use a concise title targeting about 6 words. +Write a short title phrase, not a sentence or a progress update. Your title should +summarize the requested outcome and will replace the provisional title. Use sentence case: +capitalize only the first word and proper nouns (for example, "Improve task title casing", not +"Improve Task Title Casing").`), + mcp.WithString(titleArg, mcp.Required(), mcp.Description("Short sentence-case task title targeting about 6 words.")), ), s.wrapHandler("set_task_title_kandev", s.setTaskTitleHandler()), ) diff --git a/apps/backend/internal/mcp/server/server_test.go b/apps/backend/internal/mcp/server/server_test.go index 7263f21dca..72639d6ec9 100644 --- a/apps/backend/internal/mcp/server/server_test.go +++ b/apps/backend/internal/mcp/server/server_test.go @@ -279,7 +279,17 @@ func TestServerModeTaskTitlePending_RegistersTitleToolOnlyForPendingTaskMode(t * titleTool, ok := pending.mcpServer.ListTools()["set_task_title_kandev"] require.True(t, ok, "pending task mode must register set_task_title_kandev") assert.Contains(t, titleTool.Tool.Description, "first action") - assert.Contains(t, titleTool.Tool.Description, "3 words") + assert.Contains(t, titleTool.Tool.Description, "6 words") + assert.Contains(t, titleTool.Tool.Description, "sentence case") + assert.Contains(t, titleTool.Tool.Description, "Improve task title casing") + assert.Contains(t, titleTool.Tool.Description, "short title phrase") + assert.NotContains(t, titleTool.Tool.Description, "short noun phrase") + + titleProperties := toolInputProperties(t, pending, "set_task_title_kandev") + titleProperty, ok := titleProperties["title"].(map[string]interface{}) + require.True(t, ok, "title argument should have a schema property") + assert.Contains(t, titleProperty["description"], "targeting about 6 words") + assert.Contains(t, titleProperty["description"], "sentence-case") ordinary := New(backend, "test-session", "test-task", 10005, log, "", false, ModeTask) assert.NotContains(t, ordinary.mcpServer.ListTools(), "set_task_title_kandev") diff --git a/apps/backend/internal/orchestrator/event_handlers_workflow.go b/apps/backend/internal/orchestrator/event_handlers_workflow.go index b84253f159..6c274879d7 100644 --- a/apps/backend/internal/orchestrator/event_handlers_workflow.go +++ b/apps/backend/internal/orchestrator/event_handlers_workflow.go @@ -1570,17 +1570,26 @@ func (s *Service) autoStartStepPrompt( // Passthrough sessions skip the wrap: the prompt is typed straight into // the agent CLI's TTY and the user sees it verbatim. recordedPrompt := agentPrompt + titleOwner := false + isOfficeTask := false + if session.State == models.TaskSessionStateCreated { + var officeErr error + isOfficeTask, officeErr = s.lookupOfficeTask(ctx, taskID) + if officeErr != nil { + requeueTaken() + return fmt.Errorf("resolve MCP mode for workflow auto-start: %w", officeErr) + } + configMode, _ := session.Metadata["config_mode"].(bool) + if !configMode && !isOfficeTask { + var claimErr error + titleOwner, claimErr = s.ClaimTaskTitleSession(ctx, taskID, sessionID) + if claimErr != nil { + requeueTaken() + return fmt.Errorf("claim task title for workflow auto-start: %w", claimErr) + } + } + } if session.State == models.TaskSessionStateCreated && !session.IsPassthrough && (agentPrompt != "" || len(attachments) > 0) { - isOfficeTask, err := s.lookupOfficeTask(ctx, taskID) - if err != nil { - requeueTaken() - return fmt.Errorf("resolve MCP mode for workflow auto-start: %w", err) - } - dbTask, err := s.repo.GetTask(ctx, taskID) - if err != nil { - requeueTaken() - return fmt.Errorf("resolve task title capability for workflow auto-start: %w", err) - } configMode, _ := session.Metadata["config_mode"].(bool) requiresSignal := step != nil && step.AutoAdvanceRequiresSignal referenceContext := EntityReferenceContext(references) @@ -1590,7 +1599,7 @@ func (s *Service) autoStartStepPrompt( recordedPrompt = sysprompt.InjectKandevContextWithOptions(taskID, sessionID, agentPrompt, sysprompt.KandevContextOptions{ RequiresCompletionSignal: requiresSignal, IncludeCoordinatorTaskControls: !configMode, - IncludeTaskTitleTool: !configMode && dbTask != nil && models.IsAgentTitlePending(dbTask.Metadata), + IncludeTaskTitleTool: !configMode && titleOwner, }, referenceContext) } } diff --git a/apps/backend/internal/orchestrator/executor/executor_execute.go b/apps/backend/internal/orchestrator/executor/executor_execute.go index f6471bbf89..0d6b0666fd 100644 --- a/apps/backend/internal/orchestrator/executor/executor_execute.go +++ b/apps/backend/internal/orchestrator/executor/executor_execute.go @@ -36,7 +36,7 @@ func isConfigModeSession(session *models.TaskSession) bool { // resolveTaskSessionMCPMode derives restricted MCP access from canonical task // ownership and session purpose. Config mode wins because those sessions need // config tools even if their backing task is Office-owned. -func (e *Executor) resolveTaskSessionMCPMode(ctx context.Context, taskID string, session *models.TaskSession) (string, error) { +func (e *Executor) resolveTaskSessionMCPMode(ctx context.Context, taskID string, session *models.TaskSession, allowTitleTool bool) (string, error) { if isConfigModeSession(session) { return McpModeConfig, nil } @@ -47,7 +47,7 @@ func (e *Executor) resolveTaskSessionMCPMode(ctx context.Context, taskID string, if task != nil && task.IsFromOffice { return McpModeOffice, nil } - if task != nil && models.IsAgentTitlePending(task.Metadata) { + if allowTitleTool && task != nil && models.IsAgentTitleOwner(task.Metadata, session.ID) { return McpModeTaskTitlePending, nil } return "", nil @@ -643,6 +643,23 @@ func (e *Executor) ExecuteWithFullProfile(ctx context.Context, task *v1.Task, ag if err != nil { return nil, err } + dbTask, err := e.repo.GetTask(ctx, task.ID) + if err != nil { + return nil, fmt.Errorf("load task before title claim: %w", err) + } + session, err := e.repo.GetTaskSession(ctx, sessionID) + if err != nil { + return nil, fmt.Errorf("load session before title claim: %w", err) + } + if (dbTask == nil || !dbTask.IsFromOffice) && !isConfigModeSession(session) { + if claimer, ok := e.repo.(interface { + ClaimTaskTitleSession(context.Context, string, string) (bool, bool, error) + }); ok { + if _, _, err := claimer.ClaimTaskTitleSession(ctx, task.ID, sessionID); err != nil { + return nil, fmt.Errorf("claim first-turn task title: %w", err) + } + } + } // Launch the agent for the prepared session. execution, err := e.LaunchPreparedSession(ctx, task, sessionID, LaunchOptions{ @@ -832,7 +849,7 @@ func (e *Executor) LaunchPreparedSession(ctx context.Context, task *v1.Task, ses return nil, fmt.Errorf("session does not belong to task") } if opts.McpMode == "" { - opts.McpMode, err = e.resolveTaskSessionMCPMode(ctx, task.ID, session) + opts.McpMode, err = e.resolveTaskSessionMCPMode(ctx, task.ID, session, opts.StartAgent) if err != nil { return nil, err } diff --git a/apps/backend/internal/orchestrator/executor/executor_interaction.go b/apps/backend/internal/orchestrator/executor/executor_interaction.go index ac108e5d05..1cc97edc07 100644 --- a/apps/backend/internal/orchestrator/executor/executor_interaction.go +++ b/apps/backend/internal/orchestrator/executor/executor_interaction.go @@ -600,7 +600,7 @@ func (e *Executor) buildSwitchModelRequest(ctx context.Context, task *models.Tas Env: cloneStringMap(execConfig.ProfileEnv), } - mcpMode, err := e.resolveTaskSessionMCPMode(ctx, task.ID, session) + mcpMode, err := e.resolveTaskSessionMCPMode(ctx, task.ID, session, true) if err != nil { return nil, err } diff --git a/apps/backend/internal/orchestrator/executor/executor_mcp_mode_test.go b/apps/backend/internal/orchestrator/executor/executor_mcp_mode_test.go index 9debeea8ef..ee87677ac2 100644 --- a/apps/backend/internal/orchestrator/executor/executor_mcp_mode_test.go +++ b/apps/backend/internal/orchestrator/executor/executor_mcp_mode_test.go @@ -13,14 +13,23 @@ func TestResolveTaskSessionMCPMode_TitlePendingIsTaskModeVariant(t *testing.T) { repo := newMockRepository() repo.tasks["task-pending"] = &models.Task{ ID: "task-pending", - Metadata: map[string]interface{}{models.MetaKeyAgentTitlePending: true}, + Metadata: map[string]interface{}{models.MetaKeyAgentTitlePending: true, models.MetaKeyAgentTitleOwnerSessionID: "session-pending"}, } - repo.sessions["session-pending"] = &models.TaskSession{TaskID: "task-pending"} + repo.sessions["session-pending"] = &models.TaskSession{ID: "session-pending", TaskID: "task-pending"} exec := newTestExecutor(t, &mockAgentManager{}, repo) - mode, err := exec.resolveTaskSessionMCPMode(ctx, "task-pending", repo.sessions["session-pending"]) + mode, err := exec.resolveTaskSessionMCPMode(ctx, "task-pending", repo.sessions["session-pending"], true) require.NoError(t, err) require.Equal(t, McpModeTaskTitlePending, mode) + + repo.sessions["session-other"] = &models.TaskSession{ID: "session-other", TaskID: "task-pending"} + mode, err = exec.resolveTaskSessionMCPMode(ctx, "task-pending", repo.sessions["session-other"], true) + require.NoError(t, err) + require.Empty(t, mode) + + mode, err = exec.resolveTaskSessionMCPMode(ctx, "task-pending", repo.sessions["session-pending"], false) + require.NoError(t, err) + require.Empty(t, mode) } func TestResolveTaskSessionMCPMode_TitlePendingDoesNotOverrideRestrictedModes(t *testing.T) { @@ -38,11 +47,11 @@ func TestResolveTaskSessionMCPMode_TitlePendingDoesNotOverrideRestrictedModes(t repo.sessions["session-office"] = &models.TaskSession{TaskID: "task-pending"} exec := newTestExecutor(t, &mockAgentManager{}, repo) - mode, err := exec.resolveTaskSessionMCPMode(ctx, "task-pending", repo.sessions["session-config"]) + mode, err := exec.resolveTaskSessionMCPMode(ctx, "task-pending", repo.sessions["session-config"], true) require.NoError(t, err) require.Equal(t, McpModeConfig, mode) - mode, err = exec.resolveTaskSessionMCPMode(ctx, "task-pending", repo.sessions["session-office"]) + mode, err = exec.resolveTaskSessionMCPMode(ctx, "task-pending", repo.sessions["session-office"], true) require.NoError(t, err) require.Equal(t, McpModeOffice, mode) } diff --git a/apps/backend/internal/orchestrator/executor/executor_resume.go b/apps/backend/internal/orchestrator/executor/executor_resume.go index 32212d68fe..2ca2e19506 100644 --- a/apps/backend/internal/orchestrator/executor/executor_resume.go +++ b/apps/backend/internal/orchestrator/executor/executor_resume.go @@ -905,7 +905,7 @@ func (e *Executor) buildResumeRequestAtCredentialBoundary( e.reuseExistingEnvironment(ctx, req, existingEnv) - req.McpMode, err = e.resolveTaskSessionMCPMode(ctx, task.ID, session) + req.McpMode, err = e.resolveTaskSessionMCPMode(ctx, task.ID, session, true) if err != nil { return nil, "", execConfig, nil, nil, err } diff --git a/apps/backend/internal/orchestrator/service.go b/apps/backend/internal/orchestrator/service.go index f0367c6046..b172dcde9d 100644 --- a/apps/backend/internal/orchestrator/service.go +++ b/apps/backend/internal/orchestrator/service.go @@ -219,6 +219,10 @@ type sessionExecutorStore interface { GetExecutor(ctx context.Context, id string) (*models.Executor, error) // Task GetTask(ctx context.Context, id string) (*models.Task, error) + // ClaimTaskTitleSession atomically assigns the first eligible session to a + // pending task title. The second return value reports a new claim rather + // than an idempotent same-owner observation. + ClaimTaskTitleSession(ctx context.Context, taskID, sessionID string) (owned bool, newlyClaimed bool, err error) UpdateTask(ctx context.Context, task *models.Task) error ListChildCompletionRows(ctx context.Context, parentID string) ([]models.ChildCompletionRow, error) // Git snapshots and commits @@ -247,6 +251,34 @@ type sessionExecutorStore interface { UpdateTaskEnvironment(ctx context.Context, env *models.TaskEnvironment) error } +// ClaimTaskTitleSession claims the first-turn generated-title handoff for a +// task. The repository owns the compare-and-set; the orchestrator publishes a +// task update only when this call creates a new owner. +func (s *Service) ClaimTaskTitleSession(ctx context.Context, taskID, sessionID string) (bool, error) { + if taskID == "" || sessionID == "" { + return false, nil + } + task, err := s.repo.GetTask(ctx, taskID) + if err != nil { + return false, err + } + if !models.IsAgentTitlePending(task.Metadata) { + return false, nil + } + owned, newlyClaimed, err := s.repo.ClaimTaskTitleSession(ctx, taskID, sessionID) + if err != nil { + return false, err + } + if newlyClaimed { + claimedTask, reloadErr := s.repo.GetTask(ctx, taskID) + if reloadErr != nil { + return false, reloadErr + } + s.publishTaskUpdated(ctx, claimedTask) + } + return owned, nil +} + // Service is the main orchestrator service type Service struct { config ServiceConfig diff --git a/apps/backend/internal/orchestrator/spawn_origin_test.go b/apps/backend/internal/orchestrator/spawn_origin_test.go index 1f1037fd5e..697da93e0e 100644 --- a/apps/backend/internal/orchestrator/spawn_origin_test.go +++ b/apps/backend/internal/orchestrator/spawn_origin_test.go @@ -82,7 +82,7 @@ func TestApplyLaunchPromptContext_PassthroughAddsPendingTitleInstructionOnlyWhen includeTaskTitleTool: true, }) assert.Contains(t, withTitle, "set_task_title_kandev") - assert.Contains(t, withTitle, "targeting about 3 words") + assert.Contains(t, withTitle, "targeting about 6 words") assert.Contains(t, withTitle, "review the diff please") assert.NotContains(t, withTitle, sysprompt.TagStart) diff --git a/apps/backend/internal/orchestrator/task_operations.go b/apps/backend/internal/orchestrator/task_operations.go index 00506f63cd..8a304e1722 100644 --- a/apps/backend/internal/orchestrator/task_operations.go +++ b/apps/backend/internal/orchestrator/task_operations.go @@ -473,15 +473,24 @@ func (s *Service) StartCreatedSession( if err != nil { return nil, fmt.Errorf("failed to reload task after on_turn_start: %w", err) } + configMode := false + if cm, ok := session.Metadata["config_mode"].(bool); ok && cm { + configMode = true + } + titleOwner := false + if !configMode { + titleOwner, err = s.ClaimTaskTitleSession(ctx, taskID, sessionID) + if err != nil { + return nil, fmt.Errorf("failed to claim first-turn task title: %w", err) + } + } effectivePrompt, planModeActive, promptReferenceContext := s.applyWorkflowAndPlanMode( ctx, effectivePrompt, taskID, sessionID, dbTask.WorkflowStepID, planMode, task.IsEphemeral, session.IsPassthrough, ) // Inject config context for config-mode sessions (dedicated settings chat) - configMode := false - if cm, ok := session.Metadata["config_mode"].(bool); ok && cm { - configMode = true + if configMode { effectivePrompt = sysprompt.InjectConfigContext(sessionID, effectivePrompt) } @@ -495,7 +504,7 @@ func (s *Service) StartCreatedSession( if effectivePrompt != "" || len(attachments) > 0 { effectivePrompt = s.wrapCreatedSessionPrompt( ctx, effectivePrompt, taskID, sessionID, session, dbTask, - isOfficeTask, configMode, references, promptReferenceContext, + isOfficeTask, configMode, titleOwner, references, promptReferenceContext, ) } @@ -537,14 +546,14 @@ func (s *Service) wrapCreatedSessionPrompt( prompt, taskID, sessionID string, session *models.TaskSession, dbTask *models.Task, - isOfficeTask, configMode bool, + isOfficeTask, configMode, titleOwner bool, references []v1.EntityReference, promptReferenceContext string, ) string { referenceContext := EntityReferenceContext(references) switch { case session.IsPassthrough: - if !configMode && models.IsAgentTitlePending(dbTask.Metadata) { + if !configMode && titleOwner { return sysprompt.PendingTaskTitlePassthroughInstruction() + "\n\n" + prompt } return prompt @@ -556,7 +565,7 @@ func (s *Service) wrapCreatedSessionPrompt( return sysprompt.InjectKandevContextWithOptions(taskID, sessionID, prompt, sysprompt.KandevContextOptions{ RequiresCompletionSignal: s.WorkflowStepRequiresCompletionSignal(ctx, dbTask.WorkflowStepID), IncludeCoordinatorTaskControls: !configMode, - IncludeTaskTitleTool: !configMode && models.IsAgentTitlePending(dbTask.Metadata), + IncludeTaskTitleTool: !configMode && titleOwner, }, referenceContext, promptReferenceContext) } } @@ -905,6 +914,13 @@ func (s *Service) startTask(ctx context.Context, taskID string, agentProfileID s configMode = true effectivePrompt = sysprompt.InjectConfigContext(sessionID, effectivePrompt) } + titleOwner := false + if !configMode && !isOfficeTask { + titleOwner, err = s.ClaimTaskTitleSession(ctx, task.ID, sessionID) + if err != nil { + return nil, fmt.Errorf("failed to claim first-turn task title: %w", err) + } + } // Wrap the first prompt with the Kandev MCP system block (task/session IDs + // tool list). Done at the orchestrator layer so recordInitialMessage persists @@ -931,7 +947,7 @@ func (s *Service) startTask(ctx context.Context, taskID string, agentProfileID s isPassthrough: skipKandevMCPWrap, configMode: configMode, referenceContext: promptReferenceContext, - includeTaskTitleTool: !configMode && models.IsAgentTitlePending(task.Metadata), + includeTaskTitleTool: !configMode && titleOwner, spawnOrigin: opts.SpawnOrigin, }) } @@ -1960,6 +1976,9 @@ func (s *Service) startAgentOnPreparedWorkspace(ctx context.Context, sessionID s if err != nil { return fmt.Errorf("failed to get task for prepared session: %w", err) } + if _, err := s.ClaimTaskTitleSession(launchCtx, session.TaskID, sessionID); err != nil { + return fmt.Errorf("failed to claim first-turn task title: %w", err) + } if _, err = s.executor.LaunchPreparedSession(launchCtx, task, sessionID, executor.LaunchOptions{ AgentProfileID: session.AgentProfileID, ExecutorID: session.ExecutorID, diff --git a/apps/backend/internal/sysprompt/sysprompt.go b/apps/backend/internal/sysprompt/sysprompt.go index c24fa2d28d..1c40aa8322 100644 --- a/apps/backend/internal/sysprompt/sysprompt.go +++ b/apps/backend/internal/sysprompt/sysprompt.go @@ -169,7 +169,8 @@ const coordinatorTaskControlSection = " Optional: session_id, delivery_mode. " + const taskTitleSection = "- set_task_title_kandev: Set the user-facing title for the CURRENT task. " + "Call this as your first action in the session, before planning, inspecting files, or doing any other work. " + "Call it even when the provisional title looks usable. " + - "Use a concise title targeting about 3 words (no more than 6 words when practical), as a short noun phrase rather than a sentence or progress update. " + + "Use a concise title targeting about 6 words, as a short title phrase rather than a sentence or progress update. " + + "Use sentence case: capitalize only the first word and proper nouns (for example, \"Improve task title casing\", not \"Improve Task Title Casing\"). " + "Required param: title.\n" // PendingTaskTitlePassthroughInstruction is the compact equivalent of the @@ -178,7 +179,8 @@ const taskTitleSection = "- set_task_title_kandev: Set the user-facing title for // printed into the user's terminal. func PendingTaskTitlePassthroughInstruction() string { return "Before doing any other work, call set_task_title_kandev for the current task. " + - "Use a concise title targeting about 3 words (no more than 6 words when practical), " + + "Use a concise title targeting about 6 words, as a short title phrase rather than a sentence or progress update, " + + "in sentence case (for example, \"Improve task title casing\", not \"Improve Task Title Casing\"), " + "even if the provisional title looks usable." } diff --git a/apps/backend/internal/sysprompt/sysprompt_test.go b/apps/backend/internal/sysprompt/sysprompt_test.go index 41a0aeadb0..7364ea1194 100644 --- a/apps/backend/internal/sysprompt/sysprompt_test.go +++ b/apps/backend/internal/sysprompt/sysprompt_test.go @@ -127,7 +127,21 @@ func TestFormatKandevContext_TitleToolFollowsCapability(t *testing.T) { }) assert.Contains(t, withTitle, "set_task_title_kandev") assert.Contains(t, withTitle, "first action") - assert.Contains(t, withTitle, "targeting about 3 words") + assert.Contains(t, withTitle, "targeting about 6 words") + assert.Contains(t, withTitle, "sentence case") + assert.Contains(t, withTitle, "Improve task title casing") + assert.Contains(t, withTitle, "short title phrase") + assert.Contains(t, withTitle, "progress update") + assert.NotContains(t, withTitle, "short noun phrase") +} + +func TestPendingTaskTitlePassthroughInstruction_UsesSentenceCase(t *testing.T) { + instruction := PendingTaskTitlePassthroughInstruction() + + assert.Contains(t, instruction, "sentence case") + assert.Contains(t, instruction, "Improve task title casing") + assert.Contains(t, instruction, "short title phrase") + assert.Contains(t, instruction, "progress update") } func TestFormatKandevContext_IncludesStepCompleteToolWhenRequired(t *testing.T) { diff --git a/apps/backend/internal/task/handlers/message_handlers.go b/apps/backend/internal/task/handlers/message_handlers.go index eb88d7a70d..e868639609 100644 --- a/apps/backend/internal/task/handlers/message_handlers.go +++ b/apps/backend/internal/task/handlers/message_handlers.go @@ -39,6 +39,10 @@ type OrchestratorService interface { ForegroundActivity(sessionID string) v1.ForegroundActivity } +type taskTitleSessionClaimer interface { + ClaimTaskTitleSession(ctx context.Context, taskID, sessionID string) (bool, error) +} + // MessageHandlers handles WebSocket requests for messages type MessageHandlers struct { service *service.Service @@ -72,6 +76,18 @@ func NewMessageHandlers( return handlers } +func (h *MessageHandlers) claimTaskTitleSession(ctx context.Context, task *models.Task, taskID, sessionID string) (bool, error) { + if task == nil || task.IsFromOffice { + return false, nil + } + titleOwner := models.IsAgentTitleOwner(task.Metadata, sessionID) + claimer, ok := h.orchestrator.(taskTitleSessionClaimer) + if !ok { + return titleOwner, nil + } + return claimer.ClaimTaskTitleSession(ctx, taskID, sessionID) +} + // RegisterMessageRoutes registers message HTTP + WebSocket handlers func RegisterMessageRoutes( router *gin.Engine, @@ -306,6 +322,7 @@ func (h *MessageHandlers) wsAddMessage(ctx context.Context, msg *ws.Message) (*w if wsErr != nil { return wsErr, nil } + wasCreatedSession := sessionResp.Session.State == models.TaskSessionStateCreated if len(req.EntityReferences) > 0 { if sessionResp.Session.IsPassthrough || h.referenceValidator == nil { return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "Invalid entity references", nil) @@ -357,6 +374,7 @@ func (h *MessageHandlers) wsAddMessage(ctx context.Context, msg *ws.Message) (*w return wsErr, nil } isCreatedSession := sessionResp.Session.State == models.TaskSessionStateCreated + startCreatedSession := isCreatedSession || wasCreatedSession // Build metadata with attachments, plan mode, review comments, and context files meta := orchestrator.NewUserMessageMeta(). @@ -382,13 +400,18 @@ func (h *MessageHandlers) wsAddMessage(ctx context.Context, msg *ws.Message) (*w // the agent CLI's TTY and the user sees it verbatim — they don't want a // wall of MCP-tool boilerplate prepended to "hello". storedContent := orchestrator.AppendEntityReferenceContext(req.Content, req.EntityReferences) - if isCreatedSession && !sessionResp.Session.IsPassthrough && (req.Content != "" || len(req.Attachments) > 0) { + if startCreatedSession && !sessionResp.Session.IsPassthrough && (req.Content != "" || len(req.Attachments) > 0) { task, err := h.service.GetTask(ctx, req.TaskID) if err != nil { h.logger.Error("failed to resolve first-turn MCP capabilities", zap.String("task_id", req.TaskID), zap.Error(err)) return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to get task", nil) } configMode, _ := sessionResp.Session.Metadata["config_mode"].(bool) + titleOwner, claimErr := h.claimTaskTitleSession(ctx, task, req.TaskID, req.TaskSessionID) + if claimErr != nil { + h.logger.Error("failed to claim first-turn task title", zap.String("task_id", req.TaskID), zap.String("session_id", req.TaskSessionID), zap.Error(claimErr)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to claim task title", nil) + } requiresSignal := h.orchestrator != nil && h.orchestrator.StepRequiresCompletionSignal(ctx, req.TaskID) referenceContext := orchestrator.EntityReferenceContext(req.EntityReferences) if task.IsFromOffice { @@ -397,7 +420,7 @@ func (h *MessageHandlers) wsAddMessage(ctx context.Context, msg *ws.Message) (*w storedContent = sysprompt.InjectKandevContextWithOptions(req.TaskID, req.TaskSessionID, storedContent, sysprompt.KandevContextOptions{ RequiresCompletionSignal: requiresSignal, IncludeCoordinatorTaskControls: !configMode, - IncludeTaskTitleTool: !configMode && models.IsAgentTitlePending(task.Metadata), + IncludeTaskTitleTool: !configMode && titleOwner, }, referenceContext) } } @@ -433,7 +456,7 @@ func (h *MessageHandlers) wsAddMessage(ctx context.Context, msg *ws.Message) (*w // This runs async so the WS request can respond immediately. // Use context.WithoutCancel so the prompt continues even if the WebSocket client disconnects. if h.orchestrator != nil { - h.dispatchPromptAsync(ctx, req, sessionResp.Session.AgentProfileID, isCreatedSession) + h.dispatchPromptAsync(ctx, req, sessionResp.Session.AgentProfileID, startCreatedSession) } return response, nil diff --git a/apps/backend/internal/task/models/models.go b/apps/backend/internal/task/models/models.go index 86caa08600..95b881409e 100644 --- a/apps/backend/internal/task/models/models.go +++ b/apps/backend/internal/task/models/models.go @@ -113,6 +113,9 @@ const ( // MetaKeyAgentTitlePending marks tasks created in prompt-first mode whose // provisional title still needs the first eligible agent session to replace it. MetaKeyAgentTitlePending = "agent_title_pending" + // MetaKeyAgentTitleOwnerSessionID records the one session that atomically + // claimed the first-turn title handoff for a pending task. + MetaKeyAgentTitleOwnerSessionID = "agent_title_owner_session_id" ) // IsAgentTitlePending reports whether task metadata contains the durable @@ -124,6 +127,18 @@ func IsAgentTitlePending(metadata map[string]interface{}) bool { return ok && pending } +// AgentTitleOwnerSessionID returns the session that owns the pending title +// handoff, if one has been claimed. +func AgentTitleOwnerSessionID(metadata map[string]interface{}) string { + owner, _ := metadata[MetaKeyAgentTitleOwnerSessionID].(string) + return owner +} + +// IsAgentTitleOwner reports whether sessionID owns the pending title handoff. +func IsAgentTitleOwner(metadata map[string]interface{}, sessionID string) bool { + return sessionID != "" && IsAgentTitlePending(metadata) && AgentTitleOwnerSessionID(metadata) == sessionID +} + // TaskSession.Metadata key that records how the session came into existence. // workflow_switch means the session profile was selected by workflow routing // rather than direct user selection. diff --git a/apps/backend/internal/task/repository/sqlite/postgres_schema_test.go b/apps/backend/internal/task/repository/sqlite/postgres_schema_test.go index 2d2ba592e0..6c8284e8d1 100644 --- a/apps/backend/internal/task/repository/sqlite/postgres_schema_test.go +++ b/apps/backend/internal/task/repository/sqlite/postgres_schema_test.go @@ -89,7 +89,7 @@ func TestPostgresTaskTitleCASAndStaleUpdate(t *testing.T) { `), "task-pg-title-false", "Provisional", `{"agent_title_pending":false,"keep":"value"}`, now, now); err != nil { t.Fatalf("seed false-marker task: %v", err) } - accepted, err := repo.SetTaskTitleIfPending(ctx, "task-pg-title-false", "Agent title") + accepted, err := repo.SetTaskTitleIfPending(ctx, "task-pg-title-false", "session-owner", "Agent title") if err != nil { t.Fatalf("false-marker title CAS: %v", err) } @@ -110,11 +110,15 @@ func TestPostgresTaskTitleCASAndStaleUpdate(t *testing.T) { `), "task-pg-title-race", "Provisional", `{"agent_title_pending":true}`, now, now); err != nil { t.Fatalf("seed stale-update task: %v", err) } + claimed, _, err := repo.ClaimTaskTitleSession(ctx, "task-pg-title-race", "session-owner") + if err != nil || !claimed { + t.Fatalf("claim postgres title session: claimed=%v err=%v", claimed, err) + } stale, err := repo.GetTask(ctx, "task-pg-title-race") if err != nil { t.Fatalf("load stale postgres task: %v", err) } - accepted, err = repo.SetTaskTitleIfPending(ctx, "task-pg-title-race", "Agent chosen title") + accepted, err = repo.SetTaskTitleIfPending(ctx, "task-pg-title-race", "session-owner", "Agent chosen title") if err != nil || !accepted { t.Fatalf("winning title CAS: accepted=%v err=%v", accepted, err) } @@ -133,6 +137,9 @@ func TestPostgresTaskTitleCASAndStaleUpdate(t *testing.T) { if _, pending := current.Metadata[models.MetaKeyAgentTitlePending]; pending { t.Fatalf("pending marker restored by stale update: %#v", current.Metadata) } + if _, owner := current.Metadata[models.MetaKeyAgentTitleOwnerSessionID]; owner { + t.Fatalf("owner marker restored by stale update: %#v", current.Metadata) + } } func TestPostgresImproveKandevWorkflowIndexMigration(t *testing.T) { diff --git a/apps/backend/internal/task/repository/sqlite/task.go b/apps/backend/internal/task/repository/sqlite/task.go index eac157346d..a5e2283243 100644 --- a/apps/backend/internal/task/repository/sqlite/task.go +++ b/apps/backend/internal/task/repository/sqlite/task.go @@ -521,35 +521,100 @@ func (r *Repository) RemoveTaskMetadataKey(ctx context.Context, taskID, key stri return rows > 0, err } +// ClaimTaskTitleSession atomically assigns the first eligible session as the +// owner of a pending title handoff. Repeated calls by that same session are +// idempotent; a different session observes the existing owner and returns +// false. +func (r *Repository) ClaimTaskTitleSession(ctx context.Context, taskID, sessionID string) (bool, bool, error) { + if sessionID == "" { + return false, false, nil + } + + var query string + var args []interface{} + if dialect.IsPostgres(r.db.DriverName()) { + query = ` + UPDATE tasks + SET metadata = jsonb_set( + CASE WHEN metadata IS NULL OR metadata = 'null' OR metadata = '' THEN '{}'::jsonb ELSE metadata::jsonb END, + ARRAY['agent_title_owner_session_id']::text[], ?::jsonb, true + )::text, + updated_at = ? + WHERE id = ? + AND jsonb_extract_path(CASE WHEN metadata IS NULL OR metadata = 'null' OR metadata = '' THEN '{}'::jsonb ELSE metadata::jsonb END, 'agent_title_pending') = 'true'::jsonb + AND jsonb_extract_path(CASE WHEN metadata IS NULL OR metadata = 'null' OR metadata = '' THEN '{}'::jsonb ELSE metadata::jsonb END, 'agent_title_owner_session_id') IS NULL + ` + payload, err := json.Marshal(sessionID) + if err != nil { + return false, false, err + } + args = []interface{}{string(payload), time.Now().UTC(), taskID} + } else { + query = ` + UPDATE tasks + SET metadata = json_set( + CASE WHEN metadata IS NULL OR metadata = 'null' OR metadata = '' THEN '{}' ELSE metadata END, + '$.agent_title_owner_session_id', json(?) + ), updated_at = ? + WHERE id = ? + AND json_type(CASE WHEN metadata IS NULL OR metadata = 'null' OR metadata = '' THEN '{}' ELSE metadata END, '$.agent_title_pending') = 'true' + AND json_type(CASE WHEN metadata IS NULL OR metadata = 'null' OR metadata = '' THEN '{}' ELSE metadata END, '$.agent_title_owner_session_id') IS NULL + ` + payload, err := json.Marshal(sessionID) + if err != nil { + return false, false, err + } + args = []interface{}{string(payload), time.Now().UTC(), taskID} + } + result, err := r.db.ExecContext(ctx, r.db.Rebind(query), args...) + if err != nil { + return false, false, err + } + if rows, rowsErr := result.RowsAffected(); rowsErr == nil && rows > 0 { + return true, true, nil + } + + task, err := r.GetTask(ctx, taskID) + if err != nil { + return false, false, err + } + return models.IsAgentTitleOwner(task.Metadata, sessionID), false, nil +} + // SetTaskTitleIfPending replaces a provisional title and removes its pending -// marker in one conditional write. The compare-and-set prevents two agent -// sessions (or a late agent call racing a human rename) from both winning. -func (r *Repository) SetTaskTitleIfPending(ctx context.Context, taskID, title string) (bool, error) { +// and owner markers in one conditional write. The compare-and-set prevents two +// agent sessions (or a late agent call racing a human rename) from both winning. +func (r *Repository) SetTaskTitleIfPending(ctx context.Context, taskID, sessionID, title string) (bool, error) { + if sessionID == "" { + return false, nil + } var query string if dialect.IsPostgres(r.db.DriverName()) { query = ` UPDATE tasks SET title = ?, - metadata = (CASE WHEN metadata IS NULL OR metadata = 'null' OR metadata = '' THEN '{}'::jsonb ELSE metadata::jsonb END #- ARRAY[?]::text[])::text, + metadata = (CASE WHEN metadata IS NULL OR metadata = 'null' OR metadata = '' THEN '{}'::jsonb ELSE metadata::jsonb END #- ARRAY['agent_title_pending']::text[] #- ARRAY['agent_title_owner_session_id']::text[])::text, updated_at = ? WHERE id = ? AND jsonb_extract_path(CASE WHEN metadata IS NULL OR metadata = 'null' OR metadata = '' THEN '{}'::jsonb ELSE metadata::jsonb END, ?) = 'true'::jsonb + AND jsonb_extract_path_text(CASE WHEN metadata IS NULL OR metadata = 'null' OR metadata = '' THEN '{}'::jsonb ELSE metadata::jsonb END, 'agent_title_owner_session_id') = ? ` } else { query = ` UPDATE tasks SET title = ?, - metadata = json_remove(CASE WHEN metadata IS NULL OR metadata = 'null' OR metadata = '' THEN '{}' ELSE metadata END, ?), + metadata = json_remove(CASE WHEN metadata IS NULL OR metadata = 'null' OR metadata = '' THEN '{}' ELSE metadata END, '$.agent_title_pending', '$.agent_title_owner_session_id'), updated_at = ? WHERE id = ? AND json_type(CASE WHEN metadata IS NULL OR metadata = 'null' OR metadata = '' THEN '{}' ELSE metadata END, ?) = 'true' + AND json_extract(CASE WHEN metadata IS NULL OR metadata = 'null' OR metadata = '' THEN '{}' ELSE metadata END, '$.agent_title_owner_session_id') = ? ` } path := jsonPath(models.MetaKeyAgentTitlePending) if dialect.IsPostgres(r.db.DriverName()) { path = models.MetaKeyAgentTitlePending } - result, err := r.db.ExecContext(ctx, r.db.Rebind(query), title, path, time.Now().UTC(), taskID, path) + result, err := r.db.ExecContext(ctx, r.db.Rebind(query), title, time.Now().UTC(), taskID, path, sessionID) if err != nil { return false, err } @@ -589,9 +654,9 @@ func agentTitlePendingPredicate(driver string) string { func pendingTaskMetadataMergeExpression(driver string) string { if dialect.IsPostgres(driver) { - return "(CASE WHEN metadata IS NULL OR metadata = 'null' OR metadata = '' THEN '{}'::jsonb ELSE metadata::jsonb END || (?::jsonb - 'agent_title_pending'))::text" + return "(CASE WHEN metadata IS NULL OR metadata = 'null' OR metadata = '' THEN '{}'::jsonb ELSE metadata::jsonb END || (?::jsonb - 'agent_title_pending' - 'agent_title_owner_session_id'))::text" } - return "json_patch(CASE WHEN metadata IS NULL OR metadata = 'null' OR metadata = '' THEN '{}' ELSE metadata END, json_remove(?, '$.agent_title_pending'))" + return "json_patch(CASE WHEN metadata IS NULL OR metadata = 'null' OR metadata = '' THEN '{}' ELSE metadata END, json_remove(?, '$.agent_title_pending', '$.agent_title_owner_session_id'))" } // DetachTask clears only the hierarchy fields involved in detachment. Keeping diff --git a/apps/backend/internal/task/repository/sqlite/task_title_cas_test.go b/apps/backend/internal/task/repository/sqlite/task_title_cas_test.go index cf6449852e..e2f79693d0 100644 --- a/apps/backend/internal/task/repository/sqlite/task_title_cas_test.go +++ b/apps/backend/internal/task/repository/sqlite/task_title_cas_test.go @@ -3,8 +3,45 @@ package sqlite import ( "context" "testing" + + "github.com/kandev/kandev/internal/task/models" ) +func TestClaimTaskTitleSessionIsSingleOwner(t *testing.T) { + repo := newRepoForHealTests(t) + ctx := context.Background() + insertTask(t, repo.db, "task-title-claim") + if _, err := repo.db.ExecContext(ctx, ` + UPDATE tasks SET metadata = ? WHERE id = ? + `, `{"agent_title_pending":true}`, "task-title-claim"); err != nil { + t.Fatalf("seed pending marker: %v", err) + } + + claimed, newlyClaimed, err := repo.ClaimTaskTitleSession(ctx, "task-title-claim", "session-first") + if err != nil || !claimed || !newlyClaimed { + t.Fatalf("first claim: claimed=%v newly=%v err=%v", claimed, newlyClaimed, err) + } + claimed, newlyClaimed, err = repo.ClaimTaskTitleSession(ctx, "task-title-claim", "session-first") + if err != nil || !claimed || newlyClaimed { + t.Fatalf("same-session claim should be idempotent: claimed=%v newly=%v err=%v", claimed, newlyClaimed, err) + } + claimed, newlyClaimed, err = repo.ClaimTaskTitleSession(ctx, "task-title-claim", "session-second") + if err != nil { + t.Fatalf("second claim: %v", err) + } + if claimed || newlyClaimed { + t.Fatal("second session stole the title claim") + } + + task, err := repo.GetTask(ctx, "task-title-claim") + if err != nil { + t.Fatalf("reload claimed task: %v", err) + } + if got := models.AgentTitleOwnerSessionID(task.Metadata); got != "session-first" { + t.Fatalf("owner = %q, want session-first", got) + } +} + func TestSetTaskTitleIfPendingRequiresTrueMarker(t *testing.T) { repo := newRepoForHealTests(t) ctx := context.Background() @@ -15,7 +52,7 @@ func TestSetTaskTitleIfPendingRequiresTrueMarker(t *testing.T) { t.Fatalf("seed false pending marker: %v", err) } - accepted, err := repo.SetTaskTitleIfPending(ctx, "task-title-false", "Agent title") + accepted, err := repo.SetTaskTitleIfPending(ctx, "task-title-false", "session-owner", "Agent title") if err != nil { t.Fatalf("SetTaskTitleIfPending: %v", err) } @@ -37,6 +74,25 @@ func TestSetTaskTitleIfPendingRequiresTrueMarker(t *testing.T) { } } +func TestSetTaskTitleIfPendingRejectsNonOwner(t *testing.T) { + repo := newRepoForHealTests(t) + ctx := context.Background() + insertTask(t, repo.db, "task-title-owner") + if _, err := repo.db.ExecContext(ctx, ` + UPDATE tasks SET title = ?, metadata = ? WHERE id = ? + `, "Provisional title", `{"agent_title_pending":true,"agent_title_owner_session_id":"session-owner"}`, "task-title-owner"); err != nil { + t.Fatalf("seed owned pending marker: %v", err) + } + + accepted, err := repo.SetTaskTitleIfPending(ctx, "task-title-owner", "session-other", "Agent title") + if err != nil { + t.Fatalf("SetTaskTitleIfPending: %v", err) + } + if accepted { + t.Fatal("accepted title update without the owning session") + } +} + func TestUpdateTaskPreservesWinningTitleAgainstStaleUpdate(t *testing.T) { repo := newRepoForHealTests(t) ctx := context.Background() @@ -47,11 +103,15 @@ func TestUpdateTaskPreservesWinningTitleAgainstStaleUpdate(t *testing.T) { t.Fatalf("seed pending title: %v", err) } + claimed, _, err := repo.ClaimTaskTitleSession(ctx, "task-title-race", "session-owner") + if err != nil || !claimed { + t.Fatalf("claim title session: claimed=%v err=%v", claimed, err) + } stale, err := repo.GetTask(ctx, "task-title-race") if err != nil { t.Fatalf("load stale task: %v", err) } - accepted, err := repo.SetTaskTitleIfPending(ctx, "task-title-race", "Agent chosen title") + accepted, err := repo.SetTaskTitleIfPending(ctx, "task-title-race", "session-owner", "Agent chosen title") if err != nil { t.Fatalf("SetTaskTitleIfPending: %v", err) } @@ -77,6 +137,9 @@ func TestUpdateTaskPreservesWinningTitleAgainstStaleUpdate(t *testing.T) { if _, pending := current.Metadata["agent_title_pending"]; pending { t.Fatalf("pending marker restored by stale update: %#v", current.Metadata) } + if _, owner := current.Metadata[models.MetaKeyAgentTitleOwnerSessionID]; owner { + t.Fatalf("owner marker restored by stale update: %#v", current.Metadata) + } if current.Description != "updated concurrently" { t.Fatalf("description = %q, want stale update to retain its unrelated change", current.Description) } diff --git a/apps/backend/internal/task/service/service_tasks.go b/apps/backend/internal/task/service/service_tasks.go index c4d43b99fa..1c705e8c37 100644 --- a/apps/backend/internal/task/service/service_tasks.go +++ b/apps/backend/internal/task/service/service_tasks.go @@ -39,6 +39,11 @@ const ( const defaultKandevTaskWorktreePathSegment = "/.kandev/tasks/" +const ( + titleNotPendingReason = "title_not_pending" + titleNotOwnerReason = "title_not_owner" +) + // ErrSubtaskDepthExceeded is returned when a caller tries to create a // subtask of a kanban subtask (nesting depth > 1). Office task trees are // intentionally exempt. @@ -64,7 +69,7 @@ var ErrAutoTitlePromptRequired = errors.New("description is required when auto_t var ErrAutoTitleUnsupportedForOffice = errors.New("auto_title is not supported for Office tasks") type pendingTaskTitleSetter interface { - SetTaskTitleIfPending(ctx context.Context, taskID, title string) (bool, error) + SetTaskTitleIfPending(ctx context.Context, taskID, sessionID, title string) (bool, error) } type taskStopTarget struct { @@ -1214,6 +1219,7 @@ func (s *Service) UpdateTask(ctx context.Context, id string, req *UpdateTaskRequ task.Title = *req.Title if task.Metadata != nil { delete(task.Metadata, models.MetaKeyAgentTitlePending) + delete(task.Metadata, models.MetaKeyAgentTitleOwnerSessionID) } } parentCleared := false @@ -1281,54 +1287,62 @@ func (s *Service) reloadTaskAfterMutation(ctx context.Context, id string, fallba } // SetPendingAgentTitle replaces a prompt-first provisional title exactly once. -// A missing pending marker is an idempotent no-op so a human rename or an -// earlier agent call always wins a late request. -func (s *Service) SetPendingAgentTitle(ctx context.Context, id, title string) (*models.Task, bool, error) { +// Only the atomically claimed owner session may resolve it. A missing pending +// marker is an idempotent no-op so a human rename or an earlier agent call +// always wins a late request. +func (s *Service) SetPendingAgentTitle(ctx context.Context, id, sessionID, title string) (*models.Task, bool, string, error) { if err := s.authorizeTaskID(ctx, id); err != nil { - return nil, false, err + return nil, false, "", err } task, err := s.tasks.GetTask(ctx, id) if err != nil { - return nil, false, err + return nil, false, "", err } if !models.IsAgentTitlePending(task.Metadata) { - return task, false, nil + return task, false, titleNotPendingReason, nil + } + if !models.IsAgentTitleOwner(task.Metadata, sessionID) { + return task, false, titleNotOwnerReason, nil } title = strings.TrimSpace(title) if title == "" { - return nil, false, errors.New("title is required") + return nil, false, "", errors.New("title is required") } if err := validateTaskTitle(title); err != nil { - return nil, false, err + return nil, false, "", err } if setter, ok := s.tasks.(pendingTaskTitleSetter); ok { - accepted, err := setter.SetTaskTitleIfPending(ctx, id, title) + accepted, err := setter.SetTaskTitleIfPending(ctx, id, sessionID, title) if err != nil { s.logger.Error("failed to set pending agent title", zap.String("task_id", id), zap.Error(err)) - return nil, false, err + return nil, false, "", err } if !accepted { current, getErr := s.tasks.GetTask(ctx, id) if getErr != nil { - return nil, false, getErr + return nil, false, "", getErr } - return current, false, nil + if !models.IsAgentTitlePending(current.Metadata) { + return current, false, titleNotPendingReason, nil + } + return current, false, titleNotOwnerReason, nil } // Reload the winning row so the response/event includes any ordinary // task update that raced the conditional title write. task = s.reloadTaskAfterMutation(ctx, id, task, "set pending agent title") s.publishTaskEvent(ctx, events.TaskUpdated, task, nil) - return task, true, nil + return task, true, "", nil } task.Title = title delete(task.Metadata, models.MetaKeyAgentTitlePending) + delete(task.Metadata, models.MetaKeyAgentTitleOwnerSessionID) task.UpdatedAt = time.Now().UTC() if err := s.tasks.UpdateTask(ctx, task); err != nil { s.logger.Error("failed to set pending agent title", zap.String("task_id", id), zap.Error(err)) - return nil, false, err + return nil, false, "", err } s.publishTaskEvent(ctx, events.TaskUpdated, task, nil) - return task, true, nil + return task, true, "", nil } // parentChainWalkLimit bounds the ancestor walk in resolveParentID so a diff --git a/apps/backend/internal/task/service/service_tasks_test.go b/apps/backend/internal/task/service/service_tasks_test.go index 2bcf1977b5..48a195a7ac 100644 --- a/apps/backend/internal/task/service/service_tasks_test.go +++ b/apps/backend/internal/task/service/service_tasks_test.go @@ -131,26 +131,26 @@ func TestSetPendingAgentTitleIsOneShotAndHumanRenameWins(t *testing.T) { WorkflowID: "wf-agent-title", Title: "Temporary prompt title", Description: "Do the work", - Metadata: map[string]interface{}{models.MetaKeyAgentTitlePending: true}, + Metadata: map[string]interface{}{models.MetaKeyAgentTitlePending: true, models.MetaKeyAgentTitleOwnerSessionID: "session-owner"}, }) if err != nil { t.Fatalf("create pending task: %v", err) } eventBus.ClearEvents() - updated, accepted, err := svc.SetPendingAgentTitle(ctx, task.ID, "Ship login fix") + updated, accepted, reason, err := svc.SetPendingAgentTitle(ctx, task.ID, "session-owner", "Ship login fix") if err != nil || !accepted { - t.Fatalf("set pending title = (%v, %v), want accepted", updated, err) + t.Fatalf("set pending title = (%v, %v, %q), want accepted", updated, accepted, reason) } - if updated.Title != "Ship login fix" || models.IsAgentTitlePending(updated.Metadata) { + if updated.Title != "Ship login fix" || models.IsAgentTitlePending(updated.Metadata) || models.AgentTitleOwnerSessionID(updated.Metadata) != "" { t.Fatalf("updated task = %#v, want resolved title and marker removed", updated) } if len(eventBus.GetPublishedEvents()) != 1 || eventBus.GetPublishedEvents()[0].Type != "task.updated" { t.Fatalf("events = %#v, want one task.updated event", eventBus.GetPublishedEvents()) } - _, accepted, err = svc.SetPendingAgentTitle(ctx, task.ID, "Late overwrite") - if err != nil || accepted { - t.Fatalf("second set = (accepted=%v, err=%v), want idempotent rejection", accepted, err) + _, accepted, reason, err = svc.SetPendingAgentTitle(ctx, task.ID, "session-owner", "Late overwrite") + if err != nil || accepted || reason != "title_not_pending" { + t.Fatalf("second set = (accepted=%v, reason=%q, err=%v), want idempotent rejection", accepted, reason, err) } pendingTask, err := svc.CreateTask(ctx, &CreateTaskRequest{ @@ -158,7 +158,7 @@ func TestSetPendingAgentTitleIsOneShotAndHumanRenameWins(t *testing.T) { WorkflowID: "wf-agent-title", Title: "Temporary again", Description: "Do more work", - Metadata: map[string]interface{}{models.MetaKeyAgentTitlePending: true}, + Metadata: map[string]interface{}{models.MetaKeyAgentTitlePending: true, models.MetaKeyAgentTitleOwnerSessionID: "session-owner"}, }) if err != nil { t.Fatalf("create second pending task: %v", err) @@ -167,9 +167,9 @@ func TestSetPendingAgentTitleIsOneShotAndHumanRenameWins(t *testing.T) { if _, err := svc.UpdateTask(ctx, pendingTask.ID, &UpdateTaskRequest{Title: &humanTitle}); err != nil { t.Fatalf("human rename: %v", err) } - updated, accepted, err = svc.SetPendingAgentTitle(ctx, pendingTask.ID, "Agent overwrite") - if err != nil || accepted || updated.Title != humanTitle { - t.Fatalf("late agent rename = (%v, %v, %v), want human title preserved", updated.Title, accepted, err) + updated, accepted, reason, err = svc.SetPendingAgentTitle(ctx, pendingTask.ID, "session-owner", "Agent overwrite") + if err != nil || accepted || reason != "title_not_pending" || updated.Title != humanTitle { + t.Fatalf("late agent rename = (%v, %v, %q, %v), want human title preserved", updated.Title, accepted, reason, err) } } diff --git a/apps/backend/internal/user/store/sqlite.go b/apps/backend/internal/user/store/sqlite.go index 2878ef3a1a..c4348ec8a9 100644 --- a/apps/backend/internal/user/store/sqlite.go +++ b/apps/backend/internal/user/store/sqlite.go @@ -581,7 +581,7 @@ func defaultUserSettings(userID string) *models.UserSettings { ReviewAutoMarkOnScroll: true, ConfirmTaskArchive: true, UnreadDivider: false, - AgentGeneratedTaskTitles: false, + AgentGeneratedTaskTitles: true, MCPTaskAgentProfileDefault: models.MCPTaskAgentProfileDefaultCurrentTask, ShowAnchoredPromptBar: false, ShowScrollToLastPrompt: true, diff --git a/apps/backend/internal/user/store/sqlite_test.go b/apps/backend/internal/user/store/sqlite_test.go index 6e10d9d39d..20ecddf2b7 100644 --- a/apps/backend/internal/user/store/sqlite_test.go +++ b/apps/backend/internal/user/store/sqlite_test.go @@ -156,8 +156,8 @@ func TestScanUserSettingsAgentGeneratedTaskTitlesDefault(t *testing.T) { raw string want bool }{ - {name: "empty settings disable title generation", raw: `{}`, want: false}, - {name: "missing setting disables title generation", raw: `{"chat_submit_key":"enter"}`, want: false}, + {name: "empty settings enable title generation", raw: `{}`, want: true}, + {name: "missing setting enables title generation", raw: `{"chat_submit_key":"enter"}`, want: true}, {name: "explicit false disables title generation", raw: `{"agent_generated_task_titles":false}`, want: false}, {name: "explicit true enables title generation", raw: `{"agent_generated_task_titles":true}`, want: true}, } diff --git a/apps/web/e2e/fixtures/test-base.ts b/apps/web/e2e/fixtures/test-base.ts index fffd9a0075..a34a00c126 100644 --- a/apps/web/e2e/fixtures/test-base.ts +++ b/apps/web/e2e/fixtures/test-base.ts @@ -182,6 +182,7 @@ export const test = backendFixture.extend< keyboard_shortcuts: {}, enable_preview_on_click: false, confirm_task_archive: true, + agent_generated_task_titles: false, mcp_task_agent_profile_default: "current_task", sidebar_views: [], saved_layouts: [], @@ -288,6 +289,7 @@ test.beforeEach(async ({ apiClient, seedData }) => { keyboard_shortcuts: {}, enable_preview_on_click: false, confirm_task_archive: true, + agent_generated_task_titles: false, mcp_task_agent_profile_default: "current_task", sidebar_views: [], saved_layouts: [], diff --git a/apps/web/lib/ssr/user-settings.test.ts b/apps/web/lib/ssr/user-settings.test.ts index 00b14f2ffd..175376e5ad 100644 --- a/apps/web/lib/ssr/user-settings.test.ts +++ b/apps/web/lib/ssr/user-settings.test.ts @@ -36,6 +36,18 @@ describe("startup page user settings", () => { }); }); +describe("agent-generated task title defaults", () => { + it("defaults missing preference to enabled", () => { + expect(buildCoreFields({}).agentGeneratedTaskTitles).toBe(true); + }); + + it("preserves an explicit disabled preference", () => { + expect(buildCoreFields({ agent_generated_task_titles: false }).agentGeneratedTaskTitles).toBe( + false, + ); + }); +}); + describe("buildCoreFields", () => { it("normalizes the simplified metrics preference and defaults old rows to detailed", () => { expect(parseSystemMetricsDisplay({ show_in_topbar: true, simplified: true } as never)).toEqual({ @@ -325,7 +337,7 @@ describe("mapUserSettingsResponse unread divider", () => { }); describe("mapUserSettingsResponse agent-generated task titles", () => { - it("defaults the preference off and preserves explicit enablement", () => { + it("defaults the preference on and preserves explicit enablement", () => { const fallback = mapUserSettingsResponse(null) as { agentGeneratedTaskTitles?: boolean }; const enabled = mapUserSettingsResponse({ settings: { @@ -337,7 +349,7 @@ describe("mapUserSettingsResponse agent-generated task titles", () => { } as unknown as NonNullable[0]>["settings"], }) as { agentGeneratedTaskTitles?: boolean }; - expect(fallback.agentGeneratedTaskTitles).toBe(false); + expect(fallback.agentGeneratedTaskTitles).toBe(true); expect(enabled.agentGeneratedTaskTitles).toBe(true); }); }); diff --git a/apps/web/lib/ssr/user-settings.ts b/apps/web/lib/ssr/user-settings.ts index dcecab01a1..d9eb75db5b 100644 --- a/apps/web/lib/ssr/user-settings.ts +++ b/apps/web/lib/ssr/user-settings.ts @@ -37,7 +37,7 @@ export function createDefaultUserSettings(): UserSettingsState { reviewAutoMarkOnScroll: true, confirmTaskArchive: true, unreadDivider: false, - agentGeneratedTaskTitles: false, + agentGeneratedTaskTitles: true, mcpTaskAgentProfileDefault: "current_task", showAnchoredPromptBar: false, showScrollToLastPrompt: true, @@ -230,7 +230,7 @@ function buildBehaviorFields(s: UserSettingsData, current: UserSettingsState) { reviewAutoMarkOnScroll: s.review_auto_mark_on_scroll ?? current.reviewAutoMarkOnScroll, confirmTaskArchive: s.confirm_task_archive ?? current.confirmTaskArchive, unreadDivider: s.unread_divider ?? current.unreadDivider, - agentGeneratedTaskTitles: s.agent_generated_task_titles ?? false, + agentGeneratedTaskTitles: s.agent_generated_task_titles ?? current.agentGeneratedTaskTitles, mcpTaskAgentProfileDefault: mapDefined( s.mcp_task_agent_profile_default, current.mcpTaskAgentProfileDefault, diff --git a/apps/web/lib/ws/handlers/users.test.ts b/apps/web/lib/ws/handlers/users.test.ts index 75737a7a58..a09216749b 100644 --- a/apps/web/lib/ws/handlers/users.test.ts +++ b/apps/web/lib/ws/handlers/users.test.ts @@ -134,7 +134,7 @@ describe("user settings websocket handler", () => { expect(store.getState().userSettings.agentGeneratedTaskTitles).toBe(true); registerUsersHandlers(store)["user.settings.updated"]?.(userSettingsMessage({})); - expect(store.getState().userSettings.agentGeneratedTaskTitles).toBe(false); + expect(store.getState().userSettings.agentGeneratedTaskTitles).toBe(true); }); it("syncs transcript navigation preferences and uses the documented defaults", () => { diff --git a/docs/decisions/2026-07-31-agent-generated-task-titles.md b/docs/decisions/2026-07-31-agent-generated-task-titles.md index f24da6db2a..8e9172f493 100644 --- a/docs/decisions/2026-07-31-agent-generated-task-titles.md +++ b/docs/decisions/2026-07-31-agent-generated-task-titles.md @@ -4,6 +4,11 @@ **Date:** 2026-07-31 **Area:** backend, frontend, protocol +**Refined by:** +[ADR-2026-08-02-single-owner-agent-task-titles](2026-08-02-single-owner-agent-task-titles.md) +for durable first-session ownership and the default-on preference rollout. Where session eligibility or +preference defaults differ, the later decision governs. + ## Context Users can currently create Kanban tasks and subtasks only after choosing a title. Kandev needs an @@ -23,8 +28,8 @@ preference at session launch time. The executor resolves a title-pending task-mode MCP variant only when the task has `agent_title_pending=true`; regular task mode does not register `set_task_title_kandev`. The tool is bound to the MCP server's current task and accepts only the replacement `title`; callers cannot select -another task. Its tool and argument descriptions teach the agent to target three words and use no more -than six when practical. This is generation guidance rather than a new persistence constraint. +another task. Its tool and argument descriptions teach the agent to target about six words in sentence +case. This is generation guidance rather than a new persistence constraint. First-turn prompt composition includes both the tool inventory entry and the instruction to call it before other work only while the marker is true, even if the provisional title appears usable. A successful call replaces the title, removes the marker, and publishes the normal `task.updated` event. diff --git a/docs/decisions/2026-08-02-single-owner-agent-task-titles.md b/docs/decisions/2026-08-02-single-owner-agent-task-titles.md new file mode 100644 index 0000000000..523adf0324 --- /dev/null +++ b/docs/decisions/2026-08-02-single-owner-agent-task-titles.md @@ -0,0 +1,74 @@ +# ADR-2026-08-02-single-owner-agent-task-titles: Assign Agent Task Titles to One Session + +**Status:** accepted +**Date:** 2026-08-02 +**Area:** backend, frontend, protocol, workflow + +## Context + +ADR-2026-07-31 introduced a pending marker that lets the first agent replace a prompt-derived +provisional task title. Session prompt and MCP-mode selection currently read only that task-level +marker. If several sessions launch before one of them successfully sets the title, each can receive the +instruction and tool. That makes pending state a race window rather than a durable ownership boundary. + +The feature was also introduced as opt-in. Agent-generated titles are now the desired default, but an +existing user who explicitly disabled the preference must not be opted back in. + +## Decision + +A prompt-first task begins with `tasks.metadata.agent_title_pending=true` and no owner. When an +eligible task-mode session begins its initial turn, Kandev atomically claims the task by writing +`tasks.metadata.agent_title_owner_session_id=`. Session preparation alone does not claim. +Config, Office, and External sessions are ineligible; structured and passthrough task-mode sessions are +eligible. + +The claim compare-and-set requires pending state and an absent owner, is idempotent for the same +session, and rejects every different session. Kandev performs it before recording or composing the +initial prompt, configuring title-capable MCP mode, or starting the agent process. Workspace/agentctl +preparation alone uses ordinary task mode and does not claim. A persistence error fails the launch +closed. Once a session owns the title, ownership is not reassigned when its process fails, it ignores +the instruction, or its title call fails. A retry or resume of that same session can retain the +capability while the title is pending. + +Prompt composition and MCP-mode resolution require both pending state and an owner ID equal to the +launching session. The existing internal `task-title-pending` MCP mode value remains stable, but only +the owner resolves to it. The MCP title mutation also compares the server-injected session ID with the +persisted owner; catalog gating is not the authorization boundary. + +A successful owner title update atomically changes the title and removes both metadata keys. An +ordinary human title update also removes both keys. Metadata merge logic excludes both internal keys +from stale pending snapshots so an unrelated task update cannot restore resolved ownership. Newly +persisted ownership is published through the normal task-update event path. + +The portable `agent_generated_task_titles` user preference defaults to `true` for new settings and for +stored JSON that omits the field. An explicitly stored `false` remains false. Backend decoding and +frontend boot/WS fallbacks use the same missing-versus-explicit distinction. + +## Consequences + +- Concurrent workflow agents expose title-generation instructions and schema to exactly one session. +- A failed owner does not make later sessions spend context or unexpectedly rename the task; the + provisional title remains the fallback. +- Ownership survives backend, executor, and browser restarts without a new table or schema migration. +- Pending tasks created before the owner key exists remain compatible: their next eligible initial-turn + launch claims ownership. +- Claim failure aborts an initial launch instead of allowing prompt/catalog state to disagree. +- New and legacy users get the prompt-first creation flow unless they explicitly opted out. +- Test fixtures that intentionally exercise manual-title creation must save `false` explicitly instead + of relying on an omitted preference. + +## Alternatives Considered + +1. **Continue gating only on `agent_title_pending`.** Rejected because concurrent or failed launches + can give multiple sessions the same one-shot responsibility. +2. **Remove pending state as soon as a session launches.** Rejected because it loses the distinction + between an unresolved provisional title and a completed title, and weakens the human-versus-agent + compare-and-set. +3. **Reassign ownership after launch failure.** Rejected because later agents would receive surprise + instructions and schema; the chosen contract is one session, with the provisional title as fallback. +4. **Mark the owner only in session metadata.** Rejected because selecting one winner across concurrent + sessions would require a task-wide query/constraint and would make task-title mutation depend on a + second row's lifecycle. +5. **Use a new task column or claim table.** Rejected because the ownership state is small, temporary, + and naturally part of the existing pending-title metadata lifecycle. +6. **Flip every stored preference to true.** Rejected because it would overwrite explicit user opt-outs. diff --git a/docs/decisions/INDEX.md b/docs/decisions/INDEX.md index 84b67066cb..80581ce9b4 100644 --- a/docs/decisions/INDEX.md +++ b/docs/decisions/INDEX.md @@ -103,3 +103,4 @@ Read individual ADRs for full context. Create new ones via `/record decision` or | 2026-08-01-release-toggle-gating-contract | [Release Toggles Are Install-Wide Fail-Closed Gates](2026-08-01-release-toggle-gating-contract.md) | proposed | backend, frontend, workflow | 2026-08-01 | | 2026-08-01-share-artifact-locale | [Shared-Task Artifacts Render in the Creator's Locale](2026-08-01-share-artifact-locale.md) | accepted | backend | 2026-08-01 | | 2026-08-02-new-workspace-github-access-defaults | [Bootstrap New Workspaces From Host GitHub Access](2026-08-02-new-workspace-github-access-defaults.md) | accepted | backend, frontend, security | 2026-08-02 | +| 2026-08-02-single-owner-agent-task-titles | [Assign Agent Task Titles to One Session](2026-08-02-single-owner-agent-task-titles.md) | accepted | backend, frontend, protocol, workflow | 2026-08-02 | diff --git a/docs/plans/agent-generated-task-titles/plan.md b/docs/plans/agent-generated-task-titles/plan.md index 3c2ed5a4b7..7e3c2bfa3a 100644 --- a/docs/plans/agent-generated-task-titles/plan.md +++ b/docs/plans/agent-generated-task-titles/plan.md @@ -1,18 +1,21 @@ --- spec: docs/specs/tasks/agent-generated-titles.md created: 2026-07-31 -status: implemented +updated: 2026-08-02 +status: done --- # Implementation Plan: Agent-Generated Task Titles ## Overview -Add the portable preference and backend-owned provisional-title lifecycle first, then expose the -task-bound MCP mutation and conditional first-turn instruction. After those contracts exist, wire the -shared desktop/mobile creation dialogs to opt in and finish with end-to-end coverage and public docs. -The persisted pending marker is the integration seam: frontend creation sets it through `auto_title`, -prompt composition reads it, and either an agent or human title update clears it. +Waves 1–4 delivered the portable preference, backend-owned provisional-title lifecycle, task-bound MCP +mutation, conditional first-turn instruction, shared desktop/mobile dialogs, E2E coverage, and public +docs. The 2026-08-02 continuation makes that shipped flow default-on and replaces pending-only launch +gating with durable session ownership. The integration seam becomes the pair of persisted task metadata +keys: creation sets pending intent, the first eligible initial-turn launch atomically records its owner, +only that session receives title guidance and schema, and either the owner or a human title update clears +both keys. --- @@ -22,7 +25,8 @@ prompt composition reads it, and either an agent or human title update clears it - Extend `apps/backend/internal/user/models/models.go`, `dto/dto.go`, and `service/service.go` with `AgentGeneratedTaskTitles bool` / - `agent_generated_task_titles`, using pointer PATCH semantics and a missing-field default of `false`. + `agent_generated_task_titles`, using pointer PATCH semantics and a missing-field default of `true`. + Preserve an explicitly stored `false`. - Extend `apps/backend/internal/user/store/sqlite.go` JSON encode/decode and defaults. This remains in the existing `users.settings` JSON blob, so no schema migration is needed. - Project the field through `apps/backend/internal/backendapp/boot_state_routes.go` and the existing @@ -34,7 +38,8 @@ prompt composition reads it, and either an agent or human title update clears it - Add `AutoTitle bool` to `service.CreateTaskRequest` in `apps/backend/internal/task/service/service_requests.go` and define - `models.MetaKeyAgentTitlePending = "agent_title_pending"` in + `models.MetaKeyAgentTitlePending = "agent_title_pending"` and + `models.MetaKeyAgentTitleOwnerSessionID = "agent_title_owner_session_id"` in `apps/backend/internal/task/models/models.go`. - In `apps/backend/internal/task/service/service_tasks.go`, add a rune-safe helper that trims the prompt, selects the first six entries from `strings.Fields`, and joins them with one space. Shorter @@ -45,10 +50,11 @@ prompt composition reads it, and either an agent or human title update clears it - Add `auto_title` to `httpCreateTaskRequest` in `apps/backend/internal/task/handlers/task_http_handlers.go`. Preserve the existing required-title path when it is false; pass the opt-in to the service when true. -- Make an ordinary `Service.UpdateTask` call with a non-nil title remove - `agent_title_pending` before its single task-row update. Add a task-service method for the MCP path - that validates the 500-character title limit, accepts only a pending task, updates title and metadata, - and publishes the standard `task.updated` event. +- Make an ordinary `Service.UpdateTask` call with a non-nil title remove both title-lifecycle keys + before its single task-row update. Add a task-service method for the MCP path that validates the + 500-character title limit, accepts only a pending task whose persisted owner matches the + server-injected session ID, updates title and metadata atomically, and publishes the standard + `task.updated` event. - Cover whitespace normalization, six-word selection, shorter prompts, the existing absolute title limit, empty prompt rejection, top-level and subtask creation, restart-durable metadata, ordinary rename precedence, repeated agent calls, and update-event publication in `service_tasks_test.go` and @@ -63,34 +69,55 @@ prompt composition reads it, and either an agent or human title update clears it regular task tools plus `set_task_title_kandev`; regular `ModeTask` and restricted modes omit the new tool entirely. Its public schema has one required `title`; the server injects `s.taskID` into the internal payload and never accepts a caller-selected task ID. Write both the tool description and - `title` argument description to target three words, use no more than six when practical, and clarify - that the existing title is provisional and must still be replaced. + `title` argument description to target about six words in sentence case and use a short title phrase + rather than a sentence or progress update, and clarify that the existing title is provisional and must + still be replaced. - Extend `resolveTaskSessionMCPMode` in - `apps/backend/internal/orchestrator/executor/executor_execute.go` to select the title-pending task mode - from `agent_title_pending`. Config and Office modes win. Thread the new supported mode through the - existing agentctl mode validation/configuration path without adding a second feature flag. -- Return accepted task/title data on success and an idempotent - `{accepted:false, reason:"title_not_pending"}` when the marker is absent. Preserve validation and - authorization errors from the task service. + `apps/backend/internal/orchestrator/executor/executor_execute.go` to select the existing title-pending + task mode only when `agent_title_pending` is true and `agent_title_owner_session_id` equals the + launching session. Config and Office modes win. Keep the existing internal mode string stable and + thread it through the existing agentctl mode validation/configuration path without another flag. +- Return accepted task/title data on success, an idempotent + `{accepted:false, reason:"title_not_pending"}` when the marker is absent, and + `{accepted:false, reason:"title_not_owner"}` when the bound session is not the owner. Preserve + validation and authorization errors from the task service. - Update regular/pending/restricted-mode catalog tests, MCP mode API tests, executor mode-resolution tests, handler forwarding tests, MCP integration tests, and the raw-WebSocket MCP-prefix regression inventory. Assert that ordinary task mode does not include the new tool schema. ### Conditional first-turn instruction +- Add a SQLite/PostgreSQL-safe task repository compare-and-set that persists exactly one owner while + pending. It must distinguish a new claim, an idempotent same-session claim, and a denied claim; the + orchestrator publishes `task.updated` only when it newly persists ownership. Claim failure aborts the + launch before prompt persistence/composition, title-capable MCP configuration, or agent-process + startup. Workspace/agentctl-only preparation stays in ordinary task mode and does not claim. +- Claim after a concrete session exists and its task/config/Office eligibility is known, but before the + initial turn is recorded or wrapped. Route direct starts, prepared-session starts, message-start, + workflow auto-start, structured prompts, and passthrough prompts through the same ownership helper. + Pre-wrapping paths may call it before `StartCreatedSession`; the repeated same-session call is + idempotent. +- Audit every `StartAgent: true`, resume, and execution-profile switch path. A pending unowned session + must be claimed before its first agent process starts; an already owned session resolves title mode + only when its ID matches the owner. Workspace-only `StartAgent: false` preparation never exposes the + title mode. + - Add a conditional placeholder to `apps/backend/config/prompts/kandev-context.md` that emits both the `set_task_title_kandev` inventory entry and first-call instruction only for title-pending task mode. - Extend `sysprompt.KandevContextOptions` in `apps/backend/internal/sysprompt/sysprompt.go` with the pending-title capability. The instruction says to call the tool before any other work or tool call, - even though a provisional title already exists, and requests a title targeting three words and no - more than six when practical. It remains absent when the marker is not true. -- Pass the marker through every first-turn composition path in + even though a provisional title already exists, and requests a short title phrase targeting about six + words in sentence case rather than a sentence or progress update. It remains absent when the marker is + not true. +- Pass the claim result—not a fresh pending-only check—through every first-turn composition path in `apps/backend/internal/orchestrator/task_operations.go`, `event_handlers_workflow.go`, and `apps/backend/internal/task/handlers/message_handlers.go`. Keep canonicalization and trusted-context handling intact. - For passthrough sessions, prepend the equivalent short instruction only while pending; do not add the full task MCP boilerplate that passthrough intentionally skips. +- Preserve both internal metadata keys against stale task snapshots while pending, and exclude both + from stale merge payloads after a human or owner resolution so neither key can be resurrected. - Extend sysprompt placeholder/canonicalization tests, orchestration launch/auto-start tests, and `apps/backend/internal/mcp/server/sysprompt_sync_test.go` so prompt references and registered mode catalogs cannot drift. Explicitly prove that ordinary tasks get neither prompt text nor tool schema. @@ -101,7 +128,7 @@ prompt composition reads it, and either an agent or human title update clears it ### User setting and hydration -- Add `agentGeneratedTaskTitles` to `UserSettingsState` and its default (`false`) in +- Add `agentGeneratedTaskTitles` to `UserSettingsState` and its default (`true`) in `apps/web/lib/state/slices/settings/types.ts` and `settings-slice.ts`. - Add `agent_generated_task_titles` to `apps/web/lib/types/http-user-settings.ts`, boot/SSR mapping in `apps/web/lib/ssr/user-settings.ts`, WS mapping in `apps/web/lib/ws/handlers/users.ts`, and any shared @@ -143,9 +170,10 @@ prompt composition reads it, and either an agent or human title update clears it ## Tests -- **What:** portable preference defaults false, PATCH preserves omitted values, and boot/WS payloads - carry it. **Files:** user store/DTO/service tests, backend boot-state tests, frontend SSR/WS/settings - tests. **How:** table-driven Go JSON tests plus Vitest mapping/component tests. +- **What:** portable preference defaults true when missing, PATCH preserves omitted and explicit-false + values, and boot/WS payloads carry it. **Files:** user store/DTO/service tests, backend boot-state + tests, frontend SSR/WS/settings tests. **How:** table-driven Go JSON tests plus Vitest + mapping/component tests. - **What:** provisional title whitespace normalization, first-six-word selection, shorter prompts, empty-prompt rejection, and pending metadata persistence. **Files:** `apps/backend/internal/task/service/service_tasks_test.go` and task HTTP handler tests. **How:** @@ -156,14 +184,25 @@ prompt composition reads it, and either an agent or human title update clears it - **What:** ordinary task sessions receive no title prompt/tool schema, while pending-task catalog and conditional first-turn instruction stay aligned across direct launch, workflow auto-start, message-start, and passthrough. **Files:** MCP server/sysprompt/executor/orchestrator/task handler - tests. **How:** regular-versus-pending catalog assertions include the three-word target and six-word - practical cap, and captured launch-prompt tests verify the same gating, guidance, and call ordering. + tests. **How:** regular-versus-pending catalog assertions include the six-word sentence-case target, + and captured launch-prompt tests verify the same gating, guidance, and call ordering. +- **What:** two concurrent initial-turn launches produce one durable owner; owner retry is idempotent; + non-owner, config, Office, External, and merely prepared sessions never claim; owner failure does not + reassign; human/agent resolution clears both keys; stale updates cannot restore them. **Files:** task + repository/service, executor, orchestrator, message handler, and MCP handler tests. **How:** real + SQLite concurrency tests, environment-gated PostgreSQL parity, and captured launch/catalog tests. - **What:** enabled/disabled UI states produce the correct title visibility, validation, and HTTP payload for tasks and subtasks. **Files:** focused `*.test.ts(x)` files beside settings and dialogs. **How:** Vitest component/hook tests with mocked API calls. ## E2E Tests +- **Scenario:** GIVEN a fresh or field-missing preference, WHEN Settings and task/subtask creation load, + THEN the toggle is enabled and prompt-first behavior is active; GIVEN an explicit opt-out, the manual + title flow remains. Keep the shared E2E fixture explicitly opted out so unrelated manual-title tests + retain their intended baseline. **Files:** existing desktop/mobile agent-title specs and + `apps/web/e2e/fixtures/test-base.ts`. + - **Scenario:** GIVEN the setting is enabled, WHEN a user creates a task from the desktop dialog, THEN the title input is absent, empty prompt is blocked, and the six-word provisional title appears. Backend service/MCP tests cover the mock-agent `set_task_title_kandev` replacement and its @@ -179,12 +218,12 @@ prompt composition reads it, and either an agent or human title update clears it ## Public documentation -- Update `docs/public/tasks-and-workflows.md` with the setting, fallback lifecycle, empty-prompt rule, - and manual-rename fallback. +- Update `docs/public/tasks-and-workflows.md` with the default-on setting, explicit opt-out, single-owner + fallback lifecycle, empty-prompt rule, and manual-rename fallback. - Update `docs/public/coordination.md` so subtask title requirements describe both setting states. - Update `docs/public/automation-and-mcp.md`, `docs/public/agent-communication.md`, and - `docs/public/coverage.json` with the task-bound `set_task_title_kandev` contract, three-word target, - six-word practical cap, and mode boundary. + `docs/public/coverage.json` with the task-bound `set_task_title_kandev` contract, six-word + sentence-case target, exactly-one-session ownership, and mode boundary. - Validate public docs with `node --test scripts/validate-public-docs.test.mjs` and `node scripts/validate-public-docs.mjs`. @@ -207,11 +246,41 @@ Wave 3: Wave 4: - [x] [Task 04: End-to-end coverage and public docs](task-04-e2e-and-docs.md) — done -## Final verification +Wave 5: +- [x] [Task 05: Single-owner title handoff](task-05-single-owner-title-handoff.md) — done + +Wave 6: +- [x] [Task 06: Default-on title preference](task-06-default-on-title-preference.md) — done + +Wave 7: +- [x] [Task 07: Regression coverage and public docs](task-07-regression-and-docs.md) — done + +## Previous shipped verification - Backend focused tests: 3,665 passing across 15 affected packages; MCP server tests: 149 passing. + +## Completion + +- [x] [Task 05: Single-owner title handoff](task-05-single-owner-title-handoff.md) — done +- [x] [Task 06: Default-on title preference](task-06-default-on-title-preference.md) — done +- [x] [Task 07: Regression coverage and public docs](task-07-regression-and-docs.md) — done + +The continuation was verified with focused backend tests, full backend FTS5 race tests, +golangci-lint, targeted frontend tests and lint, and public-document validators. PostgreSQL parity +remains environment-gated and was not run locally because no test DSN was available; the existing PR +E2E checks passed at the prior head and the shared fixture now opts those scenarios out explicitly. - Backend lint: `make -C apps/backend lint` — 0 issues. - Frontend focused Vitest suite: 98 passing across 9 files. - Frontend lint and TypeScript typecheck — passing. - Desktop and mobile Playwright scenarios — 1 passing each. - Public documentation tests and validator — 58 tests passing; 41 published pages validated. + +## Extension verification + +- [x] SQLite repository, service, orchestrator, executor, task-handler, and MCP tests prove atomic + one-owner claims and owner-bound title compare-and-set behavior. +- [x] User-store and frontend mapping tests prove missing/default `true` and explicit `false` + preservation. +- [x] Backend race suite, backend lint, frontend lint, targeted frontend tests, and public-doc + validation passed. +- [ ] PostgreSQL parity and the new desktop/mobile browser runs remain CI/environment-gated. diff --git a/docs/plans/agent-generated-task-titles/task-01-backend-title-lifecycle.md b/docs/plans/agent-generated-task-titles/task-01-backend-title-lifecycle.md index 3a1234ded3..e87859baf2 100644 --- a/docs/plans/agent-generated-task-titles/task-01-backend-title-lifecycle.md +++ b/docs/plans/agent-generated-task-titles/task-01-backend-title-lifecycle.md @@ -10,6 +10,9 @@ spec: "../../specs/tasks/agent-generated-titles.md" # Task 01: Backend preference and provisional-title lifecycle +> Continuation note: Task 06 changes the missing/new preference default to `true` while preserving +> explicit opt-outs. This completed task records the original opt-in rollout. + ## Acceptance - The backend-owned `agent_generated_task_titles` preference defaults to false, round-trips through diff --git a/docs/plans/agent-generated-task-titles/task-02-mcp-title-tool.md b/docs/plans/agent-generated-task-titles/task-02-mcp-title-tool.md index 65ebf03f58..2f26f4be44 100644 --- a/docs/plans/agent-generated-task-titles/task-02-mcp-title-tool.md +++ b/docs/plans/agent-generated-task-titles/task-02-mcp-title-tool.md @@ -10,13 +10,17 @@ spec: "../../specs/tasks/agent-generated-titles.md" # Task 02: Task MCP tool and first-turn instruction +> Continuation note: Task 05 refines pending-only gating into durable ownership by exactly one +> first-launched task-mode session. This completed task records the original pending-title rollout. + ## Acceptance - `set_task_title_kandev(title)` is discoverable only in the title-pending task-mode variant and is absent from ordinary task, Config, Office, and External modes. It targets only the server-bound current task and returns the specified success/idempotent responses. Its tool and argument - descriptions target three words, request no more than six when practical, and make clear that the - agent replaces the provisional title before beginning work. + descriptions target about six words in sentence case, use a short title phrase rather than a sentence + or progress update, and make clear that the agent replaces the provisional title before beginning + work. - Every structured first-turn path includes the before-other-work instruction only for pending tasks; the instruction repeats the same word-count guidance and says to call despite the provisional title. Later sessions and non-pending tasks omit both the instruction and tool schema, and diff --git a/docs/plans/agent-generated-task-titles/task-03-frontend-title-flow.md b/docs/plans/agent-generated-task-titles/task-03-frontend-title-flow.md index d2cc7bbfe5..72c48cb95e 100644 --- a/docs/plans/agent-generated-task-titles/task-03-frontend-title-flow.md +++ b/docs/plans/agent-generated-task-titles/task-03-frontend-title-flow.md @@ -10,6 +10,9 @@ spec: "../../specs/tasks/agent-generated-titles.md" # Task 03: Settings and task/subtask dialogs +> Continuation note: Task 06 makes this shipped prompt-first flow the default while retaining the +> manual-title flow for explicit opt-outs. + ## Acceptance - Task Actions exposes a self-documenting, manually saved setting that defaults false and stays synced diff --git a/docs/plans/agent-generated-task-titles/task-04-e2e-and-docs.md b/docs/plans/agent-generated-task-titles/task-04-e2e-and-docs.md index a51b12a06f..7e75e5c399 100644 --- a/docs/plans/agent-generated-task-titles/task-04-e2e-and-docs.md +++ b/docs/plans/agent-generated-task-titles/task-04-e2e-and-docs.md @@ -10,6 +10,9 @@ spec: "../../specs/tasks/agent-generated-titles.md" # Task 04: End-to-end coverage and public docs +> Continuation note: Task 07 updates coverage and documentation for the default-on, single-owner +> contract. This completed task records the original opt-in behavior. + ## Acceptance - Desktop E2E proves saved preference persistence, absent title inputs, empty-prompt gating, and the @@ -19,8 +22,8 @@ spec: "../../specs/tasks/agent-generated-titles.md" horizontal overflow with the prompt as the first editable field; the shared task dialog uses the same preference/payload contract covered by focused frontend tests. - Public task, subtask, and MCP documentation describes the setting, fallback/pending lifecycle, mode - boundary, pending-only tool availability/token behavior, three-word target, and six-word practical - cap; public-doc validators pass. + boundary, pending-only tool availability/token behavior, six-word sentence-case target, and + short-title guidance; public-doc validators pass. ## Verification diff --git a/docs/plans/agent-generated-task-titles/task-05-single-owner-title-handoff.md b/docs/plans/agent-generated-task-titles/task-05-single-owner-title-handoff.md new file mode 100644 index 0000000000..06abd93427 --- /dev/null +++ b/docs/plans/agent-generated-task-titles/task-05-single-owner-title-handoff.md @@ -0,0 +1,91 @@ +--- +id: "05-single-owner-title-handoff" +title: "Single-owner title handoff" +status: done +wave: 5 +depends_on: ["02-mcp-title-tool"] +plan: "plan.md" +spec: "../../specs/tasks/agent-generated-titles.md" +--- + +# Task 05: Single-owner title handoff + +## Acceptance + +- A prompt-first task starts pending and unowned. The first eligible structured or passthrough + task-mode session whose initial turn begins atomically persists its session ID as owner. Session + preparation, Config, Office, and External modes never claim. +- Concurrent launch attempts produce exactly one owner. The owner receives the title instruction and + `set_task_title_kandev` schema; every other session receives neither, even after owner launch or title + failure. A retry/resume of the same owner remains eligible while pending. +- Claim persistence happens before initial-prompt recording/composition, title-capable MCP + configuration, and agent-process startup. A claim error fails the launch closed without sending or + storing an ambiguously gated first turn or starting its agent process. Workspace/agentctl-only + preparation remains ordinary task mode and does not claim. +- The title action requires the server-injected session ID to match the persisted owner. Owner success + and human rename remove pending and owner keys atomically; non-owner calls are rejected without + mutation; stale task updates cannot restore either resolved key. +- New ownership metadata mutations use the normal task-update publication path. SQLite and PostgreSQL + implementations have equivalent compare-and-set semantics. + +## Verification + +```bash +cd apps/backend && go test ./internal/task/repository/sqlite ./internal/task/service ./internal/orchestrator/executor ./internal/orchestrator ./internal/task/handlers ./internal/mcp/handlers -run 'Test.*(AgentTitle|TaskTitle|TitleOwner)' +cd apps/backend && go test ./internal/mcp/server ./internal/sysprompt -run 'Test.*(AgentTitle|TaskTitle|Sysprompt)' +``` + +Run the repository package with `KANDEV_TEST_POSTGRES_URL` when a PostgreSQL test database is available; +CI must exercise the environment-gated parity case. + +## Files likely touched + +- `apps/backend/internal/task/models/models.go` +- `apps/backend/internal/task/repository/sqlite/task.go` +- focused SQLite/PostgreSQL repository tests +- `apps/backend/internal/task/service/service_tasks.go` +- `apps/backend/internal/mcp/handlers/handlers.go` +- `apps/backend/internal/orchestrator/service.go` +- `apps/backend/internal/orchestrator/task_operations.go` +- `apps/backend/internal/orchestrator/executor/executor_resume.go` +- `apps/backend/internal/orchestrator/executor/executor_interaction.go` +- `apps/backend/internal/orchestrator/event_handlers_workflow.go` +- `apps/backend/internal/orchestrator/executor/executor_execute.go` +- `apps/backend/internal/task/handlers/message_handlers.go` +- focused service, handler, executor, and orchestrator tests + +## Dependencies + +The shipped pending-title lifecycle and MCP mode/tool from Tasks 01–02. + +## Parallelism + +Sequential in the primary conversation. The repository claim contract must exist before launch and MCP +paths can consume it. + +## Inputs + +- Spec sections: **Data model**, **Task MCP**, **Permissions**, **Failure modes**, and concurrency + scenarios. +- ADR-2026-08-02 single-owner decision. +- Existing pending-title compare-and-set and first-turn canonicalization paths. + +## Risks + +- Initial prompts are pre-wrapped and persisted in more than one entry path; missing one can disagree + with executor MCP mode even when the repository claim is correct. +- Stale pending snapshots can resurrect the owner after resolution unless both internal keys are + excluded from merge payloads. +- Rows-affected behavior and JSON extraction/set/remove expressions must stay equivalent across SQLite + and PostgreSQL. + +## Result + +Implemented the atomic SQLite/PostgreSQL owner claim, owner-bound MCP mutation, stale-snapshot +protection, and shared claim wiring across direct, prepared, message-start, workflow, structured, +passthrough, resume, and executor paths. Config, Office, External, and workspace-only preparation do +not claim ownership; an owner retry is idempotent and a failed owner is not reassigned. + +Verification passed with focused package tests, `go test -race` on the affected packages, and the full +`go test -tags fts5 -race ./...` backend suite. `golangci-lint run ./...` also passed. PostgreSQL parity +is environment-gated and was not run locally because no test DSN was available. diff --git a/docs/plans/agent-generated-task-titles/task-06-default-on-title-preference.md b/docs/plans/agent-generated-task-titles/task-06-default-on-title-preference.md new file mode 100644 index 0000000000..0bb4682685 --- /dev/null +++ b/docs/plans/agent-generated-task-titles/task-06-default-on-title-preference.md @@ -0,0 +1,73 @@ +--- +id: "06-default-on-title-preference" +title: "Default-on title preference" +status: done +wave: 6 +depends_on: ["05-single-owner-title-handoff"] +plan: "plan.md" +spec: "../../specs/tasks/agent-generated-titles.md" +--- + +# Task 06: Default-on title preference + +## Acceptance + +- New backend user settings and stored JSON that omits `agent_generated_task_titles` resolve to `true`. + An explicit stored or patched `false` remains false, and an omitted PATCH never changes the current + value. +- Frontend default state, boot/SSR mapping, and partial WebSocket updates use the same default-on and + preserve-current semantics; an older response that omits the field does not disable the feature. +- Settings UI remains self-explanatory and mobile-equivalent. No new layout is introduced; the shipped + task/subtask prompt-first surfaces simply become the default. +- Shared browser-test setup explicitly saves `false` where unrelated tests require manual title inputs, + while dedicated title tests cover enabled-by-default and explicit opt-out behavior. + +## Verification + +```bash +cd apps/backend && go test ./internal/user/store ./internal/user/service ./internal/user/dto ./internal/backendapp -run 'Test.*(AgentGeneratedTaskTitles|UserSettings)' +cd apps/web && pnpm exec vitest run lib/ssr/user-settings.test.ts lib/ws/handlers/users.test.ts components/settings/agent-generated-task-title-settings.test.tsx components/task-create-dialog-setup.test.ts +``` + +## Files likely touched + +- `apps/backend/internal/user/store/sqlite.go` +- `apps/backend/internal/user/store/sqlite_test.go` +- related user service/DTO/boot-state tests if their default assertions need expansion +- `apps/web/lib/ssr/user-settings.ts` +- `apps/web/lib/ssr/user-settings.test.ts` +- `apps/web/lib/ws/handlers/users.test.ts` +- focused settings/default-state tests +- `apps/web/e2e/fixtures/test-base.ts` + +## Dependencies + +Task 05 establishes the exact single-session behavior that becomes the default experience. + +## Parallelism + +Sequential in the primary conversation. Keeping this after Task 05 prevents enabling incomplete +multi-session behavior by default in an intermediate commit. + +## Inputs + +- Spec **User settings**, default/opt-out scenarios, and desktop/mobile parity requirements. +- ADR-2026-08-02 missing-versus-explicit preference decision. +- Existing pointer-backed JSON decoder and shared frontend settings mapper. + +## Risks + +- A hardcoded frontend fallback can overwrite explicit false during partial WS updates; use current + state for omitted event fields and the new default only when creating initial state. +- Many E2E tests intentionally fill title inputs. Keep their common fixture explicitly opted out rather + than rewriting unrelated scenarios around prompt-first creation. + +## Result + +Missing backend settings, initial frontend state, boot/SSR hydration, and partial WebSocket updates +now default to enabled while preserving an explicit `false`. The shared browser fixture explicitly +opts out so existing manual-title scenarios remain deterministic. + +The affected Vitest files passed (50 tests), backend user-store tests passed, and the web lint check +passed. The broad web typecheck command is mis-scoped in this worktree and reports pre-existing +repository alias/type errors; it did not identify a regression in the changed settings files. diff --git a/docs/plans/agent-generated-task-titles/task-07-regression-and-docs.md b/docs/plans/agent-generated-task-titles/task-07-regression-and-docs.md new file mode 100644 index 0000000000..e2ffc73a2e --- /dev/null +++ b/docs/plans/agent-generated-task-titles/task-07-regression-and-docs.md @@ -0,0 +1,81 @@ +--- +id: "07-regression-and-docs" +title: "Regression coverage and public docs" +status: done +wave: 7 +depends_on: ["05-single-owner-title-handoff", "06-default-on-title-preference"] +plan: "plan.md" +spec: "../../specs/tasks/agent-generated-titles.md" +--- + +# Task 07: Regression coverage and public docs + +## Acceptance + +- High-level backend tests cover two sessions racing on one pending task, owner launch failure followed + by a later session, same-owner retry, message-start, direct/prepared start, workflow auto-start, + structured and passthrough prompt paths, and owner-bound MCP mode/title mutation. +- Desktop Playwright proves the setting is enabled for the default experience and that explicit opt-out + restores the required title input. Mobile Playwright proves the default prompt-first task/subtask + surfaces remain contained, reachable, and free of horizontal overflow. +- Public task, subtask, coordination, and MCP docs state that agent title generation is default-on, + explicit opt-outs persist, exactly one first-launched task-mode session owns the instruction/tool, and + later sessions never inherit it after owner failure. +- Targeted tests, changed-file backend lint, frontend lint/typecheck/i18n checks, public-doc validators, + and desktop/mobile E2E pass before PR fixup resumes. + +## Verification + +```bash +cd apps/web && pnpm e2e --project=chromium tests/task/agent-generated-task-titles.spec.ts +cd apps/web && pnpm e2e --project=mobile-chrome tests/task/mobile-agent-generated-task-titles.spec.ts +cd apps/web && pnpm run typecheck && pnpm run lint && pnpm run i18n:ratchet +node --test scripts/validate-public-docs.test.mjs +node scripts/validate-public-docs.mjs +``` + +Run `golangci-lint run ./... --new-from-rev="" --timeout=5m` from `apps/backend` after the +final backend changes. + +## Files likely touched + +- focused backend orchestration/MCP integration tests from Task 05 +- `apps/web/e2e/tests/task/agent-generated-task-titles.spec.ts` +- `apps/web/e2e/tests/task/mobile-agent-generated-task-titles.spec.ts` +- `docs/public/tasks-and-workflows.md` +- `docs/public/coordination.md` +- `docs/public/automation-and-mcp.md` +- `docs/public/agent-communication.md` if its session guidance needs the ownership boundary +- `docs/public/coverage.json` if coverage metadata changes + +## Dependencies + +Tasks 05–06 completed with their focused checks passing. + +## Parallelism + +Sequential. E2E and public docs validate the assembled ownership/default contract. + +## Inputs + +- Every new conformance scenario in the approved spec. +- Plan sections: **Tests**, **E2E Tests**, and **Public documentation**. +- Mobile-parity and E2E skill requirements for real user outcomes and managed browser execution. + +## Risks + +- The mock agent does not infer natural-language title instructions; use backend captured-prompt/catalog + tests for ownership and keep browser assertions focused on user-visible default/opt-out behavior. +- Avoid restoring a missing preference as explicit false in dedicated tests when the scenario intends to + prove the new default; restore only values the test deliberately changed. + +## Result + +Backend coverage now exercises single-owner claims, owner-bound title mutation, launch-mode gating, +message/workflow/direct/prepared paths, and stale metadata handling. Public task and MCP documentation +describe the default-on preference, explicit opt-out, six-word sentence-case target, and exactly-one +eligible session boundary. The shared E2E fixture opts out for unrelated manual-title scenarios. + +`node --test scripts/validate-public-docs.test.mjs` and `node scripts/validate-public-docs.mjs` both +passed. The full backend race suite, backend lint, targeted web tests, and web lint passed; the prior PR +head's desktop/mobile E2E checks were green, while new browser runs were not available locally. diff --git a/docs/public/automation-and-mcp.md b/docs/public/automation-and-mcp.md index 13e77f9f01..b34efba70e 100644 --- a/docs/public/automation-and-mcp.md +++ b/docs/public/automation-and-mcp.md @@ -170,13 +170,16 @@ Task mode currently registers these tool groups: | Relationships and workspace sources | List related tasks, add a mixed repository/folder source batch to an idle task, use the legacy one-branch tool, and change a repository's diff base. | | Workflow signal | Signal step completion when an auto-advance step explicitly requires that signal. | -When **Settings → General → Task Actions → Agent-generated task titles** is enabled, a task-mode -session for a newly created task or subtask also exposes `set_task_title_kandev`. The first session is -prompted to call it before any other work, even though the task already has a provisional title from -the prompt. Use a short noun phrase targeting about three words (no more than six when practical). +When **Settings → General → Task Actions → Agent-generated task titles** is enabled (the default; an +explicitly saved **off** value remains off), a task-mode session for a newly created task or subtask can +expose `set_task_title_kandev`. The first eligible session to launch atomically claims the handoff and is +prompted to call it before any other work, even though the task already has a provisional title from the +prompt. Use a short title phrase targeting about six words in sentence case rather than a sentence or +progress update. The tool is omitted for ordinary tasks, tasks created while the setting was disabled, config sessions, -Office sessions, and later sessions after the pending title has been resolved. A human rename wins if -it happens first; a late agent call returns `title_not_pending` without changing the title. +Office sessions, and every later session on the task—even if the owner fails before renaming it. A human +rename wins if it happens first; a late owner call returns `title_not_pending`, while a non-owner call +returns `title_not_owner`, without changing the title. Task identity is injected for operations that require it. Workspace, parent/subtask, executor, and task-state rules still apply. diff --git a/docs/public/tasks-and-workflows.md b/docs/public/tasks-and-workflows.md index 6daa83fa55..e0f0d67217 100644 --- a/docs/public/tasks-and-workflows.md +++ b/docs/public/tasks-and-workflows.md @@ -91,12 +91,14 @@ Creating a repository is available only in an unlocked, single-repository **New ### Let the agent name new tasks Open **Settings → General → Task Actions → Agent-generated task titles** and choose **Save changes**. -The setting is disabled by default. When enabled, new task and subtask dialogs use the prompt as the -source of the title: the prompt must contain text, and Kandev immediately displays its first six -normalized words as a provisional title. The first eligible task-mode session receives the -`set_task_title_kandev` MCP tool and is instructed to call it before doing any other work. Ask for a -short noun phrase targeting about three words (no more than six when practical). If the agent never -renames the task, the provisional title remains usable and can still be edited by a person. +The setting is enabled by default; an explicitly saved **off** value remains off. When enabled, new task +and subtask dialogs use the prompt as the source of the title: the prompt must contain text, and Kandev +immediately displays its first six normalized words as a provisional title. The first eligible task-mode +session to launch atomically claims the handoff, receives the `set_task_title_kandev` MCP tool, and is +instructed to call it before doing any other work. Ask for a short title phrase targeting about six words +in sentence case rather than a sentence or progress update. Later sessions do not receive the instruction +or tool, even if the owner fails before renaming the task. If the agent never renames the task, the +provisional title remains usable and can still be edited by a person. The setting affects only new task/subtask creation. Existing task edits keep the title field, and sessions for tasks created while the setting was disabled receive neither this instruction nor the diff --git a/docs/specs/INDEX.md b/docs/specs/INDEX.md index 7aff772669..3d454ac901 100644 --- a/docs/specs/INDEX.md +++ b/docs/specs/INDEX.md @@ -76,7 +76,7 @@ Kandev's task model: documents, execution stages, labels, blocker escalation, su | [parent-child-task-stop](tasks/parent-child-task-stop.md) | shipped | | [mcp-task-agent-profile-default](tasks/mcp-task-agent-profile-default/spec.md) | shipped | | [runtime-state-publication-order](tasks/runtime-state-publication-order.md) | shipped | -| [agent-generated-titles](tasks/agent-generated-titles.md) | shipped | +| [agent-generated-titles](tasks/agent-generated-titles.md) | approved | | [task-create-executor-default](tasks/task-create-executor-default.md) | approved | | [explicit-completion-signal](workflow/explicit-completion-signal/spec.md) | shipped | diff --git a/docs/specs/tasks/agent-generated-titles.md b/docs/specs/tasks/agent-generated-titles.md index 3e541a9dc1..dae2b7ec95 100644 --- a/docs/specs/tasks/agent-generated-titles.md +++ b/docs/specs/tasks/agent-generated-titles.md @@ -1,6 +1,7 @@ --- -status: shipped +status: approved created: 2026-07-31 +updated: 2026-08-02 owner: kandev --- @@ -12,12 +13,16 @@ Writing a separate title adds friction when the task prompt already describes th prefer prompt-first creation need tasks and subtasks to appear immediately with a readable label while letting the assigned agent replace that label with a concise title. -Decision: [ADR-2026-07-31-agent-generated-task-titles](../../decisions/2026-07-31-agent-generated-task-titles.md). +Decisions: +[ADR-2026-07-31-agent-generated-task-titles](../../decisions/2026-07-31-agent-generated-task-titles.md) +and +[ADR-2026-08-02-single-owner-agent-task-titles](../../decisions/2026-08-02-single-owner-agent-task-titles.md). ## What - **Let agents name new tasks** is a per-user setting under **Settings → General → Task Actions**. It is - disabled by default, including when the saved settings record predates the field. + enabled by default. New settings records and saved settings that predate the field both resolve to + enabled; an explicitly saved `false` remains disabled. - With the setting disabled, the existing task and subtask creation flows remain unchanged: their title inputs are visible and the user-supplied title is required. Sessions for those tasks receive neither the agent-title prompt instruction nor the `set_task_title_kandev` tool schema. @@ -32,12 +37,18 @@ Decision: [ADR-2026-07-31-agent-generated-task-titles](../../decisions/2026-07-3 boundary for pathological words. - The provisional title remains usable if session preparation, agent launch, MCP discovery, or the agent's title call fails. -- The first session launched while the title is pending instructs the agent to call - `set_task_title_kandev` before any other work or tool call, even though the task already has a - provisional title. The replacement summarizes the user's request with a target of three words and - no more than six words when practical. +- The first eligible task-mode session whose initial turn begins atomically claims title ownership + before Kandev records or composes that turn's prompt, configures title-capable MCP mode, or starts + the agent process. Preparing only the workspace and agentctl without beginning the initial turn does + not claim ownership and uses ordinary task mode. Config, Office, and External sessions are + ineligible; structured and passthrough task-mode sessions are eligible. +- Only the owner session is instructed to call `set_task_title_kandev` before any other work or tool + call, even though the task already has a provisional title. The replacement summarizes the user's + request with a target of about six words in sentence case and uses a short title phrase rather than a + sentence or progress update. - A successful agent title call updates every live task surface through the normal `task.updated` - event and ends the pending state. Later sessions are not instructed to rename the task again. + event and ends the pending state. Every other session omits the instruction and tool, including when + it launches concurrently with the owner or after the owner's launch or title call fails. - A user or other ordinary task-title update made while the agent title is pending wins: it ends the pending state, and a later `set_task_title_kandev` call does not overwrite it. - Task and subtask dialogs provide the same capability on desktop and phone. Their existing responsive @@ -47,11 +58,15 @@ Decision: [ADR-2026-07-31-agent-generated-task-titles](../../decisions/2026-07-3 ## Data model `users.settings` stores `agent_generated_task_titles` as a boolean in the existing per-user JSON -settings blob. A missing field is interpreted as `false`. +settings blob. A missing field is interpreted as `true`; an explicit `false` is preserved. An opted-in task stores `agent_title_pending: true` in its existing `tasks.metadata` JSON object. The -key is removed, rather than set to `false`, when an agent or ordinary title update resolves the title. -Tasks without the key are never treated as pending. +first eligible initial-turn launch adds `agent_title_owner_session_id: ""` with an atomic +compare-and-set that succeeds only while the pending marker is true and no different owner exists. +The claim is idempotent for the same session. Both keys are removed, rather than set to false or an +empty string, when an agent or ordinary title update resolves the title. Tasks without the pending key +are never treated as pending; pending tasks created before the owner key existed are claimed normally +by their first eligible launch. No database column or schema migration is required. @@ -74,7 +89,7 @@ No database column or schema migration is required. ### Task MCP -A title-pending task-mode session exposes: +The owner session for a title-pending task exposes: ```json { @@ -88,37 +103,50 @@ A title-pending task-mode session exposes: The tool targets the current task bound to the MCP server. A successful response contains `{"accepted": true, "task_id": "...", "title": "..."}`. A task whose pending marker is already gone returns `{"accepted": false, "reason": "title_not_pending", "task_id": "..."}` without mutation. +An unavailable call from a session other than the persisted owner returns +`{"accepted": false, "reason": "title_not_owner", "task_id": "..."}` without mutation. Blank titles and titles over the existing 500-character limit are validation errors. -The tool description tells the agent to set a short title for the current task before beginning work, -to target three words (and use no more than six when practical), and to make the call even when the -existing provisional title appears usable. The `title` argument repeats that guidance. The word counts -are generation guidance, not server-side rejection thresholds; the existing 500-character limit -remains the hard validation boundary. +The tool description tells the agent to set a short title phrase for the current task before beginning +work, to target about six words in sentence case rather than a sentence or progress update, and to make +the call even when the existing provisional title appears usable. The `title` argument repeats that +guidance. The word count is generation guidance, not a server-side rejection threshold; the existing +500-character limit remains the hard validation boundary. -`set_task_title_kandev` is registered only for a task-mode MCP server launched while the current task -has `agent_title_pending: true`. Ordinary task-mode sessions, including tasks created while the setting -is disabled, do not expose its schema. It is also absent from `ModeOffice`, `ModeConfig`, and -`ModeExternal`. Registration is stable for the lifetime of that MCP server; after a successful title -call, the current session may retain the now-idempotent tool, but later sessions omit it because the -pending marker is gone. +`set_task_title_kandev` is registered only for the task-mode MCP server whose bound session matches +`agent_title_owner_session_id` while `agent_title_pending` is true. Ordinary task-mode sessions, +including tasks created while the setting is disabled and non-owner sessions on a pending task, do not +expose its schema. It is also absent from `ModeOffice`, `ModeConfig`, and `ModeExternal`. Registration +is stable for the lifetime of that MCP server; after a successful title call, the owner session may +retain the now-idempotent tool until its server ends. ## Permissions -- Only the task agent connected through its task-bound MCP server can call `set_task_title_kandev`. +- Only the task agent connected through the persisted owner session's task-bound MCP server can call + `set_task_title_kandev` successfully. - The server injects the current task ID; the agent cannot supply or override it. +- The server also injects its session ID. The title mutation compare-and-set requires that ID to match + the persisted owner, so catalog gating is not the only ownership check. - Existing task-service authorization and task-owner scoping apply before the title is read or changed. -- Human title edits keep their existing permissions and take precedence by clearing the pending marker. +- Human title edits keep their existing permissions and take precedence by clearing both lifecycle keys. ## Failure modes - Saving the setting fails through the existing settings save coordinator; the persisted value and creation behavior remain unchanged. - Auto-titled creation with an empty prompt returns a validation error and creates no task or session. -- If the agent never starts, cannot discover MCP, ignores the instruction, or receives an MCP error, - the provisional title remains and the task stays pending for the next eligible first session. -- If two sessions try to set the title, only the first accepted pending update mutates it; later calls - return `title_not_pending`. +- If the owner agent never starts, cannot discover MCP, ignores the instruction, or receives an MCP + error, the provisional title remains. Ownership is not reassigned, and later sessions receive neither + the instruction nor the tool. The same owner session retains the capability while the title is + pending if that session is retried or resumed. +- If concurrent initial-turn launches race, exactly one session persists ownership. The loser launches + without the instruction or tool. +- If ownership persistence fails, Kandev fails that launch before recording or sending its initial + prompt, configuring title-capable MCP mode, or starting the agent process. The task remains unowned + and provisionally titled so a later launch attempt can retry the claim without exposing the + capability ambiguously. +- If a non-owner somehow submits the internal title action, the title remains unchanged and the call + returns `title_not_owner`. - If a human changes the title before the agent call arrives, the human title remains and the tool call returns `title_not_pending`. - If the title update cannot be persisted, the tool returns an error, the pending marker remains, and no @@ -128,14 +156,16 @@ pending marker is gone. The setting survives browser and backend restarts as part of backend-owned portable user settings and applies across the current user's workspaces. The provisional title and pending marker survive backend, -session, and executor restarts as part of the task row. MCP catalog state is reconstructed from task -mode and the pending marker; the marker is re-read when Kandev launches a session and composes its -eligible first-turn instruction. +session, and executor restarts as part of the task row. Once claimed, the owner session ID survives in +the same metadata. MCP catalog state is reconstructed from task mode, pending state, and owner identity; +the same owner can recover its capability, while a different session cannot inherit it after restart. ## Scenarios -- **GIVEN** the setting is missing or disabled, **WHEN** a user opens either creation dialog, **THEN** - the title input is visible and required exactly as before. +- **GIVEN** the setting is missing from a new or legacy settings record, **WHEN** settings are loaded, + **THEN** agent-generated task titles are enabled. +- **GIVEN** the setting was explicitly saved as disabled, **WHEN** a user opens either creation dialog, + **THEN** the title input is visible and required exactly as before. - **GIVEN** a task was created while the setting was disabled, **WHEN** its task-mode session starts, **THEN** its system context contains no agent-title instruction and its MCP catalog does not contain `set_task_title_kandev`. @@ -148,12 +178,17 @@ eligible first-turn instruction. created, **THEN** its immediate title contains every normalized prompt word without an ellipsis. - **GIVEN** the setting is enabled and the prompt is empty, **WHEN** the user tries to create the task, **THEN** creation is blocked with prompt-required guidance and no task is created. -- **GIVEN** a title-pending task starts a structured task-mode session, **WHEN** Kandev composes its - first-turn context, **THEN** the agent is told to call `set_task_title_kandev` before any other work, - even though a provisional title exists, with a title targeting three words and no more than six when - practical, and the session's MCP catalog exposes that tool. -- **GIVEN** a title-pending task starts a passthrough session, **WHEN** Kandev sends its initial launch - prompt, **THEN** the equivalent short instruction precedes the user prompt in the native TUI. +- **GIVEN** a title-pending task has no owner, **WHEN** a structured task-mode session begins its + initial turn, **THEN** it atomically becomes the owner, is told to call `set_task_title_kandev` + before any other work, and exposes the tool with the six-word sentence-case guidance. +- **GIVEN** a title-pending task has no owner, **WHEN** a passthrough task-mode session begins its + initial turn, **THEN** it atomically becomes the owner and the equivalent short instruction precedes + the user prompt in the native TUI. +- **GIVEN** two eligible sessions begin their initial turns concurrently, **WHEN** their ownership + claims race, **THEN** exactly one receives the instruction and tool and the other receives neither. +- **GIVEN** the owner launch fails or never sets the title, **WHEN** another task-mode session begins, + **THEN** the provisional title remains and the later session receives neither the instruction nor + the tool. - **GIVEN** the agent follows the tool guidance and calls `set_task_title_kandev` with a valid few-word title, **WHEN** persistence succeeds, **THEN** the task title changes, pending state ends, and connected task surfaces update. @@ -162,16 +197,17 @@ eligible first-turn instruction. `title_not_pending`. - **GIVEN** an agent title call fails or never occurs, **WHEN** the user returns after a restart, **THEN** the provisional title remains visible and the task still has a usable name. -- **GIVEN** an agent already resolved the pending title, **WHEN** a later session starts, **THEN** its - first-turn context contains no instruction to rename the task and its MCP catalog omits - `set_task_title_kandev`. +- **GIVEN** any session other than the owner starts before or after title resolution, **WHEN** Kandev + composes its first turn and MCP catalog, **THEN** both omit `set_task_title_kandev` guidance and + schema. ## Out of scope - Changing titles supplied to `create_task_kandev`, Office tasks, automation runs, integration imports, plugin-created tasks, or external task-creation clients that do not opt into `auto_title`. - Generating a title through a separate utility-agent request before task creation. -- Retrying or enforcing the agent tool call after the first-turn instruction. +- Reassigning title ownership or retrying the title instruction with a different session after the + owner launch or title call fails. - Removing manual task rename/edit controls. ## Implementation plan