diff --git a/.github/agents/campaign-designer.agent.md b/.github/agents/campaign-designer.agent.md new file mode 100644 index 00000000000..1e721a776d2 --- /dev/null +++ b/.github/agents/campaign-designer.agent.md @@ -0,0 +1,83 @@ +```chatagent +--- +description: Assist humans in designing and scaffolding gh-aw campaign specs (.campaign.md) and optional starter workflows. +--- + +# Campaign Designer for gh-aw Campaigns + +You are an AI agent that guides humans through designing and scaffolding new **campaign definitions** for this repository using the gh-aw campaigns format. + +Your job is to help the user: +- Clarify the campaign's purpose, scope, and success metrics. +- Identify owners, sponsors, risk level, lifecycle state, and tags. +- Propose one or more workflows that will implement the campaign. +- Create or update the corresponding `.campaign.md` spec and (optionally) a starter workflow. +- Record a concise design summary (for humans to persist in repo-memory or documentation). + +## Step 1: Understand the New Campaign + +Start by asking focused questions to understand: +- The campaign goal and the problem it solves. +- Expected duration and lifecycle (planned / active / paused / completed). +- Primary owners and executive sponsors. +- Risk level (low / medium / high) and governance needs. +- Which existing workflows (if any) it should reuse. + +Summarize back your understanding and get explicit confirmation before proceeding. + +## Step 2: Propose Campaign Spec Fields + +Based on the conversation, propose concrete values for the core campaign fields: +- `id` — stable identifier in kebab-case using only lowercase letters, digits, and hyphens (for example: `security-q1-2025`). +- `name` — human-friendly title. +- `description` — short explanation of what the campaign does. +- `workflows` — one or more workflow IDs (basenames under `.github/workflows/` without `.md`). +- `memory-paths` — under `memory/campaigns/-*/**` when the campaign uses repo-memory. +- `owners` — primary human owners. +- `executive-sponsors` — accountable stakeholders. +- `risk-level` — free-form risk indicator (for example: low / medium / high). +- `state` — lifecycle stage (planned, active, paused, completed, archived). +- `tags` — free-form categorization. +- `tracker-label` — use `campaign:` to stay consistent with `gh aw campaign new` and other specs. +- `allowed-safe-outputs` — which safe-outputs operations the campaign may use. +- `approval-policy` — required approvals and roles. + +Show the proposed YAML frontmatter snippet to the user and refine it until they approve. If the user already ran `gh aw campaign new `, read and refine that scaffold instead of starting from scratch. + +## Step 3: Create or Update the .campaign.md File + +Once the spec fields are approved, guide the user to create or update the spec file: + +1. The target file path should be: + - `.github/workflows/.campaign.md` +2. The file should contain: + - The approved YAML frontmatter. + - A short Markdown body explaining the campaign's goals, usage, and how agents should behave. + +Encourage the user to keep the spec aligned with existing examples such as `incident-response.campaign.md` and `security-compliance.campaign.md` in this repo. + +## Step 4: (Optional) Propose a Starter Workflow + +If the user wants a starter workflow for the campaign: + +1. Propose a workflow ID (for example: `-run` or ``). +2. Sketch the frontmatter for `.github/workflows/.md`, including: + - `engine: copilot` (or another engine they choose). + - Appropriate `on:` triggers (typically `workflow_dispatch` for manual runs at first). + - Minimal `permissions:` and `safe-outputs:` consistent with the campaign spec. +3. Describe the high-level steps the workflow should perform within the campaign. + +Keep the starter workflow intentionally simple and clearly mark TODO sections for humans to refine. + +## Step 5: Record the Design and Next Steps + +Help the user capture a brief design summary they can persist alongside the spec or in repo-memory, including: +- Final campaign spec fields. +- Chosen workflow IDs. +- Paths to created or updated files. +- Open questions or follow-up tasks. + +When you are done, summarize what you designed and clearly list next steps for the human owner (for example: "run `gh aw campaign validate`, wire this into your incident runbook", etc.). + +Always keep humans in the loop for final approval of campaign specs and workflows, especially for high-risk or compliance-sensitive campaigns. +``` \ No newline at end of file diff --git a/.github/workflows/stale-repo-identifier.lock.yml b/.github/workflows/stale-repo-identifier.lock.yml index e88aa216635..d4015c8b74b 100644 --- a/.github/workflows/stale-repo-identifier.lock.yml +++ b/.github/workflows/stale-repo-identifier.lock.yml @@ -1210,7 +1210,7 @@ jobs: ORGANIZATION: ${{ env.ORGANIZATION }} id: stale-repos name: Run stale_repos tool - uses: github/stale-repos@v3 + uses: github/stale-repos@3477b6488008d9411aaf22a0924ec7c1f6a69980 # v3 - env: INACTIVE_REPOS: ${{ steps.stale-repos.outputs.inactiveRepos }} name: Save stale repos output diff --git a/docs/src/content/docs/guides/campaigns.md b/docs/src/content/docs/guides/campaigns.md index fa3220df85f..7f6975c2707 100644 --- a/docs/src/content/docs/guides/campaigns.md +++ b/docs/src/content/docs/guides/campaigns.md @@ -413,6 +413,22 @@ This gives you a centralized, Git-backed catalog of campaigns in the repository, aligned with the executable workflows in `.github/workflows/` and the data they write into repo-memory. +### Interactive Campaign Designer + +For a more guided, conversational experience, this repo also includes a +reusable **custom agent**: + +- `.github/agents/campaign-designer.agent.md` ("Campaign Designer for gh-aw Campaigns") + +You can: + +- Use `gh aw campaign new ` to scaffold a minimal spec, then + open the **Campaign Designer** agent in GitHub Copilot Chat or your + preferred agent UI to refine fields like `owners`, `memory-paths`, and + `approval-policy`, or +- Start directly with the agent and let it propose a complete + `.campaign.md` spec (and optional starter workflow) based on your answers. + ### Example: Incident Response Campaign **Full workflow**: `.github/workflows/campaign-incident-response.md` diff --git a/pkg/campaign/command.go b/pkg/campaign/command.go index 4eeefb42048..69270f87cb9 100644 --- a/pkg/campaign/command.go +++ b/pkg/campaign/command.go @@ -2,8 +2,10 @@ package campaign import ( "encoding/json" + "errors" "fmt" "os" + "strings" "github.com/githubnext/gh-aw/pkg/console" "github.com/githubnext/gh-aw/pkg/constants" @@ -94,8 +96,28 @@ fields to match your initiative. Examples: ` + constants.CLIExtensionPrefix + ` campaign new security-q1-2025 ` + constants.CLIExtensionPrefix + ` campaign new modernization-winter2025 --force`, - Args: cobra.ExactArgs(1), + Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { + if len(args) == 0 { + // Build an error message with suggestions but without the leading + // error prefix icon; the main CLI handler will add that. + var b strings.Builder + b.WriteString("missing campaign id argument") + b.WriteString("\n\nSuggestions:\n") + suggestions := []string{ + "Provide an ID: '" + constants.CLIExtensionPrefix + " campaign new security-q1-2025'", + "Use '" + constants.CLIExtensionPrefix + " campaign' to see existing campaigns", + "Run '" + constants.CLIExtensionPrefix + " help campaign new' for full usage", + } + for _, s := range suggestions { + b.WriteString(" • ") + b.WriteString(s) + b.WriteString("\n") + } + + return errors.New(b.String()) + } + id := args[0] force, _ := cmd.Flags().GetBool("force") @@ -109,7 +131,9 @@ Examples: return err } - fmt.Fprintln(os.Stderr, console.FormatSuccessMessage("Created campaign spec at "+path)) + fmt.Fprintln(os.Stderr, console.FormatSuccessMessage( + "Created campaign spec at "+path+". Open this file and fill in owners, workflows, memory-paths, and other details.", + )) return nil }, } @@ -183,8 +207,10 @@ func runStatus(pattern string, jsonOutput bool) error { return nil } - // Render table to stdout for human-friendly output - output := console.RenderStruct(specs) + // Build a compact summary view for human-friendly table output. + // Full campaign definitions remain available via the --json flag. + summaries := buildCampaignSummaries(specs) + output := console.RenderStruct(summaries) fmt.Print(output) return nil } diff --git a/pkg/campaign/spec.go b/pkg/campaign/spec.go index b0f3ffb3e58..8a24c1df5ee 100644 --- a/pkg/campaign/spec.go +++ b/pkg/campaign/spec.go @@ -11,8 +11,8 @@ package campaign // workflows and repo-memory conventions. type CampaignSpec struct { ID string `yaml:"id" json:"id" console:"header:ID"` - Name string `yaml:"name" json:"name" console:"header:Name"` - Description string `yaml:"description,omitempty" json:"description,omitempty" console:"header:Description,omitempty"` + Name string `yaml:"name" json:"name" console:"header:Name,maxlen:30"` + Description string `yaml:"description,omitempty" json:"description,omitempty" console:"header:Description,omitempty,maxlen:60"` // Version is an optional spec version string (for example: v1). // When omitted, it defaults to v1 during validation. @@ -20,25 +20,25 @@ type CampaignSpec struct { // Workflows associates this campaign with one or more workflow IDs // (basename of the Markdown file without .md). - Workflows []string `yaml:"workflows,omitempty" json:"workflows,omitempty" console:"header:Workflows,omitempty"` + Workflows []string `yaml:"workflows,omitempty" json:"workflows,omitempty" console:"header:Workflows,omitempty,maxlen:40"` // MemoryPaths documents where this campaign writes its repo-memory // (for example: memory/campaigns/incident-*/**). - MemoryPaths []string `yaml:"memory-paths,omitempty" json:"memory_paths,omitempty" console:"header:Memory Paths,omitempty"` + MemoryPaths []string `yaml:"memory-paths,omitempty" json:"memory_paths,omitempty" console:"header:Memory Paths,omitempty,maxlen:40"` // MetricsGlob is an optional glob (relative to the repository root) // used to locate JSON metrics snapshots stored in the // memory/campaigns branch. When set, `gh aw campaign status` will // attempt to read the latest matching metrics file and surface a few // key fields. - MetricsGlob string `yaml:"metrics-glob,omitempty" json:"metrics_glob,omitempty" console:"header:Metrics Glob,omitempty"` + MetricsGlob string `yaml:"metrics-glob,omitempty" json:"metrics_glob,omitempty" console:"header:Metrics Glob,omitempty,maxlen:30"` // Owners lists the primary human owners for this campaign. - Owners []string `yaml:"owners,omitempty" json:"owners,omitempty" console:"header:Owners,omitempty"` + Owners []string `yaml:"owners,omitempty" json:"owners,omitempty" console:"header:Owners,omitempty,maxlen:30"` // ExecutiveSponsors lists executive stakeholders or sponsors who are // accountable for the outcome of this campaign. - ExecutiveSponsors []string `yaml:"executive-sponsors,omitempty" json:"executive_sponsors,omitempty" console:"header:Executive Sponsors,omitempty"` + ExecutiveSponsors []string `yaml:"executive-sponsors,omitempty" json:"executive_sponsors,omitempty" console:"header:Executive Sponsors,omitempty,maxlen:30"` // RiskLevel is an optional free-form field (e.g. low/medium/high). RiskLevel string `yaml:"risk-level,omitempty" json:"risk_level,omitempty" console:"header:Risk Level,omitempty"` @@ -53,13 +53,13 @@ type CampaignSpec struct { // Tags provide free-form categorization for reporting (for example: // security, modernization, rollout). - Tags []string `yaml:"tags,omitempty" json:"tags,omitempty" console:"header:Tags,omitempty"` + Tags []string `yaml:"tags,omitempty" json:"tags,omitempty" console:"header:Tags,omitempty,maxlen:30"` // AllowedSafeOutputs documents which safe-outputs operations this // campaign is expected to use (for example: create-issue, // create-pull-request). This is currently informational but can be // enforced by validation in the future. - AllowedSafeOutputs []string `yaml:"allowed-safe-outputs,omitempty" json:"allowed_safe_outputs,omitempty" console:"header:Allowed Safe Outputs,omitempty"` + AllowedSafeOutputs []string `yaml:"allowed-safe-outputs,omitempty" json:"allowed_safe_outputs,omitempty" console:"header:Allowed Safe Outputs,omitempty,maxlen:30"` // ApprovalPolicy describes high-level approval expectations for this // campaign (for example: number of approvals and required roles). @@ -67,7 +67,7 @@ type CampaignSpec struct { // ConfigPath is populated at load time with the relative path of // the YAML file on disk, to help users locate definitions. - ConfigPath string `yaml:"-" json:"config_path" console:"header:Config Path"` + ConfigPath string `yaml:"-" json:"config_path" console:"header:Config Path,maxlen:60"` } // CampaignApprovalPolicy captures basic approval expectations for a diff --git a/pkg/campaign/summary.go b/pkg/campaign/summary.go new file mode 100644 index 00000000000..e44a0861204 --- /dev/null +++ b/pkg/campaign/summary.go @@ -0,0 +1,37 @@ +package campaign + +import "strings" + +// campaignSummary provides a compact, human-friendly view of campaign specs +// for the default `gh aw campaign` table output. Full details remain +// available via `--json`. +type campaignSummary struct { + ID string `json:"id" console:"header:ID"` + Name string `json:"name" console:"header:Name,maxlen:30"` + State string `json:"state" console:"header:State"` + RiskLevel string `json:"risk_level,omitempty" console:"header:Risk,omitempty"` + TrackerLabel string `json:"tracker_label,omitempty" console:"header:Tracker Label,omitempty,maxlen:24"` + Workflows string `json:"workflows,omitempty" console:"header:Workflows,omitempty,maxlen:40"` + Owners string `json:"owners,omitempty" console:"header:Owners,omitempty,maxlen:30"` + ConfigPath string `json:"config_path" console:"header:Config Path,maxlen:60"` +} + +// buildCampaignSummaries converts full campaign specs into compact summaries +// suitable for human-friendly table output. +func buildCampaignSummaries(specs []CampaignSpec) []campaignSummary { + summaries := make([]campaignSummary, 0, len(specs)) + for _, spec := range specs { + summaries = append(summaries, campaignSummary{ + ID: spec.ID, + Name: spec.Name, + State: spec.State, + RiskLevel: spec.RiskLevel, + TrackerLabel: spec.TrackerLabel, + Workflows: strings.Join(spec.Workflows, ", "), + Owners: strings.Join(spec.Owners, ", "), + ConfigPath: spec.ConfigPath, + }) + } + + return summaries +} diff --git a/pkg/cli/commands.go b/pkg/cli/commands.go index f7df9b6eb93..d2f273efc88 100644 --- a/pkg/cli/commands.go +++ b/pkg/cli/commands.go @@ -33,6 +33,9 @@ var sharedAgenticWorkflowAgentTemplate string //go:embed templates/debug-agentic-workflow.agent.md var debugAgenticWorkflowAgentTemplate string +//go:embed templates/campaign-designer.agent.md +var campaignDesignerAgentTemplate string + // SetVersionInfo sets the version information for the CLI func SetVersionInfo(v string) { version = v diff --git a/pkg/cli/copilot-agents.go b/pkg/cli/copilot-agents.go index 20ec3f7dd16..acb629df6a7 100644 --- a/pkg/cli/copilot-agents.go +++ b/pkg/cli/copilot-agents.go @@ -175,6 +175,11 @@ func ensureDebugAgenticWorkflowAgent(verbose bool, skipInstructions bool) error return ensureAgentFromTemplate("debug-agentic-workflow.agent.md", debugAgenticWorkflowAgentTemplate, verbose, skipInstructions) } +// ensureCampaignDesignerAgent ensures that .github/agents/campaign-designer.agent.md contains the campaign designer agent +func ensureCampaignDesignerAgent(verbose bool, skipInstructions bool) error { + return ensureAgentFromTemplate("campaign-designer.agent.md", campaignDesignerAgentTemplate, verbose, skipInstructions) +} + // deleteSetupAgenticWorkflowsAgent deletes the setup-agentic-workflows.agent.md file if it exists func deleteSetupAgenticWorkflowsAgent(verbose bool) error { gitRoot, err := findGitRoot() diff --git a/pkg/cli/init.go b/pkg/cli/init.go index fd661cd9b2e..1306adff623 100644 --- a/pkg/cli/init.go +++ b/pkg/cli/init.go @@ -12,7 +12,7 @@ import ( var initLog = logger.New("cli:init") // InitRepository initializes the repository for agentic workflows -func InitRepository(verbose bool, mcp bool, codespaceRepos []string, codespaceEnabled bool) error { +func InitRepository(verbose bool, mcp bool, campaign bool, codespaceRepos []string, codespaceEnabled bool) error { initLog.Print("Starting repository initialization for agentic workflows") // Ensure we're in a git repository @@ -89,6 +89,18 @@ func InitRepository(verbose bool, mcp bool, codespaceRepos []string, codespaceEn fmt.Fprintln(os.Stderr, console.FormatSuccessMessage("Created debug agentic workflow agent")) } + // Write campaign designer agent if requested + if campaign { + initLog.Print("Writing campaign designer agent") + if err := ensureCampaignDesignerAgent(verbose, false); err != nil { + initLog.Printf("Failed to write campaign designer agent: %v", err) + return fmt.Errorf("failed to write campaign designer agent: %w", err) + } + if verbose { + fmt.Fprintln(os.Stderr, console.FormatSuccessMessage("Created campaign designer agent")) + } + } + // Configure MCP if requested if mcp { initLog.Print("Configuring GitHub Copilot Agent MCP integration") diff --git a/pkg/cli/init_command.go b/pkg/cli/init_command.go index 5f10d9174c3..b6e632249c8 100644 --- a/pkg/cli/init_command.go +++ b/pkg/cli/init_command.go @@ -37,6 +37,9 @@ With --codespaces flag: - Pre-installs @github/copilot - Use without value (--codespaces) for current repo only, or with comma-separated repos (--codespaces repo1,repo2) +With --campaign flag: +- Creates .github/agents/campaign-designer.agent.md with the Campaign Designer agent for gh-aw campaigns + After running this command, you can: - Use GitHub Copilot Chat: type /agent and select create-agentic-workflow to create workflows interactively - Use GitHub Copilot Chat: type /agent and select debug-agentic-workflow to debug existing workflows @@ -52,6 +55,7 @@ Examples: RunE: func(cmd *cobra.Command, args []string) error { verbose, _ := cmd.Flags().GetBool("verbose") mcp, _ := cmd.Flags().GetBool("mcp") + campaign, _ := cmd.Flags().GetBool("campaign") codespaceReposStr, _ := cmd.Flags().GetString("codespaces") codespaceEnabled := cmd.Flags().Changed("codespaces") @@ -68,8 +72,8 @@ Examples: } } - initCommandLog.Printf("Executing init command: verbose=%v, mcp=%v, codespaces=%v, codespaceEnabled=%v", verbose, mcp, codespaceRepos, codespaceEnabled) - if err := InitRepository(verbose, mcp, codespaceRepos, codespaceEnabled); err != nil { + initCommandLog.Printf("Executing init command: verbose=%v, mcp=%v, campaign=%v, codespaces=%v, codespaceEnabled=%v", verbose, mcp, campaign, codespaceRepos, codespaceEnabled) + if err := InitRepository(verbose, mcp, campaign, codespaceRepos, codespaceEnabled); err != nil { initCommandLog.Printf("Init command failed: %v", err) return err } @@ -79,6 +83,7 @@ Examples: } cmd.Flags().Bool("mcp", false, "Configure GitHub Copilot Agent MCP server integration") + cmd.Flags().Bool("campaign", false, "Install the Campaign Designer agent for gh-aw campaigns in this repository") cmd.Flags().String("codespaces", "", "Create devcontainer.json for GitHub Codespaces with agentic workflows support. Specify comma-separated repository names in the same organization (e.g., repo1,repo2), or use without value for current repo only") // NoOptDefVal allows using --codespaces without a value (returns empty string when no value provided) cmd.Flags().Lookup("codespaces").NoOptDefVal = " " diff --git a/pkg/cli/init_command_test.go b/pkg/cli/init_command_test.go index 451c415885e..1ab0143b15c 100644 --- a/pkg/cli/init_command_test.go +++ b/pkg/cli/init_command_test.go @@ -40,6 +40,16 @@ func TestNewInitCommand(t *testing.T) { return } + campaignFlag := cmd.Flags().Lookup("campaign") + if campaignFlag == nil { + t.Error("Expected 'campaign' flag to be defined") + return + } + + if campaignFlag.DefValue != "false" { + t.Errorf("Expected campaign flag default to be 'false', got %q", campaignFlag.DefValue) + } + if mcpFlag.DefValue != "false" { t.Errorf("Expected mcp flag default to be 'false', got %q", mcpFlag.DefValue) } @@ -105,8 +115,8 @@ func TestInitRepositoryBasic(t *testing.T) { exec.Command("git", "config", "user.name", "Test User").Run() exec.Command("git", "config", "user.email", "test@example.com").Run() - // Test basic init without MCP - err = InitRepository(false, false, []string{}, false) + // Test basic init without MCP or campaign agent + err = InitRepository(false, false, false, []string{}, false) if err != nil { t.Fatalf("InitRepository() failed: %v", err) } @@ -160,7 +170,7 @@ func TestInitRepositoryWithMCP(t *testing.T) { exec.Command("git", "config", "user.email", "test@example.com").Run() // Test init with MCP flag - err = InitRepository(false, true, []string{}, false) + err = InitRepository(false, true, false, []string{}, false) if err != nil { t.Fatalf("InitRepository() with MCP failed: %v", err) } @@ -203,7 +213,7 @@ func TestInitRepositoryVerbose(t *testing.T) { exec.Command("git", "config", "user.email", "test@example.com").Run() // Test verbose mode (should not error, just produce more output) - err = InitRepository(true, false, []string{}, false) + err = InitRepository(true, false, false, []string{}, false) if err != nil { t.Fatalf("InitRepository() in verbose mode failed: %v", err) } @@ -230,7 +240,7 @@ func TestInitRepositoryNotInGitRepo(t *testing.T) { } // Don't initialize git repo - should fail for some operations - err = InitRepository(false, false, []string{}, false) + err = InitRepository(false, false, false, []string{}, false) // The function should handle this gracefully or return an error // Based on the implementation, ensureGitAttributes requires git @@ -264,13 +274,13 @@ func TestInitRepositoryIdempotent(t *testing.T) { exec.Command("git", "config", "user.email", "test@example.com").Run() // Run init twice - err = InitRepository(false, false, []string{}, false) + err = InitRepository(false, false, false, []string{}, false) if err != nil { t.Fatalf("First InitRepository() failed: %v", err) } // Second run should be idempotent - err = InitRepository(false, false, []string{}, false) + err = InitRepository(false, false, false, []string{}, false) if err != nil { t.Fatalf("Second InitRepository() failed: %v", err) } @@ -315,12 +325,12 @@ func TestInitRepositoryWithMCPIdempotent(t *testing.T) { exec.Command("git", "config", "user.email", "test@example.com").Run() // Run init with MCP twice - err = InitRepository(false, true, []string{}, false) + err = InitRepository(false, true, false, []string{}, false) if err != nil { t.Fatalf("First InitRepository() with MCP failed: %v", err) } - err = InitRepository(false, true, []string{}, false) + err = InitRepository(false, true, false, []string{}, false) if err != nil { t.Fatalf("Second InitRepository() with MCP failed: %v", err) } @@ -362,7 +372,7 @@ func TestInitRepositoryCreatesDirectories(t *testing.T) { exec.Command("git", "config", "user.email", "test@example.com").Run() // Run init with MCP - err = InitRepository(false, true, []string{}, false) + err = InitRepository(false, true, false, []string{}, false) if err != nil { t.Fatalf("InitRepository() failed: %v", err) } @@ -400,6 +410,16 @@ func TestInitCommandFlagValidation(t *testing.T) { t.Errorf("Expected mcp flag to be bool, got %s", mcpFlag.Value.Type()) } + // Test that campaign flag is a boolean + campaignFlag := cmd.Flags().Lookup("campaign") + if campaignFlag == nil { + t.Fatal("Expected 'campaign' flag to exist") + } + + if campaignFlag.Value.Type() != "bool" { + t.Errorf("Expected campaign flag to be bool, got %s", campaignFlag.Value.Type()) + } + // Test verbose flag exists (inherited from parent command likely) // Note: verbose flag might be added by parent command, not in init command itself } @@ -420,7 +440,7 @@ func TestInitRepositoryErrorHandling(t *testing.T) { } // Test init without git repo - err = InitRepository(false, false, []string{}, false) + err = InitRepository(false, false, false, []string{}, false) // Should handle error gracefully or return error // The actual behavior depends on implementation @@ -463,7 +483,7 @@ func TestInitRepositoryWithExistingFiles(t *testing.T) { } // Run init - err = InitRepository(false, false, []string{}, false) + err = InitRepository(false, false, false, []string{}, false) if err != nil { t.Fatalf("InitRepository() failed: %v", err) } @@ -513,7 +533,7 @@ func TestInitRepositoryWithCodespace(t *testing.T) { // Test init with --codespaces flag (with additional repos) additionalRepos := []string{"org/repo1", "owner/repo2"} - err = InitRepository(false, false, additionalRepos, true) + err = InitRepository(false, false, false, additionalRepos, true) if err != nil { t.Fatalf("InitRepository() with codespaces failed: %v", err) } @@ -578,7 +598,7 @@ func TestInitCommandWithCodespacesNoArgs(t *testing.T) { exec.Command("git", "config", "user.email", "test@example.com").Run() // Test init with --codespaces flag (no additional repos) - err = InitRepository(false, false, []string{}, true) + err = InitRepository(false, false, false, []string{}, true) if err != nil { t.Fatalf("InitRepository() with codespaces (no args) failed: %v", err) } diff --git a/pkg/cli/init_mcp_test.go b/pkg/cli/init_mcp_test.go index a6f9fbf5acf..cd730a65196 100644 --- a/pkg/cli/init_mcp_test.go +++ b/pkg/cli/init_mcp_test.go @@ -39,8 +39,8 @@ func TestInitRepository_WithMCP(t *testing.T) { t.Fatalf("Failed to create go.mod: %v", err) } - // Call the function with MCP flag - err = InitRepository(false, true, []string{}, false) + // Call the function with MCP flag (no campaign agent) + err = InitRepository(false, true, false, []string{}, false) if err != nil { t.Fatalf("InitRepository() with MCP returned error: %v", err) } @@ -133,13 +133,13 @@ func TestInitRepository_MCP_Idempotent(t *testing.T) { } // Call the function first time with MCP - err = InitRepository(false, true, []string{}, false) + err = InitRepository(false, true, false, []string{}, false) if err != nil { t.Fatalf("InitRepository() with MCP returned error on first call: %v", err) } // Call the function second time with MCP - err = InitRepository(false, true, []string{}, false) + err = InitRepository(false, true, false, []string{}, false) if err != nil { t.Fatalf("InitRepository() with MCP returned error on second call: %v", err) } diff --git a/pkg/cli/init_test.go b/pkg/cli/init_test.go index b7d547b6978..feffbbfa68a 100644 --- a/pkg/cli/init_test.go +++ b/pkg/cli/init_test.go @@ -53,8 +53,8 @@ func TestInitRepository(t *testing.T) { } } - // Call the function - err = InitRepository(false, false, []string{}, false) + // Call the function (no MCP or campaign) + err = InitRepository(false, false, false, []string{}, false) // Check error expectation if tt.wantError { @@ -149,13 +149,13 @@ func TestInitRepository_Idempotent(t *testing.T) { } // Call the function first time - err = InitRepository(false, false, []string{}, false) + err = InitRepository(false, false, false, []string{}, false) if err != nil { t.Fatalf("InitRepository() returned error on first call: %v", err) } // Call the function second time - err = InitRepository(false, false, []string{}, false) + err = InitRepository(false, false, false, []string{}, false) if err != nil { t.Fatalf("InitRepository() returned error on second call: %v", err) } @@ -211,7 +211,7 @@ func TestInitRepository_Verbose(t *testing.T) { } // Call the function with verbose=true (should not error) - err = InitRepository(true, false, []string{}, false) + err = InitRepository(true, false, false, []string{}, false) if err != nil { t.Fatalf("InitRepository() returned error with verbose=true: %v", err) } @@ -222,3 +222,43 @@ func TestInitRepository_Verbose(t *testing.T) { t.Errorf("Expected .gitattributes file to exist with verbose=true") } } + +func TestInitRepository_WithCampaignDesignerAgent(t *testing.T) { + // Create a temporary directory for testing + tempDir := testutil.TempDir(t, "test-*") + + // Change to temp directory + oldWd, err := os.Getwd() + if err != nil { + t.Fatalf("Failed to get current directory: %v", err) + } + defer func() { + _ = os.Chdir(oldWd) + }() + if err := os.Chdir(tempDir); err != nil { + t.Fatalf("Failed to change directory: %v", err) + } + + // Initialize git repo + if err := exec.Command("git", "init").Run(); err != nil { + t.Fatalf("Failed to init git repo: %v", err) + } + + // Call InitRepository with campaign flag enabled + if err := InitRepository(false, false, true, []string{}, false); err != nil { + t.Fatalf("InitRepository() with campaign flag returned error: %v", err) + } + + agentPath := filepath.Join(tempDir, ".github", "agents", "campaign-designer.agent.md") + content, err := os.ReadFile(agentPath) + if err != nil { + t.Fatalf("Expected campaign designer agent to be created at %s, got error: %v", agentPath, err) + } + + // Ensure the written file matches the embedded template (ignoring leading/trailing whitespace) + got := strings.TrimSpace(string(content)) + want := strings.TrimSpace(campaignDesignerAgentTemplate) + if got != want { + t.Errorf("campaign-designer.agent.md content did not match embedded template") + } +} diff --git a/pkg/cli/templates/campaign-designer.agent.md b/pkg/cli/templates/campaign-designer.agent.md new file mode 100644 index 00000000000..60350d59a0e --- /dev/null +++ b/pkg/cli/templates/campaign-designer.agent.md @@ -0,0 +1,85 @@ +````chatagent +```chatagent +--- +description: Assist humans in designing and scaffolding GitHub Agentic Workflows campaign specs (.campaign.md) and optional starter workflows. +--- + +# Campaign Designer for GitHub Agentic Workflows Campaigns + +You are an AI agent that guides humans through designing and scaffolding new **campaign definitions** for this repository using the GitHub Agentic Workflows Campaigns format. + +Your job is to help the user: +- Clarify the campaign's purpose, scope, and success metrics. +- Identify owners, sponsors, risk level, lifecycle state, and tags. +- Propose one or more workflows that will implement the campaign. +- Create or update the corresponding `.campaign.md` spec and (optionally) a starter workflow. +- Record a concise design summary (for humans to persist in repo-memory or documentation). + +## Step 1: Understand the New Campaign + +Start by asking focused questions to understand: +- The campaign goal and the problem it solves. +- Expected duration and lifecycle (planned / active / paused / completed). +- Primary owners and executive sponsors. +- Risk level (low / medium / high) and governance needs. +- Which existing workflows (if any) it should reuse. + +Summarize back your understanding and get explicit confirmation before proceeding. + +## Step 2: Propose Campaign Spec Fields + +Based on the conversation, propose concrete values for the core campaign fields: +- `id` — stable identifier in kebab-case using only lowercase letters, digits, and hyphens (for example: `security-q1-2025`). +- `name` — human-friendly title. +- `description` — short explanation of what the campaign does. +- `workflows` — one or more workflow IDs (basenames under `.github/workflows/` without `.md`). +- `memory-paths` — under `memory/campaigns/-*/**` when the campaign uses repo-memory. +- `owners` — primary human owners. +- `executive-sponsors` — accountable stakeholders. +- `risk-level` — free-form risk indicator (for example: low / medium / high). +- `state` — lifecycle stage (planned, active, paused, completed, archived). +- `tags` — free-form categorization. +- `tracker-label` — use `campaign:` to stay consistent with `gh aw campaign new` and other specs. +- `allowed-safe-outputs` — which safe-outputs operations the campaign may use. +- `approval-policy` — required approvals and roles. + +Show the proposed YAML frontmatter snippet to the user and refine it until they approve. If the user already ran `gh aw campaign new `, read and refine that scaffold instead of starting from scratch. + +## Step 3: Create or Update the .campaign.md File + +Once the spec fields are approved, guide the user to create or update the spec file: + +1. The target file path should be: + - `.github/workflows/.campaign.md` +2. The file should contain: + - The approved YAML frontmatter. + - A short Markdown body explaining the campaign's goals, usage, and how agents should behave. + +Encourage the user to keep the spec aligned with existing examples such as `incident-response.campaign.md` and `security-compliance.campaign.md` in this repo. + +## Step 4: (Optional) Propose a Starter Workflow + +If the user wants a starter workflow for the campaign: + +1. Propose a workflow ID (for example: `-run` or ``). +2. Sketch the frontmatter for `.github/workflows/.md`, including: + - `engine: copilot` (or another engine they choose). + - Appropriate `on:` triggers (typically `workflow_dispatch` for manual runs at first). + - Minimal `permissions:` and `safe-outputs:` consistent with the campaign spec. +3. Describe the high-level steps the workflow should perform within the campaign. + +Keep the starter workflow intentionally simple and clearly mark TODO sections for humans to refine. + +## Step 5: Record the Design and Next Steps + +Help the user capture a brief design summary they can persist alongside the spec or in repo-memory, including: +- Final campaign spec fields. +- Chosen workflow IDs. +- Paths to created or updated files. +- Open questions or follow-up tasks. + +When you are done, summarize what you designed and clearly list next steps for the human owner (for example: "run `gh aw campaign validate`, wire this into your incident runbook", etc.). + +Always keep humans in the loop for final approval of campaign specs and workflows, especially for high-risk or compliance-sensitive campaigns. +``` +````