From ab67ecabd228e9cfdcc97d66c86630b8f347f90f Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Thu, 2 Oct 2025 05:40:59 +0000 Subject: [PATCH 1/7] Initial plan From d6147512c055ebd45d112cf8202a38d3aec7bcd8 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Thu, 2 Oct 2025 05:58:21 +0000 Subject: [PATCH 2/7] feat: implement imports feature for workflows - Add ImportSpec and lock file structures - Implement parsing for import specifications (org/repo version path) - Add import lock file read/write functionality - Create InstallImports command to resolve and clone imports - Integrate import processing into compile workflow - Add 'gh aw install' CLI command for installing imports - Update .gitignore to exclude .aw directory Co-authored-by: pelikhan <4175913+pelikhan@users.noreply.github.com> --- .gitignore | 3 + cmd/gh-aw/main.go | 34 +++- pkg/cli/install_imports.go | 385 +++++++++++++++++++++++++++++++++++++ pkg/parser/frontmatter.go | 133 +++++++++++++ pkg/parser/imports.go | 164 ++++++++++++++++ pkg/parser/imports_lock.go | 254 ++++++++++++++++++++++++ pkg/parser/imports_test.go | 316 ++++++++++++++++++++++++++++++ pkg/workflow/compiler.go | 24 +++ 8 files changed, 1310 insertions(+), 3 deletions(-) create mode 100644 pkg/cli/install_imports.go create mode 100644 pkg/parser/imports.go create mode 100644 pkg/parser/imports_lock.go create mode 100644 pkg/parser/imports_test.go diff --git a/.gitignore b/.gitignore index c56c11ce63f..3a7d21ee96b 100644 --- a/.gitignore +++ b/.gitignore @@ -55,3 +55,6 @@ node_modules/ gh-aw-test/ pkg/cli/workflows/*.yml + +# Workflow imports (local cache and lock file) +.aw/ diff --git a/cmd/gh-aw/main.go b/cmd/gh-aw/main.go index 2c696964438..83316443719 100644 --- a/cmd/gh-aw/main.go +++ b/cmd/gh-aw/main.go @@ -227,7 +227,34 @@ Examples: } var installCmd = &cobra.Command{ - Use: "install [@version]", + Use: "install [workflow-name]", + Short: "Install workflow imports and dependencies", + Long: `Install imports for agentic workflows. + +If a workflow name is specified, only imports for that workflow are installed. +Otherwise, all imports from all workflows are installed. + +Examples: + ` + constants.CLIExtensionPrefix + ` install # Install all imports + ` + constants.CLIExtensionPrefix + ` install my-workflow # Install imports for specific workflow`, + Args: cobra.MaximumNArgs(1), + Run: func(cmd *cobra.Command, args []string) { + var workflowName string + if len(args) > 0 { + workflowName = args[0] + } + if err := cli.InstallImports(workflowName, verbose); err != nil { + fmt.Fprintln(os.Stderr, console.FormatError(console.CompilerError{ + Type: "error", + Message: fmt.Sprintf("installing imports: %v", err), + })) + os.Exit(1) + } + }, +} + +var installPackageCmd = &cobra.Command{ + Use: "install-package [@version]", Short: "Install agentic workflows from a GitHub repository", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { @@ -309,8 +336,8 @@ func init() { listCmd.Flags().BoolP("packages", "p", false, "List installed packages instead of available workflows") listCmd.Flags().BoolP("local", "l", false, "List local packages instead of global packages (requires --packages)") - // Add local flag to install command - installCmd.Flags().BoolP("local", "l", false, "Install packages locally in .aw/packages instead of globally in ~/.aw/packages") + // Add local flag to install-package command + installPackageCmd.Flags().BoolP("local", "l", false, "Install packages locally in .aw/packages instead of globally in ~/.aw/packages") // Add local flag to uninstall command uninstallCmd.Flags().BoolP("local", "l", false, "Uninstall packages from local .aw/packages instead of global ~/.aw/packages") @@ -338,6 +365,7 @@ func init() { rootCmd.AddCommand(newCmd) rootCmd.AddCommand(initCmd) rootCmd.AddCommand(installCmd) + rootCmd.AddCommand(installPackageCmd) rootCmd.AddCommand(uninstallCmd) rootCmd.AddCommand(compileCmd) rootCmd.AddCommand(runCmd) diff --git a/pkg/cli/install_imports.go b/pkg/cli/install_imports.go new file mode 100644 index 00000000000..595461a8232 --- /dev/null +++ b/pkg/cli/install_imports.go @@ -0,0 +1,385 @@ +package cli + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + + "github.com/githubnext/gh-aw/pkg/console" + "github.com/githubnext/gh-aw/pkg/parser" +) + +// InstallImports installs all imports from workflows +// If workflowName is provided, only install imports for that workflow +func InstallImports(workflowName string, verbose bool) error { + if verbose { + if workflowName != "" { + fmt.Fprintln(os.Stderr, console.FormatProgressMessage(fmt.Sprintf("Installing imports for workflow: %s", workflowName))) + } else { + fmt.Fprintln(os.Stderr, console.FormatProgressMessage("Installing imports for all workflows")) + } + } + + // Get workflows directory + workflowsDir := filepath.Join(".github", "workflows") + if _, err := os.Stat(workflowsDir); os.IsNotExist(err) { + return fmt.Errorf("workflows directory not found: %s", workflowsDir) + } + + // Collect all imports from workflows + imports, err := collectImportsFromWorkflows(workflowsDir, workflowName, verbose) + if err != nil { + return fmt.Errorf("failed to collect imports: %w", err) + } + + if len(imports) == 0 { + fmt.Fprintln(os.Stderr, console.FormatInfoMessage("No imports found in workflows")) + return nil + } + + if verbose { + fmt.Fprintln(os.Stderr, console.FormatInfoMessage(fmt.Sprintf("Found %d unique import(s)", len(imports)))) + } + + // Get or create imports directory + importsDir, err := parser.GetImportsDir() + if err != nil { + return fmt.Errorf("failed to get imports directory: %w", err) + } + + if err := os.MkdirAll(importsDir, 0755); err != nil { + return fmt.Errorf("failed to create imports directory: %w", err) + } + + // Get lock file path + lockFilePath, err := parser.GetImportLockFilePath() + if err != nil { + return fmt.Errorf("failed to get lock file path: %w", err) + } + + // Ensure .aw directory exists + awDir := filepath.Dir(lockFilePath) + if err := os.MkdirAll(awDir, 0755); err != nil { + return fmt.Errorf("failed to create .aw directory: %w", err) + } + + // Read existing lock file + lock, err := parser.ReadImportLockFile(lockFilePath) + if err != nil { + return fmt.Errorf("failed to read lock file: %w", err) + } + + // Process each import + for _, importSpec := range imports { + if err := installSingleImport(importSpec, importsDir, lock, verbose); err != nil { + return fmt.Errorf("failed to install import %s: %w", importSpec.String(), err) + } + } + + // Write updated lock file + if err := parser.WriteImportLockFile(lockFilePath, lock); err != nil { + return fmt.Errorf("failed to write lock file: %w", err) + } + + fmt.Fprintln(os.Stderr, console.FormatSuccessMessage("Successfully installed all imports")) + return nil +} + +// collectImportsFromWorkflows collects all unique imports from workflow files +func collectImportsFromWorkflows(workflowsDir, workflowName string, verbose bool) ([]*parser.ImportSpec, error) { + var allImports []*parser.ImportSpec + seen := make(map[string]bool) + + // Determine which files to process + var filesToProcess []string + if workflowName != "" { + // Process specific workflow + workflowFile := filepath.Join(workflowsDir, workflowName) + if !strings.HasSuffix(workflowFile, ".md") { + workflowFile += ".md" + } + if _, err := os.Stat(workflowFile); os.IsNotExist(err) { + return nil, fmt.Errorf("workflow file not found: %s", workflowFile) + } + filesToProcess = append(filesToProcess, workflowFile) + } else { + // Process all markdown files in workflows directory + err := filepath.Walk(workflowsDir, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + if !info.IsDir() && strings.HasSuffix(info.Name(), ".md") { + filesToProcess = append(filesToProcess, path) + } + return nil + }) + if err != nil { + return nil, fmt.Errorf("failed to walk workflows directory: %w", err) + } + } + + // Extract imports from each file + for _, filePath := range filesToProcess { + if verbose { + fmt.Fprintln(os.Stderr, console.FormatInfoMessage(fmt.Sprintf("Checking %s", filePath))) + } + + content, err := os.ReadFile(filePath) + if err != nil { + return nil, fmt.Errorf("failed to read %s: %w", filePath, err) + } + + // Parse frontmatter + result, err := parser.ExtractFrontmatterFromContent(string(content)) + if err != nil { + if verbose { + fmt.Fprintln(os.Stderr, console.FormatWarningMessage(fmt.Sprintf("Failed to parse frontmatter in %s: %v", filePath, err))) + } + continue + } + + // Check for imports field + importsValue, hasImports := result.Frontmatter["imports"] + if !hasImports { + continue + } + + // Parse imports + imports, err := parser.ParseImports(importsValue) + if err != nil { + return nil, fmt.Errorf("failed to parse imports in %s: %w", filePath, err) + } + + // Add to collection (deduplicate) + for _, imp := range imports { + key := imp.String() + if !seen[key] { + seen[key] = true + allImports = append(allImports, imp) + + if verbose { + fmt.Fprintln(os.Stderr, console.FormatInfoMessage(fmt.Sprintf(" Found import: %s", imp.String()))) + } + } + } + } + + return allImports, nil +} + +// installSingleImport installs a single import by cloning the repository +func installSingleImport(importSpec *parser.ImportSpec, importsDir string, lock *parser.ImportLockFile, verbose bool) error { + // Check if already installed with same SHA in lock file + existingEntry := lock.FindEntry(importSpec) + + // Get target directory for this import + targetDir := importSpec.GetLocalCachePath(importsDir) + + // Resolve commit SHA + commitSHA, err := resolveImportVersion(importSpec, verbose) + if err != nil { + return fmt.Errorf("failed to resolve version: %w", err) + } + + // Check if already installed with correct SHA + if existingEntry != nil && existingEntry.CommitSHA == commitSHA { + if _, err := os.Stat(targetDir); err == nil { + // Verify the imported file exists + importedFilePath := filepath.Join(targetDir, importSpec.Path) + if _, err := os.Stat(importedFilePath); err == nil { + if verbose { + fmt.Fprintln(os.Stderr, console.FormatInfoMessage(fmt.Sprintf("Import %s already installed with correct version", importSpec.String()))) + } + return nil + } + } + } + + if verbose { + fmt.Fprintln(os.Stderr, console.FormatProgressMessage(fmt.Sprintf("Installing %s (%s)", importSpec.String(), commitSHA[:8]))) + } + + // Remove existing directory if present + if _, err := os.Stat(targetDir); err == nil { + if err := os.RemoveAll(targetDir); err != nil { + return fmt.Errorf("failed to remove existing import directory: %w", err) + } + } + + // Create parent directory + if err := os.MkdirAll(filepath.Dir(targetDir), 0755); err != nil { + return fmt.Errorf("failed to create parent directory: %w", err) + } + + // Clone repository (shallow clone at specific commit) + repoURL := fmt.Sprintf("https://github.com/%s/%s.git", importSpec.Org, importSpec.Repo) + + if verbose { + fmt.Fprintln(os.Stderr, console.FormatInfoMessage(fmt.Sprintf("Cloning from %s", repoURL))) + } + + // Use git clone with depth 1 at specific commit + cmd := exec.Command("git", "clone", "--depth", "1", "--branch", importSpec.Version, repoURL, targetDir) + output, err := cmd.CombinedOutput() + if err != nil { + // If branch clone fails, try full clone and checkout + if verbose { + fmt.Fprintln(os.Stderr, console.FormatInfoMessage("Shallow clone failed, trying full clone...")) + } + + cmd = exec.Command("git", "clone", repoURL, targetDir) + output, err = cmd.CombinedOutput() + if err != nil { + return fmt.Errorf("failed to clone repository: %w (output: %s)", err, string(output)) + } + + // Checkout specific version + cmd = exec.Command("git", "-C", targetDir, "checkout", commitSHA) + output, err = cmd.CombinedOutput() + if err != nil { + return fmt.Errorf("failed to checkout version %s: %w (output: %s)", commitSHA, err, string(output)) + } + } + + // Verify the imported file exists + importedFilePath := filepath.Join(targetDir, importSpec.Path) + if _, err := os.Stat(importedFilePath); os.IsNotExist(err) { + return fmt.Errorf("imported file not found: %s", importSpec.Path) + } + + // Collect transitive files (from @includes in the imported file) + transitiveFiles, err := collectTransitiveFiles(importedFilePath, targetDir, verbose) + if err != nil { + return fmt.Errorf("failed to collect transitive files: %w", err) + } + + // Update lock entry + entry := parser.CreateImportLockEntry(importSpec, commitSHA, transitiveFiles) + lock.AddOrUpdateEntry(entry) + + if verbose { + fmt.Fprintln(os.Stderr, console.FormatSuccessMessage(fmt.Sprintf("Installed %s", importSpec.String()))) + } + + return nil +} + +// resolveImportVersion resolves a version string to a commit SHA +func resolveImportVersion(importSpec *parser.ImportSpec, verbose bool) (string, error) { + // Use gh api to resolve the version to a commit SHA + repoSlug := importSpec.RepoSlug() + version := importSpec.Version + + if verbose { + fmt.Fprintln(os.Stderr, console.FormatInfoMessage(fmt.Sprintf("Resolving version %s for %s", version, repoSlug))) + } + + // Try to resolve as a ref (branch, tag, or commit) + cmd := exec.Command("gh", "api", fmt.Sprintf("/repos/%s/commits/%s", repoSlug, version)) + output, err := cmd.Output() + if err == nil { + // Parse JSON to get SHA + // For simplicity, just extract the sha field + shaLine := "" + for _, line := range strings.Split(string(output), "\n") { + if strings.Contains(line, "\"sha\":") { + shaLine = line + break + } + } + if shaLine != "" { + // Extract SHA value + sha := strings.TrimSpace(shaLine) + sha = strings.TrimPrefix(sha, "\"sha\":") + sha = strings.Trim(sha, "\", ") + if len(sha) >= 40 { + return sha[:40], nil + } + } + } + + // If that didn't work, try as a tag + cmd = exec.Command("gh", "api", fmt.Sprintf("/repos/%s/git/ref/tags/%s", repoSlug, version)) + output, err = cmd.Output() + if err == nil { + // Parse the ref to get object SHA + for _, line := range strings.Split(string(output), "\n") { + if strings.Contains(line, "\"sha\":") { + sha := strings.TrimSpace(line) + sha = strings.TrimPrefix(sha, "\"sha\":") + sha = strings.Trim(sha, "\", ") + if len(sha) >= 40 { + return sha[:40], nil + } + } + } + } + + // If we still can't resolve, return the version as-is (might be a full SHA) + if len(version) >= 40 && importSpec.IsCommitSHA() { + return version[:40], nil + } + + return "", fmt.Errorf("failed to resolve version %s to commit SHA", version) +} + +// collectTransitiveFiles collects all files referenced by @include directives +func collectTransitiveFiles(filePath, baseDir string, verbose bool) ([]string, error) { + var files []string + seen := make(map[string]bool) + + var collectRecursive func(path string) error + collectRecursive = func(path string) error { + if seen[path] { + return nil + } + seen[path] = true + + // Read file + content, err := os.ReadFile(path) + if err != nil { + return err + } + + // Look for @include directives + lines := strings.Split(string(content), "\n") + + for _, line := range lines { + line = strings.TrimSpace(line) + if strings.HasPrefix(line, "@include") { + // Extract include path + parts := strings.Fields(line) + if len(parts) >= 2 { + includePath := parts[1] + + // Handle section references + if strings.Contains(includePath, "#") { + parts := strings.SplitN(includePath, "#", 2) + includePath = parts[0] + } + + // Resolve relative to base directory + fullPath := filepath.Join(baseDir, includePath) + relPath, err := filepath.Rel(baseDir, fullPath) + if err == nil && !strings.HasPrefix(relPath, "..") { + files = append(files, relPath) + // Recursively collect from included file + if err := collectRecursive(fullPath); err != nil && verbose { + fmt.Fprintln(os.Stderr, console.FormatWarningMessage(fmt.Sprintf("Failed to process include %s: %v", includePath, err))) + } + } + } + } + } + + return nil + } + + if err := collectRecursive(filePath); err != nil { + return nil, err + } + + return files, nil +} diff --git a/pkg/parser/frontmatter.go b/pkg/parser/frontmatter.go index c0277c6bd39..63457094b10 100644 --- a/pkg/parser/frontmatter.go +++ b/pkg/parser/frontmatter.go @@ -14,6 +14,139 @@ import ( "github.com/goccy/go-yaml" ) +// ProcessImportsInFrontmatter processes import directives from frontmatter by merging imported content +func ProcessImportsInFrontmatter(content string, frontmatter map[string]any, baseDir string) (string, map[string]any, error) { + // Check if frontmatter has imports + importsValue, hasImports := frontmatter["imports"] + if !hasImports { + return content, frontmatter, nil + } + + // Parse imports + imports, err := ParseImports(importsValue) + if err != nil { + return "", nil, fmt.Errorf("failed to parse imports: %w", err) + } + + if len(imports) == 0 { + return content, frontmatter, nil + } + + // Get imports directory + importsDir, err := GetImportsDir() + if err != nil { + return "", nil, fmt.Errorf("failed to get imports directory: %w", err) + } + + // Get lock file + lockFilePath, err := GetImportLockFilePath() + if err != nil { + return "", nil, fmt.Errorf("failed to get lock file path: %w", err) + } + + lock, err := ReadImportLockFile(lockFilePath) + if err != nil { + return "", nil, fmt.Errorf("failed to read lock file (run 'gh aw install' first): %w", err) + } + + // Process each import + var mergedContent strings.Builder + mergedFrontmatter := make(map[string]any) + + // Copy existing frontmatter (except imports) + for k, v := range frontmatter { + if k != "imports" { + mergedFrontmatter[k] = v + } + } + + for _, importSpec := range imports { + // Find in lock file + entry := lock.FindEntry(importSpec) + if entry == nil { + return "", nil, fmt.Errorf("import %s not found in lock file (run 'gh aw install')", importSpec.String()) + } + + // Get local path + localDir := importSpec.GetLocalCachePath(importsDir) + importedFilePath := filepath.Join(localDir, importSpec.Path) + + // Check if file exists + if _, err := os.Stat(importedFilePath); os.IsNotExist(err) { + return "", nil, fmt.Errorf("imported file not found: %s (run 'gh aw install')", importedFilePath) + } + + // Read imported file + importedContent, err := os.ReadFile(importedFilePath) + if err != nil { + return "", nil, fmt.Errorf("failed to read imported file %s: %w", importedFilePath, err) + } + + // Parse imported file + importedResult, err := ExtractFrontmatterFromContent(string(importedContent)) + if err != nil { + return "", nil, fmt.Errorf("failed to parse imported file %s: %w", importedFilePath, err) + } + + // Merge frontmatter (tools, etc.) + if err := mergeFrontmatterMaps(mergedFrontmatter, importedResult.Frontmatter); err != nil { + return "", nil, fmt.Errorf("failed to merge frontmatter from import %s: %w", importSpec.String(), err) + } + + // Append markdown content + if importedResult.Markdown != "" { + mergedContent.WriteString(importedResult.Markdown) + mergedContent.WriteString("\n\n") + } + } + + // Append original content + mergedContent.WriteString(content) + + return mergedContent.String(), mergedFrontmatter, nil +} + +// mergeFrontmatterMaps merges two frontmatter maps +func mergeFrontmatterMaps(target, source map[string]any) error { + for key, sourceValue := range source { + // Skip imports field + if key == "imports" { + continue + } + + targetValue, exists := target[key] + if !exists { + // Key doesn't exist in target, add it + target[key] = sourceValue + continue + } + + // Key exists, need to merge + switch key { + case "tools": + // Merge tools + targetToolsMap, ok := targetValue.(map[string]any) + if !ok { + return fmt.Errorf("target tools is not a map") + } + + sourceToolsMap, ok := sourceValue.(map[string]any) + if !ok { + return fmt.Errorf("source tools is not a map") + } + + // Merge tool configurations + for toolName, sourceToolConfig := range sourceToolsMap { + targetToolsMap[toolName] = sourceToolConfig + } + default: + // For other keys, imported value takes precedence + target[key] = sourceValue + } + } + return nil +} + // isMCPType checks if a type string represents an MCP-compatible type func isMCPType(typeStr string) bool { switch typeStr { diff --git a/pkg/parser/imports.go b/pkg/parser/imports.go new file mode 100644 index 00000000000..62591e79bd1 --- /dev/null +++ b/pkg/parser/imports.go @@ -0,0 +1,164 @@ +package parser + +import ( + "fmt" + "path/filepath" + "regexp" + "strings" +) + +// ImportSpec represents a single import specification from frontmatter +// Format: "org/repo version path" (go.mod style) +type ImportSpec struct { + Org string // GitHub organization + Repo string // Repository name + Version string // Version/tag/branch/commit + Path string // Path to the file within the repository +} + +// ParseImportSpec parses a single import string into an ImportSpec +// Expected format: "org/repo version path" +// Example: "microsoft/genaiscript v1.5 agentics/engine.md" +func ParseImportSpec(importStr string) (*ImportSpec, error) { + // Trim whitespace + importStr = strings.TrimSpace(importStr) + if importStr == "" { + return nil, fmt.Errorf("empty import specification") + } + + // Split by whitespace + parts := strings.Fields(importStr) + if len(parts) < 3 { + return nil, fmt.Errorf("invalid import format '%s': expected 'org/repo version path'", importStr) + } + + // Parse org/repo + repoSpec := parts[0] + if !strings.Contains(repoSpec, "/") { + return nil, fmt.Errorf("invalid repository format '%s': expected 'org/repo'", repoSpec) + } + repoParts := strings.SplitN(repoSpec, "/", 2) + if len(repoParts) != 2 { + return nil, fmt.Errorf("invalid repository format '%s': expected 'org/repo'", repoSpec) + } + + version := parts[1] + path := strings.Join(parts[2:], " ") // Allow spaces in path + + // Validate version format (basic check) + if version == "" { + return nil, fmt.Errorf("empty version in import specification") + } + + // Validate path + if path == "" { + return nil, fmt.Errorf("empty path in import specification") + } + + return &ImportSpec{ + Org: repoParts[0], + Repo: repoParts[1], + Version: version, + Path: path, + }, nil +} + +// ParseImports parses an array of import strings from frontmatter +func ParseImports(importsValue interface{}) ([]*ImportSpec, error) { + if importsValue == nil { + return nil, nil + } + + // Handle array of strings + importsArray, ok := importsValue.([]interface{}) + if !ok { + return nil, fmt.Errorf("imports must be an array of strings") + } + + var imports []*ImportSpec + for i, item := range importsArray { + importStr, ok := item.(string) + if !ok { + return nil, fmt.Errorf("import at index %d is not a string", i) + } + + spec, err := ParseImportSpec(importStr) + if err != nil { + return nil, fmt.Errorf("import at index %d: %w", i, err) + } + + imports = append(imports, spec) + } + + return imports, nil +} + +// String returns the import specification as a string +func (i *ImportSpec) String() string { + return fmt.Sprintf("%s/%s %s %s", i.Org, i.Repo, i.Version, i.Path) +} + +// RepoSlug returns the repository slug (org/repo) +func (i *ImportSpec) RepoSlug() string { + return fmt.Sprintf("%s/%s", i.Org, i.Repo) +} + +// ImportedFilePath returns the expected file path within the imported repository +func (i *ImportSpec) ImportedFilePath() string { + return i.Path +} + +// ImportLockEntry represents an entry in the import lock file +type ImportLockEntry struct { + ImportSpec *ImportSpec + CommitSHA string // Resolved commit SHA + ResolvedAt string // Timestamp when resolved + Files []string // List of transitive files included +} + +// ImportLockFile represents the complete lock file structure +type ImportLockFile struct { + Version string // Lock file format version + Entries []*ImportLockEntry // Locked import entries +} + +// ValidatePath checks if a path looks valid +func (i *ImportSpec) ValidatePath() error { + // Basic validation + if strings.HasPrefix(i.Path, "/") { + return fmt.Errorf("path must be relative, not absolute: %s", i.Path) + } + if strings.Contains(i.Path, "..") { + return fmt.Errorf("path must not contain '..': %s", i.Path) + } + return nil +} + +// IsVersionTag checks if the version looks like a semver tag +func (i *ImportSpec) IsVersionTag() bool { + // Check if version starts with 'v' followed by digits + matched, _ := regexp.MatchString(`^v\d+`, i.Version) + return matched +} + +// IsCommitSHA checks if the version looks like a commit SHA +func (i *ImportSpec) IsCommitSHA() bool { + // Check if version is a 40-character hex string (full SHA) + matched, _ := regexp.MatchString(`^[0-9a-f]{40}$`, i.Version) + return matched +} + +// NormalizeVersion normalizes the version string for consistent comparison +func (i *ImportSpec) NormalizeVersion() string { + // Remove 'refs/tags/' or 'refs/heads/' prefix if present + version := i.Version + version = strings.TrimPrefix(version, "refs/tags/") + version = strings.TrimPrefix(version, "refs/heads/") + return version +} + +// GetLocalCachePath returns the local cache path for this import +func (i *ImportSpec) GetLocalCachePath(importsDir string) string { + // Store in .aw/imports/org/repo/version/ + return filepath.Join(importsDir, i.Org, i.Repo, i.Version) +} diff --git a/pkg/parser/imports_lock.go b/pkg/parser/imports_lock.go new file mode 100644 index 00000000000..6a028a2d8c2 --- /dev/null +++ b/pkg/parser/imports_lock.go @@ -0,0 +1,254 @@ +package parser + +import ( + "bufio" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "time" +) + +// ImportLockFileVersion is the current version of the lock file format +const ImportLockFileVersion = "1" + +// ReadImportLockFile reads and parses an import lock file +func ReadImportLockFile(lockFilePath string) (*ImportLockFile, error) { + if _, err := os.Stat(lockFilePath); os.IsNotExist(err) { + // Lock file doesn't exist, return empty lock + return &ImportLockFile{ + Version: ImportLockFileVersion, + Entries: []*ImportLockEntry{}, + }, nil + } + + file, err := os.Open(lockFilePath) + if err != nil { + return nil, fmt.Errorf("failed to open lock file: %w", err) + } + defer file.Close() + + lock := &ImportLockFile{ + Version: ImportLockFileVersion, + Entries: []*ImportLockEntry{}, + } + + scanner := bufio.NewScanner(file) + var currentEntry *ImportLockEntry + var inFilesSection bool + + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + + // Skip empty lines and comments + if line == "" || strings.HasPrefix(line, "#") { + continue + } + + // Check for version line + if strings.HasPrefix(line, "version:") { + parts := strings.SplitN(line, ":", 2) + if len(parts) == 2 { + lock.Version = strings.TrimSpace(parts[1]) + } + continue + } + + // Check for import line (starts with org/repo) + if strings.Contains(line, " ") && !strings.HasPrefix(line, " ") && !strings.HasPrefix(line, "\t") { + // Save previous entry if exists + if currentEntry != nil { + lock.Entries = append(lock.Entries, currentEntry) + } + + // Parse new entry + parts := strings.Fields(line) + if len(parts) >= 4 { + spec, err := ParseImportSpec(strings.Join(parts[:3], " ")) + if err != nil { + return nil, fmt.Errorf("failed to parse import spec '%s': %w", line, err) + } + + currentEntry = &ImportLockEntry{ + ImportSpec: spec, + CommitSHA: parts[3], + ResolvedAt: "", + Files: []string{}, + } + + // Check for resolved timestamp (optional, after SHA) + if len(parts) > 4 { + currentEntry.ResolvedAt = strings.Join(parts[4:], " ") + } + + inFilesSection = false + } + continue + } + + // Check for files section + if strings.HasPrefix(line, " files:") || strings.HasPrefix(line, "\tfiles:") { + inFilesSection = true + continue + } + + // Parse file entry + if inFilesSection && currentEntry != nil { + // Remove leading whitespace/dash + file := strings.TrimSpace(line) + file = strings.TrimPrefix(file, "- ") + file = strings.TrimPrefix(file, "-") + file = strings.TrimSpace(file) + if file != "" { + currentEntry.Files = append(currentEntry.Files, file) + } + } + } + + // Add last entry + if currentEntry != nil { + lock.Entries = append(lock.Entries, currentEntry) + } + + if err := scanner.Err(); err != nil { + return nil, fmt.Errorf("failed to read lock file: %w", err) + } + + return lock, nil +} + +// WriteImportLockFile writes an import lock file +func WriteImportLockFile(lockFilePath string, lock *ImportLockFile) error { + // Sort entries by repo slug for consistent output + sort.Slice(lock.Entries, func(i, j int) bool { + return lock.Entries[i].ImportSpec.RepoSlug() < lock.Entries[j].ImportSpec.RepoSlug() + }) + + file, err := os.Create(lockFilePath) + if err != nil { + return fmt.Errorf("failed to create lock file: %w", err) + } + defer file.Close() + + // Write header + fmt.Fprintf(file, "# Import lock file generated by gh-aw\n") + fmt.Fprintf(file, "# This file records resolved versions and commit SHAs for imports\n") + fmt.Fprintf(file, "# Do not edit manually\n\n") + fmt.Fprintf(file, "version: %s\n\n", lock.Version) + + // Write entries + for _, entry := range lock.Entries { + // Write import spec with commit SHA + fmt.Fprintf(file, "%s %s", entry.ImportSpec.String(), entry.CommitSHA) + + // Write resolved timestamp if available + if entry.ResolvedAt != "" { + fmt.Fprintf(file, " %s", entry.ResolvedAt) + } + fmt.Fprintf(file, "\n") + + // Write files section if present + if len(entry.Files) > 0 { + fmt.Fprintf(file, " files:\n") + for _, f := range entry.Files { + fmt.Fprintf(file, " - %s\n", f) + } + } + + fmt.Fprintf(file, "\n") + } + + return nil +} + +// FindEntry finds a lock entry by import spec +func (l *ImportLockFile) FindEntry(spec *ImportSpec) *ImportLockEntry { + for _, entry := range l.Entries { + if entry.ImportSpec.RepoSlug() == spec.RepoSlug() && + entry.ImportSpec.Version == spec.Version && + entry.ImportSpec.Path == spec.Path { + return entry + } + } + return nil +} + +// AddOrUpdateEntry adds or updates a lock entry +func (l *ImportLockFile) AddOrUpdateEntry(entry *ImportLockEntry) { + // Check if entry exists + for i, existing := range l.Entries { + if existing.ImportSpec.RepoSlug() == entry.ImportSpec.RepoSlug() && + existing.ImportSpec.Version == entry.ImportSpec.Version && + existing.ImportSpec.Path == entry.ImportSpec.Path { + // Update existing entry + l.Entries[i] = entry + return + } + } + + // Add new entry + l.Entries = append(l.Entries, entry) +} + +// GetImportsDir returns the directory where imports are cached +func GetImportsDir() (string, error) { + // Use .aw/imports in the current project + cwd, err := os.Getwd() + if err != nil { + return "", fmt.Errorf("failed to get current directory: %w", err) + } + + // Find git root (go up until we find .git directory) + gitRoot, err := findGitRoot(cwd) + if err != nil { + return "", fmt.Errorf("not in a git repository: %w", err) + } + + importsDir := filepath.Join(gitRoot, ".aw", "imports") + return importsDir, nil +} + +// GetImportLockFilePath returns the path to the import lock file +func GetImportLockFilePath() (string, error) { + cwd, err := os.Getwd() + if err != nil { + return "", fmt.Errorf("failed to get current directory: %w", err) + } + + gitRoot, err := findGitRoot(cwd) + if err != nil { + return "", fmt.Errorf("not in a git repository: %w", err) + } + + lockFile := filepath.Join(gitRoot, ".aw", "imports.lock") + return lockFile, nil +} + +// findGitRoot finds the git root directory by looking for .git +func findGitRoot(startDir string) (string, error) { + dir := startDir + for { + gitDir := filepath.Join(dir, ".git") + if _, err := os.Stat(gitDir); err == nil { + return dir, nil + } + + parent := filepath.Dir(dir) + if parent == dir { + // Reached root without finding .git + return "", fmt.Errorf(".git directory not found") + } + dir = parent + } +} + +// CreateImportLockEntry creates a new lock entry with current timestamp +func CreateImportLockEntry(spec *ImportSpec, commitSHA string, files []string) *ImportLockEntry { + return &ImportLockEntry{ + ImportSpec: spec, + CommitSHA: commitSHA, + ResolvedAt: time.Now().UTC().Format(time.RFC3339), + Files: files, + } +} diff --git a/pkg/parser/imports_test.go b/pkg/parser/imports_test.go new file mode 100644 index 00000000000..bf87c89269f --- /dev/null +++ b/pkg/parser/imports_test.go @@ -0,0 +1,316 @@ +package parser + +import ( + "testing" +) + +func TestParseImportSpec(t *testing.T) { + tests := []struct { + name string + input string + wantOrg string + wantRepo string + wantVersion string + wantPath string + wantErr bool + }{ + { + name: "valid import with single path segment", + input: "microsoft/genaiscript v1.5 agentics/engine.md", + wantOrg: "microsoft", + wantRepo: "genaiscript", + wantVersion: "v1.5", + wantPath: "agentics/engine.md", + wantErr: false, + }, + { + name: "valid import with nested path", + input: "github/copilot v2.0.0 workflows/shared/config.md", + wantOrg: "github", + wantRepo: "copilot", + wantVersion: "v2.0.0", + wantPath: "workflows/shared/config.md", + wantErr: false, + }, + { + name: "valid import with branch name", + input: "githubnext/gh-aw main README.md", + wantOrg: "githubnext", + wantRepo: "gh-aw", + wantVersion: "main", + wantPath: "README.md", + wantErr: false, + }, + { + name: "valid import with commit SHA", + input: "example/repo abc123def456 path/to/file.md", + wantOrg: "example", + wantRepo: "repo", + wantVersion: "abc123def456", + wantPath: "path/to/file.md", + wantErr: false, + }, + { + name: "invalid: missing path", + input: "microsoft/genaiscript v1.5", + wantErr: true, + }, + { + name: "invalid: missing version and path", + input: "microsoft/genaiscript", + wantErr: true, + }, + { + name: "invalid: no org slash", + input: "microsoft-genaiscript v1.5 path.md", + wantErr: true, + }, + { + name: "invalid: empty string", + input: "", + wantErr: true, + }, + { + name: "invalid: only whitespace", + input: " ", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + spec, err := ParseImportSpec(tt.input) + + if tt.wantErr { + if err == nil { + t.Errorf("ParseImportSpec() expected error, got nil") + } + return + } + + if err != nil { + t.Fatalf("ParseImportSpec() unexpected error: %v", err) + } + + if spec.Org != tt.wantOrg { + t.Errorf("ParseImportSpec() org = %v, want %v", spec.Org, tt.wantOrg) + } + if spec.Repo != tt.wantRepo { + t.Errorf("ParseImportSpec() repo = %v, want %v", spec.Repo, tt.wantRepo) + } + if spec.Version != tt.wantVersion { + t.Errorf("ParseImportSpec() version = %v, want %v", spec.Version, tt.wantVersion) + } + if spec.Path != tt.wantPath { + t.Errorf("ParseImportSpec() path = %v, want %v", spec.Path, tt.wantPath) + } + }) + } +} + +func TestImportSpec_RepoSlug(t *testing.T) { + spec := &ImportSpec{ + Org: "microsoft", + Repo: "genaiscript", + Version: "v1.5", + Path: "agentics/engine.md", + } + + expected := "microsoft/genaiscript" + if spec.RepoSlug() != expected { + t.Errorf("RepoSlug() = %v, want %v", spec.RepoSlug(), expected) + } +} + +func TestImportSpec_String(t *testing.T) { + spec := &ImportSpec{ + Org: "microsoft", + Repo: "genaiscript", + Version: "v1.5", + Path: "agentics/engine.md", + } + + expected := "microsoft/genaiscript v1.5 agentics/engine.md" + if spec.String() != expected { + t.Errorf("String() = %v, want %v", spec.String(), expected) + } +} + +func TestImportSpec_ValidatePath(t *testing.T) { + tests := []struct { + name string + path string + wantErr bool + }{ + { + name: "valid relative path", + path: "agentics/engine.md", + wantErr: false, + }, + { + name: "invalid absolute path", + path: "/agentics/engine.md", + wantErr: true, + }, + { + name: "invalid path with ..", + path: "../agentics/engine.md", + wantErr: true, + }, + { + name: "valid path with subdirs", + path: "workflows/shared/config.md", + wantErr: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + spec := &ImportSpec{ + Org: "test", + Repo: "repo", + Version: "v1.0", + Path: tt.path, + } + + err := spec.ValidatePath() + if (err != nil) != tt.wantErr { + t.Errorf("ValidatePath() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func TestImportSpec_IsVersionTag(t *testing.T) { + tests := []struct { + name string + version string + want bool + }{ + { + name: "semver tag v1.5", + version: "v1.5", + want: true, + }, + { + name: "semver tag v2.0.0", + version: "v2.0.0", + want: true, + }, + { + name: "branch name main", + version: "main", + want: false, + }, + { + name: "commit SHA", + version: "abc123def456", + want: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + spec := &ImportSpec{ + Org: "test", + Repo: "repo", + Version: tt.version, + Path: "path.md", + } + + if got := spec.IsVersionTag(); got != tt.want { + t.Errorf("IsVersionTag() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestParseImports(t *testing.T) { + tests := []struct { + name string + input interface{} + wantCount int + wantErr bool + }{ + { + name: "valid array of imports", + input: []interface{}{ + "microsoft/genaiscript v1.5 agentics/engine.md", + "github/copilot v2.0.0 workflows/shared/config.md", + }, + wantCount: 2, + wantErr: false, + }, + { + name: "nil input", + input: nil, + wantCount: 0, + wantErr: false, + }, + { + name: "empty array", + input: []interface{}{}, + wantCount: 0, + wantErr: false, + }, + { + name: "invalid: not an array", + input: "microsoft/genaiscript v1.5 agentics/engine.md", + wantErr: true, + }, + { + name: "invalid: array with non-string", + input: []interface{}{ + "microsoft/genaiscript v1.5 agentics/engine.md", + 123, + }, + wantErr: true, + }, + { + name: "invalid: array with invalid import spec", + input: []interface{}{ + "microsoft/genaiscript v1.5 agentics/engine.md", + "invalid-spec", + }, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + imports, err := ParseImports(tt.input) + + if tt.wantErr { + if err == nil { + t.Errorf("ParseImports() expected error, got nil") + } + return + } + + if err != nil { + t.Fatalf("ParseImports() unexpected error: %v", err) + } + + if len(imports) != tt.wantCount { + t.Errorf("ParseImports() count = %v, want %v", len(imports), tt.wantCount) + } + }) + } +} + +func TestImportSpec_GetLocalCachePath(t *testing.T) { + spec := &ImportSpec{ + Org: "microsoft", + Repo: "genaiscript", + Version: "v1.5", + Path: "agentics/engine.md", + } + + importsDir := "/home/user/.aw/imports" + expected := "/home/user/.aw/imports/microsoft/genaiscript/v1.5" + + got := spec.GetLocalCachePath(importsDir) + if got != expected { + t.Errorf("GetLocalCachePath() = %v, want %v", got, expected) + } +} diff --git a/pkg/workflow/compiler.go b/pkg/workflow/compiler.go index b5bb4856536..97b462170b7 100644 --- a/pkg/workflow/compiler.go +++ b/pkg/workflow/compiler.go @@ -424,6 +424,30 @@ func (c *Compiler) ParseWorkflowFile(markdownPath string) (*WorkflowData, error) markdownDir := filepath.Dir(markdownPath) + // Process imports from frontmatter if present + if _, hasImports := result.Frontmatter["imports"]; hasImports { + if c.verbose { + fmt.Println(console.FormatInfoMessage("Processing imports...")) + } + + processedMarkdown, processedFrontmatter, err := parser.ProcessImportsInFrontmatter( + result.Markdown, + result.Frontmatter, + markdownDir, + ) + if err != nil { + return nil, fmt.Errorf("failed to process imports: %w", err) + } + + // Update result with processed content + result.Markdown = processedMarkdown + result.Frontmatter = processedFrontmatter + + if c.verbose { + fmt.Println(console.FormatSuccessMessage("Successfully processed imports")) + } + } + // Extract AI engine setting from frontmatter engineSetting, engineConfig := c.extractEngineConfig(result.Frontmatter) From 8ebde0094fa3c7904f82e366c30f05888f16f752 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Thu, 2 Oct 2025 06:14:13 +0000 Subject: [PATCH 3/7] feat: add imports schema validation and improve install command - Add imports field to main_workflow_schema.json - Use git ls-remote instead of gh API for version resolution - Add better error handling and verbose output - Successfully tested end-to-end workflow with imports Co-authored-by: pelikhan <4175913+pelikhan@users.noreply.github.com> --- pkg/cli/install_imports.go | 88 +++++++++++++------- pkg/parser/schemas/main_workflow_schema.json | 8 ++ 2 files changed, 68 insertions(+), 28 deletions(-) diff --git a/pkg/cli/install_imports.go b/pkg/cli/install_imports.go index 595461a8232..ab6276d0136 100644 --- a/pkg/cli/install_imports.go +++ b/pkg/cli/install_imports.go @@ -268,7 +268,6 @@ func installSingleImport(importSpec *parser.ImportSpec, importsDir string, lock // resolveImportVersion resolves a version string to a commit SHA func resolveImportVersion(importSpec *parser.ImportSpec, verbose bool) (string, error) { - // Use gh api to resolve the version to a commit SHA repoSlug := importSpec.RepoSlug() version := importSpec.Version @@ -276,41 +275,74 @@ func resolveImportVersion(importSpec *parser.ImportSpec, verbose bool) (string, fmt.Fprintln(os.Stderr, console.FormatInfoMessage(fmt.Sprintf("Resolving version %s for %s", version, repoSlug))) } - // Try to resolve as a ref (branch, tag, or commit) - cmd := exec.Command("gh", "api", fmt.Sprintf("/repos/%s/commits/%s", repoSlug, version)) - output, err := cmd.Output() - if err == nil { - // Parse JSON to get SHA - // For simplicity, just extract the sha field - shaLine := "" - for _, line := range strings.Split(string(output), "\n") { - if strings.Contains(line, "\"sha\":") { - shaLine = line - break + // Use git ls-remote to resolve the version to a commit SHA + // This works without authentication and is more reliable + repoURL := fmt.Sprintf("https://github.com/%s.git", repoSlug) + + // Try to resolve as a branch or tag + cmd := exec.Command("git", "ls-remote", repoURL, version) + output, err := cmd.CombinedOutput() + if verbose && err != nil { + fmt.Fprintln(os.Stderr, console.FormatWarningMessage(fmt.Sprintf("git ls-remote error: %v, output: %s", err, string(output)))) + } + if err == nil && len(output) > 0 { + // Parse output: SHA \t refs/... + lines := strings.Split(string(output), "\n") + for _, line := range lines { + if strings.TrimSpace(line) == "" { + continue + } + parts := strings.Fields(line) + if len(parts) >= 1 { + sha := parts[0] + if len(sha) >= 40 { + if verbose { + fmt.Fprintln(os.Stderr, console.FormatSuccessMessage(fmt.Sprintf("Resolved %s to %s", version, sha[:8]))) + } + return sha[:40], nil + } } } - if shaLine != "" { - // Extract SHA value - sha := strings.TrimSpace(shaLine) - sha = strings.TrimPrefix(sha, "\"sha\":") - sha = strings.Trim(sha, "\", ") - if len(sha) >= 40 { - return sha[:40], nil + } + + // Try as a tag ref + cmd = exec.Command("git", "ls-remote", repoURL, fmt.Sprintf("refs/tags/%s", version)) + output, err = cmd.Output() + if err == nil && len(output) > 0 { + lines := strings.Split(string(output), "\n") + for _, line := range lines { + if strings.TrimSpace(line) == "" { + continue + } + parts := strings.Fields(line) + if len(parts) >= 1 { + sha := parts[0] + if len(sha) >= 40 { + if verbose { + fmt.Fprintln(os.Stderr, console.FormatSuccessMessage(fmt.Sprintf("Resolved %s to %s", version, sha[:8]))) + } + return sha[:40], nil + } } } } - // If that didn't work, try as a tag - cmd = exec.Command("gh", "api", fmt.Sprintf("/repos/%s/git/ref/tags/%s", repoSlug, version)) + // Try as a branch ref + cmd = exec.Command("git", "ls-remote", repoURL, fmt.Sprintf("refs/heads/%s", version)) output, err = cmd.Output() - if err == nil { - // Parse the ref to get object SHA - for _, line := range strings.Split(string(output), "\n") { - if strings.Contains(line, "\"sha\":") { - sha := strings.TrimSpace(line) - sha = strings.TrimPrefix(sha, "\"sha\":") - sha = strings.Trim(sha, "\", ") + if err == nil && len(output) > 0 { + lines := strings.Split(string(output), "\n") + for _, line := range lines { + if strings.TrimSpace(line) == "" { + continue + } + parts := strings.Fields(line) + if len(parts) >= 1 { + sha := parts[0] if len(sha) >= 40 { + if verbose { + fmt.Fprintln(os.Stderr, console.FormatSuccessMessage(fmt.Sprintf("Resolved %s to %s", version, sha[:8]))) + } return sha[:40], nil } } diff --git a/pkg/parser/schemas/main_workflow_schema.json b/pkg/parser/schemas/main_workflow_schema.json index 61ff496f459..4f2cb9cee41 100644 --- a/pkg/parser/schemas/main_workflow_schema.json +++ b/pkg/parser/schemas/main_workflow_schema.json @@ -1333,6 +1333,14 @@ } ] }, + "imports": { + "type": "array", + "description": "Import workflow components from external GitHub repositories. Format: 'org/repo version path' (e.g., 'microsoft/genaiscript v1.5 agentics/engine.md'). Run 'gh aw install' to download imported files before compilation.", + "items": { + "type": "string", + "description": "Import specification in format: 'org/repo version path'" + } + }, "safe-outputs": { "type": "object", "description": "Safe output processing configuration that automatically creates GitHub issues, comments, and pull requests from AI workflow output without requiring write permissions in the main job", From d7fee2ce34c95af54e51e7678680463fb789fa3a Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Thu, 2 Oct 2025 06:17:35 +0000 Subject: [PATCH 4/7] chore: format code with gofmt Co-authored-by: pelikhan <4175913+pelikhan@users.noreply.github.com> --- pkg/cli/install_imports.go | 8 ++++---- pkg/parser/frontmatter.go | 2 +- pkg/workflow/compiler.go | 6 +++--- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/pkg/cli/install_imports.go b/pkg/cli/install_imports.go index ab6276d0136..9dd52a71075 100644 --- a/pkg/cli/install_imports.go +++ b/pkg/cli/install_imports.go @@ -215,7 +215,7 @@ func installSingleImport(importSpec *parser.ImportSpec, importsDir string, lock // Clone repository (shallow clone at specific commit) repoURL := fmt.Sprintf("https://github.com/%s/%s.git", importSpec.Org, importSpec.Repo) - + if verbose { fmt.Fprintln(os.Stderr, console.FormatInfoMessage(fmt.Sprintf("Cloning from %s", repoURL))) } @@ -228,7 +228,7 @@ func installSingleImport(importSpec *parser.ImportSpec, importsDir string, lock if verbose { fmt.Fprintln(os.Stderr, console.FormatInfoMessage("Shallow clone failed, trying full clone...")) } - + cmd = exec.Command("git", "clone", repoURL, targetDir) output, err = cmd.CombinedOutput() if err != nil { @@ -377,7 +377,7 @@ func collectTransitiveFiles(filePath, baseDir string, verbose bool) ([]string, e // Look for @include directives lines := strings.Split(string(content), "\n") - + for _, line := range lines { line = strings.TrimSpace(line) if strings.HasPrefix(line, "@include") { @@ -385,7 +385,7 @@ func collectTransitiveFiles(filePath, baseDir string, verbose bool) ([]string, e parts := strings.Fields(line) if len(parts) >= 2 { includePath := parts[1] - + // Handle section references if strings.Contains(includePath, "#") { parts := strings.SplitN(includePath, "#", 2) diff --git a/pkg/parser/frontmatter.go b/pkg/parser/frontmatter.go index 63457094b10..abf626e4813 100644 --- a/pkg/parser/frontmatter.go +++ b/pkg/parser/frontmatter.go @@ -52,7 +52,7 @@ func ProcessImportsInFrontmatter(content string, frontmatter map[string]any, bas // Process each import var mergedContent strings.Builder mergedFrontmatter := make(map[string]any) - + // Copy existing frontmatter (except imports) for k, v := range frontmatter { if k != "imports" { diff --git a/pkg/workflow/compiler.go b/pkg/workflow/compiler.go index 97b462170b7..9bd3f621cb5 100644 --- a/pkg/workflow/compiler.go +++ b/pkg/workflow/compiler.go @@ -429,7 +429,7 @@ func (c *Compiler) ParseWorkflowFile(markdownPath string) (*WorkflowData, error) if c.verbose { fmt.Println(console.FormatInfoMessage("Processing imports...")) } - + processedMarkdown, processedFrontmatter, err := parser.ProcessImportsInFrontmatter( result.Markdown, result.Frontmatter, @@ -438,11 +438,11 @@ func (c *Compiler) ParseWorkflowFile(markdownPath string) (*WorkflowData, error) if err != nil { return nil, fmt.Errorf("failed to process imports: %w", err) } - + // Update result with processed content result.Markdown = processedMarkdown result.Frontmatter = processedFrontmatter - + if c.verbose { fmt.Println(console.FormatSuccessMessage("Successfully processed imports")) } From f2dfd819d970a9380174d1ebf9ab5332c62254e4 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Thu, 2 Oct 2025 06:19:37 +0000 Subject: [PATCH 5/7] docs: add comprehensive documentation for imports feature Co-authored-by: pelikhan <4175913+pelikhan@users.noreply.github.com> --- docs/src/content/docs/reference/imports.md | 227 +++++++++++++++++++++ 1 file changed, 227 insertions(+) create mode 100644 docs/src/content/docs/reference/imports.md diff --git a/docs/src/content/docs/reference/imports.md b/docs/src/content/docs/reference/imports.md new file mode 100644 index 00000000000..a81ca48b78d --- /dev/null +++ b/docs/src/content/docs/reference/imports.md @@ -0,0 +1,227 @@ +--- +title: Imports +description: Import workflow components from external GitHub repositories +--- + +The `imports` field allows agentic workflows to import content from external GitHub repositories, enabling code reuse and modular workflow design. + +## Basic Usage + +Import components from external repositories by specifying the repository, version, and file path in the frontmatter: + +```aw +--- +on: workflow_dispatch +permissions: + contents: read +engine: claude +imports: + - microsoft/genaiscript v1.5.0 agentics/engine.md + - githubnext/gh-aw main .github/workflows/agentics/shared/tool-refused.md +--- + +# My Workflow + +This workflow imports shared components from external repositories. +``` + +## Import Format + +Each import follows the format: `org/repo version path` + +- **org/repo**: GitHub repository in `owner/repository` format +- **version**: Git reference (branch name, tag, or commit SHA) +- **path**: Relative path to the file within the repository + +Examples: +- `microsoft/genaiscript v1.5.0 agentics/engine.md` - Import from a specific version tag +- `githubnext/gh-aw main .github/workflows/shared/config.md` - Import from main branch +- `example/repo abc123def path/to/file.md` - Import from specific commit + +## Installation + +Before compiling workflows with imports, install the dependencies: + +```bash +# Install imports for all workflows +gh aw install + +# Install imports for a specific workflow +gh aw install my-workflow +``` + +The install command: +1. Parses import specifications from workflow files +2. Resolves versions to commit SHAs using git ls-remote +3. Clones repositories at the specified versions +4. Stores imported files in `.aw/imports/` +5. Creates/updates `.aw/imports.lock` with resolved SHAs + +## Lock File + +The install command generates `.aw/imports.lock` which records: +- Resolved commit SHAs for each import +- Timestamp when imports were resolved +- List of transitive files (from @include directives) + +Example lock file: +``` +# Import lock file generated by gh-aw +# This file records resolved versions and commit SHAs for imports +# Do not edit manually + +version: 1 + +microsoft/genaiscript v1.5.0 agentics/engine.md abc123def456... 2025-01-15T10:30:00Z + +githubnext/gh-aw main .github/workflows/agentics/shared/tool-refused.md ce06aa00a9ce... 2025-01-15T10:30:01Z +``` + +## Compilation + +During compilation, imported files are processed: +1. Frontmatter from imports is merged (tools, engine config, etc.) +2. Markdown content is prepended to the workflow +3. The workflow is compiled as if the content was local + +```bash +# Compile after installing imports +gh aw compile my-workflow +``` + +If imports are not installed, compilation fails with: +``` +error: import org/repo version path not found in lock file (run 'gh aw install') +``` + +## Import Resolution + +Imports are resolved before @include directives during compilation: +1. Parse imports from frontmatter +2. Read lock file and verify imports exist +3. Load imported files from `.aw/imports/` +4. Merge frontmatter and markdown content +5. Process @include directives +6. Compile final workflow + +## Frontmatter Merging + +When importing files with frontmatter, configurations are merged: + +**Tools**: Tool configurations are combined. If the same tool exists in both files, the imported configuration is used. + +```aw +# Imported file +--- +tools: + github: + allowed: [get_issue, list_issues] +--- +``` + +```aw +# Main workflow +--- +imports: + - org/repo v1.0 tools-config.md +tools: + github: + allowed: [get_pull_request] +--- +``` + +Result: GitHub tools will have both sets of allowed functions. + +**Other fields**: Imported values take precedence for non-tools fields. + +## Version Control + +Add `.aw/` to `.gitignore` to exclude cached imports: + +```gitignore +# Workflow imports (local cache and lock file) +.aw/ +``` + +The lock file ensures reproducible builds by pinning exact commit SHAs, similar to `go.sum` or `package-lock.json`. + +## Best Practices + +1. **Use version tags**: Prefer semantic version tags (v1.0.0) over branch names for stability +2. **Install before compile**: Always run `gh aw install` after adding or updating imports +3. **Commit lock file**: Include `.aw/imports.lock` in version control for reproducibility +4. **Test imports**: Verify imported content compiles successfully +5. **Document dependencies**: Document why each import is needed + +## Transitive Dependencies + +Imported files can contain @include directives. The install command automatically: +- Discovers transitive @include references +- Validates all referenced files exist +- Records them in the lock file + +## Comparison with @include + +| Feature | @include | imports | +|---------|----------|---------| +| Source | Local repository | External repositories | +| Resolution | Compile time | Install time | +| Caching | None (always read) | Cached in .aw/imports/ | +| Version control | Implicit (via git) | Explicit (via lock file) | +| Use case | Project-local reuse | Cross-repo sharing | + +Use @include for local files, imports for external dependencies. + +## Troubleshooting + +**Import not found during compile**: +``` +error: import org/repo version path not found in lock file +``` +Solution: Run `gh aw install` to install imports. + +**Version resolution failed**: +``` +error: failed to resolve version v1.0.0 to commit SHA +``` +Solution: Verify the version/tag/branch exists in the repository. + +**File not found in imported repository**: +``` +error: imported file not found: path/to/file.md +``` +Solution: Check the file path exists in the repository at the specified version. + +## Example: Importing Security Notices + +```aw +--- +on: + issues: + types: [opened] +permissions: + contents: read + issues: write +engine: claude +imports: + - githubnext/gh-aw main .github/workflows/agentics/shared/tool-refused.md + - githubnext/gh-aw main .github/workflows/agentics/shared/xpia.md +tools: + github: + allowed: [get_issue, add_issue_comment] +--- + +# Issue Triage Bot + +This workflow imports security notices and tool usage guidelines. + +Analyze issue #${{ github.event.issue.number }} and provide triage recommendations. +``` + +```bash +# Install and compile +gh aw install +gh aw compile issue-triage +``` + +The compiled workflow will include the imported security notices and XPIA protection guidelines. From 21a9f0608d8ca4c8ce3ff54653c85c3ad4152b6c Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Thu, 2 Oct 2025 13:28:49 +0000 Subject: [PATCH 6/7] fix: gitignore only cached imports, not the lock file - Change .gitignore from .aw/ to .aw/imports/ - This allows .aw/imports.lock to be committed - Update documentation to reflect this change - Matches Go's approach where go.sum is committed but modules are not Co-authored-by: pelikhan <4175913+pelikhan@users.noreply.github.com> --- .github/workflows/artifacts-summary.lock.yml | 1696 +++++++++-------- .github/workflows/ci-doctor.lock.yml | 1710 +++++++++--------- .github/workflows/dev.lock.yml | 1696 +++++++++-------- .github/workflows/tidy.lock.yml | 1418 +++++++-------- .gitignore | 4 +- docs/src/content/docs/reference/imports.md | 8 +- 6 files changed, 3263 insertions(+), 3269 deletions(-) diff --git a/.github/workflows/artifacts-summary.lock.yml b/.github/workflows/artifacts-summary.lock.yml index fd431c3c459..e3b0b4fb28e 100644 --- a/.github/workflows/artifacts-summary.lock.yml +++ b/.github/workflows/artifacts-summary.lock.yml @@ -962,742 +962,742 @@ jobs: with: script: | async function main() { - const fs = require("fs"); - function sanitizeContent(content) { - if (!content || typeof content !== "string") { - return ""; + const fs = require("fs"); + function sanitizeContent(content) { + if (!content || typeof content !== "string") { + return ""; + } + const allowedDomainsEnv = process.env.GITHUB_AW_ALLOWED_DOMAINS; + const defaultAllowedDomains = ["github.com", "github.io", "githubusercontent.com", "githubassets.com", "github.dev", "codespaces.new"]; + const allowedDomains = allowedDomainsEnv + ? allowedDomainsEnv + .split(",") + .map(d => d.trim()) + .filter(d => d) + : defaultAllowedDomains; + let sanitized = content; + sanitized = neutralizeMentions(sanitized); + sanitized = removeXmlComments(sanitized); + sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); + sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); + sanitized = sanitizeUrlProtocols(sanitized); + sanitized = sanitizeUrlDomains(sanitized); + const maxLength = 524288; + if (sanitized.length > maxLength) { + sanitized = sanitized.substring(0, maxLength) + "\n[Content truncated due to length]"; + } + const lines = sanitized.split("\n"); + const maxLines = 65000; + if (lines.length > maxLines) { + sanitized = lines.slice(0, maxLines).join("\n") + "\n[Content truncated due to line count]"; + } + sanitized = neutralizeBotTriggers(sanitized); + return sanitized.trim(); + function sanitizeUrlDomains(s) { + return s.replace(/\bhttps:\/\/[^\s\])}'"<>&\x00-\x1f,;]+/gi, match => { + const urlAfterProtocol = match.slice(8); + const hostname = urlAfterProtocol.split(/[\/:\?#]/)[0].toLowerCase(); + const isAllowed = allowedDomains.some(allowedDomain => { + const normalizedAllowed = allowedDomain.toLowerCase(); + return hostname === normalizedAllowed || hostname.endsWith("." + normalizedAllowed); + }); + return isAllowed ? match : "(redacted)"; + }); + } + function sanitizeUrlProtocols(s) { + return s.replace(/\b(\w+):\/\/[^\s\])}'"<>&\x00-\x1f]+/gi, (match, protocol) => { + return protocol.toLowerCase() === "https" ? match : "(redacted)"; + }); + } + function neutralizeMentions(s) { + return s.replace(/(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, (_m, p1, p2) => `${p1}\`@${p2}\``); + } + function removeXmlComments(s) { + return s.replace(//g, "").replace(//g, ""); + } + function neutralizeBotTriggers(s) { + return s.replace(/\b(fixes?|closes?|resolves?|fix|close|resolve)\s+#(\w+)/gi, (match, action, ref) => `\`${action} #${ref}\``); + } } - const allowedDomainsEnv = process.env.GITHUB_AW_ALLOWED_DOMAINS; - const defaultAllowedDomains = ["github.com", "github.io", "githubusercontent.com", "githubassets.com", "github.dev", "codespaces.new"]; - const allowedDomains = allowedDomainsEnv - ? allowedDomainsEnv - .split(",") - .map(d => d.trim()) - .filter(d => d) - : defaultAllowedDomains; - let sanitized = content; - sanitized = neutralizeMentions(sanitized); - sanitized = removeXmlComments(sanitized); - sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); - sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); - sanitized = sanitizeUrlProtocols(sanitized); - sanitized = sanitizeUrlDomains(sanitized); - const maxLength = 524288; - if (sanitized.length > maxLength) { - sanitized = sanitized.substring(0, maxLength) + "\n[Content truncated due to length]"; + function getMaxAllowedForType(itemType, config) { + const itemConfig = config?.[itemType]; + if (itemConfig && typeof itemConfig === "object" && "max" in itemConfig && itemConfig.max) { + return itemConfig.max; + } + switch (itemType) { + case "create-issue": + return 1; + case "add-comment": + return 1; + case "create-pull-request": + return 1; + case "create-pull-request-review-comment": + return 1; + case "add-labels": + return 5; + case "update-issue": + return 1; + case "push-to-pull-request-branch": + return 1; + case "create-discussion": + return 1; + case "missing-tool": + return 1000; + case "create-code-scanning-alert": + return 1000; + case "upload-asset": + return 10; + default: + return 1; + } } - const lines = sanitized.split("\n"); - const maxLines = 65000; - if (lines.length > maxLines) { - sanitized = lines.slice(0, maxLines).join("\n") + "\n[Content truncated due to line count]"; + function getMinRequiredForType(itemType, config) { + const itemConfig = config?.[itemType]; + if (itemConfig && typeof itemConfig === "object" && "min" in itemConfig && itemConfig.min) { + return itemConfig.min; + } + return 0; } - sanitized = neutralizeBotTriggers(sanitized); - return sanitized.trim(); - function sanitizeUrlDomains(s) { - return s.replace(/\bhttps:\/\/[^\s\])}'"<>&\x00-\x1f,;]+/gi, match => { - const urlAfterProtocol = match.slice(8); - const hostname = urlAfterProtocol.split(/[\/:\?#]/)[0].toLowerCase(); - const isAllowed = allowedDomains.some(allowedDomain => { - const normalizedAllowed = allowedDomain.toLowerCase(); - return hostname === normalizedAllowed || hostname.endsWith("." + normalizedAllowed); + function repairJson(jsonStr) { + let repaired = jsonStr.trim(); + const _ctrl = { 8: "\\b", 9: "\\t", 10: "\\n", 12: "\\f", 13: "\\r" }; + repaired = repaired.replace(/[\u0000-\u001F]/g, ch => { + const c = ch.charCodeAt(0); + return _ctrl[c] || "\\u" + c.toString(16).padStart(4, "0"); }); - return isAllowed ? match : "(redacted)"; - }); - } - function sanitizeUrlProtocols(s) { - return s.replace(/\b(\w+):\/\/[^\s\])}'"<>&\x00-\x1f]+/gi, (match, protocol) => { - return protocol.toLowerCase() === "https" ? match : "(redacted)"; - }); - } - function neutralizeMentions(s) { - return s.replace( - /(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, - (_m, p1, p2) => `${p1}\`@${p2}\`` - ); - } - function removeXmlComments(s) { - return s.replace(//g, "").replace(//g, ""); - } - function neutralizeBotTriggers(s) { - return s.replace(/\b(fixes?|closes?|resolves?|fix|close|resolve)\s+#(\w+)/gi, (match, action, ref) => `\`${action} #${ref}\``); - } - } - function getMaxAllowedForType(itemType, config) { - const itemConfig = config?.[itemType]; - if (itemConfig && typeof itemConfig === "object" && "max" in itemConfig && itemConfig.max) { - return itemConfig.max; - } - switch (itemType) { - case "create-issue": - return 1; - case "add-comment": - return 1; - case "create-pull-request": - return 1; - case "create-pull-request-review-comment": - return 1; - case "add-labels": - return 5; - case "update-issue": - return 1; - case "push-to-pull-request-branch": - return 1; - case "create-discussion": - return 1; - case "missing-tool": - return 1000; - case "create-code-scanning-alert": - return 1000; - case "upload-asset": - return 10; - default: - return 1; - } - } - function getMinRequiredForType(itemType, config) { - const itemConfig = config?.[itemType]; - if (itemConfig && typeof itemConfig === "object" && "min" in itemConfig && itemConfig.min) { - return itemConfig.min; - } - return 0; - } - function repairJson(jsonStr) { - let repaired = jsonStr.trim(); - const _ctrl = { 8: "\\b", 9: "\\t", 10: "\\n", 12: "\\f", 13: "\\r" }; - repaired = repaired.replace(/[\u0000-\u001F]/g, ch => { - const c = ch.charCodeAt(0); - return _ctrl[c] || "\\u" + c.toString(16).padStart(4, "0"); - }); - repaired = repaired.replace(/'/g, '"'); - repaired = repaired.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/g, '$1"$2":'); - repaired = repaired.replace(/"([^"\\]*)"/g, (match, content) => { - if (content.includes("\n") || content.includes("\r") || content.includes("\t")) { - const escaped = content.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"); - return `"${escaped}"`; - } - return match; - }); - repaired = repaired.replace(/"([^"]*)"([^":,}\]]*)"([^"]*)"(\s*[,:}\]])/g, (match, p1, p2, p3, p4) => `"${p1}\\"${p2}\\"${p3}"${p4}`); - repaired = repaired.replace(/(\[\s*(?:"[^"]*"(?:\s*,\s*"[^"]*")*\s*),?)\s*}/g, "$1]"); - const openBraces = (repaired.match(/\{/g) || []).length; - const closeBraces = (repaired.match(/\}/g) || []).length; - if (openBraces > closeBraces) { - repaired += "}".repeat(openBraces - closeBraces); - } else if (closeBraces > openBraces) { - repaired = "{".repeat(closeBraces - openBraces) + repaired; - } - const openBrackets = (repaired.match(/\[/g) || []).length; - const closeBrackets = (repaired.match(/\]/g) || []).length; - if (openBrackets > closeBrackets) { - repaired += "]".repeat(openBrackets - closeBrackets); - } else if (closeBrackets > openBrackets) { - repaired = "[".repeat(closeBrackets - openBrackets) + repaired; - } - repaired = repaired.replace(/,(\s*[}\]])/g, "$1"); - return repaired; - } - function validatePositiveInteger(value, fieldName, lineNum) { - if (value === undefined || value === null) { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} is required`, - }; + repaired = repaired.replace(/'/g, '"'); + repaired = repaired.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/g, '$1"$2":'); + repaired = repaired.replace(/"([^"\\]*)"/g, (match, content) => { + if (content.includes("\n") || content.includes("\r") || content.includes("\t")) { + const escaped = content.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"); + return `"${escaped}"`; + } + return match; + }); + repaired = repaired.replace(/"([^"]*)"([^":,}\]]*)"([^"]*)"(\s*[,:}\]])/g, (match, p1, p2, p3, p4) => `"${p1}\\"${p2}\\"${p3}"${p4}`); + repaired = repaired.replace(/(\[\s*(?:"[^"]*"(?:\s*,\s*"[^"]*")*\s*),?)\s*}/g, "$1]"); + const openBraces = (repaired.match(/\{/g) || []).length; + const closeBraces = (repaired.match(/\}/g) || []).length; + if (openBraces > closeBraces) { + repaired += "}".repeat(openBraces - closeBraces); + } + else if (closeBraces > openBraces) { + repaired = "{".repeat(closeBraces - openBraces) + repaired; + } + const openBrackets = (repaired.match(/\[/g) || []).length; + const closeBrackets = (repaired.match(/\]/g) || []).length; + if (openBrackets > closeBrackets) { + repaired += "]".repeat(openBrackets - closeBrackets); + } + else if (closeBrackets > openBrackets) { + repaired = "[".repeat(closeBrackets - openBrackets) + repaired; + } + repaired = repaired.replace(/,(\s*[}\]])/g, "$1"); + return repaired; } - if (typeof value !== "number" && typeof value !== "string") { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number or string field`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; + function validatePositiveInteger(value, fieldName, lineNum) { + if (value === undefined || value === null) { + if (fieldName.includes("create-code-scanning-alert 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, + }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} is required`, + }; + } + if (typeof value !== "number" && typeof value !== "string") { + if (fieldName.includes("create-code-scanning-alert 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, + }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number or string field`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; + } + const parsed = typeof value === "string" ? parseInt(value, 10) : value; + if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { + if (fieldName.includes("create-code-scanning-alert 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'line' must be a valid positive integer (got: ${value})`, + }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'line' must be a positive integer`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, + }; + } + return { isValid: true, normalizedValue: parsed }; } - const parsed = typeof value === "string" ? parseInt(value, 10) : value; - if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'line' must be a valid positive integer (got: ${value})`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'line' must be a positive integer`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, - }; + function validateOptionalPositiveInteger(value, fieldName, lineNum) { + if (value === undefined) { + return { isValid: true }; + } + if (typeof value !== "number" && typeof value !== "string") { + if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a number or string`, + }; + } + if (fieldName.includes("create-code-scanning-alert 'column'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a number or string`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; + } + const parsed = typeof value === "string" ? parseInt(value, 10) : value; + if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { + if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a positive integer`, + }; + } + if (fieldName.includes("create-code-scanning-alert 'column'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a valid positive integer (got: ${value})`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, + }; + } + return { isValid: true, normalizedValue: parsed }; } - return { isValid: true, normalizedValue: parsed }; - } - function validateOptionalPositiveInteger(value, fieldName, lineNum) { - if (value === undefined) { - return { isValid: true }; + function validateIssueOrPRNumber(value, fieldName, lineNum) { + if (value === undefined) { + return { isValid: true }; + } + if (typeof value !== "number" && typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; + } + return { isValid: true }; } - if (typeof value !== "number" && typeof value !== "string") { - if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a number or string`, - }; - } - if (fieldName.includes("create-code-scanning-alert 'column'")) { + function validateFieldWithInputSchema(value, fieldName, inputSchema, lineNum) { + if (inputSchema.required && (value === undefined || value === null)) { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} is required`, + }; + } + if (value === undefined || value === null) { + return { + isValid: true, + normalizedValue: inputSchema.default || undefined, + }; + } + const inputType = inputSchema.type || "string"; + let normalizedValue = value; + switch (inputType) { + case "string": + if (typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a string`, + }; + } + normalizedValue = sanitizeContent(value); + break; + case "boolean": + if (typeof value !== "boolean") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a boolean`, + }; + } + break; + case "number": + if (typeof value !== "number") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number`, + }; + } + break; + case "choice": + if (typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a string for choice type`, + }; + } + if (inputSchema.options && !inputSchema.options.includes(value)) { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be one of: ${inputSchema.options.join(", ")}`, + }; + } + normalizedValue = sanitizeContent(value); + break; + default: + if (typeof value === "string") { + normalizedValue = sanitizeContent(value); + } + break; + } return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a number or string`, + isValid: true, + normalizedValue, }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; } - const parsed = typeof value === "string" ? parseInt(value, 10) : value; - if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { - if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a positive integer`, - }; - } - if (fieldName.includes("create-code-scanning-alert 'column'")) { + function validateItemWithSafeJobConfig(item, jobConfig, lineNum) { + const errors = []; + const normalizedItem = { ...item }; + if (!jobConfig.inputs) { + return { + isValid: true, + errors: [], + normalizedItem: item, + }; + } + for (const [fieldName, inputSchema] of Object.entries(jobConfig.inputs)) { + const fieldValue = item[fieldName]; + const validation = validateFieldWithInputSchema(fieldValue, fieldName, inputSchema, lineNum); + if (!validation.isValid && validation.error) { + errors.push(validation.error); + } + else if (validation.normalizedValue !== undefined) { + normalizedItem[fieldName] = validation.normalizedValue; + } + } return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a valid positive integer (got: ${value})`, + isValid: errors.length === 0, + errors, + normalizedItem, }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, - }; } - return { isValid: true, normalizedValue: parsed }; - } - function validateIssueOrPRNumber(value, fieldName, lineNum) { - if (value === undefined) { - return { isValid: true }; + function parseJsonWithRepair(jsonStr) { + try { + return JSON.parse(jsonStr); + } + catch (originalError) { + try { + const repairedJson = repairJson(jsonStr); + return JSON.parse(repairedJson); + } + catch (repairError) { + core.info(`invalid input json: ${jsonStr}`); + const originalMsg = originalError instanceof Error ? originalError.message : String(originalError); + const repairMsg = repairError instanceof Error ? repairError.message : String(repairError); + throw new Error(`JSON parsing failed. Original: ${originalMsg}. After attempted repair: ${repairMsg}`); + } + } } - if (typeof value !== "number" && typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; + const outputFile = process.env.GITHUB_AW_SAFE_OUTPUTS; + const safeOutputsConfig = process.env.GITHUB_AW_SAFE_OUTPUTS_CONFIG; + if (!outputFile) { + core.info("GITHUB_AW_SAFE_OUTPUTS not set, no output to collect"); + core.setOutput("output", ""); + return; } - return { isValid: true }; - } - function validateFieldWithInputSchema(value, fieldName, inputSchema, lineNum) { - if (inputSchema.required && (value === undefined || value === null)) { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} is required`, - }; + if (!fs.existsSync(outputFile)) { + core.info(`Output file does not exist: ${outputFile}`); + core.setOutput("output", ""); + return; } - if (value === undefined || value === null) { - return { - isValid: true, - normalizedValue: inputSchema.default || undefined, - }; + const outputContent = fs.readFileSync(outputFile, "utf8"); + if (outputContent.trim() === "") { + core.info("Output file is empty"); } - const inputType = inputSchema.type || "string"; - let normalizedValue = value; - switch (inputType) { - case "string": - if (typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a string`, - }; - } - normalizedValue = sanitizeContent(value); - break; - case "boolean": - if (typeof value !== "boolean") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a boolean`, - }; - } - break; - case "number": - if (typeof value !== "number") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number`, - }; - } - break; - case "choice": - if (typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a string for choice type`, - }; - } - if (inputSchema.options && !inputSchema.options.includes(value)) { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be one of: ${inputSchema.options.join(", ")}`, - }; + core.info(`Raw output content length: ${outputContent.length}`); + let expectedOutputTypes = {}; + if (safeOutputsConfig) { + try { + expectedOutputTypes = JSON.parse(safeOutputsConfig); + core.info(`Expected output types: ${JSON.stringify(Object.keys(expectedOutputTypes))}`); } - normalizedValue = sanitizeContent(value); - break; - default: - if (typeof value === "string") { - normalizedValue = sanitizeContent(value); + catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.info(`Warning: Could not parse safe-outputs config: ${errorMsg}`); } - break; } - return { - isValid: true, - normalizedValue, - }; - } - function validateItemWithSafeJobConfig(item, jobConfig, lineNum) { + const lines = outputContent.trim().split("\n"); + const parsedItems = []; const errors = []; - const normalizedItem = { ...item }; - if (!jobConfig.inputs) { - return { - isValid: true, - errors: [], - normalizedItem: item, - }; - } - for (const [fieldName, inputSchema] of Object.entries(jobConfig.inputs)) { - const fieldValue = item[fieldName]; - const validation = validateFieldWithInputSchema(fieldValue, fieldName, inputSchema, lineNum); - if (!validation.isValid && validation.error) { - errors.push(validation.error); - } else if (validation.normalizedValue !== undefined) { - normalizedItem[fieldName] = validation.normalizedValue; - } - } - return { - isValid: errors.length === 0, - errors, - normalizedItem, - }; - } - function parseJsonWithRepair(jsonStr) { - try { - return JSON.parse(jsonStr); - } catch (originalError) { - try { - const repairedJson = repairJson(jsonStr); - return JSON.parse(repairedJson); - } catch (repairError) { - core.info(`invalid input json: ${jsonStr}`); - const originalMsg = originalError instanceof Error ? originalError.message : String(originalError); - const repairMsg = repairError instanceof Error ? repairError.message : String(repairError); - throw new Error(`JSON parsing failed. Original: ${originalMsg}. After attempted repair: ${repairMsg}`); - } - } - } - const outputFile = process.env.GITHUB_AW_SAFE_OUTPUTS; - const safeOutputsConfig = process.env.GITHUB_AW_SAFE_OUTPUTS_CONFIG; - if (!outputFile) { - core.info("GITHUB_AW_SAFE_OUTPUTS not set, no output to collect"); - core.setOutput("output", ""); - return; - } - if (!fs.existsSync(outputFile)) { - core.info(`Output file does not exist: ${outputFile}`); - core.setOutput("output", ""); - return; - } - const outputContent = fs.readFileSync(outputFile, "utf8"); - if (outputContent.trim() === "") { - core.info("Output file is empty"); - } - core.info(`Raw output content length: ${outputContent.length}`); - let expectedOutputTypes = {}; - if (safeOutputsConfig) { - try { - expectedOutputTypes = JSON.parse(safeOutputsConfig); - core.info(`Expected output types: ${JSON.stringify(Object.keys(expectedOutputTypes))}`); - } catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.info(`Warning: Could not parse safe-outputs config: ${errorMsg}`); - } - } - const lines = outputContent.trim().split("\n"); - const parsedItems = []; - const errors = []; - for (let i = 0; i < lines.length; i++) { - const line = lines[i].trim(); - if (line === "") continue; - try { - const item = parseJsonWithRepair(line); - if (item === undefined) { - errors.push(`Line ${i + 1}: Invalid JSON - JSON parsing failed`); - continue; - } - if (!item.type) { - errors.push(`Line ${i + 1}: Missing required 'type' field`); - continue; - } - const itemType = item.type; - if (!expectedOutputTypes[itemType]) { - errors.push(`Line ${i + 1}: Unexpected output type '${itemType}'. Expected one of: ${Object.keys(expectedOutputTypes).join(", ")}`); - continue; - } - const typeCount = parsedItems.filter(existing => existing.type === itemType).length; - const maxAllowed = getMaxAllowedForType(itemType, expectedOutputTypes); - if (typeCount >= maxAllowed) { - errors.push(`Line ${i + 1}: Too many items of type '${itemType}'. Maximum allowed: ${maxAllowed}.`); - continue; - } - core.info(`Line ${i + 1}: type '${itemType}'`); - switch (itemType) { - case "create-issue": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_issue requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_issue requires a 'body' string field`); - continue; - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - if (item.labels && Array.isArray(item.labels)) { - item.labels = item.labels.map(label => (typeof label === "string" ? sanitizeContent(label) : label)); - } - break; - case "add-comment": - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: add_comment requires a 'body' string field`); - continue; - } - const issueNumValidation = validateIssueOrPRNumber(item.issue_number, "add_comment 'issue_number'", i + 1); - if (!issueNumValidation.isValid) { - if (issueNumValidation.error) errors.push(issueNumValidation.error); + for (let i = 0; i < lines.length; i++) { + const line = lines[i].trim(); + if (line === "") continue; - } - item.body = sanitizeContent(item.body); - break; - case "create-pull-request": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'body' string field`); - continue; - } - if (!item.branch || typeof item.branch !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'branch' string field`); - continue; - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - item.branch = sanitizeContent(item.branch); - if (item.labels && Array.isArray(item.labels)) { - item.labels = item.labels.map(label => (typeof label === "string" ? sanitizeContent(label) : label)); - } - break; - case "add-labels": - if (!item.labels || !Array.isArray(item.labels)) { - errors.push(`Line ${i + 1}: add_labels requires a 'labels' array field`); - continue; - } - if (item.labels.some(label => typeof label !== "string")) { - errors.push(`Line ${i + 1}: add_labels labels array must contain only strings`); - continue; - } - const labelsIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "add-labels 'issue_number'", i + 1); - if (!labelsIssueNumValidation.isValid) { - if (labelsIssueNumValidation.error) errors.push(labelsIssueNumValidation.error); - continue; - } - item.labels = item.labels.map(label => sanitizeContent(label)); - break; - case "update-issue": - const hasValidField = item.status !== undefined || item.title !== undefined || item.body !== undefined; - if (!hasValidField) { - errors.push(`Line ${i + 1}: update_issue requires at least one of: 'status', 'title', or 'body' fields`); - continue; - } - if (item.status !== undefined) { - if (typeof item.status !== "string" || (item.status !== "open" && item.status !== "closed")) { - errors.push(`Line ${i + 1}: update_issue 'status' must be 'open' or 'closed'`); - continue; - } - } - if (item.title !== undefined) { - if (typeof item.title !== "string") { - errors.push(`Line ${i + 1}: update-issue 'title' must be a string`); - continue; - } - item.title = sanitizeContent(item.title); - } - if (item.body !== undefined) { - if (typeof item.body !== "string") { - errors.push(`Line ${i + 1}: update-issue 'body' must be a string`); - continue; - } - item.body = sanitizeContent(item.body); - } - const updateIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "update-issue 'issue_number'", i + 1); - if (!updateIssueNumValidation.isValid) { - if (updateIssueNumValidation.error) errors.push(updateIssueNumValidation.error); - continue; - } - break; - case "push-to-pull-request-branch": - if (!item.branch || typeof item.branch !== "string") { - errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'branch' string field`); - continue; - } - if (!item.message || typeof item.message !== "string") { - errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'message' string field`); - continue; - } - item.branch = sanitizeContent(item.branch); - item.message = sanitizeContent(item.message); - const pushPRNumValidation = validateIssueOrPRNumber( - item.pull_request_number, - "push-to-pull-request-branch 'pull_request_number'", - i + 1 - ); - if (!pushPRNumValidation.isValid) { - if (pushPRNumValidation.error) errors.push(pushPRNumValidation.error); - continue; - } - break; - case "create-pull-request-review-comment": - if (!item.path || typeof item.path !== "string") { - errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'path' string field`); - continue; - } - const lineValidation = validatePositiveInteger(item.line, "create-pull-request-review-comment 'line'", i + 1); - if (!lineValidation.isValid) { - if (lineValidation.error) errors.push(lineValidation.error); - continue; - } - const lineNumber = lineValidation.normalizedValue; - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'body' string field`); - continue; - } - item.body = sanitizeContent(item.body); - const startLineValidation = validateOptionalPositiveInteger( - item.start_line, - "create-pull-request-review-comment 'start_line'", - i + 1 - ); - if (!startLineValidation.isValid) { - if (startLineValidation.error) errors.push(startLineValidation.error); - continue; - } - if ( - startLineValidation.normalizedValue !== undefined && - lineNumber !== undefined && - startLineValidation.normalizedValue > lineNumber - ) { - errors.push(`Line ${i + 1}: create-pull-request-review-comment 'start_line' must be less than or equal to 'line'`); - continue; - } - if (item.side !== undefined) { - if (typeof item.side !== "string" || (item.side !== "LEFT" && item.side !== "RIGHT")) { - errors.push(`Line ${i + 1}: create-pull-request-review-comment 'side' must be 'LEFT' or 'RIGHT'`); - continue; + try { + const item = parseJsonWithRepair(line); + if (item === undefined) { + errors.push(`Line ${i + 1}: Invalid JSON - JSON parsing failed`); + continue; } - } - break; - case "create-discussion": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_discussion requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_discussion requires a 'body' string field`); - continue; - } - if (item.category !== undefined) { - if (typeof item.category !== "string") { - errors.push(`Line ${i + 1}: create_discussion 'category' must be a string`); - continue; + if (!item.type) { + errors.push(`Line ${i + 1}: Missing required 'type' field`); + continue; } - item.category = sanitizeContent(item.category); - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - break; - case "missing-tool": - if (!item.tool || typeof item.tool !== "string") { - errors.push(`Line ${i + 1}: missing_tool requires a 'tool' string field`); - continue; - } - if (!item.reason || typeof item.reason !== "string") { - errors.push(`Line ${i + 1}: missing_tool requires a 'reason' string field`); - continue; - } - item.tool = sanitizeContent(item.tool); - item.reason = sanitizeContent(item.reason); - if (item.alternatives !== undefined) { - if (typeof item.alternatives !== "string") { - errors.push(`Line ${i + 1}: missing-tool 'alternatives' must be a string`); - continue; + const itemType = item.type; + if (!expectedOutputTypes[itemType]) { + errors.push(`Line ${i + 1}: Unexpected output type '${itemType}'. Expected one of: ${Object.keys(expectedOutputTypes).join(", ")}`); + continue; } - item.alternatives = sanitizeContent(item.alternatives); - } - break; - case "upload-asset": - if (!item.path || typeof item.path !== "string") { - errors.push(`Line ${i + 1}: upload_asset requires a 'path' string field`); - continue; - } - break; - case "create-code-scanning-alert": - if (!item.file || typeof item.file !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'file' field (string)`); - continue; - } - const alertLineValidation = validatePositiveInteger(item.line, "create-code-scanning-alert 'line'", i + 1); - if (!alertLineValidation.isValid) { - if (alertLineValidation.error) { - errors.push(alertLineValidation.error); + const typeCount = parsedItems.filter(existing => existing.type === itemType).length; + const maxAllowed = getMaxAllowedForType(itemType, expectedOutputTypes); + if (typeCount >= maxAllowed) { + errors.push(`Line ${i + 1}: Too many items of type '${itemType}'. Maximum allowed: ${maxAllowed}.`); + continue; } - continue; - } - if (!item.severity || typeof item.severity !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'severity' field (string)`); - continue; - } - if (!item.message || typeof item.message !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'message' field (string)`); - continue; - } - const allowedSeverities = ["error", "warning", "info", "note"]; - if (!allowedSeverities.includes(item.severity.toLowerCase())) { - errors.push( - `Line ${i + 1}: create-code-scanning-alert 'severity' must be one of: ${allowedSeverities.join(", ")}, got ${item.severity.toLowerCase()}` - ); - continue; - } - const columnValidation = validateOptionalPositiveInteger(item.column, "create-code-scanning-alert 'column'", i + 1); - if (!columnValidation.isValid) { - if (columnValidation.error) errors.push(columnValidation.error); - continue; - } - if (item.ruleIdSuffix !== undefined) { - if (typeof item.ruleIdSuffix !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must be a string`); - continue; - } - if (!/^[a-zA-Z0-9_-]+$/.test(item.ruleIdSuffix.trim())) { - errors.push( - `Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must contain only alphanumeric characters, hyphens, and underscores` - ); - continue; + core.info(`Line ${i + 1}: type '${itemType}'`); + switch (itemType) { + case "create-issue": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_issue requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_issue requires a 'body' string field`); + continue; + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + if (item.labels && Array.isArray(item.labels)) { + item.labels = item.labels.map((label) => (typeof label === "string" ? sanitizeContent(label) : label)); + } + break; + case "add-comment": + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: add_comment requires a 'body' string field`); + continue; + } + const issueNumValidation = validateIssueOrPRNumber(item.issue_number, "add_comment 'issue_number'", i + 1); + if (!issueNumValidation.isValid) { + if (issueNumValidation.error) + errors.push(issueNumValidation.error); + continue; + } + item.body = sanitizeContent(item.body); + break; + case "create-pull-request": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'body' string field`); + continue; + } + if (!item.branch || typeof item.branch !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'branch' string field`); + continue; + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + item.branch = sanitizeContent(item.branch); + if (item.labels && Array.isArray(item.labels)) { + item.labels = item.labels.map((label) => (typeof label === "string" ? sanitizeContent(label) : label)); + } + break; + case "add-labels": + if (!item.labels || !Array.isArray(item.labels)) { + errors.push(`Line ${i + 1}: add_labels requires a 'labels' array field`); + continue; + } + if (item.labels.some((label) => typeof label !== "string")) { + errors.push(`Line ${i + 1}: add_labels labels array must contain only strings`); + continue; + } + const labelsIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "add-labels 'issue_number'", i + 1); + if (!labelsIssueNumValidation.isValid) { + if (labelsIssueNumValidation.error) + errors.push(labelsIssueNumValidation.error); + continue; + } + item.labels = item.labels.map((label) => sanitizeContent(label)); + break; + case "update-issue": + const hasValidField = item.status !== undefined || item.title !== undefined || item.body !== undefined; + if (!hasValidField) { + errors.push(`Line ${i + 1}: update_issue requires at least one of: 'status', 'title', or 'body' fields`); + continue; + } + if (item.status !== undefined) { + if (typeof item.status !== "string" || (item.status !== "open" && item.status !== "closed")) { + errors.push(`Line ${i + 1}: update_issue 'status' must be 'open' or 'closed'`); + continue; + } + } + if (item.title !== undefined) { + if (typeof item.title !== "string") { + errors.push(`Line ${i + 1}: update-issue 'title' must be a string`); + continue; + } + item.title = sanitizeContent(item.title); + } + if (item.body !== undefined) { + if (typeof item.body !== "string") { + errors.push(`Line ${i + 1}: update-issue 'body' must be a string`); + continue; + } + item.body = sanitizeContent(item.body); + } + const updateIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "update-issue 'issue_number'", i + 1); + if (!updateIssueNumValidation.isValid) { + if (updateIssueNumValidation.error) + errors.push(updateIssueNumValidation.error); + continue; + } + break; + case "push-to-pull-request-branch": + if (!item.branch || typeof item.branch !== "string") { + errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'branch' string field`); + continue; + } + if (!item.message || typeof item.message !== "string") { + errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'message' string field`); + continue; + } + item.branch = sanitizeContent(item.branch); + item.message = sanitizeContent(item.message); + const pushPRNumValidation = validateIssueOrPRNumber(item.pull_request_number, "push-to-pull-request-branch 'pull_request_number'", i + 1); + if (!pushPRNumValidation.isValid) { + if (pushPRNumValidation.error) + errors.push(pushPRNumValidation.error); + continue; + } + break; + case "create-pull-request-review-comment": + if (!item.path || typeof item.path !== "string") { + errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'path' string field`); + continue; + } + const lineValidation = validatePositiveInteger(item.line, "create-pull-request-review-comment 'line'", i + 1); + if (!lineValidation.isValid) { + if (lineValidation.error) + errors.push(lineValidation.error); + continue; + } + const lineNumber = lineValidation.normalizedValue; + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'body' string field`); + continue; + } + item.body = sanitizeContent(item.body); + const startLineValidation = validateOptionalPositiveInteger(item.start_line, "create-pull-request-review-comment 'start_line'", i + 1); + if (!startLineValidation.isValid) { + if (startLineValidation.error) + errors.push(startLineValidation.error); + continue; + } + if (startLineValidation.normalizedValue !== undefined && + lineNumber !== undefined && + startLineValidation.normalizedValue > lineNumber) { + errors.push(`Line ${i + 1}: create-pull-request-review-comment 'start_line' must be less than or equal to 'line'`); + continue; + } + if (item.side !== undefined) { + if (typeof item.side !== "string" || (item.side !== "LEFT" && item.side !== "RIGHT")) { + errors.push(`Line ${i + 1}: create-pull-request-review-comment 'side' must be 'LEFT' or 'RIGHT'`); + continue; + } + } + break; + case "create-discussion": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_discussion requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_discussion requires a 'body' string field`); + continue; + } + if (item.category !== undefined) { + if (typeof item.category !== "string") { + errors.push(`Line ${i + 1}: create_discussion 'category' must be a string`); + continue; + } + item.category = sanitizeContent(item.category); + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + break; + case "missing-tool": + if (!item.tool || typeof item.tool !== "string") { + errors.push(`Line ${i + 1}: missing_tool requires a 'tool' string field`); + continue; + } + if (!item.reason || typeof item.reason !== "string") { + errors.push(`Line ${i + 1}: missing_tool requires a 'reason' string field`); + continue; + } + item.tool = sanitizeContent(item.tool); + item.reason = sanitizeContent(item.reason); + if (item.alternatives !== undefined) { + if (typeof item.alternatives !== "string") { + errors.push(`Line ${i + 1}: missing-tool 'alternatives' must be a string`); + continue; + } + item.alternatives = sanitizeContent(item.alternatives); + } + break; + case "upload-asset": + if (!item.path || typeof item.path !== "string") { + errors.push(`Line ${i + 1}: upload_asset requires a 'path' string field`); + continue; + } + break; + case "create-code-scanning-alert": + if (!item.file || typeof item.file !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'file' field (string)`); + continue; + } + const alertLineValidation = validatePositiveInteger(item.line, "create-code-scanning-alert 'line'", i + 1); + if (!alertLineValidation.isValid) { + if (alertLineValidation.error) { + errors.push(alertLineValidation.error); + } + continue; + } + if (!item.severity || typeof item.severity !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'severity' field (string)`); + continue; + } + if (!item.message || typeof item.message !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'message' field (string)`); + continue; + } + const allowedSeverities = ["error", "warning", "info", "note"]; + if (!allowedSeverities.includes(item.severity.toLowerCase())) { + errors.push(`Line ${i + 1}: create-code-scanning-alert 'severity' must be one of: ${allowedSeverities.join(", ")}, got ${item.severity.toLowerCase()}`); + continue; + } + const columnValidation = validateOptionalPositiveInteger(item.column, "create-code-scanning-alert 'column'", i + 1); + if (!columnValidation.isValid) { + if (columnValidation.error) + errors.push(columnValidation.error); + continue; + } + if (item.ruleIdSuffix !== undefined) { + if (typeof item.ruleIdSuffix !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must be a string`); + continue; + } + if (!/^[a-zA-Z0-9_-]+$/.test(item.ruleIdSuffix.trim())) { + errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must contain only alphanumeric characters, hyphens, and underscores`); + continue; + } + } + item.severity = item.severity.toLowerCase(); + item.file = sanitizeContent(item.file); + item.severity = sanitizeContent(item.severity); + item.message = sanitizeContent(item.message); + if (item.ruleIdSuffix) { + item.ruleIdSuffix = sanitizeContent(item.ruleIdSuffix); + } + break; + default: + const jobOutputType = expectedOutputTypes[itemType]; + if (!jobOutputType) { + errors.push(`Line ${i + 1}: Unknown output type '${itemType}'`); + continue; + } + const safeJobConfig = jobOutputType; + if (safeJobConfig && safeJobConfig.inputs) { + const validation = validateItemWithSafeJobConfig(item, safeJobConfig, i + 1); + if (!validation.isValid) { + errors.push(...validation.errors); + continue; + } + Object.assign(item, validation.normalizedItem); + } + break; } - } - item.severity = item.severity.toLowerCase(); - item.file = sanitizeContent(item.file); - item.severity = sanitizeContent(item.severity); - item.message = sanitizeContent(item.message); - if (item.ruleIdSuffix) { - item.ruleIdSuffix = sanitizeContent(item.ruleIdSuffix); - } - break; - default: - const jobOutputType = expectedOutputTypes[itemType]; - if (!jobOutputType) { - errors.push(`Line ${i + 1}: Unknown output type '${itemType}'`); - continue; - } - const safeJobConfig = jobOutputType; - if (safeJobConfig && safeJobConfig.inputs) { - const validation = validateItemWithSafeJobConfig(item, safeJobConfig, i + 1); - if (!validation.isValid) { - errors.push(...validation.errors); - continue; + core.info(`Line ${i + 1}: Valid ${itemType} item`); + parsedItems.push(item); + } + catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + errors.push(`Line ${i + 1}: Invalid JSON - ${errorMsg}`); + } + } + if (errors.length > 0) { + core.warning("Validation errors found:"); + errors.forEach(error => core.warning(` - ${error}`)); + if (parsedItems.length === 0) { + core.setFailed(errors.map(e => ` - ${e}`).join("\n")); + return; + } + } + for (const itemType of Object.keys(expectedOutputTypes)) { + const minRequired = getMinRequiredForType(itemType, expectedOutputTypes); + if (minRequired > 0) { + const actualCount = parsedItems.filter(item => item.type === itemType).length; + if (actualCount < minRequired) { + errors.push(`Too few items of type '${itemType}'. Minimum required: ${minRequired}, found: ${actualCount}.`); } - Object.assign(item, validation.normalizedItem); - } - break; - } - core.info(`Line ${i + 1}: Valid ${itemType} item`); - parsedItems.push(item); - } catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - errors.push(`Line ${i + 1}: Invalid JSON - ${errorMsg}`); + } } - } - if (errors.length > 0) { - core.warning("Validation errors found:"); - errors.forEach(error => core.warning(` - ${error}`)); - if (parsedItems.length === 0) { - core.setFailed(errors.map(e => ` - ${e}`).join("\n")); - return; + core.info(`Successfully parsed ${parsedItems.length} valid output items`); + const validatedOutput = { + items: parsedItems, + errors: errors, + }; + const agentOutputFile = "/tmp/agent_output.json"; + const validatedOutputJson = JSON.stringify(validatedOutput); + try { + fs.mkdirSync("/tmp", { recursive: true }); + fs.writeFileSync(agentOutputFile, validatedOutputJson, "utf8"); + core.info(`Stored validated output to: ${agentOutputFile}`); + core.exportVariable("GITHUB_AW_AGENT_OUTPUT", agentOutputFile); } - } - for (const itemType of Object.keys(expectedOutputTypes)) { - const minRequired = getMinRequiredForType(itemType, expectedOutputTypes); - if (minRequired > 0) { - const actualCount = parsedItems.filter(item => item.type === itemType).length; - if (actualCount < minRequired) { - errors.push(`Too few items of type '${itemType}'. Minimum required: ${minRequired}, found: ${actualCount}.`); - } + catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.error(`Failed to write agent output file: ${errorMsg}`); + } + core.setOutput("output", JSON.stringify(validatedOutput)); + core.setOutput("raw_output", outputContent); + const outputTypes = Array.from(new Set(parsedItems.map(item => item.type))); + core.info(`output_types: ${outputTypes.join(", ")}`); + core.setOutput("output_types", outputTypes.join(",")); + try { + await core.summary + .addRaw("## Processed Output\n\n") + .addRaw("```json\n") + .addRaw(JSON.stringify(validatedOutput)) + .addRaw("\n```\n") + .write(); + core.info("Successfully wrote processed output to step summary"); + } + catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.warning(`Failed to write to step summary: ${errorMsg}`); } - } - core.info(`Successfully parsed ${parsedItems.length} valid output items`); - const validatedOutput = { - items: parsedItems, - errors: errors, - }; - const agentOutputFile = "/tmp/agent_output.json"; - const validatedOutputJson = JSON.stringify(validatedOutput); - try { - fs.mkdirSync("/tmp", { recursive: true }); - fs.writeFileSync(agentOutputFile, validatedOutputJson, "utf8"); - core.info(`Stored validated output to: ${agentOutputFile}`); - core.exportVariable("GITHUB_AW_AGENT_OUTPUT", agentOutputFile); - } catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.error(`Failed to write agent output file: ${errorMsg}`); - } - core.setOutput("output", JSON.stringify(validatedOutput)); - core.setOutput("raw_output", outputContent); - const outputTypes = Array.from(new Set(parsedItems.map(item => item.type))); - core.info(`output_types: ${outputTypes.join(", ")}`); - core.setOutput("output_types", outputTypes.join(",")); - try { - await core.summary - .addRaw("## Processed Output\n\n") - .addRaw("```json\n") - .addRaw(JSON.stringify(validatedOutput)) - .addRaw("\n```\n") - .write(); - core.info("Successfully wrote processed output to step summary"); - } catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.warning(`Failed to write to step summary: ${errorMsg}`); - } } await main(); - name: Upload sanitized agent output @@ -1972,164 +1972,162 @@ jobs: with: script: | function sanitizeLabelContent(content) { - if (!content || typeof content !== "string") { - return ""; - } - let sanitized = content.trim(); - sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); - sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); - sanitized = sanitized.replace( - /(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, - (_m, p1, p2) => `${p1}\`@${p2}\`` - ); - sanitized = sanitized.replace(/[<>&'"]/g, ""); - return sanitized.trim(); + if (!content || typeof content !== "string") { + return ""; + } + let sanitized = content.trim(); + sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); + sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); + sanitized = sanitized.replace(/(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, (_m, p1, p2) => `${p1}\`@${p2}\``); + sanitized = sanitized.replace(/[<>&'"]/g, ""); + return sanitized.trim(); } async function main() { - const isStaged = process.env.GITHUB_AW_SAFE_OUTPUTS_STAGED === "true"; - const outputContent = process.env.GITHUB_AW_AGENT_OUTPUT; - if (!outputContent) { - core.info("No GITHUB_AW_AGENT_OUTPUT environment variable found"); - return; - } - if (outputContent.trim() === "") { - core.info("Agent output content is empty"); - return; - } - core.info(`Agent output content length: ${outputContent.length}`); - let validatedOutput; - try { - validatedOutput = JSON.parse(outputContent); - } catch (error) { - core.setFailed(`Error parsing agent output JSON: ${error instanceof Error ? error.message : String(error)}`); - return; - } - if (!validatedOutput.items || !Array.isArray(validatedOutput.items)) { - core.info("No valid items found in agent output"); - return; - } - const createIssueItems = validatedOutput.items.filter(item => item.type === "create-issue"); - if (createIssueItems.length === 0) { - core.info("No create-issue items found in agent output"); - return; - } - core.info(`Found ${createIssueItems.length} create-issue item(s)`); - if (isStaged) { - let summaryContent = "## 🎭 Staged Mode: Create Issues Preview\n\n"; - summaryContent += "The following issues would be created if staged mode was disabled:\n\n"; - for (let i = 0; i < createIssueItems.length; i++) { - const item = createIssueItems[i]; - summaryContent += `### Issue ${i + 1}\n`; - summaryContent += `**Title:** ${item.title || "No title provided"}\n\n`; - if (item.body) { - summaryContent += `**Body:**\n${item.body}\n\n`; - } - if (item.labels && item.labels.length > 0) { - summaryContent += `**Labels:** ${item.labels.join(", ")}\n\n`; - } - summaryContent += "---\n\n"; + const isStaged = process.env.GITHUB_AW_SAFE_OUTPUTS_STAGED === "true"; + const outputContent = process.env.GITHUB_AW_AGENT_OUTPUT; + if (!outputContent) { + core.info("No GITHUB_AW_AGENT_OUTPUT environment variable found"); + return; } - await core.summary.addRaw(summaryContent).write(); - core.info("📝 Issue creation preview written to step summary"); - return; - } - const parentIssueNumber = context.payload?.issue?.number; - const labelsEnv = process.env.GITHUB_AW_ISSUE_LABELS; - let envLabels = labelsEnv - ? labelsEnv - .split(",") - .map(label => label.trim()) - .filter(label => label) - : []; - const createdIssues = []; - for (let i = 0; i < createIssueItems.length; i++) { - const createIssueItem = createIssueItems[i]; - core.info( - `Processing create-issue item ${i + 1}/${createIssueItems.length}: title=${createIssueItem.title}, bodyLength=${createIssueItem.body.length}` - ); - let labels = [...envLabels]; - if (createIssueItem.labels && Array.isArray(createIssueItem.labels)) { - labels = [...labels, ...createIssueItem.labels]; + if (outputContent.trim() === "") { + core.info("Agent output content is empty"); + return; } - labels = labels - .filter(label => label != null && label !== false && label !== 0) - .map(label => String(label).trim()) - .filter(label => label) - .map(label => sanitizeLabelContent(label)) - .filter(label => label) - .map(label => (label.length > 64 ? label.substring(0, 64) : label)) - .filter((label, index, arr) => arr.indexOf(label) === index); - let title = createIssueItem.title ? createIssueItem.title.trim() : ""; - let bodyLines = createIssueItem.body.split("\n"); - if (!title) { - title = createIssueItem.body || "Agent Output"; + core.info(`Agent output content length: ${outputContent.length}`); + let validatedOutput; + try { + validatedOutput = JSON.parse(outputContent); } - const titlePrefix = process.env.GITHUB_AW_ISSUE_TITLE_PREFIX; - if (titlePrefix && !title.startsWith(titlePrefix)) { - title = titlePrefix + title; + catch (error) { + core.setFailed(`Error parsing agent output JSON: ${error instanceof Error ? error.message : String(error)}`); + return; } - if (parentIssueNumber) { - core.info("Detected issue context, parent issue #" + parentIssueNumber); - bodyLines.push(`Related to #${parentIssueNumber}`); + if (!validatedOutput.items || !Array.isArray(validatedOutput.items)) { + core.info("No valid items found in agent output"); + return; } - const runId = context.runId; - const runUrl = context.payload.repository - ? `${context.payload.repository.html_url}/actions/runs/${runId}` - : `https://github.com/actions/runs/${runId}`; - bodyLines.push(``, ``, `> Generated by Agentic Workflow [Run](${runUrl})`, ""); - const body = bodyLines.join("\n").trim(); - core.info(`Creating issue with title: ${title}`); - core.info(`Labels: ${labels}`); - core.info(`Body length: ${body.length}`); - try { - const { data: issue } = await github.rest.issues.create({ - owner: context.repo.owner, - repo: context.repo.repo, - title: title, - body: body, - labels: labels, - }); - core.info("Created issue #" + issue.number + ": " + issue.html_url); - createdIssues.push(issue); - if (parentIssueNumber) { + const createIssueItems = validatedOutput.items.filter(item => item.type === "create-issue"); + if (createIssueItems.length === 0) { + core.info("No create-issue items found in agent output"); + return; + } + core.info(`Found ${createIssueItems.length} create-issue item(s)`); + if (isStaged) { + let summaryContent = "## 🎭 Staged Mode: Create Issues Preview\n\n"; + summaryContent += "The following issues would be created if staged mode was disabled:\n\n"; + for (let i = 0; i < createIssueItems.length; i++) { + const item = createIssueItems[i]; + summaryContent += `### Issue ${i + 1}\n`; + summaryContent += `**Title:** ${item.title || "No title provided"}\n\n`; + if (item.body) { + summaryContent += `**Body:**\n${item.body}\n\n`; + } + if (item.labels && item.labels.length > 0) { + summaryContent += `**Labels:** ${item.labels.join(", ")}\n\n`; + } + summaryContent += "---\n\n"; + } + await core.summary.addRaw(summaryContent).write(); + core.info("📝 Issue creation preview written to step summary"); + return; + } + const parentIssueNumber = context.payload?.issue?.number; + const labelsEnv = process.env.GITHUB_AW_ISSUE_LABELS; + let envLabels = labelsEnv + ? labelsEnv + .split(",") + .map((label) => label.trim()) + .filter((label) => label) + : []; + const createdIssues = []; + for (let i = 0; i < createIssueItems.length; i++) { + const createIssueItem = createIssueItems[i]; + core.info(`Processing create-issue item ${i + 1}/${createIssueItems.length}: title=${createIssueItem.title}, bodyLength=${createIssueItem.body.length}`); + let labels = [...envLabels]; + if (createIssueItem.labels && Array.isArray(createIssueItem.labels)) { + labels = [...labels, ...createIssueItem.labels]; + } + labels = labels + .filter(label => label != null && label !== false && label !== 0) + .map(label => String(label).trim()) + .filter(label => label) + .map(label => sanitizeLabelContent(label)) + .filter(label => label) + .map(label => (label.length > 64 ? label.substring(0, 64) : label)) + .filter((label, index, arr) => arr.indexOf(label) === index); + let title = createIssueItem.title ? createIssueItem.title.trim() : ""; + let bodyLines = createIssueItem.body.split("\n"); + if (!title) { + title = createIssueItem.body || "Agent Output"; + } + const titlePrefix = process.env.GITHUB_AW_ISSUE_TITLE_PREFIX; + if (titlePrefix && !title.startsWith(titlePrefix)) { + title = titlePrefix + title; + } + if (parentIssueNumber) { + core.info("Detected issue context, parent issue #" + parentIssueNumber); + bodyLines.push(`Related to #${parentIssueNumber}`); + } + const runId = context.runId; + const runUrl = context.payload.repository + ? `${context.payload.repository.html_url}/actions/runs/${runId}` + : `https://github.com/actions/runs/${runId}`; + bodyLines.push(``, ``, `> Generated by Agentic Workflow [Run](${runUrl})`, ""); + const body = bodyLines.join("\n").trim(); + core.info(`Creating issue with title: ${title}`); + core.info(`Labels: ${labels}`); + core.info(`Body length: ${body.length}`); try { - await github.rest.issues.createComment({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: parentIssueNumber, - body: `Created related issue: #${issue.number}`, - }); - core.info("Added comment to parent issue #" + parentIssueNumber); - } catch (error) { - core.info(`Warning: Could not add comment to parent issue: ${error instanceof Error ? error.message : String(error)}`); + const { data: issue } = await github.rest.issues.create({ + owner: context.repo.owner, + repo: context.repo.repo, + title: title, + body: body, + labels: labels, + }); + core.info("Created issue #" + issue.number + ": " + issue.html_url); + createdIssues.push(issue); + if (parentIssueNumber) { + try { + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: parentIssueNumber, + body: `Created related issue: #${issue.number}`, + }); + core.info("Added comment to parent issue #" + parentIssueNumber); + } + catch (error) { + core.info(`Warning: Could not add comment to parent issue: ${error instanceof Error ? error.message : String(error)}`); + } + } + if (i === createIssueItems.length - 1) { + core.setOutput("issue_number", issue.number); + core.setOutput("issue_url", issue.html_url); + } + } + catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + if (errorMessage.includes("Issues has been disabled in this repository")) { + core.info(`⚠ Cannot create issue "${title}": Issues are disabled for this repository`); + core.info("Consider enabling issues in repository settings if you want to create issues automatically"); + continue; + } + core.error(`✗ Failed to create issue "${title}": ${errorMessage}`); + throw error; } - } - if (i === createIssueItems.length - 1) { - core.setOutput("issue_number", issue.number); - core.setOutput("issue_url", issue.html_url); - } - } catch (error) { - const errorMessage = error instanceof Error ? error.message : String(error); - if (errorMessage.includes("Issues has been disabled in this repository")) { - core.info(`⚠ Cannot create issue "${title}": Issues are disabled for this repository`); - core.info("Consider enabling issues in repository settings if you want to create issues automatically"); - continue; - } - core.error(`✗ Failed to create issue "${title}": ${errorMessage}`); - throw error; } - } - if (createdIssues.length > 0) { - let summaryContent = "\n\n## GitHub Issues\n"; - for (const issue of createdIssues) { - summaryContent += `- Issue #${issue.number}: [${issue.title}](${issue.html_url})\n`; + if (createdIssues.length > 0) { + let summaryContent = "\n\n## GitHub Issues\n"; + for (const issue of createdIssues) { + summaryContent += `- Issue #${issue.number}: [${issue.title}](${issue.html_url})\n`; + } + await core.summary.addRaw(summaryContent).write(); } - await core.summary.addRaw(summaryContent).write(); - } - core.info(`Successfully created ${createdIssues.length} issue(s)`); + core.info(`Successfully created ${createdIssues.length} issue(s)`); } (async () => { - await main(); + await main(); })(); missing_tool: diff --git a/.github/workflows/ci-doctor.lock.yml b/.github/workflows/ci-doctor.lock.yml index 91392138389..a6903270cd1 100644 --- a/.github/workflows/ci-doctor.lock.yml +++ b/.github/workflows/ci-doctor.lock.yml @@ -1213,742 +1213,742 @@ jobs: with: script: | async function main() { - const fs = require("fs"); - function sanitizeContent(content) { - if (!content || typeof content !== "string") { - return ""; - } - const allowedDomainsEnv = process.env.GITHUB_AW_ALLOWED_DOMAINS; - const defaultAllowedDomains = ["github.com", "github.io", "githubusercontent.com", "githubassets.com", "github.dev", "codespaces.new"]; - const allowedDomains = allowedDomainsEnv - ? allowedDomainsEnv - .split(",") - .map(d => d.trim()) - .filter(d => d) - : defaultAllowedDomains; - let sanitized = content; - sanitized = neutralizeMentions(sanitized); - sanitized = removeXmlComments(sanitized); - sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); - sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); - sanitized = sanitizeUrlProtocols(sanitized); - sanitized = sanitizeUrlDomains(sanitized); - const maxLength = 524288; - if (sanitized.length > maxLength) { - sanitized = sanitized.substring(0, maxLength) + "\n[Content truncated due to length]"; - } - const lines = sanitized.split("\n"); - const maxLines = 65000; - if (lines.length > maxLines) { - sanitized = lines.slice(0, maxLines).join("\n") + "\n[Content truncated due to line count]"; - } - sanitized = neutralizeBotTriggers(sanitized); - return sanitized.trim(); - function sanitizeUrlDomains(s) { - return s.replace(/\bhttps:\/\/[^\s\])}'"<>&\x00-\x1f,;]+/gi, match => { - const urlAfterProtocol = match.slice(8); - const hostname = urlAfterProtocol.split(/[\/:\?#]/)[0].toLowerCase(); - const isAllowed = allowedDomains.some(allowedDomain => { - const normalizedAllowed = allowedDomain.toLowerCase(); - return hostname === normalizedAllowed || hostname.endsWith("." + normalizedAllowed); - }); - return isAllowed ? match : "(redacted)"; - }); - } - function sanitizeUrlProtocols(s) { - return s.replace(/\b(\w+):\/\/[^\s\])}'"<>&\x00-\x1f]+/gi, (match, protocol) => { - return protocol.toLowerCase() === "https" ? match : "(redacted)"; - }); - } - function neutralizeMentions(s) { - return s.replace( - /(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, - (_m, p1, p2) => `${p1}\`@${p2}\`` - ); - } - function removeXmlComments(s) { - return s.replace(//g, "").replace(//g, ""); - } - function neutralizeBotTriggers(s) { - return s.replace(/\b(fixes?|closes?|resolves?|fix|close|resolve)\s+#(\w+)/gi, (match, action, ref) => `\`${action} #${ref}\``); - } - } - function getMaxAllowedForType(itemType, config) { - const itemConfig = config?.[itemType]; - if (itemConfig && typeof itemConfig === "object" && "max" in itemConfig && itemConfig.max) { - return itemConfig.max; - } - switch (itemType) { - case "create-issue": - return 1; - case "add-comment": - return 1; - case "create-pull-request": - return 1; - case "create-pull-request-review-comment": - return 1; - case "add-labels": - return 5; - case "update-issue": - return 1; - case "push-to-pull-request-branch": - return 1; - case "create-discussion": - return 1; - case "missing-tool": - return 1000; - case "create-code-scanning-alert": - return 1000; - case "upload-asset": - return 10; - default: - return 1; + const fs = require("fs"); + function sanitizeContent(content) { + if (!content || typeof content !== "string") { + return ""; + } + const allowedDomainsEnv = process.env.GITHUB_AW_ALLOWED_DOMAINS; + const defaultAllowedDomains = ["github.com", "github.io", "githubusercontent.com", "githubassets.com", "github.dev", "codespaces.new"]; + const allowedDomains = allowedDomainsEnv + ? allowedDomainsEnv + .split(",") + .map(d => d.trim()) + .filter(d => d) + : defaultAllowedDomains; + let sanitized = content; + sanitized = neutralizeMentions(sanitized); + sanitized = removeXmlComments(sanitized); + sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); + sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); + sanitized = sanitizeUrlProtocols(sanitized); + sanitized = sanitizeUrlDomains(sanitized); + const maxLength = 524288; + if (sanitized.length > maxLength) { + sanitized = sanitized.substring(0, maxLength) + "\n[Content truncated due to length]"; + } + const lines = sanitized.split("\n"); + const maxLines = 65000; + if (lines.length > maxLines) { + sanitized = lines.slice(0, maxLines).join("\n") + "\n[Content truncated due to line count]"; + } + sanitized = neutralizeBotTriggers(sanitized); + return sanitized.trim(); + function sanitizeUrlDomains(s) { + return s.replace(/\bhttps:\/\/[^\s\])}'"<>&\x00-\x1f,;]+/gi, match => { + const urlAfterProtocol = match.slice(8); + const hostname = urlAfterProtocol.split(/[\/:\?#]/)[0].toLowerCase(); + const isAllowed = allowedDomains.some(allowedDomain => { + const normalizedAllowed = allowedDomain.toLowerCase(); + return hostname === normalizedAllowed || hostname.endsWith("." + normalizedAllowed); + }); + return isAllowed ? match : "(redacted)"; + }); + } + function sanitizeUrlProtocols(s) { + return s.replace(/\b(\w+):\/\/[^\s\])}'"<>&\x00-\x1f]+/gi, (match, protocol) => { + return protocol.toLowerCase() === "https" ? match : "(redacted)"; + }); + } + function neutralizeMentions(s) { + return s.replace(/(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, (_m, p1, p2) => `${p1}\`@${p2}\``); + } + function removeXmlComments(s) { + return s.replace(//g, "").replace(//g, ""); + } + function neutralizeBotTriggers(s) { + return s.replace(/\b(fixes?|closes?|resolves?|fix|close|resolve)\s+#(\w+)/gi, (match, action, ref) => `\`${action} #${ref}\``); + } } - } - function getMinRequiredForType(itemType, config) { - const itemConfig = config?.[itemType]; - if (itemConfig && typeof itemConfig === "object" && "min" in itemConfig && itemConfig.min) { - return itemConfig.min; + function getMaxAllowedForType(itemType, config) { + const itemConfig = config?.[itemType]; + if (itemConfig && typeof itemConfig === "object" && "max" in itemConfig && itemConfig.max) { + return itemConfig.max; + } + switch (itemType) { + case "create-issue": + return 1; + case "add-comment": + return 1; + case "create-pull-request": + return 1; + case "create-pull-request-review-comment": + return 1; + case "add-labels": + return 5; + case "update-issue": + return 1; + case "push-to-pull-request-branch": + return 1; + case "create-discussion": + return 1; + case "missing-tool": + return 1000; + case "create-code-scanning-alert": + return 1000; + case "upload-asset": + return 10; + default: + return 1; + } } - return 0; - } - function repairJson(jsonStr) { - let repaired = jsonStr.trim(); - const _ctrl = { 8: "\\b", 9: "\\t", 10: "\\n", 12: "\\f", 13: "\\r" }; - repaired = repaired.replace(/[\u0000-\u001F]/g, ch => { - const c = ch.charCodeAt(0); - return _ctrl[c] || "\\u" + c.toString(16).padStart(4, "0"); - }); - repaired = repaired.replace(/'/g, '"'); - repaired = repaired.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/g, '$1"$2":'); - repaired = repaired.replace(/"([^"\\]*)"/g, (match, content) => { - if (content.includes("\n") || content.includes("\r") || content.includes("\t")) { - const escaped = content.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"); - return `"${escaped}"`; - } - return match; - }); - repaired = repaired.replace(/"([^"]*)"([^":,}\]]*)"([^"]*)"(\s*[,:}\]])/g, (match, p1, p2, p3, p4) => `"${p1}\\"${p2}\\"${p3}"${p4}`); - repaired = repaired.replace(/(\[\s*(?:"[^"]*"(?:\s*,\s*"[^"]*")*\s*),?)\s*}/g, "$1]"); - const openBraces = (repaired.match(/\{/g) || []).length; - const closeBraces = (repaired.match(/\}/g) || []).length; - if (openBraces > closeBraces) { - repaired += "}".repeat(openBraces - closeBraces); - } else if (closeBraces > openBraces) { - repaired = "{".repeat(closeBraces - openBraces) + repaired; - } - const openBrackets = (repaired.match(/\[/g) || []).length; - const closeBrackets = (repaired.match(/\]/g) || []).length; - if (openBrackets > closeBrackets) { - repaired += "]".repeat(openBrackets - closeBrackets); - } else if (closeBrackets > openBrackets) { - repaired = "[".repeat(closeBrackets - openBrackets) + repaired; - } - repaired = repaired.replace(/,(\s*[}\]])/g, "$1"); - return repaired; - } - function validatePositiveInteger(value, fieldName, lineNum) { - if (value === undefined || value === null) { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} is required`, - }; + function getMinRequiredForType(itemType, config) { + const itemConfig = config?.[itemType]; + if (itemConfig && typeof itemConfig === "object" && "min" in itemConfig && itemConfig.min) { + return itemConfig.min; + } + return 0; + } + function repairJson(jsonStr) { + let repaired = jsonStr.trim(); + const _ctrl = { 8: "\\b", 9: "\\t", 10: "\\n", 12: "\\f", 13: "\\r" }; + repaired = repaired.replace(/[\u0000-\u001F]/g, ch => { + const c = ch.charCodeAt(0); + return _ctrl[c] || "\\u" + c.toString(16).padStart(4, "0"); + }); + repaired = repaired.replace(/'/g, '"'); + repaired = repaired.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/g, '$1"$2":'); + repaired = repaired.replace(/"([^"\\]*)"/g, (match, content) => { + if (content.includes("\n") || content.includes("\r") || content.includes("\t")) { + const escaped = content.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"); + return `"${escaped}"`; + } + return match; + }); + repaired = repaired.replace(/"([^"]*)"([^":,}\]]*)"([^"]*)"(\s*[,:}\]])/g, (match, p1, p2, p3, p4) => `"${p1}\\"${p2}\\"${p3}"${p4}`); + repaired = repaired.replace(/(\[\s*(?:"[^"]*"(?:\s*,\s*"[^"]*")*\s*),?)\s*}/g, "$1]"); + const openBraces = (repaired.match(/\{/g) || []).length; + const closeBraces = (repaired.match(/\}/g) || []).length; + if (openBraces > closeBraces) { + repaired += "}".repeat(openBraces - closeBraces); + } + else if (closeBraces > openBraces) { + repaired = "{".repeat(closeBraces - openBraces) + repaired; + } + const openBrackets = (repaired.match(/\[/g) || []).length; + const closeBrackets = (repaired.match(/\]/g) || []).length; + if (openBrackets > closeBrackets) { + repaired += "]".repeat(openBrackets - closeBrackets); + } + else if (closeBrackets > openBrackets) { + repaired = "[".repeat(closeBrackets - openBrackets) + repaired; + } + repaired = repaired.replace(/,(\s*[}\]])/g, "$1"); + return repaired; + } + function validatePositiveInteger(value, fieldName, lineNum) { + if (value === undefined || value === null) { + if (fieldName.includes("create-code-scanning-alert 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, + }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} is required`, + }; + } + if (typeof value !== "number" && typeof value !== "string") { + if (fieldName.includes("create-code-scanning-alert 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, + }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number or string field`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; + } + const parsed = typeof value === "string" ? parseInt(value, 10) : value; + if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { + if (fieldName.includes("create-code-scanning-alert 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'line' must be a valid positive integer (got: ${value})`, + }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'line' must be a positive integer`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, + }; + } + return { isValid: true, normalizedValue: parsed }; } - if (typeof value !== "number" && typeof value !== "string") { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number or string field`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; + function validateOptionalPositiveInteger(value, fieldName, lineNum) { + if (value === undefined) { + return { isValid: true }; + } + if (typeof value !== "number" && typeof value !== "string") { + if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a number or string`, + }; + } + if (fieldName.includes("create-code-scanning-alert 'column'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a number or string`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; + } + const parsed = typeof value === "string" ? parseInt(value, 10) : value; + if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { + if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a positive integer`, + }; + } + if (fieldName.includes("create-code-scanning-alert 'column'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a valid positive integer (got: ${value})`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, + }; + } + return { isValid: true, normalizedValue: parsed }; } - const parsed = typeof value === "string" ? parseInt(value, 10) : value; - if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'line' must be a valid positive integer (got: ${value})`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { + function validateIssueOrPRNumber(value, fieldName, lineNum) { + if (value === undefined) { + return { isValid: true }; + } + if (typeof value !== "number" && typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; + } + return { isValid: true }; + } + function validateFieldWithInputSchema(value, fieldName, inputSchema, lineNum) { + if (inputSchema.required && (value === undefined || value === null)) { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} is required`, + }; + } + if (value === undefined || value === null) { + return { + isValid: true, + normalizedValue: inputSchema.default || undefined, + }; + } + const inputType = inputSchema.type || "string"; + let normalizedValue = value; + switch (inputType) { + case "string": + if (typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a string`, + }; + } + normalizedValue = sanitizeContent(value); + break; + case "boolean": + if (typeof value !== "boolean") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a boolean`, + }; + } + break; + case "number": + if (typeof value !== "number") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number`, + }; + } + break; + case "choice": + if (typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a string for choice type`, + }; + } + if (inputSchema.options && !inputSchema.options.includes(value)) { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be one of: ${inputSchema.options.join(", ")}`, + }; + } + normalizedValue = sanitizeContent(value); + break; + default: + if (typeof value === "string") { + normalizedValue = sanitizeContent(value); + } + break; + } return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'line' must be a positive integer`, + isValid: true, + normalizedValue, }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, - }; } - return { isValid: true, normalizedValue: parsed }; - } - function validateOptionalPositiveInteger(value, fieldName, lineNum) { - if (value === undefined) { - return { isValid: true }; - } - if (typeof value !== "number" && typeof value !== "string") { - if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a number or string`, - }; - } - if (fieldName.includes("create-code-scanning-alert 'column'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a number or string`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; - } - const parsed = typeof value === "string" ? parseInt(value, 10) : value; - if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { - if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a positive integer`, - }; - } - if (fieldName.includes("create-code-scanning-alert 'column'")) { + function validateItemWithSafeJobConfig(item, jobConfig, lineNum) { + const errors = []; + const normalizedItem = { ...item }; + if (!jobConfig.inputs) { + return { + isValid: true, + errors: [], + normalizedItem: item, + }; + } + for (const [fieldName, inputSchema] of Object.entries(jobConfig.inputs)) { + const fieldValue = item[fieldName]; + const validation = validateFieldWithInputSchema(fieldValue, fieldName, inputSchema, lineNum); + if (!validation.isValid && validation.error) { + errors.push(validation.error); + } + else if (validation.normalizedValue !== undefined) { + normalizedItem[fieldName] = validation.normalizedValue; + } + } return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a valid positive integer (got: ${value})`, + isValid: errors.length === 0, + errors, + normalizedItem, }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, - }; } - return { isValid: true, normalizedValue: parsed }; - } - function validateIssueOrPRNumber(value, fieldName, lineNum) { - if (value === undefined) { - return { isValid: true }; + function parseJsonWithRepair(jsonStr) { + try { + return JSON.parse(jsonStr); + } + catch (originalError) { + try { + const repairedJson = repairJson(jsonStr); + return JSON.parse(repairedJson); + } + catch (repairError) { + core.info(`invalid input json: ${jsonStr}`); + const originalMsg = originalError instanceof Error ? originalError.message : String(originalError); + const repairMsg = repairError instanceof Error ? repairError.message : String(repairError); + throw new Error(`JSON parsing failed. Original: ${originalMsg}. After attempted repair: ${repairMsg}`); + } + } } - if (typeof value !== "number" && typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; + const outputFile = process.env.GITHUB_AW_SAFE_OUTPUTS; + const safeOutputsConfig = process.env.GITHUB_AW_SAFE_OUTPUTS_CONFIG; + if (!outputFile) { + core.info("GITHUB_AW_SAFE_OUTPUTS not set, no output to collect"); + core.setOutput("output", ""); + return; } - return { isValid: true }; - } - function validateFieldWithInputSchema(value, fieldName, inputSchema, lineNum) { - if (inputSchema.required && (value === undefined || value === null)) { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} is required`, - }; + if (!fs.existsSync(outputFile)) { + core.info(`Output file does not exist: ${outputFile}`); + core.setOutput("output", ""); + return; } - if (value === undefined || value === null) { - return { - isValid: true, - normalizedValue: inputSchema.default || undefined, - }; + const outputContent = fs.readFileSync(outputFile, "utf8"); + if (outputContent.trim() === "") { + core.info("Output file is empty"); } - const inputType = inputSchema.type || "string"; - let normalizedValue = value; - switch (inputType) { - case "string": - if (typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a string`, - }; - } - normalizedValue = sanitizeContent(value); - break; - case "boolean": - if (typeof value !== "boolean") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a boolean`, - }; - } - break; - case "number": - if (typeof value !== "number") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number`, - }; - } - break; - case "choice": - if (typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a string for choice type`, - }; - } - if (inputSchema.options && !inputSchema.options.includes(value)) { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be one of: ${inputSchema.options.join(", ")}`, - }; + core.info(`Raw output content length: ${outputContent.length}`); + let expectedOutputTypes = {}; + if (safeOutputsConfig) { + try { + expectedOutputTypes = JSON.parse(safeOutputsConfig); + core.info(`Expected output types: ${JSON.stringify(Object.keys(expectedOutputTypes))}`); } - normalizedValue = sanitizeContent(value); - break; - default: - if (typeof value === "string") { - normalizedValue = sanitizeContent(value); + catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.info(`Warning: Could not parse safe-outputs config: ${errorMsg}`); } - break; } - return { - isValid: true, - normalizedValue, - }; - } - function validateItemWithSafeJobConfig(item, jobConfig, lineNum) { + const lines = outputContent.trim().split("\n"); + const parsedItems = []; const errors = []; - const normalizedItem = { ...item }; - if (!jobConfig.inputs) { - return { - isValid: true, - errors: [], - normalizedItem: item, - }; - } - for (const [fieldName, inputSchema] of Object.entries(jobConfig.inputs)) { - const fieldValue = item[fieldName]; - const validation = validateFieldWithInputSchema(fieldValue, fieldName, inputSchema, lineNum); - if (!validation.isValid && validation.error) { - errors.push(validation.error); - } else if (validation.normalizedValue !== undefined) { - normalizedItem[fieldName] = validation.normalizedValue; - } - } - return { - isValid: errors.length === 0, - errors, - normalizedItem, - }; - } - function parseJsonWithRepair(jsonStr) { - try { - return JSON.parse(jsonStr); - } catch (originalError) { - try { - const repairedJson = repairJson(jsonStr); - return JSON.parse(repairedJson); - } catch (repairError) { - core.info(`invalid input json: ${jsonStr}`); - const originalMsg = originalError instanceof Error ? originalError.message : String(originalError); - const repairMsg = repairError instanceof Error ? repairError.message : String(repairError); - throw new Error(`JSON parsing failed. Original: ${originalMsg}. After attempted repair: ${repairMsg}`); - } - } - } - const outputFile = process.env.GITHUB_AW_SAFE_OUTPUTS; - const safeOutputsConfig = process.env.GITHUB_AW_SAFE_OUTPUTS_CONFIG; - if (!outputFile) { - core.info("GITHUB_AW_SAFE_OUTPUTS not set, no output to collect"); - core.setOutput("output", ""); - return; - } - if (!fs.existsSync(outputFile)) { - core.info(`Output file does not exist: ${outputFile}`); - core.setOutput("output", ""); - return; - } - const outputContent = fs.readFileSync(outputFile, "utf8"); - if (outputContent.trim() === "") { - core.info("Output file is empty"); - } - core.info(`Raw output content length: ${outputContent.length}`); - let expectedOutputTypes = {}; - if (safeOutputsConfig) { - try { - expectedOutputTypes = JSON.parse(safeOutputsConfig); - core.info(`Expected output types: ${JSON.stringify(Object.keys(expectedOutputTypes))}`); - } catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.info(`Warning: Could not parse safe-outputs config: ${errorMsg}`); - } - } - const lines = outputContent.trim().split("\n"); - const parsedItems = []; - const errors = []; - for (let i = 0; i < lines.length; i++) { - const line = lines[i].trim(); - if (line === "") continue; - try { - const item = parseJsonWithRepair(line); - if (item === undefined) { - errors.push(`Line ${i + 1}: Invalid JSON - JSON parsing failed`); - continue; - } - if (!item.type) { - errors.push(`Line ${i + 1}: Missing required 'type' field`); - continue; - } - const itemType = item.type; - if (!expectedOutputTypes[itemType]) { - errors.push(`Line ${i + 1}: Unexpected output type '${itemType}'. Expected one of: ${Object.keys(expectedOutputTypes).join(", ")}`); - continue; - } - const typeCount = parsedItems.filter(existing => existing.type === itemType).length; - const maxAllowed = getMaxAllowedForType(itemType, expectedOutputTypes); - if (typeCount >= maxAllowed) { - errors.push(`Line ${i + 1}: Too many items of type '${itemType}'. Maximum allowed: ${maxAllowed}.`); - continue; - } - core.info(`Line ${i + 1}: type '${itemType}'`); - switch (itemType) { - case "create-issue": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_issue requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_issue requires a 'body' string field`); - continue; - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - if (item.labels && Array.isArray(item.labels)) { - item.labels = item.labels.map(label => (typeof label === "string" ? sanitizeContent(label) : label)); - } - break; - case "add-comment": - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: add_comment requires a 'body' string field`); - continue; - } - const issueNumValidation = validateIssueOrPRNumber(item.issue_number, "add_comment 'issue_number'", i + 1); - if (!issueNumValidation.isValid) { - if (issueNumValidation.error) errors.push(issueNumValidation.error); - continue; - } - item.body = sanitizeContent(item.body); - break; - case "create-pull-request": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'body' string field`); - continue; - } - if (!item.branch || typeof item.branch !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'branch' string field`); - continue; - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - item.branch = sanitizeContent(item.branch); - if (item.labels && Array.isArray(item.labels)) { - item.labels = item.labels.map(label => (typeof label === "string" ? sanitizeContent(label) : label)); - } - break; - case "add-labels": - if (!item.labels || !Array.isArray(item.labels)) { - errors.push(`Line ${i + 1}: add_labels requires a 'labels' array field`); + for (let i = 0; i < lines.length; i++) { + const line = lines[i].trim(); + if (line === "") continue; - } - if (item.labels.some(label => typeof label !== "string")) { - errors.push(`Line ${i + 1}: add_labels labels array must contain only strings`); - continue; - } - const labelsIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "add-labels 'issue_number'", i + 1); - if (!labelsIssueNumValidation.isValid) { - if (labelsIssueNumValidation.error) errors.push(labelsIssueNumValidation.error); - continue; - } - item.labels = item.labels.map(label => sanitizeContent(label)); - break; - case "update-issue": - const hasValidField = item.status !== undefined || item.title !== undefined || item.body !== undefined; - if (!hasValidField) { - errors.push(`Line ${i + 1}: update_issue requires at least one of: 'status', 'title', or 'body' fields`); - continue; - } - if (item.status !== undefined) { - if (typeof item.status !== "string" || (item.status !== "open" && item.status !== "closed")) { - errors.push(`Line ${i + 1}: update_issue 'status' must be 'open' or 'closed'`); - continue; - } - } - if (item.title !== undefined) { - if (typeof item.title !== "string") { - errors.push(`Line ${i + 1}: update-issue 'title' must be a string`); - continue; - } - item.title = sanitizeContent(item.title); - } - if (item.body !== undefined) { - if (typeof item.body !== "string") { - errors.push(`Line ${i + 1}: update-issue 'body' must be a string`); - continue; - } - item.body = sanitizeContent(item.body); - } - const updateIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "update-issue 'issue_number'", i + 1); - if (!updateIssueNumValidation.isValid) { - if (updateIssueNumValidation.error) errors.push(updateIssueNumValidation.error); - continue; - } - break; - case "push-to-pull-request-branch": - if (!item.branch || typeof item.branch !== "string") { - errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'branch' string field`); - continue; - } - if (!item.message || typeof item.message !== "string") { - errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'message' string field`); - continue; - } - item.branch = sanitizeContent(item.branch); - item.message = sanitizeContent(item.message); - const pushPRNumValidation = validateIssueOrPRNumber( - item.pull_request_number, - "push-to-pull-request-branch 'pull_request_number'", - i + 1 - ); - if (!pushPRNumValidation.isValid) { - if (pushPRNumValidation.error) errors.push(pushPRNumValidation.error); - continue; - } - break; - case "create-pull-request-review-comment": - if (!item.path || typeof item.path !== "string") { - errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'path' string field`); - continue; - } - const lineValidation = validatePositiveInteger(item.line, "create-pull-request-review-comment 'line'", i + 1); - if (!lineValidation.isValid) { - if (lineValidation.error) errors.push(lineValidation.error); - continue; - } - const lineNumber = lineValidation.normalizedValue; - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'body' string field`); - continue; - } - item.body = sanitizeContent(item.body); - const startLineValidation = validateOptionalPositiveInteger( - item.start_line, - "create-pull-request-review-comment 'start_line'", - i + 1 - ); - if (!startLineValidation.isValid) { - if (startLineValidation.error) errors.push(startLineValidation.error); - continue; - } - if ( - startLineValidation.normalizedValue !== undefined && - lineNumber !== undefined && - startLineValidation.normalizedValue > lineNumber - ) { - errors.push(`Line ${i + 1}: create-pull-request-review-comment 'start_line' must be less than or equal to 'line'`); - continue; - } - if (item.side !== undefined) { - if (typeof item.side !== "string" || (item.side !== "LEFT" && item.side !== "RIGHT")) { - errors.push(`Line ${i + 1}: create-pull-request-review-comment 'side' must be 'LEFT' or 'RIGHT'`); - continue; - } - } - break; - case "create-discussion": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_discussion requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_discussion requires a 'body' string field`); - continue; - } - if (item.category !== undefined) { - if (typeof item.category !== "string") { - errors.push(`Line ${i + 1}: create_discussion 'category' must be a string`); - continue; - } - item.category = sanitizeContent(item.category); - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - break; - case "missing-tool": - if (!item.tool || typeof item.tool !== "string") { - errors.push(`Line ${i + 1}: missing_tool requires a 'tool' string field`); - continue; - } - if (!item.reason || typeof item.reason !== "string") { - errors.push(`Line ${i + 1}: missing_tool requires a 'reason' string field`); - continue; - } - item.tool = sanitizeContent(item.tool); - item.reason = sanitizeContent(item.reason); - if (item.alternatives !== undefined) { - if (typeof item.alternatives !== "string") { - errors.push(`Line ${i + 1}: missing-tool 'alternatives' must be a string`); - continue; + try { + const item = parseJsonWithRepair(line); + if (item === undefined) { + errors.push(`Line ${i + 1}: Invalid JSON - JSON parsing failed`); + continue; } - item.alternatives = sanitizeContent(item.alternatives); - } - break; - case "upload-asset": - if (!item.path || typeof item.path !== "string") { - errors.push(`Line ${i + 1}: upload_asset requires a 'path' string field`); - continue; - } - break; - case "create-code-scanning-alert": - if (!item.file || typeof item.file !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'file' field (string)`); - continue; - } - const alertLineValidation = validatePositiveInteger(item.line, "create-code-scanning-alert 'line'", i + 1); - if (!alertLineValidation.isValid) { - if (alertLineValidation.error) { - errors.push(alertLineValidation.error); + if (!item.type) { + errors.push(`Line ${i + 1}: Missing required 'type' field`); + continue; } - continue; - } - if (!item.severity || typeof item.severity !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'severity' field (string)`); - continue; - } - if (!item.message || typeof item.message !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'message' field (string)`); - continue; - } - const allowedSeverities = ["error", "warning", "info", "note"]; - if (!allowedSeverities.includes(item.severity.toLowerCase())) { - errors.push( - `Line ${i + 1}: create-code-scanning-alert 'severity' must be one of: ${allowedSeverities.join(", ")}, got ${item.severity.toLowerCase()}` - ); - continue; - } - const columnValidation = validateOptionalPositiveInteger(item.column, "create-code-scanning-alert 'column'", i + 1); - if (!columnValidation.isValid) { - if (columnValidation.error) errors.push(columnValidation.error); - continue; - } - if (item.ruleIdSuffix !== undefined) { - if (typeof item.ruleIdSuffix !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must be a string`); - continue; + const itemType = item.type; + if (!expectedOutputTypes[itemType]) { + errors.push(`Line ${i + 1}: Unexpected output type '${itemType}'. Expected one of: ${Object.keys(expectedOutputTypes).join(", ")}`); + continue; } - if (!/^[a-zA-Z0-9_-]+$/.test(item.ruleIdSuffix.trim())) { - errors.push( - `Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must contain only alphanumeric characters, hyphens, and underscores` - ); - continue; + const typeCount = parsedItems.filter(existing => existing.type === itemType).length; + const maxAllowed = getMaxAllowedForType(itemType, expectedOutputTypes); + if (typeCount >= maxAllowed) { + errors.push(`Line ${i + 1}: Too many items of type '${itemType}'. Maximum allowed: ${maxAllowed}.`); + continue; } - } - item.severity = item.severity.toLowerCase(); - item.file = sanitizeContent(item.file); - item.severity = sanitizeContent(item.severity); - item.message = sanitizeContent(item.message); - if (item.ruleIdSuffix) { - item.ruleIdSuffix = sanitizeContent(item.ruleIdSuffix); - } - break; - default: - const jobOutputType = expectedOutputTypes[itemType]; - if (!jobOutputType) { - errors.push(`Line ${i + 1}: Unknown output type '${itemType}'`); - continue; - } - const safeJobConfig = jobOutputType; - if (safeJobConfig && safeJobConfig.inputs) { - const validation = validateItemWithSafeJobConfig(item, safeJobConfig, i + 1); - if (!validation.isValid) { - errors.push(...validation.errors); - continue; + core.info(`Line ${i + 1}: type '${itemType}'`); + switch (itemType) { + case "create-issue": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_issue requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_issue requires a 'body' string field`); + continue; + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + if (item.labels && Array.isArray(item.labels)) { + item.labels = item.labels.map((label) => (typeof label === "string" ? sanitizeContent(label) : label)); + } + break; + case "add-comment": + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: add_comment requires a 'body' string field`); + continue; + } + const issueNumValidation = validateIssueOrPRNumber(item.issue_number, "add_comment 'issue_number'", i + 1); + if (!issueNumValidation.isValid) { + if (issueNumValidation.error) + errors.push(issueNumValidation.error); + continue; + } + item.body = sanitizeContent(item.body); + break; + case "create-pull-request": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'body' string field`); + continue; + } + if (!item.branch || typeof item.branch !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'branch' string field`); + continue; + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + item.branch = sanitizeContent(item.branch); + if (item.labels && Array.isArray(item.labels)) { + item.labels = item.labels.map((label) => (typeof label === "string" ? sanitizeContent(label) : label)); + } + break; + case "add-labels": + if (!item.labels || !Array.isArray(item.labels)) { + errors.push(`Line ${i + 1}: add_labels requires a 'labels' array field`); + continue; + } + if (item.labels.some((label) => typeof label !== "string")) { + errors.push(`Line ${i + 1}: add_labels labels array must contain only strings`); + continue; + } + const labelsIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "add-labels 'issue_number'", i + 1); + if (!labelsIssueNumValidation.isValid) { + if (labelsIssueNumValidation.error) + errors.push(labelsIssueNumValidation.error); + continue; + } + item.labels = item.labels.map((label) => sanitizeContent(label)); + break; + case "update-issue": + const hasValidField = item.status !== undefined || item.title !== undefined || item.body !== undefined; + if (!hasValidField) { + errors.push(`Line ${i + 1}: update_issue requires at least one of: 'status', 'title', or 'body' fields`); + continue; + } + if (item.status !== undefined) { + if (typeof item.status !== "string" || (item.status !== "open" && item.status !== "closed")) { + errors.push(`Line ${i + 1}: update_issue 'status' must be 'open' or 'closed'`); + continue; + } + } + if (item.title !== undefined) { + if (typeof item.title !== "string") { + errors.push(`Line ${i + 1}: update-issue 'title' must be a string`); + continue; + } + item.title = sanitizeContent(item.title); + } + if (item.body !== undefined) { + if (typeof item.body !== "string") { + errors.push(`Line ${i + 1}: update-issue 'body' must be a string`); + continue; + } + item.body = sanitizeContent(item.body); + } + const updateIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "update-issue 'issue_number'", i + 1); + if (!updateIssueNumValidation.isValid) { + if (updateIssueNumValidation.error) + errors.push(updateIssueNumValidation.error); + continue; + } + break; + case "push-to-pull-request-branch": + if (!item.branch || typeof item.branch !== "string") { + errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'branch' string field`); + continue; + } + if (!item.message || typeof item.message !== "string") { + errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'message' string field`); + continue; + } + item.branch = sanitizeContent(item.branch); + item.message = sanitizeContent(item.message); + const pushPRNumValidation = validateIssueOrPRNumber(item.pull_request_number, "push-to-pull-request-branch 'pull_request_number'", i + 1); + if (!pushPRNumValidation.isValid) { + if (pushPRNumValidation.error) + errors.push(pushPRNumValidation.error); + continue; + } + break; + case "create-pull-request-review-comment": + if (!item.path || typeof item.path !== "string") { + errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'path' string field`); + continue; + } + const lineValidation = validatePositiveInteger(item.line, "create-pull-request-review-comment 'line'", i + 1); + if (!lineValidation.isValid) { + if (lineValidation.error) + errors.push(lineValidation.error); + continue; + } + const lineNumber = lineValidation.normalizedValue; + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'body' string field`); + continue; + } + item.body = sanitizeContent(item.body); + const startLineValidation = validateOptionalPositiveInteger(item.start_line, "create-pull-request-review-comment 'start_line'", i + 1); + if (!startLineValidation.isValid) { + if (startLineValidation.error) + errors.push(startLineValidation.error); + continue; + } + if (startLineValidation.normalizedValue !== undefined && + lineNumber !== undefined && + startLineValidation.normalizedValue > lineNumber) { + errors.push(`Line ${i + 1}: create-pull-request-review-comment 'start_line' must be less than or equal to 'line'`); + continue; + } + if (item.side !== undefined) { + if (typeof item.side !== "string" || (item.side !== "LEFT" && item.side !== "RIGHT")) { + errors.push(`Line ${i + 1}: create-pull-request-review-comment 'side' must be 'LEFT' or 'RIGHT'`); + continue; + } + } + break; + case "create-discussion": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_discussion requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_discussion requires a 'body' string field`); + continue; + } + if (item.category !== undefined) { + if (typeof item.category !== "string") { + errors.push(`Line ${i + 1}: create_discussion 'category' must be a string`); + continue; + } + item.category = sanitizeContent(item.category); + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + break; + case "missing-tool": + if (!item.tool || typeof item.tool !== "string") { + errors.push(`Line ${i + 1}: missing_tool requires a 'tool' string field`); + continue; + } + if (!item.reason || typeof item.reason !== "string") { + errors.push(`Line ${i + 1}: missing_tool requires a 'reason' string field`); + continue; + } + item.tool = sanitizeContent(item.tool); + item.reason = sanitizeContent(item.reason); + if (item.alternatives !== undefined) { + if (typeof item.alternatives !== "string") { + errors.push(`Line ${i + 1}: missing-tool 'alternatives' must be a string`); + continue; + } + item.alternatives = sanitizeContent(item.alternatives); + } + break; + case "upload-asset": + if (!item.path || typeof item.path !== "string") { + errors.push(`Line ${i + 1}: upload_asset requires a 'path' string field`); + continue; + } + break; + case "create-code-scanning-alert": + if (!item.file || typeof item.file !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'file' field (string)`); + continue; + } + const alertLineValidation = validatePositiveInteger(item.line, "create-code-scanning-alert 'line'", i + 1); + if (!alertLineValidation.isValid) { + if (alertLineValidation.error) { + errors.push(alertLineValidation.error); + } + continue; + } + if (!item.severity || typeof item.severity !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'severity' field (string)`); + continue; + } + if (!item.message || typeof item.message !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'message' field (string)`); + continue; + } + const allowedSeverities = ["error", "warning", "info", "note"]; + if (!allowedSeverities.includes(item.severity.toLowerCase())) { + errors.push(`Line ${i + 1}: create-code-scanning-alert 'severity' must be one of: ${allowedSeverities.join(", ")}, got ${item.severity.toLowerCase()}`); + continue; + } + const columnValidation = validateOptionalPositiveInteger(item.column, "create-code-scanning-alert 'column'", i + 1); + if (!columnValidation.isValid) { + if (columnValidation.error) + errors.push(columnValidation.error); + continue; + } + if (item.ruleIdSuffix !== undefined) { + if (typeof item.ruleIdSuffix !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must be a string`); + continue; + } + if (!/^[a-zA-Z0-9_-]+$/.test(item.ruleIdSuffix.trim())) { + errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must contain only alphanumeric characters, hyphens, and underscores`); + continue; + } + } + item.severity = item.severity.toLowerCase(); + item.file = sanitizeContent(item.file); + item.severity = sanitizeContent(item.severity); + item.message = sanitizeContent(item.message); + if (item.ruleIdSuffix) { + item.ruleIdSuffix = sanitizeContent(item.ruleIdSuffix); + } + break; + default: + const jobOutputType = expectedOutputTypes[itemType]; + if (!jobOutputType) { + errors.push(`Line ${i + 1}: Unknown output type '${itemType}'`); + continue; + } + const safeJobConfig = jobOutputType; + if (safeJobConfig && safeJobConfig.inputs) { + const validation = validateItemWithSafeJobConfig(item, safeJobConfig, i + 1); + if (!validation.isValid) { + errors.push(...validation.errors); + continue; + } + Object.assign(item, validation.normalizedItem); + } + break; } - Object.assign(item, validation.normalizedItem); - } - break; - } - core.info(`Line ${i + 1}: Valid ${itemType} item`); - parsedItems.push(item); - } catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - errors.push(`Line ${i + 1}: Invalid JSON - ${errorMsg}`); + core.info(`Line ${i + 1}: Valid ${itemType} item`); + parsedItems.push(item); + } + catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + errors.push(`Line ${i + 1}: Invalid JSON - ${errorMsg}`); + } } - } - if (errors.length > 0) { - core.warning("Validation errors found:"); - errors.forEach(error => core.warning(` - ${error}`)); - if (parsedItems.length === 0) { - core.setFailed(errors.map(e => ` - ${e}`).join("\n")); - return; + if (errors.length > 0) { + core.warning("Validation errors found:"); + errors.forEach(error => core.warning(` - ${error}`)); + if (parsedItems.length === 0) { + core.setFailed(errors.map(e => ` - ${e}`).join("\n")); + return; + } } - } - for (const itemType of Object.keys(expectedOutputTypes)) { - const minRequired = getMinRequiredForType(itemType, expectedOutputTypes); - if (minRequired > 0) { - const actualCount = parsedItems.filter(item => item.type === itemType).length; - if (actualCount < minRequired) { - errors.push(`Too few items of type '${itemType}'. Minimum required: ${minRequired}, found: ${actualCount}.`); - } + for (const itemType of Object.keys(expectedOutputTypes)) { + const minRequired = getMinRequiredForType(itemType, expectedOutputTypes); + if (minRequired > 0) { + const actualCount = parsedItems.filter(item => item.type === itemType).length; + if (actualCount < minRequired) { + errors.push(`Too few items of type '${itemType}'. Minimum required: ${minRequired}, found: ${actualCount}.`); + } + } + } + core.info(`Successfully parsed ${parsedItems.length} valid output items`); + const validatedOutput = { + items: parsedItems, + errors: errors, + }; + const agentOutputFile = "/tmp/agent_output.json"; + const validatedOutputJson = JSON.stringify(validatedOutput); + try { + fs.mkdirSync("/tmp", { recursive: true }); + fs.writeFileSync(agentOutputFile, validatedOutputJson, "utf8"); + core.info(`Stored validated output to: ${agentOutputFile}`); + core.exportVariable("GITHUB_AW_AGENT_OUTPUT", agentOutputFile); + } + catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.error(`Failed to write agent output file: ${errorMsg}`); + } + core.setOutput("output", JSON.stringify(validatedOutput)); + core.setOutput("raw_output", outputContent); + const outputTypes = Array.from(new Set(parsedItems.map(item => item.type))); + core.info(`output_types: ${outputTypes.join(", ")}`); + core.setOutput("output_types", outputTypes.join(",")); + try { + await core.summary + .addRaw("## Processed Output\n\n") + .addRaw("```json\n") + .addRaw(JSON.stringify(validatedOutput)) + .addRaw("\n```\n") + .write(); + core.info("Successfully wrote processed output to step summary"); + } + catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.warning(`Failed to write to step summary: ${errorMsg}`); } - } - core.info(`Successfully parsed ${parsedItems.length} valid output items`); - const validatedOutput = { - items: parsedItems, - errors: errors, - }; - const agentOutputFile = "/tmp/agent_output.json"; - const validatedOutputJson = JSON.stringify(validatedOutput); - try { - fs.mkdirSync("/tmp", { recursive: true }); - fs.writeFileSync(agentOutputFile, validatedOutputJson, "utf8"); - core.info(`Stored validated output to: ${agentOutputFile}`); - core.exportVariable("GITHUB_AW_AGENT_OUTPUT", agentOutputFile); - } catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.error(`Failed to write agent output file: ${errorMsg}`); - } - core.setOutput("output", JSON.stringify(validatedOutput)); - core.setOutput("raw_output", outputContent); - const outputTypes = Array.from(new Set(parsedItems.map(item => item.type))); - core.info(`output_types: ${outputTypes.join(", ")}`); - core.setOutput("output_types", outputTypes.join(",")); - try { - await core.summary - .addRaw("## Processed Output\n\n") - .addRaw("```json\n") - .addRaw(JSON.stringify(validatedOutput)) - .addRaw("\n```\n") - .write(); - core.info("Successfully wrote processed output to step summary"); - } catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.warning(`Failed to write to step summary: ${errorMsg}`); - } } await main(); - name: Upload sanitized agent output @@ -2488,164 +2488,162 @@ jobs: with: script: | function sanitizeLabelContent(content) { - if (!content || typeof content !== "string") { - return ""; - } - let sanitized = content.trim(); - sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); - sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); - sanitized = sanitized.replace( - /(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, - (_m, p1, p2) => `${p1}\`@${p2}\`` - ); - sanitized = sanitized.replace(/[<>&'"]/g, ""); - return sanitized.trim(); + if (!content || typeof content !== "string") { + return ""; + } + let sanitized = content.trim(); + sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); + sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); + sanitized = sanitized.replace(/(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, (_m, p1, p2) => `${p1}\`@${p2}\``); + sanitized = sanitized.replace(/[<>&'"]/g, ""); + return sanitized.trim(); } async function main() { - const isStaged = process.env.GITHUB_AW_SAFE_OUTPUTS_STAGED === "true"; - const outputContent = process.env.GITHUB_AW_AGENT_OUTPUT; - if (!outputContent) { - core.info("No GITHUB_AW_AGENT_OUTPUT environment variable found"); - return; - } - if (outputContent.trim() === "") { - core.info("Agent output content is empty"); - return; - } - core.info(`Agent output content length: ${outputContent.length}`); - let validatedOutput; - try { - validatedOutput = JSON.parse(outputContent); - } catch (error) { - core.setFailed(`Error parsing agent output JSON: ${error instanceof Error ? error.message : String(error)}`); - return; - } - if (!validatedOutput.items || !Array.isArray(validatedOutput.items)) { - core.info("No valid items found in agent output"); - return; - } - const createIssueItems = validatedOutput.items.filter(item => item.type === "create-issue"); - if (createIssueItems.length === 0) { - core.info("No create-issue items found in agent output"); - return; - } - core.info(`Found ${createIssueItems.length} create-issue item(s)`); - if (isStaged) { - let summaryContent = "## 🎭 Staged Mode: Create Issues Preview\n\n"; - summaryContent += "The following issues would be created if staged mode was disabled:\n\n"; - for (let i = 0; i < createIssueItems.length; i++) { - const item = createIssueItems[i]; - summaryContent += `### Issue ${i + 1}\n`; - summaryContent += `**Title:** ${item.title || "No title provided"}\n\n`; - if (item.body) { - summaryContent += `**Body:**\n${item.body}\n\n`; - } - if (item.labels && item.labels.length > 0) { - summaryContent += `**Labels:** ${item.labels.join(", ")}\n\n`; - } - summaryContent += "---\n\n"; + const isStaged = process.env.GITHUB_AW_SAFE_OUTPUTS_STAGED === "true"; + const outputContent = process.env.GITHUB_AW_AGENT_OUTPUT; + if (!outputContent) { + core.info("No GITHUB_AW_AGENT_OUTPUT environment variable found"); + return; } - await core.summary.addRaw(summaryContent).write(); - core.info("📝 Issue creation preview written to step summary"); - return; - } - const parentIssueNumber = context.payload?.issue?.number; - const labelsEnv = process.env.GITHUB_AW_ISSUE_LABELS; - let envLabels = labelsEnv - ? labelsEnv - .split(",") - .map(label => label.trim()) - .filter(label => label) - : []; - const createdIssues = []; - for (let i = 0; i < createIssueItems.length; i++) { - const createIssueItem = createIssueItems[i]; - core.info( - `Processing create-issue item ${i + 1}/${createIssueItems.length}: title=${createIssueItem.title}, bodyLength=${createIssueItem.body.length}` - ); - let labels = [...envLabels]; - if (createIssueItem.labels && Array.isArray(createIssueItem.labels)) { - labels = [...labels, ...createIssueItem.labels]; - } - labels = labels - .filter(label => label != null && label !== false && label !== 0) - .map(label => String(label).trim()) - .filter(label => label) - .map(label => sanitizeLabelContent(label)) - .filter(label => label) - .map(label => (label.length > 64 ? label.substring(0, 64) : label)) - .filter((label, index, arr) => arr.indexOf(label) === index); - let title = createIssueItem.title ? createIssueItem.title.trim() : ""; - let bodyLines = createIssueItem.body.split("\n"); - if (!title) { - title = createIssueItem.body || "Agent Output"; - } - const titlePrefix = process.env.GITHUB_AW_ISSUE_TITLE_PREFIX; - if (titlePrefix && !title.startsWith(titlePrefix)) { - title = titlePrefix + title; - } - if (parentIssueNumber) { - core.info("Detected issue context, parent issue #" + parentIssueNumber); - bodyLines.push(`Related to #${parentIssueNumber}`); + if (outputContent.trim() === "") { + core.info("Agent output content is empty"); + return; } - const runId = context.runId; - const runUrl = context.payload.repository - ? `${context.payload.repository.html_url}/actions/runs/${runId}` - : `https://github.com/actions/runs/${runId}`; - bodyLines.push(``, ``, `> Generated by Agentic Workflow [Run](${runUrl})`, ""); - const body = bodyLines.join("\n").trim(); - core.info(`Creating issue with title: ${title}`); - core.info(`Labels: ${labels}`); - core.info(`Body length: ${body.length}`); + core.info(`Agent output content length: ${outputContent.length}`); + let validatedOutput; try { - const { data: issue } = await github.rest.issues.create({ - owner: context.repo.owner, - repo: context.repo.repo, - title: title, - body: body, - labels: labels, - }); - core.info("Created issue #" + issue.number + ": " + issue.html_url); - createdIssues.push(issue); - if (parentIssueNumber) { + validatedOutput = JSON.parse(outputContent); + } + catch (error) { + core.setFailed(`Error parsing agent output JSON: ${error instanceof Error ? error.message : String(error)}`); + return; + } + if (!validatedOutput.items || !Array.isArray(validatedOutput.items)) { + core.info("No valid items found in agent output"); + return; + } + const createIssueItems = validatedOutput.items.filter(item => item.type === "create-issue"); + if (createIssueItems.length === 0) { + core.info("No create-issue items found in agent output"); + return; + } + core.info(`Found ${createIssueItems.length} create-issue item(s)`); + if (isStaged) { + let summaryContent = "## 🎭 Staged Mode: Create Issues Preview\n\n"; + summaryContent += "The following issues would be created if staged mode was disabled:\n\n"; + for (let i = 0; i < createIssueItems.length; i++) { + const item = createIssueItems[i]; + summaryContent += `### Issue ${i + 1}\n`; + summaryContent += `**Title:** ${item.title || "No title provided"}\n\n`; + if (item.body) { + summaryContent += `**Body:**\n${item.body}\n\n`; + } + if (item.labels && item.labels.length > 0) { + summaryContent += `**Labels:** ${item.labels.join(", ")}\n\n`; + } + summaryContent += "---\n\n"; + } + await core.summary.addRaw(summaryContent).write(); + core.info("📝 Issue creation preview written to step summary"); + return; + } + const parentIssueNumber = context.payload?.issue?.number; + const labelsEnv = process.env.GITHUB_AW_ISSUE_LABELS; + let envLabels = labelsEnv + ? labelsEnv + .split(",") + .map((label) => label.trim()) + .filter((label) => label) + : []; + const createdIssues = []; + for (let i = 0; i < createIssueItems.length; i++) { + const createIssueItem = createIssueItems[i]; + core.info(`Processing create-issue item ${i + 1}/${createIssueItems.length}: title=${createIssueItem.title}, bodyLength=${createIssueItem.body.length}`); + let labels = [...envLabels]; + if (createIssueItem.labels && Array.isArray(createIssueItem.labels)) { + labels = [...labels, ...createIssueItem.labels]; + } + labels = labels + .filter(label => label != null && label !== false && label !== 0) + .map(label => String(label).trim()) + .filter(label => label) + .map(label => sanitizeLabelContent(label)) + .filter(label => label) + .map(label => (label.length > 64 ? label.substring(0, 64) : label)) + .filter((label, index, arr) => arr.indexOf(label) === index); + let title = createIssueItem.title ? createIssueItem.title.trim() : ""; + let bodyLines = createIssueItem.body.split("\n"); + if (!title) { + title = createIssueItem.body || "Agent Output"; + } + const titlePrefix = process.env.GITHUB_AW_ISSUE_TITLE_PREFIX; + if (titlePrefix && !title.startsWith(titlePrefix)) { + title = titlePrefix + title; + } + if (parentIssueNumber) { + core.info("Detected issue context, parent issue #" + parentIssueNumber); + bodyLines.push(`Related to #${parentIssueNumber}`); + } + const runId = context.runId; + const runUrl = context.payload.repository + ? `${context.payload.repository.html_url}/actions/runs/${runId}` + : `https://github.com/actions/runs/${runId}`; + bodyLines.push(``, ``, `> Generated by Agentic Workflow [Run](${runUrl})`, ""); + const body = bodyLines.join("\n").trim(); + core.info(`Creating issue with title: ${title}`); + core.info(`Labels: ${labels}`); + core.info(`Body length: ${body.length}`); try { - await github.rest.issues.createComment({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: parentIssueNumber, - body: `Created related issue: #${issue.number}`, - }); - core.info("Added comment to parent issue #" + parentIssueNumber); - } catch (error) { - core.info(`Warning: Could not add comment to parent issue: ${error instanceof Error ? error.message : String(error)}`); + const { data: issue } = await github.rest.issues.create({ + owner: context.repo.owner, + repo: context.repo.repo, + title: title, + body: body, + labels: labels, + }); + core.info("Created issue #" + issue.number + ": " + issue.html_url); + createdIssues.push(issue); + if (parentIssueNumber) { + try { + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: parentIssueNumber, + body: `Created related issue: #${issue.number}`, + }); + core.info("Added comment to parent issue #" + parentIssueNumber); + } + catch (error) { + core.info(`Warning: Could not add comment to parent issue: ${error instanceof Error ? error.message : String(error)}`); + } + } + if (i === createIssueItems.length - 1) { + core.setOutput("issue_number", issue.number); + core.setOutput("issue_url", issue.html_url); + } + } + catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + if (errorMessage.includes("Issues has been disabled in this repository")) { + core.info(`⚠ Cannot create issue "${title}": Issues are disabled for this repository`); + core.info("Consider enabling issues in repository settings if you want to create issues automatically"); + continue; + } + core.error(`✗ Failed to create issue "${title}": ${errorMessage}`); + throw error; } - } - if (i === createIssueItems.length - 1) { - core.setOutput("issue_number", issue.number); - core.setOutput("issue_url", issue.html_url); - } - } catch (error) { - const errorMessage = error instanceof Error ? error.message : String(error); - if (errorMessage.includes("Issues has been disabled in this repository")) { - core.info(`⚠ Cannot create issue "${title}": Issues are disabled for this repository`); - core.info("Consider enabling issues in repository settings if you want to create issues automatically"); - continue; - } - core.error(`✗ Failed to create issue "${title}": ${errorMessage}`); - throw error; } - } - if (createdIssues.length > 0) { - let summaryContent = "\n\n## GitHub Issues\n"; - for (const issue of createdIssues) { - summaryContent += `- Issue #${issue.number}: [${issue.title}](${issue.html_url})\n`; + if (createdIssues.length > 0) { + let summaryContent = "\n\n## GitHub Issues\n"; + for (const issue of createdIssues) { + summaryContent += `- Issue #${issue.number}: [${issue.title}](${issue.html_url})\n`; + } + await core.summary.addRaw(summaryContent).write(); } - await core.summary.addRaw(summaryContent).write(); - } - core.info(`Successfully created ${createdIssues.length} issue(s)`); + core.info(`Successfully created ${createdIssues.length} issue(s)`); } (async () => { - await main(); + await main(); })(); add_comment: diff --git a/.github/workflows/dev.lock.yml b/.github/workflows/dev.lock.yml index a7465aa55d5..11214431901 100644 --- a/.github/workflows/dev.lock.yml +++ b/.github/workflows/dev.lock.yml @@ -990,742 +990,742 @@ jobs: with: script: | async function main() { - const fs = require("fs"); - function sanitizeContent(content) { - if (!content || typeof content !== "string") { - return ""; + const fs = require("fs"); + function sanitizeContent(content) { + if (!content || typeof content !== "string") { + return ""; + } + const allowedDomainsEnv = process.env.GITHUB_AW_ALLOWED_DOMAINS; + const defaultAllowedDomains = ["github.com", "github.io", "githubusercontent.com", "githubassets.com", "github.dev", "codespaces.new"]; + const allowedDomains = allowedDomainsEnv + ? allowedDomainsEnv + .split(",") + .map(d => d.trim()) + .filter(d => d) + : defaultAllowedDomains; + let sanitized = content; + sanitized = neutralizeMentions(sanitized); + sanitized = removeXmlComments(sanitized); + sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); + sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); + sanitized = sanitizeUrlProtocols(sanitized); + sanitized = sanitizeUrlDomains(sanitized); + const maxLength = 524288; + if (sanitized.length > maxLength) { + sanitized = sanitized.substring(0, maxLength) + "\n[Content truncated due to length]"; + } + const lines = sanitized.split("\n"); + const maxLines = 65000; + if (lines.length > maxLines) { + sanitized = lines.slice(0, maxLines).join("\n") + "\n[Content truncated due to line count]"; + } + sanitized = neutralizeBotTriggers(sanitized); + return sanitized.trim(); + function sanitizeUrlDomains(s) { + return s.replace(/\bhttps:\/\/[^\s\])}'"<>&\x00-\x1f,;]+/gi, match => { + const urlAfterProtocol = match.slice(8); + const hostname = urlAfterProtocol.split(/[\/:\?#]/)[0].toLowerCase(); + const isAllowed = allowedDomains.some(allowedDomain => { + const normalizedAllowed = allowedDomain.toLowerCase(); + return hostname === normalizedAllowed || hostname.endsWith("." + normalizedAllowed); + }); + return isAllowed ? match : "(redacted)"; + }); + } + function sanitizeUrlProtocols(s) { + return s.replace(/\b(\w+):\/\/[^\s\])}'"<>&\x00-\x1f]+/gi, (match, protocol) => { + return protocol.toLowerCase() === "https" ? match : "(redacted)"; + }); + } + function neutralizeMentions(s) { + return s.replace(/(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, (_m, p1, p2) => `${p1}\`@${p2}\``); + } + function removeXmlComments(s) { + return s.replace(//g, "").replace(//g, ""); + } + function neutralizeBotTriggers(s) { + return s.replace(/\b(fixes?|closes?|resolves?|fix|close|resolve)\s+#(\w+)/gi, (match, action, ref) => `\`${action} #${ref}\``); + } } - const allowedDomainsEnv = process.env.GITHUB_AW_ALLOWED_DOMAINS; - const defaultAllowedDomains = ["github.com", "github.io", "githubusercontent.com", "githubassets.com", "github.dev", "codespaces.new"]; - const allowedDomains = allowedDomainsEnv - ? allowedDomainsEnv - .split(",") - .map(d => d.trim()) - .filter(d => d) - : defaultAllowedDomains; - let sanitized = content; - sanitized = neutralizeMentions(sanitized); - sanitized = removeXmlComments(sanitized); - sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); - sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); - sanitized = sanitizeUrlProtocols(sanitized); - sanitized = sanitizeUrlDomains(sanitized); - const maxLength = 524288; - if (sanitized.length > maxLength) { - sanitized = sanitized.substring(0, maxLength) + "\n[Content truncated due to length]"; + function getMaxAllowedForType(itemType, config) { + const itemConfig = config?.[itemType]; + if (itemConfig && typeof itemConfig === "object" && "max" in itemConfig && itemConfig.max) { + return itemConfig.max; + } + switch (itemType) { + case "create-issue": + return 1; + case "add-comment": + return 1; + case "create-pull-request": + return 1; + case "create-pull-request-review-comment": + return 1; + case "add-labels": + return 5; + case "update-issue": + return 1; + case "push-to-pull-request-branch": + return 1; + case "create-discussion": + return 1; + case "missing-tool": + return 1000; + case "create-code-scanning-alert": + return 1000; + case "upload-asset": + return 10; + default: + return 1; + } } - const lines = sanitized.split("\n"); - const maxLines = 65000; - if (lines.length > maxLines) { - sanitized = lines.slice(0, maxLines).join("\n") + "\n[Content truncated due to line count]"; + function getMinRequiredForType(itemType, config) { + const itemConfig = config?.[itemType]; + if (itemConfig && typeof itemConfig === "object" && "min" in itemConfig && itemConfig.min) { + return itemConfig.min; + } + return 0; } - sanitized = neutralizeBotTriggers(sanitized); - return sanitized.trim(); - function sanitizeUrlDomains(s) { - return s.replace(/\bhttps:\/\/[^\s\])}'"<>&\x00-\x1f,;]+/gi, match => { - const urlAfterProtocol = match.slice(8); - const hostname = urlAfterProtocol.split(/[\/:\?#]/)[0].toLowerCase(); - const isAllowed = allowedDomains.some(allowedDomain => { - const normalizedAllowed = allowedDomain.toLowerCase(); - return hostname === normalizedAllowed || hostname.endsWith("." + normalizedAllowed); + function repairJson(jsonStr) { + let repaired = jsonStr.trim(); + const _ctrl = { 8: "\\b", 9: "\\t", 10: "\\n", 12: "\\f", 13: "\\r" }; + repaired = repaired.replace(/[\u0000-\u001F]/g, ch => { + const c = ch.charCodeAt(0); + return _ctrl[c] || "\\u" + c.toString(16).padStart(4, "0"); }); - return isAllowed ? match : "(redacted)"; - }); - } - function sanitizeUrlProtocols(s) { - return s.replace(/\b(\w+):\/\/[^\s\])}'"<>&\x00-\x1f]+/gi, (match, protocol) => { - return protocol.toLowerCase() === "https" ? match : "(redacted)"; - }); - } - function neutralizeMentions(s) { - return s.replace( - /(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, - (_m, p1, p2) => `${p1}\`@${p2}\`` - ); - } - function removeXmlComments(s) { - return s.replace(//g, "").replace(//g, ""); - } - function neutralizeBotTriggers(s) { - return s.replace(/\b(fixes?|closes?|resolves?|fix|close|resolve)\s+#(\w+)/gi, (match, action, ref) => `\`${action} #${ref}\``); - } - } - function getMaxAllowedForType(itemType, config) { - const itemConfig = config?.[itemType]; - if (itemConfig && typeof itemConfig === "object" && "max" in itemConfig && itemConfig.max) { - return itemConfig.max; - } - switch (itemType) { - case "create-issue": - return 1; - case "add-comment": - return 1; - case "create-pull-request": - return 1; - case "create-pull-request-review-comment": - return 1; - case "add-labels": - return 5; - case "update-issue": - return 1; - case "push-to-pull-request-branch": - return 1; - case "create-discussion": - return 1; - case "missing-tool": - return 1000; - case "create-code-scanning-alert": - return 1000; - case "upload-asset": - return 10; - default: - return 1; - } - } - function getMinRequiredForType(itemType, config) { - const itemConfig = config?.[itemType]; - if (itemConfig && typeof itemConfig === "object" && "min" in itemConfig && itemConfig.min) { - return itemConfig.min; - } - return 0; - } - function repairJson(jsonStr) { - let repaired = jsonStr.trim(); - const _ctrl = { 8: "\\b", 9: "\\t", 10: "\\n", 12: "\\f", 13: "\\r" }; - repaired = repaired.replace(/[\u0000-\u001F]/g, ch => { - const c = ch.charCodeAt(0); - return _ctrl[c] || "\\u" + c.toString(16).padStart(4, "0"); - }); - repaired = repaired.replace(/'/g, '"'); - repaired = repaired.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/g, '$1"$2":'); - repaired = repaired.replace(/"([^"\\]*)"/g, (match, content) => { - if (content.includes("\n") || content.includes("\r") || content.includes("\t")) { - const escaped = content.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"); - return `"${escaped}"`; - } - return match; - }); - repaired = repaired.replace(/"([^"]*)"([^":,}\]]*)"([^"]*)"(\s*[,:}\]])/g, (match, p1, p2, p3, p4) => `"${p1}\\"${p2}\\"${p3}"${p4}`); - repaired = repaired.replace(/(\[\s*(?:"[^"]*"(?:\s*,\s*"[^"]*")*\s*),?)\s*}/g, "$1]"); - const openBraces = (repaired.match(/\{/g) || []).length; - const closeBraces = (repaired.match(/\}/g) || []).length; - if (openBraces > closeBraces) { - repaired += "}".repeat(openBraces - closeBraces); - } else if (closeBraces > openBraces) { - repaired = "{".repeat(closeBraces - openBraces) + repaired; - } - const openBrackets = (repaired.match(/\[/g) || []).length; - const closeBrackets = (repaired.match(/\]/g) || []).length; - if (openBrackets > closeBrackets) { - repaired += "]".repeat(openBrackets - closeBrackets); - } else if (closeBrackets > openBrackets) { - repaired = "[".repeat(closeBrackets - openBrackets) + repaired; - } - repaired = repaired.replace(/,(\s*[}\]])/g, "$1"); - return repaired; - } - function validatePositiveInteger(value, fieldName, lineNum) { - if (value === undefined || value === null) { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} is required`, - }; + repaired = repaired.replace(/'/g, '"'); + repaired = repaired.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/g, '$1"$2":'); + repaired = repaired.replace(/"([^"\\]*)"/g, (match, content) => { + if (content.includes("\n") || content.includes("\r") || content.includes("\t")) { + const escaped = content.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"); + return `"${escaped}"`; + } + return match; + }); + repaired = repaired.replace(/"([^"]*)"([^":,}\]]*)"([^"]*)"(\s*[,:}\]])/g, (match, p1, p2, p3, p4) => `"${p1}\\"${p2}\\"${p3}"${p4}`); + repaired = repaired.replace(/(\[\s*(?:"[^"]*"(?:\s*,\s*"[^"]*")*\s*),?)\s*}/g, "$1]"); + const openBraces = (repaired.match(/\{/g) || []).length; + const closeBraces = (repaired.match(/\}/g) || []).length; + if (openBraces > closeBraces) { + repaired += "}".repeat(openBraces - closeBraces); + } + else if (closeBraces > openBraces) { + repaired = "{".repeat(closeBraces - openBraces) + repaired; + } + const openBrackets = (repaired.match(/\[/g) || []).length; + const closeBrackets = (repaired.match(/\]/g) || []).length; + if (openBrackets > closeBrackets) { + repaired += "]".repeat(openBrackets - closeBrackets); + } + else if (closeBrackets > openBrackets) { + repaired = "[".repeat(closeBrackets - openBrackets) + repaired; + } + repaired = repaired.replace(/,(\s*[}\]])/g, "$1"); + return repaired; } - if (typeof value !== "number" && typeof value !== "string") { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number or string field`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; + function validatePositiveInteger(value, fieldName, lineNum) { + if (value === undefined || value === null) { + if (fieldName.includes("create-code-scanning-alert 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, + }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} is required`, + }; + } + if (typeof value !== "number" && typeof value !== "string") { + if (fieldName.includes("create-code-scanning-alert 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, + }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number or string field`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; + } + const parsed = typeof value === "string" ? parseInt(value, 10) : value; + if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { + if (fieldName.includes("create-code-scanning-alert 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'line' must be a valid positive integer (got: ${value})`, + }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'line' must be a positive integer`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, + }; + } + return { isValid: true, normalizedValue: parsed }; } - const parsed = typeof value === "string" ? parseInt(value, 10) : value; - if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'line' must be a valid positive integer (got: ${value})`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'line' must be a positive integer`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, - }; + function validateOptionalPositiveInteger(value, fieldName, lineNum) { + if (value === undefined) { + return { isValid: true }; + } + if (typeof value !== "number" && typeof value !== "string") { + if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a number or string`, + }; + } + if (fieldName.includes("create-code-scanning-alert 'column'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a number or string`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; + } + const parsed = typeof value === "string" ? parseInt(value, 10) : value; + if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { + if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a positive integer`, + }; + } + if (fieldName.includes("create-code-scanning-alert 'column'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a valid positive integer (got: ${value})`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, + }; + } + return { isValid: true, normalizedValue: parsed }; } - return { isValid: true, normalizedValue: parsed }; - } - function validateOptionalPositiveInteger(value, fieldName, lineNum) { - if (value === undefined) { - return { isValid: true }; + function validateIssueOrPRNumber(value, fieldName, lineNum) { + if (value === undefined) { + return { isValid: true }; + } + if (typeof value !== "number" && typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; + } + return { isValid: true }; } - if (typeof value !== "number" && typeof value !== "string") { - if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a number or string`, - }; - } - if (fieldName.includes("create-code-scanning-alert 'column'")) { + function validateFieldWithInputSchema(value, fieldName, inputSchema, lineNum) { + if (inputSchema.required && (value === undefined || value === null)) { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} is required`, + }; + } + if (value === undefined || value === null) { + return { + isValid: true, + normalizedValue: inputSchema.default || undefined, + }; + } + const inputType = inputSchema.type || "string"; + let normalizedValue = value; + switch (inputType) { + case "string": + if (typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a string`, + }; + } + normalizedValue = sanitizeContent(value); + break; + case "boolean": + if (typeof value !== "boolean") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a boolean`, + }; + } + break; + case "number": + if (typeof value !== "number") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number`, + }; + } + break; + case "choice": + if (typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a string for choice type`, + }; + } + if (inputSchema.options && !inputSchema.options.includes(value)) { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be one of: ${inputSchema.options.join(", ")}`, + }; + } + normalizedValue = sanitizeContent(value); + break; + default: + if (typeof value === "string") { + normalizedValue = sanitizeContent(value); + } + break; + } return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a number or string`, + isValid: true, + normalizedValue, }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; } - const parsed = typeof value === "string" ? parseInt(value, 10) : value; - if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { - if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a positive integer`, - }; - } - if (fieldName.includes("create-code-scanning-alert 'column'")) { + function validateItemWithSafeJobConfig(item, jobConfig, lineNum) { + const errors = []; + const normalizedItem = { ...item }; + if (!jobConfig.inputs) { + return { + isValid: true, + errors: [], + normalizedItem: item, + }; + } + for (const [fieldName, inputSchema] of Object.entries(jobConfig.inputs)) { + const fieldValue = item[fieldName]; + const validation = validateFieldWithInputSchema(fieldValue, fieldName, inputSchema, lineNum); + if (!validation.isValid && validation.error) { + errors.push(validation.error); + } + else if (validation.normalizedValue !== undefined) { + normalizedItem[fieldName] = validation.normalizedValue; + } + } return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a valid positive integer (got: ${value})`, + isValid: errors.length === 0, + errors, + normalizedItem, }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, - }; } - return { isValid: true, normalizedValue: parsed }; - } - function validateIssueOrPRNumber(value, fieldName, lineNum) { - if (value === undefined) { - return { isValid: true }; + function parseJsonWithRepair(jsonStr) { + try { + return JSON.parse(jsonStr); + } + catch (originalError) { + try { + const repairedJson = repairJson(jsonStr); + return JSON.parse(repairedJson); + } + catch (repairError) { + core.info(`invalid input json: ${jsonStr}`); + const originalMsg = originalError instanceof Error ? originalError.message : String(originalError); + const repairMsg = repairError instanceof Error ? repairError.message : String(repairError); + throw new Error(`JSON parsing failed. Original: ${originalMsg}. After attempted repair: ${repairMsg}`); + } + } } - if (typeof value !== "number" && typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; + const outputFile = process.env.GITHUB_AW_SAFE_OUTPUTS; + const safeOutputsConfig = process.env.GITHUB_AW_SAFE_OUTPUTS_CONFIG; + if (!outputFile) { + core.info("GITHUB_AW_SAFE_OUTPUTS not set, no output to collect"); + core.setOutput("output", ""); + return; } - return { isValid: true }; - } - function validateFieldWithInputSchema(value, fieldName, inputSchema, lineNum) { - if (inputSchema.required && (value === undefined || value === null)) { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} is required`, - }; + if (!fs.existsSync(outputFile)) { + core.info(`Output file does not exist: ${outputFile}`); + core.setOutput("output", ""); + return; } - if (value === undefined || value === null) { - return { - isValid: true, - normalizedValue: inputSchema.default || undefined, - }; + const outputContent = fs.readFileSync(outputFile, "utf8"); + if (outputContent.trim() === "") { + core.info("Output file is empty"); } - const inputType = inputSchema.type || "string"; - let normalizedValue = value; - switch (inputType) { - case "string": - if (typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a string`, - }; - } - normalizedValue = sanitizeContent(value); - break; - case "boolean": - if (typeof value !== "boolean") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a boolean`, - }; - } - break; - case "number": - if (typeof value !== "number") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number`, - }; - } - break; - case "choice": - if (typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a string for choice type`, - }; - } - if (inputSchema.options && !inputSchema.options.includes(value)) { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be one of: ${inputSchema.options.join(", ")}`, - }; + core.info(`Raw output content length: ${outputContent.length}`); + let expectedOutputTypes = {}; + if (safeOutputsConfig) { + try { + expectedOutputTypes = JSON.parse(safeOutputsConfig); + core.info(`Expected output types: ${JSON.stringify(Object.keys(expectedOutputTypes))}`); } - normalizedValue = sanitizeContent(value); - break; - default: - if (typeof value === "string") { - normalizedValue = sanitizeContent(value); + catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.info(`Warning: Could not parse safe-outputs config: ${errorMsg}`); } - break; } - return { - isValid: true, - normalizedValue, - }; - } - function validateItemWithSafeJobConfig(item, jobConfig, lineNum) { + const lines = outputContent.trim().split("\n"); + const parsedItems = []; const errors = []; - const normalizedItem = { ...item }; - if (!jobConfig.inputs) { - return { - isValid: true, - errors: [], - normalizedItem: item, - }; - } - for (const [fieldName, inputSchema] of Object.entries(jobConfig.inputs)) { - const fieldValue = item[fieldName]; - const validation = validateFieldWithInputSchema(fieldValue, fieldName, inputSchema, lineNum); - if (!validation.isValid && validation.error) { - errors.push(validation.error); - } else if (validation.normalizedValue !== undefined) { - normalizedItem[fieldName] = validation.normalizedValue; - } - } - return { - isValid: errors.length === 0, - errors, - normalizedItem, - }; - } - function parseJsonWithRepair(jsonStr) { - try { - return JSON.parse(jsonStr); - } catch (originalError) { - try { - const repairedJson = repairJson(jsonStr); - return JSON.parse(repairedJson); - } catch (repairError) { - core.info(`invalid input json: ${jsonStr}`); - const originalMsg = originalError instanceof Error ? originalError.message : String(originalError); - const repairMsg = repairError instanceof Error ? repairError.message : String(repairError); - throw new Error(`JSON parsing failed. Original: ${originalMsg}. After attempted repair: ${repairMsg}`); - } - } - } - const outputFile = process.env.GITHUB_AW_SAFE_OUTPUTS; - const safeOutputsConfig = process.env.GITHUB_AW_SAFE_OUTPUTS_CONFIG; - if (!outputFile) { - core.info("GITHUB_AW_SAFE_OUTPUTS not set, no output to collect"); - core.setOutput("output", ""); - return; - } - if (!fs.existsSync(outputFile)) { - core.info(`Output file does not exist: ${outputFile}`); - core.setOutput("output", ""); - return; - } - const outputContent = fs.readFileSync(outputFile, "utf8"); - if (outputContent.trim() === "") { - core.info("Output file is empty"); - } - core.info(`Raw output content length: ${outputContent.length}`); - let expectedOutputTypes = {}; - if (safeOutputsConfig) { - try { - expectedOutputTypes = JSON.parse(safeOutputsConfig); - core.info(`Expected output types: ${JSON.stringify(Object.keys(expectedOutputTypes))}`); - } catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.info(`Warning: Could not parse safe-outputs config: ${errorMsg}`); - } - } - const lines = outputContent.trim().split("\n"); - const parsedItems = []; - const errors = []; - for (let i = 0; i < lines.length; i++) { - const line = lines[i].trim(); - if (line === "") continue; - try { - const item = parseJsonWithRepair(line); - if (item === undefined) { - errors.push(`Line ${i + 1}: Invalid JSON - JSON parsing failed`); - continue; - } - if (!item.type) { - errors.push(`Line ${i + 1}: Missing required 'type' field`); - continue; - } - const itemType = item.type; - if (!expectedOutputTypes[itemType]) { - errors.push(`Line ${i + 1}: Unexpected output type '${itemType}'. Expected one of: ${Object.keys(expectedOutputTypes).join(", ")}`); - continue; - } - const typeCount = parsedItems.filter(existing => existing.type === itemType).length; - const maxAllowed = getMaxAllowedForType(itemType, expectedOutputTypes); - if (typeCount >= maxAllowed) { - errors.push(`Line ${i + 1}: Too many items of type '${itemType}'. Maximum allowed: ${maxAllowed}.`); - continue; - } - core.info(`Line ${i + 1}: type '${itemType}'`); - switch (itemType) { - case "create-issue": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_issue requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_issue requires a 'body' string field`); - continue; - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - if (item.labels && Array.isArray(item.labels)) { - item.labels = item.labels.map(label => (typeof label === "string" ? sanitizeContent(label) : label)); - } - break; - case "add-comment": - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: add_comment requires a 'body' string field`); - continue; - } - const issueNumValidation = validateIssueOrPRNumber(item.issue_number, "add_comment 'issue_number'", i + 1); - if (!issueNumValidation.isValid) { - if (issueNumValidation.error) errors.push(issueNumValidation.error); + for (let i = 0; i < lines.length; i++) { + const line = lines[i].trim(); + if (line === "") continue; - } - item.body = sanitizeContent(item.body); - break; - case "create-pull-request": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'body' string field`); - continue; - } - if (!item.branch || typeof item.branch !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'branch' string field`); - continue; - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - item.branch = sanitizeContent(item.branch); - if (item.labels && Array.isArray(item.labels)) { - item.labels = item.labels.map(label => (typeof label === "string" ? sanitizeContent(label) : label)); - } - break; - case "add-labels": - if (!item.labels || !Array.isArray(item.labels)) { - errors.push(`Line ${i + 1}: add_labels requires a 'labels' array field`); - continue; - } - if (item.labels.some(label => typeof label !== "string")) { - errors.push(`Line ${i + 1}: add_labels labels array must contain only strings`); - continue; - } - const labelsIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "add-labels 'issue_number'", i + 1); - if (!labelsIssueNumValidation.isValid) { - if (labelsIssueNumValidation.error) errors.push(labelsIssueNumValidation.error); - continue; - } - item.labels = item.labels.map(label => sanitizeContent(label)); - break; - case "update-issue": - const hasValidField = item.status !== undefined || item.title !== undefined || item.body !== undefined; - if (!hasValidField) { - errors.push(`Line ${i + 1}: update_issue requires at least one of: 'status', 'title', or 'body' fields`); - continue; - } - if (item.status !== undefined) { - if (typeof item.status !== "string" || (item.status !== "open" && item.status !== "closed")) { - errors.push(`Line ${i + 1}: update_issue 'status' must be 'open' or 'closed'`); - continue; - } - } - if (item.title !== undefined) { - if (typeof item.title !== "string") { - errors.push(`Line ${i + 1}: update-issue 'title' must be a string`); - continue; - } - item.title = sanitizeContent(item.title); - } - if (item.body !== undefined) { - if (typeof item.body !== "string") { - errors.push(`Line ${i + 1}: update-issue 'body' must be a string`); - continue; - } - item.body = sanitizeContent(item.body); - } - const updateIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "update-issue 'issue_number'", i + 1); - if (!updateIssueNumValidation.isValid) { - if (updateIssueNumValidation.error) errors.push(updateIssueNumValidation.error); - continue; - } - break; - case "push-to-pull-request-branch": - if (!item.branch || typeof item.branch !== "string") { - errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'branch' string field`); - continue; - } - if (!item.message || typeof item.message !== "string") { - errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'message' string field`); - continue; - } - item.branch = sanitizeContent(item.branch); - item.message = sanitizeContent(item.message); - const pushPRNumValidation = validateIssueOrPRNumber( - item.pull_request_number, - "push-to-pull-request-branch 'pull_request_number'", - i + 1 - ); - if (!pushPRNumValidation.isValid) { - if (pushPRNumValidation.error) errors.push(pushPRNumValidation.error); - continue; - } - break; - case "create-pull-request-review-comment": - if (!item.path || typeof item.path !== "string") { - errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'path' string field`); - continue; - } - const lineValidation = validatePositiveInteger(item.line, "create-pull-request-review-comment 'line'", i + 1); - if (!lineValidation.isValid) { - if (lineValidation.error) errors.push(lineValidation.error); - continue; - } - const lineNumber = lineValidation.normalizedValue; - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'body' string field`); - continue; - } - item.body = sanitizeContent(item.body); - const startLineValidation = validateOptionalPositiveInteger( - item.start_line, - "create-pull-request-review-comment 'start_line'", - i + 1 - ); - if (!startLineValidation.isValid) { - if (startLineValidation.error) errors.push(startLineValidation.error); - continue; - } - if ( - startLineValidation.normalizedValue !== undefined && - lineNumber !== undefined && - startLineValidation.normalizedValue > lineNumber - ) { - errors.push(`Line ${i + 1}: create-pull-request-review-comment 'start_line' must be less than or equal to 'line'`); - continue; - } - if (item.side !== undefined) { - if (typeof item.side !== "string" || (item.side !== "LEFT" && item.side !== "RIGHT")) { - errors.push(`Line ${i + 1}: create-pull-request-review-comment 'side' must be 'LEFT' or 'RIGHT'`); - continue; + try { + const item = parseJsonWithRepair(line); + if (item === undefined) { + errors.push(`Line ${i + 1}: Invalid JSON - JSON parsing failed`); + continue; } - } - break; - case "create-discussion": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_discussion requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_discussion requires a 'body' string field`); - continue; - } - if (item.category !== undefined) { - if (typeof item.category !== "string") { - errors.push(`Line ${i + 1}: create_discussion 'category' must be a string`); - continue; + if (!item.type) { + errors.push(`Line ${i + 1}: Missing required 'type' field`); + continue; } - item.category = sanitizeContent(item.category); - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - break; - case "missing-tool": - if (!item.tool || typeof item.tool !== "string") { - errors.push(`Line ${i + 1}: missing_tool requires a 'tool' string field`); - continue; - } - if (!item.reason || typeof item.reason !== "string") { - errors.push(`Line ${i + 1}: missing_tool requires a 'reason' string field`); - continue; - } - item.tool = sanitizeContent(item.tool); - item.reason = sanitizeContent(item.reason); - if (item.alternatives !== undefined) { - if (typeof item.alternatives !== "string") { - errors.push(`Line ${i + 1}: missing-tool 'alternatives' must be a string`); - continue; + const itemType = item.type; + if (!expectedOutputTypes[itemType]) { + errors.push(`Line ${i + 1}: Unexpected output type '${itemType}'. Expected one of: ${Object.keys(expectedOutputTypes).join(", ")}`); + continue; } - item.alternatives = sanitizeContent(item.alternatives); - } - break; - case "upload-asset": - if (!item.path || typeof item.path !== "string") { - errors.push(`Line ${i + 1}: upload_asset requires a 'path' string field`); - continue; - } - break; - case "create-code-scanning-alert": - if (!item.file || typeof item.file !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'file' field (string)`); - continue; - } - const alertLineValidation = validatePositiveInteger(item.line, "create-code-scanning-alert 'line'", i + 1); - if (!alertLineValidation.isValid) { - if (alertLineValidation.error) { - errors.push(alertLineValidation.error); + const typeCount = parsedItems.filter(existing => existing.type === itemType).length; + const maxAllowed = getMaxAllowedForType(itemType, expectedOutputTypes); + if (typeCount >= maxAllowed) { + errors.push(`Line ${i + 1}: Too many items of type '${itemType}'. Maximum allowed: ${maxAllowed}.`); + continue; } - continue; - } - if (!item.severity || typeof item.severity !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'severity' field (string)`); - continue; - } - if (!item.message || typeof item.message !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'message' field (string)`); - continue; - } - const allowedSeverities = ["error", "warning", "info", "note"]; - if (!allowedSeverities.includes(item.severity.toLowerCase())) { - errors.push( - `Line ${i + 1}: create-code-scanning-alert 'severity' must be one of: ${allowedSeverities.join(", ")}, got ${item.severity.toLowerCase()}` - ); - continue; - } - const columnValidation = validateOptionalPositiveInteger(item.column, "create-code-scanning-alert 'column'", i + 1); - if (!columnValidation.isValid) { - if (columnValidation.error) errors.push(columnValidation.error); - continue; - } - if (item.ruleIdSuffix !== undefined) { - if (typeof item.ruleIdSuffix !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must be a string`); - continue; - } - if (!/^[a-zA-Z0-9_-]+$/.test(item.ruleIdSuffix.trim())) { - errors.push( - `Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must contain only alphanumeric characters, hyphens, and underscores` - ); - continue; + core.info(`Line ${i + 1}: type '${itemType}'`); + switch (itemType) { + case "create-issue": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_issue requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_issue requires a 'body' string field`); + continue; + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + if (item.labels && Array.isArray(item.labels)) { + item.labels = item.labels.map((label) => (typeof label === "string" ? sanitizeContent(label) : label)); + } + break; + case "add-comment": + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: add_comment requires a 'body' string field`); + continue; + } + const issueNumValidation = validateIssueOrPRNumber(item.issue_number, "add_comment 'issue_number'", i + 1); + if (!issueNumValidation.isValid) { + if (issueNumValidation.error) + errors.push(issueNumValidation.error); + continue; + } + item.body = sanitizeContent(item.body); + break; + case "create-pull-request": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'body' string field`); + continue; + } + if (!item.branch || typeof item.branch !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'branch' string field`); + continue; + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + item.branch = sanitizeContent(item.branch); + if (item.labels && Array.isArray(item.labels)) { + item.labels = item.labels.map((label) => (typeof label === "string" ? sanitizeContent(label) : label)); + } + break; + case "add-labels": + if (!item.labels || !Array.isArray(item.labels)) { + errors.push(`Line ${i + 1}: add_labels requires a 'labels' array field`); + continue; + } + if (item.labels.some((label) => typeof label !== "string")) { + errors.push(`Line ${i + 1}: add_labels labels array must contain only strings`); + continue; + } + const labelsIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "add-labels 'issue_number'", i + 1); + if (!labelsIssueNumValidation.isValid) { + if (labelsIssueNumValidation.error) + errors.push(labelsIssueNumValidation.error); + continue; + } + item.labels = item.labels.map((label) => sanitizeContent(label)); + break; + case "update-issue": + const hasValidField = item.status !== undefined || item.title !== undefined || item.body !== undefined; + if (!hasValidField) { + errors.push(`Line ${i + 1}: update_issue requires at least one of: 'status', 'title', or 'body' fields`); + continue; + } + if (item.status !== undefined) { + if (typeof item.status !== "string" || (item.status !== "open" && item.status !== "closed")) { + errors.push(`Line ${i + 1}: update_issue 'status' must be 'open' or 'closed'`); + continue; + } + } + if (item.title !== undefined) { + if (typeof item.title !== "string") { + errors.push(`Line ${i + 1}: update-issue 'title' must be a string`); + continue; + } + item.title = sanitizeContent(item.title); + } + if (item.body !== undefined) { + if (typeof item.body !== "string") { + errors.push(`Line ${i + 1}: update-issue 'body' must be a string`); + continue; + } + item.body = sanitizeContent(item.body); + } + const updateIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "update-issue 'issue_number'", i + 1); + if (!updateIssueNumValidation.isValid) { + if (updateIssueNumValidation.error) + errors.push(updateIssueNumValidation.error); + continue; + } + break; + case "push-to-pull-request-branch": + if (!item.branch || typeof item.branch !== "string") { + errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'branch' string field`); + continue; + } + if (!item.message || typeof item.message !== "string") { + errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'message' string field`); + continue; + } + item.branch = sanitizeContent(item.branch); + item.message = sanitizeContent(item.message); + const pushPRNumValidation = validateIssueOrPRNumber(item.pull_request_number, "push-to-pull-request-branch 'pull_request_number'", i + 1); + if (!pushPRNumValidation.isValid) { + if (pushPRNumValidation.error) + errors.push(pushPRNumValidation.error); + continue; + } + break; + case "create-pull-request-review-comment": + if (!item.path || typeof item.path !== "string") { + errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'path' string field`); + continue; + } + const lineValidation = validatePositiveInteger(item.line, "create-pull-request-review-comment 'line'", i + 1); + if (!lineValidation.isValid) { + if (lineValidation.error) + errors.push(lineValidation.error); + continue; + } + const lineNumber = lineValidation.normalizedValue; + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'body' string field`); + continue; + } + item.body = sanitizeContent(item.body); + const startLineValidation = validateOptionalPositiveInteger(item.start_line, "create-pull-request-review-comment 'start_line'", i + 1); + if (!startLineValidation.isValid) { + if (startLineValidation.error) + errors.push(startLineValidation.error); + continue; + } + if (startLineValidation.normalizedValue !== undefined && + lineNumber !== undefined && + startLineValidation.normalizedValue > lineNumber) { + errors.push(`Line ${i + 1}: create-pull-request-review-comment 'start_line' must be less than or equal to 'line'`); + continue; + } + if (item.side !== undefined) { + if (typeof item.side !== "string" || (item.side !== "LEFT" && item.side !== "RIGHT")) { + errors.push(`Line ${i + 1}: create-pull-request-review-comment 'side' must be 'LEFT' or 'RIGHT'`); + continue; + } + } + break; + case "create-discussion": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_discussion requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_discussion requires a 'body' string field`); + continue; + } + if (item.category !== undefined) { + if (typeof item.category !== "string") { + errors.push(`Line ${i + 1}: create_discussion 'category' must be a string`); + continue; + } + item.category = sanitizeContent(item.category); + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + break; + case "missing-tool": + if (!item.tool || typeof item.tool !== "string") { + errors.push(`Line ${i + 1}: missing_tool requires a 'tool' string field`); + continue; + } + if (!item.reason || typeof item.reason !== "string") { + errors.push(`Line ${i + 1}: missing_tool requires a 'reason' string field`); + continue; + } + item.tool = sanitizeContent(item.tool); + item.reason = sanitizeContent(item.reason); + if (item.alternatives !== undefined) { + if (typeof item.alternatives !== "string") { + errors.push(`Line ${i + 1}: missing-tool 'alternatives' must be a string`); + continue; + } + item.alternatives = sanitizeContent(item.alternatives); + } + break; + case "upload-asset": + if (!item.path || typeof item.path !== "string") { + errors.push(`Line ${i + 1}: upload_asset requires a 'path' string field`); + continue; + } + break; + case "create-code-scanning-alert": + if (!item.file || typeof item.file !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'file' field (string)`); + continue; + } + const alertLineValidation = validatePositiveInteger(item.line, "create-code-scanning-alert 'line'", i + 1); + if (!alertLineValidation.isValid) { + if (alertLineValidation.error) { + errors.push(alertLineValidation.error); + } + continue; + } + if (!item.severity || typeof item.severity !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'severity' field (string)`); + continue; + } + if (!item.message || typeof item.message !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'message' field (string)`); + continue; + } + const allowedSeverities = ["error", "warning", "info", "note"]; + if (!allowedSeverities.includes(item.severity.toLowerCase())) { + errors.push(`Line ${i + 1}: create-code-scanning-alert 'severity' must be one of: ${allowedSeverities.join(", ")}, got ${item.severity.toLowerCase()}`); + continue; + } + const columnValidation = validateOptionalPositiveInteger(item.column, "create-code-scanning-alert 'column'", i + 1); + if (!columnValidation.isValid) { + if (columnValidation.error) + errors.push(columnValidation.error); + continue; + } + if (item.ruleIdSuffix !== undefined) { + if (typeof item.ruleIdSuffix !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must be a string`); + continue; + } + if (!/^[a-zA-Z0-9_-]+$/.test(item.ruleIdSuffix.trim())) { + errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must contain only alphanumeric characters, hyphens, and underscores`); + continue; + } + } + item.severity = item.severity.toLowerCase(); + item.file = sanitizeContent(item.file); + item.severity = sanitizeContent(item.severity); + item.message = sanitizeContent(item.message); + if (item.ruleIdSuffix) { + item.ruleIdSuffix = sanitizeContent(item.ruleIdSuffix); + } + break; + default: + const jobOutputType = expectedOutputTypes[itemType]; + if (!jobOutputType) { + errors.push(`Line ${i + 1}: Unknown output type '${itemType}'`); + continue; + } + const safeJobConfig = jobOutputType; + if (safeJobConfig && safeJobConfig.inputs) { + const validation = validateItemWithSafeJobConfig(item, safeJobConfig, i + 1); + if (!validation.isValid) { + errors.push(...validation.errors); + continue; + } + Object.assign(item, validation.normalizedItem); + } + break; } - } - item.severity = item.severity.toLowerCase(); - item.file = sanitizeContent(item.file); - item.severity = sanitizeContent(item.severity); - item.message = sanitizeContent(item.message); - if (item.ruleIdSuffix) { - item.ruleIdSuffix = sanitizeContent(item.ruleIdSuffix); - } - break; - default: - const jobOutputType = expectedOutputTypes[itemType]; - if (!jobOutputType) { - errors.push(`Line ${i + 1}: Unknown output type '${itemType}'`); - continue; - } - const safeJobConfig = jobOutputType; - if (safeJobConfig && safeJobConfig.inputs) { - const validation = validateItemWithSafeJobConfig(item, safeJobConfig, i + 1); - if (!validation.isValid) { - errors.push(...validation.errors); - continue; + core.info(`Line ${i + 1}: Valid ${itemType} item`); + parsedItems.push(item); + } + catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + errors.push(`Line ${i + 1}: Invalid JSON - ${errorMsg}`); + } + } + if (errors.length > 0) { + core.warning("Validation errors found:"); + errors.forEach(error => core.warning(` - ${error}`)); + if (parsedItems.length === 0) { + core.setFailed(errors.map(e => ` - ${e}`).join("\n")); + return; + } + } + for (const itemType of Object.keys(expectedOutputTypes)) { + const minRequired = getMinRequiredForType(itemType, expectedOutputTypes); + if (minRequired > 0) { + const actualCount = parsedItems.filter(item => item.type === itemType).length; + if (actualCount < minRequired) { + errors.push(`Too few items of type '${itemType}'. Minimum required: ${minRequired}, found: ${actualCount}.`); } - Object.assign(item, validation.normalizedItem); - } - break; - } - core.info(`Line ${i + 1}: Valid ${itemType} item`); - parsedItems.push(item); - } catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - errors.push(`Line ${i + 1}: Invalid JSON - ${errorMsg}`); + } } - } - if (errors.length > 0) { - core.warning("Validation errors found:"); - errors.forEach(error => core.warning(` - ${error}`)); - if (parsedItems.length === 0) { - core.setFailed(errors.map(e => ` - ${e}`).join("\n")); - return; + core.info(`Successfully parsed ${parsedItems.length} valid output items`); + const validatedOutput = { + items: parsedItems, + errors: errors, + }; + const agentOutputFile = "/tmp/agent_output.json"; + const validatedOutputJson = JSON.stringify(validatedOutput); + try { + fs.mkdirSync("/tmp", { recursive: true }); + fs.writeFileSync(agentOutputFile, validatedOutputJson, "utf8"); + core.info(`Stored validated output to: ${agentOutputFile}`); + core.exportVariable("GITHUB_AW_AGENT_OUTPUT", agentOutputFile); } - } - for (const itemType of Object.keys(expectedOutputTypes)) { - const minRequired = getMinRequiredForType(itemType, expectedOutputTypes); - if (minRequired > 0) { - const actualCount = parsedItems.filter(item => item.type === itemType).length; - if (actualCount < minRequired) { - errors.push(`Too few items of type '${itemType}'. Minimum required: ${minRequired}, found: ${actualCount}.`); - } + catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.error(`Failed to write agent output file: ${errorMsg}`); + } + core.setOutput("output", JSON.stringify(validatedOutput)); + core.setOutput("raw_output", outputContent); + const outputTypes = Array.from(new Set(parsedItems.map(item => item.type))); + core.info(`output_types: ${outputTypes.join(", ")}`); + core.setOutput("output_types", outputTypes.join(",")); + try { + await core.summary + .addRaw("## Processed Output\n\n") + .addRaw("```json\n") + .addRaw(JSON.stringify(validatedOutput)) + .addRaw("\n```\n") + .write(); + core.info("Successfully wrote processed output to step summary"); + } + catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.warning(`Failed to write to step summary: ${errorMsg}`); } - } - core.info(`Successfully parsed ${parsedItems.length} valid output items`); - const validatedOutput = { - items: parsedItems, - errors: errors, - }; - const agentOutputFile = "/tmp/agent_output.json"; - const validatedOutputJson = JSON.stringify(validatedOutput); - try { - fs.mkdirSync("/tmp", { recursive: true }); - fs.writeFileSync(agentOutputFile, validatedOutputJson, "utf8"); - core.info(`Stored validated output to: ${agentOutputFile}`); - core.exportVariable("GITHUB_AW_AGENT_OUTPUT", agentOutputFile); - } catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.error(`Failed to write agent output file: ${errorMsg}`); - } - core.setOutput("output", JSON.stringify(validatedOutput)); - core.setOutput("raw_output", outputContent); - const outputTypes = Array.from(new Set(parsedItems.map(item => item.type))); - core.info(`output_types: ${outputTypes.join(", ")}`); - core.setOutput("output_types", outputTypes.join(",")); - try { - await core.summary - .addRaw("## Processed Output\n\n") - .addRaw("```json\n") - .addRaw(JSON.stringify(validatedOutput)) - .addRaw("\n```\n") - .write(); - core.info("Successfully wrote processed output to step summary"); - } catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.warning(`Failed to write to step summary: ${errorMsg}`); - } } await main(); - name: Upload sanitized agent output @@ -1999,164 +1999,162 @@ jobs: with: script: | function sanitizeLabelContent(content) { - if (!content || typeof content !== "string") { - return ""; - } - let sanitized = content.trim(); - sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); - sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); - sanitized = sanitized.replace( - /(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, - (_m, p1, p2) => `${p1}\`@${p2}\`` - ); - sanitized = sanitized.replace(/[<>&'"]/g, ""); - return sanitized.trim(); + if (!content || typeof content !== "string") { + return ""; + } + let sanitized = content.trim(); + sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); + sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); + sanitized = sanitized.replace(/(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, (_m, p1, p2) => `${p1}\`@${p2}\``); + sanitized = sanitized.replace(/[<>&'"]/g, ""); + return sanitized.trim(); } async function main() { - const isStaged = process.env.GITHUB_AW_SAFE_OUTPUTS_STAGED === "true"; - const outputContent = process.env.GITHUB_AW_AGENT_OUTPUT; - if (!outputContent) { - core.info("No GITHUB_AW_AGENT_OUTPUT environment variable found"); - return; - } - if (outputContent.trim() === "") { - core.info("Agent output content is empty"); - return; - } - core.info(`Agent output content length: ${outputContent.length}`); - let validatedOutput; - try { - validatedOutput = JSON.parse(outputContent); - } catch (error) { - core.setFailed(`Error parsing agent output JSON: ${error instanceof Error ? error.message : String(error)}`); - return; - } - if (!validatedOutput.items || !Array.isArray(validatedOutput.items)) { - core.info("No valid items found in agent output"); - return; - } - const createIssueItems = validatedOutput.items.filter(item => item.type === "create-issue"); - if (createIssueItems.length === 0) { - core.info("No create-issue items found in agent output"); - return; - } - core.info(`Found ${createIssueItems.length} create-issue item(s)`); - if (isStaged) { - let summaryContent = "## 🎭 Staged Mode: Create Issues Preview\n\n"; - summaryContent += "The following issues would be created if staged mode was disabled:\n\n"; - for (let i = 0; i < createIssueItems.length; i++) { - const item = createIssueItems[i]; - summaryContent += `### Issue ${i + 1}\n`; - summaryContent += `**Title:** ${item.title || "No title provided"}\n\n`; - if (item.body) { - summaryContent += `**Body:**\n${item.body}\n\n`; - } - if (item.labels && item.labels.length > 0) { - summaryContent += `**Labels:** ${item.labels.join(", ")}\n\n`; - } - summaryContent += "---\n\n"; + const isStaged = process.env.GITHUB_AW_SAFE_OUTPUTS_STAGED === "true"; + const outputContent = process.env.GITHUB_AW_AGENT_OUTPUT; + if (!outputContent) { + core.info("No GITHUB_AW_AGENT_OUTPUT environment variable found"); + return; } - await core.summary.addRaw(summaryContent).write(); - core.info("📝 Issue creation preview written to step summary"); - return; - } - const parentIssueNumber = context.payload?.issue?.number; - const labelsEnv = process.env.GITHUB_AW_ISSUE_LABELS; - let envLabels = labelsEnv - ? labelsEnv - .split(",") - .map(label => label.trim()) - .filter(label => label) - : []; - const createdIssues = []; - for (let i = 0; i < createIssueItems.length; i++) { - const createIssueItem = createIssueItems[i]; - core.info( - `Processing create-issue item ${i + 1}/${createIssueItems.length}: title=${createIssueItem.title}, bodyLength=${createIssueItem.body.length}` - ); - let labels = [...envLabels]; - if (createIssueItem.labels && Array.isArray(createIssueItem.labels)) { - labels = [...labels, ...createIssueItem.labels]; + if (outputContent.trim() === "") { + core.info("Agent output content is empty"); + return; } - labels = labels - .filter(label => label != null && label !== false && label !== 0) - .map(label => String(label).trim()) - .filter(label => label) - .map(label => sanitizeLabelContent(label)) - .filter(label => label) - .map(label => (label.length > 64 ? label.substring(0, 64) : label)) - .filter((label, index, arr) => arr.indexOf(label) === index); - let title = createIssueItem.title ? createIssueItem.title.trim() : ""; - let bodyLines = createIssueItem.body.split("\n"); - if (!title) { - title = createIssueItem.body || "Agent Output"; + core.info(`Agent output content length: ${outputContent.length}`); + let validatedOutput; + try { + validatedOutput = JSON.parse(outputContent); } - const titlePrefix = process.env.GITHUB_AW_ISSUE_TITLE_PREFIX; - if (titlePrefix && !title.startsWith(titlePrefix)) { - title = titlePrefix + title; + catch (error) { + core.setFailed(`Error parsing agent output JSON: ${error instanceof Error ? error.message : String(error)}`); + return; } - if (parentIssueNumber) { - core.info("Detected issue context, parent issue #" + parentIssueNumber); - bodyLines.push(`Related to #${parentIssueNumber}`); + if (!validatedOutput.items || !Array.isArray(validatedOutput.items)) { + core.info("No valid items found in agent output"); + return; } - const runId = context.runId; - const runUrl = context.payload.repository - ? `${context.payload.repository.html_url}/actions/runs/${runId}` - : `https://github.com/actions/runs/${runId}`; - bodyLines.push(``, ``, `> Generated by Agentic Workflow [Run](${runUrl})`, ""); - const body = bodyLines.join("\n").trim(); - core.info(`Creating issue with title: ${title}`); - core.info(`Labels: ${labels}`); - core.info(`Body length: ${body.length}`); - try { - const { data: issue } = await github.rest.issues.create({ - owner: context.repo.owner, - repo: context.repo.repo, - title: title, - body: body, - labels: labels, - }); - core.info("Created issue #" + issue.number + ": " + issue.html_url); - createdIssues.push(issue); - if (parentIssueNumber) { + const createIssueItems = validatedOutput.items.filter(item => item.type === "create-issue"); + if (createIssueItems.length === 0) { + core.info("No create-issue items found in agent output"); + return; + } + core.info(`Found ${createIssueItems.length} create-issue item(s)`); + if (isStaged) { + let summaryContent = "## 🎭 Staged Mode: Create Issues Preview\n\n"; + summaryContent += "The following issues would be created if staged mode was disabled:\n\n"; + for (let i = 0; i < createIssueItems.length; i++) { + const item = createIssueItems[i]; + summaryContent += `### Issue ${i + 1}\n`; + summaryContent += `**Title:** ${item.title || "No title provided"}\n\n`; + if (item.body) { + summaryContent += `**Body:**\n${item.body}\n\n`; + } + if (item.labels && item.labels.length > 0) { + summaryContent += `**Labels:** ${item.labels.join(", ")}\n\n`; + } + summaryContent += "---\n\n"; + } + await core.summary.addRaw(summaryContent).write(); + core.info("📝 Issue creation preview written to step summary"); + return; + } + const parentIssueNumber = context.payload?.issue?.number; + const labelsEnv = process.env.GITHUB_AW_ISSUE_LABELS; + let envLabels = labelsEnv + ? labelsEnv + .split(",") + .map((label) => label.trim()) + .filter((label) => label) + : []; + const createdIssues = []; + for (let i = 0; i < createIssueItems.length; i++) { + const createIssueItem = createIssueItems[i]; + core.info(`Processing create-issue item ${i + 1}/${createIssueItems.length}: title=${createIssueItem.title}, bodyLength=${createIssueItem.body.length}`); + let labels = [...envLabels]; + if (createIssueItem.labels && Array.isArray(createIssueItem.labels)) { + labels = [...labels, ...createIssueItem.labels]; + } + labels = labels + .filter(label => label != null && label !== false && label !== 0) + .map(label => String(label).trim()) + .filter(label => label) + .map(label => sanitizeLabelContent(label)) + .filter(label => label) + .map(label => (label.length > 64 ? label.substring(0, 64) : label)) + .filter((label, index, arr) => arr.indexOf(label) === index); + let title = createIssueItem.title ? createIssueItem.title.trim() : ""; + let bodyLines = createIssueItem.body.split("\n"); + if (!title) { + title = createIssueItem.body || "Agent Output"; + } + const titlePrefix = process.env.GITHUB_AW_ISSUE_TITLE_PREFIX; + if (titlePrefix && !title.startsWith(titlePrefix)) { + title = titlePrefix + title; + } + if (parentIssueNumber) { + core.info("Detected issue context, parent issue #" + parentIssueNumber); + bodyLines.push(`Related to #${parentIssueNumber}`); + } + const runId = context.runId; + const runUrl = context.payload.repository + ? `${context.payload.repository.html_url}/actions/runs/${runId}` + : `https://github.com/actions/runs/${runId}`; + bodyLines.push(``, ``, `> Generated by Agentic Workflow [Run](${runUrl})`, ""); + const body = bodyLines.join("\n").trim(); + core.info(`Creating issue with title: ${title}`); + core.info(`Labels: ${labels}`); + core.info(`Body length: ${body.length}`); try { - await github.rest.issues.createComment({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: parentIssueNumber, - body: `Created related issue: #${issue.number}`, - }); - core.info("Added comment to parent issue #" + parentIssueNumber); - } catch (error) { - core.info(`Warning: Could not add comment to parent issue: ${error instanceof Error ? error.message : String(error)}`); + const { data: issue } = await github.rest.issues.create({ + owner: context.repo.owner, + repo: context.repo.repo, + title: title, + body: body, + labels: labels, + }); + core.info("Created issue #" + issue.number + ": " + issue.html_url); + createdIssues.push(issue); + if (parentIssueNumber) { + try { + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: parentIssueNumber, + body: `Created related issue: #${issue.number}`, + }); + core.info("Added comment to parent issue #" + parentIssueNumber); + } + catch (error) { + core.info(`Warning: Could not add comment to parent issue: ${error instanceof Error ? error.message : String(error)}`); + } + } + if (i === createIssueItems.length - 1) { + core.setOutput("issue_number", issue.number); + core.setOutput("issue_url", issue.html_url); + } + } + catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + if (errorMessage.includes("Issues has been disabled in this repository")) { + core.info(`⚠ Cannot create issue "${title}": Issues are disabled for this repository`); + core.info("Consider enabling issues in repository settings if you want to create issues automatically"); + continue; + } + core.error(`✗ Failed to create issue "${title}": ${errorMessage}`); + throw error; } - } - if (i === createIssueItems.length - 1) { - core.setOutput("issue_number", issue.number); - core.setOutput("issue_url", issue.html_url); - } - } catch (error) { - const errorMessage = error instanceof Error ? error.message : String(error); - if (errorMessage.includes("Issues has been disabled in this repository")) { - core.info(`⚠ Cannot create issue "${title}": Issues are disabled for this repository`); - core.info("Consider enabling issues in repository settings if you want to create issues automatically"); - continue; - } - core.error(`✗ Failed to create issue "${title}": ${errorMessage}`); - throw error; } - } - if (createdIssues.length > 0) { - let summaryContent = "\n\n## GitHub Issues\n"; - for (const issue of createdIssues) { - summaryContent += `- Issue #${issue.number}: [${issue.title}](${issue.html_url})\n`; + if (createdIssues.length > 0) { + let summaryContent = "\n\n## GitHub Issues\n"; + for (const issue of createdIssues) { + summaryContent += `- Issue #${issue.number}: [${issue.title}](${issue.html_url})\n`; + } + await core.summary.addRaw(summaryContent).write(); } - await core.summary.addRaw(summaryContent).write(); - } - core.info(`Successfully created ${createdIssues.length} issue(s)`); + core.info(`Successfully created ${createdIssues.length} issue(s)`); } (async () => { - await main(); + await main(); })(); missing_tool: diff --git a/.github/workflows/tidy.lock.yml b/.github/workflows/tidy.lock.yml index b1871bc7e60..bca0b207e3e 100644 --- a/.github/workflows/tidy.lock.yml +++ b/.github/workflows/tidy.lock.yml @@ -1126,742 +1126,742 @@ jobs: with: script: | async function main() { - const fs = require("fs"); - function sanitizeContent(content) { - if (!content || typeof content !== "string") { - return ""; - } - const allowedDomainsEnv = process.env.GITHUB_AW_ALLOWED_DOMAINS; - const defaultAllowedDomains = ["github.com", "github.io", "githubusercontent.com", "githubassets.com", "github.dev", "codespaces.new"]; - const allowedDomains = allowedDomainsEnv - ? allowedDomainsEnv - .split(",") - .map(d => d.trim()) - .filter(d => d) - : defaultAllowedDomains; - let sanitized = content; - sanitized = neutralizeMentions(sanitized); - sanitized = removeXmlComments(sanitized); - sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); - sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); - sanitized = sanitizeUrlProtocols(sanitized); - sanitized = sanitizeUrlDomains(sanitized); - const maxLength = 524288; - if (sanitized.length > maxLength) { - sanitized = sanitized.substring(0, maxLength) + "\n[Content truncated due to length]"; - } - const lines = sanitized.split("\n"); - const maxLines = 65000; - if (lines.length > maxLines) { - sanitized = lines.slice(0, maxLines).join("\n") + "\n[Content truncated due to line count]"; - } - sanitized = neutralizeBotTriggers(sanitized); - return sanitized.trim(); - function sanitizeUrlDomains(s) { - return s.replace(/\bhttps:\/\/[^\s\])}'"<>&\x00-\x1f,;]+/gi, match => { - const urlAfterProtocol = match.slice(8); - const hostname = urlAfterProtocol.split(/[\/:\?#]/)[0].toLowerCase(); - const isAllowed = allowedDomains.some(allowedDomain => { - const normalizedAllowed = allowedDomain.toLowerCase(); - return hostname === normalizedAllowed || hostname.endsWith("." + normalizedAllowed); - }); - return isAllowed ? match : "(redacted)"; - }); - } - function sanitizeUrlProtocols(s) { - return s.replace(/\b(\w+):\/\/[^\s\])}'"<>&\x00-\x1f]+/gi, (match, protocol) => { - return protocol.toLowerCase() === "https" ? match : "(redacted)"; - }); - } - function neutralizeMentions(s) { - return s.replace( - /(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, - (_m, p1, p2) => `${p1}\`@${p2}\`` - ); - } - function removeXmlComments(s) { - return s.replace(//g, "").replace(//g, ""); - } - function neutralizeBotTriggers(s) { - return s.replace(/\b(fixes?|closes?|resolves?|fix|close|resolve)\s+#(\w+)/gi, (match, action, ref) => `\`${action} #${ref}\``); - } - } - function getMaxAllowedForType(itemType, config) { - const itemConfig = config?.[itemType]; - if (itemConfig && typeof itemConfig === "object" && "max" in itemConfig && itemConfig.max) { - return itemConfig.max; - } - switch (itemType) { - case "create-issue": - return 1; - case "add-comment": - return 1; - case "create-pull-request": - return 1; - case "create-pull-request-review-comment": - return 1; - case "add-labels": - return 5; - case "update-issue": - return 1; - case "push-to-pull-request-branch": - return 1; - case "create-discussion": - return 1; - case "missing-tool": - return 1000; - case "create-code-scanning-alert": - return 1000; - case "upload-asset": - return 10; - default: - return 1; - } - } - function getMinRequiredForType(itemType, config) { - const itemConfig = config?.[itemType]; - if (itemConfig && typeof itemConfig === "object" && "min" in itemConfig && itemConfig.min) { - return itemConfig.min; - } - return 0; - } - function repairJson(jsonStr) { - let repaired = jsonStr.trim(); - const _ctrl = { 8: "\\b", 9: "\\t", 10: "\\n", 12: "\\f", 13: "\\r" }; - repaired = repaired.replace(/[\u0000-\u001F]/g, ch => { - const c = ch.charCodeAt(0); - return _ctrl[c] || "\\u" + c.toString(16).padStart(4, "0"); - }); - repaired = repaired.replace(/'/g, '"'); - repaired = repaired.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/g, '$1"$2":'); - repaired = repaired.replace(/"([^"\\]*)"/g, (match, content) => { - if (content.includes("\n") || content.includes("\r") || content.includes("\t")) { - const escaped = content.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"); - return `"${escaped}"`; - } - return match; - }); - repaired = repaired.replace(/"([^"]*)"([^":,}\]]*)"([^"]*)"(\s*[,:}\]])/g, (match, p1, p2, p3, p4) => `"${p1}\\"${p2}\\"${p3}"${p4}`); - repaired = repaired.replace(/(\[\s*(?:"[^"]*"(?:\s*,\s*"[^"]*")*\s*),?)\s*}/g, "$1]"); - const openBraces = (repaired.match(/\{/g) || []).length; - const closeBraces = (repaired.match(/\}/g) || []).length; - if (openBraces > closeBraces) { - repaired += "}".repeat(openBraces - closeBraces); - } else if (closeBraces > openBraces) { - repaired = "{".repeat(closeBraces - openBraces) + repaired; - } - const openBrackets = (repaired.match(/\[/g) || []).length; - const closeBrackets = (repaired.match(/\]/g) || []).length; - if (openBrackets > closeBrackets) { - repaired += "]".repeat(openBrackets - closeBrackets); - } else if (closeBrackets > openBrackets) { - repaired = "[".repeat(closeBrackets - openBrackets) + repaired; - } - repaired = repaired.replace(/,(\s*[}\]])/g, "$1"); - return repaired; - } - function validatePositiveInteger(value, fieldName, lineNum) { - if (value === undefined || value === null) { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} is required`, - }; + const fs = require("fs"); + function sanitizeContent(content) { + if (!content || typeof content !== "string") { + return ""; + } + const allowedDomainsEnv = process.env.GITHUB_AW_ALLOWED_DOMAINS; + const defaultAllowedDomains = ["github.com", "github.io", "githubusercontent.com", "githubassets.com", "github.dev", "codespaces.new"]; + const allowedDomains = allowedDomainsEnv + ? allowedDomainsEnv + .split(",") + .map(d => d.trim()) + .filter(d => d) + : defaultAllowedDomains; + let sanitized = content; + sanitized = neutralizeMentions(sanitized); + sanitized = removeXmlComments(sanitized); + sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); + sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); + sanitized = sanitizeUrlProtocols(sanitized); + sanitized = sanitizeUrlDomains(sanitized); + const maxLength = 524288; + if (sanitized.length > maxLength) { + sanitized = sanitized.substring(0, maxLength) + "\n[Content truncated due to length]"; + } + const lines = sanitized.split("\n"); + const maxLines = 65000; + if (lines.length > maxLines) { + sanitized = lines.slice(0, maxLines).join("\n") + "\n[Content truncated due to line count]"; + } + sanitized = neutralizeBotTriggers(sanitized); + return sanitized.trim(); + function sanitizeUrlDomains(s) { + return s.replace(/\bhttps:\/\/[^\s\])}'"<>&\x00-\x1f,;]+/gi, match => { + const urlAfterProtocol = match.slice(8); + const hostname = urlAfterProtocol.split(/[\/:\?#]/)[0].toLowerCase(); + const isAllowed = allowedDomains.some(allowedDomain => { + const normalizedAllowed = allowedDomain.toLowerCase(); + return hostname === normalizedAllowed || hostname.endsWith("." + normalizedAllowed); + }); + return isAllowed ? match : "(redacted)"; + }); + } + function sanitizeUrlProtocols(s) { + return s.replace(/\b(\w+):\/\/[^\s\])}'"<>&\x00-\x1f]+/gi, (match, protocol) => { + return protocol.toLowerCase() === "https" ? match : "(redacted)"; + }); + } + function neutralizeMentions(s) { + return s.replace(/(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, (_m, p1, p2) => `${p1}\`@${p2}\``); + } + function removeXmlComments(s) { + return s.replace(//g, "").replace(//g, ""); + } + function neutralizeBotTriggers(s) { + return s.replace(/\b(fixes?|closes?|resolves?|fix|close|resolve)\s+#(\w+)/gi, (match, action, ref) => `\`${action} #${ref}\``); + } } - if (typeof value !== "number" && typeof value !== "string") { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number or string field`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; + function getMaxAllowedForType(itemType, config) { + const itemConfig = config?.[itemType]; + if (itemConfig && typeof itemConfig === "object" && "max" in itemConfig && itemConfig.max) { + return itemConfig.max; + } + switch (itemType) { + case "create-issue": + return 1; + case "add-comment": + return 1; + case "create-pull-request": + return 1; + case "create-pull-request-review-comment": + return 1; + case "add-labels": + return 5; + case "update-issue": + return 1; + case "push-to-pull-request-branch": + return 1; + case "create-discussion": + return 1; + case "missing-tool": + return 1000; + case "create-code-scanning-alert": + return 1000; + case "upload-asset": + return 10; + default: + return 1; + } } - const parsed = typeof value === "string" ? parseInt(value, 10) : value; - if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'line' must be a valid positive integer (got: ${value})`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'line' must be a positive integer`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, - }; + function getMinRequiredForType(itemType, config) { + const itemConfig = config?.[itemType]; + if (itemConfig && typeof itemConfig === "object" && "min" in itemConfig && itemConfig.min) { + return itemConfig.min; + } + return 0; + } + function repairJson(jsonStr) { + let repaired = jsonStr.trim(); + const _ctrl = { 8: "\\b", 9: "\\t", 10: "\\n", 12: "\\f", 13: "\\r" }; + repaired = repaired.replace(/[\u0000-\u001F]/g, ch => { + const c = ch.charCodeAt(0); + return _ctrl[c] || "\\u" + c.toString(16).padStart(4, "0"); + }); + repaired = repaired.replace(/'/g, '"'); + repaired = repaired.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/g, '$1"$2":'); + repaired = repaired.replace(/"([^"\\]*)"/g, (match, content) => { + if (content.includes("\n") || content.includes("\r") || content.includes("\t")) { + const escaped = content.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"); + return `"${escaped}"`; + } + return match; + }); + repaired = repaired.replace(/"([^"]*)"([^":,}\]]*)"([^"]*)"(\s*[,:}\]])/g, (match, p1, p2, p3, p4) => `"${p1}\\"${p2}\\"${p3}"${p4}`); + repaired = repaired.replace(/(\[\s*(?:"[^"]*"(?:\s*,\s*"[^"]*")*\s*),?)\s*}/g, "$1]"); + const openBraces = (repaired.match(/\{/g) || []).length; + const closeBraces = (repaired.match(/\}/g) || []).length; + if (openBraces > closeBraces) { + repaired += "}".repeat(openBraces - closeBraces); + } + else if (closeBraces > openBraces) { + repaired = "{".repeat(closeBraces - openBraces) + repaired; + } + const openBrackets = (repaired.match(/\[/g) || []).length; + const closeBrackets = (repaired.match(/\]/g) || []).length; + if (openBrackets > closeBrackets) { + repaired += "]".repeat(openBrackets - closeBrackets); + } + else if (closeBrackets > openBrackets) { + repaired = "[".repeat(closeBrackets - openBrackets) + repaired; + } + repaired = repaired.replace(/,(\s*[}\]])/g, "$1"); + return repaired; + } + function validatePositiveInteger(value, fieldName, lineNum) { + if (value === undefined || value === null) { + if (fieldName.includes("create-code-scanning-alert 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, + }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} is required`, + }; + } + if (typeof value !== "number" && typeof value !== "string") { + if (fieldName.includes("create-code-scanning-alert 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, + }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number or string field`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; + } + const parsed = typeof value === "string" ? parseInt(value, 10) : value; + if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { + if (fieldName.includes("create-code-scanning-alert 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'line' must be a valid positive integer (got: ${value})`, + }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'line' must be a positive integer`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, + }; + } + return { isValid: true, normalizedValue: parsed }; } - return { isValid: true, normalizedValue: parsed }; - } - function validateOptionalPositiveInteger(value, fieldName, lineNum) { - if (value === undefined) { - return { isValid: true }; + function validateOptionalPositiveInteger(value, fieldName, lineNum) { + if (value === undefined) { + return { isValid: true }; + } + if (typeof value !== "number" && typeof value !== "string") { + if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a number or string`, + }; + } + if (fieldName.includes("create-code-scanning-alert 'column'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a number or string`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; + } + const parsed = typeof value === "string" ? parseInt(value, 10) : value; + if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { + if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a positive integer`, + }; + } + if (fieldName.includes("create-code-scanning-alert 'column'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a valid positive integer (got: ${value})`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, + }; + } + return { isValid: true, normalizedValue: parsed }; } - if (typeof value !== "number" && typeof value !== "string") { - if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a number or string`, - }; - } - if (fieldName.includes("create-code-scanning-alert 'column'")) { + function validateIssueOrPRNumber(value, fieldName, lineNum) { + if (value === undefined) { + return { isValid: true }; + } + if (typeof value !== "number" && typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; + } + return { isValid: true }; + } + function validateFieldWithInputSchema(value, fieldName, inputSchema, lineNum) { + if (inputSchema.required && (value === undefined || value === null)) { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} is required`, + }; + } + if (value === undefined || value === null) { + return { + isValid: true, + normalizedValue: inputSchema.default || undefined, + }; + } + const inputType = inputSchema.type || "string"; + let normalizedValue = value; + switch (inputType) { + case "string": + if (typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a string`, + }; + } + normalizedValue = sanitizeContent(value); + break; + case "boolean": + if (typeof value !== "boolean") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a boolean`, + }; + } + break; + case "number": + if (typeof value !== "number") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number`, + }; + } + break; + case "choice": + if (typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a string for choice type`, + }; + } + if (inputSchema.options && !inputSchema.options.includes(value)) { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be one of: ${inputSchema.options.join(", ")}`, + }; + } + normalizedValue = sanitizeContent(value); + break; + default: + if (typeof value === "string") { + normalizedValue = sanitizeContent(value); + } + break; + } return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a number or string`, + isValid: true, + normalizedValue, }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; } - const parsed = typeof value === "string" ? parseInt(value, 10) : value; - if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { - if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a positive integer`, - }; - } - if (fieldName.includes("create-code-scanning-alert 'column'")) { + function validateItemWithSafeJobConfig(item, jobConfig, lineNum) { + const errors = []; + const normalizedItem = { ...item }; + if (!jobConfig.inputs) { + return { + isValid: true, + errors: [], + normalizedItem: item, + }; + } + for (const [fieldName, inputSchema] of Object.entries(jobConfig.inputs)) { + const fieldValue = item[fieldName]; + const validation = validateFieldWithInputSchema(fieldValue, fieldName, inputSchema, lineNum); + if (!validation.isValid && validation.error) { + errors.push(validation.error); + } + else if (validation.normalizedValue !== undefined) { + normalizedItem[fieldName] = validation.normalizedValue; + } + } return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a valid positive integer (got: ${value})`, + isValid: errors.length === 0, + errors, + normalizedItem, }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, - }; } - return { isValid: true, normalizedValue: parsed }; - } - function validateIssueOrPRNumber(value, fieldName, lineNum) { - if (value === undefined) { - return { isValid: true }; + function parseJsonWithRepair(jsonStr) { + try { + return JSON.parse(jsonStr); + } + catch (originalError) { + try { + const repairedJson = repairJson(jsonStr); + return JSON.parse(repairedJson); + } + catch (repairError) { + core.info(`invalid input json: ${jsonStr}`); + const originalMsg = originalError instanceof Error ? originalError.message : String(originalError); + const repairMsg = repairError instanceof Error ? repairError.message : String(repairError); + throw new Error(`JSON parsing failed. Original: ${originalMsg}. After attempted repair: ${repairMsg}`); + } + } } - if (typeof value !== "number" && typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; + const outputFile = process.env.GITHUB_AW_SAFE_OUTPUTS; + const safeOutputsConfig = process.env.GITHUB_AW_SAFE_OUTPUTS_CONFIG; + if (!outputFile) { + core.info("GITHUB_AW_SAFE_OUTPUTS not set, no output to collect"); + core.setOutput("output", ""); + return; } - return { isValid: true }; - } - function validateFieldWithInputSchema(value, fieldName, inputSchema, lineNum) { - if (inputSchema.required && (value === undefined || value === null)) { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} is required`, - }; + if (!fs.existsSync(outputFile)) { + core.info(`Output file does not exist: ${outputFile}`); + core.setOutput("output", ""); + return; } - if (value === undefined || value === null) { - return { - isValid: true, - normalizedValue: inputSchema.default || undefined, - }; + const outputContent = fs.readFileSync(outputFile, "utf8"); + if (outputContent.trim() === "") { + core.info("Output file is empty"); } - const inputType = inputSchema.type || "string"; - let normalizedValue = value; - switch (inputType) { - case "string": - if (typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a string`, - }; - } - normalizedValue = sanitizeContent(value); - break; - case "boolean": - if (typeof value !== "boolean") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a boolean`, - }; - } - break; - case "number": - if (typeof value !== "number") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number`, - }; - } - break; - case "choice": - if (typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a string for choice type`, - }; + core.info(`Raw output content length: ${outputContent.length}`); + let expectedOutputTypes = {}; + if (safeOutputsConfig) { + try { + expectedOutputTypes = JSON.parse(safeOutputsConfig); + core.info(`Expected output types: ${JSON.stringify(Object.keys(expectedOutputTypes))}`); } - if (inputSchema.options && !inputSchema.options.includes(value)) { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be one of: ${inputSchema.options.join(", ")}`, - }; + catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.info(`Warning: Could not parse safe-outputs config: ${errorMsg}`); } - normalizedValue = sanitizeContent(value); - break; - default: - if (typeof value === "string") { - normalizedValue = sanitizeContent(value); - } - break; } - return { - isValid: true, - normalizedValue, - }; - } - function validateItemWithSafeJobConfig(item, jobConfig, lineNum) { + const lines = outputContent.trim().split("\n"); + const parsedItems = []; const errors = []; - const normalizedItem = { ...item }; - if (!jobConfig.inputs) { - return { - isValid: true, - errors: [], - normalizedItem: item, - }; - } - for (const [fieldName, inputSchema] of Object.entries(jobConfig.inputs)) { - const fieldValue = item[fieldName]; - const validation = validateFieldWithInputSchema(fieldValue, fieldName, inputSchema, lineNum); - if (!validation.isValid && validation.error) { - errors.push(validation.error); - } else if (validation.normalizedValue !== undefined) { - normalizedItem[fieldName] = validation.normalizedValue; - } - } - return { - isValid: errors.length === 0, - errors, - normalizedItem, - }; - } - function parseJsonWithRepair(jsonStr) { - try { - return JSON.parse(jsonStr); - } catch (originalError) { - try { - const repairedJson = repairJson(jsonStr); - return JSON.parse(repairedJson); - } catch (repairError) { - core.info(`invalid input json: ${jsonStr}`); - const originalMsg = originalError instanceof Error ? originalError.message : String(originalError); - const repairMsg = repairError instanceof Error ? repairError.message : String(repairError); - throw new Error(`JSON parsing failed. Original: ${originalMsg}. After attempted repair: ${repairMsg}`); - } - } - } - const outputFile = process.env.GITHUB_AW_SAFE_OUTPUTS; - const safeOutputsConfig = process.env.GITHUB_AW_SAFE_OUTPUTS_CONFIG; - if (!outputFile) { - core.info("GITHUB_AW_SAFE_OUTPUTS not set, no output to collect"); - core.setOutput("output", ""); - return; - } - if (!fs.existsSync(outputFile)) { - core.info(`Output file does not exist: ${outputFile}`); - core.setOutput("output", ""); - return; - } - const outputContent = fs.readFileSync(outputFile, "utf8"); - if (outputContent.trim() === "") { - core.info("Output file is empty"); - } - core.info(`Raw output content length: ${outputContent.length}`); - let expectedOutputTypes = {}; - if (safeOutputsConfig) { - try { - expectedOutputTypes = JSON.parse(safeOutputsConfig); - core.info(`Expected output types: ${JSON.stringify(Object.keys(expectedOutputTypes))}`); - } catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.info(`Warning: Could not parse safe-outputs config: ${errorMsg}`); - } - } - const lines = outputContent.trim().split("\n"); - const parsedItems = []; - const errors = []; - for (let i = 0; i < lines.length; i++) { - const line = lines[i].trim(); - if (line === "") continue; - try { - const item = parseJsonWithRepair(line); - if (item === undefined) { - errors.push(`Line ${i + 1}: Invalid JSON - JSON parsing failed`); - continue; - } - if (!item.type) { - errors.push(`Line ${i + 1}: Missing required 'type' field`); - continue; - } - const itemType = item.type; - if (!expectedOutputTypes[itemType]) { - errors.push(`Line ${i + 1}: Unexpected output type '${itemType}'. Expected one of: ${Object.keys(expectedOutputTypes).join(", ")}`); - continue; - } - const typeCount = parsedItems.filter(existing => existing.type === itemType).length; - const maxAllowed = getMaxAllowedForType(itemType, expectedOutputTypes); - if (typeCount >= maxAllowed) { - errors.push(`Line ${i + 1}: Too many items of type '${itemType}'. Maximum allowed: ${maxAllowed}.`); - continue; - } - core.info(`Line ${i + 1}: type '${itemType}'`); - switch (itemType) { - case "create-issue": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_issue requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_issue requires a 'body' string field`); - continue; - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - if (item.labels && Array.isArray(item.labels)) { - item.labels = item.labels.map(label => (typeof label === "string" ? sanitizeContent(label) : label)); - } - break; - case "add-comment": - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: add_comment requires a 'body' string field`); - continue; - } - const issueNumValidation = validateIssueOrPRNumber(item.issue_number, "add_comment 'issue_number'", i + 1); - if (!issueNumValidation.isValid) { - if (issueNumValidation.error) errors.push(issueNumValidation.error); - continue; - } - item.body = sanitizeContent(item.body); - break; - case "create-pull-request": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'body' string field`); + for (let i = 0; i < lines.length; i++) { + const line = lines[i].trim(); + if (line === "") continue; - } - if (!item.branch || typeof item.branch !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'branch' string field`); - continue; - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - item.branch = sanitizeContent(item.branch); - if (item.labels && Array.isArray(item.labels)) { - item.labels = item.labels.map(label => (typeof label === "string" ? sanitizeContent(label) : label)); - } - break; - case "add-labels": - if (!item.labels || !Array.isArray(item.labels)) { - errors.push(`Line ${i + 1}: add_labels requires a 'labels' array field`); - continue; - } - if (item.labels.some(label => typeof label !== "string")) { - errors.push(`Line ${i + 1}: add_labels labels array must contain only strings`); - continue; - } - const labelsIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "add-labels 'issue_number'", i + 1); - if (!labelsIssueNumValidation.isValid) { - if (labelsIssueNumValidation.error) errors.push(labelsIssueNumValidation.error); - continue; - } - item.labels = item.labels.map(label => sanitizeContent(label)); - break; - case "update-issue": - const hasValidField = item.status !== undefined || item.title !== undefined || item.body !== undefined; - if (!hasValidField) { - errors.push(`Line ${i + 1}: update_issue requires at least one of: 'status', 'title', or 'body' fields`); - continue; - } - if (item.status !== undefined) { - if (typeof item.status !== "string" || (item.status !== "open" && item.status !== "closed")) { - errors.push(`Line ${i + 1}: update_issue 'status' must be 'open' or 'closed'`); - continue; + try { + const item = parseJsonWithRepair(line); + if (item === undefined) { + errors.push(`Line ${i + 1}: Invalid JSON - JSON parsing failed`); + continue; } - } - if (item.title !== undefined) { - if (typeof item.title !== "string") { - errors.push(`Line ${i + 1}: update-issue 'title' must be a string`); - continue; + if (!item.type) { + errors.push(`Line ${i + 1}: Missing required 'type' field`); + continue; } - item.title = sanitizeContent(item.title); - } - if (item.body !== undefined) { - if (typeof item.body !== "string") { - errors.push(`Line ${i + 1}: update-issue 'body' must be a string`); - continue; + const itemType = item.type; + if (!expectedOutputTypes[itemType]) { + errors.push(`Line ${i + 1}: Unexpected output type '${itemType}'. Expected one of: ${Object.keys(expectedOutputTypes).join(", ")}`); + continue; } - item.body = sanitizeContent(item.body); - } - const updateIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "update-issue 'issue_number'", i + 1); - if (!updateIssueNumValidation.isValid) { - if (updateIssueNumValidation.error) errors.push(updateIssueNumValidation.error); - continue; - } - break; - case "push-to-pull-request-branch": - if (!item.branch || typeof item.branch !== "string") { - errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'branch' string field`); - continue; - } - if (!item.message || typeof item.message !== "string") { - errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'message' string field`); - continue; - } - item.branch = sanitizeContent(item.branch); - item.message = sanitizeContent(item.message); - const pushPRNumValidation = validateIssueOrPRNumber( - item.pull_request_number, - "push-to-pull-request-branch 'pull_request_number'", - i + 1 - ); - if (!pushPRNumValidation.isValid) { - if (pushPRNumValidation.error) errors.push(pushPRNumValidation.error); - continue; - } - break; - case "create-pull-request-review-comment": - if (!item.path || typeof item.path !== "string") { - errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'path' string field`); - continue; - } - const lineValidation = validatePositiveInteger(item.line, "create-pull-request-review-comment 'line'", i + 1); - if (!lineValidation.isValid) { - if (lineValidation.error) errors.push(lineValidation.error); - continue; - } - const lineNumber = lineValidation.normalizedValue; - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'body' string field`); - continue; - } - item.body = sanitizeContent(item.body); - const startLineValidation = validateOptionalPositiveInteger( - item.start_line, - "create-pull-request-review-comment 'start_line'", - i + 1 - ); - if (!startLineValidation.isValid) { - if (startLineValidation.error) errors.push(startLineValidation.error); - continue; - } - if ( - startLineValidation.normalizedValue !== undefined && - lineNumber !== undefined && - startLineValidation.normalizedValue > lineNumber - ) { - errors.push(`Line ${i + 1}: create-pull-request-review-comment 'start_line' must be less than or equal to 'line'`); - continue; - } - if (item.side !== undefined) { - if (typeof item.side !== "string" || (item.side !== "LEFT" && item.side !== "RIGHT")) { - errors.push(`Line ${i + 1}: create-pull-request-review-comment 'side' must be 'LEFT' or 'RIGHT'`); - continue; - } - } - break; - case "create-discussion": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_discussion requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_discussion requires a 'body' string field`); - continue; - } - if (item.category !== undefined) { - if (typeof item.category !== "string") { - errors.push(`Line ${i + 1}: create_discussion 'category' must be a string`); - continue; - } - item.category = sanitizeContent(item.category); - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - break; - case "missing-tool": - if (!item.tool || typeof item.tool !== "string") { - errors.push(`Line ${i + 1}: missing_tool requires a 'tool' string field`); - continue; - } - if (!item.reason || typeof item.reason !== "string") { - errors.push(`Line ${i + 1}: missing_tool requires a 'reason' string field`); - continue; - } - item.tool = sanitizeContent(item.tool); - item.reason = sanitizeContent(item.reason); - if (item.alternatives !== undefined) { - if (typeof item.alternatives !== "string") { - errors.push(`Line ${i + 1}: missing-tool 'alternatives' must be a string`); - continue; - } - item.alternatives = sanitizeContent(item.alternatives); - } - break; - case "upload-asset": - if (!item.path || typeof item.path !== "string") { - errors.push(`Line ${i + 1}: upload_asset requires a 'path' string field`); - continue; - } - break; - case "create-code-scanning-alert": - if (!item.file || typeof item.file !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'file' field (string)`); - continue; - } - const alertLineValidation = validatePositiveInteger(item.line, "create-code-scanning-alert 'line'", i + 1); - if (!alertLineValidation.isValid) { - if (alertLineValidation.error) { - errors.push(alertLineValidation.error); - } - continue; - } - if (!item.severity || typeof item.severity !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'severity' field (string)`); - continue; - } - if (!item.message || typeof item.message !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'message' field (string)`); - continue; - } - const allowedSeverities = ["error", "warning", "info", "note"]; - if (!allowedSeverities.includes(item.severity.toLowerCase())) { - errors.push( - `Line ${i + 1}: create-code-scanning-alert 'severity' must be one of: ${allowedSeverities.join(", ")}, got ${item.severity.toLowerCase()}` - ); - continue; - } - const columnValidation = validateOptionalPositiveInteger(item.column, "create-code-scanning-alert 'column'", i + 1); - if (!columnValidation.isValid) { - if (columnValidation.error) errors.push(columnValidation.error); - continue; - } - if (item.ruleIdSuffix !== undefined) { - if (typeof item.ruleIdSuffix !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must be a string`); - continue; + const typeCount = parsedItems.filter(existing => existing.type === itemType).length; + const maxAllowed = getMaxAllowedForType(itemType, expectedOutputTypes); + if (typeCount >= maxAllowed) { + errors.push(`Line ${i + 1}: Too many items of type '${itemType}'. Maximum allowed: ${maxAllowed}.`); + continue; } - if (!/^[a-zA-Z0-9_-]+$/.test(item.ruleIdSuffix.trim())) { - errors.push( - `Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must contain only alphanumeric characters, hyphens, and underscores` - ); - continue; + core.info(`Line ${i + 1}: type '${itemType}'`); + switch (itemType) { + case "create-issue": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_issue requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_issue requires a 'body' string field`); + continue; + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + if (item.labels && Array.isArray(item.labels)) { + item.labels = item.labels.map((label) => (typeof label === "string" ? sanitizeContent(label) : label)); + } + break; + case "add-comment": + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: add_comment requires a 'body' string field`); + continue; + } + const issueNumValidation = validateIssueOrPRNumber(item.issue_number, "add_comment 'issue_number'", i + 1); + if (!issueNumValidation.isValid) { + if (issueNumValidation.error) + errors.push(issueNumValidation.error); + continue; + } + item.body = sanitizeContent(item.body); + break; + case "create-pull-request": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'body' string field`); + continue; + } + if (!item.branch || typeof item.branch !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'branch' string field`); + continue; + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + item.branch = sanitizeContent(item.branch); + if (item.labels && Array.isArray(item.labels)) { + item.labels = item.labels.map((label) => (typeof label === "string" ? sanitizeContent(label) : label)); + } + break; + case "add-labels": + if (!item.labels || !Array.isArray(item.labels)) { + errors.push(`Line ${i + 1}: add_labels requires a 'labels' array field`); + continue; + } + if (item.labels.some((label) => typeof label !== "string")) { + errors.push(`Line ${i + 1}: add_labels labels array must contain only strings`); + continue; + } + const labelsIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "add-labels 'issue_number'", i + 1); + if (!labelsIssueNumValidation.isValid) { + if (labelsIssueNumValidation.error) + errors.push(labelsIssueNumValidation.error); + continue; + } + item.labels = item.labels.map((label) => sanitizeContent(label)); + break; + case "update-issue": + const hasValidField = item.status !== undefined || item.title !== undefined || item.body !== undefined; + if (!hasValidField) { + errors.push(`Line ${i + 1}: update_issue requires at least one of: 'status', 'title', or 'body' fields`); + continue; + } + if (item.status !== undefined) { + if (typeof item.status !== "string" || (item.status !== "open" && item.status !== "closed")) { + errors.push(`Line ${i + 1}: update_issue 'status' must be 'open' or 'closed'`); + continue; + } + } + if (item.title !== undefined) { + if (typeof item.title !== "string") { + errors.push(`Line ${i + 1}: update-issue 'title' must be a string`); + continue; + } + item.title = sanitizeContent(item.title); + } + if (item.body !== undefined) { + if (typeof item.body !== "string") { + errors.push(`Line ${i + 1}: update-issue 'body' must be a string`); + continue; + } + item.body = sanitizeContent(item.body); + } + const updateIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "update-issue 'issue_number'", i + 1); + if (!updateIssueNumValidation.isValid) { + if (updateIssueNumValidation.error) + errors.push(updateIssueNumValidation.error); + continue; + } + break; + case "push-to-pull-request-branch": + if (!item.branch || typeof item.branch !== "string") { + errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'branch' string field`); + continue; + } + if (!item.message || typeof item.message !== "string") { + errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'message' string field`); + continue; + } + item.branch = sanitizeContent(item.branch); + item.message = sanitizeContent(item.message); + const pushPRNumValidation = validateIssueOrPRNumber(item.pull_request_number, "push-to-pull-request-branch 'pull_request_number'", i + 1); + if (!pushPRNumValidation.isValid) { + if (pushPRNumValidation.error) + errors.push(pushPRNumValidation.error); + continue; + } + break; + case "create-pull-request-review-comment": + if (!item.path || typeof item.path !== "string") { + errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'path' string field`); + continue; + } + const lineValidation = validatePositiveInteger(item.line, "create-pull-request-review-comment 'line'", i + 1); + if (!lineValidation.isValid) { + if (lineValidation.error) + errors.push(lineValidation.error); + continue; + } + const lineNumber = lineValidation.normalizedValue; + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'body' string field`); + continue; + } + item.body = sanitizeContent(item.body); + const startLineValidation = validateOptionalPositiveInteger(item.start_line, "create-pull-request-review-comment 'start_line'", i + 1); + if (!startLineValidation.isValid) { + if (startLineValidation.error) + errors.push(startLineValidation.error); + continue; + } + if (startLineValidation.normalizedValue !== undefined && + lineNumber !== undefined && + startLineValidation.normalizedValue > lineNumber) { + errors.push(`Line ${i + 1}: create-pull-request-review-comment 'start_line' must be less than or equal to 'line'`); + continue; + } + if (item.side !== undefined) { + if (typeof item.side !== "string" || (item.side !== "LEFT" && item.side !== "RIGHT")) { + errors.push(`Line ${i + 1}: create-pull-request-review-comment 'side' must be 'LEFT' or 'RIGHT'`); + continue; + } + } + break; + case "create-discussion": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_discussion requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_discussion requires a 'body' string field`); + continue; + } + if (item.category !== undefined) { + if (typeof item.category !== "string") { + errors.push(`Line ${i + 1}: create_discussion 'category' must be a string`); + continue; + } + item.category = sanitizeContent(item.category); + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + break; + case "missing-tool": + if (!item.tool || typeof item.tool !== "string") { + errors.push(`Line ${i + 1}: missing_tool requires a 'tool' string field`); + continue; + } + if (!item.reason || typeof item.reason !== "string") { + errors.push(`Line ${i + 1}: missing_tool requires a 'reason' string field`); + continue; + } + item.tool = sanitizeContent(item.tool); + item.reason = sanitizeContent(item.reason); + if (item.alternatives !== undefined) { + if (typeof item.alternatives !== "string") { + errors.push(`Line ${i + 1}: missing-tool 'alternatives' must be a string`); + continue; + } + item.alternatives = sanitizeContent(item.alternatives); + } + break; + case "upload-asset": + if (!item.path || typeof item.path !== "string") { + errors.push(`Line ${i + 1}: upload_asset requires a 'path' string field`); + continue; + } + break; + case "create-code-scanning-alert": + if (!item.file || typeof item.file !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'file' field (string)`); + continue; + } + const alertLineValidation = validatePositiveInteger(item.line, "create-code-scanning-alert 'line'", i + 1); + if (!alertLineValidation.isValid) { + if (alertLineValidation.error) { + errors.push(alertLineValidation.error); + } + continue; + } + if (!item.severity || typeof item.severity !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'severity' field (string)`); + continue; + } + if (!item.message || typeof item.message !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'message' field (string)`); + continue; + } + const allowedSeverities = ["error", "warning", "info", "note"]; + if (!allowedSeverities.includes(item.severity.toLowerCase())) { + errors.push(`Line ${i + 1}: create-code-scanning-alert 'severity' must be one of: ${allowedSeverities.join(", ")}, got ${item.severity.toLowerCase()}`); + continue; + } + const columnValidation = validateOptionalPositiveInteger(item.column, "create-code-scanning-alert 'column'", i + 1); + if (!columnValidation.isValid) { + if (columnValidation.error) + errors.push(columnValidation.error); + continue; + } + if (item.ruleIdSuffix !== undefined) { + if (typeof item.ruleIdSuffix !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must be a string`); + continue; + } + if (!/^[a-zA-Z0-9_-]+$/.test(item.ruleIdSuffix.trim())) { + errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must contain only alphanumeric characters, hyphens, and underscores`); + continue; + } + } + item.severity = item.severity.toLowerCase(); + item.file = sanitizeContent(item.file); + item.severity = sanitizeContent(item.severity); + item.message = sanitizeContent(item.message); + if (item.ruleIdSuffix) { + item.ruleIdSuffix = sanitizeContent(item.ruleIdSuffix); + } + break; + default: + const jobOutputType = expectedOutputTypes[itemType]; + if (!jobOutputType) { + errors.push(`Line ${i + 1}: Unknown output type '${itemType}'`); + continue; + } + const safeJobConfig = jobOutputType; + if (safeJobConfig && safeJobConfig.inputs) { + const validation = validateItemWithSafeJobConfig(item, safeJobConfig, i + 1); + if (!validation.isValid) { + errors.push(...validation.errors); + continue; + } + Object.assign(item, validation.normalizedItem); + } + break; } - } - item.severity = item.severity.toLowerCase(); - item.file = sanitizeContent(item.file); - item.severity = sanitizeContent(item.severity); - item.message = sanitizeContent(item.message); - if (item.ruleIdSuffix) { - item.ruleIdSuffix = sanitizeContent(item.ruleIdSuffix); - } - break; - default: - const jobOutputType = expectedOutputTypes[itemType]; - if (!jobOutputType) { - errors.push(`Line ${i + 1}: Unknown output type '${itemType}'`); - continue; - } - const safeJobConfig = jobOutputType; - if (safeJobConfig && safeJobConfig.inputs) { - const validation = validateItemWithSafeJobConfig(item, safeJobConfig, i + 1); - if (!validation.isValid) { - errors.push(...validation.errors); - continue; - } - Object.assign(item, validation.normalizedItem); - } - break; - } - core.info(`Line ${i + 1}: Valid ${itemType} item`); - parsedItems.push(item); - } catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - errors.push(`Line ${i + 1}: Invalid JSON - ${errorMsg}`); + core.info(`Line ${i + 1}: Valid ${itemType} item`); + parsedItems.push(item); + } + catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + errors.push(`Line ${i + 1}: Invalid JSON - ${errorMsg}`); + } } - } - if (errors.length > 0) { - core.warning("Validation errors found:"); - errors.forEach(error => core.warning(` - ${error}`)); - if (parsedItems.length === 0) { - core.setFailed(errors.map(e => ` - ${e}`).join("\n")); - return; + if (errors.length > 0) { + core.warning("Validation errors found:"); + errors.forEach(error => core.warning(` - ${error}`)); + if (parsedItems.length === 0) { + core.setFailed(errors.map(e => ` - ${e}`).join("\n")); + return; + } } - } - for (const itemType of Object.keys(expectedOutputTypes)) { - const minRequired = getMinRequiredForType(itemType, expectedOutputTypes); - if (minRequired > 0) { - const actualCount = parsedItems.filter(item => item.type === itemType).length; - if (actualCount < minRequired) { - errors.push(`Too few items of type '${itemType}'. Minimum required: ${minRequired}, found: ${actualCount}.`); - } + for (const itemType of Object.keys(expectedOutputTypes)) { + const minRequired = getMinRequiredForType(itemType, expectedOutputTypes); + if (minRequired > 0) { + const actualCount = parsedItems.filter(item => item.type === itemType).length; + if (actualCount < minRequired) { + errors.push(`Too few items of type '${itemType}'. Minimum required: ${minRequired}, found: ${actualCount}.`); + } + } + } + core.info(`Successfully parsed ${parsedItems.length} valid output items`); + const validatedOutput = { + items: parsedItems, + errors: errors, + }; + const agentOutputFile = "/tmp/agent_output.json"; + const validatedOutputJson = JSON.stringify(validatedOutput); + try { + fs.mkdirSync("/tmp", { recursive: true }); + fs.writeFileSync(agentOutputFile, validatedOutputJson, "utf8"); + core.info(`Stored validated output to: ${agentOutputFile}`); + core.exportVariable("GITHUB_AW_AGENT_OUTPUT", agentOutputFile); + } + catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.error(`Failed to write agent output file: ${errorMsg}`); + } + core.setOutput("output", JSON.stringify(validatedOutput)); + core.setOutput("raw_output", outputContent); + const outputTypes = Array.from(new Set(parsedItems.map(item => item.type))); + core.info(`output_types: ${outputTypes.join(", ")}`); + core.setOutput("output_types", outputTypes.join(",")); + try { + await core.summary + .addRaw("## Processed Output\n\n") + .addRaw("```json\n") + .addRaw(JSON.stringify(validatedOutput)) + .addRaw("\n```\n") + .write(); + core.info("Successfully wrote processed output to step summary"); + } + catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.warning(`Failed to write to step summary: ${errorMsg}`); } - } - core.info(`Successfully parsed ${parsedItems.length} valid output items`); - const validatedOutput = { - items: parsedItems, - errors: errors, - }; - const agentOutputFile = "/tmp/agent_output.json"; - const validatedOutputJson = JSON.stringify(validatedOutput); - try { - fs.mkdirSync("/tmp", { recursive: true }); - fs.writeFileSync(agentOutputFile, validatedOutputJson, "utf8"); - core.info(`Stored validated output to: ${agentOutputFile}`); - core.exportVariable("GITHUB_AW_AGENT_OUTPUT", agentOutputFile); - } catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.error(`Failed to write agent output file: ${errorMsg}`); - } - core.setOutput("output", JSON.stringify(validatedOutput)); - core.setOutput("raw_output", outputContent); - const outputTypes = Array.from(new Set(parsedItems.map(item => item.type))); - core.info(`output_types: ${outputTypes.join(", ")}`); - core.setOutput("output_types", outputTypes.join(",")); - try { - await core.summary - .addRaw("## Processed Output\n\n") - .addRaw("```json\n") - .addRaw(JSON.stringify(validatedOutput)) - .addRaw("\n```\n") - .write(); - core.info("Successfully wrote processed output to step summary"); - } catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.warning(`Failed to write to step summary: ${errorMsg}`); - } } await main(); - name: Upload sanitized agent output diff --git a/.gitignore b/.gitignore index 3a7d21ee96b..3e02f312900 100644 --- a/.gitignore +++ b/.gitignore @@ -56,5 +56,5 @@ gh-aw-test/ pkg/cli/workflows/*.yml -# Workflow imports (local cache and lock file) -.aw/ +# Workflow imports (cached files only, not the lock file) +.aw/imports/ diff --git a/docs/src/content/docs/reference/imports.md b/docs/src/content/docs/reference/imports.md index a81ca48b78d..ca7282b24a9 100644 --- a/docs/src/content/docs/reference/imports.md +++ b/docs/src/content/docs/reference/imports.md @@ -136,14 +136,14 @@ Result: GitHub tools will have both sets of allowed functions. ## Version Control -Add `.aw/` to `.gitignore` to exclude cached imports: +Add `.aw/imports/` to `.gitignore` to exclude cached imported files while keeping the lock file: ```gitignore -# Workflow imports (local cache and lock file) -.aw/ +# Workflow imports (cached files only, not the lock file) +.aw/imports/ ``` -The lock file ensures reproducible builds by pinning exact commit SHAs, similar to `go.sum` or `package-lock.json`. +The lock file (`.aw/imports.lock`) should be committed to version control to ensure reproducible builds by pinning exact commit SHAs, similar to `go.sum` or `package-lock.json`. ## Best Practices From d924b1bd73b926a3647b26b26b10d5d9e424bd93 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Thu, 2 Oct 2025 14:12:38 +0000 Subject: [PATCH 7/7] feat: auto-generate .gitignore in .aw directory - Install command now creates .aw/.gitignore automatically - This ensures imports/ folder is ignored even without root .gitignore - Prevents accidental commits of cached imported files - Updates documentation to reflect this automatic behavior Co-authored-by: pelikhan <4175913+pelikhan@users.noreply.github.com> --- .github/workflows/artifacts-summary.lock.yml | 1696 ++++++++--------- .github/workflows/ci-doctor.lock.yml | 1710 +++++++++--------- .github/workflows/dev.lock.yml | 1696 ++++++++--------- .github/workflows/tidy.lock.yml | 1418 +++++++-------- docs/src/content/docs/reference/imports.md | 5 +- pkg/cli/install_imports.go | 36 + 6 files changed, 3303 insertions(+), 3258 deletions(-) diff --git a/.github/workflows/artifacts-summary.lock.yml b/.github/workflows/artifacts-summary.lock.yml index e3b0b4fb28e..fd431c3c459 100644 --- a/.github/workflows/artifacts-summary.lock.yml +++ b/.github/workflows/artifacts-summary.lock.yml @@ -962,742 +962,742 @@ jobs: with: script: | async function main() { - const fs = require("fs"); - function sanitizeContent(content) { - if (!content || typeof content !== "string") { - return ""; - } - const allowedDomainsEnv = process.env.GITHUB_AW_ALLOWED_DOMAINS; - const defaultAllowedDomains = ["github.com", "github.io", "githubusercontent.com", "githubassets.com", "github.dev", "codespaces.new"]; - const allowedDomains = allowedDomainsEnv - ? allowedDomainsEnv - .split(",") - .map(d => d.trim()) - .filter(d => d) - : defaultAllowedDomains; - let sanitized = content; - sanitized = neutralizeMentions(sanitized); - sanitized = removeXmlComments(sanitized); - sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); - sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); - sanitized = sanitizeUrlProtocols(sanitized); - sanitized = sanitizeUrlDomains(sanitized); - const maxLength = 524288; - if (sanitized.length > maxLength) { - sanitized = sanitized.substring(0, maxLength) + "\n[Content truncated due to length]"; - } - const lines = sanitized.split("\n"); - const maxLines = 65000; - if (lines.length > maxLines) { - sanitized = lines.slice(0, maxLines).join("\n") + "\n[Content truncated due to line count]"; - } - sanitized = neutralizeBotTriggers(sanitized); - return sanitized.trim(); - function sanitizeUrlDomains(s) { - return s.replace(/\bhttps:\/\/[^\s\])}'"<>&\x00-\x1f,;]+/gi, match => { - const urlAfterProtocol = match.slice(8); - const hostname = urlAfterProtocol.split(/[\/:\?#]/)[0].toLowerCase(); - const isAllowed = allowedDomains.some(allowedDomain => { - const normalizedAllowed = allowedDomain.toLowerCase(); - return hostname === normalizedAllowed || hostname.endsWith("." + normalizedAllowed); - }); - return isAllowed ? match : "(redacted)"; - }); - } - function sanitizeUrlProtocols(s) { - return s.replace(/\b(\w+):\/\/[^\s\])}'"<>&\x00-\x1f]+/gi, (match, protocol) => { - return protocol.toLowerCase() === "https" ? match : "(redacted)"; - }); - } - function neutralizeMentions(s) { - return s.replace(/(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, (_m, p1, p2) => `${p1}\`@${p2}\``); - } - function removeXmlComments(s) { - return s.replace(//g, "").replace(//g, ""); - } - function neutralizeBotTriggers(s) { - return s.replace(/\b(fixes?|closes?|resolves?|fix|close|resolve)\s+#(\w+)/gi, (match, action, ref) => `\`${action} #${ref}\``); - } + const fs = require("fs"); + function sanitizeContent(content) { + if (!content || typeof content !== "string") { + return ""; } - function getMaxAllowedForType(itemType, config) { - const itemConfig = config?.[itemType]; - if (itemConfig && typeof itemConfig === "object" && "max" in itemConfig && itemConfig.max) { - return itemConfig.max; - } - switch (itemType) { - case "create-issue": - return 1; - case "add-comment": - return 1; - case "create-pull-request": - return 1; - case "create-pull-request-review-comment": - return 1; - case "add-labels": - return 5; - case "update-issue": - return 1; - case "push-to-pull-request-branch": - return 1; - case "create-discussion": - return 1; - case "missing-tool": - return 1000; - case "create-code-scanning-alert": - return 1000; - case "upload-asset": - return 10; - default: - return 1; - } + const allowedDomainsEnv = process.env.GITHUB_AW_ALLOWED_DOMAINS; + const defaultAllowedDomains = ["github.com", "github.io", "githubusercontent.com", "githubassets.com", "github.dev", "codespaces.new"]; + const allowedDomains = allowedDomainsEnv + ? allowedDomainsEnv + .split(",") + .map(d => d.trim()) + .filter(d => d) + : defaultAllowedDomains; + let sanitized = content; + sanitized = neutralizeMentions(sanitized); + sanitized = removeXmlComments(sanitized); + sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); + sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); + sanitized = sanitizeUrlProtocols(sanitized); + sanitized = sanitizeUrlDomains(sanitized); + const maxLength = 524288; + if (sanitized.length > maxLength) { + sanitized = sanitized.substring(0, maxLength) + "\n[Content truncated due to length]"; } - function getMinRequiredForType(itemType, config) { - const itemConfig = config?.[itemType]; - if (itemConfig && typeof itemConfig === "object" && "min" in itemConfig && itemConfig.min) { - return itemConfig.min; - } - return 0; + const lines = sanitized.split("\n"); + const maxLines = 65000; + if (lines.length > maxLines) { + sanitized = lines.slice(0, maxLines).join("\n") + "\n[Content truncated due to line count]"; } - function repairJson(jsonStr) { - let repaired = jsonStr.trim(); - const _ctrl = { 8: "\\b", 9: "\\t", 10: "\\n", 12: "\\f", 13: "\\r" }; - repaired = repaired.replace(/[\u0000-\u001F]/g, ch => { - const c = ch.charCodeAt(0); - return _ctrl[c] || "\\u" + c.toString(16).padStart(4, "0"); - }); - repaired = repaired.replace(/'/g, '"'); - repaired = repaired.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/g, '$1"$2":'); - repaired = repaired.replace(/"([^"\\]*)"/g, (match, content) => { - if (content.includes("\n") || content.includes("\r") || content.includes("\t")) { - const escaped = content.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"); - return `"${escaped}"`; - } - return match; + sanitized = neutralizeBotTriggers(sanitized); + return sanitized.trim(); + function sanitizeUrlDomains(s) { + return s.replace(/\bhttps:\/\/[^\s\])}'"<>&\x00-\x1f,;]+/gi, match => { + const urlAfterProtocol = match.slice(8); + const hostname = urlAfterProtocol.split(/[\/:\?#]/)[0].toLowerCase(); + const isAllowed = allowedDomains.some(allowedDomain => { + const normalizedAllowed = allowedDomain.toLowerCase(); + return hostname === normalizedAllowed || hostname.endsWith("." + normalizedAllowed); }); - repaired = repaired.replace(/"([^"]*)"([^":,}\]]*)"([^"]*)"(\s*[,:}\]])/g, (match, p1, p2, p3, p4) => `"${p1}\\"${p2}\\"${p3}"${p4}`); - repaired = repaired.replace(/(\[\s*(?:"[^"]*"(?:\s*,\s*"[^"]*")*\s*),?)\s*}/g, "$1]"); - const openBraces = (repaired.match(/\{/g) || []).length; - const closeBraces = (repaired.match(/\}/g) || []).length; - if (openBraces > closeBraces) { - repaired += "}".repeat(openBraces - closeBraces); - } - else if (closeBraces > openBraces) { - repaired = "{".repeat(closeBraces - openBraces) + repaired; - } - const openBrackets = (repaired.match(/\[/g) || []).length; - const closeBrackets = (repaired.match(/\]/g) || []).length; - if (openBrackets > closeBrackets) { - repaired += "]".repeat(openBrackets - closeBrackets); - } - else if (closeBrackets > openBrackets) { - repaired = "[".repeat(closeBrackets - openBrackets) + repaired; - } - repaired = repaired.replace(/,(\s*[}\]])/g, "$1"); - return repaired; + return isAllowed ? match : "(redacted)"; + }); } - function validatePositiveInteger(value, fieldName, lineNum) { - if (value === undefined || value === null) { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} is required`, - }; - } - if (typeof value !== "number" && typeof value !== "string") { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number or string field`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; - } - const parsed = typeof value === "string" ? parseInt(value, 10) : value; - if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'line' must be a valid positive integer (got: ${value})`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'line' must be a positive integer`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, - }; - } - return { isValid: true, normalizedValue: parsed }; + function sanitizeUrlProtocols(s) { + return s.replace(/\b(\w+):\/\/[^\s\])}'"<>&\x00-\x1f]+/gi, (match, protocol) => { + return protocol.toLowerCase() === "https" ? match : "(redacted)"; + }); } - function validateOptionalPositiveInteger(value, fieldName, lineNum) { - if (value === undefined) { - return { isValid: true }; - } - if (typeof value !== "number" && typeof value !== "string") { - if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a number or string`, - }; - } - if (fieldName.includes("create-code-scanning-alert 'column'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a number or string`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; - } - const parsed = typeof value === "string" ? parseInt(value, 10) : value; - if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { - if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a positive integer`, - }; - } - if (fieldName.includes("create-code-scanning-alert 'column'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a valid positive integer (got: ${value})`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, - }; - } - return { isValid: true, normalizedValue: parsed }; + function neutralizeMentions(s) { + return s.replace( + /(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, + (_m, p1, p2) => `${p1}\`@${p2}\`` + ); } - function validateIssueOrPRNumber(value, fieldName, lineNum) { - if (value === undefined) { - return { isValid: true }; - } - if (typeof value !== "number" && typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; - } - return { isValid: true }; + function removeXmlComments(s) { + return s.replace(//g, "").replace(//g, ""); } - function validateFieldWithInputSchema(value, fieldName, inputSchema, lineNum) { - if (inputSchema.required && (value === undefined || value === null)) { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} is required`, - }; - } - if (value === undefined || value === null) { - return { - isValid: true, - normalizedValue: inputSchema.default || undefined, - }; - } - const inputType = inputSchema.type || "string"; - let normalizedValue = value; - switch (inputType) { - case "string": - if (typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a string`, - }; - } - normalizedValue = sanitizeContent(value); - break; - case "boolean": - if (typeof value !== "boolean") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a boolean`, - }; - } - break; - case "number": - if (typeof value !== "number") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number`, - }; - } - break; - case "choice": - if (typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a string for choice type`, - }; - } - if (inputSchema.options && !inputSchema.options.includes(value)) { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be one of: ${inputSchema.options.join(", ")}`, - }; - } - normalizedValue = sanitizeContent(value); - break; - default: - if (typeof value === "string") { - normalizedValue = sanitizeContent(value); - } - break; - } + function neutralizeBotTriggers(s) { + return s.replace(/\b(fixes?|closes?|resolves?|fix|close|resolve)\s+#(\w+)/gi, (match, action, ref) => `\`${action} #${ref}\``); + } + } + function getMaxAllowedForType(itemType, config) { + const itemConfig = config?.[itemType]; + if (itemConfig && typeof itemConfig === "object" && "max" in itemConfig && itemConfig.max) { + return itemConfig.max; + } + switch (itemType) { + case "create-issue": + return 1; + case "add-comment": + return 1; + case "create-pull-request": + return 1; + case "create-pull-request-review-comment": + return 1; + case "add-labels": + return 5; + case "update-issue": + return 1; + case "push-to-pull-request-branch": + return 1; + case "create-discussion": + return 1; + case "missing-tool": + return 1000; + case "create-code-scanning-alert": + return 1000; + case "upload-asset": + return 10; + default: + return 1; + } + } + function getMinRequiredForType(itemType, config) { + const itemConfig = config?.[itemType]; + if (itemConfig && typeof itemConfig === "object" && "min" in itemConfig && itemConfig.min) { + return itemConfig.min; + } + return 0; + } + function repairJson(jsonStr) { + let repaired = jsonStr.trim(); + const _ctrl = { 8: "\\b", 9: "\\t", 10: "\\n", 12: "\\f", 13: "\\r" }; + repaired = repaired.replace(/[\u0000-\u001F]/g, ch => { + const c = ch.charCodeAt(0); + return _ctrl[c] || "\\u" + c.toString(16).padStart(4, "0"); + }); + repaired = repaired.replace(/'/g, '"'); + repaired = repaired.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/g, '$1"$2":'); + repaired = repaired.replace(/"([^"\\]*)"/g, (match, content) => { + if (content.includes("\n") || content.includes("\r") || content.includes("\t")) { + const escaped = content.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"); + return `"${escaped}"`; + } + return match; + }); + repaired = repaired.replace(/"([^"]*)"([^":,}\]]*)"([^"]*)"(\s*[,:}\]])/g, (match, p1, p2, p3, p4) => `"${p1}\\"${p2}\\"${p3}"${p4}`); + repaired = repaired.replace(/(\[\s*(?:"[^"]*"(?:\s*,\s*"[^"]*")*\s*),?)\s*}/g, "$1]"); + const openBraces = (repaired.match(/\{/g) || []).length; + const closeBraces = (repaired.match(/\}/g) || []).length; + if (openBraces > closeBraces) { + repaired += "}".repeat(openBraces - closeBraces); + } else if (closeBraces > openBraces) { + repaired = "{".repeat(closeBraces - openBraces) + repaired; + } + const openBrackets = (repaired.match(/\[/g) || []).length; + const closeBrackets = (repaired.match(/\]/g) || []).length; + if (openBrackets > closeBrackets) { + repaired += "]".repeat(openBrackets - closeBrackets); + } else if (closeBrackets > openBrackets) { + repaired = "[".repeat(closeBrackets - openBrackets) + repaired; + } + repaired = repaired.replace(/,(\s*[}\]])/g, "$1"); + return repaired; + } + function validatePositiveInteger(value, fieldName, lineNum) { + if (value === undefined || value === null) { + if (fieldName.includes("create-code-scanning-alert 'line'")) { return { - isValid: true, - normalizedValue, + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} is required`, + }; } - function validateItemWithSafeJobConfig(item, jobConfig, lineNum) { - const errors = []; - const normalizedItem = { ...item }; - if (!jobConfig.inputs) { - return { - isValid: true, - errors: [], - normalizedItem: item, - }; - } - for (const [fieldName, inputSchema] of Object.entries(jobConfig.inputs)) { - const fieldValue = item[fieldName]; - const validation = validateFieldWithInputSchema(fieldValue, fieldName, inputSchema, lineNum); - if (!validation.isValid && validation.error) { - errors.push(validation.error); - } - else if (validation.normalizedValue !== undefined) { - normalizedItem[fieldName] = validation.normalizedValue; - } - } + if (typeof value !== "number" && typeof value !== "string") { + if (fieldName.includes("create-code-scanning-alert 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, + }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { return { - isValid: errors.length === 0, - errors, - normalizedItem, + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number or string field`, }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; } - function parseJsonWithRepair(jsonStr) { - try { - return JSON.parse(jsonStr); - } - catch (originalError) { - try { - const repairedJson = repairJson(jsonStr); - return JSON.parse(repairedJson); - } - catch (repairError) { - core.info(`invalid input json: ${jsonStr}`); - const originalMsg = originalError instanceof Error ? originalError.message : String(originalError); - const repairMsg = repairError instanceof Error ? repairError.message : String(repairError); - throw new Error(`JSON parsing failed. Original: ${originalMsg}. After attempted repair: ${repairMsg}`); - } - } + const parsed = typeof value === "string" ? parseInt(value, 10) : value; + if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { + if (fieldName.includes("create-code-scanning-alert 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'line' must be a valid positive integer (got: ${value})`, + }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'line' must be a positive integer`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, + }; } - const outputFile = process.env.GITHUB_AW_SAFE_OUTPUTS; - const safeOutputsConfig = process.env.GITHUB_AW_SAFE_OUTPUTS_CONFIG; - if (!outputFile) { - core.info("GITHUB_AW_SAFE_OUTPUTS not set, no output to collect"); - core.setOutput("output", ""); - return; + return { isValid: true, normalizedValue: parsed }; + } + function validateOptionalPositiveInteger(value, fieldName, lineNum) { + if (value === undefined) { + return { isValid: true }; } - if (!fs.existsSync(outputFile)) { - core.info(`Output file does not exist: ${outputFile}`); - core.setOutput("output", ""); - return; + if (typeof value !== "number" && typeof value !== "string") { + if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a number or string`, + }; + } + if (fieldName.includes("create-code-scanning-alert 'column'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a number or string`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; } - const outputContent = fs.readFileSync(outputFile, "utf8"); - if (outputContent.trim() === "") { - core.info("Output file is empty"); + const parsed = typeof value === "string" ? parseInt(value, 10) : value; + if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { + if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a positive integer`, + }; + } + if (fieldName.includes("create-code-scanning-alert 'column'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a valid positive integer (got: ${value})`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, + }; } - core.info(`Raw output content length: ${outputContent.length}`); - let expectedOutputTypes = {}; - if (safeOutputsConfig) { - try { - expectedOutputTypes = JSON.parse(safeOutputsConfig); - core.info(`Expected output types: ${JSON.stringify(Object.keys(expectedOutputTypes))}`); + return { isValid: true, normalizedValue: parsed }; + } + function validateIssueOrPRNumber(value, fieldName, lineNum) { + if (value === undefined) { + return { isValid: true }; + } + if (typeof value !== "number" && typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; + } + return { isValid: true }; + } + function validateFieldWithInputSchema(value, fieldName, inputSchema, lineNum) { + if (inputSchema.required && (value === undefined || value === null)) { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} is required`, + }; + } + if (value === undefined || value === null) { + return { + isValid: true, + normalizedValue: inputSchema.default || undefined, + }; + } + const inputType = inputSchema.type || "string"; + let normalizedValue = value; + switch (inputType) { + case "string": + if (typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a string`, + }; } - catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.info(`Warning: Could not parse safe-outputs config: ${errorMsg}`); + normalizedValue = sanitizeContent(value); + break; + case "boolean": + if (typeof value !== "boolean") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a boolean`, + }; } - } - const lines = outputContent.trim().split("\n"); - const parsedItems = []; - const errors = []; - for (let i = 0; i < lines.length; i++) { - const line = lines[i].trim(); - if (line === "") - continue; - try { - const item = parseJsonWithRepair(line); - if (item === undefined) { - errors.push(`Line ${i + 1}: Invalid JSON - JSON parsing failed`); - continue; - } - if (!item.type) { - errors.push(`Line ${i + 1}: Missing required 'type' field`); - continue; - } - const itemType = item.type; - if (!expectedOutputTypes[itemType]) { - errors.push(`Line ${i + 1}: Unexpected output type '${itemType}'. Expected one of: ${Object.keys(expectedOutputTypes).join(", ")}`); - continue; - } - const typeCount = parsedItems.filter(existing => existing.type === itemType).length; - const maxAllowed = getMaxAllowedForType(itemType, expectedOutputTypes); - if (typeCount >= maxAllowed) { - errors.push(`Line ${i + 1}: Too many items of type '${itemType}'. Maximum allowed: ${maxAllowed}.`); - continue; - } - core.info(`Line ${i + 1}: type '${itemType}'`); - switch (itemType) { - case "create-issue": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_issue requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_issue requires a 'body' string field`); - continue; - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - if (item.labels && Array.isArray(item.labels)) { - item.labels = item.labels.map((label) => (typeof label === "string" ? sanitizeContent(label) : label)); - } - break; - case "add-comment": - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: add_comment requires a 'body' string field`); - continue; - } - const issueNumValidation = validateIssueOrPRNumber(item.issue_number, "add_comment 'issue_number'", i + 1); - if (!issueNumValidation.isValid) { - if (issueNumValidation.error) - errors.push(issueNumValidation.error); - continue; - } - item.body = sanitizeContent(item.body); - break; - case "create-pull-request": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'body' string field`); - continue; - } - if (!item.branch || typeof item.branch !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'branch' string field`); - continue; - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - item.branch = sanitizeContent(item.branch); - if (item.labels && Array.isArray(item.labels)) { - item.labels = item.labels.map((label) => (typeof label === "string" ? sanitizeContent(label) : label)); - } - break; - case "add-labels": - if (!item.labels || !Array.isArray(item.labels)) { - errors.push(`Line ${i + 1}: add_labels requires a 'labels' array field`); - continue; - } - if (item.labels.some((label) => typeof label !== "string")) { - errors.push(`Line ${i + 1}: add_labels labels array must contain only strings`); - continue; - } - const labelsIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "add-labels 'issue_number'", i + 1); - if (!labelsIssueNumValidation.isValid) { - if (labelsIssueNumValidation.error) - errors.push(labelsIssueNumValidation.error); - continue; - } - item.labels = item.labels.map((label) => sanitizeContent(label)); - break; - case "update-issue": - const hasValidField = item.status !== undefined || item.title !== undefined || item.body !== undefined; - if (!hasValidField) { - errors.push(`Line ${i + 1}: update_issue requires at least one of: 'status', 'title', or 'body' fields`); - continue; - } - if (item.status !== undefined) { - if (typeof item.status !== "string" || (item.status !== "open" && item.status !== "closed")) { - errors.push(`Line ${i + 1}: update_issue 'status' must be 'open' or 'closed'`); - continue; - } - } - if (item.title !== undefined) { - if (typeof item.title !== "string") { - errors.push(`Line ${i + 1}: update-issue 'title' must be a string`); - continue; - } - item.title = sanitizeContent(item.title); - } - if (item.body !== undefined) { - if (typeof item.body !== "string") { - errors.push(`Line ${i + 1}: update-issue 'body' must be a string`); - continue; - } - item.body = sanitizeContent(item.body); - } - const updateIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "update-issue 'issue_number'", i + 1); - if (!updateIssueNumValidation.isValid) { - if (updateIssueNumValidation.error) - errors.push(updateIssueNumValidation.error); - continue; - } - break; - case "push-to-pull-request-branch": - if (!item.branch || typeof item.branch !== "string") { - errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'branch' string field`); - continue; - } - if (!item.message || typeof item.message !== "string") { - errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'message' string field`); - continue; - } - item.branch = sanitizeContent(item.branch); - item.message = sanitizeContent(item.message); - const pushPRNumValidation = validateIssueOrPRNumber(item.pull_request_number, "push-to-pull-request-branch 'pull_request_number'", i + 1); - if (!pushPRNumValidation.isValid) { - if (pushPRNumValidation.error) - errors.push(pushPRNumValidation.error); - continue; - } - break; - case "create-pull-request-review-comment": - if (!item.path || typeof item.path !== "string") { - errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'path' string field`); - continue; - } - const lineValidation = validatePositiveInteger(item.line, "create-pull-request-review-comment 'line'", i + 1); - if (!lineValidation.isValid) { - if (lineValidation.error) - errors.push(lineValidation.error); - continue; - } - const lineNumber = lineValidation.normalizedValue; - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'body' string field`); - continue; - } - item.body = sanitizeContent(item.body); - const startLineValidation = validateOptionalPositiveInteger(item.start_line, "create-pull-request-review-comment 'start_line'", i + 1); - if (!startLineValidation.isValid) { - if (startLineValidation.error) - errors.push(startLineValidation.error); - continue; - } - if (startLineValidation.normalizedValue !== undefined && - lineNumber !== undefined && - startLineValidation.normalizedValue > lineNumber) { - errors.push(`Line ${i + 1}: create-pull-request-review-comment 'start_line' must be less than or equal to 'line'`); - continue; - } - if (item.side !== undefined) { - if (typeof item.side !== "string" || (item.side !== "LEFT" && item.side !== "RIGHT")) { - errors.push(`Line ${i + 1}: create-pull-request-review-comment 'side' must be 'LEFT' or 'RIGHT'`); - continue; - } - } - break; - case "create-discussion": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_discussion requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_discussion requires a 'body' string field`); - continue; - } - if (item.category !== undefined) { - if (typeof item.category !== "string") { - errors.push(`Line ${i + 1}: create_discussion 'category' must be a string`); - continue; - } - item.category = sanitizeContent(item.category); - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - break; - case "missing-tool": - if (!item.tool || typeof item.tool !== "string") { - errors.push(`Line ${i + 1}: missing_tool requires a 'tool' string field`); - continue; - } - if (!item.reason || typeof item.reason !== "string") { - errors.push(`Line ${i + 1}: missing_tool requires a 'reason' string field`); - continue; - } - item.tool = sanitizeContent(item.tool); - item.reason = sanitizeContent(item.reason); - if (item.alternatives !== undefined) { - if (typeof item.alternatives !== "string") { - errors.push(`Line ${i + 1}: missing-tool 'alternatives' must be a string`); - continue; - } - item.alternatives = sanitizeContent(item.alternatives); - } - break; - case "upload-asset": - if (!item.path || typeof item.path !== "string") { - errors.push(`Line ${i + 1}: upload_asset requires a 'path' string field`); - continue; - } - break; - case "create-code-scanning-alert": - if (!item.file || typeof item.file !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'file' field (string)`); - continue; - } - const alertLineValidation = validatePositiveInteger(item.line, "create-code-scanning-alert 'line'", i + 1); - if (!alertLineValidation.isValid) { - if (alertLineValidation.error) { - errors.push(alertLineValidation.error); - } - continue; - } - if (!item.severity || typeof item.severity !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'severity' field (string)`); - continue; - } - if (!item.message || typeof item.message !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'message' field (string)`); - continue; - } - const allowedSeverities = ["error", "warning", "info", "note"]; - if (!allowedSeverities.includes(item.severity.toLowerCase())) { - errors.push(`Line ${i + 1}: create-code-scanning-alert 'severity' must be one of: ${allowedSeverities.join(", ")}, got ${item.severity.toLowerCase()}`); - continue; - } - const columnValidation = validateOptionalPositiveInteger(item.column, "create-code-scanning-alert 'column'", i + 1); - if (!columnValidation.isValid) { - if (columnValidation.error) - errors.push(columnValidation.error); - continue; - } - if (item.ruleIdSuffix !== undefined) { - if (typeof item.ruleIdSuffix !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must be a string`); - continue; - } - if (!/^[a-zA-Z0-9_-]+$/.test(item.ruleIdSuffix.trim())) { - errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must contain only alphanumeric characters, hyphens, and underscores`); - continue; - } - } - item.severity = item.severity.toLowerCase(); - item.file = sanitizeContent(item.file); - item.severity = sanitizeContent(item.severity); - item.message = sanitizeContent(item.message); - if (item.ruleIdSuffix) { - item.ruleIdSuffix = sanitizeContent(item.ruleIdSuffix); - } - break; - default: - const jobOutputType = expectedOutputTypes[itemType]; - if (!jobOutputType) { - errors.push(`Line ${i + 1}: Unknown output type '${itemType}'`); - continue; - } - const safeJobConfig = jobOutputType; - if (safeJobConfig && safeJobConfig.inputs) { - const validation = validateItemWithSafeJobConfig(item, safeJobConfig, i + 1); - if (!validation.isValid) { - errors.push(...validation.errors); - continue; - } - Object.assign(item, validation.normalizedItem); - } - break; - } - core.info(`Line ${i + 1}: Valid ${itemType} item`); - parsedItems.push(item); + break; + case "number": + if (typeof value !== "number") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number`, + }; } - catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - errors.push(`Line ${i + 1}: Invalid JSON - ${errorMsg}`); + break; + case "choice": + if (typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a string for choice type`, + }; } - } - if (errors.length > 0) { - core.warning("Validation errors found:"); - errors.forEach(error => core.warning(` - ${error}`)); - if (parsedItems.length === 0) { - core.setFailed(errors.map(e => ` - ${e}`).join("\n")); - return; + if (inputSchema.options && !inputSchema.options.includes(value)) { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be one of: ${inputSchema.options.join(", ")}`, + }; } - } - for (const itemType of Object.keys(expectedOutputTypes)) { - const minRequired = getMinRequiredForType(itemType, expectedOutputTypes); - if (minRequired > 0) { - const actualCount = parsedItems.filter(item => item.type === itemType).length; - if (actualCount < minRequired) { - errors.push(`Too few items of type '${itemType}'. Minimum required: ${minRequired}, found: ${actualCount}.`); - } + normalizedValue = sanitizeContent(value); + break; + default: + if (typeof value === "string") { + normalizedValue = sanitizeContent(value); } + break; } - core.info(`Successfully parsed ${parsedItems.length} valid output items`); - const validatedOutput = { - items: parsedItems, - errors: errors, + return { + isValid: true, + normalizedValue, }; - const agentOutputFile = "/tmp/agent_output.json"; - const validatedOutputJson = JSON.stringify(validatedOutput); + } + function validateItemWithSafeJobConfig(item, jobConfig, lineNum) { + const errors = []; + const normalizedItem = { ...item }; + if (!jobConfig.inputs) { + return { + isValid: true, + errors: [], + normalizedItem: item, + }; + } + for (const [fieldName, inputSchema] of Object.entries(jobConfig.inputs)) { + const fieldValue = item[fieldName]; + const validation = validateFieldWithInputSchema(fieldValue, fieldName, inputSchema, lineNum); + if (!validation.isValid && validation.error) { + errors.push(validation.error); + } else if (validation.normalizedValue !== undefined) { + normalizedItem[fieldName] = validation.normalizedValue; + } + } + return { + isValid: errors.length === 0, + errors, + normalizedItem, + }; + } + function parseJsonWithRepair(jsonStr) { try { - fs.mkdirSync("/tmp", { recursive: true }); - fs.writeFileSync(agentOutputFile, validatedOutputJson, "utf8"); - core.info(`Stored validated output to: ${agentOutputFile}`); - core.exportVariable("GITHUB_AW_AGENT_OUTPUT", agentOutputFile); + return JSON.parse(jsonStr); + } catch (originalError) { + try { + const repairedJson = repairJson(jsonStr); + return JSON.parse(repairedJson); + } catch (repairError) { + core.info(`invalid input json: ${jsonStr}`); + const originalMsg = originalError instanceof Error ? originalError.message : String(originalError); + const repairMsg = repairError instanceof Error ? repairError.message : String(repairError); + throw new Error(`JSON parsing failed. Original: ${originalMsg}. After attempted repair: ${repairMsg}`); + } } - catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.error(`Failed to write agent output file: ${errorMsg}`); + } + const outputFile = process.env.GITHUB_AW_SAFE_OUTPUTS; + const safeOutputsConfig = process.env.GITHUB_AW_SAFE_OUTPUTS_CONFIG; + if (!outputFile) { + core.info("GITHUB_AW_SAFE_OUTPUTS not set, no output to collect"); + core.setOutput("output", ""); + return; + } + if (!fs.existsSync(outputFile)) { + core.info(`Output file does not exist: ${outputFile}`); + core.setOutput("output", ""); + return; + } + const outputContent = fs.readFileSync(outputFile, "utf8"); + if (outputContent.trim() === "") { + core.info("Output file is empty"); + } + core.info(`Raw output content length: ${outputContent.length}`); + let expectedOutputTypes = {}; + if (safeOutputsConfig) { + try { + expectedOutputTypes = JSON.parse(safeOutputsConfig); + core.info(`Expected output types: ${JSON.stringify(Object.keys(expectedOutputTypes))}`); + } catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.info(`Warning: Could not parse safe-outputs config: ${errorMsg}`); } - core.setOutput("output", JSON.stringify(validatedOutput)); - core.setOutput("raw_output", outputContent); - const outputTypes = Array.from(new Set(parsedItems.map(item => item.type))); - core.info(`output_types: ${outputTypes.join(", ")}`); - core.setOutput("output_types", outputTypes.join(",")); + } + const lines = outputContent.trim().split("\n"); + const parsedItems = []; + const errors = []; + for (let i = 0; i < lines.length; i++) { + const line = lines[i].trim(); + if (line === "") continue; try { - await core.summary - .addRaw("## Processed Output\n\n") - .addRaw("```json\n") - .addRaw(JSON.stringify(validatedOutput)) - .addRaw("\n```\n") - .write(); - core.info("Successfully wrote processed output to step summary"); + const item = parseJsonWithRepair(line); + if (item === undefined) { + errors.push(`Line ${i + 1}: Invalid JSON - JSON parsing failed`); + continue; + } + if (!item.type) { + errors.push(`Line ${i + 1}: Missing required 'type' field`); + continue; + } + const itemType = item.type; + if (!expectedOutputTypes[itemType]) { + errors.push(`Line ${i + 1}: Unexpected output type '${itemType}'. Expected one of: ${Object.keys(expectedOutputTypes).join(", ")}`); + continue; + } + const typeCount = parsedItems.filter(existing => existing.type === itemType).length; + const maxAllowed = getMaxAllowedForType(itemType, expectedOutputTypes); + if (typeCount >= maxAllowed) { + errors.push(`Line ${i + 1}: Too many items of type '${itemType}'. Maximum allowed: ${maxAllowed}.`); + continue; + } + core.info(`Line ${i + 1}: type '${itemType}'`); + switch (itemType) { + case "create-issue": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_issue requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_issue requires a 'body' string field`); + continue; + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + if (item.labels && Array.isArray(item.labels)) { + item.labels = item.labels.map(label => (typeof label === "string" ? sanitizeContent(label) : label)); + } + break; + case "add-comment": + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: add_comment requires a 'body' string field`); + continue; + } + const issueNumValidation = validateIssueOrPRNumber(item.issue_number, "add_comment 'issue_number'", i + 1); + if (!issueNumValidation.isValid) { + if (issueNumValidation.error) errors.push(issueNumValidation.error); + continue; + } + item.body = sanitizeContent(item.body); + break; + case "create-pull-request": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'body' string field`); + continue; + } + if (!item.branch || typeof item.branch !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'branch' string field`); + continue; + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + item.branch = sanitizeContent(item.branch); + if (item.labels && Array.isArray(item.labels)) { + item.labels = item.labels.map(label => (typeof label === "string" ? sanitizeContent(label) : label)); + } + break; + case "add-labels": + if (!item.labels || !Array.isArray(item.labels)) { + errors.push(`Line ${i + 1}: add_labels requires a 'labels' array field`); + continue; + } + if (item.labels.some(label => typeof label !== "string")) { + errors.push(`Line ${i + 1}: add_labels labels array must contain only strings`); + continue; + } + const labelsIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "add-labels 'issue_number'", i + 1); + if (!labelsIssueNumValidation.isValid) { + if (labelsIssueNumValidation.error) errors.push(labelsIssueNumValidation.error); + continue; + } + item.labels = item.labels.map(label => sanitizeContent(label)); + break; + case "update-issue": + const hasValidField = item.status !== undefined || item.title !== undefined || item.body !== undefined; + if (!hasValidField) { + errors.push(`Line ${i + 1}: update_issue requires at least one of: 'status', 'title', or 'body' fields`); + continue; + } + if (item.status !== undefined) { + if (typeof item.status !== "string" || (item.status !== "open" && item.status !== "closed")) { + errors.push(`Line ${i + 1}: update_issue 'status' must be 'open' or 'closed'`); + continue; + } + } + if (item.title !== undefined) { + if (typeof item.title !== "string") { + errors.push(`Line ${i + 1}: update-issue 'title' must be a string`); + continue; + } + item.title = sanitizeContent(item.title); + } + if (item.body !== undefined) { + if (typeof item.body !== "string") { + errors.push(`Line ${i + 1}: update-issue 'body' must be a string`); + continue; + } + item.body = sanitizeContent(item.body); + } + const updateIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "update-issue 'issue_number'", i + 1); + if (!updateIssueNumValidation.isValid) { + if (updateIssueNumValidation.error) errors.push(updateIssueNumValidation.error); + continue; + } + break; + case "push-to-pull-request-branch": + if (!item.branch || typeof item.branch !== "string") { + errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'branch' string field`); + continue; + } + if (!item.message || typeof item.message !== "string") { + errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'message' string field`); + continue; + } + item.branch = sanitizeContent(item.branch); + item.message = sanitizeContent(item.message); + const pushPRNumValidation = validateIssueOrPRNumber( + item.pull_request_number, + "push-to-pull-request-branch 'pull_request_number'", + i + 1 + ); + if (!pushPRNumValidation.isValid) { + if (pushPRNumValidation.error) errors.push(pushPRNumValidation.error); + continue; + } + break; + case "create-pull-request-review-comment": + if (!item.path || typeof item.path !== "string") { + errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'path' string field`); + continue; + } + const lineValidation = validatePositiveInteger(item.line, "create-pull-request-review-comment 'line'", i + 1); + if (!lineValidation.isValid) { + if (lineValidation.error) errors.push(lineValidation.error); + continue; + } + const lineNumber = lineValidation.normalizedValue; + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'body' string field`); + continue; + } + item.body = sanitizeContent(item.body); + const startLineValidation = validateOptionalPositiveInteger( + item.start_line, + "create-pull-request-review-comment 'start_line'", + i + 1 + ); + if (!startLineValidation.isValid) { + if (startLineValidation.error) errors.push(startLineValidation.error); + continue; + } + if ( + startLineValidation.normalizedValue !== undefined && + lineNumber !== undefined && + startLineValidation.normalizedValue > lineNumber + ) { + errors.push(`Line ${i + 1}: create-pull-request-review-comment 'start_line' must be less than or equal to 'line'`); + continue; + } + if (item.side !== undefined) { + if (typeof item.side !== "string" || (item.side !== "LEFT" && item.side !== "RIGHT")) { + errors.push(`Line ${i + 1}: create-pull-request-review-comment 'side' must be 'LEFT' or 'RIGHT'`); + continue; + } + } + break; + case "create-discussion": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_discussion requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_discussion requires a 'body' string field`); + continue; + } + if (item.category !== undefined) { + if (typeof item.category !== "string") { + errors.push(`Line ${i + 1}: create_discussion 'category' must be a string`); + continue; + } + item.category = sanitizeContent(item.category); + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + break; + case "missing-tool": + if (!item.tool || typeof item.tool !== "string") { + errors.push(`Line ${i + 1}: missing_tool requires a 'tool' string field`); + continue; + } + if (!item.reason || typeof item.reason !== "string") { + errors.push(`Line ${i + 1}: missing_tool requires a 'reason' string field`); + continue; + } + item.tool = sanitizeContent(item.tool); + item.reason = sanitizeContent(item.reason); + if (item.alternatives !== undefined) { + if (typeof item.alternatives !== "string") { + errors.push(`Line ${i + 1}: missing-tool 'alternatives' must be a string`); + continue; + } + item.alternatives = sanitizeContent(item.alternatives); + } + break; + case "upload-asset": + if (!item.path || typeof item.path !== "string") { + errors.push(`Line ${i + 1}: upload_asset requires a 'path' string field`); + continue; + } + break; + case "create-code-scanning-alert": + if (!item.file || typeof item.file !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'file' field (string)`); + continue; + } + const alertLineValidation = validatePositiveInteger(item.line, "create-code-scanning-alert 'line'", i + 1); + if (!alertLineValidation.isValid) { + if (alertLineValidation.error) { + errors.push(alertLineValidation.error); + } + continue; + } + if (!item.severity || typeof item.severity !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'severity' field (string)`); + continue; + } + if (!item.message || typeof item.message !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'message' field (string)`); + continue; + } + const allowedSeverities = ["error", "warning", "info", "note"]; + if (!allowedSeverities.includes(item.severity.toLowerCase())) { + errors.push( + `Line ${i + 1}: create-code-scanning-alert 'severity' must be one of: ${allowedSeverities.join(", ")}, got ${item.severity.toLowerCase()}` + ); + continue; + } + const columnValidation = validateOptionalPositiveInteger(item.column, "create-code-scanning-alert 'column'", i + 1); + if (!columnValidation.isValid) { + if (columnValidation.error) errors.push(columnValidation.error); + continue; + } + if (item.ruleIdSuffix !== undefined) { + if (typeof item.ruleIdSuffix !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must be a string`); + continue; + } + if (!/^[a-zA-Z0-9_-]+$/.test(item.ruleIdSuffix.trim())) { + errors.push( + `Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must contain only alphanumeric characters, hyphens, and underscores` + ); + continue; + } + } + item.severity = item.severity.toLowerCase(); + item.file = sanitizeContent(item.file); + item.severity = sanitizeContent(item.severity); + item.message = sanitizeContent(item.message); + if (item.ruleIdSuffix) { + item.ruleIdSuffix = sanitizeContent(item.ruleIdSuffix); + } + break; + default: + const jobOutputType = expectedOutputTypes[itemType]; + if (!jobOutputType) { + errors.push(`Line ${i + 1}: Unknown output type '${itemType}'`); + continue; + } + const safeJobConfig = jobOutputType; + if (safeJobConfig && safeJobConfig.inputs) { + const validation = validateItemWithSafeJobConfig(item, safeJobConfig, i + 1); + if (!validation.isValid) { + errors.push(...validation.errors); + continue; + } + Object.assign(item, validation.normalizedItem); + } + break; + } + core.info(`Line ${i + 1}: Valid ${itemType} item`); + parsedItems.push(item); + } catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + errors.push(`Line ${i + 1}: Invalid JSON - ${errorMsg}`); } - catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.warning(`Failed to write to step summary: ${errorMsg}`); + } + if (errors.length > 0) { + core.warning("Validation errors found:"); + errors.forEach(error => core.warning(` - ${error}`)); + if (parsedItems.length === 0) { + core.setFailed(errors.map(e => ` - ${e}`).join("\n")); + return; + } + } + for (const itemType of Object.keys(expectedOutputTypes)) { + const minRequired = getMinRequiredForType(itemType, expectedOutputTypes); + if (minRequired > 0) { + const actualCount = parsedItems.filter(item => item.type === itemType).length; + if (actualCount < minRequired) { + errors.push(`Too few items of type '${itemType}'. Minimum required: ${minRequired}, found: ${actualCount}.`); + } } + } + core.info(`Successfully parsed ${parsedItems.length} valid output items`); + const validatedOutput = { + items: parsedItems, + errors: errors, + }; + const agentOutputFile = "/tmp/agent_output.json"; + const validatedOutputJson = JSON.stringify(validatedOutput); + try { + fs.mkdirSync("/tmp", { recursive: true }); + fs.writeFileSync(agentOutputFile, validatedOutputJson, "utf8"); + core.info(`Stored validated output to: ${agentOutputFile}`); + core.exportVariable("GITHUB_AW_AGENT_OUTPUT", agentOutputFile); + } catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.error(`Failed to write agent output file: ${errorMsg}`); + } + core.setOutput("output", JSON.stringify(validatedOutput)); + core.setOutput("raw_output", outputContent); + const outputTypes = Array.from(new Set(parsedItems.map(item => item.type))); + core.info(`output_types: ${outputTypes.join(", ")}`); + core.setOutput("output_types", outputTypes.join(",")); + try { + await core.summary + .addRaw("## Processed Output\n\n") + .addRaw("```json\n") + .addRaw(JSON.stringify(validatedOutput)) + .addRaw("\n```\n") + .write(); + core.info("Successfully wrote processed output to step summary"); + } catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.warning(`Failed to write to step summary: ${errorMsg}`); + } } await main(); - name: Upload sanitized agent output @@ -1972,162 +1972,164 @@ jobs: with: script: | function sanitizeLabelContent(content) { - if (!content || typeof content !== "string") { - return ""; - } - let sanitized = content.trim(); - sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); - sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); - sanitized = sanitized.replace(/(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, (_m, p1, p2) => `${p1}\`@${p2}\``); - sanitized = sanitized.replace(/[<>&'"]/g, ""); - return sanitized.trim(); + if (!content || typeof content !== "string") { + return ""; + } + let sanitized = content.trim(); + sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); + sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); + sanitized = sanitized.replace( + /(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, + (_m, p1, p2) => `${p1}\`@${p2}\`` + ); + sanitized = sanitized.replace(/[<>&'"]/g, ""); + return sanitized.trim(); } async function main() { - const isStaged = process.env.GITHUB_AW_SAFE_OUTPUTS_STAGED === "true"; - const outputContent = process.env.GITHUB_AW_AGENT_OUTPUT; - if (!outputContent) { - core.info("No GITHUB_AW_AGENT_OUTPUT environment variable found"); - return; - } - if (outputContent.trim() === "") { - core.info("Agent output content is empty"); - return; - } - core.info(`Agent output content length: ${outputContent.length}`); - let validatedOutput; - try { - validatedOutput = JSON.parse(outputContent); + const isStaged = process.env.GITHUB_AW_SAFE_OUTPUTS_STAGED === "true"; + const outputContent = process.env.GITHUB_AW_AGENT_OUTPUT; + if (!outputContent) { + core.info("No GITHUB_AW_AGENT_OUTPUT environment variable found"); + return; + } + if (outputContent.trim() === "") { + core.info("Agent output content is empty"); + return; + } + core.info(`Agent output content length: ${outputContent.length}`); + let validatedOutput; + try { + validatedOutput = JSON.parse(outputContent); + } catch (error) { + core.setFailed(`Error parsing agent output JSON: ${error instanceof Error ? error.message : String(error)}`); + return; + } + if (!validatedOutput.items || !Array.isArray(validatedOutput.items)) { + core.info("No valid items found in agent output"); + return; + } + const createIssueItems = validatedOutput.items.filter(item => item.type === "create-issue"); + if (createIssueItems.length === 0) { + core.info("No create-issue items found in agent output"); + return; + } + core.info(`Found ${createIssueItems.length} create-issue item(s)`); + if (isStaged) { + let summaryContent = "## 🎭 Staged Mode: Create Issues Preview\n\n"; + summaryContent += "The following issues would be created if staged mode was disabled:\n\n"; + for (let i = 0; i < createIssueItems.length; i++) { + const item = createIssueItems[i]; + summaryContent += `### Issue ${i + 1}\n`; + summaryContent += `**Title:** ${item.title || "No title provided"}\n\n`; + if (item.body) { + summaryContent += `**Body:**\n${item.body}\n\n`; + } + if (item.labels && item.labels.length > 0) { + summaryContent += `**Labels:** ${item.labels.join(", ")}\n\n`; + } + summaryContent += "---\n\n"; } - catch (error) { - core.setFailed(`Error parsing agent output JSON: ${error instanceof Error ? error.message : String(error)}`); - return; + await core.summary.addRaw(summaryContent).write(); + core.info("📝 Issue creation preview written to step summary"); + return; + } + const parentIssueNumber = context.payload?.issue?.number; + const labelsEnv = process.env.GITHUB_AW_ISSUE_LABELS; + let envLabels = labelsEnv + ? labelsEnv + .split(",") + .map(label => label.trim()) + .filter(label => label) + : []; + const createdIssues = []; + for (let i = 0; i < createIssueItems.length; i++) { + const createIssueItem = createIssueItems[i]; + core.info( + `Processing create-issue item ${i + 1}/${createIssueItems.length}: title=${createIssueItem.title}, bodyLength=${createIssueItem.body.length}` + ); + let labels = [...envLabels]; + if (createIssueItem.labels && Array.isArray(createIssueItem.labels)) { + labels = [...labels, ...createIssueItem.labels]; } - if (!validatedOutput.items || !Array.isArray(validatedOutput.items)) { - core.info("No valid items found in agent output"); - return; + labels = labels + .filter(label => label != null && label !== false && label !== 0) + .map(label => String(label).trim()) + .filter(label => label) + .map(label => sanitizeLabelContent(label)) + .filter(label => label) + .map(label => (label.length > 64 ? label.substring(0, 64) : label)) + .filter((label, index, arr) => arr.indexOf(label) === index); + let title = createIssueItem.title ? createIssueItem.title.trim() : ""; + let bodyLines = createIssueItem.body.split("\n"); + if (!title) { + title = createIssueItem.body || "Agent Output"; } - const createIssueItems = validatedOutput.items.filter(item => item.type === "create-issue"); - if (createIssueItems.length === 0) { - core.info("No create-issue items found in agent output"); - return; + const titlePrefix = process.env.GITHUB_AW_ISSUE_TITLE_PREFIX; + if (titlePrefix && !title.startsWith(titlePrefix)) { + title = titlePrefix + title; } - core.info(`Found ${createIssueItems.length} create-issue item(s)`); - if (isStaged) { - let summaryContent = "## 🎭 Staged Mode: Create Issues Preview\n\n"; - summaryContent += "The following issues would be created if staged mode was disabled:\n\n"; - for (let i = 0; i < createIssueItems.length; i++) { - const item = createIssueItems[i]; - summaryContent += `### Issue ${i + 1}\n`; - summaryContent += `**Title:** ${item.title || "No title provided"}\n\n`; - if (item.body) { - summaryContent += `**Body:**\n${item.body}\n\n`; - } - if (item.labels && item.labels.length > 0) { - summaryContent += `**Labels:** ${item.labels.join(", ")}\n\n`; - } - summaryContent += "---\n\n"; - } - await core.summary.addRaw(summaryContent).write(); - core.info("📝 Issue creation preview written to step summary"); - return; + if (parentIssueNumber) { + core.info("Detected issue context, parent issue #" + parentIssueNumber); + bodyLines.push(`Related to #${parentIssueNumber}`); } - const parentIssueNumber = context.payload?.issue?.number; - const labelsEnv = process.env.GITHUB_AW_ISSUE_LABELS; - let envLabels = labelsEnv - ? labelsEnv - .split(",") - .map((label) => label.trim()) - .filter((label) => label) - : []; - const createdIssues = []; - for (let i = 0; i < createIssueItems.length; i++) { - const createIssueItem = createIssueItems[i]; - core.info(`Processing create-issue item ${i + 1}/${createIssueItems.length}: title=${createIssueItem.title}, bodyLength=${createIssueItem.body.length}`); - let labels = [...envLabels]; - if (createIssueItem.labels && Array.isArray(createIssueItem.labels)) { - labels = [...labels, ...createIssueItem.labels]; - } - labels = labels - .filter(label => label != null && label !== false && label !== 0) - .map(label => String(label).trim()) - .filter(label => label) - .map(label => sanitizeLabelContent(label)) - .filter(label => label) - .map(label => (label.length > 64 ? label.substring(0, 64) : label)) - .filter((label, index, arr) => arr.indexOf(label) === index); - let title = createIssueItem.title ? createIssueItem.title.trim() : ""; - let bodyLines = createIssueItem.body.split("\n"); - if (!title) { - title = createIssueItem.body || "Agent Output"; - } - const titlePrefix = process.env.GITHUB_AW_ISSUE_TITLE_PREFIX; - if (titlePrefix && !title.startsWith(titlePrefix)) { - title = titlePrefix + title; - } - if (parentIssueNumber) { - core.info("Detected issue context, parent issue #" + parentIssueNumber); - bodyLines.push(`Related to #${parentIssueNumber}`); - } - const runId = context.runId; - const runUrl = context.payload.repository - ? `${context.payload.repository.html_url}/actions/runs/${runId}` - : `https://github.com/actions/runs/${runId}`; - bodyLines.push(``, ``, `> Generated by Agentic Workflow [Run](${runUrl})`, ""); - const body = bodyLines.join("\n").trim(); - core.info(`Creating issue with title: ${title}`); - core.info(`Labels: ${labels}`); - core.info(`Body length: ${body.length}`); + const runId = context.runId; + const runUrl = context.payload.repository + ? `${context.payload.repository.html_url}/actions/runs/${runId}` + : `https://github.com/actions/runs/${runId}`; + bodyLines.push(``, ``, `> Generated by Agentic Workflow [Run](${runUrl})`, ""); + const body = bodyLines.join("\n").trim(); + core.info(`Creating issue with title: ${title}`); + core.info(`Labels: ${labels}`); + core.info(`Body length: ${body.length}`); + try { + const { data: issue } = await github.rest.issues.create({ + owner: context.repo.owner, + repo: context.repo.repo, + title: title, + body: body, + labels: labels, + }); + core.info("Created issue #" + issue.number + ": " + issue.html_url); + createdIssues.push(issue); + if (parentIssueNumber) { try { - const { data: issue } = await github.rest.issues.create({ - owner: context.repo.owner, - repo: context.repo.repo, - title: title, - body: body, - labels: labels, - }); - core.info("Created issue #" + issue.number + ": " + issue.html_url); - createdIssues.push(issue); - if (parentIssueNumber) { - try { - await github.rest.issues.createComment({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: parentIssueNumber, - body: `Created related issue: #${issue.number}`, - }); - core.info("Added comment to parent issue #" + parentIssueNumber); - } - catch (error) { - core.info(`Warning: Could not add comment to parent issue: ${error instanceof Error ? error.message : String(error)}`); - } - } - if (i === createIssueItems.length - 1) { - core.setOutput("issue_number", issue.number); - core.setOutput("issue_url", issue.html_url); - } - } - catch (error) { - const errorMessage = error instanceof Error ? error.message : String(error); - if (errorMessage.includes("Issues has been disabled in this repository")) { - core.info(`⚠ Cannot create issue "${title}": Issues are disabled for this repository`); - core.info("Consider enabling issues in repository settings if you want to create issues automatically"); - continue; - } - core.error(`✗ Failed to create issue "${title}": ${errorMessage}`); - throw error; + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: parentIssueNumber, + body: `Created related issue: #${issue.number}`, + }); + core.info("Added comment to parent issue #" + parentIssueNumber); + } catch (error) { + core.info(`Warning: Could not add comment to parent issue: ${error instanceof Error ? error.message : String(error)}`); } + } + if (i === createIssueItems.length - 1) { + core.setOutput("issue_number", issue.number); + core.setOutput("issue_url", issue.html_url); + } + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + if (errorMessage.includes("Issues has been disabled in this repository")) { + core.info(`⚠ Cannot create issue "${title}": Issues are disabled for this repository`); + core.info("Consider enabling issues in repository settings if you want to create issues automatically"); + continue; + } + core.error(`✗ Failed to create issue "${title}": ${errorMessage}`); + throw error; } - if (createdIssues.length > 0) { - let summaryContent = "\n\n## GitHub Issues\n"; - for (const issue of createdIssues) { - summaryContent += `- Issue #${issue.number}: [${issue.title}](${issue.html_url})\n`; - } - await core.summary.addRaw(summaryContent).write(); + } + if (createdIssues.length > 0) { + let summaryContent = "\n\n## GitHub Issues\n"; + for (const issue of createdIssues) { + summaryContent += `- Issue #${issue.number}: [${issue.title}](${issue.html_url})\n`; } - core.info(`Successfully created ${createdIssues.length} issue(s)`); + await core.summary.addRaw(summaryContent).write(); + } + core.info(`Successfully created ${createdIssues.length} issue(s)`); } (async () => { - await main(); + await main(); })(); missing_tool: diff --git a/.github/workflows/ci-doctor.lock.yml b/.github/workflows/ci-doctor.lock.yml index a6903270cd1..91392138389 100644 --- a/.github/workflows/ci-doctor.lock.yml +++ b/.github/workflows/ci-doctor.lock.yml @@ -1213,742 +1213,742 @@ jobs: with: script: | async function main() { - const fs = require("fs"); - function sanitizeContent(content) { - if (!content || typeof content !== "string") { - return ""; - } - const allowedDomainsEnv = process.env.GITHUB_AW_ALLOWED_DOMAINS; - const defaultAllowedDomains = ["github.com", "github.io", "githubusercontent.com", "githubassets.com", "github.dev", "codespaces.new"]; - const allowedDomains = allowedDomainsEnv - ? allowedDomainsEnv - .split(",") - .map(d => d.trim()) - .filter(d => d) - : defaultAllowedDomains; - let sanitized = content; - sanitized = neutralizeMentions(sanitized); - sanitized = removeXmlComments(sanitized); - sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); - sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); - sanitized = sanitizeUrlProtocols(sanitized); - sanitized = sanitizeUrlDomains(sanitized); - const maxLength = 524288; - if (sanitized.length > maxLength) { - sanitized = sanitized.substring(0, maxLength) + "\n[Content truncated due to length]"; - } - const lines = sanitized.split("\n"); - const maxLines = 65000; - if (lines.length > maxLines) { - sanitized = lines.slice(0, maxLines).join("\n") + "\n[Content truncated due to line count]"; - } - sanitized = neutralizeBotTriggers(sanitized); - return sanitized.trim(); - function sanitizeUrlDomains(s) { - return s.replace(/\bhttps:\/\/[^\s\])}'"<>&\x00-\x1f,;]+/gi, match => { - const urlAfterProtocol = match.slice(8); - const hostname = urlAfterProtocol.split(/[\/:\?#]/)[0].toLowerCase(); - const isAllowed = allowedDomains.some(allowedDomain => { - const normalizedAllowed = allowedDomain.toLowerCase(); - return hostname === normalizedAllowed || hostname.endsWith("." + normalizedAllowed); - }); - return isAllowed ? match : "(redacted)"; - }); - } - function sanitizeUrlProtocols(s) { - return s.replace(/\b(\w+):\/\/[^\s\])}'"<>&\x00-\x1f]+/gi, (match, protocol) => { - return protocol.toLowerCase() === "https" ? match : "(redacted)"; - }); - } - function neutralizeMentions(s) { - return s.replace(/(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, (_m, p1, p2) => `${p1}\`@${p2}\``); - } - function removeXmlComments(s) { - return s.replace(//g, "").replace(//g, ""); - } - function neutralizeBotTriggers(s) { - return s.replace(/\b(fixes?|closes?|resolves?|fix|close|resolve)\s+#(\w+)/gi, (match, action, ref) => `\`${action} #${ref}\``); - } + const fs = require("fs"); + function sanitizeContent(content) { + if (!content || typeof content !== "string") { + return ""; + } + const allowedDomainsEnv = process.env.GITHUB_AW_ALLOWED_DOMAINS; + const defaultAllowedDomains = ["github.com", "github.io", "githubusercontent.com", "githubassets.com", "github.dev", "codespaces.new"]; + const allowedDomains = allowedDomainsEnv + ? allowedDomainsEnv + .split(",") + .map(d => d.trim()) + .filter(d => d) + : defaultAllowedDomains; + let sanitized = content; + sanitized = neutralizeMentions(sanitized); + sanitized = removeXmlComments(sanitized); + sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); + sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); + sanitized = sanitizeUrlProtocols(sanitized); + sanitized = sanitizeUrlDomains(sanitized); + const maxLength = 524288; + if (sanitized.length > maxLength) { + sanitized = sanitized.substring(0, maxLength) + "\n[Content truncated due to length]"; + } + const lines = sanitized.split("\n"); + const maxLines = 65000; + if (lines.length > maxLines) { + sanitized = lines.slice(0, maxLines).join("\n") + "\n[Content truncated due to line count]"; + } + sanitized = neutralizeBotTriggers(sanitized); + return sanitized.trim(); + function sanitizeUrlDomains(s) { + return s.replace(/\bhttps:\/\/[^\s\])}'"<>&\x00-\x1f,;]+/gi, match => { + const urlAfterProtocol = match.slice(8); + const hostname = urlAfterProtocol.split(/[\/:\?#]/)[0].toLowerCase(); + const isAllowed = allowedDomains.some(allowedDomain => { + const normalizedAllowed = allowedDomain.toLowerCase(); + return hostname === normalizedAllowed || hostname.endsWith("." + normalizedAllowed); + }); + return isAllowed ? match : "(redacted)"; + }); } - function getMaxAllowedForType(itemType, config) { - const itemConfig = config?.[itemType]; - if (itemConfig && typeof itemConfig === "object" && "max" in itemConfig && itemConfig.max) { - return itemConfig.max; - } - switch (itemType) { - case "create-issue": - return 1; - case "add-comment": - return 1; - case "create-pull-request": - return 1; - case "create-pull-request-review-comment": - return 1; - case "add-labels": - return 5; - case "update-issue": - return 1; - case "push-to-pull-request-branch": - return 1; - case "create-discussion": - return 1; - case "missing-tool": - return 1000; - case "create-code-scanning-alert": - return 1000; - case "upload-asset": - return 10; - default: - return 1; - } + function sanitizeUrlProtocols(s) { + return s.replace(/\b(\w+):\/\/[^\s\])}'"<>&\x00-\x1f]+/gi, (match, protocol) => { + return protocol.toLowerCase() === "https" ? match : "(redacted)"; + }); } - function getMinRequiredForType(itemType, config) { - const itemConfig = config?.[itemType]; - if (itemConfig && typeof itemConfig === "object" && "min" in itemConfig && itemConfig.min) { - return itemConfig.min; - } - return 0; - } - function repairJson(jsonStr) { - let repaired = jsonStr.trim(); - const _ctrl = { 8: "\\b", 9: "\\t", 10: "\\n", 12: "\\f", 13: "\\r" }; - repaired = repaired.replace(/[\u0000-\u001F]/g, ch => { - const c = ch.charCodeAt(0); - return _ctrl[c] || "\\u" + c.toString(16).padStart(4, "0"); - }); - repaired = repaired.replace(/'/g, '"'); - repaired = repaired.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/g, '$1"$2":'); - repaired = repaired.replace(/"([^"\\]*)"/g, (match, content) => { - if (content.includes("\n") || content.includes("\r") || content.includes("\t")) { - const escaped = content.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"); - return `"${escaped}"`; - } - return match; - }); - repaired = repaired.replace(/"([^"]*)"([^":,}\]]*)"([^"]*)"(\s*[,:}\]])/g, (match, p1, p2, p3, p4) => `"${p1}\\"${p2}\\"${p3}"${p4}`); - repaired = repaired.replace(/(\[\s*(?:"[^"]*"(?:\s*,\s*"[^"]*")*\s*),?)\s*}/g, "$1]"); - const openBraces = (repaired.match(/\{/g) || []).length; - const closeBraces = (repaired.match(/\}/g) || []).length; - if (openBraces > closeBraces) { - repaired += "}".repeat(openBraces - closeBraces); - } - else if (closeBraces > openBraces) { - repaired = "{".repeat(closeBraces - openBraces) + repaired; - } - const openBrackets = (repaired.match(/\[/g) || []).length; - const closeBrackets = (repaired.match(/\]/g) || []).length; - if (openBrackets > closeBrackets) { - repaired += "]".repeat(openBrackets - closeBrackets); - } - else if (closeBrackets > openBrackets) { - repaired = "[".repeat(closeBrackets - openBrackets) + repaired; - } - repaired = repaired.replace(/,(\s*[}\]])/g, "$1"); - return repaired; - } - function validatePositiveInteger(value, fieldName, lineNum) { - if (value === undefined || value === null) { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} is required`, - }; - } - if (typeof value !== "number" && typeof value !== "string") { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number or string field`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; - } - const parsed = typeof value === "string" ? parseInt(value, 10) : value; - if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'line' must be a valid positive integer (got: ${value})`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'line' must be a positive integer`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, - }; - } - return { isValid: true, normalizedValue: parsed }; + function neutralizeMentions(s) { + return s.replace( + /(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, + (_m, p1, p2) => `${p1}\`@${p2}\`` + ); } - function validateOptionalPositiveInteger(value, fieldName, lineNum) { - if (value === undefined) { - return { isValid: true }; - } - if (typeof value !== "number" && typeof value !== "string") { - if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a number or string`, - }; - } - if (fieldName.includes("create-code-scanning-alert 'column'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a number or string`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; - } - const parsed = typeof value === "string" ? parseInt(value, 10) : value; - if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { - if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a positive integer`, - }; - } - if (fieldName.includes("create-code-scanning-alert 'column'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a valid positive integer (got: ${value})`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, - }; - } - return { isValid: true, normalizedValue: parsed }; + function removeXmlComments(s) { + return s.replace(//g, "").replace(//g, ""); } - function validateIssueOrPRNumber(value, fieldName, lineNum) { - if (value === undefined) { - return { isValid: true }; - } - if (typeof value !== "number" && typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; - } - return { isValid: true }; - } - function validateFieldWithInputSchema(value, fieldName, inputSchema, lineNum) { - if (inputSchema.required && (value === undefined || value === null)) { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} is required`, - }; - } - if (value === undefined || value === null) { - return { - isValid: true, - normalizedValue: inputSchema.default || undefined, - }; - } - const inputType = inputSchema.type || "string"; - let normalizedValue = value; - switch (inputType) { - case "string": - if (typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a string`, - }; - } - normalizedValue = sanitizeContent(value); - break; - case "boolean": - if (typeof value !== "boolean") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a boolean`, - }; - } - break; - case "number": - if (typeof value !== "number") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number`, - }; - } - break; - case "choice": - if (typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a string for choice type`, - }; - } - if (inputSchema.options && !inputSchema.options.includes(value)) { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be one of: ${inputSchema.options.join(", ")}`, - }; - } - normalizedValue = sanitizeContent(value); - break; - default: - if (typeof value === "string") { - normalizedValue = sanitizeContent(value); - } - break; - } + function neutralizeBotTriggers(s) { + return s.replace(/\b(fixes?|closes?|resolves?|fix|close|resolve)\s+#(\w+)/gi, (match, action, ref) => `\`${action} #${ref}\``); + } + } + function getMaxAllowedForType(itemType, config) { + const itemConfig = config?.[itemType]; + if (itemConfig && typeof itemConfig === "object" && "max" in itemConfig && itemConfig.max) { + return itemConfig.max; + } + switch (itemType) { + case "create-issue": + return 1; + case "add-comment": + return 1; + case "create-pull-request": + return 1; + case "create-pull-request-review-comment": + return 1; + case "add-labels": + return 5; + case "update-issue": + return 1; + case "push-to-pull-request-branch": + return 1; + case "create-discussion": + return 1; + case "missing-tool": + return 1000; + case "create-code-scanning-alert": + return 1000; + case "upload-asset": + return 10; + default: + return 1; + } + } + function getMinRequiredForType(itemType, config) { + const itemConfig = config?.[itemType]; + if (itemConfig && typeof itemConfig === "object" && "min" in itemConfig && itemConfig.min) { + return itemConfig.min; + } + return 0; + } + function repairJson(jsonStr) { + let repaired = jsonStr.trim(); + const _ctrl = { 8: "\\b", 9: "\\t", 10: "\\n", 12: "\\f", 13: "\\r" }; + repaired = repaired.replace(/[\u0000-\u001F]/g, ch => { + const c = ch.charCodeAt(0); + return _ctrl[c] || "\\u" + c.toString(16).padStart(4, "0"); + }); + repaired = repaired.replace(/'/g, '"'); + repaired = repaired.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/g, '$1"$2":'); + repaired = repaired.replace(/"([^"\\]*)"/g, (match, content) => { + if (content.includes("\n") || content.includes("\r") || content.includes("\t")) { + const escaped = content.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"); + return `"${escaped}"`; + } + return match; + }); + repaired = repaired.replace(/"([^"]*)"([^":,}\]]*)"([^"]*)"(\s*[,:}\]])/g, (match, p1, p2, p3, p4) => `"${p1}\\"${p2}\\"${p3}"${p4}`); + repaired = repaired.replace(/(\[\s*(?:"[^"]*"(?:\s*,\s*"[^"]*")*\s*),?)\s*}/g, "$1]"); + const openBraces = (repaired.match(/\{/g) || []).length; + const closeBraces = (repaired.match(/\}/g) || []).length; + if (openBraces > closeBraces) { + repaired += "}".repeat(openBraces - closeBraces); + } else if (closeBraces > openBraces) { + repaired = "{".repeat(closeBraces - openBraces) + repaired; + } + const openBrackets = (repaired.match(/\[/g) || []).length; + const closeBrackets = (repaired.match(/\]/g) || []).length; + if (openBrackets > closeBrackets) { + repaired += "]".repeat(openBrackets - closeBrackets); + } else if (closeBrackets > openBrackets) { + repaired = "[".repeat(closeBrackets - openBrackets) + repaired; + } + repaired = repaired.replace(/,(\s*[}\]])/g, "$1"); + return repaired; + } + function validatePositiveInteger(value, fieldName, lineNum) { + if (value === undefined || value === null) { + if (fieldName.includes("create-code-scanning-alert 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, + }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { return { - isValid: true, - normalizedValue, + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number`, }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} is required`, + }; } - function validateItemWithSafeJobConfig(item, jobConfig, lineNum) { - const errors = []; - const normalizedItem = { ...item }; - if (!jobConfig.inputs) { - return { - isValid: true, - errors: [], - normalizedItem: item, - }; - } - for (const [fieldName, inputSchema] of Object.entries(jobConfig.inputs)) { - const fieldValue = item[fieldName]; - const validation = validateFieldWithInputSchema(fieldValue, fieldName, inputSchema, lineNum); - if (!validation.isValid && validation.error) { - errors.push(validation.error); - } - else if (validation.normalizedValue !== undefined) { - normalizedItem[fieldName] = validation.normalizedValue; - } - } + if (typeof value !== "number" && typeof value !== "string") { + if (fieldName.includes("create-code-scanning-alert 'line'")) { return { - isValid: errors.length === 0, - errors, - normalizedItem, + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number or string field`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; } - function parseJsonWithRepair(jsonStr) { - try { - return JSON.parse(jsonStr); - } - catch (originalError) { - try { - const repairedJson = repairJson(jsonStr); - return JSON.parse(repairedJson); - } - catch (repairError) { - core.info(`invalid input json: ${jsonStr}`); - const originalMsg = originalError instanceof Error ? originalError.message : String(originalError); - const repairMsg = repairError instanceof Error ? repairError.message : String(repairError); - throw new Error(`JSON parsing failed. Original: ${originalMsg}. After attempted repair: ${repairMsg}`); - } - } + const parsed = typeof value === "string" ? parseInt(value, 10) : value; + if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { + if (fieldName.includes("create-code-scanning-alert 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'line' must be a valid positive integer (got: ${value})`, + }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'line' must be a positive integer`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, + }; } - const outputFile = process.env.GITHUB_AW_SAFE_OUTPUTS; - const safeOutputsConfig = process.env.GITHUB_AW_SAFE_OUTPUTS_CONFIG; - if (!outputFile) { - core.info("GITHUB_AW_SAFE_OUTPUTS not set, no output to collect"); - core.setOutput("output", ""); - return; + return { isValid: true, normalizedValue: parsed }; + } + function validateOptionalPositiveInteger(value, fieldName, lineNum) { + if (value === undefined) { + return { isValid: true }; } - if (!fs.existsSync(outputFile)) { - core.info(`Output file does not exist: ${outputFile}`); - core.setOutput("output", ""); - return; + if (typeof value !== "number" && typeof value !== "string") { + if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a number or string`, + }; + } + if (fieldName.includes("create-code-scanning-alert 'column'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a number or string`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; + } + const parsed = typeof value === "string" ? parseInt(value, 10) : value; + if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { + if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a positive integer`, + }; + } + if (fieldName.includes("create-code-scanning-alert 'column'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a valid positive integer (got: ${value})`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, + }; } - const outputContent = fs.readFileSync(outputFile, "utf8"); - if (outputContent.trim() === "") { - core.info("Output file is empty"); + return { isValid: true, normalizedValue: parsed }; + } + function validateIssueOrPRNumber(value, fieldName, lineNum) { + if (value === undefined) { + return { isValid: true }; } - core.info(`Raw output content length: ${outputContent.length}`); - let expectedOutputTypes = {}; - if (safeOutputsConfig) { - try { - expectedOutputTypes = JSON.parse(safeOutputsConfig); - core.info(`Expected output types: ${JSON.stringify(Object.keys(expectedOutputTypes))}`); + if (typeof value !== "number" && typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; + } + return { isValid: true }; + } + function validateFieldWithInputSchema(value, fieldName, inputSchema, lineNum) { + if (inputSchema.required && (value === undefined || value === null)) { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} is required`, + }; + } + if (value === undefined || value === null) { + return { + isValid: true, + normalizedValue: inputSchema.default || undefined, + }; + } + const inputType = inputSchema.type || "string"; + let normalizedValue = value; + switch (inputType) { + case "string": + if (typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a string`, + }; + } + normalizedValue = sanitizeContent(value); + break; + case "boolean": + if (typeof value !== "boolean") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a boolean`, + }; + } + break; + case "number": + if (typeof value !== "number") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number`, + }; } - catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.info(`Warning: Could not parse safe-outputs config: ${errorMsg}`); + break; + case "choice": + if (typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a string for choice type`, + }; + } + if (inputSchema.options && !inputSchema.options.includes(value)) { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be one of: ${inputSchema.options.join(", ")}`, + }; + } + normalizedValue = sanitizeContent(value); + break; + default: + if (typeof value === "string") { + normalizedValue = sanitizeContent(value); } + break; } - const lines = outputContent.trim().split("\n"); - const parsedItems = []; + return { + isValid: true, + normalizedValue, + }; + } + function validateItemWithSafeJobConfig(item, jobConfig, lineNum) { const errors = []; - for (let i = 0; i < lines.length; i++) { - const line = lines[i].trim(); - if (line === "") + const normalizedItem = { ...item }; + if (!jobConfig.inputs) { + return { + isValid: true, + errors: [], + normalizedItem: item, + }; + } + for (const [fieldName, inputSchema] of Object.entries(jobConfig.inputs)) { + const fieldValue = item[fieldName]; + const validation = validateFieldWithInputSchema(fieldValue, fieldName, inputSchema, lineNum); + if (!validation.isValid && validation.error) { + errors.push(validation.error); + } else if (validation.normalizedValue !== undefined) { + normalizedItem[fieldName] = validation.normalizedValue; + } + } + return { + isValid: errors.length === 0, + errors, + normalizedItem, + }; + } + function parseJsonWithRepair(jsonStr) { + try { + return JSON.parse(jsonStr); + } catch (originalError) { + try { + const repairedJson = repairJson(jsonStr); + return JSON.parse(repairedJson); + } catch (repairError) { + core.info(`invalid input json: ${jsonStr}`); + const originalMsg = originalError instanceof Error ? originalError.message : String(originalError); + const repairMsg = repairError instanceof Error ? repairError.message : String(repairError); + throw new Error(`JSON parsing failed. Original: ${originalMsg}. After attempted repair: ${repairMsg}`); + } + } + } + const outputFile = process.env.GITHUB_AW_SAFE_OUTPUTS; + const safeOutputsConfig = process.env.GITHUB_AW_SAFE_OUTPUTS_CONFIG; + if (!outputFile) { + core.info("GITHUB_AW_SAFE_OUTPUTS not set, no output to collect"); + core.setOutput("output", ""); + return; + } + if (!fs.existsSync(outputFile)) { + core.info(`Output file does not exist: ${outputFile}`); + core.setOutput("output", ""); + return; + } + const outputContent = fs.readFileSync(outputFile, "utf8"); + if (outputContent.trim() === "") { + core.info("Output file is empty"); + } + core.info(`Raw output content length: ${outputContent.length}`); + let expectedOutputTypes = {}; + if (safeOutputsConfig) { + try { + expectedOutputTypes = JSON.parse(safeOutputsConfig); + core.info(`Expected output types: ${JSON.stringify(Object.keys(expectedOutputTypes))}`); + } catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.info(`Warning: Could not parse safe-outputs config: ${errorMsg}`); + } + } + const lines = outputContent.trim().split("\n"); + const parsedItems = []; + const errors = []; + for (let i = 0; i < lines.length; i++) { + const line = lines[i].trim(); + if (line === "") continue; + try { + const item = parseJsonWithRepair(line); + if (item === undefined) { + errors.push(`Line ${i + 1}: Invalid JSON - JSON parsing failed`); + continue; + } + if (!item.type) { + errors.push(`Line ${i + 1}: Missing required 'type' field`); + continue; + } + const itemType = item.type; + if (!expectedOutputTypes[itemType]) { + errors.push(`Line ${i + 1}: Unexpected output type '${itemType}'. Expected one of: ${Object.keys(expectedOutputTypes).join(", ")}`); + continue; + } + const typeCount = parsedItems.filter(existing => existing.type === itemType).length; + const maxAllowed = getMaxAllowedForType(itemType, expectedOutputTypes); + if (typeCount >= maxAllowed) { + errors.push(`Line ${i + 1}: Too many items of type '${itemType}'. Maximum allowed: ${maxAllowed}.`); + continue; + } + core.info(`Line ${i + 1}: type '${itemType}'`); + switch (itemType) { + case "create-issue": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_issue requires a 'title' string field`); continue; - try { - const item = parseJsonWithRepair(line); - if (item === undefined) { - errors.push(`Line ${i + 1}: Invalid JSON - JSON parsing failed`); - continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_issue requires a 'body' string field`); + continue; + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + if (item.labels && Array.isArray(item.labels)) { + item.labels = item.labels.map(label => (typeof label === "string" ? sanitizeContent(label) : label)); + } + break; + case "add-comment": + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: add_comment requires a 'body' string field`); + continue; + } + const issueNumValidation = validateIssueOrPRNumber(item.issue_number, "add_comment 'issue_number'", i + 1); + if (!issueNumValidation.isValid) { + if (issueNumValidation.error) errors.push(issueNumValidation.error); + continue; + } + item.body = sanitizeContent(item.body); + break; + case "create-pull-request": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'body' string field`); + continue; + } + if (!item.branch || typeof item.branch !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'branch' string field`); + continue; + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + item.branch = sanitizeContent(item.branch); + if (item.labels && Array.isArray(item.labels)) { + item.labels = item.labels.map(label => (typeof label === "string" ? sanitizeContent(label) : label)); + } + break; + case "add-labels": + if (!item.labels || !Array.isArray(item.labels)) { + errors.push(`Line ${i + 1}: add_labels requires a 'labels' array field`); + continue; + } + if (item.labels.some(label => typeof label !== "string")) { + errors.push(`Line ${i + 1}: add_labels labels array must contain only strings`); + continue; + } + const labelsIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "add-labels 'issue_number'", i + 1); + if (!labelsIssueNumValidation.isValid) { + if (labelsIssueNumValidation.error) errors.push(labelsIssueNumValidation.error); + continue; + } + item.labels = item.labels.map(label => sanitizeContent(label)); + break; + case "update-issue": + const hasValidField = item.status !== undefined || item.title !== undefined || item.body !== undefined; + if (!hasValidField) { + errors.push(`Line ${i + 1}: update_issue requires at least one of: 'status', 'title', or 'body' fields`); + continue; + } + if (item.status !== undefined) { + if (typeof item.status !== "string" || (item.status !== "open" && item.status !== "closed")) { + errors.push(`Line ${i + 1}: update_issue 'status' must be 'open' or 'closed'`); + continue; } - if (!item.type) { - errors.push(`Line ${i + 1}: Missing required 'type' field`); - continue; + } + if (item.title !== undefined) { + if (typeof item.title !== "string") { + errors.push(`Line ${i + 1}: update-issue 'title' must be a string`); + continue; } - const itemType = item.type; - if (!expectedOutputTypes[itemType]) { - errors.push(`Line ${i + 1}: Unexpected output type '${itemType}'. Expected one of: ${Object.keys(expectedOutputTypes).join(", ")}`); - continue; + item.title = sanitizeContent(item.title); + } + if (item.body !== undefined) { + if (typeof item.body !== "string") { + errors.push(`Line ${i + 1}: update-issue 'body' must be a string`); + continue; } - const typeCount = parsedItems.filter(existing => existing.type === itemType).length; - const maxAllowed = getMaxAllowedForType(itemType, expectedOutputTypes); - if (typeCount >= maxAllowed) { - errors.push(`Line ${i + 1}: Too many items of type '${itemType}'. Maximum allowed: ${maxAllowed}.`); - continue; + item.body = sanitizeContent(item.body); + } + const updateIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "update-issue 'issue_number'", i + 1); + if (!updateIssueNumValidation.isValid) { + if (updateIssueNumValidation.error) errors.push(updateIssueNumValidation.error); + continue; + } + break; + case "push-to-pull-request-branch": + if (!item.branch || typeof item.branch !== "string") { + errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'branch' string field`); + continue; + } + if (!item.message || typeof item.message !== "string") { + errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'message' string field`); + continue; + } + item.branch = sanitizeContent(item.branch); + item.message = sanitizeContent(item.message); + const pushPRNumValidation = validateIssueOrPRNumber( + item.pull_request_number, + "push-to-pull-request-branch 'pull_request_number'", + i + 1 + ); + if (!pushPRNumValidation.isValid) { + if (pushPRNumValidation.error) errors.push(pushPRNumValidation.error); + continue; + } + break; + case "create-pull-request-review-comment": + if (!item.path || typeof item.path !== "string") { + errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'path' string field`); + continue; + } + const lineValidation = validatePositiveInteger(item.line, "create-pull-request-review-comment 'line'", i + 1); + if (!lineValidation.isValid) { + if (lineValidation.error) errors.push(lineValidation.error); + continue; + } + const lineNumber = lineValidation.normalizedValue; + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'body' string field`); + continue; + } + item.body = sanitizeContent(item.body); + const startLineValidation = validateOptionalPositiveInteger( + item.start_line, + "create-pull-request-review-comment 'start_line'", + i + 1 + ); + if (!startLineValidation.isValid) { + if (startLineValidation.error) errors.push(startLineValidation.error); + continue; + } + if ( + startLineValidation.normalizedValue !== undefined && + lineNumber !== undefined && + startLineValidation.normalizedValue > lineNumber + ) { + errors.push(`Line ${i + 1}: create-pull-request-review-comment 'start_line' must be less than or equal to 'line'`); + continue; + } + if (item.side !== undefined) { + if (typeof item.side !== "string" || (item.side !== "LEFT" && item.side !== "RIGHT")) { + errors.push(`Line ${i + 1}: create-pull-request-review-comment 'side' must be 'LEFT' or 'RIGHT'`); + continue; } - core.info(`Line ${i + 1}: type '${itemType}'`); - switch (itemType) { - case "create-issue": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_issue requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_issue requires a 'body' string field`); - continue; - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - if (item.labels && Array.isArray(item.labels)) { - item.labels = item.labels.map((label) => (typeof label === "string" ? sanitizeContent(label) : label)); - } - break; - case "add-comment": - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: add_comment requires a 'body' string field`); - continue; - } - const issueNumValidation = validateIssueOrPRNumber(item.issue_number, "add_comment 'issue_number'", i + 1); - if (!issueNumValidation.isValid) { - if (issueNumValidation.error) - errors.push(issueNumValidation.error); - continue; - } - item.body = sanitizeContent(item.body); - break; - case "create-pull-request": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'body' string field`); - continue; - } - if (!item.branch || typeof item.branch !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'branch' string field`); - continue; - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - item.branch = sanitizeContent(item.branch); - if (item.labels && Array.isArray(item.labels)) { - item.labels = item.labels.map((label) => (typeof label === "string" ? sanitizeContent(label) : label)); - } - break; - case "add-labels": - if (!item.labels || !Array.isArray(item.labels)) { - errors.push(`Line ${i + 1}: add_labels requires a 'labels' array field`); - continue; - } - if (item.labels.some((label) => typeof label !== "string")) { - errors.push(`Line ${i + 1}: add_labels labels array must contain only strings`); - continue; - } - const labelsIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "add-labels 'issue_number'", i + 1); - if (!labelsIssueNumValidation.isValid) { - if (labelsIssueNumValidation.error) - errors.push(labelsIssueNumValidation.error); - continue; - } - item.labels = item.labels.map((label) => sanitizeContent(label)); - break; - case "update-issue": - const hasValidField = item.status !== undefined || item.title !== undefined || item.body !== undefined; - if (!hasValidField) { - errors.push(`Line ${i + 1}: update_issue requires at least one of: 'status', 'title', or 'body' fields`); - continue; - } - if (item.status !== undefined) { - if (typeof item.status !== "string" || (item.status !== "open" && item.status !== "closed")) { - errors.push(`Line ${i + 1}: update_issue 'status' must be 'open' or 'closed'`); - continue; - } - } - if (item.title !== undefined) { - if (typeof item.title !== "string") { - errors.push(`Line ${i + 1}: update-issue 'title' must be a string`); - continue; - } - item.title = sanitizeContent(item.title); - } - if (item.body !== undefined) { - if (typeof item.body !== "string") { - errors.push(`Line ${i + 1}: update-issue 'body' must be a string`); - continue; - } - item.body = sanitizeContent(item.body); - } - const updateIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "update-issue 'issue_number'", i + 1); - if (!updateIssueNumValidation.isValid) { - if (updateIssueNumValidation.error) - errors.push(updateIssueNumValidation.error); - continue; - } - break; - case "push-to-pull-request-branch": - if (!item.branch || typeof item.branch !== "string") { - errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'branch' string field`); - continue; - } - if (!item.message || typeof item.message !== "string") { - errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'message' string field`); - continue; - } - item.branch = sanitizeContent(item.branch); - item.message = sanitizeContent(item.message); - const pushPRNumValidation = validateIssueOrPRNumber(item.pull_request_number, "push-to-pull-request-branch 'pull_request_number'", i + 1); - if (!pushPRNumValidation.isValid) { - if (pushPRNumValidation.error) - errors.push(pushPRNumValidation.error); - continue; - } - break; - case "create-pull-request-review-comment": - if (!item.path || typeof item.path !== "string") { - errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'path' string field`); - continue; - } - const lineValidation = validatePositiveInteger(item.line, "create-pull-request-review-comment 'line'", i + 1); - if (!lineValidation.isValid) { - if (lineValidation.error) - errors.push(lineValidation.error); - continue; - } - const lineNumber = lineValidation.normalizedValue; - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'body' string field`); - continue; - } - item.body = sanitizeContent(item.body); - const startLineValidation = validateOptionalPositiveInteger(item.start_line, "create-pull-request-review-comment 'start_line'", i + 1); - if (!startLineValidation.isValid) { - if (startLineValidation.error) - errors.push(startLineValidation.error); - continue; - } - if (startLineValidation.normalizedValue !== undefined && - lineNumber !== undefined && - startLineValidation.normalizedValue > lineNumber) { - errors.push(`Line ${i + 1}: create-pull-request-review-comment 'start_line' must be less than or equal to 'line'`); - continue; - } - if (item.side !== undefined) { - if (typeof item.side !== "string" || (item.side !== "LEFT" && item.side !== "RIGHT")) { - errors.push(`Line ${i + 1}: create-pull-request-review-comment 'side' must be 'LEFT' or 'RIGHT'`); - continue; - } - } - break; - case "create-discussion": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_discussion requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_discussion requires a 'body' string field`); - continue; - } - if (item.category !== undefined) { - if (typeof item.category !== "string") { - errors.push(`Line ${i + 1}: create_discussion 'category' must be a string`); - continue; - } - item.category = sanitizeContent(item.category); - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - break; - case "missing-tool": - if (!item.tool || typeof item.tool !== "string") { - errors.push(`Line ${i + 1}: missing_tool requires a 'tool' string field`); - continue; - } - if (!item.reason || typeof item.reason !== "string") { - errors.push(`Line ${i + 1}: missing_tool requires a 'reason' string field`); - continue; - } - item.tool = sanitizeContent(item.tool); - item.reason = sanitizeContent(item.reason); - if (item.alternatives !== undefined) { - if (typeof item.alternatives !== "string") { - errors.push(`Line ${i + 1}: missing-tool 'alternatives' must be a string`); - continue; - } - item.alternatives = sanitizeContent(item.alternatives); - } - break; - case "upload-asset": - if (!item.path || typeof item.path !== "string") { - errors.push(`Line ${i + 1}: upload_asset requires a 'path' string field`); - continue; - } - break; - case "create-code-scanning-alert": - if (!item.file || typeof item.file !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'file' field (string)`); - continue; - } - const alertLineValidation = validatePositiveInteger(item.line, "create-code-scanning-alert 'line'", i + 1); - if (!alertLineValidation.isValid) { - if (alertLineValidation.error) { - errors.push(alertLineValidation.error); - } - continue; - } - if (!item.severity || typeof item.severity !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'severity' field (string)`); - continue; - } - if (!item.message || typeof item.message !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'message' field (string)`); - continue; - } - const allowedSeverities = ["error", "warning", "info", "note"]; - if (!allowedSeverities.includes(item.severity.toLowerCase())) { - errors.push(`Line ${i + 1}: create-code-scanning-alert 'severity' must be one of: ${allowedSeverities.join(", ")}, got ${item.severity.toLowerCase()}`); - continue; - } - const columnValidation = validateOptionalPositiveInteger(item.column, "create-code-scanning-alert 'column'", i + 1); - if (!columnValidation.isValid) { - if (columnValidation.error) - errors.push(columnValidation.error); - continue; - } - if (item.ruleIdSuffix !== undefined) { - if (typeof item.ruleIdSuffix !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must be a string`); - continue; - } - if (!/^[a-zA-Z0-9_-]+$/.test(item.ruleIdSuffix.trim())) { - errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must contain only alphanumeric characters, hyphens, and underscores`); - continue; - } - } - item.severity = item.severity.toLowerCase(); - item.file = sanitizeContent(item.file); - item.severity = sanitizeContent(item.severity); - item.message = sanitizeContent(item.message); - if (item.ruleIdSuffix) { - item.ruleIdSuffix = sanitizeContent(item.ruleIdSuffix); - } - break; - default: - const jobOutputType = expectedOutputTypes[itemType]; - if (!jobOutputType) { - errors.push(`Line ${i + 1}: Unknown output type '${itemType}'`); - continue; - } - const safeJobConfig = jobOutputType; - if (safeJobConfig && safeJobConfig.inputs) { - const validation = validateItemWithSafeJobConfig(item, safeJobConfig, i + 1); - if (!validation.isValid) { - errors.push(...validation.errors); - continue; - } - Object.assign(item, validation.normalizedItem); - } - break; + } + break; + case "create-discussion": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_discussion requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_discussion requires a 'body' string field`); + continue; + } + if (item.category !== undefined) { + if (typeof item.category !== "string") { + errors.push(`Line ${i + 1}: create_discussion 'category' must be a string`); + continue; } - core.info(`Line ${i + 1}: Valid ${itemType} item`); - parsedItems.push(item); - } - catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - errors.push(`Line ${i + 1}: Invalid JSON - ${errorMsg}`); - } - } - if (errors.length > 0) { - core.warning("Validation errors found:"); - errors.forEach(error => core.warning(` - ${error}`)); - if (parsedItems.length === 0) { - core.setFailed(errors.map(e => ` - ${e}`).join("\n")); - return; - } - } - for (const itemType of Object.keys(expectedOutputTypes)) { - const minRequired = getMinRequiredForType(itemType, expectedOutputTypes); - if (minRequired > 0) { - const actualCount = parsedItems.filter(item => item.type === itemType).length; - if (actualCount < minRequired) { - errors.push(`Too few items of type '${itemType}'. Minimum required: ${minRequired}, found: ${actualCount}.`); + item.category = sanitizeContent(item.category); + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + break; + case "missing-tool": + if (!item.tool || typeof item.tool !== "string") { + errors.push(`Line ${i + 1}: missing_tool requires a 'tool' string field`); + continue; + } + if (!item.reason || typeof item.reason !== "string") { + errors.push(`Line ${i + 1}: missing_tool requires a 'reason' string field`); + continue; + } + item.tool = sanitizeContent(item.tool); + item.reason = sanitizeContent(item.reason); + if (item.alternatives !== undefined) { + if (typeof item.alternatives !== "string") { + errors.push(`Line ${i + 1}: missing-tool 'alternatives' must be a string`); + continue; } - } + item.alternatives = sanitizeContent(item.alternatives); + } + break; + case "upload-asset": + if (!item.path || typeof item.path !== "string") { + errors.push(`Line ${i + 1}: upload_asset requires a 'path' string field`); + continue; + } + break; + case "create-code-scanning-alert": + if (!item.file || typeof item.file !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'file' field (string)`); + continue; + } + const alertLineValidation = validatePositiveInteger(item.line, "create-code-scanning-alert 'line'", i + 1); + if (!alertLineValidation.isValid) { + if (alertLineValidation.error) { + errors.push(alertLineValidation.error); + } + continue; + } + if (!item.severity || typeof item.severity !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'severity' field (string)`); + continue; + } + if (!item.message || typeof item.message !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'message' field (string)`); + continue; + } + const allowedSeverities = ["error", "warning", "info", "note"]; + if (!allowedSeverities.includes(item.severity.toLowerCase())) { + errors.push( + `Line ${i + 1}: create-code-scanning-alert 'severity' must be one of: ${allowedSeverities.join(", ")}, got ${item.severity.toLowerCase()}` + ); + continue; + } + const columnValidation = validateOptionalPositiveInteger(item.column, "create-code-scanning-alert 'column'", i + 1); + if (!columnValidation.isValid) { + if (columnValidation.error) errors.push(columnValidation.error); + continue; + } + if (item.ruleIdSuffix !== undefined) { + if (typeof item.ruleIdSuffix !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must be a string`); + continue; + } + if (!/^[a-zA-Z0-9_-]+$/.test(item.ruleIdSuffix.trim())) { + errors.push( + `Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must contain only alphanumeric characters, hyphens, and underscores` + ); + continue; + } + } + item.severity = item.severity.toLowerCase(); + item.file = sanitizeContent(item.file); + item.severity = sanitizeContent(item.severity); + item.message = sanitizeContent(item.message); + if (item.ruleIdSuffix) { + item.ruleIdSuffix = sanitizeContent(item.ruleIdSuffix); + } + break; + default: + const jobOutputType = expectedOutputTypes[itemType]; + if (!jobOutputType) { + errors.push(`Line ${i + 1}: Unknown output type '${itemType}'`); + continue; + } + const safeJobConfig = jobOutputType; + if (safeJobConfig && safeJobConfig.inputs) { + const validation = validateItemWithSafeJobConfig(item, safeJobConfig, i + 1); + if (!validation.isValid) { + errors.push(...validation.errors); + continue; + } + Object.assign(item, validation.normalizedItem); + } + break; + } + core.info(`Line ${i + 1}: Valid ${itemType} item`); + parsedItems.push(item); + } catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + errors.push(`Line ${i + 1}: Invalid JSON - ${errorMsg}`); } - core.info(`Successfully parsed ${parsedItems.length} valid output items`); - const validatedOutput = { - items: parsedItems, - errors: errors, - }; - const agentOutputFile = "/tmp/agent_output.json"; - const validatedOutputJson = JSON.stringify(validatedOutput); - try { - fs.mkdirSync("/tmp", { recursive: true }); - fs.writeFileSync(agentOutputFile, validatedOutputJson, "utf8"); - core.info(`Stored validated output to: ${agentOutputFile}`); - core.exportVariable("GITHUB_AW_AGENT_OUTPUT", agentOutputFile); - } - catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.error(`Failed to write agent output file: ${errorMsg}`); - } - core.setOutput("output", JSON.stringify(validatedOutput)); - core.setOutput("raw_output", outputContent); - const outputTypes = Array.from(new Set(parsedItems.map(item => item.type))); - core.info(`output_types: ${outputTypes.join(", ")}`); - core.setOutput("output_types", outputTypes.join(",")); - try { - await core.summary - .addRaw("## Processed Output\n\n") - .addRaw("```json\n") - .addRaw(JSON.stringify(validatedOutput)) - .addRaw("\n```\n") - .write(); - core.info("Successfully wrote processed output to step summary"); - } - catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.warning(`Failed to write to step summary: ${errorMsg}`); + } + if (errors.length > 0) { + core.warning("Validation errors found:"); + errors.forEach(error => core.warning(` - ${error}`)); + if (parsedItems.length === 0) { + core.setFailed(errors.map(e => ` - ${e}`).join("\n")); + return; + } + } + for (const itemType of Object.keys(expectedOutputTypes)) { + const minRequired = getMinRequiredForType(itemType, expectedOutputTypes); + if (minRequired > 0) { + const actualCount = parsedItems.filter(item => item.type === itemType).length; + if (actualCount < minRequired) { + errors.push(`Too few items of type '${itemType}'. Minimum required: ${minRequired}, found: ${actualCount}.`); + } } + } + core.info(`Successfully parsed ${parsedItems.length} valid output items`); + const validatedOutput = { + items: parsedItems, + errors: errors, + }; + const agentOutputFile = "/tmp/agent_output.json"; + const validatedOutputJson = JSON.stringify(validatedOutput); + try { + fs.mkdirSync("/tmp", { recursive: true }); + fs.writeFileSync(agentOutputFile, validatedOutputJson, "utf8"); + core.info(`Stored validated output to: ${agentOutputFile}`); + core.exportVariable("GITHUB_AW_AGENT_OUTPUT", agentOutputFile); + } catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.error(`Failed to write agent output file: ${errorMsg}`); + } + core.setOutput("output", JSON.stringify(validatedOutput)); + core.setOutput("raw_output", outputContent); + const outputTypes = Array.from(new Set(parsedItems.map(item => item.type))); + core.info(`output_types: ${outputTypes.join(", ")}`); + core.setOutput("output_types", outputTypes.join(",")); + try { + await core.summary + .addRaw("## Processed Output\n\n") + .addRaw("```json\n") + .addRaw(JSON.stringify(validatedOutput)) + .addRaw("\n```\n") + .write(); + core.info("Successfully wrote processed output to step summary"); + } catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.warning(`Failed to write to step summary: ${errorMsg}`); + } } await main(); - name: Upload sanitized agent output @@ -2488,162 +2488,164 @@ jobs: with: script: | function sanitizeLabelContent(content) { - if (!content || typeof content !== "string") { - return ""; - } - let sanitized = content.trim(); - sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); - sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); - sanitized = sanitized.replace(/(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, (_m, p1, p2) => `${p1}\`@${p2}\``); - sanitized = sanitized.replace(/[<>&'"]/g, ""); - return sanitized.trim(); + if (!content || typeof content !== "string") { + return ""; + } + let sanitized = content.trim(); + sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); + sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); + sanitized = sanitized.replace( + /(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, + (_m, p1, p2) => `${p1}\`@${p2}\`` + ); + sanitized = sanitized.replace(/[<>&'"]/g, ""); + return sanitized.trim(); } async function main() { - const isStaged = process.env.GITHUB_AW_SAFE_OUTPUTS_STAGED === "true"; - const outputContent = process.env.GITHUB_AW_AGENT_OUTPUT; - if (!outputContent) { - core.info("No GITHUB_AW_AGENT_OUTPUT environment variable found"); - return; + const isStaged = process.env.GITHUB_AW_SAFE_OUTPUTS_STAGED === "true"; + const outputContent = process.env.GITHUB_AW_AGENT_OUTPUT; + if (!outputContent) { + core.info("No GITHUB_AW_AGENT_OUTPUT environment variable found"); + return; + } + if (outputContent.trim() === "") { + core.info("Agent output content is empty"); + return; + } + core.info(`Agent output content length: ${outputContent.length}`); + let validatedOutput; + try { + validatedOutput = JSON.parse(outputContent); + } catch (error) { + core.setFailed(`Error parsing agent output JSON: ${error instanceof Error ? error.message : String(error)}`); + return; + } + if (!validatedOutput.items || !Array.isArray(validatedOutput.items)) { + core.info("No valid items found in agent output"); + return; + } + const createIssueItems = validatedOutput.items.filter(item => item.type === "create-issue"); + if (createIssueItems.length === 0) { + core.info("No create-issue items found in agent output"); + return; + } + core.info(`Found ${createIssueItems.length} create-issue item(s)`); + if (isStaged) { + let summaryContent = "## 🎭 Staged Mode: Create Issues Preview\n\n"; + summaryContent += "The following issues would be created if staged mode was disabled:\n\n"; + for (let i = 0; i < createIssueItems.length; i++) { + const item = createIssueItems[i]; + summaryContent += `### Issue ${i + 1}\n`; + summaryContent += `**Title:** ${item.title || "No title provided"}\n\n`; + if (item.body) { + summaryContent += `**Body:**\n${item.body}\n\n`; + } + if (item.labels && item.labels.length > 0) { + summaryContent += `**Labels:** ${item.labels.join(", ")}\n\n`; + } + summaryContent += "---\n\n"; } - if (outputContent.trim() === "") { - core.info("Agent output content is empty"); - return; + await core.summary.addRaw(summaryContent).write(); + core.info("📝 Issue creation preview written to step summary"); + return; + } + const parentIssueNumber = context.payload?.issue?.number; + const labelsEnv = process.env.GITHUB_AW_ISSUE_LABELS; + let envLabels = labelsEnv + ? labelsEnv + .split(",") + .map(label => label.trim()) + .filter(label => label) + : []; + const createdIssues = []; + for (let i = 0; i < createIssueItems.length; i++) { + const createIssueItem = createIssueItems[i]; + core.info( + `Processing create-issue item ${i + 1}/${createIssueItems.length}: title=${createIssueItem.title}, bodyLength=${createIssueItem.body.length}` + ); + let labels = [...envLabels]; + if (createIssueItem.labels && Array.isArray(createIssueItem.labels)) { + labels = [...labels, ...createIssueItem.labels]; + } + labels = labels + .filter(label => label != null && label !== false && label !== 0) + .map(label => String(label).trim()) + .filter(label => label) + .map(label => sanitizeLabelContent(label)) + .filter(label => label) + .map(label => (label.length > 64 ? label.substring(0, 64) : label)) + .filter((label, index, arr) => arr.indexOf(label) === index); + let title = createIssueItem.title ? createIssueItem.title.trim() : ""; + let bodyLines = createIssueItem.body.split("\n"); + if (!title) { + title = createIssueItem.body || "Agent Output"; + } + const titlePrefix = process.env.GITHUB_AW_ISSUE_TITLE_PREFIX; + if (titlePrefix && !title.startsWith(titlePrefix)) { + title = titlePrefix + title; + } + if (parentIssueNumber) { + core.info("Detected issue context, parent issue #" + parentIssueNumber); + bodyLines.push(`Related to #${parentIssueNumber}`); } - core.info(`Agent output content length: ${outputContent.length}`); - let validatedOutput; + const runId = context.runId; + const runUrl = context.payload.repository + ? `${context.payload.repository.html_url}/actions/runs/${runId}` + : `https://github.com/actions/runs/${runId}`; + bodyLines.push(``, ``, `> Generated by Agentic Workflow [Run](${runUrl})`, ""); + const body = bodyLines.join("\n").trim(); + core.info(`Creating issue with title: ${title}`); + core.info(`Labels: ${labels}`); + core.info(`Body length: ${body.length}`); try { - validatedOutput = JSON.parse(outputContent); - } - catch (error) { - core.setFailed(`Error parsing agent output JSON: ${error instanceof Error ? error.message : String(error)}`); - return; - } - if (!validatedOutput.items || !Array.isArray(validatedOutput.items)) { - core.info("No valid items found in agent output"); - return; - } - const createIssueItems = validatedOutput.items.filter(item => item.type === "create-issue"); - if (createIssueItems.length === 0) { - core.info("No create-issue items found in agent output"); - return; - } - core.info(`Found ${createIssueItems.length} create-issue item(s)`); - if (isStaged) { - let summaryContent = "## 🎭 Staged Mode: Create Issues Preview\n\n"; - summaryContent += "The following issues would be created if staged mode was disabled:\n\n"; - for (let i = 0; i < createIssueItems.length; i++) { - const item = createIssueItems[i]; - summaryContent += `### Issue ${i + 1}\n`; - summaryContent += `**Title:** ${item.title || "No title provided"}\n\n`; - if (item.body) { - summaryContent += `**Body:**\n${item.body}\n\n`; - } - if (item.labels && item.labels.length > 0) { - summaryContent += `**Labels:** ${item.labels.join(", ")}\n\n`; - } - summaryContent += "---\n\n"; - } - await core.summary.addRaw(summaryContent).write(); - core.info("📝 Issue creation preview written to step summary"); - return; - } - const parentIssueNumber = context.payload?.issue?.number; - const labelsEnv = process.env.GITHUB_AW_ISSUE_LABELS; - let envLabels = labelsEnv - ? labelsEnv - .split(",") - .map((label) => label.trim()) - .filter((label) => label) - : []; - const createdIssues = []; - for (let i = 0; i < createIssueItems.length; i++) { - const createIssueItem = createIssueItems[i]; - core.info(`Processing create-issue item ${i + 1}/${createIssueItems.length}: title=${createIssueItem.title}, bodyLength=${createIssueItem.body.length}`); - let labels = [...envLabels]; - if (createIssueItem.labels && Array.isArray(createIssueItem.labels)) { - labels = [...labels, ...createIssueItem.labels]; - } - labels = labels - .filter(label => label != null && label !== false && label !== 0) - .map(label => String(label).trim()) - .filter(label => label) - .map(label => sanitizeLabelContent(label)) - .filter(label => label) - .map(label => (label.length > 64 ? label.substring(0, 64) : label)) - .filter((label, index, arr) => arr.indexOf(label) === index); - let title = createIssueItem.title ? createIssueItem.title.trim() : ""; - let bodyLines = createIssueItem.body.split("\n"); - if (!title) { - title = createIssueItem.body || "Agent Output"; - } - const titlePrefix = process.env.GITHUB_AW_ISSUE_TITLE_PREFIX; - if (titlePrefix && !title.startsWith(titlePrefix)) { - title = titlePrefix + title; - } - if (parentIssueNumber) { - core.info("Detected issue context, parent issue #" + parentIssueNumber); - bodyLines.push(`Related to #${parentIssueNumber}`); - } - const runId = context.runId; - const runUrl = context.payload.repository - ? `${context.payload.repository.html_url}/actions/runs/${runId}` - : `https://github.com/actions/runs/${runId}`; - bodyLines.push(``, ``, `> Generated by Agentic Workflow [Run](${runUrl})`, ""); - const body = bodyLines.join("\n").trim(); - core.info(`Creating issue with title: ${title}`); - core.info(`Labels: ${labels}`); - core.info(`Body length: ${body.length}`); + const { data: issue } = await github.rest.issues.create({ + owner: context.repo.owner, + repo: context.repo.repo, + title: title, + body: body, + labels: labels, + }); + core.info("Created issue #" + issue.number + ": " + issue.html_url); + createdIssues.push(issue); + if (parentIssueNumber) { try { - const { data: issue } = await github.rest.issues.create({ - owner: context.repo.owner, - repo: context.repo.repo, - title: title, - body: body, - labels: labels, - }); - core.info("Created issue #" + issue.number + ": " + issue.html_url); - createdIssues.push(issue); - if (parentIssueNumber) { - try { - await github.rest.issues.createComment({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: parentIssueNumber, - body: `Created related issue: #${issue.number}`, - }); - core.info("Added comment to parent issue #" + parentIssueNumber); - } - catch (error) { - core.info(`Warning: Could not add comment to parent issue: ${error instanceof Error ? error.message : String(error)}`); - } - } - if (i === createIssueItems.length - 1) { - core.setOutput("issue_number", issue.number); - core.setOutput("issue_url", issue.html_url); - } - } - catch (error) { - const errorMessage = error instanceof Error ? error.message : String(error); - if (errorMessage.includes("Issues has been disabled in this repository")) { - core.info(`⚠ Cannot create issue "${title}": Issues are disabled for this repository`); - core.info("Consider enabling issues in repository settings if you want to create issues automatically"); - continue; - } - core.error(`✗ Failed to create issue "${title}": ${errorMessage}`); - throw error; + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: parentIssueNumber, + body: `Created related issue: #${issue.number}`, + }); + core.info("Added comment to parent issue #" + parentIssueNumber); + } catch (error) { + core.info(`Warning: Could not add comment to parent issue: ${error instanceof Error ? error.message : String(error)}`); } + } + if (i === createIssueItems.length - 1) { + core.setOutput("issue_number", issue.number); + core.setOutput("issue_url", issue.html_url); + } + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + if (errorMessage.includes("Issues has been disabled in this repository")) { + core.info(`⚠ Cannot create issue "${title}": Issues are disabled for this repository`); + core.info("Consider enabling issues in repository settings if you want to create issues automatically"); + continue; + } + core.error(`✗ Failed to create issue "${title}": ${errorMessage}`); + throw error; } - if (createdIssues.length > 0) { - let summaryContent = "\n\n## GitHub Issues\n"; - for (const issue of createdIssues) { - summaryContent += `- Issue #${issue.number}: [${issue.title}](${issue.html_url})\n`; - } - await core.summary.addRaw(summaryContent).write(); + } + if (createdIssues.length > 0) { + let summaryContent = "\n\n## GitHub Issues\n"; + for (const issue of createdIssues) { + summaryContent += `- Issue #${issue.number}: [${issue.title}](${issue.html_url})\n`; } - core.info(`Successfully created ${createdIssues.length} issue(s)`); + await core.summary.addRaw(summaryContent).write(); + } + core.info(`Successfully created ${createdIssues.length} issue(s)`); } (async () => { - await main(); + await main(); })(); add_comment: diff --git a/.github/workflows/dev.lock.yml b/.github/workflows/dev.lock.yml index 11214431901..a7465aa55d5 100644 --- a/.github/workflows/dev.lock.yml +++ b/.github/workflows/dev.lock.yml @@ -990,742 +990,742 @@ jobs: with: script: | async function main() { - const fs = require("fs"); - function sanitizeContent(content) { - if (!content || typeof content !== "string") { - return ""; - } - const allowedDomainsEnv = process.env.GITHUB_AW_ALLOWED_DOMAINS; - const defaultAllowedDomains = ["github.com", "github.io", "githubusercontent.com", "githubassets.com", "github.dev", "codespaces.new"]; - const allowedDomains = allowedDomainsEnv - ? allowedDomainsEnv - .split(",") - .map(d => d.trim()) - .filter(d => d) - : defaultAllowedDomains; - let sanitized = content; - sanitized = neutralizeMentions(sanitized); - sanitized = removeXmlComments(sanitized); - sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); - sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); - sanitized = sanitizeUrlProtocols(sanitized); - sanitized = sanitizeUrlDomains(sanitized); - const maxLength = 524288; - if (sanitized.length > maxLength) { - sanitized = sanitized.substring(0, maxLength) + "\n[Content truncated due to length]"; - } - const lines = sanitized.split("\n"); - const maxLines = 65000; - if (lines.length > maxLines) { - sanitized = lines.slice(0, maxLines).join("\n") + "\n[Content truncated due to line count]"; - } - sanitized = neutralizeBotTriggers(sanitized); - return sanitized.trim(); - function sanitizeUrlDomains(s) { - return s.replace(/\bhttps:\/\/[^\s\])}'"<>&\x00-\x1f,;]+/gi, match => { - const urlAfterProtocol = match.slice(8); - const hostname = urlAfterProtocol.split(/[\/:\?#]/)[0].toLowerCase(); - const isAllowed = allowedDomains.some(allowedDomain => { - const normalizedAllowed = allowedDomain.toLowerCase(); - return hostname === normalizedAllowed || hostname.endsWith("." + normalizedAllowed); - }); - return isAllowed ? match : "(redacted)"; - }); - } - function sanitizeUrlProtocols(s) { - return s.replace(/\b(\w+):\/\/[^\s\])}'"<>&\x00-\x1f]+/gi, (match, protocol) => { - return protocol.toLowerCase() === "https" ? match : "(redacted)"; - }); - } - function neutralizeMentions(s) { - return s.replace(/(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, (_m, p1, p2) => `${p1}\`@${p2}\``); - } - function removeXmlComments(s) { - return s.replace(//g, "").replace(//g, ""); - } - function neutralizeBotTriggers(s) { - return s.replace(/\b(fixes?|closes?|resolves?|fix|close|resolve)\s+#(\w+)/gi, (match, action, ref) => `\`${action} #${ref}\``); - } + const fs = require("fs"); + function sanitizeContent(content) { + if (!content || typeof content !== "string") { + return ""; } - function getMaxAllowedForType(itemType, config) { - const itemConfig = config?.[itemType]; - if (itemConfig && typeof itemConfig === "object" && "max" in itemConfig && itemConfig.max) { - return itemConfig.max; - } - switch (itemType) { - case "create-issue": - return 1; - case "add-comment": - return 1; - case "create-pull-request": - return 1; - case "create-pull-request-review-comment": - return 1; - case "add-labels": - return 5; - case "update-issue": - return 1; - case "push-to-pull-request-branch": - return 1; - case "create-discussion": - return 1; - case "missing-tool": - return 1000; - case "create-code-scanning-alert": - return 1000; - case "upload-asset": - return 10; - default: - return 1; - } + const allowedDomainsEnv = process.env.GITHUB_AW_ALLOWED_DOMAINS; + const defaultAllowedDomains = ["github.com", "github.io", "githubusercontent.com", "githubassets.com", "github.dev", "codespaces.new"]; + const allowedDomains = allowedDomainsEnv + ? allowedDomainsEnv + .split(",") + .map(d => d.trim()) + .filter(d => d) + : defaultAllowedDomains; + let sanitized = content; + sanitized = neutralizeMentions(sanitized); + sanitized = removeXmlComments(sanitized); + sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); + sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); + sanitized = sanitizeUrlProtocols(sanitized); + sanitized = sanitizeUrlDomains(sanitized); + const maxLength = 524288; + if (sanitized.length > maxLength) { + sanitized = sanitized.substring(0, maxLength) + "\n[Content truncated due to length]"; } - function getMinRequiredForType(itemType, config) { - const itemConfig = config?.[itemType]; - if (itemConfig && typeof itemConfig === "object" && "min" in itemConfig && itemConfig.min) { - return itemConfig.min; - } - return 0; + const lines = sanitized.split("\n"); + const maxLines = 65000; + if (lines.length > maxLines) { + sanitized = lines.slice(0, maxLines).join("\n") + "\n[Content truncated due to line count]"; } - function repairJson(jsonStr) { - let repaired = jsonStr.trim(); - const _ctrl = { 8: "\\b", 9: "\\t", 10: "\\n", 12: "\\f", 13: "\\r" }; - repaired = repaired.replace(/[\u0000-\u001F]/g, ch => { - const c = ch.charCodeAt(0); - return _ctrl[c] || "\\u" + c.toString(16).padStart(4, "0"); - }); - repaired = repaired.replace(/'/g, '"'); - repaired = repaired.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/g, '$1"$2":'); - repaired = repaired.replace(/"([^"\\]*)"/g, (match, content) => { - if (content.includes("\n") || content.includes("\r") || content.includes("\t")) { - const escaped = content.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"); - return `"${escaped}"`; - } - return match; + sanitized = neutralizeBotTriggers(sanitized); + return sanitized.trim(); + function sanitizeUrlDomains(s) { + return s.replace(/\bhttps:\/\/[^\s\])}'"<>&\x00-\x1f,;]+/gi, match => { + const urlAfterProtocol = match.slice(8); + const hostname = urlAfterProtocol.split(/[\/:\?#]/)[0].toLowerCase(); + const isAllowed = allowedDomains.some(allowedDomain => { + const normalizedAllowed = allowedDomain.toLowerCase(); + return hostname === normalizedAllowed || hostname.endsWith("." + normalizedAllowed); }); - repaired = repaired.replace(/"([^"]*)"([^":,}\]]*)"([^"]*)"(\s*[,:}\]])/g, (match, p1, p2, p3, p4) => `"${p1}\\"${p2}\\"${p3}"${p4}`); - repaired = repaired.replace(/(\[\s*(?:"[^"]*"(?:\s*,\s*"[^"]*")*\s*),?)\s*}/g, "$1]"); - const openBraces = (repaired.match(/\{/g) || []).length; - const closeBraces = (repaired.match(/\}/g) || []).length; - if (openBraces > closeBraces) { - repaired += "}".repeat(openBraces - closeBraces); - } - else if (closeBraces > openBraces) { - repaired = "{".repeat(closeBraces - openBraces) + repaired; - } - const openBrackets = (repaired.match(/\[/g) || []).length; - const closeBrackets = (repaired.match(/\]/g) || []).length; - if (openBrackets > closeBrackets) { - repaired += "]".repeat(openBrackets - closeBrackets); - } - else if (closeBrackets > openBrackets) { - repaired = "[".repeat(closeBrackets - openBrackets) + repaired; - } - repaired = repaired.replace(/,(\s*[}\]])/g, "$1"); - return repaired; + return isAllowed ? match : "(redacted)"; + }); } - function validatePositiveInteger(value, fieldName, lineNum) { - if (value === undefined || value === null) { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} is required`, - }; - } - if (typeof value !== "number" && typeof value !== "string") { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number or string field`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; - } - const parsed = typeof value === "string" ? parseInt(value, 10) : value; - if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'line' must be a valid positive integer (got: ${value})`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'line' must be a positive integer`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, - }; - } - return { isValid: true, normalizedValue: parsed }; + function sanitizeUrlProtocols(s) { + return s.replace(/\b(\w+):\/\/[^\s\])}'"<>&\x00-\x1f]+/gi, (match, protocol) => { + return protocol.toLowerCase() === "https" ? match : "(redacted)"; + }); } - function validateOptionalPositiveInteger(value, fieldName, lineNum) { - if (value === undefined) { - return { isValid: true }; - } - if (typeof value !== "number" && typeof value !== "string") { - if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a number or string`, - }; - } - if (fieldName.includes("create-code-scanning-alert 'column'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a number or string`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; - } - const parsed = typeof value === "string" ? parseInt(value, 10) : value; - if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { - if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a positive integer`, - }; - } - if (fieldName.includes("create-code-scanning-alert 'column'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a valid positive integer (got: ${value})`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, - }; - } - return { isValid: true, normalizedValue: parsed }; + function neutralizeMentions(s) { + return s.replace( + /(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, + (_m, p1, p2) => `${p1}\`@${p2}\`` + ); } - function validateIssueOrPRNumber(value, fieldName, lineNum) { - if (value === undefined) { - return { isValid: true }; - } - if (typeof value !== "number" && typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; - } - return { isValid: true }; + function removeXmlComments(s) { + return s.replace(//g, "").replace(//g, ""); } - function validateFieldWithInputSchema(value, fieldName, inputSchema, lineNum) { - if (inputSchema.required && (value === undefined || value === null)) { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} is required`, - }; - } - if (value === undefined || value === null) { - return { - isValid: true, - normalizedValue: inputSchema.default || undefined, - }; - } - const inputType = inputSchema.type || "string"; - let normalizedValue = value; - switch (inputType) { - case "string": - if (typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a string`, - }; - } - normalizedValue = sanitizeContent(value); - break; - case "boolean": - if (typeof value !== "boolean") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a boolean`, - }; - } - break; - case "number": - if (typeof value !== "number") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number`, - }; - } - break; - case "choice": - if (typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a string for choice type`, - }; - } - if (inputSchema.options && !inputSchema.options.includes(value)) { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be one of: ${inputSchema.options.join(", ")}`, - }; - } - normalizedValue = sanitizeContent(value); - break; - default: - if (typeof value === "string") { - normalizedValue = sanitizeContent(value); - } - break; - } + function neutralizeBotTriggers(s) { + return s.replace(/\b(fixes?|closes?|resolves?|fix|close|resolve)\s+#(\w+)/gi, (match, action, ref) => `\`${action} #${ref}\``); + } + } + function getMaxAllowedForType(itemType, config) { + const itemConfig = config?.[itemType]; + if (itemConfig && typeof itemConfig === "object" && "max" in itemConfig && itemConfig.max) { + return itemConfig.max; + } + switch (itemType) { + case "create-issue": + return 1; + case "add-comment": + return 1; + case "create-pull-request": + return 1; + case "create-pull-request-review-comment": + return 1; + case "add-labels": + return 5; + case "update-issue": + return 1; + case "push-to-pull-request-branch": + return 1; + case "create-discussion": + return 1; + case "missing-tool": + return 1000; + case "create-code-scanning-alert": + return 1000; + case "upload-asset": + return 10; + default: + return 1; + } + } + function getMinRequiredForType(itemType, config) { + const itemConfig = config?.[itemType]; + if (itemConfig && typeof itemConfig === "object" && "min" in itemConfig && itemConfig.min) { + return itemConfig.min; + } + return 0; + } + function repairJson(jsonStr) { + let repaired = jsonStr.trim(); + const _ctrl = { 8: "\\b", 9: "\\t", 10: "\\n", 12: "\\f", 13: "\\r" }; + repaired = repaired.replace(/[\u0000-\u001F]/g, ch => { + const c = ch.charCodeAt(0); + return _ctrl[c] || "\\u" + c.toString(16).padStart(4, "0"); + }); + repaired = repaired.replace(/'/g, '"'); + repaired = repaired.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/g, '$1"$2":'); + repaired = repaired.replace(/"([^"\\]*)"/g, (match, content) => { + if (content.includes("\n") || content.includes("\r") || content.includes("\t")) { + const escaped = content.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"); + return `"${escaped}"`; + } + return match; + }); + repaired = repaired.replace(/"([^"]*)"([^":,}\]]*)"([^"]*)"(\s*[,:}\]])/g, (match, p1, p2, p3, p4) => `"${p1}\\"${p2}\\"${p3}"${p4}`); + repaired = repaired.replace(/(\[\s*(?:"[^"]*"(?:\s*,\s*"[^"]*")*\s*),?)\s*}/g, "$1]"); + const openBraces = (repaired.match(/\{/g) || []).length; + const closeBraces = (repaired.match(/\}/g) || []).length; + if (openBraces > closeBraces) { + repaired += "}".repeat(openBraces - closeBraces); + } else if (closeBraces > openBraces) { + repaired = "{".repeat(closeBraces - openBraces) + repaired; + } + const openBrackets = (repaired.match(/\[/g) || []).length; + const closeBrackets = (repaired.match(/\]/g) || []).length; + if (openBrackets > closeBrackets) { + repaired += "]".repeat(openBrackets - closeBrackets); + } else if (closeBrackets > openBrackets) { + repaired = "[".repeat(closeBrackets - openBrackets) + repaired; + } + repaired = repaired.replace(/,(\s*[}\]])/g, "$1"); + return repaired; + } + function validatePositiveInteger(value, fieldName, lineNum) { + if (value === undefined || value === null) { + if (fieldName.includes("create-code-scanning-alert 'line'")) { return { - isValid: true, - normalizedValue, + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} is required`, + }; } - function validateItemWithSafeJobConfig(item, jobConfig, lineNum) { - const errors = []; - const normalizedItem = { ...item }; - if (!jobConfig.inputs) { - return { - isValid: true, - errors: [], - normalizedItem: item, - }; - } - for (const [fieldName, inputSchema] of Object.entries(jobConfig.inputs)) { - const fieldValue = item[fieldName]; - const validation = validateFieldWithInputSchema(fieldValue, fieldName, inputSchema, lineNum); - if (!validation.isValid && validation.error) { - errors.push(validation.error); - } - else if (validation.normalizedValue !== undefined) { - normalizedItem[fieldName] = validation.normalizedValue; - } - } + if (typeof value !== "number" && typeof value !== "string") { + if (fieldName.includes("create-code-scanning-alert 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, + }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { return { - isValid: errors.length === 0, - errors, - normalizedItem, + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number or string field`, }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; } - function parseJsonWithRepair(jsonStr) { - try { - return JSON.parse(jsonStr); - } - catch (originalError) { - try { - const repairedJson = repairJson(jsonStr); - return JSON.parse(repairedJson); - } - catch (repairError) { - core.info(`invalid input json: ${jsonStr}`); - const originalMsg = originalError instanceof Error ? originalError.message : String(originalError); - const repairMsg = repairError instanceof Error ? repairError.message : String(repairError); - throw new Error(`JSON parsing failed. Original: ${originalMsg}. After attempted repair: ${repairMsg}`); - } - } + const parsed = typeof value === "string" ? parseInt(value, 10) : value; + if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { + if (fieldName.includes("create-code-scanning-alert 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'line' must be a valid positive integer (got: ${value})`, + }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'line' must be a positive integer`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, + }; } - const outputFile = process.env.GITHUB_AW_SAFE_OUTPUTS; - const safeOutputsConfig = process.env.GITHUB_AW_SAFE_OUTPUTS_CONFIG; - if (!outputFile) { - core.info("GITHUB_AW_SAFE_OUTPUTS not set, no output to collect"); - core.setOutput("output", ""); - return; + return { isValid: true, normalizedValue: parsed }; + } + function validateOptionalPositiveInteger(value, fieldName, lineNum) { + if (value === undefined) { + return { isValid: true }; } - if (!fs.existsSync(outputFile)) { - core.info(`Output file does not exist: ${outputFile}`); - core.setOutput("output", ""); - return; + if (typeof value !== "number" && typeof value !== "string") { + if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a number or string`, + }; + } + if (fieldName.includes("create-code-scanning-alert 'column'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a number or string`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; } - const outputContent = fs.readFileSync(outputFile, "utf8"); - if (outputContent.trim() === "") { - core.info("Output file is empty"); + const parsed = typeof value === "string" ? parseInt(value, 10) : value; + if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { + if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a positive integer`, + }; + } + if (fieldName.includes("create-code-scanning-alert 'column'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a valid positive integer (got: ${value})`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, + }; } - core.info(`Raw output content length: ${outputContent.length}`); - let expectedOutputTypes = {}; - if (safeOutputsConfig) { - try { - expectedOutputTypes = JSON.parse(safeOutputsConfig); - core.info(`Expected output types: ${JSON.stringify(Object.keys(expectedOutputTypes))}`); + return { isValid: true, normalizedValue: parsed }; + } + function validateIssueOrPRNumber(value, fieldName, lineNum) { + if (value === undefined) { + return { isValid: true }; + } + if (typeof value !== "number" && typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; + } + return { isValid: true }; + } + function validateFieldWithInputSchema(value, fieldName, inputSchema, lineNum) { + if (inputSchema.required && (value === undefined || value === null)) { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} is required`, + }; + } + if (value === undefined || value === null) { + return { + isValid: true, + normalizedValue: inputSchema.default || undefined, + }; + } + const inputType = inputSchema.type || "string"; + let normalizedValue = value; + switch (inputType) { + case "string": + if (typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a string`, + }; } - catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.info(`Warning: Could not parse safe-outputs config: ${errorMsg}`); + normalizedValue = sanitizeContent(value); + break; + case "boolean": + if (typeof value !== "boolean") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a boolean`, + }; } - } - const lines = outputContent.trim().split("\n"); - const parsedItems = []; - const errors = []; - for (let i = 0; i < lines.length; i++) { - const line = lines[i].trim(); - if (line === "") - continue; - try { - const item = parseJsonWithRepair(line); - if (item === undefined) { - errors.push(`Line ${i + 1}: Invalid JSON - JSON parsing failed`); - continue; - } - if (!item.type) { - errors.push(`Line ${i + 1}: Missing required 'type' field`); - continue; - } - const itemType = item.type; - if (!expectedOutputTypes[itemType]) { - errors.push(`Line ${i + 1}: Unexpected output type '${itemType}'. Expected one of: ${Object.keys(expectedOutputTypes).join(", ")}`); - continue; - } - const typeCount = parsedItems.filter(existing => existing.type === itemType).length; - const maxAllowed = getMaxAllowedForType(itemType, expectedOutputTypes); - if (typeCount >= maxAllowed) { - errors.push(`Line ${i + 1}: Too many items of type '${itemType}'. Maximum allowed: ${maxAllowed}.`); - continue; - } - core.info(`Line ${i + 1}: type '${itemType}'`); - switch (itemType) { - case "create-issue": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_issue requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_issue requires a 'body' string field`); - continue; - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - if (item.labels && Array.isArray(item.labels)) { - item.labels = item.labels.map((label) => (typeof label === "string" ? sanitizeContent(label) : label)); - } - break; - case "add-comment": - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: add_comment requires a 'body' string field`); - continue; - } - const issueNumValidation = validateIssueOrPRNumber(item.issue_number, "add_comment 'issue_number'", i + 1); - if (!issueNumValidation.isValid) { - if (issueNumValidation.error) - errors.push(issueNumValidation.error); - continue; - } - item.body = sanitizeContent(item.body); - break; - case "create-pull-request": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'body' string field`); - continue; - } - if (!item.branch || typeof item.branch !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'branch' string field`); - continue; - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - item.branch = sanitizeContent(item.branch); - if (item.labels && Array.isArray(item.labels)) { - item.labels = item.labels.map((label) => (typeof label === "string" ? sanitizeContent(label) : label)); - } - break; - case "add-labels": - if (!item.labels || !Array.isArray(item.labels)) { - errors.push(`Line ${i + 1}: add_labels requires a 'labels' array field`); - continue; - } - if (item.labels.some((label) => typeof label !== "string")) { - errors.push(`Line ${i + 1}: add_labels labels array must contain only strings`); - continue; - } - const labelsIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "add-labels 'issue_number'", i + 1); - if (!labelsIssueNumValidation.isValid) { - if (labelsIssueNumValidation.error) - errors.push(labelsIssueNumValidation.error); - continue; - } - item.labels = item.labels.map((label) => sanitizeContent(label)); - break; - case "update-issue": - const hasValidField = item.status !== undefined || item.title !== undefined || item.body !== undefined; - if (!hasValidField) { - errors.push(`Line ${i + 1}: update_issue requires at least one of: 'status', 'title', or 'body' fields`); - continue; - } - if (item.status !== undefined) { - if (typeof item.status !== "string" || (item.status !== "open" && item.status !== "closed")) { - errors.push(`Line ${i + 1}: update_issue 'status' must be 'open' or 'closed'`); - continue; - } - } - if (item.title !== undefined) { - if (typeof item.title !== "string") { - errors.push(`Line ${i + 1}: update-issue 'title' must be a string`); - continue; - } - item.title = sanitizeContent(item.title); - } - if (item.body !== undefined) { - if (typeof item.body !== "string") { - errors.push(`Line ${i + 1}: update-issue 'body' must be a string`); - continue; - } - item.body = sanitizeContent(item.body); - } - const updateIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "update-issue 'issue_number'", i + 1); - if (!updateIssueNumValidation.isValid) { - if (updateIssueNumValidation.error) - errors.push(updateIssueNumValidation.error); - continue; - } - break; - case "push-to-pull-request-branch": - if (!item.branch || typeof item.branch !== "string") { - errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'branch' string field`); - continue; - } - if (!item.message || typeof item.message !== "string") { - errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'message' string field`); - continue; - } - item.branch = sanitizeContent(item.branch); - item.message = sanitizeContent(item.message); - const pushPRNumValidation = validateIssueOrPRNumber(item.pull_request_number, "push-to-pull-request-branch 'pull_request_number'", i + 1); - if (!pushPRNumValidation.isValid) { - if (pushPRNumValidation.error) - errors.push(pushPRNumValidation.error); - continue; - } - break; - case "create-pull-request-review-comment": - if (!item.path || typeof item.path !== "string") { - errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'path' string field`); - continue; - } - const lineValidation = validatePositiveInteger(item.line, "create-pull-request-review-comment 'line'", i + 1); - if (!lineValidation.isValid) { - if (lineValidation.error) - errors.push(lineValidation.error); - continue; - } - const lineNumber = lineValidation.normalizedValue; - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'body' string field`); - continue; - } - item.body = sanitizeContent(item.body); - const startLineValidation = validateOptionalPositiveInteger(item.start_line, "create-pull-request-review-comment 'start_line'", i + 1); - if (!startLineValidation.isValid) { - if (startLineValidation.error) - errors.push(startLineValidation.error); - continue; - } - if (startLineValidation.normalizedValue !== undefined && - lineNumber !== undefined && - startLineValidation.normalizedValue > lineNumber) { - errors.push(`Line ${i + 1}: create-pull-request-review-comment 'start_line' must be less than or equal to 'line'`); - continue; - } - if (item.side !== undefined) { - if (typeof item.side !== "string" || (item.side !== "LEFT" && item.side !== "RIGHT")) { - errors.push(`Line ${i + 1}: create-pull-request-review-comment 'side' must be 'LEFT' or 'RIGHT'`); - continue; - } - } - break; - case "create-discussion": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_discussion requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_discussion requires a 'body' string field`); - continue; - } - if (item.category !== undefined) { - if (typeof item.category !== "string") { - errors.push(`Line ${i + 1}: create_discussion 'category' must be a string`); - continue; - } - item.category = sanitizeContent(item.category); - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - break; - case "missing-tool": - if (!item.tool || typeof item.tool !== "string") { - errors.push(`Line ${i + 1}: missing_tool requires a 'tool' string field`); - continue; - } - if (!item.reason || typeof item.reason !== "string") { - errors.push(`Line ${i + 1}: missing_tool requires a 'reason' string field`); - continue; - } - item.tool = sanitizeContent(item.tool); - item.reason = sanitizeContent(item.reason); - if (item.alternatives !== undefined) { - if (typeof item.alternatives !== "string") { - errors.push(`Line ${i + 1}: missing-tool 'alternatives' must be a string`); - continue; - } - item.alternatives = sanitizeContent(item.alternatives); - } - break; - case "upload-asset": - if (!item.path || typeof item.path !== "string") { - errors.push(`Line ${i + 1}: upload_asset requires a 'path' string field`); - continue; - } - break; - case "create-code-scanning-alert": - if (!item.file || typeof item.file !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'file' field (string)`); - continue; - } - const alertLineValidation = validatePositiveInteger(item.line, "create-code-scanning-alert 'line'", i + 1); - if (!alertLineValidation.isValid) { - if (alertLineValidation.error) { - errors.push(alertLineValidation.error); - } - continue; - } - if (!item.severity || typeof item.severity !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'severity' field (string)`); - continue; - } - if (!item.message || typeof item.message !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'message' field (string)`); - continue; - } - const allowedSeverities = ["error", "warning", "info", "note"]; - if (!allowedSeverities.includes(item.severity.toLowerCase())) { - errors.push(`Line ${i + 1}: create-code-scanning-alert 'severity' must be one of: ${allowedSeverities.join(", ")}, got ${item.severity.toLowerCase()}`); - continue; - } - const columnValidation = validateOptionalPositiveInteger(item.column, "create-code-scanning-alert 'column'", i + 1); - if (!columnValidation.isValid) { - if (columnValidation.error) - errors.push(columnValidation.error); - continue; - } - if (item.ruleIdSuffix !== undefined) { - if (typeof item.ruleIdSuffix !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must be a string`); - continue; - } - if (!/^[a-zA-Z0-9_-]+$/.test(item.ruleIdSuffix.trim())) { - errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must contain only alphanumeric characters, hyphens, and underscores`); - continue; - } - } - item.severity = item.severity.toLowerCase(); - item.file = sanitizeContent(item.file); - item.severity = sanitizeContent(item.severity); - item.message = sanitizeContent(item.message); - if (item.ruleIdSuffix) { - item.ruleIdSuffix = sanitizeContent(item.ruleIdSuffix); - } - break; - default: - const jobOutputType = expectedOutputTypes[itemType]; - if (!jobOutputType) { - errors.push(`Line ${i + 1}: Unknown output type '${itemType}'`); - continue; - } - const safeJobConfig = jobOutputType; - if (safeJobConfig && safeJobConfig.inputs) { - const validation = validateItemWithSafeJobConfig(item, safeJobConfig, i + 1); - if (!validation.isValid) { - errors.push(...validation.errors); - continue; - } - Object.assign(item, validation.normalizedItem); - } - break; - } - core.info(`Line ${i + 1}: Valid ${itemType} item`); - parsedItems.push(item); + break; + case "number": + if (typeof value !== "number") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number`, + }; } - catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - errors.push(`Line ${i + 1}: Invalid JSON - ${errorMsg}`); + break; + case "choice": + if (typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a string for choice type`, + }; } - } - if (errors.length > 0) { - core.warning("Validation errors found:"); - errors.forEach(error => core.warning(` - ${error}`)); - if (parsedItems.length === 0) { - core.setFailed(errors.map(e => ` - ${e}`).join("\n")); - return; + if (inputSchema.options && !inputSchema.options.includes(value)) { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be one of: ${inputSchema.options.join(", ")}`, + }; } - } - for (const itemType of Object.keys(expectedOutputTypes)) { - const minRequired = getMinRequiredForType(itemType, expectedOutputTypes); - if (minRequired > 0) { - const actualCount = parsedItems.filter(item => item.type === itemType).length; - if (actualCount < minRequired) { - errors.push(`Too few items of type '${itemType}'. Minimum required: ${minRequired}, found: ${actualCount}.`); - } + normalizedValue = sanitizeContent(value); + break; + default: + if (typeof value === "string") { + normalizedValue = sanitizeContent(value); } + break; } - core.info(`Successfully parsed ${parsedItems.length} valid output items`); - const validatedOutput = { - items: parsedItems, - errors: errors, + return { + isValid: true, + normalizedValue, }; - const agentOutputFile = "/tmp/agent_output.json"; - const validatedOutputJson = JSON.stringify(validatedOutput); + } + function validateItemWithSafeJobConfig(item, jobConfig, lineNum) { + const errors = []; + const normalizedItem = { ...item }; + if (!jobConfig.inputs) { + return { + isValid: true, + errors: [], + normalizedItem: item, + }; + } + for (const [fieldName, inputSchema] of Object.entries(jobConfig.inputs)) { + const fieldValue = item[fieldName]; + const validation = validateFieldWithInputSchema(fieldValue, fieldName, inputSchema, lineNum); + if (!validation.isValid && validation.error) { + errors.push(validation.error); + } else if (validation.normalizedValue !== undefined) { + normalizedItem[fieldName] = validation.normalizedValue; + } + } + return { + isValid: errors.length === 0, + errors, + normalizedItem, + }; + } + function parseJsonWithRepair(jsonStr) { try { - fs.mkdirSync("/tmp", { recursive: true }); - fs.writeFileSync(agentOutputFile, validatedOutputJson, "utf8"); - core.info(`Stored validated output to: ${agentOutputFile}`); - core.exportVariable("GITHUB_AW_AGENT_OUTPUT", agentOutputFile); + return JSON.parse(jsonStr); + } catch (originalError) { + try { + const repairedJson = repairJson(jsonStr); + return JSON.parse(repairedJson); + } catch (repairError) { + core.info(`invalid input json: ${jsonStr}`); + const originalMsg = originalError instanceof Error ? originalError.message : String(originalError); + const repairMsg = repairError instanceof Error ? repairError.message : String(repairError); + throw new Error(`JSON parsing failed. Original: ${originalMsg}. After attempted repair: ${repairMsg}`); + } } - catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.error(`Failed to write agent output file: ${errorMsg}`); + } + const outputFile = process.env.GITHUB_AW_SAFE_OUTPUTS; + const safeOutputsConfig = process.env.GITHUB_AW_SAFE_OUTPUTS_CONFIG; + if (!outputFile) { + core.info("GITHUB_AW_SAFE_OUTPUTS not set, no output to collect"); + core.setOutput("output", ""); + return; + } + if (!fs.existsSync(outputFile)) { + core.info(`Output file does not exist: ${outputFile}`); + core.setOutput("output", ""); + return; + } + const outputContent = fs.readFileSync(outputFile, "utf8"); + if (outputContent.trim() === "") { + core.info("Output file is empty"); + } + core.info(`Raw output content length: ${outputContent.length}`); + let expectedOutputTypes = {}; + if (safeOutputsConfig) { + try { + expectedOutputTypes = JSON.parse(safeOutputsConfig); + core.info(`Expected output types: ${JSON.stringify(Object.keys(expectedOutputTypes))}`); + } catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.info(`Warning: Could not parse safe-outputs config: ${errorMsg}`); } - core.setOutput("output", JSON.stringify(validatedOutput)); - core.setOutput("raw_output", outputContent); - const outputTypes = Array.from(new Set(parsedItems.map(item => item.type))); - core.info(`output_types: ${outputTypes.join(", ")}`); - core.setOutput("output_types", outputTypes.join(",")); + } + const lines = outputContent.trim().split("\n"); + const parsedItems = []; + const errors = []; + for (let i = 0; i < lines.length; i++) { + const line = lines[i].trim(); + if (line === "") continue; try { - await core.summary - .addRaw("## Processed Output\n\n") - .addRaw("```json\n") - .addRaw(JSON.stringify(validatedOutput)) - .addRaw("\n```\n") - .write(); - core.info("Successfully wrote processed output to step summary"); + const item = parseJsonWithRepair(line); + if (item === undefined) { + errors.push(`Line ${i + 1}: Invalid JSON - JSON parsing failed`); + continue; + } + if (!item.type) { + errors.push(`Line ${i + 1}: Missing required 'type' field`); + continue; + } + const itemType = item.type; + if (!expectedOutputTypes[itemType]) { + errors.push(`Line ${i + 1}: Unexpected output type '${itemType}'. Expected one of: ${Object.keys(expectedOutputTypes).join(", ")}`); + continue; + } + const typeCount = parsedItems.filter(existing => existing.type === itemType).length; + const maxAllowed = getMaxAllowedForType(itemType, expectedOutputTypes); + if (typeCount >= maxAllowed) { + errors.push(`Line ${i + 1}: Too many items of type '${itemType}'. Maximum allowed: ${maxAllowed}.`); + continue; + } + core.info(`Line ${i + 1}: type '${itemType}'`); + switch (itemType) { + case "create-issue": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_issue requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_issue requires a 'body' string field`); + continue; + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + if (item.labels && Array.isArray(item.labels)) { + item.labels = item.labels.map(label => (typeof label === "string" ? sanitizeContent(label) : label)); + } + break; + case "add-comment": + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: add_comment requires a 'body' string field`); + continue; + } + const issueNumValidation = validateIssueOrPRNumber(item.issue_number, "add_comment 'issue_number'", i + 1); + if (!issueNumValidation.isValid) { + if (issueNumValidation.error) errors.push(issueNumValidation.error); + continue; + } + item.body = sanitizeContent(item.body); + break; + case "create-pull-request": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'body' string field`); + continue; + } + if (!item.branch || typeof item.branch !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'branch' string field`); + continue; + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + item.branch = sanitizeContent(item.branch); + if (item.labels && Array.isArray(item.labels)) { + item.labels = item.labels.map(label => (typeof label === "string" ? sanitizeContent(label) : label)); + } + break; + case "add-labels": + if (!item.labels || !Array.isArray(item.labels)) { + errors.push(`Line ${i + 1}: add_labels requires a 'labels' array field`); + continue; + } + if (item.labels.some(label => typeof label !== "string")) { + errors.push(`Line ${i + 1}: add_labels labels array must contain only strings`); + continue; + } + const labelsIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "add-labels 'issue_number'", i + 1); + if (!labelsIssueNumValidation.isValid) { + if (labelsIssueNumValidation.error) errors.push(labelsIssueNumValidation.error); + continue; + } + item.labels = item.labels.map(label => sanitizeContent(label)); + break; + case "update-issue": + const hasValidField = item.status !== undefined || item.title !== undefined || item.body !== undefined; + if (!hasValidField) { + errors.push(`Line ${i + 1}: update_issue requires at least one of: 'status', 'title', or 'body' fields`); + continue; + } + if (item.status !== undefined) { + if (typeof item.status !== "string" || (item.status !== "open" && item.status !== "closed")) { + errors.push(`Line ${i + 1}: update_issue 'status' must be 'open' or 'closed'`); + continue; + } + } + if (item.title !== undefined) { + if (typeof item.title !== "string") { + errors.push(`Line ${i + 1}: update-issue 'title' must be a string`); + continue; + } + item.title = sanitizeContent(item.title); + } + if (item.body !== undefined) { + if (typeof item.body !== "string") { + errors.push(`Line ${i + 1}: update-issue 'body' must be a string`); + continue; + } + item.body = sanitizeContent(item.body); + } + const updateIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "update-issue 'issue_number'", i + 1); + if (!updateIssueNumValidation.isValid) { + if (updateIssueNumValidation.error) errors.push(updateIssueNumValidation.error); + continue; + } + break; + case "push-to-pull-request-branch": + if (!item.branch || typeof item.branch !== "string") { + errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'branch' string field`); + continue; + } + if (!item.message || typeof item.message !== "string") { + errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'message' string field`); + continue; + } + item.branch = sanitizeContent(item.branch); + item.message = sanitizeContent(item.message); + const pushPRNumValidation = validateIssueOrPRNumber( + item.pull_request_number, + "push-to-pull-request-branch 'pull_request_number'", + i + 1 + ); + if (!pushPRNumValidation.isValid) { + if (pushPRNumValidation.error) errors.push(pushPRNumValidation.error); + continue; + } + break; + case "create-pull-request-review-comment": + if (!item.path || typeof item.path !== "string") { + errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'path' string field`); + continue; + } + const lineValidation = validatePositiveInteger(item.line, "create-pull-request-review-comment 'line'", i + 1); + if (!lineValidation.isValid) { + if (lineValidation.error) errors.push(lineValidation.error); + continue; + } + const lineNumber = lineValidation.normalizedValue; + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'body' string field`); + continue; + } + item.body = sanitizeContent(item.body); + const startLineValidation = validateOptionalPositiveInteger( + item.start_line, + "create-pull-request-review-comment 'start_line'", + i + 1 + ); + if (!startLineValidation.isValid) { + if (startLineValidation.error) errors.push(startLineValidation.error); + continue; + } + if ( + startLineValidation.normalizedValue !== undefined && + lineNumber !== undefined && + startLineValidation.normalizedValue > lineNumber + ) { + errors.push(`Line ${i + 1}: create-pull-request-review-comment 'start_line' must be less than or equal to 'line'`); + continue; + } + if (item.side !== undefined) { + if (typeof item.side !== "string" || (item.side !== "LEFT" && item.side !== "RIGHT")) { + errors.push(`Line ${i + 1}: create-pull-request-review-comment 'side' must be 'LEFT' or 'RIGHT'`); + continue; + } + } + break; + case "create-discussion": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_discussion requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_discussion requires a 'body' string field`); + continue; + } + if (item.category !== undefined) { + if (typeof item.category !== "string") { + errors.push(`Line ${i + 1}: create_discussion 'category' must be a string`); + continue; + } + item.category = sanitizeContent(item.category); + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + break; + case "missing-tool": + if (!item.tool || typeof item.tool !== "string") { + errors.push(`Line ${i + 1}: missing_tool requires a 'tool' string field`); + continue; + } + if (!item.reason || typeof item.reason !== "string") { + errors.push(`Line ${i + 1}: missing_tool requires a 'reason' string field`); + continue; + } + item.tool = sanitizeContent(item.tool); + item.reason = sanitizeContent(item.reason); + if (item.alternatives !== undefined) { + if (typeof item.alternatives !== "string") { + errors.push(`Line ${i + 1}: missing-tool 'alternatives' must be a string`); + continue; + } + item.alternatives = sanitizeContent(item.alternatives); + } + break; + case "upload-asset": + if (!item.path || typeof item.path !== "string") { + errors.push(`Line ${i + 1}: upload_asset requires a 'path' string field`); + continue; + } + break; + case "create-code-scanning-alert": + if (!item.file || typeof item.file !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'file' field (string)`); + continue; + } + const alertLineValidation = validatePositiveInteger(item.line, "create-code-scanning-alert 'line'", i + 1); + if (!alertLineValidation.isValid) { + if (alertLineValidation.error) { + errors.push(alertLineValidation.error); + } + continue; + } + if (!item.severity || typeof item.severity !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'severity' field (string)`); + continue; + } + if (!item.message || typeof item.message !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'message' field (string)`); + continue; + } + const allowedSeverities = ["error", "warning", "info", "note"]; + if (!allowedSeverities.includes(item.severity.toLowerCase())) { + errors.push( + `Line ${i + 1}: create-code-scanning-alert 'severity' must be one of: ${allowedSeverities.join(", ")}, got ${item.severity.toLowerCase()}` + ); + continue; + } + const columnValidation = validateOptionalPositiveInteger(item.column, "create-code-scanning-alert 'column'", i + 1); + if (!columnValidation.isValid) { + if (columnValidation.error) errors.push(columnValidation.error); + continue; + } + if (item.ruleIdSuffix !== undefined) { + if (typeof item.ruleIdSuffix !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must be a string`); + continue; + } + if (!/^[a-zA-Z0-9_-]+$/.test(item.ruleIdSuffix.trim())) { + errors.push( + `Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must contain only alphanumeric characters, hyphens, and underscores` + ); + continue; + } + } + item.severity = item.severity.toLowerCase(); + item.file = sanitizeContent(item.file); + item.severity = sanitizeContent(item.severity); + item.message = sanitizeContent(item.message); + if (item.ruleIdSuffix) { + item.ruleIdSuffix = sanitizeContent(item.ruleIdSuffix); + } + break; + default: + const jobOutputType = expectedOutputTypes[itemType]; + if (!jobOutputType) { + errors.push(`Line ${i + 1}: Unknown output type '${itemType}'`); + continue; + } + const safeJobConfig = jobOutputType; + if (safeJobConfig && safeJobConfig.inputs) { + const validation = validateItemWithSafeJobConfig(item, safeJobConfig, i + 1); + if (!validation.isValid) { + errors.push(...validation.errors); + continue; + } + Object.assign(item, validation.normalizedItem); + } + break; + } + core.info(`Line ${i + 1}: Valid ${itemType} item`); + parsedItems.push(item); + } catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + errors.push(`Line ${i + 1}: Invalid JSON - ${errorMsg}`); } - catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.warning(`Failed to write to step summary: ${errorMsg}`); + } + if (errors.length > 0) { + core.warning("Validation errors found:"); + errors.forEach(error => core.warning(` - ${error}`)); + if (parsedItems.length === 0) { + core.setFailed(errors.map(e => ` - ${e}`).join("\n")); + return; + } + } + for (const itemType of Object.keys(expectedOutputTypes)) { + const minRequired = getMinRequiredForType(itemType, expectedOutputTypes); + if (minRequired > 0) { + const actualCount = parsedItems.filter(item => item.type === itemType).length; + if (actualCount < minRequired) { + errors.push(`Too few items of type '${itemType}'. Minimum required: ${minRequired}, found: ${actualCount}.`); + } } + } + core.info(`Successfully parsed ${parsedItems.length} valid output items`); + const validatedOutput = { + items: parsedItems, + errors: errors, + }; + const agentOutputFile = "/tmp/agent_output.json"; + const validatedOutputJson = JSON.stringify(validatedOutput); + try { + fs.mkdirSync("/tmp", { recursive: true }); + fs.writeFileSync(agentOutputFile, validatedOutputJson, "utf8"); + core.info(`Stored validated output to: ${agentOutputFile}`); + core.exportVariable("GITHUB_AW_AGENT_OUTPUT", agentOutputFile); + } catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.error(`Failed to write agent output file: ${errorMsg}`); + } + core.setOutput("output", JSON.stringify(validatedOutput)); + core.setOutput("raw_output", outputContent); + const outputTypes = Array.from(new Set(parsedItems.map(item => item.type))); + core.info(`output_types: ${outputTypes.join(", ")}`); + core.setOutput("output_types", outputTypes.join(",")); + try { + await core.summary + .addRaw("## Processed Output\n\n") + .addRaw("```json\n") + .addRaw(JSON.stringify(validatedOutput)) + .addRaw("\n```\n") + .write(); + core.info("Successfully wrote processed output to step summary"); + } catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.warning(`Failed to write to step summary: ${errorMsg}`); + } } await main(); - name: Upload sanitized agent output @@ -1999,162 +1999,164 @@ jobs: with: script: | function sanitizeLabelContent(content) { - if (!content || typeof content !== "string") { - return ""; - } - let sanitized = content.trim(); - sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); - sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); - sanitized = sanitized.replace(/(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, (_m, p1, p2) => `${p1}\`@${p2}\``); - sanitized = sanitized.replace(/[<>&'"]/g, ""); - return sanitized.trim(); + if (!content || typeof content !== "string") { + return ""; + } + let sanitized = content.trim(); + sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); + sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); + sanitized = sanitized.replace( + /(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, + (_m, p1, p2) => `${p1}\`@${p2}\`` + ); + sanitized = sanitized.replace(/[<>&'"]/g, ""); + return sanitized.trim(); } async function main() { - const isStaged = process.env.GITHUB_AW_SAFE_OUTPUTS_STAGED === "true"; - const outputContent = process.env.GITHUB_AW_AGENT_OUTPUT; - if (!outputContent) { - core.info("No GITHUB_AW_AGENT_OUTPUT environment variable found"); - return; - } - if (outputContent.trim() === "") { - core.info("Agent output content is empty"); - return; - } - core.info(`Agent output content length: ${outputContent.length}`); - let validatedOutput; - try { - validatedOutput = JSON.parse(outputContent); + const isStaged = process.env.GITHUB_AW_SAFE_OUTPUTS_STAGED === "true"; + const outputContent = process.env.GITHUB_AW_AGENT_OUTPUT; + if (!outputContent) { + core.info("No GITHUB_AW_AGENT_OUTPUT environment variable found"); + return; + } + if (outputContent.trim() === "") { + core.info("Agent output content is empty"); + return; + } + core.info(`Agent output content length: ${outputContent.length}`); + let validatedOutput; + try { + validatedOutput = JSON.parse(outputContent); + } catch (error) { + core.setFailed(`Error parsing agent output JSON: ${error instanceof Error ? error.message : String(error)}`); + return; + } + if (!validatedOutput.items || !Array.isArray(validatedOutput.items)) { + core.info("No valid items found in agent output"); + return; + } + const createIssueItems = validatedOutput.items.filter(item => item.type === "create-issue"); + if (createIssueItems.length === 0) { + core.info("No create-issue items found in agent output"); + return; + } + core.info(`Found ${createIssueItems.length} create-issue item(s)`); + if (isStaged) { + let summaryContent = "## 🎭 Staged Mode: Create Issues Preview\n\n"; + summaryContent += "The following issues would be created if staged mode was disabled:\n\n"; + for (let i = 0; i < createIssueItems.length; i++) { + const item = createIssueItems[i]; + summaryContent += `### Issue ${i + 1}\n`; + summaryContent += `**Title:** ${item.title || "No title provided"}\n\n`; + if (item.body) { + summaryContent += `**Body:**\n${item.body}\n\n`; + } + if (item.labels && item.labels.length > 0) { + summaryContent += `**Labels:** ${item.labels.join(", ")}\n\n`; + } + summaryContent += "---\n\n"; } - catch (error) { - core.setFailed(`Error parsing agent output JSON: ${error instanceof Error ? error.message : String(error)}`); - return; + await core.summary.addRaw(summaryContent).write(); + core.info("📝 Issue creation preview written to step summary"); + return; + } + const parentIssueNumber = context.payload?.issue?.number; + const labelsEnv = process.env.GITHUB_AW_ISSUE_LABELS; + let envLabels = labelsEnv + ? labelsEnv + .split(",") + .map(label => label.trim()) + .filter(label => label) + : []; + const createdIssues = []; + for (let i = 0; i < createIssueItems.length; i++) { + const createIssueItem = createIssueItems[i]; + core.info( + `Processing create-issue item ${i + 1}/${createIssueItems.length}: title=${createIssueItem.title}, bodyLength=${createIssueItem.body.length}` + ); + let labels = [...envLabels]; + if (createIssueItem.labels && Array.isArray(createIssueItem.labels)) { + labels = [...labels, ...createIssueItem.labels]; } - if (!validatedOutput.items || !Array.isArray(validatedOutput.items)) { - core.info("No valid items found in agent output"); - return; + labels = labels + .filter(label => label != null && label !== false && label !== 0) + .map(label => String(label).trim()) + .filter(label => label) + .map(label => sanitizeLabelContent(label)) + .filter(label => label) + .map(label => (label.length > 64 ? label.substring(0, 64) : label)) + .filter((label, index, arr) => arr.indexOf(label) === index); + let title = createIssueItem.title ? createIssueItem.title.trim() : ""; + let bodyLines = createIssueItem.body.split("\n"); + if (!title) { + title = createIssueItem.body || "Agent Output"; } - const createIssueItems = validatedOutput.items.filter(item => item.type === "create-issue"); - if (createIssueItems.length === 0) { - core.info("No create-issue items found in agent output"); - return; + const titlePrefix = process.env.GITHUB_AW_ISSUE_TITLE_PREFIX; + if (titlePrefix && !title.startsWith(titlePrefix)) { + title = titlePrefix + title; } - core.info(`Found ${createIssueItems.length} create-issue item(s)`); - if (isStaged) { - let summaryContent = "## 🎭 Staged Mode: Create Issues Preview\n\n"; - summaryContent += "The following issues would be created if staged mode was disabled:\n\n"; - for (let i = 0; i < createIssueItems.length; i++) { - const item = createIssueItems[i]; - summaryContent += `### Issue ${i + 1}\n`; - summaryContent += `**Title:** ${item.title || "No title provided"}\n\n`; - if (item.body) { - summaryContent += `**Body:**\n${item.body}\n\n`; - } - if (item.labels && item.labels.length > 0) { - summaryContent += `**Labels:** ${item.labels.join(", ")}\n\n`; - } - summaryContent += "---\n\n"; - } - await core.summary.addRaw(summaryContent).write(); - core.info("📝 Issue creation preview written to step summary"); - return; + if (parentIssueNumber) { + core.info("Detected issue context, parent issue #" + parentIssueNumber); + bodyLines.push(`Related to #${parentIssueNumber}`); } - const parentIssueNumber = context.payload?.issue?.number; - const labelsEnv = process.env.GITHUB_AW_ISSUE_LABELS; - let envLabels = labelsEnv - ? labelsEnv - .split(",") - .map((label) => label.trim()) - .filter((label) => label) - : []; - const createdIssues = []; - for (let i = 0; i < createIssueItems.length; i++) { - const createIssueItem = createIssueItems[i]; - core.info(`Processing create-issue item ${i + 1}/${createIssueItems.length}: title=${createIssueItem.title}, bodyLength=${createIssueItem.body.length}`); - let labels = [...envLabels]; - if (createIssueItem.labels && Array.isArray(createIssueItem.labels)) { - labels = [...labels, ...createIssueItem.labels]; - } - labels = labels - .filter(label => label != null && label !== false && label !== 0) - .map(label => String(label).trim()) - .filter(label => label) - .map(label => sanitizeLabelContent(label)) - .filter(label => label) - .map(label => (label.length > 64 ? label.substring(0, 64) : label)) - .filter((label, index, arr) => arr.indexOf(label) === index); - let title = createIssueItem.title ? createIssueItem.title.trim() : ""; - let bodyLines = createIssueItem.body.split("\n"); - if (!title) { - title = createIssueItem.body || "Agent Output"; - } - const titlePrefix = process.env.GITHUB_AW_ISSUE_TITLE_PREFIX; - if (titlePrefix && !title.startsWith(titlePrefix)) { - title = titlePrefix + title; - } - if (parentIssueNumber) { - core.info("Detected issue context, parent issue #" + parentIssueNumber); - bodyLines.push(`Related to #${parentIssueNumber}`); - } - const runId = context.runId; - const runUrl = context.payload.repository - ? `${context.payload.repository.html_url}/actions/runs/${runId}` - : `https://github.com/actions/runs/${runId}`; - bodyLines.push(``, ``, `> Generated by Agentic Workflow [Run](${runUrl})`, ""); - const body = bodyLines.join("\n").trim(); - core.info(`Creating issue with title: ${title}`); - core.info(`Labels: ${labels}`); - core.info(`Body length: ${body.length}`); + const runId = context.runId; + const runUrl = context.payload.repository + ? `${context.payload.repository.html_url}/actions/runs/${runId}` + : `https://github.com/actions/runs/${runId}`; + bodyLines.push(``, ``, `> Generated by Agentic Workflow [Run](${runUrl})`, ""); + const body = bodyLines.join("\n").trim(); + core.info(`Creating issue with title: ${title}`); + core.info(`Labels: ${labels}`); + core.info(`Body length: ${body.length}`); + try { + const { data: issue } = await github.rest.issues.create({ + owner: context.repo.owner, + repo: context.repo.repo, + title: title, + body: body, + labels: labels, + }); + core.info("Created issue #" + issue.number + ": " + issue.html_url); + createdIssues.push(issue); + if (parentIssueNumber) { try { - const { data: issue } = await github.rest.issues.create({ - owner: context.repo.owner, - repo: context.repo.repo, - title: title, - body: body, - labels: labels, - }); - core.info("Created issue #" + issue.number + ": " + issue.html_url); - createdIssues.push(issue); - if (parentIssueNumber) { - try { - await github.rest.issues.createComment({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: parentIssueNumber, - body: `Created related issue: #${issue.number}`, - }); - core.info("Added comment to parent issue #" + parentIssueNumber); - } - catch (error) { - core.info(`Warning: Could not add comment to parent issue: ${error instanceof Error ? error.message : String(error)}`); - } - } - if (i === createIssueItems.length - 1) { - core.setOutput("issue_number", issue.number); - core.setOutput("issue_url", issue.html_url); - } - } - catch (error) { - const errorMessage = error instanceof Error ? error.message : String(error); - if (errorMessage.includes("Issues has been disabled in this repository")) { - core.info(`⚠ Cannot create issue "${title}": Issues are disabled for this repository`); - core.info("Consider enabling issues in repository settings if you want to create issues automatically"); - continue; - } - core.error(`✗ Failed to create issue "${title}": ${errorMessage}`); - throw error; + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: parentIssueNumber, + body: `Created related issue: #${issue.number}`, + }); + core.info("Added comment to parent issue #" + parentIssueNumber); + } catch (error) { + core.info(`Warning: Could not add comment to parent issue: ${error instanceof Error ? error.message : String(error)}`); } + } + if (i === createIssueItems.length - 1) { + core.setOutput("issue_number", issue.number); + core.setOutput("issue_url", issue.html_url); + } + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + if (errorMessage.includes("Issues has been disabled in this repository")) { + core.info(`⚠ Cannot create issue "${title}": Issues are disabled for this repository`); + core.info("Consider enabling issues in repository settings if you want to create issues automatically"); + continue; + } + core.error(`✗ Failed to create issue "${title}": ${errorMessage}`); + throw error; } - if (createdIssues.length > 0) { - let summaryContent = "\n\n## GitHub Issues\n"; - for (const issue of createdIssues) { - summaryContent += `- Issue #${issue.number}: [${issue.title}](${issue.html_url})\n`; - } - await core.summary.addRaw(summaryContent).write(); + } + if (createdIssues.length > 0) { + let summaryContent = "\n\n## GitHub Issues\n"; + for (const issue of createdIssues) { + summaryContent += `- Issue #${issue.number}: [${issue.title}](${issue.html_url})\n`; } - core.info(`Successfully created ${createdIssues.length} issue(s)`); + await core.summary.addRaw(summaryContent).write(); + } + core.info(`Successfully created ${createdIssues.length} issue(s)`); } (async () => { - await main(); + await main(); })(); missing_tool: diff --git a/.github/workflows/tidy.lock.yml b/.github/workflows/tidy.lock.yml index bca0b207e3e..b1871bc7e60 100644 --- a/.github/workflows/tidy.lock.yml +++ b/.github/workflows/tidy.lock.yml @@ -1126,742 +1126,742 @@ jobs: with: script: | async function main() { - const fs = require("fs"); - function sanitizeContent(content) { - if (!content || typeof content !== "string") { - return ""; - } - const allowedDomainsEnv = process.env.GITHUB_AW_ALLOWED_DOMAINS; - const defaultAllowedDomains = ["github.com", "github.io", "githubusercontent.com", "githubassets.com", "github.dev", "codespaces.new"]; - const allowedDomains = allowedDomainsEnv - ? allowedDomainsEnv - .split(",") - .map(d => d.trim()) - .filter(d => d) - : defaultAllowedDomains; - let sanitized = content; - sanitized = neutralizeMentions(sanitized); - sanitized = removeXmlComments(sanitized); - sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); - sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); - sanitized = sanitizeUrlProtocols(sanitized); - sanitized = sanitizeUrlDomains(sanitized); - const maxLength = 524288; - if (sanitized.length > maxLength) { - sanitized = sanitized.substring(0, maxLength) + "\n[Content truncated due to length]"; - } - const lines = sanitized.split("\n"); - const maxLines = 65000; - if (lines.length > maxLines) { - sanitized = lines.slice(0, maxLines).join("\n") + "\n[Content truncated due to line count]"; - } - sanitized = neutralizeBotTriggers(sanitized); - return sanitized.trim(); - function sanitizeUrlDomains(s) { - return s.replace(/\bhttps:\/\/[^\s\])}'"<>&\x00-\x1f,;]+/gi, match => { - const urlAfterProtocol = match.slice(8); - const hostname = urlAfterProtocol.split(/[\/:\?#]/)[0].toLowerCase(); - const isAllowed = allowedDomains.some(allowedDomain => { - const normalizedAllowed = allowedDomain.toLowerCase(); - return hostname === normalizedAllowed || hostname.endsWith("." + normalizedAllowed); - }); - return isAllowed ? match : "(redacted)"; - }); - } - function sanitizeUrlProtocols(s) { - return s.replace(/\b(\w+):\/\/[^\s\])}'"<>&\x00-\x1f]+/gi, (match, protocol) => { - return protocol.toLowerCase() === "https" ? match : "(redacted)"; - }); - } - function neutralizeMentions(s) { - return s.replace(/(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, (_m, p1, p2) => `${p1}\`@${p2}\``); - } - function removeXmlComments(s) { - return s.replace(//g, "").replace(//g, ""); - } - function neutralizeBotTriggers(s) { - return s.replace(/\b(fixes?|closes?|resolves?|fix|close|resolve)\s+#(\w+)/gi, (match, action, ref) => `\`${action} #${ref}\``); - } + const fs = require("fs"); + function sanitizeContent(content) { + if (!content || typeof content !== "string") { + return ""; + } + const allowedDomainsEnv = process.env.GITHUB_AW_ALLOWED_DOMAINS; + const defaultAllowedDomains = ["github.com", "github.io", "githubusercontent.com", "githubassets.com", "github.dev", "codespaces.new"]; + const allowedDomains = allowedDomainsEnv + ? allowedDomainsEnv + .split(",") + .map(d => d.trim()) + .filter(d => d) + : defaultAllowedDomains; + let sanitized = content; + sanitized = neutralizeMentions(sanitized); + sanitized = removeXmlComments(sanitized); + sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, ""); + sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); + sanitized = sanitizeUrlProtocols(sanitized); + sanitized = sanitizeUrlDomains(sanitized); + const maxLength = 524288; + if (sanitized.length > maxLength) { + sanitized = sanitized.substring(0, maxLength) + "\n[Content truncated due to length]"; + } + const lines = sanitized.split("\n"); + const maxLines = 65000; + if (lines.length > maxLines) { + sanitized = lines.slice(0, maxLines).join("\n") + "\n[Content truncated due to line count]"; + } + sanitized = neutralizeBotTriggers(sanitized); + return sanitized.trim(); + function sanitizeUrlDomains(s) { + return s.replace(/\bhttps:\/\/[^\s\])}'"<>&\x00-\x1f,;]+/gi, match => { + const urlAfterProtocol = match.slice(8); + const hostname = urlAfterProtocol.split(/[\/:\?#]/)[0].toLowerCase(); + const isAllowed = allowedDomains.some(allowedDomain => { + const normalizedAllowed = allowedDomain.toLowerCase(); + return hostname === normalizedAllowed || hostname.endsWith("." + normalizedAllowed); + }); + return isAllowed ? match : "(redacted)"; + }); } - function getMaxAllowedForType(itemType, config) { - const itemConfig = config?.[itemType]; - if (itemConfig && typeof itemConfig === "object" && "max" in itemConfig && itemConfig.max) { - return itemConfig.max; - } - switch (itemType) { - case "create-issue": - return 1; - case "add-comment": - return 1; - case "create-pull-request": - return 1; - case "create-pull-request-review-comment": - return 1; - case "add-labels": - return 5; - case "update-issue": - return 1; - case "push-to-pull-request-branch": - return 1; - case "create-discussion": - return 1; - case "missing-tool": - return 1000; - case "create-code-scanning-alert": - return 1000; - case "upload-asset": - return 10; - default: - return 1; - } + function sanitizeUrlProtocols(s) { + return s.replace(/\b(\w+):\/\/[^\s\])}'"<>&\x00-\x1f]+/gi, (match, protocol) => { + return protocol.toLowerCase() === "https" ? match : "(redacted)"; + }); } - function getMinRequiredForType(itemType, config) { - const itemConfig = config?.[itemType]; - if (itemConfig && typeof itemConfig === "object" && "min" in itemConfig && itemConfig.min) { - return itemConfig.min; - } - return 0; - } - function repairJson(jsonStr) { - let repaired = jsonStr.trim(); - const _ctrl = { 8: "\\b", 9: "\\t", 10: "\\n", 12: "\\f", 13: "\\r" }; - repaired = repaired.replace(/[\u0000-\u001F]/g, ch => { - const c = ch.charCodeAt(0); - return _ctrl[c] || "\\u" + c.toString(16).padStart(4, "0"); - }); - repaired = repaired.replace(/'/g, '"'); - repaired = repaired.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/g, '$1"$2":'); - repaired = repaired.replace(/"([^"\\]*)"/g, (match, content) => { - if (content.includes("\n") || content.includes("\r") || content.includes("\t")) { - const escaped = content.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"); - return `"${escaped}"`; - } - return match; - }); - repaired = repaired.replace(/"([^"]*)"([^":,}\]]*)"([^"]*)"(\s*[,:}\]])/g, (match, p1, p2, p3, p4) => `"${p1}\\"${p2}\\"${p3}"${p4}`); - repaired = repaired.replace(/(\[\s*(?:"[^"]*"(?:\s*,\s*"[^"]*")*\s*),?)\s*}/g, "$1]"); - const openBraces = (repaired.match(/\{/g) || []).length; - const closeBraces = (repaired.match(/\}/g) || []).length; - if (openBraces > closeBraces) { - repaired += "}".repeat(openBraces - closeBraces); - } - else if (closeBraces > openBraces) { - repaired = "{".repeat(closeBraces - openBraces) + repaired; - } - const openBrackets = (repaired.match(/\[/g) || []).length; - const closeBrackets = (repaired.match(/\]/g) || []).length; - if (openBrackets > closeBrackets) { - repaired += "]".repeat(openBrackets - closeBrackets); - } - else if (closeBrackets > openBrackets) { - repaired = "[".repeat(closeBrackets - openBrackets) + repaired; - } - repaired = repaired.replace(/,(\s*[}\]])/g, "$1"); - return repaired; - } - function validatePositiveInteger(value, fieldName, lineNum) { - if (value === undefined || value === null) { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} is required`, - }; - } - if (typeof value !== "number" && typeof value !== "string") { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number or string field`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; - } - const parsed = typeof value === "string" ? parseInt(value, 10) : value; - if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { - if (fieldName.includes("create-code-scanning-alert 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'line' must be a valid positive integer (got: ${value})`, - }; - } - if (fieldName.includes("create-pull-request-review-comment 'line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'line' must be a positive integer`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, - }; - } - return { isValid: true, normalizedValue: parsed }; + function neutralizeMentions(s) { + return s.replace( + /(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g, + (_m, p1, p2) => `${p1}\`@${p2}\`` + ); } - function validateOptionalPositiveInteger(value, fieldName, lineNum) { - if (value === undefined) { - return { isValid: true }; - } - if (typeof value !== "number" && typeof value !== "string") { - if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a number or string`, - }; - } - if (fieldName.includes("create-code-scanning-alert 'column'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a number or string`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; - } - const parsed = typeof value === "string" ? parseInt(value, 10) : value; - if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { - if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a positive integer`, - }; - } - if (fieldName.includes("create-code-scanning-alert 'column'")) { - return { - isValid: false, - error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a valid positive integer (got: ${value})`, - }; - } - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, - }; - } - return { isValid: true, normalizedValue: parsed }; + function removeXmlComments(s) { + return s.replace(//g, "").replace(//g, ""); + } + function neutralizeBotTriggers(s) { + return s.replace(/\b(fixes?|closes?|resolves?|fix|close|resolve)\s+#(\w+)/gi, (match, action, ref) => `\`${action} #${ref}\``); + } + } + function getMaxAllowedForType(itemType, config) { + const itemConfig = config?.[itemType]; + if (itemConfig && typeof itemConfig === "object" && "max" in itemConfig && itemConfig.max) { + return itemConfig.max; + } + switch (itemType) { + case "create-issue": + return 1; + case "add-comment": + return 1; + case "create-pull-request": + return 1; + case "create-pull-request-review-comment": + return 1; + case "add-labels": + return 5; + case "update-issue": + return 1; + case "push-to-pull-request-branch": + return 1; + case "create-discussion": + return 1; + case "missing-tool": + return 1000; + case "create-code-scanning-alert": + return 1000; + case "upload-asset": + return 10; + default: + return 1; } - function validateIssueOrPRNumber(value, fieldName, lineNum) { - if (value === undefined) { - return { isValid: true }; - } - if (typeof value !== "number" && typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number or string`, - }; - } - return { isValid: true }; - } - function validateFieldWithInputSchema(value, fieldName, inputSchema, lineNum) { - if (inputSchema.required && (value === undefined || value === null)) { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} is required`, - }; - } - if (value === undefined || value === null) { - return { - isValid: true, - normalizedValue: inputSchema.default || undefined, - }; - } - const inputType = inputSchema.type || "string"; - let normalizedValue = value; - switch (inputType) { - case "string": - if (typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a string`, - }; - } - normalizedValue = sanitizeContent(value); - break; - case "boolean": - if (typeof value !== "boolean") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a boolean`, - }; - } - break; - case "number": - if (typeof value !== "number") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a number`, - }; - } - break; - case "choice": - if (typeof value !== "string") { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be a string for choice type`, - }; - } - if (inputSchema.options && !inputSchema.options.includes(value)) { - return { - isValid: false, - error: `Line ${lineNum}: ${fieldName} must be one of: ${inputSchema.options.join(", ")}`, - }; - } - normalizedValue = sanitizeContent(value); - break; - default: - if (typeof value === "string") { - normalizedValue = sanitizeContent(value); - } - break; - } + } + function getMinRequiredForType(itemType, config) { + const itemConfig = config?.[itemType]; + if (itemConfig && typeof itemConfig === "object" && "min" in itemConfig && itemConfig.min) { + return itemConfig.min; + } + return 0; + } + function repairJson(jsonStr) { + let repaired = jsonStr.trim(); + const _ctrl = { 8: "\\b", 9: "\\t", 10: "\\n", 12: "\\f", 13: "\\r" }; + repaired = repaired.replace(/[\u0000-\u001F]/g, ch => { + const c = ch.charCodeAt(0); + return _ctrl[c] || "\\u" + c.toString(16).padStart(4, "0"); + }); + repaired = repaired.replace(/'/g, '"'); + repaired = repaired.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/g, '$1"$2":'); + repaired = repaired.replace(/"([^"\\]*)"/g, (match, content) => { + if (content.includes("\n") || content.includes("\r") || content.includes("\t")) { + const escaped = content.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"); + return `"${escaped}"`; + } + return match; + }); + repaired = repaired.replace(/"([^"]*)"([^":,}\]]*)"([^"]*)"(\s*[,:}\]])/g, (match, p1, p2, p3, p4) => `"${p1}\\"${p2}\\"${p3}"${p4}`); + repaired = repaired.replace(/(\[\s*(?:"[^"]*"(?:\s*,\s*"[^"]*")*\s*),?)\s*}/g, "$1]"); + const openBraces = (repaired.match(/\{/g) || []).length; + const closeBraces = (repaired.match(/\}/g) || []).length; + if (openBraces > closeBraces) { + repaired += "}".repeat(openBraces - closeBraces); + } else if (closeBraces > openBraces) { + repaired = "{".repeat(closeBraces - openBraces) + repaired; + } + const openBrackets = (repaired.match(/\[/g) || []).length; + const closeBrackets = (repaired.match(/\]/g) || []).length; + if (openBrackets > closeBrackets) { + repaired += "]".repeat(openBrackets - closeBrackets); + } else if (closeBrackets > openBrackets) { + repaired = "[".repeat(closeBrackets - openBrackets) + repaired; + } + repaired = repaired.replace(/,(\s*[}\]])/g, "$1"); + return repaired; + } + function validatePositiveInteger(value, fieldName, lineNum) { + if (value === undefined || value === null) { + if (fieldName.includes("create-code-scanning-alert 'line'")) { return { - isValid: true, - normalizedValue, + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} is required`, + }; } - function validateItemWithSafeJobConfig(item, jobConfig, lineNum) { - const errors = []; - const normalizedItem = { ...item }; - if (!jobConfig.inputs) { - return { - isValid: true, - errors: [], - normalizedItem: item, - }; - } - for (const [fieldName, inputSchema] of Object.entries(jobConfig.inputs)) { - const fieldValue = item[fieldName]; - const validation = validateFieldWithInputSchema(fieldValue, fieldName, inputSchema, lineNum); - if (!validation.isValid && validation.error) { - errors.push(validation.error); - } - else if (validation.normalizedValue !== undefined) { - normalizedItem[fieldName] = validation.normalizedValue; - } - } + if (typeof value !== "number" && typeof value !== "string") { + if (fieldName.includes("create-code-scanning-alert 'line'")) { return { - isValid: errors.length === 0, - errors, - normalizedItem, + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert requires a 'line' field (number or string)`, }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment requires a 'line' number or string field`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; } - function parseJsonWithRepair(jsonStr) { - try { - return JSON.parse(jsonStr); - } - catch (originalError) { - try { - const repairedJson = repairJson(jsonStr); - return JSON.parse(repairedJson); - } - catch (repairError) { - core.info(`invalid input json: ${jsonStr}`); - const originalMsg = originalError instanceof Error ? originalError.message : String(originalError); - const repairMsg = repairError instanceof Error ? repairError.message : String(repairError); - throw new Error(`JSON parsing failed. Original: ${originalMsg}. After attempted repair: ${repairMsg}`); - } - } + const parsed = typeof value === "string" ? parseInt(value, 10) : value; + if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { + if (fieldName.includes("create-code-scanning-alert 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'line' must be a valid positive integer (got: ${value})`, + }; + } + if (fieldName.includes("create-pull-request-review-comment 'line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'line' must be a positive integer`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, + }; } - const outputFile = process.env.GITHUB_AW_SAFE_OUTPUTS; - const safeOutputsConfig = process.env.GITHUB_AW_SAFE_OUTPUTS_CONFIG; - if (!outputFile) { - core.info("GITHUB_AW_SAFE_OUTPUTS not set, no output to collect"); - core.setOutput("output", ""); - return; + return { isValid: true, normalizedValue: parsed }; + } + function validateOptionalPositiveInteger(value, fieldName, lineNum) { + if (value === undefined) { + return { isValid: true }; } - if (!fs.existsSync(outputFile)) { - core.info(`Output file does not exist: ${outputFile}`); - core.setOutput("output", ""); - return; + if (typeof value !== "number" && typeof value !== "string") { + if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a number or string`, + }; + } + if (fieldName.includes("create-code-scanning-alert 'column'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a number or string`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; } - const outputContent = fs.readFileSync(outputFile, "utf8"); - if (outputContent.trim() === "") { - core.info("Output file is empty"); + const parsed = typeof value === "string" ? parseInt(value, 10) : value; + if (isNaN(parsed) || parsed <= 0 || !Number.isInteger(parsed)) { + if (fieldName.includes("create-pull-request-review-comment 'start_line'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-pull-request-review-comment 'start_line' must be a positive integer`, + }; + } + if (fieldName.includes("create-code-scanning-alert 'column'")) { + return { + isValid: false, + error: `Line ${lineNum}: create-code-scanning-alert 'column' must be a valid positive integer (got: ${value})`, + }; + } + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a positive integer (got: ${value})`, + }; } - core.info(`Raw output content length: ${outputContent.length}`); - let expectedOutputTypes = {}; - if (safeOutputsConfig) { - try { - expectedOutputTypes = JSON.parse(safeOutputsConfig); - core.info(`Expected output types: ${JSON.stringify(Object.keys(expectedOutputTypes))}`); + return { isValid: true, normalizedValue: parsed }; + } + function validateIssueOrPRNumber(value, fieldName, lineNum) { + if (value === undefined) { + return { isValid: true }; + } + if (typeof value !== "number" && typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number or string`, + }; + } + return { isValid: true }; + } + function validateFieldWithInputSchema(value, fieldName, inputSchema, lineNum) { + if (inputSchema.required && (value === undefined || value === null)) { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} is required`, + }; + } + if (value === undefined || value === null) { + return { + isValid: true, + normalizedValue: inputSchema.default || undefined, + }; + } + const inputType = inputSchema.type || "string"; + let normalizedValue = value; + switch (inputType) { + case "string": + if (typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a string`, + }; + } + normalizedValue = sanitizeContent(value); + break; + case "boolean": + if (typeof value !== "boolean") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a boolean`, + }; + } + break; + case "number": + if (typeof value !== "number") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a number`, + }; + } + break; + case "choice": + if (typeof value !== "string") { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be a string for choice type`, + }; } - catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.info(`Warning: Could not parse safe-outputs config: ${errorMsg}`); + if (inputSchema.options && !inputSchema.options.includes(value)) { + return { + isValid: false, + error: `Line ${lineNum}: ${fieldName} must be one of: ${inputSchema.options.join(", ")}`, + }; } + normalizedValue = sanitizeContent(value); + break; + default: + if (typeof value === "string") { + normalizedValue = sanitizeContent(value); + } + break; } - const lines = outputContent.trim().split("\n"); - const parsedItems = []; + return { + isValid: true, + normalizedValue, + }; + } + function validateItemWithSafeJobConfig(item, jobConfig, lineNum) { const errors = []; - for (let i = 0; i < lines.length; i++) { - const line = lines[i].trim(); - if (line === "") + const normalizedItem = { ...item }; + if (!jobConfig.inputs) { + return { + isValid: true, + errors: [], + normalizedItem: item, + }; + } + for (const [fieldName, inputSchema] of Object.entries(jobConfig.inputs)) { + const fieldValue = item[fieldName]; + const validation = validateFieldWithInputSchema(fieldValue, fieldName, inputSchema, lineNum); + if (!validation.isValid && validation.error) { + errors.push(validation.error); + } else if (validation.normalizedValue !== undefined) { + normalizedItem[fieldName] = validation.normalizedValue; + } + } + return { + isValid: errors.length === 0, + errors, + normalizedItem, + }; + } + function parseJsonWithRepair(jsonStr) { + try { + return JSON.parse(jsonStr); + } catch (originalError) { + try { + const repairedJson = repairJson(jsonStr); + return JSON.parse(repairedJson); + } catch (repairError) { + core.info(`invalid input json: ${jsonStr}`); + const originalMsg = originalError instanceof Error ? originalError.message : String(originalError); + const repairMsg = repairError instanceof Error ? repairError.message : String(repairError); + throw new Error(`JSON parsing failed. Original: ${originalMsg}. After attempted repair: ${repairMsg}`); + } + } + } + const outputFile = process.env.GITHUB_AW_SAFE_OUTPUTS; + const safeOutputsConfig = process.env.GITHUB_AW_SAFE_OUTPUTS_CONFIG; + if (!outputFile) { + core.info("GITHUB_AW_SAFE_OUTPUTS not set, no output to collect"); + core.setOutput("output", ""); + return; + } + if (!fs.existsSync(outputFile)) { + core.info(`Output file does not exist: ${outputFile}`); + core.setOutput("output", ""); + return; + } + const outputContent = fs.readFileSync(outputFile, "utf8"); + if (outputContent.trim() === "") { + core.info("Output file is empty"); + } + core.info(`Raw output content length: ${outputContent.length}`); + let expectedOutputTypes = {}; + if (safeOutputsConfig) { + try { + expectedOutputTypes = JSON.parse(safeOutputsConfig); + core.info(`Expected output types: ${JSON.stringify(Object.keys(expectedOutputTypes))}`); + } catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.info(`Warning: Could not parse safe-outputs config: ${errorMsg}`); + } + } + const lines = outputContent.trim().split("\n"); + const parsedItems = []; + const errors = []; + for (let i = 0; i < lines.length; i++) { + const line = lines[i].trim(); + if (line === "") continue; + try { + const item = parseJsonWithRepair(line); + if (item === undefined) { + errors.push(`Line ${i + 1}: Invalid JSON - JSON parsing failed`); + continue; + } + if (!item.type) { + errors.push(`Line ${i + 1}: Missing required 'type' field`); + continue; + } + const itemType = item.type; + if (!expectedOutputTypes[itemType]) { + errors.push(`Line ${i + 1}: Unexpected output type '${itemType}'. Expected one of: ${Object.keys(expectedOutputTypes).join(", ")}`); + continue; + } + const typeCount = parsedItems.filter(existing => existing.type === itemType).length; + const maxAllowed = getMaxAllowedForType(itemType, expectedOutputTypes); + if (typeCount >= maxAllowed) { + errors.push(`Line ${i + 1}: Too many items of type '${itemType}'. Maximum allowed: ${maxAllowed}.`); + continue; + } + core.info(`Line ${i + 1}: type '${itemType}'`); + switch (itemType) { + case "create-issue": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_issue requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_issue requires a 'body' string field`); + continue; + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + if (item.labels && Array.isArray(item.labels)) { + item.labels = item.labels.map(label => (typeof label === "string" ? sanitizeContent(label) : label)); + } + break; + case "add-comment": + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: add_comment requires a 'body' string field`); + continue; + } + const issueNumValidation = validateIssueOrPRNumber(item.issue_number, "add_comment 'issue_number'", i + 1); + if (!issueNumValidation.isValid) { + if (issueNumValidation.error) errors.push(issueNumValidation.error); + continue; + } + item.body = sanitizeContent(item.body); + break; + case "create-pull-request": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'body' string field`); continue; - try { - const item = parseJsonWithRepair(line); - if (item === undefined) { - errors.push(`Line ${i + 1}: Invalid JSON - JSON parsing failed`); - continue; + } + if (!item.branch || typeof item.branch !== "string") { + errors.push(`Line ${i + 1}: create_pull_request requires a 'branch' string field`); + continue; + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + item.branch = sanitizeContent(item.branch); + if (item.labels && Array.isArray(item.labels)) { + item.labels = item.labels.map(label => (typeof label === "string" ? sanitizeContent(label) : label)); + } + break; + case "add-labels": + if (!item.labels || !Array.isArray(item.labels)) { + errors.push(`Line ${i + 1}: add_labels requires a 'labels' array field`); + continue; + } + if (item.labels.some(label => typeof label !== "string")) { + errors.push(`Line ${i + 1}: add_labels labels array must contain only strings`); + continue; + } + const labelsIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "add-labels 'issue_number'", i + 1); + if (!labelsIssueNumValidation.isValid) { + if (labelsIssueNumValidation.error) errors.push(labelsIssueNumValidation.error); + continue; + } + item.labels = item.labels.map(label => sanitizeContent(label)); + break; + case "update-issue": + const hasValidField = item.status !== undefined || item.title !== undefined || item.body !== undefined; + if (!hasValidField) { + errors.push(`Line ${i + 1}: update_issue requires at least one of: 'status', 'title', or 'body' fields`); + continue; + } + if (item.status !== undefined) { + if (typeof item.status !== "string" || (item.status !== "open" && item.status !== "closed")) { + errors.push(`Line ${i + 1}: update_issue 'status' must be 'open' or 'closed'`); + continue; } - if (!item.type) { - errors.push(`Line ${i + 1}: Missing required 'type' field`); - continue; + } + if (item.title !== undefined) { + if (typeof item.title !== "string") { + errors.push(`Line ${i + 1}: update-issue 'title' must be a string`); + continue; } - const itemType = item.type; - if (!expectedOutputTypes[itemType]) { - errors.push(`Line ${i + 1}: Unexpected output type '${itemType}'. Expected one of: ${Object.keys(expectedOutputTypes).join(", ")}`); - continue; + item.title = sanitizeContent(item.title); + } + if (item.body !== undefined) { + if (typeof item.body !== "string") { + errors.push(`Line ${i + 1}: update-issue 'body' must be a string`); + continue; } - const typeCount = parsedItems.filter(existing => existing.type === itemType).length; - const maxAllowed = getMaxAllowedForType(itemType, expectedOutputTypes); - if (typeCount >= maxAllowed) { - errors.push(`Line ${i + 1}: Too many items of type '${itemType}'. Maximum allowed: ${maxAllowed}.`); - continue; + item.body = sanitizeContent(item.body); + } + const updateIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "update-issue 'issue_number'", i + 1); + if (!updateIssueNumValidation.isValid) { + if (updateIssueNumValidation.error) errors.push(updateIssueNumValidation.error); + continue; + } + break; + case "push-to-pull-request-branch": + if (!item.branch || typeof item.branch !== "string") { + errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'branch' string field`); + continue; + } + if (!item.message || typeof item.message !== "string") { + errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'message' string field`); + continue; + } + item.branch = sanitizeContent(item.branch); + item.message = sanitizeContent(item.message); + const pushPRNumValidation = validateIssueOrPRNumber( + item.pull_request_number, + "push-to-pull-request-branch 'pull_request_number'", + i + 1 + ); + if (!pushPRNumValidation.isValid) { + if (pushPRNumValidation.error) errors.push(pushPRNumValidation.error); + continue; + } + break; + case "create-pull-request-review-comment": + if (!item.path || typeof item.path !== "string") { + errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'path' string field`); + continue; + } + const lineValidation = validatePositiveInteger(item.line, "create-pull-request-review-comment 'line'", i + 1); + if (!lineValidation.isValid) { + if (lineValidation.error) errors.push(lineValidation.error); + continue; + } + const lineNumber = lineValidation.normalizedValue; + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'body' string field`); + continue; + } + item.body = sanitizeContent(item.body); + const startLineValidation = validateOptionalPositiveInteger( + item.start_line, + "create-pull-request-review-comment 'start_line'", + i + 1 + ); + if (!startLineValidation.isValid) { + if (startLineValidation.error) errors.push(startLineValidation.error); + continue; + } + if ( + startLineValidation.normalizedValue !== undefined && + lineNumber !== undefined && + startLineValidation.normalizedValue > lineNumber + ) { + errors.push(`Line ${i + 1}: create-pull-request-review-comment 'start_line' must be less than or equal to 'line'`); + continue; + } + if (item.side !== undefined) { + if (typeof item.side !== "string" || (item.side !== "LEFT" && item.side !== "RIGHT")) { + errors.push(`Line ${i + 1}: create-pull-request-review-comment 'side' must be 'LEFT' or 'RIGHT'`); + continue; } - core.info(`Line ${i + 1}: type '${itemType}'`); - switch (itemType) { - case "create-issue": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_issue requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_issue requires a 'body' string field`); - continue; - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - if (item.labels && Array.isArray(item.labels)) { - item.labels = item.labels.map((label) => (typeof label === "string" ? sanitizeContent(label) : label)); - } - break; - case "add-comment": - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: add_comment requires a 'body' string field`); - continue; - } - const issueNumValidation = validateIssueOrPRNumber(item.issue_number, "add_comment 'issue_number'", i + 1); - if (!issueNumValidation.isValid) { - if (issueNumValidation.error) - errors.push(issueNumValidation.error); - continue; - } - item.body = sanitizeContent(item.body); - break; - case "create-pull-request": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'body' string field`); - continue; - } - if (!item.branch || typeof item.branch !== "string") { - errors.push(`Line ${i + 1}: create_pull_request requires a 'branch' string field`); - continue; - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - item.branch = sanitizeContent(item.branch); - if (item.labels && Array.isArray(item.labels)) { - item.labels = item.labels.map((label) => (typeof label === "string" ? sanitizeContent(label) : label)); - } - break; - case "add-labels": - if (!item.labels || !Array.isArray(item.labels)) { - errors.push(`Line ${i + 1}: add_labels requires a 'labels' array field`); - continue; - } - if (item.labels.some((label) => typeof label !== "string")) { - errors.push(`Line ${i + 1}: add_labels labels array must contain only strings`); - continue; - } - const labelsIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "add-labels 'issue_number'", i + 1); - if (!labelsIssueNumValidation.isValid) { - if (labelsIssueNumValidation.error) - errors.push(labelsIssueNumValidation.error); - continue; - } - item.labels = item.labels.map((label) => sanitizeContent(label)); - break; - case "update-issue": - const hasValidField = item.status !== undefined || item.title !== undefined || item.body !== undefined; - if (!hasValidField) { - errors.push(`Line ${i + 1}: update_issue requires at least one of: 'status', 'title', or 'body' fields`); - continue; - } - if (item.status !== undefined) { - if (typeof item.status !== "string" || (item.status !== "open" && item.status !== "closed")) { - errors.push(`Line ${i + 1}: update_issue 'status' must be 'open' or 'closed'`); - continue; - } - } - if (item.title !== undefined) { - if (typeof item.title !== "string") { - errors.push(`Line ${i + 1}: update-issue 'title' must be a string`); - continue; - } - item.title = sanitizeContent(item.title); - } - if (item.body !== undefined) { - if (typeof item.body !== "string") { - errors.push(`Line ${i + 1}: update-issue 'body' must be a string`); - continue; - } - item.body = sanitizeContent(item.body); - } - const updateIssueNumValidation = validateIssueOrPRNumber(item.issue_number, "update-issue 'issue_number'", i + 1); - if (!updateIssueNumValidation.isValid) { - if (updateIssueNumValidation.error) - errors.push(updateIssueNumValidation.error); - continue; - } - break; - case "push-to-pull-request-branch": - if (!item.branch || typeof item.branch !== "string") { - errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'branch' string field`); - continue; - } - if (!item.message || typeof item.message !== "string") { - errors.push(`Line ${i + 1}: push_to_pull_request_branch requires a 'message' string field`); - continue; - } - item.branch = sanitizeContent(item.branch); - item.message = sanitizeContent(item.message); - const pushPRNumValidation = validateIssueOrPRNumber(item.pull_request_number, "push-to-pull-request-branch 'pull_request_number'", i + 1); - if (!pushPRNumValidation.isValid) { - if (pushPRNumValidation.error) - errors.push(pushPRNumValidation.error); - continue; - } - break; - case "create-pull-request-review-comment": - if (!item.path || typeof item.path !== "string") { - errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'path' string field`); - continue; - } - const lineValidation = validatePositiveInteger(item.line, "create-pull-request-review-comment 'line'", i + 1); - if (!lineValidation.isValid) { - if (lineValidation.error) - errors.push(lineValidation.error); - continue; - } - const lineNumber = lineValidation.normalizedValue; - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create-pull-request-review-comment requires a 'body' string field`); - continue; - } - item.body = sanitizeContent(item.body); - const startLineValidation = validateOptionalPositiveInteger(item.start_line, "create-pull-request-review-comment 'start_line'", i + 1); - if (!startLineValidation.isValid) { - if (startLineValidation.error) - errors.push(startLineValidation.error); - continue; - } - if (startLineValidation.normalizedValue !== undefined && - lineNumber !== undefined && - startLineValidation.normalizedValue > lineNumber) { - errors.push(`Line ${i + 1}: create-pull-request-review-comment 'start_line' must be less than or equal to 'line'`); - continue; - } - if (item.side !== undefined) { - if (typeof item.side !== "string" || (item.side !== "LEFT" && item.side !== "RIGHT")) { - errors.push(`Line ${i + 1}: create-pull-request-review-comment 'side' must be 'LEFT' or 'RIGHT'`); - continue; - } - } - break; - case "create-discussion": - if (!item.title || typeof item.title !== "string") { - errors.push(`Line ${i + 1}: create_discussion requires a 'title' string field`); - continue; - } - if (!item.body || typeof item.body !== "string") { - errors.push(`Line ${i + 1}: create_discussion requires a 'body' string field`); - continue; - } - if (item.category !== undefined) { - if (typeof item.category !== "string") { - errors.push(`Line ${i + 1}: create_discussion 'category' must be a string`); - continue; - } - item.category = sanitizeContent(item.category); - } - item.title = sanitizeContent(item.title); - item.body = sanitizeContent(item.body); - break; - case "missing-tool": - if (!item.tool || typeof item.tool !== "string") { - errors.push(`Line ${i + 1}: missing_tool requires a 'tool' string field`); - continue; - } - if (!item.reason || typeof item.reason !== "string") { - errors.push(`Line ${i + 1}: missing_tool requires a 'reason' string field`); - continue; - } - item.tool = sanitizeContent(item.tool); - item.reason = sanitizeContent(item.reason); - if (item.alternatives !== undefined) { - if (typeof item.alternatives !== "string") { - errors.push(`Line ${i + 1}: missing-tool 'alternatives' must be a string`); - continue; - } - item.alternatives = sanitizeContent(item.alternatives); - } - break; - case "upload-asset": - if (!item.path || typeof item.path !== "string") { - errors.push(`Line ${i + 1}: upload_asset requires a 'path' string field`); - continue; - } - break; - case "create-code-scanning-alert": - if (!item.file || typeof item.file !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'file' field (string)`); - continue; - } - const alertLineValidation = validatePositiveInteger(item.line, "create-code-scanning-alert 'line'", i + 1); - if (!alertLineValidation.isValid) { - if (alertLineValidation.error) { - errors.push(alertLineValidation.error); - } - continue; - } - if (!item.severity || typeof item.severity !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'severity' field (string)`); - continue; - } - if (!item.message || typeof item.message !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'message' field (string)`); - continue; - } - const allowedSeverities = ["error", "warning", "info", "note"]; - if (!allowedSeverities.includes(item.severity.toLowerCase())) { - errors.push(`Line ${i + 1}: create-code-scanning-alert 'severity' must be one of: ${allowedSeverities.join(", ")}, got ${item.severity.toLowerCase()}`); - continue; - } - const columnValidation = validateOptionalPositiveInteger(item.column, "create-code-scanning-alert 'column'", i + 1); - if (!columnValidation.isValid) { - if (columnValidation.error) - errors.push(columnValidation.error); - continue; - } - if (item.ruleIdSuffix !== undefined) { - if (typeof item.ruleIdSuffix !== "string") { - errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must be a string`); - continue; - } - if (!/^[a-zA-Z0-9_-]+$/.test(item.ruleIdSuffix.trim())) { - errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must contain only alphanumeric characters, hyphens, and underscores`); - continue; - } - } - item.severity = item.severity.toLowerCase(); - item.file = sanitizeContent(item.file); - item.severity = sanitizeContent(item.severity); - item.message = sanitizeContent(item.message); - if (item.ruleIdSuffix) { - item.ruleIdSuffix = sanitizeContent(item.ruleIdSuffix); - } - break; - default: - const jobOutputType = expectedOutputTypes[itemType]; - if (!jobOutputType) { - errors.push(`Line ${i + 1}: Unknown output type '${itemType}'`); - continue; - } - const safeJobConfig = jobOutputType; - if (safeJobConfig && safeJobConfig.inputs) { - const validation = validateItemWithSafeJobConfig(item, safeJobConfig, i + 1); - if (!validation.isValid) { - errors.push(...validation.errors); - continue; - } - Object.assign(item, validation.normalizedItem); - } - break; + } + break; + case "create-discussion": + if (!item.title || typeof item.title !== "string") { + errors.push(`Line ${i + 1}: create_discussion requires a 'title' string field`); + continue; + } + if (!item.body || typeof item.body !== "string") { + errors.push(`Line ${i + 1}: create_discussion requires a 'body' string field`); + continue; + } + if (item.category !== undefined) { + if (typeof item.category !== "string") { + errors.push(`Line ${i + 1}: create_discussion 'category' must be a string`); + continue; } - core.info(`Line ${i + 1}: Valid ${itemType} item`); - parsedItems.push(item); - } - catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - errors.push(`Line ${i + 1}: Invalid JSON - ${errorMsg}`); - } - } - if (errors.length > 0) { - core.warning("Validation errors found:"); - errors.forEach(error => core.warning(` - ${error}`)); - if (parsedItems.length === 0) { - core.setFailed(errors.map(e => ` - ${e}`).join("\n")); - return; - } - } - for (const itemType of Object.keys(expectedOutputTypes)) { - const minRequired = getMinRequiredForType(itemType, expectedOutputTypes); - if (minRequired > 0) { - const actualCount = parsedItems.filter(item => item.type === itemType).length; - if (actualCount < minRequired) { - errors.push(`Too few items of type '${itemType}'. Minimum required: ${minRequired}, found: ${actualCount}.`); + item.category = sanitizeContent(item.category); + } + item.title = sanitizeContent(item.title); + item.body = sanitizeContent(item.body); + break; + case "missing-tool": + if (!item.tool || typeof item.tool !== "string") { + errors.push(`Line ${i + 1}: missing_tool requires a 'tool' string field`); + continue; + } + if (!item.reason || typeof item.reason !== "string") { + errors.push(`Line ${i + 1}: missing_tool requires a 'reason' string field`); + continue; + } + item.tool = sanitizeContent(item.tool); + item.reason = sanitizeContent(item.reason); + if (item.alternatives !== undefined) { + if (typeof item.alternatives !== "string") { + errors.push(`Line ${i + 1}: missing-tool 'alternatives' must be a string`); + continue; } - } + item.alternatives = sanitizeContent(item.alternatives); + } + break; + case "upload-asset": + if (!item.path || typeof item.path !== "string") { + errors.push(`Line ${i + 1}: upload_asset requires a 'path' string field`); + continue; + } + break; + case "create-code-scanning-alert": + if (!item.file || typeof item.file !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'file' field (string)`); + continue; + } + const alertLineValidation = validatePositiveInteger(item.line, "create-code-scanning-alert 'line'", i + 1); + if (!alertLineValidation.isValid) { + if (alertLineValidation.error) { + errors.push(alertLineValidation.error); + } + continue; + } + if (!item.severity || typeof item.severity !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'severity' field (string)`); + continue; + } + if (!item.message || typeof item.message !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert requires a 'message' field (string)`); + continue; + } + const allowedSeverities = ["error", "warning", "info", "note"]; + if (!allowedSeverities.includes(item.severity.toLowerCase())) { + errors.push( + `Line ${i + 1}: create-code-scanning-alert 'severity' must be one of: ${allowedSeverities.join(", ")}, got ${item.severity.toLowerCase()}` + ); + continue; + } + const columnValidation = validateOptionalPositiveInteger(item.column, "create-code-scanning-alert 'column'", i + 1); + if (!columnValidation.isValid) { + if (columnValidation.error) errors.push(columnValidation.error); + continue; + } + if (item.ruleIdSuffix !== undefined) { + if (typeof item.ruleIdSuffix !== "string") { + errors.push(`Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must be a string`); + continue; + } + if (!/^[a-zA-Z0-9_-]+$/.test(item.ruleIdSuffix.trim())) { + errors.push( + `Line ${i + 1}: create-code-scanning-alert 'ruleIdSuffix' must contain only alphanumeric characters, hyphens, and underscores` + ); + continue; + } + } + item.severity = item.severity.toLowerCase(); + item.file = sanitizeContent(item.file); + item.severity = sanitizeContent(item.severity); + item.message = sanitizeContent(item.message); + if (item.ruleIdSuffix) { + item.ruleIdSuffix = sanitizeContent(item.ruleIdSuffix); + } + break; + default: + const jobOutputType = expectedOutputTypes[itemType]; + if (!jobOutputType) { + errors.push(`Line ${i + 1}: Unknown output type '${itemType}'`); + continue; + } + const safeJobConfig = jobOutputType; + if (safeJobConfig && safeJobConfig.inputs) { + const validation = validateItemWithSafeJobConfig(item, safeJobConfig, i + 1); + if (!validation.isValid) { + errors.push(...validation.errors); + continue; + } + Object.assign(item, validation.normalizedItem); + } + break; + } + core.info(`Line ${i + 1}: Valid ${itemType} item`); + parsedItems.push(item); + } catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + errors.push(`Line ${i + 1}: Invalid JSON - ${errorMsg}`); } - core.info(`Successfully parsed ${parsedItems.length} valid output items`); - const validatedOutput = { - items: parsedItems, - errors: errors, - }; - const agentOutputFile = "/tmp/agent_output.json"; - const validatedOutputJson = JSON.stringify(validatedOutput); - try { - fs.mkdirSync("/tmp", { recursive: true }); - fs.writeFileSync(agentOutputFile, validatedOutputJson, "utf8"); - core.info(`Stored validated output to: ${agentOutputFile}`); - core.exportVariable("GITHUB_AW_AGENT_OUTPUT", agentOutputFile); - } - catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.error(`Failed to write agent output file: ${errorMsg}`); - } - core.setOutput("output", JSON.stringify(validatedOutput)); - core.setOutput("raw_output", outputContent); - const outputTypes = Array.from(new Set(parsedItems.map(item => item.type))); - core.info(`output_types: ${outputTypes.join(", ")}`); - core.setOutput("output_types", outputTypes.join(",")); - try { - await core.summary - .addRaw("## Processed Output\n\n") - .addRaw("```json\n") - .addRaw(JSON.stringify(validatedOutput)) - .addRaw("\n```\n") - .write(); - core.info("Successfully wrote processed output to step summary"); - } - catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - core.warning(`Failed to write to step summary: ${errorMsg}`); + } + if (errors.length > 0) { + core.warning("Validation errors found:"); + errors.forEach(error => core.warning(` - ${error}`)); + if (parsedItems.length === 0) { + core.setFailed(errors.map(e => ` - ${e}`).join("\n")); + return; + } + } + for (const itemType of Object.keys(expectedOutputTypes)) { + const minRequired = getMinRequiredForType(itemType, expectedOutputTypes); + if (minRequired > 0) { + const actualCount = parsedItems.filter(item => item.type === itemType).length; + if (actualCount < minRequired) { + errors.push(`Too few items of type '${itemType}'. Minimum required: ${minRequired}, found: ${actualCount}.`); + } } + } + core.info(`Successfully parsed ${parsedItems.length} valid output items`); + const validatedOutput = { + items: parsedItems, + errors: errors, + }; + const agentOutputFile = "/tmp/agent_output.json"; + const validatedOutputJson = JSON.stringify(validatedOutput); + try { + fs.mkdirSync("/tmp", { recursive: true }); + fs.writeFileSync(agentOutputFile, validatedOutputJson, "utf8"); + core.info(`Stored validated output to: ${agentOutputFile}`); + core.exportVariable("GITHUB_AW_AGENT_OUTPUT", agentOutputFile); + } catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.error(`Failed to write agent output file: ${errorMsg}`); + } + core.setOutput("output", JSON.stringify(validatedOutput)); + core.setOutput("raw_output", outputContent); + const outputTypes = Array.from(new Set(parsedItems.map(item => item.type))); + core.info(`output_types: ${outputTypes.join(", ")}`); + core.setOutput("output_types", outputTypes.join(",")); + try { + await core.summary + .addRaw("## Processed Output\n\n") + .addRaw("```json\n") + .addRaw(JSON.stringify(validatedOutput)) + .addRaw("\n```\n") + .write(); + core.info("Successfully wrote processed output to step summary"); + } catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + core.warning(`Failed to write to step summary: ${errorMsg}`); + } } await main(); - name: Upload sanitized agent output diff --git a/docs/src/content/docs/reference/imports.md b/docs/src/content/docs/reference/imports.md index ca7282b24a9..75702cf5bed 100644 --- a/docs/src/content/docs/reference/imports.md +++ b/docs/src/content/docs/reference/imports.md @@ -56,6 +56,7 @@ The install command: 3. Clones repositories at the specified versions 4. Stores imported files in `.aw/imports/` 5. Creates/updates `.aw/imports.lock` with resolved SHAs +6. Creates `.aw/.gitignore` to automatically ignore the `imports/` folder ## Lock File @@ -136,7 +137,9 @@ Result: GitHub tools will have both sets of allowed functions. ## Version Control -Add `.aw/imports/` to `.gitignore` to exclude cached imported files while keeping the lock file: +The `gh aw install` command automatically creates a `.aw/.gitignore` file that ignores the `imports/` folder. This ensures the cached imported files are not committed while the lock file remains trackable. + +You can also add `.aw/imports/` to your project's root `.gitignore` for additional protection: ```gitignore # Workflow imports (cached files only, not the lock file) diff --git a/pkg/cli/install_imports.go b/pkg/cli/install_imports.go index 9dd52a71075..4c0b7c3276b 100644 --- a/pkg/cli/install_imports.go +++ b/pkg/cli/install_imports.go @@ -65,6 +65,11 @@ func InstallImports(workflowName string, verbose bool) error { return fmt.Errorf("failed to create .aw directory: %w", err) } + // Create .gitignore in .aw directory to ignore imports folder + if err := ensureAwGitignore(awDir, verbose); err != nil { + return fmt.Errorf("failed to create .aw/.gitignore: %w", err) + } + // Read existing lock file lock, err := parser.ReadImportLockFile(lockFilePath) if err != nil { @@ -415,3 +420,34 @@ func collectTransitiveFiles(filePath, baseDir string, verbose bool) ([]string, e return files, nil } + +// ensureAwGitignore creates or updates .gitignore in .aw directory to ignore imports folder +func ensureAwGitignore(awDir string, verbose bool) error { + gitignorePath := filepath.Join(awDir, ".gitignore") + + // Content to write - ignore the imports folder + content := "# Ignore cached imported files\nimports/\n" + + // Check if .gitignore already exists + existingContent, err := os.ReadFile(gitignorePath) + if err == nil { + // File exists, check if it already has the imports/ entry + if strings.Contains(string(existingContent), "imports/") { + // Already configured, no need to update + return nil + } + // Append to existing content + content = string(existingContent) + "\n" + content + } + + // Write the .gitignore file + if err := os.WriteFile(gitignorePath, []byte(content), 0644); err != nil { + return fmt.Errorf("failed to write .gitignore: %w", err) + } + + if verbose { + fmt.Fprintln(os.Stderr, console.FormatInfoMessage(fmt.Sprintf("Created/updated %s", gitignorePath))) + } + + return nil +}