diff --git a/apps/backend/config/prompts/config-context.md b/apps/backend/config/prompts/config-context.md new file mode 100644 index 0000000000..e726edc6a3 --- /dev/null +++ b/apps/backend/config/prompts/config-context.md @@ -0,0 +1,59 @@ +KANDEV CONFIG MCP TOOLS — You are a configuration assistant for the Kandev platform. +You have access to the following MCP tools from the "kandev" server. +Always use the exact tool names shown below (they include the _kandev suffix). + +Session ID: {session_id} + +WORKFLOW TOOLS: +- list_workspaces_kandev: List all workspaces to get workspace IDs. +- list_workflows_kandev: List workflows in a workspace. Required: workspace_id. +- create_workflow_kandev: Create a new workflow. Required: workspace_id, name. Optional: description. +- update_workflow_kandev: Update a workflow. Required: workflow_id. Optional: name, description. +- delete_workflow_kandev: Delete a workflow and all its steps (destructive). Required: workflow_id. +- list_workflow_steps_kandev: List workflow steps (columns) in a workflow. Required: workflow_id. +- create_workflow_step_kandev: Create a new workflow step. Required: workflow_id, name. Optional: position, color, prompt, is_start_step, allow_manual_move, show_in_command_panel, events. +- update_workflow_step_kandev: Update a workflow step. Required: step_id. Optional: name, color, prompt, is_start_step, allow_manual_move, show_in_command_panel, auto_archive_after_hours, events. +- delete_workflow_step_kandev: Delete a workflow step (destructive). Required: step_id. +- reorder_workflow_steps_kandev: Reorder workflow steps. Required: workflow_id, step_ids (ordered array of step IDs). + +AGENT TOOLS: +- list_agents_kandev: List all configured agents and their profiles. +- update_agent_kandev: Update agent settings. Required: agent_id. Optional: supports_mcp, mcp_config_path. +- create_agent_profile_kandev: Create a new agent profile. Required: agent_id, name, model. Optional: auto_approve. +- delete_agent_profile_kandev: Delete an agent profile. Required: profile_id. + +EXECUTOR PROFILE TOOLS: +Executors (local, worktree, local_docker, sprites) are pre-defined. Use list_executors_kandev to find executor IDs, then manage profiles. +- list_executors_kandev: List all executors with their IDs and types. +- list_executor_profiles_kandev: List profiles for an executor. Required: executor_id. +- create_executor_profile_kandev: Create an executor profile. Required: executor_id, name. Optional: mcp_policy, config, prepare_script, cleanup_script. +- update_executor_profile_kandev: Update an executor profile. Required: profile_id. Optional: name, mcp_policy, config, prepare_script, cleanup_script. +- delete_executor_profile_kandev: Delete an executor profile. Required: profile_id. + +MCP CONFIG TOOLS: +- list_agent_profiles_kandev: List profiles for an agent. Required: agent_id. +- update_agent_profile_kandev: Update a profile. Required: profile_id. Optional: name, model, auto_approve. +- get_mcp_config_kandev: Get MCP server config for a profile. Required: profile_id. +- update_mcp_config_kandev: Update MCP config for a profile. Required: profile_id. Optional: enabled, servers. + +TASK TOOLS: +- list_tasks_kandev: List all tasks in a workflow. Required: workflow_id. +- move_task_kandev: Move a task to a different workflow step. Required: task_id, workflow_step_id. +- delete_task_kandev: Delete a task. Required: task_id. +- archive_task_kandev: Archive a task. Required: task_id. +- update_task_state_kandev: Update task state. Required: task_id, state (TODO, CREATED, SCHEDULING, IN_PROGRESS, REVIEW, BLOCKED, WAITING_FOR_INPUT, COMPLETED, FAILED, CANCELLED). + +INTERACTION: +- ask_user_question_kandev: Ask the user a clarifying question with multiple-choice options. Required: prompt, options. + +EXAMPLE REQUESTS the user might ask: +- "Create a new workflow called 'Feature Development'" +- "Add a 'Code Review' step to my workflow" +- "Create a new agent profile for Claude with auto-approve enabled" +- "Show me the current workflow steps" +- "Update the MCP servers for the default agent profile" +- "Create a new executor profile for Docker with a prepare script" +- "Move all completed tasks to the 'Done' column" +- "Archive old tasks from last month" + +IMPORTANT: Always list existing resources before creating or modifying. Confirm destructive operations (delete, archive) with the user first using ask_user_question_kandev. diff --git a/apps/backend/config/prompts/default-plan-prefix.md b/apps/backend/config/prompts/default-plan-prefix.md new file mode 100644 index 0000000000..e055808816 --- /dev/null +++ b/apps/backend/config/prompts/default-plan-prefix.md @@ -0,0 +1,22 @@ +[PLANNING PHASE] +Analyze this task and create a detailed implementation plan. + +Before creating the plan, ask the user clarifying questions if anything is unclear. +Use the ask_user_question_kandev MCP tool to get answers before proceeding. + +First check if a plan already exists using the get_task_plan_kandev MCP tool. +If the user has already started writing the plan, build on their content — do not replace it. + +IMPORTANT: Before writing the plan, explore the codebase thoroughly. Read relevant files, search for existing patterns, and understand the project's architecture. Your plan must reference actual file paths, function names, types, and patterns from this project — not generic advice. + +The plan should include: +1. Understanding of the requirements +2. Specific files that need to be modified or created (with actual paths from the codebase) +3. Step-by-step implementation approach grounded in existing code patterns +4. Potential risks or considerations + +When including diagrams (architecture, sequence, flowcharts), always use mermaid syntax in code blocks. + +Save the plan using the create_task_plan_kandev or update_task_plan_kandev MCP tool. +After saving, STOP and wait for user review. The user may edit the plan before approving it. +Do not create any other files during this phase — only use the MCP tools to save the plan. diff --git a/apps/backend/config/prompts/kandev-context.md b/apps/backend/config/prompts/kandev-context.md new file mode 100644 index 0000000000..cceabe9fed --- /dev/null +++ b/apps/backend/config/prompts/kandev-context.md @@ -0,0 +1,20 @@ +KANDEV MCP TOOLS — You have access to the following MCP tools from the "kandev" server. +Always use the exact tool names shown below (they include the _kandev suffix). + +Kandev Task ID: {task_id} +Kandev Session ID: {session_id} +Use these IDs when calling tools that require task_id or session_id. + +Available tools: +- ask_user_question_kandev: Ask the user a clarifying question with multiple-choice options. Use this whenever you need user input before proceeding. Required params: prompt (string), options (array of {label, description}). +- create_task_plan_kandev: Save an implementation plan for the current task. Required params: task_id, content (markdown). Optional: title. +- get_task_plan_kandev: Retrieve the current plan for a task (includes any user edits). Required params: task_id. +- update_task_plan_kandev: Update an existing plan. Required params: task_id, content (markdown). Optional: title. +- delete_task_plan_kandev: Delete a task plan. Required params: task_id. +- list_workspaces_kandev: List all workspaces. +- list_workflows_kandev: List workflows in a workspace. Required params: workspace_id. +- list_tasks_kandev: List tasks in a workflow. Required params: workflow_id. +- create_task_kandev: Create a new task. Required params: workspace_id, workflow_id, workflow_step_id, title. +- update_task_kandev: Update a task. Required params: task_id. + +IMPORTANT: You MUST use these MCP tools when instructed to create plans, ask questions, or interact with the Kandev platform. Do not skip them. diff --git a/apps/backend/config/prompts/plan-mode.md b/apps/backend/config/prompts/plan-mode.md new file mode 100644 index 0000000000..4f874ea429 --- /dev/null +++ b/apps/backend/config/prompts/plan-mode.md @@ -0,0 +1,19 @@ +PLAN MODE ACTIVE: +You are in planning mode. Do not implement anything — focus on the plan. + +The plan is a shared document that both you and the user can edit. The user may have already written parts of the plan or made edits to your previous version. +Ask the user clarifying questions if anything is unclear or if you need guidance on how to proceed. + +WORKFLOW: +1. Read the current plan using the get_task_plan_kandev MCP tool. +2. Build on what already exists. Only replace or discard the user content if it is clearly irrelevant or incorrect. +3. If you need more context to make specific additions, explore the codebase - search for relevant files, read existing code, and understand the patterns in use. Ask questions if needed. +4. Make your additions specific to this project — reference actual file paths, function names, types, and architectural patterns. Avoid adding generic or boilerplate content. +5. Save your changes using the update_task_plan_kandev MCP tool (or create_task_plan_kandev if no plan exists yet). +6. After saving, STOP and wait for the user to review. + +When the user sends comments or feedback on the plan, treat them as revision requests: +- Read the current plan, apply the requested changes, and save the updated plan. +- Do NOT start implementing code changes. Stay in planning mode. + +This instruction applies to THIS PROMPT ONLY. diff --git a/apps/backend/config/prompts/session-handover.md b/apps/backend/config/prompts/session-handover.md new file mode 100644 index 0000000000..deac43cab1 --- /dev/null +++ b/apps/backend/config/prompts/session-handover.md @@ -0,0 +1,6 @@ +CONTEXT FROM PREVIOUS SESSIONS: +This task has had {session_count} previous session(s). You are starting a new session on the same workspace. +Any code changes from previous sessions are already present in the working directory. +{plan_section} +Review the current state of the codebase before making changes — previous sessions may have +already completed part of the work. Do not repeat work that is already done. diff --git a/apps/backend/internal/agentctl/server/mcp/sysprompt_sync_test.go b/apps/backend/internal/agentctl/server/mcp/sysprompt_sync_test.go index f134a363c9..c0cbe69add 100644 --- a/apps/backend/internal/agentctl/server/mcp/sysprompt_sync_test.go +++ b/apps/backend/internal/agentctl/server/mcp/sysprompt_sync_test.go @@ -83,13 +83,13 @@ func TestSyspromptToolNames_MatchMCPTaskMode(t *testing.T) { } referenced := make(map[string]struct{}) - for name := range extractKandevTools(sysprompt.PlanMode) { + for name := range extractKandevTools(sysprompt.PlanMode()) { referenced[name] = struct{}{} } - for name := range extractKandevTools(sysprompt.KandevContext) { + for name := range extractKandevTools(sysprompt.KandevContext()) { referenced[name] = struct{}{} } - for name := range extractKandevTools(sysprompt.DefaultPlanPrefix) { + for name := range extractKandevTools(sysprompt.DefaultPlanPrefix()) { referenced[name] = struct{}{} } @@ -118,7 +118,7 @@ func TestSyspromptToolNames_MatchMCPConfigMode(t *testing.T) { registered[name] = struct{}{} } - referenced := extractKandevTools(sysprompt.ConfigContext) + referenced := extractKandevTools(sysprompt.ConfigContext()) require.NotEmpty(t, referenced, "expected ConfigContext to reference at least one _kandev tool") for name := range referenced { @@ -154,10 +154,10 @@ func TestSyspromptToolNames_NoBareToolReferences(t *testing.T) { bareNames := bareNamesOf(registered) cases := map[string]string{ - "PlanMode": sysprompt.PlanMode, - "KandevContext": sysprompt.KandevContext, - "DefaultPlanPrefix": sysprompt.DefaultPlanPrefix, - "ConfigContext": sysprompt.ConfigContext, + "PlanMode": sysprompt.PlanMode(), + "KandevContext": sysprompt.KandevContext(), + "DefaultPlanPrefix": sysprompt.DefaultPlanPrefix(), + "ConfigContext": sysprompt.ConfigContext(), } for name, prompt := range cases { diff --git a/apps/backend/internal/orchestrator/task_operations.go b/apps/backend/internal/orchestrator/task_operations.go index c7cb85eb66..46ceaf6698 100644 --- a/apps/backend/internal/orchestrator/task_operations.go +++ b/apps/backend/internal/orchestrator/task_operations.go @@ -519,7 +519,7 @@ func (s *Service) applyWorkflowAndPlanMode(ctx context.Context, prompt string, t if planMode && !stepHasPlanMode { var parts []string - parts = append(parts, sysprompt.Wrap(sysprompt.InterpolatePlaceholders(sysprompt.DefaultPlanPrefix, taskID))) + parts = append(parts, sysprompt.Wrap(sysprompt.DefaultPlanPrefix())) parts = append(parts, effectivePrompt) effectivePrompt = strings.Join(parts, "\n\n") } diff --git a/apps/backend/internal/sysprompt/sysprompt.go b/apps/backend/internal/sysprompt/sysprompt.go index 542af829d5..45c4715395 100644 --- a/apps/backend/internal/sysprompt/sysprompt.go +++ b/apps/backend/internal/sysprompt/sysprompt.go @@ -3,12 +3,18 @@ // // All system prompts are wrapped in tags to mark them as // system-injected content that can be stripped when displaying to users. +// +// Prompt templates are stored as markdown files in config/prompts/ and loaded +// via the prompts package (go:embed). Placeholders use {key} syntax and are +// resolved by [Resolve]. package sysprompt import ( - "fmt" "regexp" + "strconv" "strings" + + "github.com/kandev/kandev/config/prompts" ) // System tag constants for marking system-injected content. @@ -22,6 +28,9 @@ const ( // systemTagRegex matches ... content including the tags. var systemTagRegex = regexp.MustCompile(`[\s\S]*?\s*`) +// placeholderRegex matches {key} placeholders in prompt templates. +var placeholderRegex = regexp.MustCompile(`\{([A-Za-z0-9_]+)\}`) + // StripSystemContent removes all ... blocks from text. // This is used to hide system-injected content from the frontend UI. func StripSystemContent(text string) string { @@ -38,123 +47,32 @@ func HasSystemContent(text string) bool { return systemTagRegex.MatchString(text) } -// PlanMode is the system prompt prepended when plan mode is enabled. +// PlanMode returns the system prompt prepended when plan mode is enabled. // It instructs agents to collaborate on the plan without implementing changes. -// Used for both initial plan creation and follow-up plan refinement messages. -const PlanMode = `PLAN MODE ACTIVE: -You are in planning mode. Do not implement anything — focus on the plan. +func PlanMode() string { return prompts.Get("plan-mode") } -The plan is a shared document that both you and the user can edit. The user may have already written parts of the plan or made edits to your previous version. -Ask the user clarifying questions if anything is unclear or if you need guidance on how to proceed. - -WORKFLOW: -1. Read the current plan using the get_task_plan_kandev MCP tool. -2. Build on what already exists. Only replace or discard the user content if it is clearly irrelevant or incorrect. -3. If you need more context to make specific additions, explore the codebase - search for relevant files, read existing code, and understand the patterns in use. Ask questions if needed. -4. Make your additions specific to this project — reference actual file paths, function names, types, and architectural patterns. Avoid adding generic or boilerplate content. -5. Save your changes using the update_task_plan_kandev MCP tool (or create_task_plan_kandev if no plan exists yet). -6. After saving, STOP and wait for the user to review. - -When the user sends comments or feedback on the plan, treat them as revision requests: -- Read the current plan, apply the requested changes, and save the updated plan. -- Do NOT start implementing code changes. Stay in planning mode. - -This instruction applies to THIS PROMPT ONLY.` - -// KandevContext is the system prompt that provides Kandev-specific instructions -// and session context to agents. Use FormatKandevContext to inject task/session IDs. -const KandevContext = `KANDEV MCP TOOLS — You have access to the following MCP tools from the "kandev" server. -Always use the exact tool names shown below (they include the _kandev suffix). - -Kandev Task ID: %s -Kandev Session ID: %s -Use these IDs when calling tools that require task_id or session_id. - -Available tools: -- ask_user_question_kandev: Ask the user a clarifying question with multiple-choice options. Use this whenever you need user input before proceeding. Required params: prompt (string), options (array of {label, description}). -- create_task_plan_kandev: Save an implementation plan for the current task. Required params: task_id, content (markdown). Optional: title. -- get_task_plan_kandev: Retrieve the current plan for a task (includes any user edits). Required params: task_id. -- update_task_plan_kandev: Update an existing plan. Required params: task_id, content (markdown). Optional: title. -- delete_task_plan_kandev: Delete a task plan. Required params: task_id. -- list_workspaces_kandev: List all workspaces. -- list_workflows_kandev: List workflows in a workspace. Required params: workspace_id. -- list_tasks_kandev: List tasks in a workflow. Required params: workflow_id. -- create_task_kandev: Create a new task. Required params: workspace_id, workflow_id, workflow_step_id, title. -- update_task_kandev: Update a task. Required params: task_id. - -IMPORTANT: You MUST use these MCP tools when instructed to create plans, ask questions, or interact with the Kandev platform. Do not skip them.` +// KandevContext returns the system prompt template that provides Kandev-specific +// instructions and session context to agents. Contains {task_id} and {session_id} +// placeholders — use [FormatKandevContext] to inject values. +func KandevContext() string { return prompts.Get("kandev-context") } // FormatKandevContext returns the Kandev context prompt with task and session IDs injected. func FormatKandevContext(taskID, sessionID string) string { - return fmt.Sprintf(KandevContext, taskID, sessionID) + return Resolve("kandev-context", map[string]string{ + "task_id": taskID, + "session_id": sessionID, + }) } -// ConfigContext is the system prompt for config-mode MCP sessions. -// It provides instructions for agents performing configuration operations -// via the dedicated config chat on the settings page. -const ConfigContext = `KANDEV CONFIG MCP TOOLS — You are a configuration assistant for the Kandev platform. -You have access to the following MCP tools from the "kandev" server. -Always use the exact tool names shown below (they include the _kandev suffix). - -Session ID: %s - -WORKFLOW TOOLS: -- list_workspaces_kandev: List all workspaces to get workspace IDs. -- list_workflows_kandev: List workflows in a workspace. Required: workspace_id. -- create_workflow_kandev: Create a new workflow. Required: workspace_id, name. Optional: description. -- update_workflow_kandev: Update a workflow. Required: workflow_id. Optional: name, description. -- delete_workflow_kandev: Delete a workflow and all its steps (destructive). Required: workflow_id. -- list_workflow_steps_kandev: List workflow steps (columns) in a workflow. Required: workflow_id. -- create_workflow_step_kandev: Create a new workflow step. Required: workflow_id, name. Optional: position, color, prompt, is_start_step, allow_manual_move, show_in_command_panel, events. -- update_workflow_step_kandev: Update a workflow step. Required: step_id. Optional: name, color, prompt, is_start_step, allow_manual_move, show_in_command_panel, auto_archive_after_hours, events. -- delete_workflow_step_kandev: Delete a workflow step (destructive). Required: step_id. -- reorder_workflow_steps_kandev: Reorder workflow steps. Required: workflow_id, step_ids (ordered array of step IDs). - -AGENT TOOLS: -- list_agents_kandev: List all configured agents and their profiles. -- update_agent_kandev: Update agent settings. Required: agent_id. Optional: supports_mcp, mcp_config_path. -- create_agent_profile_kandev: Create a new agent profile. Required: agent_id, name, model. Optional: auto_approve. -- delete_agent_profile_kandev: Delete an agent profile. Required: profile_id. - -EXECUTOR PROFILE TOOLS: -Executors (local, worktree, local_docker, sprites) are pre-defined. Use list_executors_kandev to find executor IDs, then manage profiles. -- list_executors_kandev: List all executors with their IDs and types. -- list_executor_profiles_kandev: List profiles for an executor. Required: executor_id. -- create_executor_profile_kandev: Create an executor profile. Required: executor_id, name. Optional: mcp_policy, config, prepare_script, cleanup_script. -- update_executor_profile_kandev: Update an executor profile. Required: profile_id. Optional: name, mcp_policy, config, prepare_script, cleanup_script. -- delete_executor_profile_kandev: Delete an executor profile. Required: profile_id. - -MCP CONFIG TOOLS: -- list_agent_profiles_kandev: List profiles for an agent. Required: agent_id. -- update_agent_profile_kandev: Update a profile. Required: profile_id. Optional: name, model, auto_approve. -- get_mcp_config_kandev: Get MCP server config for a profile. Required: profile_id. -- update_mcp_config_kandev: Update MCP config for a profile. Required: profile_id. Optional: enabled, servers. - -TASK TOOLS: -- list_tasks_kandev: List all tasks in a workflow. Required: workflow_id. -- move_task_kandev: Move a task to a different workflow step. Required: task_id, workflow_step_id. -- delete_task_kandev: Delete a task. Required: task_id. -- archive_task_kandev: Archive a task. Required: task_id. -- update_task_state_kandev: Update task state. Required: task_id, state (TODO, CREATED, SCHEDULING, IN_PROGRESS, REVIEW, BLOCKED, WAITING_FOR_INPUT, COMPLETED, FAILED, CANCELLED). - -INTERACTION: -- ask_user_question_kandev: Ask the user a clarifying question with multiple-choice options. Required: prompt, options. - -EXAMPLE REQUESTS the user might ask: -- "Create a new workflow called 'Feature Development'" -- "Add a 'Code Review' step to my workflow" -- "Create a new agent profile for Claude with auto-approve enabled" -- "Show me the current workflow steps" -- "Update the MCP servers for the default agent profile" -- "Create a new executor profile for Docker with a prepare script" -- "Move all completed tasks to the 'Done' column" -- "Archive old tasks from last month" - -IMPORTANT: Always list existing resources before creating or modifying. Confirm destructive operations (delete, archive) with the user first using ask_user_question_kandev.` +// ConfigContext returns the system prompt for config-mode MCP sessions. +// Contains a {session_id} placeholder — use [FormatConfigContext] to inject values. +func ConfigContext() string { return prompts.Get("config-context") } // FormatConfigContext returns the config context prompt with the session ID injected. func FormatConfigContext(sessionID string) string { - return fmt.Sprintf(ConfigContext, sessionID) + return Resolve("config-context", map[string]string{ + "session_id": sessionID, + }) } // InjectConfigContext prepends the config system prompt to a user's prompt. @@ -169,50 +87,28 @@ func InjectKandevContext(taskID, sessionID, prompt string) string { return Wrap(FormatKandevContext(taskID, sessionID)) + "\n\n" + prompt } -// DefaultPlanPrefix is the planning instruction prompt used when plan mode is -// requested but no workflow step provides its own prompt prefix. -const DefaultPlanPrefix = `[PLANNING PHASE] -Analyze this task and create a detailed implementation plan. - -Before creating the plan, ask the user clarifying questions if anything is unclear. -Use the ask_user_question_kandev MCP tool to get answers before proceeding. - -First check if a plan already exists using the get_task_plan_kandev MCP tool. -If the user has already started writing the plan, build on their content — do not replace it. - -IMPORTANT: Before writing the plan, explore the codebase thoroughly. Read relevant files, search for existing patterns, and understand the project's architecture. Your plan must reference actual file paths, function names, types, and patterns from this project — not generic advice. - -The plan should include: -1. Understanding of the requirements -2. Specific files that need to be modified or created (with actual paths from the codebase) -3. Step-by-step implementation approach grounded in existing code patterns -4. Potential risks or considerations - -When including diagrams (architecture, sequence, flowcharts), always use mermaid syntax in code blocks. - -Save the plan using the create_task_plan_kandev or update_task_plan_kandev MCP tool. -After saving, STOP and wait for user review. The user may edit the plan before approving it. -Do not create any other files during this phase — only use the MCP tools to save the plan.` +// DefaultPlanPrefix returns the planning instruction prompt used when plan mode +// is requested but no workflow step provides its own prompt prefix. +func DefaultPlanPrefix() string { return prompts.Get("default-plan-prefix") } // InjectPlanMode prepends the plan mode system prompt to a user's prompt. // The system content is wrapped in tags. func InjectPlanMode(prompt string) string { - return Wrap(PlanMode) + "\n\n" + prompt + return Wrap(PlanMode()) + "\n\n" + prompt } -// SessionHandoverContext is injected when a new session starts for a task that -// already has previous sessions. It gives the agent awareness of prior work. -const SessionHandoverContext = `CONTEXT FROM PREVIOUS SESSIONS: -This task has had %d previous session(s). You are starting a new session on the same workspace. -Any code changes from previous sessions are already present in the working directory. -%s -Review the current state of the codebase before making changes — previous sessions may have -already completed part of the work. Do not repeat work that is already done.` +// SessionHandoverContext returns the template injected when a new session starts +// for a task that already has previous sessions. Contains {session_count} and +// {plan_section} placeholders — use [FormatSessionHandover] to inject values. +func SessionHandoverContext() string { return prompts.Get("session-handover") } // FormatSessionHandover formats the session handover context. // planSection should be pre-formatted (empty string if no plan exists). func FormatSessionHandover(sessionCount int, planSection string) string { - return fmt.Sprintf(SessionHandoverContext, sessionCount, planSection) + return Resolve("session-handover", map[string]string{ + "session_count": strconv.Itoa(sessionCount), + "plan_section": planSection, + }) } // InjectSessionHandover prepends session handover context to a prompt, wrapped in system tags. @@ -220,6 +116,24 @@ func InjectSessionHandover(sessionCount int, planSection, prompt string) string return Wrap(FormatSessionHandover(sessionCount, planSection)) + "\n\n" + prompt } +// Resolve loads a prompt template by name and replaces all {key} placeholders +// with the corresponding values from vars. Every placeholder in the template +// should have a corresponding entry in vars; unreplaced placeholders are left +// as-is and passed through to the caller. +// +// Replacement is single-pass: values that themselves contain placeholder-like +// text (e.g. a plan section containing "{session_count}") are never re-processed. +func Resolve(name string, vars map[string]string) string { + template := prompts.Get(name) + return placeholderRegex.ReplaceAllStringFunc(template, func(placeholder string) string { + key := placeholder[1 : len(placeholder)-1] + if value, ok := vars[key]; ok { + return value + } + return placeholder + }) +} + // InterpolatePlaceholders replaces placeholders in prompt templates with actual values. // Supported placeholders: // - {task_id} - the task ID diff --git a/apps/backend/internal/sysprompt/sysprompt_test.go b/apps/backend/internal/sysprompt/sysprompt_test.go index f6bac840a9..7e8dec36db 100644 --- a/apps/backend/internal/sysprompt/sysprompt_test.go +++ b/apps/backend/internal/sysprompt/sysprompt_test.go @@ -51,30 +51,29 @@ func TestConfigContext_ContainsAllTools(t *testing.T) { } for _, tool := range expectedTools { - assert.Contains(t, ConfigContext, tool, "ConfigContext should contain tool: %s", tool) + assert.Contains(t, ConfigContext(), tool, "ConfigContext should contain tool: %s", tool) } } func TestConfigContext_ContainsSections(t *testing.T) { - assert.Contains(t, ConfigContext, "WORKFLOW TOOLS:") - assert.Contains(t, ConfigContext, "AGENT TOOLS:") - assert.Contains(t, ConfigContext, "EXECUTOR PROFILE TOOLS:") - assert.Contains(t, ConfigContext, "MCP CONFIG TOOLS:") - assert.Contains(t, ConfigContext, "TASK TOOLS:") - assert.Contains(t, ConfigContext, "INTERACTION:") - assert.Contains(t, ConfigContext, "EXAMPLE REQUESTS") + assert.Contains(t, ConfigContext(), "WORKFLOW TOOLS:") + assert.Contains(t, ConfigContext(), "AGENT TOOLS:") + assert.Contains(t, ConfigContext(), "EXECUTOR PROFILE TOOLS:") + assert.Contains(t, ConfigContext(), "MCP CONFIG TOOLS:") + assert.Contains(t, ConfigContext(), "TASK TOOLS:") + assert.Contains(t, ConfigContext(), "INTERACTION:") + assert.Contains(t, ConfigContext(), "EXAMPLE REQUESTS") } func TestConfigContext_HasExactlyOneSessionIDPlaceholder(t *testing.T) { - count := strings.Count(ConfigContext, "%s") - assert.Equal(t, 1, count, "ConfigContext should have exactly 1 %%s placeholder") + count := strings.Count(ConfigContext(), "{session_id}") + assert.Equal(t, 1, count, "ConfigContext should have exactly 1 {session_id} placeholder") } func TestFormatConfigContext_InjectsSessionID(t *testing.T) { result := FormatConfigContext("session-abc-123") assert.Contains(t, result, "Session ID: session-abc-123") - assert.NotContains(t, result, "%s") - assert.NotContains(t, result, "%!") + assert.NotContains(t, result, "{session_id}") } func TestInjectConfigContext_WrapsInSystemTags(t *testing.T) { @@ -95,15 +94,19 @@ func TestInjectConfigContext_SystemContentStrippable(t *testing.T) { // --- KandevContext tests (existing, verify not broken) --- func TestKandevContext_HasExactlyTwoPlaceholders(t *testing.T) { - count := strings.Count(KandevContext, "%s") - assert.Equal(t, 2, count, "KandevContext should have exactly 2 %%s placeholders") + ctx := KandevContext() + taskCount := strings.Count(ctx, "{task_id}") + sessionCount := strings.Count(ctx, "{session_id}") + assert.Equal(t, 1, taskCount, "KandevContext should have exactly 1 {task_id} placeholder") + assert.Equal(t, 1, sessionCount, "KandevContext should have exactly 1 {session_id} placeholder") } func TestFormatKandevContext_InjectsIDs(t *testing.T) { result := FormatKandevContext("task-abc", "session-xyz") assert.Contains(t, result, "Kandev Task ID: task-abc") assert.Contains(t, result, "Session ID: session-xyz") - assert.NotContains(t, result, "%!") + assert.NotContains(t, result, "{task_id}") + assert.NotContains(t, result, "{session_id}") } func TestInjectKandevContext_WrapsInSystemTags(t *testing.T) { @@ -172,6 +175,42 @@ func TestInjectPlanMode_SystemContentStrippable(t *testing.T) { assert.Equal(t, testPlanPrompt, stripped) } +// --- SessionHandover tests --- + +func TestSessionHandoverContext_HasPlaceholders(t *testing.T) { + ctx := SessionHandoverContext() + assert.Contains(t, ctx, "{session_count}") + assert.Contains(t, ctx, "{plan_section}") +} + +func TestFormatSessionHandover_InjectsValues(t *testing.T) { + result := FormatSessionHandover(3, "PLAN: do the thing") + assert.Contains(t, result, "3 previous session(s)") + assert.Contains(t, result, "PLAN: do the thing") + assert.NotContains(t, result, "{session_count}") + assert.NotContains(t, result, "{plan_section}") +} + +func TestInjectSessionHandover_WrapsInSystemTags(t *testing.T) { + result := InjectSessionHandover(2, "", "Do the work") + assert.True(t, strings.HasPrefix(result, TagStart)) + assert.Contains(t, result, "Do the work") +} + +func TestInjectSessionHandover_SystemContentStrippable(t *testing.T) { + result := InjectSessionHandover(2, "", "Do the work") + stripped := StripSystemContent(result) + assert.Equal(t, "Do the work", stripped) +} + +func TestFormatSessionHandover_ValueWithPlaceholderLikeText(t *testing.T) { + // Verify single-pass replacement: a plan section containing {session_count} + // must not be re-processed. + result := FormatSessionHandover(2, "Plan mentions {session_count} literally") + assert.Contains(t, result, "2 previous session(s)") + assert.Contains(t, result, "Plan mentions {session_count} literally") +} + // --- InterpolatePlaceholders tests --- func TestInterpolatePlaceholders_TaskID(t *testing.T) { @@ -192,15 +231,15 @@ func TestInterpolatePlaceholders_MultiplePlaceholders(t *testing.T) { // --- ConfigContext vs KandevContext distinction --- func TestConfigContext_DoesNotContainPlanTools(t *testing.T) { - assert.NotContains(t, ConfigContext, "create_task_plan_kandev") - assert.NotContains(t, ConfigContext, "get_task_plan_kandev") - assert.NotContains(t, ConfigContext, "update_task_plan_kandev") - assert.NotContains(t, ConfigContext, "delete_task_plan_kandev") + assert.NotContains(t, ConfigContext(), "create_task_plan_kandev") + assert.NotContains(t, ConfigContext(), "get_task_plan_kandev") + assert.NotContains(t, ConfigContext(), "update_task_plan_kandev") + assert.NotContains(t, ConfigContext(), "delete_task_plan_kandev") } func TestKandevContext_DoesNotContainConfigTools(t *testing.T) { - assert.NotContains(t, KandevContext, "create_workflow_step_kandev") - assert.NotContains(t, KandevContext, "update_workflow_step_kandev") - assert.NotContains(t, KandevContext, "list_agents_kandev") - assert.NotContains(t, KandevContext, "create_agent_kandev") + assert.NotContains(t, KandevContext(), "create_workflow_step_kandev") + assert.NotContains(t, KandevContext(), "update_workflow_step_kandev") + assert.NotContains(t, KandevContext(), "list_agents_kandev") + assert.NotContains(t, KandevContext(), "create_agent_kandev") }