Repository navigation
Expand file tree
/
Copy pathcompiler.go
More file actions
2471 lines (2131 loc) · 87.7 KB
/
Copy pathcompiler.go
File metadata and controls
2471 lines (2131 loc) · 87.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package workflow
import (
_ "embed"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/githubnext/gh-aw/pkg/console"
"github.com/githubnext/gh-aw/pkg/constants"
"github.com/githubnext/gh-aw/pkg/parser"
"github.com/githubnext/gh-aw/pkg/workflow/pretty"
"github.com/goccy/go-yaml"
"github.com/santhosh-tekuri/jsonschema/v6"
)
const (
// OutputArtifactName is the standard name for GITHUB_AW_SAFE_OUTPUTS artifact
OutputArtifactName = "safe_output.jsonl"
)
//go:embed schemas/github-workflow.json
var githubWorkflowSchema string
// FileTracker interface for tracking files created during compilation
type FileTracker interface {
TrackCreated(filePath string)
}
// Compiler handles converting markdown workflows to GitHub Actions YAML
type Compiler struct {
verbose bool
engineOverride string
customOutput string // If set, output will be written to this path instead of default location
version string // Version of the extension
skipValidation bool // If true, skip schema validation
noEmit bool // If true, validate without generating lock files
jobManager *JobManager // Manages jobs and dependencies
engineRegistry *EngineRegistry // Registry of available agentic engines
fileTracker FileTracker // Optional file tracker for tracking created files
}
// generateSafeFileName converts a workflow name to a safe filename for logs
func generateSafeFileName(name string) string {
// Replace spaces and special characters with hyphens
result := strings.ReplaceAll(name, " ", "-")
result = strings.ReplaceAll(result, "/", "-")
result = strings.ReplaceAll(result, "\\", "-")
result = strings.ReplaceAll(result, ":", "-")
result = strings.ReplaceAll(result, "*", "-")
result = strings.ReplaceAll(result, "?", "-")
result = strings.ReplaceAll(result, "\"", "-")
result = strings.ReplaceAll(result, "<", "-")
result = strings.ReplaceAll(result, ">", "-")
result = strings.ReplaceAll(result, "|", "-")
result = strings.ReplaceAll(result, "@", "-")
result = strings.ToLower(result)
// Remove multiple consecutive hyphens
for strings.Contains(result, "--") {
result = strings.ReplaceAll(result, "--", "-")
}
// Trim leading/trailing hyphens
result = strings.Trim(result, "-")
// Ensure it's not empty
if result == "" {
result = "workflow"
}
return result
}
// NewCompiler creates a new workflow compiler with optional configuration
func NewCompiler(verbose bool, engineOverride string, version string) *Compiler {
c := &Compiler{
verbose: verbose,
engineOverride: engineOverride,
version: version,
skipValidation: true, // Skip validation by default for now since existing workflows don't fully comply
jobManager: NewJobManager(),
engineRegistry: GetGlobalEngineRegistry(),
}
return c
}
// SetSkipValidation configures whether to skip schema validation
func (c *Compiler) SetSkipValidation(skip bool) {
c.skipValidation = skip
}
// SetNoEmit configures whether to validate without generating lock files
func (c *Compiler) SetNoEmit(noEmit bool) {
c.noEmit = noEmit
}
// SetFileTracker sets the file tracker for tracking created files
func (c *Compiler) SetFileTracker(tracker FileTracker) {
c.fileTracker = tracker
}
// NewCompilerWithCustomOutput creates a new workflow compiler with custom output path
func NewCompilerWithCustomOutput(verbose bool, engineOverride string, customOutput string, version string) *Compiler {
c := &Compiler{
verbose: verbose,
engineOverride: engineOverride,
customOutput: customOutput,
version: version,
skipValidation: true, // Skip validation by default for now since existing workflows don't fully comply
jobManager: NewJobManager(),
engineRegistry: GetGlobalEngineRegistry(),
}
return c
}
// WorkflowData holds all the data needed to generate a GitHub Actions workflow
type WorkflowData struct {
Name string
FrontmatterName string // name field from frontmatter (for code scanning alert driver default)
On string
Permissions string
Network string // top-level network permissions configuration
Concurrency string
RunName string
Env string
If string
TimeoutMinutes string
CustomSteps string
PostSteps string // steps to run after AI execution
RunsOn string
Tools map[string]any
MarkdownContent string
AI string // "claude" or "codex" (for backwards compatibility)
EngineConfig *EngineConfig // Extended engine configuration
StopTime string
Command string // for /command trigger support
CommandOtherEvents map[string]any // for merging command with other events
AIReaction string // AI reaction type like "eyes", "heart", etc.
Jobs map[string]any // custom job configurations with dependencies
Cache string // cache configuration
NeedsTextOutput bool // whether the workflow uses ${{ needs.task.outputs.text }}
NetworkPermissions *NetworkPermissions // parsed network permissions
SafeOutputs *SafeOutputsConfig // output configuration for automatic output routes
Roles []string // permission levels required to trigger workflow
CacheMemoryConfig *CacheMemoryConfig // parsed cache-memory configuration
}
// SafeOutputsConfig holds configuration for automatic output routes
type SafeOutputsConfig struct {
CreateIssues *CreateIssuesConfig `yaml:"create-issues,omitempty"`
CreateDiscussions *CreateDiscussionsConfig `yaml:"create-discussions,omitempty"`
AddComments *AddCommentsConfig `yaml:"add-comments,omitempty"`
CreatePullRequests *CreatePullRequestsConfig `yaml:"create-pull-requests,omitempty"`
CreatePullRequestReviewComments *CreatePullRequestReviewCommentsConfig `yaml:"create-pull-request-review-comments,omitempty"`
CreateCodeScanningAlerts *CreateCodeScanningAlertsConfig `yaml:"create-code-scanning-alerts,omitempty"`
AddLabels *AddLabelsConfig `yaml:"add-labels,omitempty"`
UpdateIssues *UpdateIssuesConfig `yaml:"update-issues,omitempty"`
PushToPullRequestBranch *PushToPullRequestBranchConfig `yaml:"push-to-pr-branch,omitempty"`
UploadAssets *UploadAssetsConfig `yaml:"upload-assets,omitempty"`
MissingTool *MissingToolConfig `yaml:"missing-tool,omitempty"` // Optional for reporting missing functionality
AllowedDomains []string `yaml:"allowed-domains,omitempty"`
Staged *bool `yaml:"staged,omitempty"` // If true, emit step summary messages instead of making GitHub API calls
Env map[string]string `yaml:"env,omitempty"` // Environment variables to pass to safe output jobs
GitHubToken string `yaml:"github-token,omitempty"` // GitHub token for safe output jobs
MaximumPatchSize int `yaml:"max-patch-size,omitempty"` // Maximum allowed patch size in KB (defaults to 1024)
}
// CompileWorkflow converts a markdown workflow to GitHub Actions YAML
func (c *Compiler) CompileWorkflow(markdownPath string) error {
// replace the .md extension by .lock.yml
lockFile := strings.TrimSuffix(markdownPath, ".md") + ".lock.yml"
if c.verbose {
fmt.Println(console.FormatInfoMessage(fmt.Sprintf("Starting compilation of: %s", console.ToRelativePath(markdownPath))))
fmt.Println(console.FormatInfoMessage(fmt.Sprintf("Output file: %s", console.ToRelativePath(lockFile))))
}
// Parse the markdown file
if c.verbose {
fmt.Println(console.FormatInfoMessage("Parsing workflow file..."))
}
workflowData, err := c.parseWorkflowFile(markdownPath)
if err != nil {
// Check if this is already a formatted console error
if strings.Contains(err.Error(), ":") && (strings.Contains(err.Error(), "error:") || strings.Contains(err.Error(), "warning:")) {
// Already formatted, return as-is
return err
}
// Otherwise, create a basic formatted error
formattedErr := console.FormatError(console.CompilerError{
Position: console.ErrorPosition{
File: markdownPath,
Line: 1,
Column: 1,
},
Type: "error",
Message: err.Error(),
})
return errors.New(formattedErr)
}
// Validate expression safety - check that all GitHub Actions expressions are in the allowed list
if c.verbose {
fmt.Println(console.FormatInfoMessage("Validating expression safety..."))
}
if err := validateExpressionSafety(workflowData.MarkdownContent); err != nil {
formattedErr := console.FormatError(console.CompilerError{
Position: console.ErrorPosition{
File: markdownPath,
Line: 1,
Column: 1,
},
Type: "error",
Message: err.Error(),
})
return errors.New(formattedErr)
}
if c.verbose {
fmt.Println(console.FormatSuccessMessage("Expression safety validation passed"))
}
if c.verbose {
fmt.Println(console.FormatSuccessMessage("Successfully parsed frontmatter and markdown content"))
fmt.Println(console.FormatInfoMessage(fmt.Sprintf("Workflow name: %s", workflowData.Name)))
if len(workflowData.Tools) > 0 {
fmt.Println(console.FormatInfoMessage(fmt.Sprintf("Tools configured: %d", len(workflowData.Tools))))
}
if workflowData.AIReaction != "" {
fmt.Println(console.FormatInfoMessage(fmt.Sprintf("AI reaction configured: %s", workflowData.AIReaction)))
}
}
// Note: compute-text functionality is now inlined directly in the task job
// instead of using a shared action file
// Generate the YAML content
if c.verbose {
fmt.Println(console.FormatInfoMessage("Generating GitHub Actions YAML..."))
}
yamlContent, err := c.generateYAML(workflowData, markdownPath)
if err != nil {
formattedErr := console.FormatError(console.CompilerError{
Position: console.ErrorPosition{
File: markdownPath,
Line: 1,
Column: 1,
},
Type: "error",
Message: fmt.Sprintf("failed to generate YAML: %v", err),
})
return errors.New(formattedErr)
}
if c.verbose {
fmt.Println(console.FormatSuccessMessage(fmt.Sprintf("Generated YAML content (%d bytes)", len(yamlContent))))
}
if c.verbose {
fmt.Println(console.FormatSuccessMessage(fmt.Sprintf("Generated YAML content (%d bytes)", len(yamlContent))))
}
// Validate against GitHub Actions schema (unless skipped)
if !c.skipValidation {
if c.verbose {
fmt.Println(console.FormatInfoMessage("Validating workflow against GitHub Actions schema..."))
}
if err := c.validateGitHubActionsSchema(yamlContent); err != nil {
formattedErr := console.FormatError(console.CompilerError{
Position: console.ErrorPosition{
File: markdownPath,
Line: 1,
Column: 1,
},
Type: "error",
Message: fmt.Sprintf("workflow schema validation failed: %v", err),
})
return errors.New(formattedErr)
}
if c.verbose {
fmt.Println(console.FormatSuccessMessage("GitHub Actions schema validation passed"))
}
} else if c.verbose {
fmt.Println(console.FormatWarningMessage("Schema validation available but skipped (use SetSkipValidation(false) to enable)"))
}
// Write to lock file (unless noEmit is enabled)
if c.noEmit {
if c.verbose {
fmt.Println(console.FormatInfoMessage("Validation completed - no lock file generated (--no-emit enabled)"))
}
} else {
if c.verbose {
fmt.Println(console.FormatInfoMessage(fmt.Sprintf("Writing output to: %s", console.ToRelativePath(lockFile))))
}
if err := os.WriteFile(lockFile, []byte(yamlContent), 0644); err != nil {
formattedErr := console.FormatError(console.CompilerError{
Position: console.ErrorPosition{
File: lockFile,
Line: 1,
Column: 1,
},
Type: "error",
Message: fmt.Sprintf("failed to write lock file: %v", err),
})
return errors.New(formattedErr)
}
}
// Display success message with file size if we generated a lock file
if c.noEmit {
fmt.Println(console.FormatSuccessMessage(console.ToRelativePath(markdownPath)))
} else {
// Get the size of the generated lock file for display
if lockFileInfo, err := os.Stat(lockFile); err == nil {
lockSize := pretty.FormatFileSize(lockFileInfo.Size())
fmt.Println(console.FormatSuccessMessage(fmt.Sprintf("%s (%s)", console.ToRelativePath(markdownPath), lockSize)))
} else {
// Fallback to original display if we can't get file info
fmt.Println(console.FormatSuccessMessage(console.ToRelativePath(markdownPath)))
}
}
return nil
}
// validateGitHubActionsSchema validates the generated YAML content against the GitHub Actions workflow schema
func (c *Compiler) validateGitHubActionsSchema(yamlContent string) error {
// Convert YAML to any for JSON conversion
var workflowData any
if err := yaml.Unmarshal([]byte(yamlContent), &workflowData); err != nil {
return fmt.Errorf("failed to parse YAML for schema validation: %w", err)
}
// Convert to JSON for schema validation
jsonData, err := json.Marshal(workflowData)
if err != nil {
return fmt.Errorf("failed to convert YAML to JSON for validation: %w", err)
}
// Parse the embedded schema
var schemaDoc any
if err := json.Unmarshal([]byte(githubWorkflowSchema), &schemaDoc); err != nil {
return fmt.Errorf("failed to parse embedded GitHub Actions schema: %w", err)
}
// Create compiler and add the schema as a resource
loader := jsonschema.NewCompiler()
schemaURL := "https://json.schemastore.org/github-workflow.json"
if err := loader.AddResource(schemaURL, schemaDoc); err != nil {
return fmt.Errorf("failed to add schema resource: %w", err)
}
// Compile the schema
schema, err := loader.Compile(schemaURL)
if err != nil {
return fmt.Errorf("failed to compile GitHub Actions schema: %w", err)
}
// Validate the JSON data against the schema
var jsonObj any
if err := json.Unmarshal(jsonData, &jsonObj); err != nil {
return fmt.Errorf("failed to unmarshal JSON for validation: %w", err)
}
if err := schema.Validate(jsonObj); err != nil {
return fmt.Errorf("GitHub Actions schema validation failed: %w", err)
}
return nil
}
// parseWorkflowFile parses a markdown workflow file and extracts all necessary data
func (c *Compiler) parseWorkflowFile(markdownPath string) (*WorkflowData, error) {
if c.verbose {
fmt.Println(console.FormatInfoMessage(fmt.Sprintf("Reading file: %s", console.ToRelativePath(markdownPath))))
}
// Read the file
content, err := os.ReadFile(markdownPath)
if err != nil {
return nil, fmt.Errorf("failed to read file: %w", err)
}
if c.verbose {
fmt.Println(console.FormatInfoMessage(fmt.Sprintf("File size: %d bytes", len(content))))
fmt.Println(console.FormatInfoMessage("Extracting frontmatter..."))
}
// Parse frontmatter and markdown
result, err := parser.ExtractFrontmatterFromContent(string(content))
if err != nil {
// Use FrontmatterStart from result if available, otherwise default to line 2 (after opening ---)
frontmatterStart := 2
if result != nil && result.FrontmatterStart > 0 {
frontmatterStart = result.FrontmatterStart
}
return nil, c.createFrontmatterError(markdownPath, string(content), err, frontmatterStart)
}
if len(result.Frontmatter) == 0 {
return nil, fmt.Errorf("no frontmatter found")
}
if result.Markdown == "" {
return nil, fmt.Errorf("no markdown content found")
}
// Check for deprecated stop-time usage at root level BEFORE schema validation
if stopTimeValue := c.extractYAMLValue(result.Frontmatter, "stop-time"); stopTimeValue != "" {
return nil, fmt.Errorf("'stop-time' is no longer supported at the root level. Please move it under the 'on:' section and rename to 'stop-after:'.\n\nExample:\n---\non:\n schedule:\n - cron: \"0 9 * * 1\"\n stop-after: \"%s\"\n---", stopTimeValue)
}
// Validate main workflow frontmatter contains only expected entries
if err := parser.ValidateMainWorkflowFrontmatterWithSchemaAndLocation(result.Frontmatter, markdownPath); err != nil {
return nil, err
}
if c.verbose {
fmt.Println(console.FormatInfoMessage(fmt.Sprintf("Frontmatter length: %d characters", len(result.Frontmatter))))
fmt.Println(console.FormatInfoMessage(fmt.Sprintf("Markdown content length: %d characters", len(result.Markdown))))
}
markdownDir := filepath.Dir(markdownPath)
// Extract AI engine setting from frontmatter
engineSetting, engineConfig := c.extractEngineConfig(result.Frontmatter)
// Extract network permissions from frontmatter
networkPermissions := c.extractNetworkPermissions(result.Frontmatter)
// Default to 'defaults' network access if no network permissions specified
if networkPermissions == nil {
networkPermissions = &NetworkPermissions{
Mode: "defaults",
}
}
// Override with command line AI engine setting if provided
if c.engineOverride != "" {
originalEngineSetting := engineSetting
if originalEngineSetting != "" && originalEngineSetting != c.engineOverride {
fmt.Println(console.FormatWarningMessage(fmt.Sprintf("Command line --engine %s overrides markdown file engine: %s", c.engineOverride, originalEngineSetting)))
}
engineSetting = c.engineOverride
}
// Process @include directives to extract engine configurations and check for conflicts
includedEngines, err := parser.ExpandIncludesForEngines(result.Markdown, markdownDir)
if err != nil {
return nil, fmt.Errorf("failed to expand includes for engines: %w", err)
}
// Validate that only one engine field exists across all files
finalEngineSetting, err := c.validateSingleEngineSpecification(engineSetting, includedEngines)
if err != nil {
return nil, err
}
if finalEngineSetting != "" {
engineSetting = finalEngineSetting
}
// Apply the default AI engine setting if not specified
if engineSetting == "" {
defaultEngine := c.engineRegistry.GetDefaultEngine()
engineSetting = defaultEngine.GetID()
if c.verbose {
fmt.Println(console.FormatInfoMessage(fmt.Sprintf("NOTE: No 'engine:' setting found, defaulting to: %s", engineSetting)))
}
}
// Validate the engine setting
if err := c.validateEngine(engineSetting); err != nil {
return nil, fmt.Errorf("invalid engine setting '%s': %w", engineSetting, err)
}
// Get the agentic engine instance
agenticEngine, err := c.getAgenticEngine(engineSetting)
if err != nil {
return nil, fmt.Errorf("failed to get agentic engine: %w", err)
}
if c.verbose {
fmt.Println(console.FormatInfoMessage(fmt.Sprintf("AI engine: %s (%s)", agenticEngine.GetDisplayName(), engineSetting)))
if agenticEngine.IsExperimental() {
fmt.Println(console.FormatWarningMessage(fmt.Sprintf("Using experimental engine: %s", agenticEngine.GetDisplayName())))
}
fmt.Println(console.FormatInfoMessage("Processing tools and includes..."))
}
// Extract SafeOutputs configuration early so we can use it when applying default tools
safeOutputs := c.extractSafeOutputsConfig(result.Frontmatter)
var tools map[string]any
// Extract tools from the main file
topTools := extractToolsFromFrontmatter(result.Frontmatter)
// Process @include directives to extract additional tools
includedTools, err := parser.ExpandIncludes(result.Markdown, markdownDir, true)
if err != nil {
return nil, fmt.Errorf("failed to expand includes for tools: %w", err)
}
// Merge tools
tools, err = c.mergeTools(topTools, includedTools)
if err != nil {
return nil, fmt.Errorf("failed to merge tools: %w", err)
}
// Validate MCP configurations
if err := ValidateMCPConfigs(tools); err != nil {
return nil, fmt.Errorf("invalid MCP configuration: %w", err)
}
// Validate HTTP transport support for the current engine
if err := c.validateHTTPTransportSupport(tools, agenticEngine); err != nil {
return nil, fmt.Errorf("HTTP transport not supported: %w", err)
}
if !agenticEngine.SupportsToolsAllowlist() {
// For engines that don't support tool allowlists (like codex), ignore tools section and provide warnings
fmt.Println(console.FormatWarningMessage(fmt.Sprintf("Using experimental %s support (engine: %s)", agenticEngine.GetDisplayName(), engineSetting)))
if _, hasTools := result.Frontmatter["tools"]; hasTools {
fmt.Println(console.FormatWarningMessage(fmt.Sprintf("'tools' section ignored when using engine: %s (%s doesn't support MCP tool allow-listing)", engineSetting, agenticEngine.GetDisplayName())))
}
tools = map[string]any{}
// For now, we'll add a basic github tool (always uses docker MCP)
githubConfig := map[string]any{}
tools["github"] = githubConfig
}
// Validate max-turns support for the current engine
if err := c.validateMaxTurnsSupport(result.Frontmatter, agenticEngine); err != nil {
return nil, fmt.Errorf("max-turns not supported: %w", err)
}
// Process @include directives in markdown content
markdownContent, err := parser.ExpandIncludes(result.Markdown, markdownDir, false)
if err != nil {
return nil, fmt.Errorf("failed to expand includes in markdown: %w", err)
}
if c.verbose {
fmt.Println(console.FormatInfoMessage("Expanded includes in markdown content"))
}
// Extract workflow name
workflowName, err := parser.ExtractWorkflowNameFromMarkdown(markdownPath)
if err != nil {
return nil, fmt.Errorf("failed to extract workflow name: %w", err)
}
// Check if frontmatter specifies a custom name and use it instead
frontmatterName := extractStringValue(result.Frontmatter, "name")
if frontmatterName != "" {
workflowName = frontmatterName
}
if c.verbose {
fmt.Println(console.FormatInfoMessage(fmt.Sprintf("Extracted workflow name: '%s'", workflowName)))
}
// Check if the markdown content uses the text output
needsTextOutput := c.detectTextOutputUsage(markdownContent)
// Build workflow data
workflowData := &WorkflowData{
Name: workflowName,
FrontmatterName: frontmatterName,
Tools: tools,
MarkdownContent: markdownContent,
AI: engineSetting,
EngineConfig: engineConfig,
NetworkPermissions: networkPermissions,
NeedsTextOutput: needsTextOutput,
}
// Extract YAML sections from frontmatter - use direct frontmatter map extraction
// to avoid issues with nested keys (e.g., tools.mcps.*.env being confused with top-level env)
workflowData.On = c.extractTopLevelYAMLSection(result.Frontmatter, "on")
workflowData.Permissions = c.extractTopLevelYAMLSection(result.Frontmatter, "permissions")
workflowData.Network = c.extractTopLevelYAMLSection(result.Frontmatter, "network")
workflowData.Concurrency = c.extractTopLevelYAMLSection(result.Frontmatter, "concurrency")
workflowData.RunName = c.extractTopLevelYAMLSection(result.Frontmatter, "run-name")
workflowData.Env = c.extractTopLevelYAMLSection(result.Frontmatter, "env")
workflowData.If = c.extractIfCondition(result.Frontmatter)
workflowData.TimeoutMinutes = c.extractTopLevelYAMLSection(result.Frontmatter, "timeout_minutes")
workflowData.CustomSteps = c.extractTopLevelYAMLSection(result.Frontmatter, "steps")
workflowData.PostSteps = c.extractTopLevelYAMLSection(result.Frontmatter, "post-steps")
workflowData.RunsOn = c.extractTopLevelYAMLSection(result.Frontmatter, "runs-on")
workflowData.Cache = c.extractTopLevelYAMLSection(result.Frontmatter, "cache")
workflowData.CacheMemoryConfig = c.extractCacheMemoryConfig(topTools)
// Process stop-after configuration from the on: section
err = c.processStopAfterConfiguration(result.Frontmatter, workflowData)
if err != nil {
return nil, err
}
workflowData.Command = c.extractCommandName(result.Frontmatter)
workflowData.Jobs = c.extractJobsFromFrontmatter(result.Frontmatter)
workflowData.Roles = c.extractRoles(result.Frontmatter)
// Use the already extracted output configuration
workflowData.SafeOutputs = safeOutputs
// Parse the "on" section for command triggers, reactions, and other events
err = c.parseOnSection(result.Frontmatter, workflowData, markdownPath)
if err != nil {
return nil, err
}
// Apply defaults
c.applyDefaults(workflowData, markdownPath)
// Apply pull request draft filter if specified
c.applyPullRequestDraftFilter(workflowData, result.Frontmatter)
// Apply pull request fork filter if specified
c.applyPullRequestForkFilter(workflowData, result.Frontmatter)
return workflowData, nil
}
// extractTopLevelYAMLSection extracts a top-level YAML section from the frontmatter map
// This ensures we only extract keys at the root level, avoiding nested keys with the same name
func (c *Compiler) extractTopLevelYAMLSection(frontmatter map[string]any, key string) string {
value, exists := frontmatter[key]
if !exists {
return ""
}
// Convert the value back to YAML format
yamlBytes, err := yaml.Marshal(map[string]any{key: value})
if err != nil {
return ""
}
yamlStr := string(yamlBytes)
// Remove the trailing newline
yamlStr = strings.TrimSuffix(yamlStr, "\n")
// Clean up quoted keys - replace "key": with key:
// This handles cases where YAML marshaling adds unnecessary quotes around reserved words like "on"
quotedKeyPattern := `"` + key + `":`
unquotedKey := key + ":"
yamlStr = strings.Replace(yamlStr, quotedKeyPattern, unquotedKey, 1)
// Special handling for "on" section - comment out draft and fork fields from pull_request
if key == "on" {
yamlStr = c.commentOutProcessedFieldsInOnSection(yamlStr)
}
return yamlStr
}
// extractIfCondition extracts the if condition from frontmatter, returning just the expression
// without the "if: " prefix
func (c *Compiler) extractIfCondition(frontmatter map[string]any) string {
value, exists := frontmatter["if"]
if !exists {
return ""
}
// Convert the value to string - it should be just the expression
if strValue, ok := value.(string); ok {
return c.extractExpressionFromIfString(strValue)
}
return ""
}
// extractExpressionFromIfString extracts the expression part from a string that might
// contain "if: expression" or just "expression", returning just the expression
func (c *Compiler) extractExpressionFromIfString(ifString string) string {
if ifString == "" {
return ""
}
// Check if the string starts with "if: " and strip it
if strings.HasPrefix(ifString, "if: ") {
return strings.TrimSpace(ifString[4:]) // Remove "if: " prefix
}
// Return the string as-is (it's just the expression)
return ifString
}
// commentOutProcessedFieldsInOnSection comments out draft, fork, and forks fields in pull_request sections within the YAML string
// These fields are processed separately by applyPullRequestDraftFilter and applyPullRequestForkFilter and should be commented for documentation
func (c *Compiler) commentOutProcessedFieldsInOnSection(yamlStr string) string {
lines := strings.Split(yamlStr, "\n")
var result []string
inPullRequest := false
inForksArray := false
for _, line := range lines {
// Check if we're entering a pull_request section
if strings.Contains(line, "pull_request:") {
inPullRequest = true
result = append(result, line)
continue
}
// Check if we're leaving the pull_request section (new top-level key or end of indent)
if inPullRequest {
// If line is not indented or is a new top-level key, we're out of pull_request
if strings.TrimSpace(line) != "" && !strings.HasPrefix(line, " ") && !strings.HasPrefix(line, "\t") {
inPullRequest = false
inForksArray = false
}
}
trimmedLine := strings.TrimSpace(line)
// Check if we're entering the forks array
if inPullRequest && strings.HasPrefix(trimmedLine, "forks:") {
inForksArray = true
}
// Check if we're leaving the forks array by encountering another top-level field at the same level
if inForksArray && inPullRequest && strings.TrimSpace(line) != "" {
// Get the indentation of the current line
lineIndent := len(line) - len(strings.TrimLeft(line, " \t"))
// If this is a non-dash line at the same level as the forks field (4 spaces), we're out of the array
if lineIndent == 4 && !strings.HasPrefix(trimmedLine, "-") && !strings.HasPrefix(trimmedLine, "forks:") {
inForksArray = false
}
}
// Determine if we should comment out this line
shouldComment := false
var commentReason string
if inPullRequest && strings.Contains(trimmedLine, "draft:") {
shouldComment = true
commentReason = " # Draft filtering applied via job conditions"
} else if inPullRequest && strings.HasPrefix(trimmedLine, "forks:") {
shouldComment = true
commentReason = " # Fork filtering applied via job conditions"
} else if inForksArray && strings.HasPrefix(trimmedLine, "-") {
shouldComment = true
commentReason = " # Fork filtering applied via job conditions"
}
if shouldComment {
// Preserve the original indentation and comment out the line
indentation := ""
trimmed := strings.TrimLeft(line, " \t")
if len(line) > len(trimmed) {
indentation = line[:len(line)-len(trimmed)]
}
commentedLine := indentation + "# " + trimmed + commentReason
result = append(result, commentedLine)
} else {
result = append(result, line)
}
}
return strings.Join(result, "\n")
}
// parseOnSection parses the "on" section from frontmatter to extract command triggers, reactions, and other events
func (c *Compiler) parseOnSection(frontmatter map[string]any, workflowData *WorkflowData, markdownPath string) error {
// Check if "command" is used as a trigger in the "on" section
// Also extract "reaction" from the "on" section
var hasCommand bool
var hasReaction bool
var hasStopAfter bool
var otherEvents map[string]any
if onValue, exists := frontmatter["on"]; exists {
// Check for new format: on.command and on.reaction
if onMap, ok := onValue.(map[string]any); ok {
// Check for stop-after in the on section
if _, hasStopAfterKey := onMap["stop-after"]; hasStopAfterKey {
hasStopAfter = true
}
// Extract reaction from on section
if reactionValue, hasReactionField := onMap["reaction"]; hasReactionField {
hasReaction = true
if reactionStr, ok := reactionValue.(string); ok {
workflowData.AIReaction = reactionStr
}
}
if _, hasCommandKey := onMap["command"]; hasCommandKey {
hasCommand = true
// Set default command to filename if not specified in the command section
if workflowData.Command == "" {
baseName := strings.TrimSuffix(filepath.Base(markdownPath), ".md")
workflowData.Command = baseName
}
// Check for conflicting events
conflictingEvents := []string{"issues", "issue_comment", "pull_request", "pull_request_review_comment"}
for _, eventName := range conflictingEvents {
if _, hasConflict := onMap[eventName]; hasConflict {
return fmt.Errorf("cannot use 'command' with '%s' in the same workflow", eventName)
}
}
// Clear the On field so applyDefaults will handle command trigger generation
workflowData.On = ""
}
// Extract other (non-conflicting) events excluding command, reaction, and stop-after
otherEvents = filterMapKeys(onMap, "command", "reaction", "stop-after")
}
}
// Clear command field if no command trigger was found
if !hasCommand {
workflowData.Command = ""
}
// Store other events for merging in applyDefaults
if hasCommand && len(otherEvents) > 0 {
// We'll store this and handle it in applyDefaults
workflowData.On = "" // This will trigger command handling in applyDefaults
workflowData.CommandOtherEvents = otherEvents
} else if (hasReaction || hasStopAfter) && len(otherEvents) > 0 {
// Only re-marshal the "on" if we have to
onEventsYAML, err := yaml.Marshal(map[string]any{"on": otherEvents})
if err == nil {
workflowData.On = strings.TrimSuffix(string(onEventsYAML), "\n")
} else {
// Fallback to extracting the original on field (this will include reaction but shouldn't matter for compilation)
workflowData.On = c.extractTopLevelYAMLSection(frontmatter, "on")
}
}
return nil
}
// generateJobName converts a workflow name to a valid YAML job identifier
func (c *Compiler) generateJobName(workflowName string) string {
// Convert to lowercase and replace spaces and special characters with hyphens
jobName := strings.ToLower(workflowName)
// Replace spaces and common punctuation with hyphens
jobName = strings.ReplaceAll(jobName, " ", "-")
jobName = strings.ReplaceAll(jobName, ":", "-")
jobName = strings.ReplaceAll(jobName, ".", "-")
jobName = strings.ReplaceAll(jobName, ",", "-")
jobName = strings.ReplaceAll(jobName, "(", "-")
jobName = strings.ReplaceAll(jobName, ")", "-")
jobName = strings.ReplaceAll(jobName, "/", "-")
jobName = strings.ReplaceAll(jobName, "\\", "-")
jobName = strings.ReplaceAll(jobName, "@", "-")
jobName = strings.ReplaceAll(jobName, "'", "")
jobName = strings.ReplaceAll(jobName, "\"", "")
// Remove multiple consecutive hyphens
for strings.Contains(jobName, "--") {
jobName = strings.ReplaceAll(jobName, "--", "-")
}
// Remove leading/trailing hyphens
jobName = strings.Trim(jobName, "-")
// Ensure it's not empty and starts with a letter or underscore
if jobName == "" || (!strings.ContainsAny(string(jobName[0]), "abcdefghijklmnopqrstuvwxyz_")) {
jobName = "workflow-" + jobName
}
return jobName
} // extractCommandName extracts the command name from frontmatter using the new nested format
func (c *Compiler) extractCommandName(frontmatter map[string]any) string {
// Check new format: on.command.name
if onValue, exists := frontmatter["on"]; exists {
if onMap, ok := onValue.(map[string]any); ok {
if commandValue, hasCommand := onMap["command"]; hasCommand {
if commandMap, ok := commandValue.(map[string]any); ok {
if nameValue, hasName := commandMap["name"]; hasName {
if nameStr, ok := nameValue.(string); ok {
return nameStr
}
}
}
}
}
}
return ""
}
// applyDefaults applies default values for missing workflow sections
func (c *Compiler) applyDefaults(data *WorkflowData, markdownPath string) {
// Check if this is a command trigger workflow (by checking if user specified "on.command")
isCommandTrigger := false
if data.On == "" {
// Check the original frontmatter for command trigger
content, err := os.ReadFile(markdownPath)
if err == nil {
result, err := parser.ExtractFrontmatterFromContent(string(content))
if err == nil {
if onValue, exists := result.Frontmatter["on"]; exists {
// Check for new format: on.command
if onMap, ok := onValue.(map[string]any); ok {
if _, hasCommand := onMap["command"]; hasCommand {
isCommandTrigger = true
}
}
}
}
}
}
if data.On == "" {
if isCommandTrigger {
// Generate command-specific GitHub Actions events (updated to include reopened and pull_request)
commandEvents := `on:
issues:
types: [opened, edited, reopened]
issue_comment:
types: [created, edited]
pull_request:
types: [opened, edited, reopened]
pull_request_review_comment:
types: [created, edited]`
// Check if there are other events to merge
if len(data.CommandOtherEvents) > 0 {
// Merge command events with other events
commandEventsMap := map[string]any{
"issues": map[string]any{
"types": []string{"opened", "edited", "reopened"},
},
"issue_comment": map[string]any{
"types": []string{"created", "edited"},
},
"pull_request": map[string]any{
"types": []string{"opened", "edited", "reopened"},
},
"pull_request_review_comment": map[string]any{
"types": []string{"created", "edited"},
},
}
// Merge other events into command events
for key, value := range data.CommandOtherEvents {
commandEventsMap[key] = value
}
// Convert merged events to YAML
mergedEventsYAML, err := yaml.Marshal(map[string]any{"on": commandEventsMap})
if err == nil {
data.On = strings.TrimSuffix(string(mergedEventsYAML), "\n")
} else {
// If conversion fails, just use command events
data.On = commandEvents
}
} else {
data.On = commandEvents
}
// Add conditional logic to check for command in issue content
// Use event-aware condition that only applies command checks to comment-related events
hasOtherEvents := len(data.CommandOtherEvents) > 0
commandConditionTree := buildEventAwareCommandCondition(data.Command, hasOtherEvents)
if data.If == "" {
data.If = commandConditionTree.Render()
}
} else {
data.On = `on:
# Start either every 10 minutes, or when some kind of human event occurs.
# Because of the implicit "concurrency" section, only one instance of this
# workflow will run at a time.
schedule:
- cron: "0/10 * * * *"
issues:
types: [opened, edited, closed]
issue_comment:
types: [created, edited]
pull_request:
types: [opened, edited, closed]
push:
branches:
- main
workflow_dispatch:`
}
}
if data.Permissions == "" {
// Default behavior: use read-all permissions
data.Permissions = `permissions: read-all`
}