[sergo] Sergo Report: filepath-walk-consolidation-and-error-suppression - 2026-04-11 #25840
Closed
Replies: 1 comment
-
|
This discussion has been marked as outdated by Sergo - Serena Go Expert. A newer discussion is available at Discussion #25934. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Executive Summary
Today's Sergo run combined two complementary lenses: extending the error-suppression sweep from the previous run, and a new exploration into utility-function adoption. The most impactful discovery is that the
clipackage already contains afindFileInDirhelper (defined incopilot_events_jsonl.go:131) that perfectly encapsulates the "walk a directory tree to find the first file matching a name" pattern — yet 9 other sites in the same package reimplement the identical pattern inline instead of calling it. A secondary finding confirms that silentos.Setenvdiscards inengine_secrets.goremain unaddressed from the previous run, and a new medium-severity issue was found inmcp_playwright_config.gowhere both return values ofExtractExpressionsare discarded, silently swallowing extraction errors.Overall code quality is good; these are refinement-level issues rather than architectural problems. The codebase continues to show careful error handling in most places, making these outlier suppressions more notable.
Serena Tools Update
Tools Snapshot
Tool Capabilities Used Today
search_for_pattern_ = filepath.Walk,_ = \w+\.\w+\(,go func(),context.WithTimeout,sync.WaitGrouppatternsfind_symbolExtractExpressionssignature inexpression_extraction.gofind_referencing_symbolsfindFileInDirget_symbols_overviewmcp_playwright_config.golist_dir/read_filedocker_images.go,update_check.go,pr_command.go,git.go,safe_outputs_actions.goStrategy Selection
Cached Reuse Component (50%)
Previous Strategy Adapted:
context-sleep-extension-and-error-suppression(2026-04-10, score: 8/10)_ = os.Setenv()inengine_secrets.go. That finding is still open. Today the same_ = func()lens was widened to all non-test production Go files, revealing a larger cluster of suppressed errors infilepath.Walkandexec.Commandcallsites.os.Setenvonly → all_ = method()and_, _ = method()patterns inpkg/, filtered to the most impactful (non-obvious, non-cleanup) suppressions.New Exploration Component (50%)
Novel Approach: Utility function adoption analysis — does the codebase define helpers that are then ignored in favor of inline duplication?
search_for_pattern,find_referencing_symbols,read_filepkg/cli— the largest package (30+ files, heavy I/O operations)Combined Strategy Rationale
The cached component found where errors are suppressed. The new component found why the same pattern keeps appearing: the utility that should replace these inline implementations already exists but isn't widely known/used within the package. Together they tell a complete story: the
findFileInDirhelper was written to prevent this kind of duplication, but the duplication happened anyway — likely because the function is buried insidecopilot_events_jsonl.gowith no indication it's a general-purpose utility.Analysis Execution
Codebase Context
pkg/cli,pkg/workflow_ = func()), goroutine management, utility function adoptionGoroutine Safety Check (New: Ruled Out)
All
go func()spawns inpkg/clinon-test code were inspected:spinner.go:140— WaitGroup-coordinated ✅update_check.go:242— fire-and-forget with context check + panic recovery ✅docker_images.go:132— context-aware withselect ctx.Done()+ exponential backoff ✅mcp_inspect_inspector.go:139— WaitGroup-coordinated with timeout ✅No goroutine leaks found. Goroutine management is solid.
Context Cancellation in Loops (New: Ruled Out)
safe_outputs_actions.go:297–300uses manualcancel()inside afor rangeloop rather thandefer cancel(). This is actually correct —deferwould delay cancellation until the function returns, not the loop iteration. The inlinecancel()beforecontinueis the right pattern here.Findings Summary
findFileInDirduplication (9 sites),os.Setenvsilent failure (3 sites)ExtractExpressionsdouble-discard inmcp_playwright_config.goDetailed Findings
Finding 1 —
findFileInDirUtility Ignored by Same-Package Code (High)Location:
pkg/cli/copilot_events_jsonl.go:131(definition), plus 9 call sites that should use itA generic file-search utility already exists:
The following 9 sites in the same
clipackage duplicate this logic inline instead of callingfindFileInDir:copilot_events_jsonl.goevents.jsonl(duplicate in defining file!)copilot_agent.goredacted_domains.goredacted-urls.logtoken_usage.gotoken-usage.jsonllogs_parsing_core.goAgentOutputArtifactNamelogs_parsing_core.goagentOutputDirlogs_parsing_core.goevents.jsonl+*.loglogs_parsing_core.goevents.jsonl+ session/process logslogs_parsing_core.goagent-stdio.loglogs_download.gooutputDirlogs_github_rate_limit_usage.goImpact: 10 independent reimplementations of the same pattern. Changes to the Walk logic (e.g., handling symlinks, adding logging) must be replicated everywhere. The defining file (
copilot_events_jsonl.go) even has a duplicate next to its own function definition.Note:
logs_parsing_core.gohas more complex variants (multi-file searches) that can't be naively replaced withfindFileInDir, but lines 113–120 and 240–250 are direct substitutions.Finding 2 — Silent
os.SetenvFailure inengine_secrets.go(High, Carried from 2026-04-10)Location:
pkg/cli/engine_secrets.go:329, 377, 430Three prompt functions all silently discard
os.Setenverrors:os.Setenvonly fails when the variable name contains=or a null byte — butreq.Nameis user-controlled (from workflow frontmatter). If a malformed engine secret name reaches these functions, the env var is never set, the workflow engine never gets the secret, but the user sees a success message. The failure is completely invisible.Finding 3 —
ExtractExpressionsDouble-Discard inmcp_playwright_config.go(Medium)Location:
pkg/workflow/mcp_playwright_config.go:53ExtractExpressionssignature (fromexpression_extraction.go:50):ExtractExpressionsis called for its side effect of populating the extractor's internal expression map. The[]*ExpressionMappingresult anderrorare both thrown away. IfExtractExpressionsreturns an error (e.g., on a malformed$\{\{ }}expression),ReplaceExpressionsWithEnvVarswill execute against an incomplete map, producing incorrect/unreplaced expressions in Playwright args — silently.Improvement Tasks Generated
Task 1: Promote
findFileInDirto a Package-Level Utility and Eliminate DuplicatesIssue Type: Code Duplication / Utility Adoption
Problem:
findFileInDiris buried incopilot_events_jsonl.gowith no indication it's a general-purpose helper. Nine other sites in the sameclipackage reimplement the same_ = filepath.Walk()file-search pattern.Location(s):
pkg/cli/copilot_events_jsonl.go:129–142copilot_events_jsonl.go:108,copilot_agent.go:109,redacted_domains.go:122,token_usage.go:195,logs_parsing_core.go:113,240,logs_download.go:858,logs_github_rate_limit_usage.go:86Impact:
Recommendation: Move
findFileInDirto a dedicated utility file (e.g.,pkg/cli/file_search.go) with a clear doc comment indicating it's a general helper. Then replace the 5+ direct-substitution duplicates:Before (repeated pattern):
After:
Validation:
findFileInDirhandles theerrors.New("stop")sentinel correctly (it already does)logs_parsing_core.goare handled separately if they can't be simplifiedEstimated Effort: Small (mechanical substitution)
Task 2: Propagate
os.SetenvErrors inengine_secrets.goIssue Type: Silent Error Suppression / Incorrect User Feedback
Problem: Three token-prompting functions discard
os.Setenverrors and print a success message regardless. Ifreq.Namecontains an invalid character (=or null byte), the secret is never set but the user is told it was received successfully.Location(s):
pkg/cli/engine_secrets.go:329—promptForCopilotTokenUnifiedpkg/cli/engine_secrets.go:377—promptForSystemTokenUnifiedpkg/cli/engine_secrets.go:430—promptForGenericAPIKeyUnifiedImpact:
Recommendation: Check
os.Setenvreturn value and surface errors before printing success:Before:
After:
Validation:
error(check callers to ensure error propagation chain)"INVALID=NAME") to confirm the error is now surfacedSetenvEstimated Effort: Small
Task 3: Handle
ExtractExpressionsError inmcp_playwright_config.goIssue Type: Silent Error Discard / Incorrect Output
Problem:
replaceExpressionsInPlaywrightArgscallsExtractExpressionsfor its side effect but discards the error. An extraction failure would causeReplaceExpressionsWithEnvVarsto silently produce incorrect Playwright configuration.Location(s):
pkg/workflow/mcp_playwright_config.go:53pkg/workflow/expression_extraction.go:50(signature reference)Impact:
$\{\{ }}expressions may be passed un-replaced to the processRecommendation: Return the error from
replaceExpressionsInPlaywrightArgsand propagate it:Before:
After:
Validation:
replaceExpressionsInPlaywrightArgsto handle the newerrorreturnExpressionExtractor.ExtractExpressionsactually returns meaningful errors (check test cases)Estimated Effort: Small-Medium (signature change requires updating callers)
Success Metrics
This Run
pkg/cliandpkg/workflowReasoning for Score
pkg/clierror suppression andpkg/workflowexpression handling. Goroutine analysis was thorough and correctly ruled out false positives.Historical Context
Strategy Performance
Cumulative Statistics
Recommendations
Immediate Actions
findFileInDirtopkg/cli/file_search.goand replace the 5+ direct-substitution duplicates incopilot_agent.go,redacted_domains.go,token_usage.go,logs_parsing_core.go:113,logs_parsing_core.go:240,logs_github_rate_limit_usage.goos.Setenverrors inengine_secrets.go:329,377,430— check callers accept an error return and thread it upwardreplaceExpressionsInPlaywrightArgssignature to return([]string, error)and update its callersLong-term Improvements
findFileInDirduplication suggests that utility functions defined in domain-specific files (e.g.,copilot_events_jsonl.go) are not discoverable. Consider creating apkg/cli/util.go(orpkg/cli/file_search.go) as a canonical home for general-purpose helpers, with a comment indicating they are package-wide utilities._ = os.Setenv: Consider adding anerrchecklinter exception list that explicitly excludes this pattern, making remaining suppressions intentional and visible.Next Run Preview
Suggested Focus Areas
init()bodies (js.go:14, scripts.go:20, expression_patterns.go:67) — 3 runs without resolutionstrings.Builderadoption — check for+=string concatenation in loops, which Go's compiler handles butstrings.Buildermakes explicit and measurablereplaceExpressionsInPlaywrightArgscallers are updated if Task 3 is completedStrategy Evolution
The "utility adoption" lens proved productive today (new approach). Consider pairing it with the "duplicate code detection" strategy next cycle — look for other internal helpers that are defined once but ignored in favor of inline reimplementation.
References:
Run ID: 24290724834 · Strategy: filepath-walk-consolidation-and-error-suppression
Beta Was this translation helpful? Give feedback.
All reactions