-
Notifications
You must be signed in to change notification settings - Fork 414
Expand file tree
/
Copy pathsemantic-function-refactor.lock.yml
More file actions
8046 lines (7830 loc) · 378 KB
/
semantic-function-refactor.lock.yml
File metadata and controls
8046 lines (7830 loc) · 378 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
#
# ___ _ _
# / _ \ | | (_)
# | |_| | __ _ ___ _ __ | |_ _ ___
# | _ |/ _` |/ _ \ '_ \| __| |/ __|
# | | | | (_| | __/ | | | |_| | (__
# \_| |_/\__, |\___|_| |_|\__|_|\___|
# __/ |
# _ _ |___/
# | | | | / _| |
# | | | | ___ _ __ _ __| |_| | _____ ____
# | |/\| |/ _ \ '__| |/ /| _| |/ _ \ \ /\ / / ___|
# \ /\ / (_) | | | | ( | | | | (_) \ V V /\__ \
# \/ \/ \___/|_| |_|\_\|_| |_|\___/ \_/\_/ |___/
#
# This file was automatically generated by gh-aw. DO NOT EDIT.
# To update this file, edit the corresponding .md file and run:
# gh aw compile
# For more information: https://github.com/githubnext/gh-aw/blob/main/.github/aw/github-agentic-workflows.md
#
# Analyzes Go codebase daily to identify opportunities for semantic function extraction and refactoring
#
# Original Frontmatter:
# ```yaml
# name: Semantic Function Refactoring
# description: Analyzes Go codebase daily to identify opportunities for semantic function extraction and refactoring
# on:
# workflow_dispatch:
# schedule:
# - cron: daily at 08:00
#
# permissions:
# contents: read
# issues: read
# pull-requests: read
#
# engine: claude
#
# imports:
# - shared/reporting.md
#
# safe-outputs:
# close-issue:
# required-title-prefix: "[refactor] "
# target: "*"
# max: 10
# create-issue:
# title-prefix: "[refactor] "
# labels: [refactoring, code-quality, automated-analysis]
# max: 1
#
# tools:
# github:
# toolsets: [default, issues]
# edit:
# bash:
# - "find pkg -name '*.go' ! -name '*_test.go' -type f"
# - "find pkg -type f -name '*.go' ! -name '*_test.go'"
# - "ls -la pkg/"
# - "ls -la pkg/workflow/"
# - "wc -l pkg/**/*.go"
# - "head -n * pkg/**/*.go"
# - "grep -r 'func ' pkg --include='*.go'"
# - "cat pkg/**/*.go"
#
# timeout-minutes: 20
# strict: true
# ```
#
# Resolved workflow manifest:
# Imports:
# - shared/reporting.md
#
# Job Dependency Graph:
# ```mermaid
# graph LR
# activation["activation"]
# agent["agent"]
# close_issue["close_issue"]
# conclusion["conclusion"]
# create_issue["create_issue"]
# detection["detection"]
# activation --> agent
# activation --> conclusion
# agent --> close_issue
# agent --> conclusion
# agent --> create_issue
# agent --> detection
# close_issue --> conclusion
# create_issue --> conclusion
# detection --> close_issue
# detection --> conclusion
# detection --> create_issue
# ```
#
# Original Prompt:
# ```markdown
# ## Report Formatting
#
# Structure your report with an overview followed by detailed content:
#
# 1. **Content Overview**: Start with 1-2 paragraphs that summarize the key findings, highlights, or main points of your report. This should give readers a quick understanding of what the report contains without needing to expand the details.
#
# 2. **Detailed Content**: Place the rest of your report inside HTML `<details>` and `<summary>` tags to allow readers to expand and view the full information. **IMPORTANT**: Always wrap the summary text in `<b>` tags to make it bold.
#
# **Example format:**
#
# `````markdown
# Brief overview paragraph 1 introducing the report and its main findings.
#
# Optional overview paragraph 2 with additional context or highlights.
#
# <details>
# <summary><b>Full Report Details</b></summary>
#
# ## Detailed Analysis
#
# Full report content with all sections, tables, and detailed information goes here.
#
# ### Section 1
# [Content]
#
# ### Section 2
# [Content]
#
# </details>
# `````
#
# ## Reporting Workflow Run Information
#
# When analyzing workflow run logs or reporting information from GitHub Actions runs:
#
# ### 1. Workflow Run ID Formatting
#
# **Always render workflow run IDs as clickable URLs** when mentioning them in your report. The workflow run data includes a `url` field that provides the full GitHub Actions run page URL.
#
# **Format:**
#
# `````markdown
# [§12345](https://github.com/owner/repo/actions/runs/12345)
# `````
#
# **Example:**
#
# `````markdown
# Analysis based on [§456789](https://github.com/githubnext/gh-aw/actions/runs/456789)
# `````
#
# ### 2. Document References for Workflow Runs
#
# When your analysis is based on information mined from one or more workflow runs, **include up to 3 workflow run URLs as document references** at the end of your report.
#
# **Format:**
#
# `````markdown
# ---
#
# **References:**
# - [§12345](https://github.com/owner/repo/actions/runs/12345)
# - [§12346](https://github.com/owner/repo/actions/runs/12346)
# - [§12347](https://github.com/owner/repo/actions/runs/12347)
# `````
#
# **Guidelines:**
#
# - Include **maximum 3 references** to keep reports concise
# - Choose the most relevant or representative runs (e.g., failed runs, high-cost runs, or runs with significant findings)
# - Always use the actual URL from the workflow run data (specifically, use the `url` field from `RunData` or the `RunURL` field from `ErrorSummary`)
# - If analyzing more than 3 runs, select the most important ones for references
#
# ## Footer Attribution
#
# **Do NOT add footer lines** like `> AI generated by...` to your comment. The system automatically appends attribution after your content to prevent duplicates.
#
# # Semantic Function Clustering and Refactoring
#
# You are an AI agent that analyzes Go code to identify potential refactoring opportunities by clustering functions semantically and detecting outliers or duplicates.
#
# ## Mission
#
# **IMPORTANT: Before performing analysis, close any existing open issues with the title prefix `[refactor]` to avoid duplicate issues.**
#
# Analyze all Go source files (`.go` files, excluding test files) in the repository to:
# 1. **First, close existing open issues** with the `[refactor]` prefix
# 2. Collect all function names per file
# 3. Cluster functions semantically by name and purpose
# 4. Identify outliers (functions that might be in the wrong file)
# 5. Use Serena's semantic analysis to detect potential duplicates
# 6. Suggest refactoring fixes
#
# ## Important Constraints
#
# 1. **Only analyze `.go` files** - Ignore all other file types
# 2. **Skip test files** - Never analyze files ending in `_test.go`
# 3. **Focus on pkg/ directory** - Primary analysis area
# 4. **Use Serena for semantic analysis** - Leverage the MCP server's capabilities
# 5. **One file per feature rule** - Files should be named after their primary purpose/feature
#
# ## Serena Configuration
#
# The Serena MCP server is configured for this workspace:
# - **Workspace**: ${{ github.workspace }}
# - **Memory cache**: /tmp/gh-aw/cache-memory/serena
# - **Context**: codex
# - **Language service**: Go (gopls)
#
# ## Close Existing Refactor Issues (CRITICAL FIRST STEP)
#
# **Before performing any analysis**, you must close existing open issues with the `[refactor]` title prefix to prevent duplicate issues.
#
# Use the GitHub API tools to:
# 1. Search for open issues with title containing `[refactor]` in repository ${{ github.repository }}
# 2. Close each found issue with a comment explaining a new analysis is being performed
# 3. Use the `close_issue` safe output to close these issues
#
# **Important**: The `close-issue` safe output is configured with:
# - `required-title-prefix: "[refactor]"` - Only issues starting with this prefix will be closed
# - `target: "*"` - Can close any issue by number (not just triggering issue)
# - `max: 10` - Can close up to 10 issues in one run
#
# To close an existing refactor issue, emit:
# ```
# close_issue(issue_number=123, body="Closing this issue as a new semantic function refactoring analysis is being performed.")
# ```
#
# **Do not proceed with analysis until all existing `[refactor]` issues are closed.**
#
# ## Task Steps
#
# ### 1. Close Existing Refactor Issues
#
# **CRITICAL FIRST STEP**: Before performing any analysis, close existing open issues with the `[refactor]` prefix to prevent duplicate issues.
#
# 1. Use GitHub search to find open issues with `[refactor]` in the title
# 2. For each found issue, use `close_issue` to close it with an explanatory comment
# 3. Example: `close_issue(issue_number=4542, body="Closing this issue as a new semantic function refactoring analysis is being performed.")`
#
# **Do not proceed to step 2 until all existing `[refactor]` issues are closed.**
#
# ### 2. Activate Serena Project
#
# After closing existing issues, activate the project in Serena to enable semantic analysis:
#
# ```bash
# # Serena's activate_project tool should be called with the workspace path
# # This is handled automatically by the MCP server configuration
# ```
#
# Use Serena's `activate_project` tool with the workspace path.
#
# ### 3. Discover Go Source Files
#
# Find all non-test Go files in the repository:
#
# ```bash
# # Find all Go files excluding tests
# find pkg -name "*.go" ! -name "*_test.go" -type f | sort
# ```
#
# Group files by package/directory to understand the organization.
#
# ### 4. Collect Function Names Per File
#
# For each discovered Go file:
#
# 1. Use Serena's `get_symbols_overview` to get all symbols (functions, methods, types) in the file
# 2. Use Serena's `read_file` if needed to understand context
# 3. Create a structured inventory of:
# - File path
# - Package name
# - All function names
# - All method names (with receiver type)
# - Function signatures (parameters and return types)
#
# Example structure:
# ```
# File: pkg/workflow/compiler.go
# Package: workflow
# Functions:
# - CompileWorkflow(path string) error
# - compileFile(data []byte) (*Workflow, error)
# - validateFrontmatter(fm map[string]interface{}) error
# ```
#
# ### 5. Semantic Clustering Analysis
#
# Analyze the collected functions to identify patterns:
#
# **Clustering by Naming Patterns:**
# - Group functions with similar prefixes (e.g., `create*`, `parse*`, `validate*`)
# - Group functions with similar suffixes (e.g., `*Helper`, `*Config`, `*Step`)
# - Identify functions that operate on the same data types
# - Identify functions that share common functionality
#
# **File Organization Rules:**
# According to Go best practices, files should be organized by feature:
# - `compiler.go` - compilation-related functions
# - `parser.go` - parsing-related functions
# - `validator.go` - validation-related functions
# - `create_*.go` - creation/construction functions for specific entities
#
# **Identify Outliers:**
# Look for functions that don't match their file's primary purpose:
# - Validation functions in a compiler file
# - Parser functions in a network file
# - Helper functions scattered across multiple files
# - Generic utility functions not in a dedicated utils file
#
# ### 6. Use Serena for Semantic Duplicate Detection
#
# For each cluster of similar functions:
#
# 1. Use `find_symbol` to locate functions with similar names across files
# 2. Use `search_for_pattern` to find similar code patterns
# 3. Use `find_referencing_symbols` to understand usage patterns
# 4. Compare function implementations to identify:
# - Exact duplicates (identical implementations)
# - Near duplicates (similar logic with variations)
# - Functional duplicates (different implementations, same purpose)
#
# Example Serena tool usage:
# ```bash
# # Find symbols with similar names
# # Use find_symbol for "processData" or similar
# # Use search_for_pattern to find similar implementations
# ```
#
# ### 7. Deep Reasoning Analysis
#
# Apply deep reasoning to identify refactoring opportunities:
#
# **Duplicate Detection Criteria:**
# - Functions with >80% code similarity
# - Functions with identical logic but different variable names
# - Functions that perform the same operation on different types (candidates for generics)
# - Helper functions repeated across multiple files
#
# **Refactoring Patterns to Suggest:**
# - **Extract Common Function**: When 2+ functions share significant code
# - **Move to Appropriate File**: When a function is in the wrong file based on its purpose
# - **Create Utility File**: When helper functions are scattered
# - **Use Generics**: When similar functions differ only by type
# - **Extract Interface**: When similar methods are defined on different types
#
# ### 8. Generate Refactoring Report
#
# Create a comprehensive issue with findings:
#
# **Report Structure:**
#
# ```markdown
# # 🔧 Semantic Function Clustering Analysis
#
# *Analysis of repository: ${{ github.repository }}*
#
# ## Executive Summary
#
# [Brief overview of findings - total files analyzed, clusters found, outliers identified, duplicates detected]
#
# ## Function Inventory
#
# ### By Package
#
# [List of packages with file counts and primary purposes]
#
# ### Clustering Results
#
# [Summary of function clusters identified by semantic similarity]
#
# ## Identified Issues
#
# ### 1. Outlier Functions (Functions in Wrong Files)
#
# **Issue**: Functions that don't match their file's primary purpose
#
# #### Example: Validation in Compiler File
#
# - **File**: `pkg/workflow/compiler.go`
# - **Function**: `validateConfig(cfg *Config) error`
# - **Issue**: Validation function in compiler file
# - **Recommendation**: Move to `pkg/workflow/validation.go`
# - **Estimated Impact**: Improved code organization
#
# [... more outliers ...]
#
# ### 2. Duplicate or Near-Duplicate Functions
#
# **Issue**: Functions with similar or identical implementations
#
# #### Example: String Processing Duplicates
#
# - **Occurrence 1**: `pkg/workflow/helpers.go:processString(s string) string`
# - **Occurrence 2**: `pkg/workflow/utils.go:cleanString(s string) string`
# - **Similarity**: 90% code similarity
# - **Code Comparison**:
# ```go
# // helpers.go
# func processString(s string) string {
# s = strings.TrimSpace(s)
# s = strings.ToLower(s)
# return s
# }
#
# // utils.go
# func cleanString(s string) string {
# s = strings.TrimSpace(s)
# return strings.ToLower(s)
# }
# ```
# - **Recommendation**: Consolidate into single function in `pkg/workflow/strings.go`
# - **Estimated Impact**: Reduced code duplication, easier maintenance
#
# [... more duplicates ...]
#
# ### 3. Scattered Helper Functions
#
# **Issue**: Similar helper functions spread across multiple files
#
# **Examples**:
# - `parseValue()` in 3 different files
# - `formatError()` in 4 different files
# - `sanitizeInput()` in 2 different files
#
# **Recommendation**: Create `pkg/workflow/helpers.go` or enhance existing helper files
# **Estimated Impact**: Centralized utilities, easier testing
#
# ### 4. Opportunities for Generics
#
# **Issue**: Type-specific functions that could use generics
#
# [Examples of functions that differ only by type]
#
# ## Detailed Function Clusters
#
# ### Cluster 1: Creation Functions
#
# **Pattern**: `create*` functions
# **Files**: [list of files]
# **Functions**:
# - `pkg/workflow/create_issue.go:CreateIssue(...)`
# - `pkg/workflow/create_pr.go:CreatePR(...)`
# - `pkg/workflow/create_discussion.go:CreateDiscussion(...)`
#
# **Analysis**: Well-organized - each creation function has its own file ✓
#
# ### Cluster 2: Parsing Functions
#
# **Pattern**: `parse*` functions
# **Files**: [list of files]
# **Functions**: [list]
#
# **Analysis**: [Whether organization is good or needs improvement]
#
# [... more clusters ...]
#
# ## Refactoring Recommendations
#
# ### Priority 1: High Impact
#
# 1. **Move Outlier Functions**
# - Move validation functions to validation.go
# - Move parser functions to appropriate parser files
# - Estimated effort: 2-4 hours
# - Benefits: Clearer code organization
#
# 2. **Consolidate Duplicate Functions**
# - Merge duplicate string processing functions
# - Merge duplicate error formatting functions
# - Estimated effort: 3-5 hours
# - Benefits: Reduced code size, single source of truth
#
# ### Priority 2: Medium Impact
#
# 3. **Centralize Helper Functions**
# - Create or enhance helper utility files
# - Move scattered helpers to central location
# - Estimated effort: 4-6 hours
# - Benefits: Easier discoverability, reduced duplication
#
# ### Priority 3: Long-term Improvements
#
# 4. **Consider Generics for Type-Specific Functions**
# - Identify candidates for generic implementations
# - Estimated effort: 6-8 hours
# - Benefits: Type-safe code reuse
#
# ## Implementation Checklist
#
# - [ ] Review findings and prioritize refactoring tasks
# - [ ] Create detailed refactoring plan for Priority 1 items
# - [ ] Implement outlier function moves
# - [ ] Consolidate duplicate functions
# - [ ] Update tests to reflect changes
# - [ ] Verify no functionality broken
# - [ ] Consider Priority 2 and 3 items for future work
#
# ## Analysis Metadata
#
# - **Total Go Files Analyzed**: [count]
# - **Total Functions Cataloged**: [count]
# - **Function Clusters Identified**: [count]
# - **Outliers Found**: [count]
# - **Duplicates Detected**: [count]
# - **Detection Method**: Serena semantic code analysis + naming pattern analysis
# - **Analysis Date**: [timestamp]
# ```
#
# ## Operational Guidelines
#
# ### Security
# - Never execute untrusted code
# - Only use read-only analysis tools
# - Do not modify files during analysis (read-only mode)
#
# ### Efficiency
# - Use Serena's semantic analysis capabilities effectively
# - Cache Serena results in the memory folder
# - Balance thoroughness with timeout constraints
# - Focus on meaningful patterns, not trivial similarities
#
# ### Accuracy
# - Verify findings before reporting
# - Distinguish between acceptable duplication and problematic duplication
# - Consider Go idioms and best practices
# - Provide specific, actionable recommendations
#
# ### Issue Creation
# - Only create an issue if significant findings are discovered
# - Include sufficient detail for developers to understand and act
# - Provide concrete examples with file paths and function signatures
# - Suggest practical refactoring approaches
# - Focus on high-impact improvements
#
# ## Analysis Focus Areas
#
# ### High-Value Analysis
# 1. **Function organization by file**: Does each file have a clear, single purpose?
# 2. **Function naming patterns**: Are similar functions grouped together?
# 3. **Code duplication**: Are there functions that should be consolidated?
# 4. **Utility scatter**: Are helper functions properly centralized?
#
# ### What to Report
# - Functions clearly in the wrong file (e.g., network functions in parser file)
# - Duplicate implementations of the same functionality
# - Scattered helper functions that should be centralized
# - Opportunities for improved code organization
#
# ### What to Skip
# - Minor naming inconsistencies
# - Single-occurrence patterns
# - Language-specific idioms (constructors, standard patterns)
# - Test files (already excluded)
# - Trivial helper functions (<5 lines)
#
# ## Serena Tool Usage Guide
#
# ### Project Activation
# ```
# Tool: activate_project
# Args: { "path": "${{ github.workspace }}" }
# ```
#
# ### Symbol Overview
# ```
# Tool: get_symbols_overview
# Args: { "file_path": "pkg/workflow/compiler.go" }
# ```
#
# ### Find Similar Symbols
# ```
# Tool: find_symbol
# Args: { "symbol_name": "parseConfig", "workspace": "${{ github.workspace }}" }
# ```
#
# ### Search for Patterns
# ```
# Tool: search_for_pattern
# Args: { "pattern": "func.*Config.*error", "workspace": "${{ github.workspace }}" }
# ```
#
# ### Find References
# ```
# Tool: find_referencing_symbols
# Args: { "symbol_name": "CompileWorkflow", "file_path": "pkg/workflow/compiler.go" }
# ```
#
# ### Read File Content
# ```
# Tool: read_file
# Args: { "file_path": "pkg/workflow/compiler.go" }
# ```
#
# ## Success Criteria
#
# This analysis is successful when:
# 1. ✅ All non-test Go files in pkg/ are analyzed
# 2. ✅ Function names and signatures are collected and organized
# 3. ✅ Semantic clusters are identified based on naming and purpose
# 4. ✅ Outliers (functions in wrong files) are detected
# 5. ✅ Duplicates are identified using Serena's semantic analysis
# 6. ✅ Concrete refactoring recommendations are provided
# 7. ✅ A detailed issue is created with actionable findings
#
# **Objective**: Improve code organization and reduce duplication by identifying refactoring opportunities through semantic function clustering and duplicate detection. Focus on high-impact, actionable findings that developers can implement.
# ```
#
# Pinned GitHub Actions:
# - actions/checkout@v5 (93cb6efe18208431cddfb8368fd83d5badbf9bfd)
# https://github.com/actions/checkout/commit/93cb6efe18208431cddfb8368fd83d5badbf9bfd
# - actions/download-artifact@v6 (018cc2cf5baa6db3ef3c5f8a56943fffe632ef53)
# https://github.com/actions/download-artifact/commit/018cc2cf5baa6db3ef3c5f8a56943fffe632ef53
# - actions/github-script@v8 (ed597411d8f924073f98dfc5c65a23a2325f34cd)
# https://github.com/actions/github-script/commit/ed597411d8f924073f98dfc5c65a23a2325f34cd
# - actions/setup-node@v6 (395ad3262231945c25e8478fd5baf05154b1d79f)
# https://github.com/actions/setup-node/commit/395ad3262231945c25e8478fd5baf05154b1d79f
# - actions/upload-artifact@v5 (330a01c490aca151604b8cf639adc76d48f6c5d4)
# https://github.com/actions/upload-artifact/commit/330a01c490aca151604b8cf639adc76d48f6c5d4
name: "Semantic Function Refactoring"
"on":
schedule:
- cron: "0 8 * * *"
# Friendly format: daily at 08:00
workflow_dispatch: null
permissions:
contents: read
issues: read
pull-requests: read
concurrency:
group: "gh-aw-${{ github.workflow }}"
run-name: "Semantic Function Refactoring"
jobs:
activation:
runs-on: ubuntu-slim
permissions:
contents: read
outputs:
comment_id: ""
comment_repo: ""
steps:
- name: Check workflow file timestamps
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
env:
GH_AW_WORKFLOW_FILE: "semantic-function-refactor.lock.yml"
with:
script: |
async function main() {
const workflowFile = process.env.GH_AW_WORKFLOW_FILE;
if (!workflowFile) {
core.setFailed("Configuration error: GH_AW_WORKFLOW_FILE not available.");
return;
}
const workflowBasename = workflowFile.replace(".lock.yml", "");
const workflowMdPath = `.github/workflows/${workflowBasename}.md`;
const lockFilePath = `.github/workflows/${workflowFile}`;
core.info(`Checking workflow timestamps using GitHub API:`);
core.info(` Source: ${workflowMdPath}`);
core.info(` Lock file: ${lockFilePath}`);
const { owner, repo } = context.repo;
const ref = context.sha;
async function getLastCommitForFile(path) {
try {
const response = await github.rest.repos.listCommits({
owner,
repo,
path,
per_page: 1,
sha: ref,
});
if (response.data && response.data.length > 0) {
const commit = response.data[0];
return {
sha: commit.sha,
date: commit.commit.committer.date,
message: commit.commit.message,
};
}
return null;
} catch (error) {
core.info(`Could not fetch commit for ${path}: ${error.message}`);
return null;
}
}
const workflowCommit = await getLastCommitForFile(workflowMdPath);
const lockCommit = await getLastCommitForFile(lockFilePath);
if (!workflowCommit) {
core.info(`Source file does not exist: ${workflowMdPath}`);
}
if (!lockCommit) {
core.info(`Lock file does not exist: ${lockFilePath}`);
}
if (!workflowCommit || !lockCommit) {
core.info("Skipping timestamp check - one or both files not found");
return;
}
const workflowDate = new Date(workflowCommit.date);
const lockDate = new Date(lockCommit.date);
core.info(` Source last commit: ${workflowDate.toISOString()} (${workflowCommit.sha.substring(0, 7)})`);
core.info(` Lock last commit: ${lockDate.toISOString()} (${lockCommit.sha.substring(0, 7)})`);
if (workflowDate > lockDate) {
const warningMessage = `WARNING: Lock file '${lockFilePath}' is outdated! The workflow file '${workflowMdPath}' has been modified more recently. Run 'gh aw compile' to regenerate the lock file.`;
core.error(warningMessage);
const workflowTimestamp = workflowDate.toISOString();
const lockTimestamp = lockDate.toISOString();
let summary = core.summary
.addRaw("### ⚠️ Workflow Lock File Warning\n\n")
.addRaw("**WARNING**: Lock file is outdated and needs to be regenerated.\n\n")
.addRaw("**Files:**\n")
.addRaw(`- Source: \`${workflowMdPath}\`\n`)
.addRaw(` - Last commit: ${workflowTimestamp}\n`)
.addRaw(
` - Commit SHA: [\`${workflowCommit.sha.substring(0, 7)}\`](https://github.com/${owner}/${repo}/commit/${workflowCommit.sha})\n`
)
.addRaw(`- Lock: \`${lockFilePath}\`\n`)
.addRaw(` - Last commit: ${lockTimestamp}\n`)
.addRaw(` - Commit SHA: [\`${lockCommit.sha.substring(0, 7)}\`](https://github.com/${owner}/${repo}/commit/${lockCommit.sha})\n\n`)
.addRaw("**Action Required:** Run `gh aw compile` to regenerate the lock file.\n\n");
await summary.write();
} else if (workflowCommit.sha === lockCommit.sha) {
core.info("✅ Lock file is up to date (same commit)");
} else {
core.info("✅ Lock file is up to date");
}
}
main().catch(error => {
core.setFailed(error instanceof Error ? error.message : String(error));
});
agent:
needs: activation
runs-on: ubuntu-latest
permissions:
contents: read
issues: read
pull-requests: read
concurrency:
group: "gh-aw-claude-${{ github.workflow }}"
env:
GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs
GH_AW_SAFE_OUTPUTS: /tmp/gh-aw/safeoutputs/outputs.jsonl
GH_AW_SAFE_OUTPUTS_CONFIG_PATH: /tmp/gh-aw/safeoutputs/config.json
GH_AW_SAFE_OUTPUTS_TOOLS_PATH: /tmp/gh-aw/safeoutputs/tools.json
outputs:
has_patch: ${{ steps.collect_output.outputs.has_patch }}
model: ${{ steps.generate_aw_info.outputs.model }}
output: ${{ steps.collect_output.outputs.output }}
output_types: ${{ steps.collect_output.outputs.output_types }}
steps:
- name: Checkout repository
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5
with:
persist-credentials: false
- name: Create gh-aw temp directory
run: |
mkdir -p /tmp/gh-aw/agent
mkdir -p /tmp/gh-aw/sandbox/agent/logs
echo "Created /tmp/gh-aw/agent directory for agentic workflow temporary files"
- name: Configure Git credentials
env:
REPO_NAME: ${{ github.repository }}
SERVER_URL: ${{ github.server_url }}
run: |
git config --global user.email "github-actions[bot]@users.noreply.github.com"
git config --global user.name "github-actions[bot]"
# Re-authenticate git with GitHub token
SERVER_URL_STRIPPED="${SERVER_URL#https://}"
git remote set-url origin "https://x-access-token:${{ github.token }}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git"
echo "Git configured with standard GitHub Actions identity"
- name: Checkout PR branch
if: |
github.event.pull_request
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
env:
GH_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
with:
github-token: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
script: |
async function main() {
const eventName = context.eventName;
const pullRequest = context.payload.pull_request;
if (!pullRequest) {
core.info("No pull request context available, skipping checkout");
return;
}
core.info(`Event: ${eventName}`);
core.info(`Pull Request #${pullRequest.number}`);
try {
if (eventName === "pull_request") {
const branchName = pullRequest.head.ref;
core.info(`Checking out PR branch: ${branchName}`);
await exec.exec("git", ["fetch", "origin", branchName]);
await exec.exec("git", ["checkout", branchName]);
core.info(`✅ Successfully checked out branch: ${branchName}`);
} else {
const prNumber = pullRequest.number;
core.info(`Checking out PR #${prNumber} using gh pr checkout`);
await exec.exec("gh", ["pr", "checkout", prNumber.toString()]);
core.info(`✅ Successfully checked out PR #${prNumber}`);
}
} catch (error) {
core.setFailed(`Failed to checkout PR branch: ${error instanceof Error ? error.message : String(error)}`);
}
}
main().catch(error => {
core.setFailed(error instanceof Error ? error.message : String(error));
});
- name: Validate CLAUDE_CODE_OAUTH_TOKEN or ANTHROPIC_API_KEY secret
run: |
if [ -z "$CLAUDE_CODE_OAUTH_TOKEN" ] && [ -z "$ANTHROPIC_API_KEY" ]; then
{
echo "❌ Error: Neither CLAUDE_CODE_OAUTH_TOKEN nor ANTHROPIC_API_KEY secret is set"
echo "The Claude Code engine requires either CLAUDE_CODE_OAUTH_TOKEN or ANTHROPIC_API_KEY secret to be configured."
echo "Please configure one of these secrets in your repository settings."
echo "Documentation: https://githubnext.github.io/gh-aw/reference/engines/#anthropic-claude-code"
} >> "$GITHUB_STEP_SUMMARY"
echo "Error: Neither CLAUDE_CODE_OAUTH_TOKEN nor ANTHROPIC_API_KEY secret is set"
echo "The Claude Code engine requires either CLAUDE_CODE_OAUTH_TOKEN or ANTHROPIC_API_KEY secret to be configured."
echo "Please configure one of these secrets in your repository settings."
echo "Documentation: https://githubnext.github.io/gh-aw/reference/engines/#anthropic-claude-code"
exit 1
fi
# Log success to stdout (not step summary)
if [ -n "$CLAUDE_CODE_OAUTH_TOKEN" ]; then
echo "CLAUDE_CODE_OAUTH_TOKEN secret is configured"
else
echo "ANTHROPIC_API_KEY secret is configured (using as fallback for CLAUDE_CODE_OAUTH_TOKEN)"
fi
env:
CLAUDE_CODE_OAUTH_TOKEN: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
- name: Setup Node.js
uses: actions/setup-node@395ad3262231945c25e8478fd5baf05154b1d79f # v6
with:
node-version: '24'
package-manager-cache: false
- name: Install Claude Code CLI
run: npm install -g @anthropic-ai/claude-code@2.0.65
- name: Generate Claude Settings
run: |
mkdir -p /tmp/gh-aw/.claude
cat > /tmp/gh-aw/.claude/settings.json << 'EOF'
{
"hooks": {
"PreToolUse": [
{
"matcher": "WebFetch|WebSearch",
"hooks": [
{
"type": "command",
"command": ".claude/hooks/network_permissions.py"
}
]
}
]
}
}
EOF
- name: Generate Network Permissions Hook
run: |
mkdir -p .claude/hooks
cat > .claude/hooks/network_permissions.py << 'EOF'
#!/usr/bin/env python3
"""
Network permissions validator for Claude Code engine.
Generated by gh-aw from workflow-level network configuration.
"""
import json
import sys
import urllib.parse
import re
# Domain allow-list (populated during generation)
# JSON string is safely parsed using json.loads() to eliminate quoting vulnerabilities
ALLOWED_DOMAINS = json.loads('''["crl3.digicert.com","crl4.digicert.com","ocsp.digicert.com","ts-crl.ws.symantec.com","ts-ocsp.ws.symantec.com","crl.geotrust.com","ocsp.geotrust.com","crl.thawte.com","ocsp.thawte.com","crl.verisign.com","ocsp.verisign.com","crl.globalsign.com","ocsp.globalsign.com","crls.ssl.com","ocsp.ssl.com","crl.identrust.com","ocsp.identrust.com","crl.sectigo.com","ocsp.sectigo.com","crl.usertrust.com","ocsp.usertrust.com","s.symcb.com","s.symcd.com","json-schema.org","json.schemastore.org","archive.ubuntu.com","security.ubuntu.com","ppa.launchpad.net","keyserver.ubuntu.com","azure.archive.ubuntu.com","api.snapcraft.io","packagecloud.io","packages.cloud.google.com","packages.microsoft.com"]''')
def extract_domain(url_or_query):
"""Extract domain from URL or search query."""
if not url_or_query:
return None
if url_or_query.startswith(('http://', 'https://')):
return urllib.parse.urlparse(url_or_query).netloc.lower()
# Check for domain patterns in search queries
match = re.search(r'site:([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})', url_or_query)
if match:
return match.group(1).lower()
return None
def is_domain_allowed(domain):
"""Check if domain is allowed."""
if not domain:
# If no domain detected, allow only if not under deny-all policy
return bool(ALLOWED_DOMAINS) # False if empty list (deny-all), True if has domains
# Empty allowed domains means deny all
if not ALLOWED_DOMAINS:
return False
for pattern in ALLOWED_DOMAINS:
regex = pattern.replace('.', r'\.').replace('*', '.*')
if re.match(f'^{regex}$', domain):
return True
return False
# Main logic
try:
data = json.load(sys.stdin)
tool_name = data.get('tool_name', '')
tool_input = data.get('tool_input', {})
if tool_name not in ['WebFetch', 'WebSearch']:
sys.exit(0) # Allow other tools
target = tool_input.get('url') or tool_input.get('query', '')
domain = extract_domain(target)
# For WebSearch, apply domain restrictions consistently
# If no domain detected in search query, check if restrictions are in place
if tool_name == 'WebSearch' and not domain:
# Since this hook is only generated when network permissions are configured,
# empty ALLOWED_DOMAINS means deny-all policy
if not ALLOWED_DOMAINS: # Empty list means deny all
print(f"Network access blocked: deny-all policy in effect", file=sys.stderr)
print(f"No domains are allowed for WebSearch", file=sys.stderr)
sys.exit(2) # Block under deny-all policy
else:
print(f"Network access blocked for web-search: no specific domain detected", file=sys.stderr)
print(f"Allowed domains: {', '.join(ALLOWED_DOMAINS)}", file=sys.stderr)
sys.exit(2) # Block general searches when domain allowlist is configured
if not is_domain_allowed(domain):
print(f"Network access blocked for domain: {domain}", file=sys.stderr)
print(f"Allowed domains: {', '.join(ALLOWED_DOMAINS)}", file=sys.stderr)
sys.exit(2) # Block with feedback to Claude
sys.exit(0) # Allow
except Exception as e:
print(f"Network validation error: {e}", file=sys.stderr)
sys.exit(2) # Block on errors
EOF
chmod +x .claude/hooks/network_permissions.py
- name: Downloading container images
run: |
set -e
docker pull ghcr.io/github/github-mcp-server:v0.24.1
- name: Write Safe Outputs Config
run: |
mkdir -p /tmp/gh-aw/safeoutputs
mkdir -p /tmp/gh-aw/mcp-logs/safeoutputs
cat > /tmp/gh-aw/safeoutputs/config.json << 'EOF'
{"close_issue":{"max":10,"required_title_prefix":"[refactor] "},"create_issue":{"max":1},"missing_tool":{"max":0},"noop":{"max":1}}
EOF
cat > /tmp/gh-aw/safeoutputs/tools.json << 'EOF'
[
{
"description": "Create a new GitHub issue for tracking bugs, feature requests, or tasks. Use this for actionable work items that need assignment, labeling, and status tracking. For reports, announcements, or status updates that don't require task tracking, use create_discussion instead. CONSTRAINTS: Maximum 1 issue(s) can be created. Title will be prefixed with \"[refactor] \". Labels [refactoring code-quality automated-analysis] will be automatically added.",
"inputSchema": {
"additionalProperties": false,
"properties": {
"body": {
"description": "Detailed issue description in Markdown. Do NOT repeat the title as a heading since it already appears as the issue's h1. Include context, reproduction steps, or acceptance criteria as appropriate.",
"type": "string"
},
"labels": {
"description": "Labels to categorize the issue (e.g., 'bug', 'enhancement'). Labels must exist in the repository.",
"items": {
"type": "string"
},
"type": "array"
},
"parent": {
"description": "Parent issue number for creating sub-issues. Can be a real issue number (e.g., 42) or a temporary_id (e.g., 'aw_abc123def456') from a previously created issue in the same workflow run.",
"type": [
"number",
"string"
]
},
"temporary_id": {
"description": "Unique temporary identifier for referencing this issue before it's created. Format: 'aw_' followed by 12 hex characters (e.g., 'aw_abc123def456'). Use '#aw_ID' in body text to reference other issues by their temporary_id; these are replaced with actual issue numbers after creation.",
"type": "string"
},
"title": {
"description": "Concise issue title summarizing the bug, feature, or task. The title appears as the main heading, so keep it brief and descriptive.",
"type": "string"
}
},
"required": [
"title",
"body"
],