diff --git a/docs/adr/80754-split-compile-pipeline-into-focused-stages.md b/docs/adr/80754-split-compile-pipeline-into-focused-stages.md new file mode 100644 index 00000000000..820ca242df9 --- /dev/null +++ b/docs/adr/80754-split-compile-pipeline-into-focused-stages.md @@ -0,0 +1,43 @@ +# ADR-80754: Split Compilation Pipeline into Focused Stages + +**Date**: 2026-11-24 +**Status**: Draft +**PR**: #80754 +**Linked issue**: #80720 + +## Context + +`pkg/cli/compile_pipeline.go` had grown to 1162 lines, above the 800-line threshold recorded in issue #80720. Its two orchestrators, `compileSpecificFiles` and `compileAllFilesInDirectory`, were both marked `nolint:largefunc`. Each duplicated per-file compilation bookkeeping (stats, results, lock-file tracking, batch-tool inputs). Batch tool runners, duplicate-name notices, purge tracking, and post-processing shared the same file. + +## Decision + +Split the pipeline by responsibility and move the shared per-file bookkeeping into one stage type used by both orchestrators: + +- `compile_pipeline.go` (238 lines): the two orchestrators, which now delegate to `compilePipelineStage`. +- `compile_pipeline_stages.go` (new, 124 lines): `compilePipelineStage` holds the compiler, config, stats, results, workflows, lock files, batch-tool options, and success/failure counters. Its `compile()` and `recordFile()` methods implement per-file bookkeeping for both paths. +- `compile_pipeline_batch_tools.go` (new, 295 lines): batch linters, scanners, and external tool runners. +- `compile_pipeline_notices.go` (new, 155 lines): duplicate-name warnings, batch notices, and MCP progress writing. +- `compile_pipeline_postprocess.go` (new, 195 lines): post-processing and output. +- `compile_pipeline_purge.go` (new, 63 lines): purge tracking. + +The PR description states that the public API and compilation behavior are preserved. This draft has not independently verified that claim. + +## Alternatives Considered + +1. **Split files only, keeping per-file bookkeeping duplicated in each orchestrator.** This is a smaller change. It leaves the duplicated compile-and-record logic in place and keeps both orchestrators large. +2. **Move the pipeline into a separate package.** This gives a stronger boundary. It would require exporting internals that are currently package-private in `pkg/cli`, which enlarges the API surface. It is not part of this PR's diff. + +## Consequences + +**Positive** + +- The orchestrator file drops from 1162 to 238 lines, and each concern lives in a focused file. +- Per-file bookkeeping lives in one place and serves both the specific-file and directory paths. +- The new `compile_pipeline_stages_test.go` (105 lines) covers stage bookkeeping, per the PR description. + +**Negative** + +- Five new files in `pkg/cli`. The stage struct holds pointers to shared stats and results, so the order of stage calls becomes an implicit contract. +- The diff also regenerates 71 `.lock.yml` files that change the pinned Claude Code CLI version from `2.1.331` to `2.1.325` (observed in `pr-files.json` patches). This is unrelated to the decision and must be confirmed or reverted separately. + +/home/runner/work/gh-aw/gh-aw/docs/adr/80754-split-compile-pipeline-into-focused-stages.md \ No newline at end of file diff --git a/pkg/cli/compile_pipeline.go b/pkg/cli/compile_pipeline.go index 58936fdd567..0db2f27a844 100644 --- a/pkg/cli/compile_pipeline.go +++ b/pkg/cli/compile_pipeline.go @@ -22,18 +22,14 @@ package cli import ( - "cmp" "context" "errors" "fmt" "io/fs" "os" "path/filepath" - "slices" - "strings" "github.com/github/gh-aw/pkg/gitutil" - "github.com/github/gh-aw/pkg/stringutil" "github.com/github/gh-aw/pkg/console" "github.com/github/gh-aw/pkg/logger" @@ -42,29 +38,10 @@ import ( var compileOrchestrationLog = logger.New("cli:compile_pipeline") -// Batch tool entry points are exposed as package-level function variables so -// tests can override them to verify the batch pipeline invokes every enabled -// scanner in order, without short-circuiting, and without depending on the -// underlying external tool binaries/Docker images being available. -var ( - runBatchActionlintOnFiles = RunActionlintOnFiles - runBatchZizmorOnFiles = RunZizmorOnFiles - runBatchDryRunZizmorOnFiles = func(files []string, verbose, strict bool) error { - return runZizmorOnFilesWithOptions(files, verbose, strict, zizmorResultOptions{dryRun: true}) - } - runBatchPoutineOnDirectory = RunPoutineOnDirectory - runBatchRunnerGuardOnDirectory = RunRunnerGuardOnDirectory - runBatchSyftOnLockFiles = RunSyftOnLockFiles - runBatchGrypeOnLockFiles = RunGrypeOnLockFiles - runBatchGrantOnLockFiles = RunGrantOnLockFiles - runBatchYamllintOnFiles = RunYamllintOnFiles - runBatchShellcheckOnLockFilesAndResources = RunShellcheckOnLockFilesAndResources -) - const fallbackCompilationErrorMessage = "compilation failed (no detailed error message available)" // compileSpecificFiles compiles a specific list of workflow files -func compileSpecificFiles( //nolint:largefunc // Orchestrates the full targeted compile pipeline. +func compileSpecificFiles( ctx context.Context, compiler *workflow.Compiler, config CompileConfig, @@ -80,163 +57,20 @@ func compileSpecificFiles( //nolint:largefunc // Orchestrates the full targeted compiler.SetBatchMode(batchMode) compiler.SetQuiet(batchMode) - // Enable validation automatically when force-refresh-action-pins is used - // to verify all resolved action SHAs are valid - shouldValidate := config.Validate || config.ForceRefreshActionPins - if config.ForceRefreshActionPins && !config.Validate { - compileOrchestrationLog.Print("Automatically enabling action SHA validation due to --force-refresh-action-pins") - } - - var workflowDataList []*workflow.WorkflowData - var compiledCount int - var errorCount int - var lockFilesForActionlint []string - var lockFilesForZizmor []string - var lockFilesForDirTools []string // lock files for directory-based tools (poutine, runner-guard) - var lockFilesForSyft []string // lock files for syft container image SBOM scanning - var lockFilesForGrype []string // lock files for grype container image vulnerability scanning - var lockFilesForGrant []string // lock files for grant container image license scanning - var strictGrantErr error - var lockFilesForYamllint []string // lock files for yamllint YAML linter - var lockFilesForShellcheck []string // lock files for shellcheck run step linting - var shellcheckResources []workflow.ShellScriptResource - var compiledLockFiles []string // every lock file actually emitted, regardless of which lint tools are enabled - - // Compile each specified file - for _, markdownFile := range config.MarkdownFiles { - // Respect context cancellation between files (e.g. Ctrl+C) - select { - case <-ctx.Done(): - fmt.Fprintln(os.Stderr, console.FormatWarningMessageStderr("Operation cancelled")) - return workflowDataList, ctx.Err() - default: - } - - stats.Total++ - - // Initialize validation result - result := ValidationResult{ - Workflow: markdownFile, - Valid: true, - Errors: []ValidationIssue{}, - Warnings: []ValidationIssue{}, - } - - // Resolve workflow ID or file path to actual file path - compileOrchestrationLog.Printf("Resolving workflow file: %s", markdownFile) - resolvedFile, err := resolveWorkflowFile(markdownFile, config.Verbose) - if err != nil { - // Don't print error here - it will be displayed in the compilation summary - // The error is stored in ValidationResult for JSON output and returned for main to display - errorCount++ - stats.Errors++ - trackWorkflowFailure(stats, markdownFile, 1, []string{err.Error()}) - result.Valid = false - result.Errors = append(result.Errors, ValidationIssue{ - Type: "resolution_error", - Message: err.Error(), - }) - *validationResults = append(*validationResults, result) - writeMCPCompileProgress(config.MCPProgressFile, *validationResults) - continue - } - compileOrchestrationLog.Printf("Resolved to: %s", resolvedFile) - - // Update result with resolved file name - result.Workflow = filepath.Base(resolvedFile) - - // Compile regular workflow file (disable per-file security tools) - fileResult := compileWorkflowFile( - ctx, compiler, resolvedFile, compileWorkflowFileOptions{ - verbose: config.Verbose, - jsonOutput: config.JSONOutput, - noEmit: config.NoEmit, - strict: config.Strict, - validate: shouldValidate, - failOnWarnings: config.DryRun, - // zizmor, poutine, actionlint disabled per-file (batched instead) - }, - ) - - if !fileResult.success { - // Collect error messages from validation result for display in summary - var errMsgs []string - for _, verr := range fileResult.validationResult.Errors { - errMsgs = append(errMsgs, verr.Message) - } - if len(errMsgs) == 0 { - errMsgs = []string{fallbackCompilationErrorMessage} - } - errorCount++ - stats.Errors += len(errMsgs) - trackWorkflowFailure(stats, resolvedFile, len(errMsgs), errMsgs) - } else { - compiledCount++ - stats.Succeeded++ - if fileResult.workflowData != nil { - workflowDataList = append(workflowDataList, fileResult.workflowData) - } - - // Collect lock files for batch security tools - if !config.NoEmit && fileResult.lockFile != "" { - if _, err := os.Stat(fileResult.lockFile); err == nil { - compiledLockFiles = append(compiledLockFiles, fileResult.lockFile) - if config.Actionlint { - lockFilesForActionlint = append(lockFilesForActionlint, fileResult.lockFile) - } - if config.Zizmor { - lockFilesForZizmor = append(lockFilesForZizmor, fileResult.lockFile) - } - if config.Poutine || config.RunnerGuard { - lockFilesForDirTools = append(lockFilesForDirTools, fileResult.lockFile) - } - if config.Grype { - lockFilesForGrype = append(lockFilesForGrype, fileResult.lockFile) - } - if config.Grant { - lockFilesForGrant = append(lockFilesForGrant, fileResult.lockFile) - } - if config.Syft { - lockFilesForSyft = append(lockFilesForSyft, fileResult.lockFile) - } - if config.Yamllint { - lockFilesForYamllint = append(lockFilesForYamllint, fileResult.lockFile) - } - if config.shellcheckEnabled() { - lockFilesForShellcheck = append(lockFilesForShellcheck, fileResult.lockFile) - shellcheckResources = append(shellcheckResources, fileResult.workflowData.ShellScriptResources()...) - } - } - } - } - - if len(*validationResults) == 0 { - appendMCPCachedModelInventoryWarning(config, &fileResult.validationResult) - } - *validationResults = append(*validationResults, fileResult.validationResult) - writeMCPCompileProgress(config.MCPProgressFile, *validationResults) + stage := compilePipelineStage{compiler: compiler, config: config, stats: stats, results: validationResults} + if err := stage.compile(ctx, config.MarkdownFiles, true); err != nil { + return stage.workflows, err } - - workflowDir := "" if config.DryRun { - workflowDir = config.dryRunWorkflowDir + stage.batch.workflowDir = config.dryRunWorkflowDir } - strictGrantErr, batchToolErr := runBatchExternalTools(ctx, config, batchToolsOptions{ - workflowDir: workflowDir, - lockFilesForActionlint: lockFilesForActionlint, - lockFilesForZizmor: lockFilesForZizmor, - lockFilesForDirTools: lockFilesForDirTools, - lockFilesForSyft: lockFilesForSyft, - lockFilesForGrype: lockFilesForGrype, - lockFilesForGrant: lockFilesForGrant, - lockFilesForYamllint: lockFilesForYamllint, - lockFilesForShellcheck: lockFilesForShellcheck, - shellcheckResources: shellcheckResources, - }, stats, validationResults) + strictGrantErr, batchToolErr := runBatchExternalTools(ctx, config, stage.batch, stats, validationResults) + return stage.finishSpecific(ctx, strictGrantErr, batchToolErr) +} - if strictGrantErr != nil || batchToolErr != nil { - errorCount++ - } +func (stage *compilePipelineStage) finishSpecific(ctx context.Context, strictGrantErr, batchToolErr error) ([]*workflow.WorkflowData, error) { + compiler, config, stats, validationResults := stage.compiler, stage.config, stage.stats, stage.results + workflowDataList := stage.workflows // Get warning count from compiler stats.Warnings = compiler.GetWarningCount() @@ -252,7 +86,7 @@ func compileSpecificFiles( //nolint:largefunc // Orchestrates the full targeted // Post-processing if !config.NoEmit { - if err := runPostProcessing(ctx, compiler, workflowDataList, compiledLockFiles, config, compiledCount); err != nil { + if err := runPostProcessing(ctx, compiler, workflowDataList, stage.compiledLockFiles, config, stage.successes); err != nil { return workflowDataList, err } } @@ -264,24 +98,11 @@ func compileSpecificFiles( //nolint:largefunc // Orchestrates the full targeted return workflowDataList, err } - // Return error if any compilations failed - // Don't return the detailed error message here since it's already printed in the summary - // Returning a simple error prevents duplication in the output - if errorCount > 0 { - if strictGrantErr != nil { - return workflowDataList, strictGrantErr - } - if batchToolErr != nil { - return workflowDataList, batchToolErr - } - return workflowDataList, errors.New("compilation failed") - } - - return workflowDataList, developmentErr + return workflowDataList, compilationResultError(stage.failures, strictGrantErr, batchToolErr, developmentErr) } // compileAllFilesInDirectory compiles all workflow files in a directory -func compileAllFilesInDirectory( //nolint:largefunc // Orchestrates the full directory compile pipeline. +func compileAllFilesInDirectory( ctx context.Context, compiler *workflow.Compiler, config CompileConfig, @@ -289,36 +110,9 @@ func compileAllFilesInDirectory( //nolint:largefunc // Orchestrates the full dir stats *CompilationStats, validationResults *[]ValidationResult, ) ([]*workflow.WorkflowData, error) { - // Find git root for consistent behavior - gitRoot, err := gitutil.FindGitRoot() + gitRoot, workflowsDir, mdFiles, err := findDirectoryWorkflows(workflowDir, config.Verbose) if err != nil { - return nil, fmt.Errorf("compile without arguments requires being in a git repository: %w", err) - } - compileOrchestrationLog.Printf("Found git root: %s", gitRoot) - - // Compile all markdown files in the specified workflow directory - workflowsDir := filepath.Join(gitRoot, workflowDir) - if _, err := os.Stat(workflowsDir); errors.Is(err, fs.ErrNotExist) { - return nil, fmt.Errorf("the %s directory does not exist in git root (%s)", workflowDir, gitRoot) - } - - compileOrchestrationLog.Printf("Scanning for markdown files in %s", workflowsDir) - if config.Verbose { - fmt.Fprintln(os.Stderr, console.FormatInfoMessageStderr("Scanning for markdown files in "+workflowsDir)) - } - - // Find and filter markdown files (shared helper keeps logic in one place) - mdFiles, err := getMarkdownWorkflowFiles(workflowsDir) - if err != nil { - return nil, fmt.Errorf("failed to find markdown files: %w", err) - } - mdFiles, err = filterMarkdownFilesWithFrontmatter(mdFiles) - if err != nil { - return nil, fmt.Errorf("failed to filter markdown files: %w", err) - } - - if len(mdFiles) == 0 { - return nil, fmt.Errorf("no workflow markdown files found in %s (workflow files must start with a frontmatter opener on the first line)", workflowsDir) + return nil, err } if err := prepareDryRunScannerBaseline(ctx, &config, mdFiles, workflowsDir, compiler); err != nil { return nil, err @@ -333,7 +127,6 @@ func compileAllFilesInDirectory( //nolint:largefunc // Orchestrates the full dir compiler.SetBatchMode(batchMode) compiler.SetQuiet(batchMode) - // Handle purge logic: collect existing files before compilation var purgeData *purgeTrackingData if config.Purge { purgeData, err = collectPurgeData(workflowsDir, mdFiles, config.Verbose) @@ -342,153 +135,63 @@ func compileAllFilesInDirectory( //nolint:largefunc // Orchestrates the full dir } } - // Enable validation automatically when force-refresh-action-pins is used - // to verify all resolved action SHAs are valid - shouldValidate := config.Validate || config.ForceRefreshActionPins - if config.ForceRefreshActionPins && !config.Validate { - compileOrchestrationLog.Print("Automatically enabling action SHA validation due to --force-refresh-action-pins") + stage := compilePipelineStage{compiler: compiler, config: config, stats: stats, results: validationResults} + if err := stage.compile(ctx, mdFiles, false); err != nil { + return stage.workflows, err } + stage.batch.workflowDir = workflowsDir + if config.DryRun { + stage.batch.workflowDir = firstNonEmpty(config.dryRunWorkflowDir, workflowsDir) + } + strictGrantErr, batchToolErr := runBatchExternalTools(ctx, config, stage.batch, stats, validationResults) + return stage.finishDirectory(ctx, gitRoot, workflowsDir, mdFiles, purgeData, strictGrantErr, batchToolErr) +} - // Compile each file - var workflowDataList []*workflow.WorkflowData - var successCount int - var errorCount int - var lockFilesForActionlint []string - var lockFilesForZizmor []string - var lockFilesForDirTools []string // lock files for directory-based tools (poutine, runner-guard) - var lockFilesForSyft []string // lock files for syft container image SBOM scanning - var lockFilesForGrype []string // lock files for grype container image vulnerability scanning - var lockFilesForGrant []string // lock files for grant container image license scanning - var strictGrantErr error - var lockFilesForYamllint []string // lock files for yamllint YAML linter - var lockFilesForShellcheck []string // lock files for shellcheck run step linting - var shellcheckResources []workflow.ShellScriptResource - var workflowValidationResultIndexes []int - - for _, file := range mdFiles { - // Respect context cancellation between files (e.g. Ctrl+C) - select { - case <-ctx.Done(): - fmt.Fprintln(os.Stderr, console.FormatWarningMessageStderr("Operation cancelled")) - return workflowDataList, ctx.Err() - default: - } - - stats.Total++ - - // Compile regular workflow file (disable per-file security tools) - fileResult := compileWorkflowFile( - ctx, compiler, file, compileWorkflowFileOptions{ - verbose: config.Verbose, - jsonOutput: config.JSONOutput, - noEmit: config.NoEmit, - strict: config.Strict, - validate: shouldValidate, - failOnWarnings: config.DryRun, - // zizmor, poutine, actionlint disabled per-file (batched instead) - }, - ) +func findDirectoryWorkflows(workflowDir string, verbose bool) (string, string, []string, error) { + // Find git root for consistent behavior + gitRoot, err := gitutil.FindGitRoot() + if err != nil { + return "", "", nil, fmt.Errorf("compile without arguments requires being in a git repository: %w", err) + } + compileOrchestrationLog.Printf("Found git root: %s", gitRoot) - if !fileResult.success { - // Collect error messages from validation result - var errMsgs []string - for _, verr := range fileResult.validationResult.Errors { - errMsgs = append(errMsgs, verr.Message) - } - if len(errMsgs) == 0 { - errMsgs = []string{fallbackCompilationErrorMessage} - } - errorCount++ - stats.Errors += len(errMsgs) - trackWorkflowFailure(stats, file, len(errMsgs), errMsgs) - } else { - successCount++ - stats.Succeeded++ - if fileResult.workflowData != nil { - workflowDataList = append(workflowDataList, fileResult.workflowData) - workflowValidationResultIndexes = append(workflowValidationResultIndexes, len(*validationResults)) - } + // Compile all markdown files in the specified workflow directory + workflowsDir := filepath.Join(gitRoot, workflowDir) + if _, err := os.Stat(workflowsDir); errors.Is(err, fs.ErrNotExist) { + return "", "", nil, fmt.Errorf("the %s directory does not exist in git root (%s)", workflowDir, gitRoot) + } - // Collect lock files for batch security tools - if !config.NoEmit && fileResult.lockFile != "" { - if _, err := os.Stat(fileResult.lockFile); err == nil { - if config.Actionlint { - lockFilesForActionlint = append(lockFilesForActionlint, fileResult.lockFile) - } - if config.Zizmor { - lockFilesForZizmor = append(lockFilesForZizmor, fileResult.lockFile) - } - if config.Poutine || config.RunnerGuard { - lockFilesForDirTools = append(lockFilesForDirTools, fileResult.lockFile) - } - if config.Syft { - lockFilesForSyft = append(lockFilesForSyft, fileResult.lockFile) - } - if config.Grype { - lockFilesForGrype = append(lockFilesForGrype, fileResult.lockFile) - } - if config.Grant { - lockFilesForGrant = append(lockFilesForGrant, fileResult.lockFile) - } - if config.Yamllint { - lockFilesForYamllint = append(lockFilesForYamllint, fileResult.lockFile) - } - if config.shellcheckEnabled() { - lockFilesForShellcheck = append(lockFilesForShellcheck, fileResult.lockFile) - shellcheckResources = append(shellcheckResources, fileResult.workflowData.ShellScriptResources()...) - } - } - } - } + compileOrchestrationLog.Printf("Scanning for markdown files in %s", workflowsDir) + if verbose { + fmt.Fprintln(os.Stderr, console.FormatInfoMessageStderr("Scanning for markdown files in "+workflowsDir)) + } - *validationResults = append(*validationResults, fileResult.validationResult) - writeMCPCompileProgress(config.MCPProgressFile, *validationResults) + // Find and filter markdown files (shared helper keeps logic in one place) + mdFiles, err := getMarkdownWorkflowFiles(workflowsDir) + if err != nil { + return "", "", nil, fmt.Errorf("failed to find markdown files: %w", err) + } + mdFiles, err = filterMarkdownFilesWithFrontmatter(mdFiles) + if err != nil { + return "", "", nil, fmt.Errorf("failed to filter markdown files: %w", err) } - dryRunWorkflowDir := "" - if config.DryRun { - dryRunWorkflowDir = config.dryRunWorkflowDir + if len(mdFiles) == 0 { + return "", "", nil, fmt.Errorf("no workflow markdown files found in %s (workflow files must start with a frontmatter opener on the first line)", workflowsDir) } - strictGrantErr, batchToolErr := runBatchExternalTools(ctx, config, batchToolsOptions{ - workflowDir: firstNonEmpty(dryRunWorkflowDir, workflowsDir), - lockFilesForActionlint: lockFilesForActionlint, - lockFilesForZizmor: lockFilesForZizmor, - lockFilesForDirTools: lockFilesForDirTools, - lockFilesForSyft: lockFilesForSyft, - lockFilesForGrype: lockFilesForGrype, - lockFilesForGrant: lockFilesForGrant, - lockFilesForYamllint: lockFilesForYamllint, - lockFilesForShellcheck: lockFilesForShellcheck, - shellcheckResources: shellcheckResources, - }, stats, validationResults) + return gitRoot, workflowsDir, mdFiles, nil +} +func (stage *compilePipelineStage) finishDirectory(ctx context.Context, gitRoot, workflowsDir string, mdFiles []string, purgeData *purgeTrackingData, strictGrantErr, batchToolErr error) ([]*workflow.WorkflowData, error) { + compiler, config, stats, validationResults := stage.compiler, stage.config, stage.stats, stage.results + workflowDataList, successCount, errorCount := stage.workflows, stage.successes, stage.failures if strictGrantErr != nil || batchToolErr != nil { errorCount++ } - // Emit recommendation when many slash commands are present without centralized strategy. - displayCentralizedSlashCommandRecommendation(compiler, workflowDataList, config.JSONOutput) - - duplicateNameWarnings, err := appendDuplicateWorkflowNameWarnings(workflowDataList, workflowValidationResultIndexes, validationResults) - if err != nil { + if err := stage.reportDirectoryNotices(); err != nil { return workflowDataList, err } - if !config.JSONOutput { - for _, warning := range duplicateNameWarnings { - fmt.Fprintln(os.Stderr, console.FormatWarningMessageStderr(warning.Message)) - } - } - - // Get warning count from compiler - stats.Warnings = compiler.GetWarningCount() + len(duplicateNameWarnings) - - displayBatchCompilationNotices(compiler, config) - - // Display schedule warnings - displayScheduleWarnings(compiler, config.JSONOutput) - - // Display safe update warnings (emitted as prompts for the calling agent) - displaySafeUpdateWarnings(compiler, config.JSONOutput) if config.Verbose { fmt.Fprintln(os.Stderr, console.FormatSuccessMessageStderr(fmt.Sprintf("Successfully compiled %d out of %d workflow files", successCount, len(mdFiles)))) @@ -518,645 +221,18 @@ func compileAllFilesInDirectory( //nolint:largefunc // Orchestrates the full dir return workflowDataList, err } - // Return error if any compilations failed - if errorCount > 0 { - if strictGrantErr != nil { - return workflowDataList, strictGrantErr - } - if batchToolErr != nil { - return workflowDataList, batchToolErr - } - return workflowDataList, errors.New("compilation failed") - } - - return workflowDataList, developmentErr -} - -func writeMCPCompileProgress(progressPath string, results []ValidationResult) { - if progressPath == "" { - return - } - sanitizedResults := make([]ValidationResult, 0, len(results)) - for _, result := range results { - sanitizedErrors := make([]ValidationIssue, 0, len(result.Errors)) - for _, issue := range result.Errors { - issue.Message = boundMCPCompileDiagnostic(issue.Message) - sanitizedErrors = append(sanitizedErrors, issue) - } - result.Errors = sanitizedErrors - sanitizedWarnings := make([]ValidationIssue, 0, len(result.Warnings)) - for _, issue := range result.Warnings { - issue.Message = boundMCPCompileDiagnostic(issue.Message) - sanitizedWarnings = append(sanitizedWarnings, issue) - } - result.Warnings = sanitizedWarnings - sanitizedResults = append(sanitizedResults, result) - } - output, err := formatValidationOutput(sanitizedResults) - if err != nil { - compileOrchestrationLog.Printf("Failed to format MCP compile progress: %v", err) - return - } - if err := writeSensitiveFile(progressPath, []byte(output)); err != nil { - compileOrchestrationLog.Printf("Failed to publish MCP compile progress: %v", err) - } -} - -type batchToolsOptions struct { - reportResult func(string, int, error) - filterResult func(string, error) error - dryRunZizmor bool - workflowDir string - lockFilesForActionlint []string - lockFilesForZizmor []string - lockFilesForDirTools []string - lockFilesForSyft []string - lockFilesForGrype []string - lockFilesForGrant []string - lockFilesForYamllint []string - lockFilesForShellcheck []string - shellcheckResources []workflow.ShellScriptResource -} - -func (opts batchToolsOptions) recordResult(tool string, inputs int, err error) error { - if opts.filterResult != nil { - err = opts.filterResult(tool, err) - } - if opts.reportResult != nil { - opts.reportResult(tool, inputs, err) - } - return err -} - -// runBatchExternalTools executes all enabled batch analysis tools sequentially without short-circuiting -// when individual tools report findings or errors. -func runBatchLinters(ctx context.Context, config CompileConfig, opts batchToolsOptions) error { - var firstErr error - - if config.Actionlint && !config.NoEmit { - if err := ctx.Err(); err != nil { - return err - } - err := runBatchActionlintOnFiles(ctx, opts.lockFilesForActionlint, config.Verbose && !config.JSONOutput, config.Strict) - err = opts.recordResult("actionlint", len(opts.lockFilesForActionlint), err) - if err != nil { - if config.Strict && firstErr == nil { - firstErr = err - } - } - } - - if config.Zizmor && !config.NoEmit { - if err := ctx.Err(); err != nil { - return err - } - var err error - if opts.dryRunZizmor || config.DryRun && config.dryRunBaseline != nil { - err = runBatchDryRunZizmorOnFiles(opts.lockFilesForZizmor, config.Verbose && !config.JSONOutput, config.Strict) - } else { - err = runBatchZizmorOnFiles(opts.lockFilesForZizmor, config.Verbose && !config.JSONOutput, config.Strict) - } - err = opts.recordResult("zizmor", len(opts.lockFilesForZizmor), err) - if err != nil { - if firstErr == nil { - firstErr = err - } - } - } - - return firstErr -} - -func runBatchDirScanners(ctx context.Context, config CompileConfig, opts batchToolsOptions) error { - var firstErr error - - if config.Poutine && !config.NoEmit { - if err := ctx.Err(); err != nil { - return err - } - workflowDir := opts.workflowDir - if workflowDir == "" && len(opts.lockFilesForDirTools) > 0 { - workflowDir = filepath.Dir(opts.lockFilesForDirTools[0]) - } - err := runBatchDirectoryTool("poutine", workflowDir, config.Verbose && !config.JSONOutput, config.Strict, runBatchPoutineOnDirectory) - err = opts.recordResult("poutine", len(opts.lockFilesForDirTools), err) - if err != nil { - if config.Strict && firstErr == nil { - firstErr = err - } - } - } - - if config.RunnerGuard && !config.NoEmit { - if err := ctx.Err(); err != nil { - return err - } - workflowDir := opts.workflowDir - if workflowDir == "" && len(opts.lockFilesForDirTools) > 0 { - workflowDir = filepath.Dir(opts.lockFilesForDirTools[0]) - } - err := runBatchDirectoryTool("runner-guard", workflowDir, config.Verbose && !config.JSONOutput, config.Strict, runBatchRunnerGuardOnDirectory) - err = opts.recordResult("runner-guard", len(opts.lockFilesForDirTools), err) - if err != nil { - if config.Strict && firstErr == nil { - firstErr = err - } - } - } - - return firstErr -} - -func runBatchContainerScanners( - ctx context.Context, - config CompileConfig, - opts batchToolsOptions, - stats *CompilationStats, - validationResults *[]ValidationResult, -) (strictGrantErr error, containerErr error) { - if config.Syft && !config.NoEmit { - if err := ctx.Err(); err != nil { - return nil, err - } - err := runBatchSyftOnLockFiles(opts.lockFilesForSyft, config.Verbose && !config.JSONOutput, config.Strict) - err = opts.recordResult("syft", len(opts.lockFilesForSyft), err) - if err != nil { - if config.Strict && containerErr == nil { - containerErr = err - } - } - } - - if config.Grype && !config.NoEmit { - if err := ctx.Err(); err != nil { - return nil, err - } - err := runBatchGrypeOnLockFiles(opts.lockFilesForGrype, config.Verbose && !config.JSONOutput, config.Strict) - err = opts.recordResult("grype", len(opts.lockFilesForGrype), err) - if err != nil { - if config.Strict && containerErr == nil { - containerErr = err - } - } - } - - if config.Grant && !config.NoEmit { - if err := ctx.Err(); err != nil { - return nil, err - } - err := runBatchGrantOnLockFiles(opts.lockFilesForGrant, config.Verbose && !config.JSONOutput, config.Strict) - err = opts.recordResult("grant", len(opts.lockFilesForGrant), err) - if err != nil { - if config.Strict { - if !config.DryRun { - stats.Errors++ - *validationResults = append(*validationResults, ValidationResult{ - Workflow: "grant", - Valid: false, - Errors: []ValidationIssue{{ - Type: "grant_error", - Message: err.Error(), - }}, - }) - } - if strictGrantErr == nil { - strictGrantErr = err - } - } - } - } - - return strictGrantErr, containerErr -} - -func runBatchScriptLinters(ctx context.Context, config CompileConfig, opts batchToolsOptions) error { - var firstErr error - - if config.Yamllint && !config.NoEmit { - if err := ctx.Err(); err != nil { - return err - } - err := runBatchYamllintOnFiles(opts.lockFilesForYamllint, config.Verbose && !config.JSONOutput, config.Strict) - err = opts.recordResult("yamllint", len(opts.lockFilesForYamllint), err) - if err != nil { - if config.Strict && firstErr == nil { - firstErr = err - } - } - } - - if config.shellcheckEnabled() && !config.NoEmit { - if err := ctx.Err(); err != nil { - return err - } - err := runBatchShellcheckOnLockFilesAndResources(ctx, opts.lockFilesForShellcheck, opts.shellcheckResources, config.Verbose && !config.JSONOutput, config.Strict) - err = opts.recordResult("shellcheck", len(opts.lockFilesForShellcheck)+len(opts.shellcheckResources), err) - if err != nil { - if config.Strict && firstErr == nil { - firstErr = err - } - } - } - - return firstErr -} - -func runBatchExternalTools( - ctx context.Context, - config CompileConfig, - opts batchToolsOptions, - stats *CompilationStats, - validationResults *[]ValidationResult, -) (strictGrantErr error, batchToolErr error) { - scannerResults := make(map[string]error) - ctx = context.WithValue(ctx, compileScannerReporterKey{}, func(tool string, err error) { - scannerResults[tool] = err - }) - previousReport := opts.reportResult - if config.DryRun { - if config.dryRunBaseline != nil { - opts.filterResult = func(tool string, err error) error { - diff, filteredErr := config.dryRunBaseline.filter(tool, err) - if config.dryRunReport != nil && diff != nil { - check := config.dryRunReport.Scanners[tool] - check.Differential = diff - config.dryRunReport.Scanners[tool] = check - } - return filteredErr - } - } - opts.reportResult = func(tool string, inputs int, err error) { - recordDryRunScannerResult(config.dryRunReport, tool, inputs, err) - appendDryRunScannerResult(tool, scannerResults[tool], err, stats, validationResults) - if previousReport != nil { - previousReport(tool, inputs, err) - } - } - } else { - opts.reportResult = func(tool string, inputs int, err error) { - diagnostics, reported := scannerResults[tool] - if !reported { - diagnostics = err - } - // Grant already emits its strict batch result. - if tool != "grant" || !config.Strict { - appendCompileScannerResult(tool, diagnostics, config.Strict && err != nil, stats, validationResults) - } - if previousReport != nil { - previousReport(tool, inputs, err) - } - } - } - if err := runBatchLinters(ctx, config, opts); err != nil && batchToolErr == nil { - batchToolErr = err - } - - if err := runBatchDirScanners(ctx, config, opts); err != nil && batchToolErr == nil { - batchToolErr = err - } - - sGrantErr, containerErr := runBatchContainerScanners(ctx, config, opts, stats, validationResults) - if sGrantErr != nil && strictGrantErr == nil { - strictGrantErr = sGrantErr - } - if containerErr != nil && batchToolErr == nil { - batchToolErr = containerErr - } - - if err := runBatchScriptLinters(ctx, config, opts); err != nil && batchToolErr == nil { - batchToolErr = err - } - - return strictGrantErr, batchToolErr -} - -func appendDuplicateWorkflowNameWarnings(workflowDataList []*workflow.WorkflowData, validationResultIndexes []int, validationResults *[]ValidationResult) ([]ValidationIssue, error) { - workflowIDsByName := make(map[string][]string) - for _, workflowData := range workflowDataList { - if workflowData != nil && workflowData.Name != "" { - workflowIDsByName[workflowData.Name] = append(workflowIDsByName[workflowData.Name], workflowData.WorkflowID) - } - } - - warningsByName := make(map[string]ValidationIssue) - for name, workflowIDs := range workflowIDsByName { - if len(workflowIDs) > 1 { - slices.Sort(workflowIDs) - warningsByName[name] = ValidationIssue{ - Type: "duplicate_workflow_name", - Message: fmt.Sprintf("Duplicate workflow name %q in %s; GitHub displays them as the same agentic workflow", name, strings.Join(workflowIDs, ", ")), - } - } - } - - var warnings []ValidationIssue - reportedNames := make(map[string]struct{}) - for workflowIndex, workflowData := range workflowDataList { - if workflowData == nil || workflowData.Name == "" { - continue - } - - warning, duplicate := warningsByName[workflowData.Name] - if !duplicate { - continue - } - - if _, reported := reportedNames[workflowData.Name]; !reported { - warnings = append(warnings, warning) - reportedNames[workflowData.Name] = struct{}{} - } - - if workflowIndex < 0 || workflowIndex >= len(validationResultIndexes) { - return nil, fmt.Errorf("missing validation result index for workflow %q", workflowData.WorkflowID) - } - resultIndex := validationResultIndexes[workflowIndex] - results := *validationResults - if resultIndex < 0 || resultIndex >= len(results) { - return nil, fmt.Errorf("validation result index %d for workflow %q is out of range", resultIndex, workflowData.WorkflowID) - } - result := &results[resultIndex] - result.Warnings = append(result.Warnings, warning) - } - - return warnings, nil -} - -func displayBatchCompilationNotices(compiler *workflow.Compiler, config CompileConfig) { - if config.JSONOutput || config.Verbose { - return - } - - featureUsage := compiler.GetExperimentalFeatureUsage() - if len(featureUsage) > 0 { - type featureCount struct { - name string - count int - } - features := make([]featureCount, 0, len(featureUsage)) - for message, count := range featureUsage { - features = append(features, featureCount{ - name: strings.TrimPrefix(message, "Using experimental feature: "), - count: count, - }) - } - slices.SortFunc(features, func(a, b featureCount) int { - if a.count != b.count { - return cmp.Compare(b.count, a.count) - } - return cmp.Compare(a.name, b.name) - }) - - fmt.Fprintln(os.Stderr, console.FormatWarningMessageStderr("Experimental features in use:")) - for _, feature := range features { - fmt.Fprintln(os.Stderr, console.FormatListItemStderr(fmt.Sprintf("%s: %s", feature.name, formatWorkflowCount(feature.count)))) - } - } - - if count := compiler.DefaultModelRoutingWorkflowCount(); count > 0 { - fmt.Fprintln(os.Stderr, console.FormatInfoMessageStderr(workflow.DefaultModelRoutingBatchNotice(count))) - } - - if compiler.CopilotRequestsTipNeeded() { - fmt.Fprintln(os.Stderr, console.FormatInfoMessageStderr( - "Copilot token-based inference may be available: add permissions.copilot-requests: write. "+ - "To suppress this tip when using a PAT, set permissions.copilot-requests: none. "+ - "See https://github.github.com/gh-aw/reference/billing/", - )) - } -} - -// purgeTrackingData holds data needed for purge operations -type purgeTrackingData struct { - existingLockFiles []string - existingInvalidFiles []string - expectedLockFiles []string -} - -// collectPurgeData collects existing files for purge operations -func collectPurgeData(workflowsDir string, mdFiles []string, verbose bool) (*purgeTrackingData, error) { - return collectPurgeDataWithPatterns(workflowsDir, mdFiles, verbose, "*.lock.yml", "*.invalid.yml") + return workflowDataList, compilationResultError(stage.failures, strictGrantErr, batchToolErr, developmentErr) } -// collectPurgeDataWithPatterns is the testable implementation of collectPurgeData. -// lockPattern and invalidPattern are appended to workflowsDir for the glob calls. -func collectPurgeDataWithPatterns(workflowsDir string, mdFiles []string, verbose bool, lockPattern, invalidPattern string) (*purgeTrackingData, error) { - data := &purgeTrackingData{} - - // Find all existing files - var err error - data.existingLockFiles, err = filepath.Glob(filepath.Join(workflowsDir, lockPattern)) - if err != nil { - return nil, fmt.Errorf("failed to glob existing .lock.yml files in %s: %w", workflowsDir, err) - } - data.existingInvalidFiles, err = filepath.Glob(filepath.Join(workflowsDir, invalidPattern)) - if err != nil { - return nil, fmt.Errorf("failed to glob existing .invalid.yml files in %s: %w", workflowsDir, err) - } - - // Create expected files list - for _, mdFile := range mdFiles { - lockFile := stringutil.MarkdownToLockFile(mdFile) - data.expectedLockFiles = append(data.expectedLockFiles, lockFile) - } - - if verbose { - if len(data.existingLockFiles) > 0 { - fmt.Fprintln(os.Stderr, console.FormatInfoMessageStderr(fmt.Sprintf("Found %d existing .lock.yml files", len(data.existingLockFiles)))) - } - if len(data.existingInvalidFiles) > 0 { - fmt.Fprintln(os.Stderr, console.FormatInfoMessageStderr(fmt.Sprintf("Found %d existing .invalid.yml files", len(data.existingInvalidFiles)))) - } +func compilationResultError(failures int, strictGrantErr, batchToolErr, developmentErr error) error { + if strictGrantErr != nil { + return strictGrantErr } - - return data, nil -} - -// runPurgeOperations runs all purge operations -func runPurgeOperations(workflowsDir string, data *purgeTrackingData, verbose bool) { - // Errors from purge operations are logged but don't stop compilation - _ = purgeOrphanedLockFiles(workflowsDir, data.expectedLockFiles, verbose) - _ = purgeInvalidFiles(workflowsDir, verbose) -} - -// runPostProcessing runs post-processing for specific files compilation -func runPostProcessing( - ctx context.Context, - compiler *workflow.Compiler, - workflowDataList []*workflow.WorkflowData, - compiledLockFiles []string, - config CompileConfig, - successCount int, -) error { - // Get action cache - actionCache := compiler.GetSharedActionCache() - - // Update .gitattributes (errors are non-fatal) - _ = updateGitAttributes(successCount, actionCache, config.Verbose) - - // Generate Dependabot manifests and reconcile compiler-managed ignore entries if requested. - if config.Dependabot && !config.NoEmit { - if gitRoot, err := gitutil.FindGitRoot(); err == nil { - absWorkflowDir := filepath.Join(gitRoot, config.WorkflowDir) - if err := generateDependabotManifestsWrapper(ctx, compiler, workflowDataList, absWorkflowDir, config.ForceOverwrite, config.Strict); err != nil { - if config.Strict { - return err - } - } - if err := compiler.ReconcileManagedDependabotIgnoresInRepo(gitRoot); err != nil { - if config.Strict { - return err - } - fmt.Fprintln(os.Stderr, console.FormatWarningMessageStderr(fmt.Sprintf("Failed to reconcile compiler-managed Dependabot ignore entries: %v", err))) - } - } + if batchToolErr != nil { + return batchToolErr } - - // Reconcile the implicit action-failure expiry marker so specific-file - // compiles agree with what a full directory compile would produce. - // Maintenance workflow generation itself is skipped for specific-file - // compiles because it requires parsing every workflow in the directory to - // check for expires fields; only reconcile when using the default - // workflow directory (custom --dir compiles and --no-emit compiles are - // left untouched). - if !config.NoEmit && config.usesDefaultWorkflowDir() && len(compiledLockFiles) > 0 { - if gitRoot, err := gitutil.FindGitRoot(); err == nil { - absWorkflowDir := getAbsoluteWorkflowDir(getWorkflowsDir(), gitRoot) - repoConfig, err := workflow.LoadRepoConfig(gitRoot) - if err != nil { - repoConfig = nil - } - workflow.DisableDefaultActionFailureExpiryMarkersIfUnenforced(compiledLockFiles, absWorkflowDir, repoConfig) - } + if failures > 0 { + return errors.New("compilation failed") } - - // Prune stale gh-aw-actions entries before saving - pruneStaleActionCacheEntries(compiler, actionCache) - - // Save action cache (errors are logged but non-fatal) - _ = saveActionCache(actionCache, config.Verbose) - - return nil -} - -// runPostProcessingForDirectory runs post-processing for directory compilation -func runPostProcessingForDirectory( - ctx context.Context, - compiler *workflow.Compiler, - workflowDataList []*workflow.WorkflowData, - config CompileConfig, - workflowsDir string, - gitRoot string, - successCount int, - errorCount int, -) error { - // Get action cache - actionCache := compiler.GetSharedActionCache() - - // Update .gitattributes (errors are non-fatal) - _ = updateGitAttributes(successCount, actionCache, config.Verbose) - - // Generate Dependabot manifests if requested - if config.Dependabot && !config.NoEmit { - absWorkflowDir := getAbsoluteWorkflowDir(workflowsDir, gitRoot) - if err := generateDependabotManifestsWrapper(ctx, compiler, workflowDataList, absWorkflowDir, config.ForceOverwrite, config.Strict); err != nil { - if config.Strict { - return err - } - } - } - - // Reconcile compiler-managed Dependabot ignore entries for compiler-emitted action refs. - if config.Dependabot && !config.NoEmit { - if err := compiler.ReconcileManagedDependabotIgnoresInRepo(gitRoot); err != nil { - if config.Strict { - return err - } - fmt.Fprintln(os.Stderr, console.FormatWarningMessageStderr(fmt.Sprintf("Failed to reconcile compiler-managed Dependabot ignore entries: %v", err))) - } - } - - // Generate maintenance workflow if needed. - // Skip maintenance workflow generation when using custom --dir option. - // Keep invoking generators for empty workflowDataList so stale generated files are cleaned up. - if !config.NoEmit && config.usesDefaultWorkflowDir() { - absWorkflowDir := getAbsoluteWorkflowDir(workflowsDir, gitRoot) - if err := generateMaintenanceWorkflowWrapper(ctx, compiler, workflowDataList, absWorkflowDir, gitRoot, config.Verbose, config.Strict, config.NoLogo); err != nil { - if config.Strict { - return err - } - } - if err := generateWorkQueueEventWorkflowWrapper(ctx, workflowDataList, absWorkflowDir, gitRoot, config.Strict, config.NoLogo); err != nil { - if config.Strict { - return err - } - } - if err := generateCentralSlashCommandWorkflowWrapper(ctx, workflowDataList, absWorkflowDir, gitRoot, config.Strict, config.NoLogo); err != nil { - if config.Strict { - return err - } - } - } - - // Prune stale gh-aw-actions entries before saving - pruneStaleActionCacheEntries(compiler, actionCache) - - // Prune orphaned entries — entries for action versions no longer referenced - // by any workflow in the directory (e.g. old pins left after a version bump). - // Safe to call only after a full-directory compilation with zero compile errors. - pruneOrphanedActionCacheEntries(compiler, actionCache, errorCount) - - // Save action cache (errors are logged but non-fatal) - _ = saveActionCache(actionCache, config.Verbose) - - return nil -} - -// outputResults outputs compilation results in the requested format -func outputResults( - stats *CompilationStats, - validationResults *[]ValidationResult, - config CompileConfig, -) error { - if !config.DryRun && len(config.modelValidationWarnings) > 0 { - issues := modelInventoryWarnings(config) - *validationResults = append(*validationResults, ValidationResult{ - Scope: "batch", Workflow: "models", Valid: true, Errors: []ValidationIssue{}, Warnings: issues, - }) - stats.Warnings += len(issues) - if !config.JSONOutput { - for _, issue := range issues { - fmt.Fprintln(os.Stderr, console.FormatWarningMessageStderr(issue.Message)) - } - } - } - appendDryRunCompileReport(config, stats, validationResults) - - // Collect and display stats if requested - if config.Stats && !config.NoEmit && !config.JSONOutput { - var statsList []*WorkflowStats - if len(config.MarkdownFiles) > 0 { - statsList = collectWorkflowStatisticsWrapper(config.MarkdownFiles) - } - displayStatsTable(statsList) - displayScheduleCalendar(statsList) - } - - // Output JSON if requested - if config.JSONOutput { - jsonStr, err := formatValidationOutput(*validationResults) - if err != nil { - return err - } - fmt.Fprintln(os.Stdout, jsonStr) - } else if !config.Stats { - // Print summary for text output (skip if stats mode) - printCompilationSummary(stats, config.ShowAllErrors) - } - - // Display actionlint summary if enabled - if config.Actionlint && !config.NoEmit && !config.JSONOutput { - displayActionlintSummary() - } - - return nil + return developmentErr } diff --git a/pkg/cli/compile_pipeline_batch_tools.go b/pkg/cli/compile_pipeline_batch_tools.go new file mode 100644 index 00000000000..6cc64d004f2 --- /dev/null +++ b/pkg/cli/compile_pipeline_batch_tools.go @@ -0,0 +1,295 @@ +package cli + +import ( + "context" + "path/filepath" + + "github.com/github/gh-aw/pkg/workflow" +) + +// Batch tool entry points are exposed as package-level function variables so +// tests can override them to verify the batch pipeline invokes every enabled +// scanner in order, without short-circuiting, and without depending on the +// underlying external tool binaries/Docker images being available. +var ( + runBatchActionlintOnFiles = RunActionlintOnFiles + runBatchZizmorOnFiles = RunZizmorOnFiles + runBatchDryRunZizmorOnFiles = func(files []string, verbose, strict bool) error { + return runZizmorOnFilesWithOptions(files, verbose, strict, zizmorResultOptions{dryRun: true}) + } + runBatchPoutineOnDirectory = RunPoutineOnDirectory + runBatchRunnerGuardOnDirectory = RunRunnerGuardOnDirectory + runBatchSyftOnLockFiles = RunSyftOnLockFiles + runBatchGrypeOnLockFiles = RunGrypeOnLockFiles + runBatchGrantOnLockFiles = RunGrantOnLockFiles + runBatchYamllintOnFiles = RunYamllintOnFiles + runBatchShellcheckOnLockFilesAndResources = RunShellcheckOnLockFilesAndResources +) + +type batchToolsOptions struct { + reportResult func(string, int, error) + filterResult func(string, error) error + dryRunZizmor bool + workflowDir string + lockFilesForActionlint []string + lockFilesForZizmor []string + lockFilesForDirTools []string + lockFilesForSyft []string + lockFilesForGrype []string + lockFilesForGrant []string + lockFilesForYamllint []string + lockFilesForShellcheck []string + shellcheckResources []workflow.ShellScriptResource +} + +func (opts batchToolsOptions) recordResult(tool string, inputs int, err error) error { + if opts.filterResult != nil { + err = opts.filterResult(tool, err) + } + if opts.reportResult != nil { + opts.reportResult(tool, inputs, err) + } + return err +} + +// runBatchExternalTools executes all enabled batch analysis tools sequentially without short-circuiting +// when individual tools report findings or errors. +func runBatchLinters(ctx context.Context, config CompileConfig, opts batchToolsOptions) error { + var firstErr error + + if config.Actionlint && !config.NoEmit { + if err := ctx.Err(); err != nil { + return err + } + err := runBatchActionlintOnFiles(ctx, opts.lockFilesForActionlint, config.Verbose && !config.JSONOutput, config.Strict) + err = opts.recordResult("actionlint", len(opts.lockFilesForActionlint), err) + if err != nil { + if config.Strict && firstErr == nil { + firstErr = err + } + } + } + + if config.Zizmor && !config.NoEmit { + if err := ctx.Err(); err != nil { + return err + } + var err error + if opts.dryRunZizmor || config.DryRun && config.dryRunBaseline != nil { + err = runBatchDryRunZizmorOnFiles(opts.lockFilesForZizmor, config.Verbose && !config.JSONOutput, config.Strict) + } else { + err = runBatchZizmorOnFiles(opts.lockFilesForZizmor, config.Verbose && !config.JSONOutput, config.Strict) + } + err = opts.recordResult("zizmor", len(opts.lockFilesForZizmor), err) + if err != nil { + if firstErr == nil { + firstErr = err + } + } + } + + return firstErr +} + +func runBatchDirScanners(ctx context.Context, config CompileConfig, opts batchToolsOptions) error { + var firstErr error + + if config.Poutine && !config.NoEmit { + if err := ctx.Err(); err != nil { + return err + } + workflowDir := opts.workflowDir + if workflowDir == "" && len(opts.lockFilesForDirTools) > 0 { + workflowDir = filepath.Dir(opts.lockFilesForDirTools[0]) + } + err := runBatchDirectoryTool("poutine", workflowDir, config.Verbose && !config.JSONOutput, config.Strict, runBatchPoutineOnDirectory) + err = opts.recordResult("poutine", len(opts.lockFilesForDirTools), err) + if err != nil { + if config.Strict && firstErr == nil { + firstErr = err + } + } + } + + if config.RunnerGuard && !config.NoEmit { + if err := ctx.Err(); err != nil { + return err + } + workflowDir := opts.workflowDir + if workflowDir == "" && len(opts.lockFilesForDirTools) > 0 { + workflowDir = filepath.Dir(opts.lockFilesForDirTools[0]) + } + err := runBatchDirectoryTool("runner-guard", workflowDir, config.Verbose && !config.JSONOutput, config.Strict, runBatchRunnerGuardOnDirectory) + err = opts.recordResult("runner-guard", len(opts.lockFilesForDirTools), err) + if err != nil { + if config.Strict && firstErr == nil { + firstErr = err + } + } + } + + return firstErr +} + +func runBatchContainerScanners( + ctx context.Context, + config CompileConfig, + opts batchToolsOptions, + stats *CompilationStats, + validationResults *[]ValidationResult, +) (strictGrantErr error, containerErr error) { + if config.Syft && !config.NoEmit { + if err := ctx.Err(); err != nil { + return nil, err + } + err := runBatchSyftOnLockFiles(opts.lockFilesForSyft, config.Verbose && !config.JSONOutput, config.Strict) + err = opts.recordResult("syft", len(opts.lockFilesForSyft), err) + if err != nil { + if config.Strict && containerErr == nil { + containerErr = err + } + } + } + + if config.Grype && !config.NoEmit { + if err := ctx.Err(); err != nil { + return nil, err + } + err := runBatchGrypeOnLockFiles(opts.lockFilesForGrype, config.Verbose && !config.JSONOutput, config.Strict) + err = opts.recordResult("grype", len(opts.lockFilesForGrype), err) + if err != nil { + if config.Strict && containerErr == nil { + containerErr = err + } + } + } + + if config.Grant && !config.NoEmit { + if err := ctx.Err(); err != nil { + return nil, err + } + err := runBatchGrantOnLockFiles(opts.lockFilesForGrant, config.Verbose && !config.JSONOutput, config.Strict) + err = opts.recordResult("grant", len(opts.lockFilesForGrant), err) + if err != nil { + if config.Strict { + if !config.DryRun { + stats.Errors++ + *validationResults = append(*validationResults, ValidationResult{ + Workflow: "grant", + Valid: false, + Errors: []ValidationIssue{{ + Type: "grant_error", + Message: err.Error(), + }}, + }) + } + if strictGrantErr == nil { + strictGrantErr = err + } + } + } + } + + return strictGrantErr, containerErr +} + +func runBatchScriptLinters(ctx context.Context, config CompileConfig, opts batchToolsOptions) error { + var firstErr error + + if config.Yamllint && !config.NoEmit { + if err := ctx.Err(); err != nil { + return err + } + err := runBatchYamllintOnFiles(opts.lockFilesForYamllint, config.Verbose && !config.JSONOutput, config.Strict) + err = opts.recordResult("yamllint", len(opts.lockFilesForYamllint), err) + if err != nil { + if config.Strict && firstErr == nil { + firstErr = err + } + } + } + + if config.shellcheckEnabled() && !config.NoEmit { + if err := ctx.Err(); err != nil { + return err + } + err := runBatchShellcheckOnLockFilesAndResources(ctx, opts.lockFilesForShellcheck, opts.shellcheckResources, config.Verbose && !config.JSONOutput, config.Strict) + err = opts.recordResult("shellcheck", len(opts.lockFilesForShellcheck)+len(opts.shellcheckResources), err) + if err != nil { + if config.Strict && firstErr == nil { + firstErr = err + } + } + } + + return firstErr +} + +func runBatchExternalTools( + ctx context.Context, + config CompileConfig, + opts batchToolsOptions, + stats *CompilationStats, + validationResults *[]ValidationResult, +) (strictGrantErr error, batchToolErr error) { + scannerResults := make(map[string]error) + ctx = context.WithValue(ctx, compileScannerReporterKey{}, func(tool string, err error) { + scannerResults[tool] = err + }) + previousReport := opts.reportResult + if config.DryRun { + if config.dryRunBaseline != nil { + opts.filterResult = func(tool string, err error) error { + diff, filteredErr := config.dryRunBaseline.filter(tool, err) + if config.dryRunReport != nil && diff != nil { + check := config.dryRunReport.Scanners[tool] + check.Differential = diff + config.dryRunReport.Scanners[tool] = check + } + return filteredErr + } + } + opts.reportResult = func(tool string, inputs int, err error) { + recordDryRunScannerResult(config.dryRunReport, tool, inputs, err) + appendDryRunScannerResult(tool, scannerResults[tool], err, stats, validationResults) + if previousReport != nil { + previousReport(tool, inputs, err) + } + } + } else { + opts.reportResult = func(tool string, inputs int, err error) { + diagnostics, reported := scannerResults[tool] + if !reported { + diagnostics = err + } + // Grant already emits its strict batch result. + if tool != "grant" || !config.Strict { + appendCompileScannerResult(tool, diagnostics, config.Strict && err != nil, stats, validationResults) + } + if previousReport != nil { + previousReport(tool, inputs, err) + } + } + } + if err := runBatchLinters(ctx, config, opts); err != nil && batchToolErr == nil { + batchToolErr = err + } + + if err := runBatchDirScanners(ctx, config, opts); err != nil && batchToolErr == nil { + batchToolErr = err + } + + sGrantErr, containerErr := runBatchContainerScanners(ctx, config, opts, stats, validationResults) + if sGrantErr != nil && strictGrantErr == nil { + strictGrantErr = sGrantErr + } + if containerErr != nil && batchToolErr == nil { + batchToolErr = containerErr + } + + if err := runBatchScriptLinters(ctx, config, opts); err != nil && batchToolErr == nil { + batchToolErr = err + } + + return strictGrantErr, batchToolErr +} diff --git a/pkg/cli/compile_pipeline_notices.go b/pkg/cli/compile_pipeline_notices.go new file mode 100644 index 00000000000..057709e830a --- /dev/null +++ b/pkg/cli/compile_pipeline_notices.go @@ -0,0 +1,155 @@ +package cli + +import ( + "cmp" + "fmt" + "os" + "slices" + "strings" + + "github.com/github/gh-aw/pkg/console" + "github.com/github/gh-aw/pkg/workflow" +) + +func (stage *compilePipelineStage) reportDirectoryNotices() error { + displayCentralizedSlashCommandRecommendation(stage.compiler, stage.workflows, stage.config.JSONOutput) + warnings, err := appendDuplicateWorkflowNameWarnings(stage.workflows, stage.resultIndexes, stage.results) + if err != nil { + return err + } + if !stage.config.JSONOutput { + for _, warning := range warnings { + fmt.Fprintln(os.Stderr, console.FormatWarningMessageStderr(warning.Message)) + } + } + stage.stats.Warnings = stage.compiler.GetWarningCount() + len(warnings) + displayBatchCompilationNotices(stage.compiler, stage.config) + displayScheduleWarnings(stage.compiler, stage.config.JSONOutput) + displaySafeUpdateWarnings(stage.compiler, stage.config.JSONOutput) + return nil +} + +func writeMCPCompileProgress(progressPath string, results []ValidationResult) { + if progressPath == "" { + return + } + sanitizedResults := make([]ValidationResult, 0, len(results)) + for _, result := range results { + sanitizedErrors := make([]ValidationIssue, 0, len(result.Errors)) + for _, issue := range result.Errors { + issue.Message = boundMCPCompileDiagnostic(issue.Message) + sanitizedErrors = append(sanitizedErrors, issue) + } + result.Errors = sanitizedErrors + sanitizedWarnings := make([]ValidationIssue, 0, len(result.Warnings)) + for _, issue := range result.Warnings { + issue.Message = boundMCPCompileDiagnostic(issue.Message) + sanitizedWarnings = append(sanitizedWarnings, issue) + } + result.Warnings = sanitizedWarnings + sanitizedResults = append(sanitizedResults, result) + } + output, err := formatValidationOutput(sanitizedResults) + if err != nil { + compileOrchestrationLog.Printf("Failed to format MCP compile progress: %v", err) + return + } + if err := writeSensitiveFile(progressPath, []byte(output)); err != nil { + compileOrchestrationLog.Printf("Failed to publish MCP compile progress: %v", err) + } +} + +func appendDuplicateWorkflowNameWarnings(workflowDataList []*workflow.WorkflowData, validationResultIndexes []int, validationResults *[]ValidationResult) ([]ValidationIssue, error) { + workflowIDsByName := make(map[string][]string) + for _, workflowData := range workflowDataList { + if workflowData != nil && workflowData.Name != "" { + workflowIDsByName[workflowData.Name] = append(workflowIDsByName[workflowData.Name], workflowData.WorkflowID) + } + } + + warningsByName := make(map[string]ValidationIssue) + for name, workflowIDs := range workflowIDsByName { + if len(workflowIDs) > 1 { + slices.Sort(workflowIDs) + warningsByName[name] = ValidationIssue{ + Type: "duplicate_workflow_name", + Message: fmt.Sprintf("Duplicate workflow name %q in %s; GitHub displays them as the same agentic workflow", name, strings.Join(workflowIDs, ", ")), + } + } + } + + var warnings []ValidationIssue + reportedNames := make(map[string]struct{}) + for workflowIndex, workflowData := range workflowDataList { + if workflowData == nil || workflowData.Name == "" { + continue + } + + warning, duplicate := warningsByName[workflowData.Name] + if !duplicate { + continue + } + + if _, reported := reportedNames[workflowData.Name]; !reported { + warnings = append(warnings, warning) + reportedNames[workflowData.Name] = struct{}{} + } + + if workflowIndex < 0 || workflowIndex >= len(validationResultIndexes) { + return nil, fmt.Errorf("missing validation result index for workflow %q", workflowData.WorkflowID) + } + resultIndex := validationResultIndexes[workflowIndex] + results := *validationResults + if resultIndex < 0 || resultIndex >= len(results) { + return nil, fmt.Errorf("validation result index %d for workflow %q is out of range", resultIndex, workflowData.WorkflowID) + } + result := &results[resultIndex] + result.Warnings = append(result.Warnings, warning) + } + + return warnings, nil +} + +func displayBatchCompilationNotices(compiler *workflow.Compiler, config CompileConfig) { + if config.JSONOutput || config.Verbose { + return + } + + featureUsage := compiler.GetExperimentalFeatureUsage() + if len(featureUsage) > 0 { + type featureCount struct { + name string + count int + } + features := make([]featureCount, 0, len(featureUsage)) + for message, count := range featureUsage { + features = append(features, featureCount{ + name: strings.TrimPrefix(message, "Using experimental feature: "), + count: count, + }) + } + slices.SortFunc(features, func(a, b featureCount) int { + if a.count != b.count { + return cmp.Compare(b.count, a.count) + } + return cmp.Compare(a.name, b.name) + }) + + fmt.Fprintln(os.Stderr, console.FormatWarningMessageStderr("Experimental features in use:")) + for _, feature := range features { + fmt.Fprintln(os.Stderr, console.FormatListItemStderr(fmt.Sprintf("%s: %s", feature.name, formatWorkflowCount(feature.count)))) + } + } + + if count := compiler.DefaultModelRoutingWorkflowCount(); count > 0 { + fmt.Fprintln(os.Stderr, console.FormatInfoMessageStderr(workflow.DefaultModelRoutingBatchNotice(count))) + } + + if compiler.CopilotRequestsTipNeeded() { + fmt.Fprintln(os.Stderr, console.FormatInfoMessageStderr( + "Copilot token-based inference may be available: add permissions.copilot-requests: write. "+ + "To suppress this tip when using a PAT, set permissions.copilot-requests: none. "+ + "See https://github.github.com/gh-aw/reference/billing/", + )) + } +} diff --git a/pkg/cli/compile_pipeline_postprocess.go b/pkg/cli/compile_pipeline_postprocess.go new file mode 100644 index 00000000000..de552732940 --- /dev/null +++ b/pkg/cli/compile_pipeline_postprocess.go @@ -0,0 +1,195 @@ +package cli + +import ( + "context" + "fmt" + "os" + "path/filepath" + + "github.com/github/gh-aw/pkg/console" + "github.com/github/gh-aw/pkg/gitutil" + "github.com/github/gh-aw/pkg/workflow" +) + +// runPostProcessing runs post-processing for specific files compilation +func runPostProcessing( + ctx context.Context, + compiler *workflow.Compiler, + workflowDataList []*workflow.WorkflowData, + compiledLockFiles []string, + config CompileConfig, + successCount int, +) error { + // Get action cache + actionCache := compiler.GetSharedActionCache() + + // Update .gitattributes (errors are non-fatal) + _ = updateGitAttributes(successCount, actionCache, config.Verbose) //nolint:ignoredlocalerror // Non-fatal and logged by the helper. + + // Generate Dependabot manifests and reconcile compiler-managed ignore entries if requested. + if config.Dependabot && !config.NoEmit { + if gitRoot, err := gitutil.FindGitRoot(); err == nil { + absWorkflowDir := filepath.Join(gitRoot, config.WorkflowDir) + if err := generateDependabotManifestsWrapper(ctx, compiler, workflowDataList, absWorkflowDir, config.ForceOverwrite, config.Strict); err != nil { + if config.Strict { + return err + } + } + if err := compiler.ReconcileManagedDependabotIgnoresInRepo(gitRoot); err != nil { + if config.Strict { + return err + } + fmt.Fprintln(os.Stderr, console.FormatWarningMessageStderr(fmt.Sprintf("Failed to reconcile compiler-managed Dependabot ignore entries: %v", err))) + } + } + } + + // Reconcile the implicit action-failure expiry marker so specific-file + // compiles agree with what a full directory compile would produce. + // Maintenance workflow generation itself is skipped for specific-file + // compiles because it requires parsing every workflow in the directory to + // check for expires fields; only reconcile when using the default + // workflow directory (custom --dir compiles and --no-emit compiles are + // left untouched). + if !config.NoEmit && config.usesDefaultWorkflowDir() && len(compiledLockFiles) > 0 { + if gitRoot, err := gitutil.FindGitRoot(); err == nil { + absWorkflowDir := getAbsoluteWorkflowDir(getWorkflowsDir(), gitRoot) + repoConfig, err := workflow.LoadRepoConfig(gitRoot) + if err != nil { + repoConfig = nil + } + workflow.DisableDefaultActionFailureExpiryMarkersIfUnenforced(compiledLockFiles, absWorkflowDir, repoConfig) + } + } + + // Prune stale gh-aw-actions entries before saving + pruneStaleActionCacheEntries(compiler, actionCache) + + // Save action cache (errors are logged but non-fatal) + _ = saveActionCache(actionCache, config.Verbose) //nolint:ignoredlocalerror // Non-fatal and logged by the helper. + + return nil +} + +// runPostProcessingForDirectory runs post-processing for directory compilation +func runPostProcessingForDirectory( + ctx context.Context, + compiler *workflow.Compiler, + workflowDataList []*workflow.WorkflowData, + config CompileConfig, + workflowsDir string, + gitRoot string, + successCount int, + errorCount int, +) error { + // Get action cache + actionCache := compiler.GetSharedActionCache() + + // Update .gitattributes (errors are non-fatal) + _ = updateGitAttributes(successCount, actionCache, config.Verbose) //nolint:ignoredlocalerror // Non-fatal and logged by the helper. + + // Generate Dependabot manifests if requested + if config.Dependabot && !config.NoEmit { + absWorkflowDir := getAbsoluteWorkflowDir(workflowsDir, gitRoot) + if err := generateDependabotManifestsWrapper(ctx, compiler, workflowDataList, absWorkflowDir, config.ForceOverwrite, config.Strict); err != nil { + if config.Strict { + return err + } + } + } + + // Reconcile compiler-managed Dependabot ignore entries for compiler-emitted action refs. + if config.Dependabot && !config.NoEmit { + if err := compiler.ReconcileManagedDependabotIgnoresInRepo(gitRoot); err != nil { + if config.Strict { + return err + } + fmt.Fprintln(os.Stderr, console.FormatWarningMessageStderr(fmt.Sprintf("Failed to reconcile compiler-managed Dependabot ignore entries: %v", err))) + } + } + + // Generate maintenance workflow if needed. + // Skip maintenance workflow generation when using custom --dir option. + // Keep invoking generators for empty workflowDataList so stale generated files are cleaned up. + if !config.NoEmit && config.usesDefaultWorkflowDir() { + absWorkflowDir := getAbsoluteWorkflowDir(workflowsDir, gitRoot) + if err := generateMaintenanceWorkflowWrapper(ctx, compiler, workflowDataList, absWorkflowDir, gitRoot, config.Verbose, config.Strict, config.NoLogo); err != nil { + if config.Strict { + return err + } + } + if err := generateWorkQueueEventWorkflowWrapper(ctx, workflowDataList, absWorkflowDir, gitRoot, config.Strict, config.NoLogo); err != nil { + if config.Strict { + return err + } + } + if err := generateCentralSlashCommandWorkflowWrapper(ctx, workflowDataList, absWorkflowDir, gitRoot, config.Strict, config.NoLogo); err != nil { + if config.Strict { + return err + } + } + } + + // Prune stale gh-aw-actions entries before saving + pruneStaleActionCacheEntries(compiler, actionCache) + + // Prune orphaned entries — entries for action versions no longer referenced + // by any workflow in the directory (e.g. old pins left after a version bump). + // Safe to call only after a full-directory compilation with zero compile errors. + pruneOrphanedActionCacheEntries(compiler, actionCache, errorCount) + + // Save action cache (errors are logged but non-fatal) + _ = saveActionCache(actionCache, config.Verbose) //nolint:ignoredlocalerror // Non-fatal and logged by the helper. + + return nil +} + +// outputResults outputs compilation results in the requested format +func outputResults( + stats *CompilationStats, + validationResults *[]ValidationResult, + config CompileConfig, +) error { + if !config.DryRun && len(config.modelValidationWarnings) > 0 { + issues := modelInventoryWarnings(config) + *validationResults = append(*validationResults, ValidationResult{ + Scope: "batch", Workflow: "models", Valid: true, Errors: []ValidationIssue{}, Warnings: issues, + }) + stats.Warnings += len(issues) + if !config.JSONOutput { + for _, issue := range issues { + fmt.Fprintln(os.Stderr, console.FormatWarningMessageStderr(issue.Message)) + } + } + } + appendDryRunCompileReport(config, stats, validationResults) + + // Collect and display stats if requested + if config.Stats && !config.NoEmit && !config.JSONOutput { + var statsList []*WorkflowStats + if len(config.MarkdownFiles) > 0 { + statsList = collectWorkflowStatisticsWrapper(config.MarkdownFiles) + } + displayStatsTable(statsList) + displayScheduleCalendar(statsList) + } + + // Output JSON if requested + if config.JSONOutput { + jsonStr, err := formatValidationOutput(*validationResults) + if err != nil { + return err + } + fmt.Fprintln(os.Stdout, jsonStr) + } else if !config.Stats { + // Print summary for text output (skip if stats mode) + printCompilationSummary(stats, config.ShowAllErrors) + } + + // Display actionlint summary if enabled + if config.Actionlint && !config.NoEmit && !config.JSONOutput { + displayActionlintSummary() + } + + return nil +} diff --git a/pkg/cli/compile_pipeline_purge.go b/pkg/cli/compile_pipeline_purge.go new file mode 100644 index 00000000000..52009e84225 --- /dev/null +++ b/pkg/cli/compile_pipeline_purge.go @@ -0,0 +1,63 @@ +package cli + +import ( + "fmt" + "os" + "path/filepath" + + "github.com/github/gh-aw/pkg/console" + "github.com/github/gh-aw/pkg/stringutil" +) + +// purgeTrackingData holds data needed for purge operations +type purgeTrackingData struct { + existingLockFiles []string + existingInvalidFiles []string + expectedLockFiles []string +} + +// collectPurgeData collects existing files for purge operations +func collectPurgeData(workflowsDir string, mdFiles []string, verbose bool) (*purgeTrackingData, error) { + return collectPurgeDataWithPatterns(workflowsDir, mdFiles, verbose, "*.lock.yml", "*.invalid.yml") +} + +// collectPurgeDataWithPatterns is the testable implementation of collectPurgeData. +// lockPattern and invalidPattern are appended to workflowsDir for the glob calls. +func collectPurgeDataWithPatterns(workflowsDir string, mdFiles []string, verbose bool, lockPattern, invalidPattern string) (*purgeTrackingData, error) { + data := &purgeTrackingData{} + + // Find all existing files + var err error + data.existingLockFiles, err = filepath.Glob(filepath.Join(workflowsDir, lockPattern)) + if err != nil { + return nil, fmt.Errorf("failed to glob existing .lock.yml files in %s: %w", workflowsDir, err) + } + data.existingInvalidFiles, err = filepath.Glob(filepath.Join(workflowsDir, invalidPattern)) + if err != nil { + return nil, fmt.Errorf("failed to glob existing .invalid.yml files in %s: %w", workflowsDir, err) + } + + // Create expected files list + for _, mdFile := range mdFiles { + lockFile := stringutil.MarkdownToLockFile(mdFile) + data.expectedLockFiles = append(data.expectedLockFiles, lockFile) + } + + if verbose { + if len(data.existingLockFiles) > 0 { + fmt.Fprintln(os.Stderr, console.FormatInfoMessageStderr(fmt.Sprintf("Found %d existing .lock.yml files", len(data.existingLockFiles)))) + } + if len(data.existingInvalidFiles) > 0 { + fmt.Fprintln(os.Stderr, console.FormatInfoMessageStderr(fmt.Sprintf("Found %d existing .invalid.yml files", len(data.existingInvalidFiles)))) + } + } + + return data, nil +} + +// runPurgeOperations runs all purge operations +func runPurgeOperations(workflowsDir string, data *purgeTrackingData, verbose bool) { + // Errors from purge operations are logged but don't stop compilation + _ = purgeOrphanedLockFiles(workflowsDir, data.expectedLockFiles, verbose) //nolint:ignoredlocalerror // Preserve non-fatal purge behavior. + _ = purgeInvalidFiles(workflowsDir, verbose) //nolint:ignoredlocalerror // Preserve non-fatal purge behavior. +} diff --git a/pkg/cli/compile_pipeline_stages.go b/pkg/cli/compile_pipeline_stages.go new file mode 100644 index 00000000000..f0931e1b3a3 --- /dev/null +++ b/pkg/cli/compile_pipeline_stages.go @@ -0,0 +1,124 @@ +package cli + +import ( + "context" + "fmt" + "os" + + "github.com/github/gh-aw/pkg/console" + "github.com/github/gh-aw/pkg/workflow" +) + +type compilePipelineStage struct { + compiler *workflow.Compiler + config CompileConfig + stats *CompilationStats + results *[]ValidationResult + workflows []*workflow.WorkflowData + resultIndexes []int + compiledLockFiles []string + batch batchToolsOptions + successes int + failures int +} + +func (stage *compilePipelineStage) compile(ctx context.Context, files []string, resolve bool) error { + validate := stage.config.Validate || stage.config.ForceRefreshActionPins + if stage.config.ForceRefreshActionPins && !stage.config.Validate { + compileOrchestrationLog.Print("Automatically enabling action SHA validation due to --force-refresh-action-pins") + } + + for _, file := range files { + if err := ctx.Err(); err != nil { + fmt.Fprintln(os.Stderr, console.FormatWarningMessageStderr("Operation cancelled")) + return err + } + stage.stats.Total++ + if resolve { + compileOrchestrationLog.Printf("Resolving workflow file: %s", file) + resolved, err := resolveWorkflowFile(file, stage.config.Verbose) + if err != nil { + stage.failures++ + stage.stats.Errors++ + trackWorkflowFailure(stage.stats, file, 1, []string{err.Error()}) + *stage.results = append(*stage.results, ValidationResult{ + Workflow: file, Valid: false, + Errors: []ValidationIssue{{Type: "resolution_error", Message: err.Error()}}, + Warnings: []ValidationIssue{}, + }) + writeMCPCompileProgress(stage.config.MCPProgressFile, *stage.results) + continue + } + file = resolved + compileOrchestrationLog.Printf("Resolved to: %s", file) + } + + result := compileWorkflowFile(ctx, stage.compiler, file, compileWorkflowFileOptions{ + verbose: stage.config.Verbose, jsonOutput: stage.config.JSONOutput, + noEmit: stage.config.NoEmit, strict: stage.config.Strict, + validate: validate, failOnWarnings: stage.config.DryRun, + }) + stage.recordFile(file, result) + if resolve && len(*stage.results) == 0 { + appendMCPCachedModelInventoryWarning(stage.config, &result.validationResult) + } + *stage.results = append(*stage.results, result.validationResult) + writeMCPCompileProgress(stage.config.MCPProgressFile, *stage.results) + } + return nil +} + +func (stage *compilePipelineStage) recordFile(file string, result compileWorkflowFileResult) { + if !result.success { + var messages []string + for _, issue := range result.validationResult.Errors { + messages = append(messages, issue.Message) + } + if len(messages) == 0 { + messages = []string{fallbackCompilationErrorMessage} + } + stage.failures++ + stage.stats.Errors += len(messages) + trackWorkflowFailure(stage.stats, file, len(messages), messages) + return + } + + stage.successes++ + stage.stats.Succeeded++ + if result.workflowData != nil { + stage.workflows = append(stage.workflows, result.workflowData) + stage.resultIndexes = append(stage.resultIndexes, len(*stage.results)) + } + if stage.config.NoEmit || result.lockFile == "" { + return + } + if _, err := os.Stat(result.lockFile); err != nil { + return + } + stage.compiledLockFiles = append(stage.compiledLockFiles, result.lockFile) + if stage.config.Actionlint { + stage.batch.lockFilesForActionlint = append(stage.batch.lockFilesForActionlint, result.lockFile) + } + if stage.config.Zizmor { + stage.batch.lockFilesForZizmor = append(stage.batch.lockFilesForZizmor, result.lockFile) + } + if stage.config.Poutine || stage.config.RunnerGuard { + stage.batch.lockFilesForDirTools = append(stage.batch.lockFilesForDirTools, result.lockFile) + } + if stage.config.Syft { + stage.batch.lockFilesForSyft = append(stage.batch.lockFilesForSyft, result.lockFile) + } + if stage.config.Grype { + stage.batch.lockFilesForGrype = append(stage.batch.lockFilesForGrype, result.lockFile) + } + if stage.config.Grant { + stage.batch.lockFilesForGrant = append(stage.batch.lockFilesForGrant, result.lockFile) + } + if stage.config.Yamllint { + stage.batch.lockFilesForYamllint = append(stage.batch.lockFilesForYamllint, result.lockFile) + } + if stage.config.shellcheckEnabled() { + stage.batch.lockFilesForShellcheck = append(stage.batch.lockFilesForShellcheck, result.lockFile) + stage.batch.shellcheckResources = append(stage.batch.shellcheckResources, result.workflowData.ShellScriptResources()...) + } +} diff --git a/pkg/cli/compile_pipeline_stages_test.go b/pkg/cli/compile_pipeline_stages_test.go new file mode 100644 index 00000000000..6a104631d97 --- /dev/null +++ b/pkg/cli/compile_pipeline_stages_test.go @@ -0,0 +1,105 @@ +//go:build !integration + +package cli + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + + "github.com/github/gh-aw/pkg/workflow" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCompilePipelineStageRecordsFiles(t *testing.T) { + lockFile := filepath.Join(t.TempDir(), "test.lock.yml") + require.NoError(t, os.WriteFile(lockFile, []byte("name: test\n"), 0o644)) + data := &workflow.WorkflowData{ + WorkflowID: "test", + MCPScripts: &workflow.MCPScriptsConfig{Tools: map[string]*workflow.MCPScriptToolConfig{ + "inspect": {Run: "echo test"}, + }}, + } + results := []ValidationResult{{Workflow: "previous"}} + stats := &CompilationStats{} + stage := compilePipelineStage{ + config: CompileConfig{ + Actionlint: true, Zizmor: true, Poutine: true, Syft: true, + Grype: true, Grant: true, Yamllint: true, Shellcheck: true, + }, + stats: stats, results: &results, + } + stage.recordFile("test.md", compileWorkflowFileResult{success: true, workflowData: data, lockFile: lockFile}) + + assert.Equal(t, 1, stats.Succeeded) + assert.Equal(t, 1, stage.successes) + assert.Equal(t, []*workflow.WorkflowData{data}, stage.workflows) + assert.Equal(t, []int{1}, stage.resultIndexes) + assert.Equal(t, []string{lockFile}, stage.compiledLockFiles) + for _, files := range [][]string{ + stage.batch.lockFilesForActionlint, stage.batch.lockFilesForZizmor, + stage.batch.lockFilesForDirTools, stage.batch.lockFilesForSyft, + stage.batch.lockFilesForGrype, stage.batch.lockFilesForGrant, + stage.batch.lockFilesForYamllint, stage.batch.lockFilesForShellcheck, + } { + assert.Equal(t, []string{lockFile}, files) + } + assert.Equal(t, []workflow.ShellScriptResource{{Name: "mcp-scripts.inspect", Script: "echo test", Shell: "bash", Source: "test"}}, stage.batch.shellcheckResources) + + stage.recordFile("broken.md", compileWorkflowFileResult{}) + assert.Equal(t, 1, stage.failures) + assert.Equal(t, 1, stats.Errors) + require.Len(t, stats.FailureDetails, 1) + assert.Equal(t, []string{fallbackCompilationErrorMessage}, stats.FailureDetails[0].ErrorMessages) +} + +func TestCompilePipelineStageSkipsUnemittedLocks(t *testing.T) { + lockFile := filepath.Join(t.TempDir(), "test.lock.yml") + require.NoError(t, os.WriteFile(lockFile, nil, 0o644)) + for _, tc := range []struct { + name string + noEmit bool + lock string + }{ + {name: "no emit", noEmit: true, lock: lockFile}, + {name: "empty path"}, + {name: "missing file", lock: lockFile + ".missing"}, + } { + t.Run(tc.name, func(t *testing.T) { + results := []ValidationResult{} + stage := compilePipelineStage{ + config: CompileConfig{NoEmit: tc.noEmit, Actionlint: true}, + stats: &CompilationStats{}, results: &results, + } + stage.recordFile("test.md", compileWorkflowFileResult{success: true, lockFile: tc.lock}) + assert.Empty(t, stage.compiledLockFiles) + assert.Empty(t, stage.batch.lockFilesForActionlint) + assert.Equal(t, 1, stage.successes) + }) + } +} + +func TestCompilePipelineStageCancellation(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + results := []ValidationResult{} + stats := &CompilationStats{} + stage := compilePipelineStage{stats: stats, results: &results} + require.ErrorIs(t, stage.compile(ctx, []string{"test.md"}, true), context.Canceled) + assert.Zero(t, stats.Total) + assert.Empty(t, results) +} + +func TestCompilationResultErrorPrecedence(t *testing.T) { + grantErr := errors.New("grant") + batchErr := errors.New("batch") + developmentErr := errors.New("development") + require.ErrorIs(t, compilationResultError(1, grantErr, batchErr, developmentErr), grantErr) + require.ErrorIs(t, compilationResultError(1, nil, batchErr, developmentErr), batchErr) + require.EqualError(t, compilationResultError(1, nil, nil, developmentErr), "compilation failed") + require.ErrorIs(t, compilationResultError(0, nil, nil, developmentErr), developmentErr) + require.NoError(t, compilationResultError(0, nil, nil, nil)) +}