Skip to content

Refactor interactive/audit CLI large functions into focused helpers - #49799

Merged
pelikhan merged 8 commits into
mainfrom
copilot/lint-monster-fix-function-lengths-again
Aug 2, 2026
Merged

Refactor interactive/audit CLI large functions into focused helpers#49799
pelikhan merged 8 commits into
mainfrom
copilot/lint-monster-fix-function-lengths-again

Conversation

Copilot AI commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

This PR addresses the lint-monster largefunc slice for CLI interactive/audit/entrypoint flows by decomposing oversized functions into focused internal helpers while preserving existing command behavior. The changes are intentionally scoped to the reported CLI files in this slice.

  • Interactive flow decomposition (pkg/cli/add_interactive_*)

    • Split engine selection into smaller phases: workflow-engine discovery, default-engine resolution, option construction, and option prioritization.
    • Split PR/merge orchestration into dedicated helpers for merge-loop state, action prompting, title editing, and secret configuration.
    • Split orchestrator setup into explicit phases: host auto-detection, preflight checks, preparation/confirmation, and bootstrap application.
  • Audit diff decomposition (pkg/cli/audit_diff.go)

    • Broke computeFirewallDiff into domain-focused helpers:
      • stats extraction
      • domain collection
      • per-domain diff classification
      • new/removed/existing domain entry builders
    • Kept anomaly semantics and summary accounting unchanged.
  • Access log and action build decomposition

    • parseSquidAccessLog: extracted line processing, status classification, and unique-domain append helpers.
    • buildAction: extracted JavaScript action build path into a dedicated helper, keeping setup/composite branching intact.
  • Targeted helper tests

    • Added focused tests for new helper behavior in:
      • add_interactive_engine_test.go (prioritizeEngineOption)
      • add_interactive_git_test.go (buildMergeOptions)
func buildMergeOptions(mergeFailed, userReviewing bool) []huh.Option[mergeAction] {
	options := []huh.Option[mergeAction]{
		huh.NewOption("Attempt to merge", mergeActionAttempt),
	}
	if mergeFailed {
		options = append(options, huh.NewOption("Edit PR title and retry", mergeActionEditTitle))
	}
	if userReviewing {
		options = append(options,
			huh.NewOption("PR has been manually merged", mergeActionConfirmed),
			huh.NewOption("Exit, I'm done here", mergeActionExit),
		)
		return options
	}
	return append(options,
		huh.NewOption("I'll review/merge myself", mergeActionReview),
		huh.NewOption("Exit", mergeActionExit),
	)
}

Generated by 👨‍🍳 PR Sous Chef · gpt54 · 11.4 AIC · ⌖ 6.61 AIC · ⊞ 8.3K ·
Comment /souschef to run again

Copilot AI linked an issue Aug 2, 2026 that may be closed by this pull request
6 tasks
Co-authored-by: pelikhan <4175913+pelikhan@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix function length issues in CLI interactive audit Refactor interactive/audit CLI large functions into focused helpers Aug 2, 2026
Copilot AI requested a review from pelikhan August 2, 2026 15:02
@pelikhan
pelikhan marked this pull request as ready for review August 2, 2026 15:33
Copilot AI review requested due to automatic review settings August 2, 2026 15:33

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Refactors oversized CLI functions into focused helpers while retaining existing interactive, audit, log-parsing, and action-build flows.

Changes:

  • Decomposes interactive setup, engine selection, PR merging, and bootstrap orchestration.
  • Extracts firewall diff, Squid log parsing, and JavaScript action-build helpers.
  • Adds targeted tests for engine prioritization and merge options.
Show a summary per file
File Description
pkg/cli/audit_diff.go Extracts firewall diff classification helpers.
pkg/cli/add_interactive_orchestrator.go Splits interactive orchestration into phases.
pkg/cli/add_interactive_git.go Extracts PR merge and secret helpers.
pkg/cli/add_interactive_git_test.go Tests merge-option construction.
pkg/cli/add_interactive_engine.go Extracts engine selection helpers.
pkg/cli/add_interactive_engine_test.go Tests engine-option prioritization.
pkg/cli/actions_build_command.go Extracts JavaScript action building.
pkg/cli/access_log.go Extracts Squid log-line processing.

Review details

Tip

Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

  • Files reviewed: 8/8 changed files
  • Comments generated: 2
  • Review effort level: Balanced

Comment on lines +89 to +94
for _, opt := range constants.EngineOptions {
if setutil.Contains(c.existingSecrets, opt.SecretName) {
addInteractiveLog.Printf("Found existing secret %s, recommending engine: %s", opt.SecretName, opt.Value)
return opt.Value
}
}
Comment thread pkg/cli/add_interactive_git.go Outdated
Comment on lines 107 to 109
if err := c.promptAndEditPRTitle(prNumber); err == nil {
mergeFailed = false
}
@github-actions

github-actions Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Test Quality Sentinel completed test quality analysis.

@github-actions

github-actions Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Design Decision Gate 🏗️ failed during design decision gate check.

@github-actions

github-actions Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

🧠 Matt Pocock Skills Reviewer has completed the skills-based review. ✅

@github-actions

github-actions Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

⚠️ PR Code Quality Reviewer failed during code quality review.

@github-actions

github-actions Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

🧪 Test Quality Sentinel Report

⚠️ Test Quality Score: 68/100 — Acceptable

Analyzed 6 test(s): 5 design, 1 behavioral, 0 violation(s).

📊 Metrics (6 tests)
Metric Value
Analyzed 6 (Go: 6, JS: 0)
✅ Design 5 (83%)
⚠️ Behavioral 1 (17%)
Edge/error coverage 5 (83%)
Duplicate clusters 0
Inflation No (engine: 0.20:1, git: 0.31:1)
🚨 Violations 0
✅ Test Breakdown
Test File Type Quality
TestApplyCopilotAuthMethodChoice add_interactive_engine_test.go:12 Design Table-driven, 3 scenarios
TestApplyCopilotAuthMethodChoice_ReEntryClearsOldValue add_interactive_engine_test.go:43 Design State management contract
TestPrioritizeEngineOption add_interactive_engine_test.go:55 Design Edge case: missing key
TestParseDefaultBranchFromLsRemote add_interactive_git_test.go:16 Design 10 scenarios, regression checks
TestParseDefaultBranchFromLsRemoteWithRealGit add_interactive_git_test.go:101 Behavioral Real git integration
TestBuildMergeOptions add_interactive_git_test.go:184 Design Conditional logic

🟢 Quality Signals

  • Build tags: ✓ All tests have //go:build !integration
  • Edge coverage: Strong — empty inputs, missing values, real git integration
  • Regression prevention: Good — specific checks to prevent "ref:" prefix bugs
  • Test inflation: Healthy — 0.20–0.31× ratio (well under 2:1 threshold)
  • No mock violations: ✓ No gomock/testify-mock usage

Verdict

passed. 17% behavioral tests (threshold: 30%). No violations. Strong edge-case coverage and clean structure.

🧪 Test quality analysis by Test Quality Sentinel · haiku45 · 18.7 AIC · ⌖ 5.22 AIC · ⊞ 8.5K ·
Comment /review to run again

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Test Quality Sentinel: 68/100. 17% behavioral tests (threshold: 30%). No violations. Strong edge-case coverage and clean test structure.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactoring Review

The decomposition is clean and behavior-preserving overall. Two correctness issues have already been flagged by prior Copilot comments (engine-default priority shift in determineDefaultEngine, and silent error suppression in the promptAndEditPRTitle caller). Beyond those, a couple of structural observations:

processSquidAccessLogLine return type — the helper returns error but only ever returns nil. The unused error return adds noise and will mislead future callers if a real error path is added without testing. Consider returning bool (skip line?) or nothing, matching the original intent.

appendExistingFirewallDomainDiff append structure — the anomaly branches each do their own diff.StatusChanges = append(...) and return early, while a non-anomaly status change hits a separate append at the end. This is correct but fragile. Consistent with buildNewFirewallDomainEntry/buildRemovedFirewallDomainEntry, prefer: set anomaly fields conditionally, then append unconditionally.

No blocking issues beyond the two already filed.

🧵 Reviewed using Impeccable skills by Impeccable Skills Reviewer · sonnet46 · 42 AIC · ⌖ 12.1 AIC · ⊞ 5.4K

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Skills-Based Review 🧠

Applied /tdd and /codebase-design — requesting changes on three correctness/clarity issues before merge.

📋 Key Themes & Highlights

Key Issues

  1. Missing tests for determineDefaultEngine — the 4-level priority chain is the most business-critical logic in this file and is entirely untested despite the PR adding tests for the simpler prioritizeEngineOption helper.
  2. Silent error discard in the title-edit pathrunPRMergeLoop swallows all errors from promptAndEditPRTitle, masking form cancellation and network failures.
  3. Misleading error return signature in processSquidAccessLogLine — the function always returns nil but the caller treats non-nil as a hard fatal abort, silently changing the original continue-on-error behaviour.

Positive Highlights

  • ✅ Clean decomposition throughout — each helper has a single clear responsibility
  • buildMergeOptions / TestBuildMergeOptions is an excellent example of the helper + test pattern to follow
  • appendExistingFirewallDomainDiff correctly preserves all anomaly-count semantics from the original megafunction
  • mergeAction constants promoted to package scope — good move for testability

🧠 Reviewed using Matt Pocock's skills by Matt Pocock Skills Reviewer · sonnet46 · 64.2 AIC · ⌖ 11 AIC · ⊞ 7.1K
Comment /matt to run again

return ""
}

func (c *AddInteractiveConfig) determineDefaultEngine(workflowSpecifiedEngine string) string {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[/tdd] determineDefaultEngine implements a non-trivial 4-level priority chain (flag → secret → workflow frontmatter → env var) but has no unit tests. A wrong ordering silently selects the wrong model for every new user. Consider adding table-driven tests covering each priority level, similar to the TestPrioritizeEngineOption pattern already used in this PR.

@copilot please address this.

Comment thread pkg/cli/add_interactive_git.go Outdated
mergeDone = done
mergeFailed = failed
case mergeActionEditTitle:
if err := c.promptAndEditPRTitle(prNumber); err == nil {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[/codebase-design] Error from promptAndEditPRTitle is silently dropped on the happy path: if err := c.promptAndEditPRTitle(prNumber); err == nil { mergeFailed = false }. A form-cancellation or network error is treated identically to an empty-title user decision, making the loop hard to reason about. Consider distinguishing user cancellation (return error and break loop) from empty-title (show warning, stay in loop) explicitly.

@copilot please address this.

Comment thread pkg/cli/access_log.go Outdated
analysis.BlockedDomains = append(analysis.BlockedDomains, domain)
}
if err := processSquidAccessLogLine(strings.TrimSpace(scanner.Text()), verbose, analysis, allowedDomainsSet, blockedDomainsSet); err != nil {
return nil, err

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[/codebase-design] The extracted processSquidAccessLogLine now returns a non-nil error only in an unreachable code path (it always returns nil), yet the caller propagates it as a fatal error with return nil, err. The original loop used continue for every error condition, so this changes observable behavior: any future addition of a real error return in the helper will suddenly abort log parsing. Either remove the error return and pass *DomainAnalysis mutations by pointer only, or document which conditions are fatal.

@copilot please address this.

Comment thread pkg/cli/audit_diff.go
return entry, 0
}

func appendExistingFirewallDomainDiff(diff *FirewallDiff, domain string, stats1, stats2 DomainRequestStats) int {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[/codebase-design] appendExistingFirewallDomainDiff returns an anomaly count that is 0 for volume changes, yet a volume change is appended to diff.VolumeChanges. The caller sums the return value into anomalyCount, which feeds diff.Summary.AnomalyCount. Volume changes are not anomalies, so the count is correct — but the asymmetry (new/removed return 1, status_changed returns 1, volume returns 0) is invisible from the call site and easy to misread or break. Consider returning a named struct or adding a brief comment above each return stating what it counts.

@copilot please address this.

@github-actions

github-actions Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Design Decision Gate — ADR Required

This PR makes significant changes to core business logic (514 new lines in pkg/) but does not have a linked Architecture Decision Record (ADR).

Draft ADR committed: docs/adr/49799-decompose-cli-largefunc-helpers.md — review and complete it before merging.

This PR cannot merge until an ADR is linked in the PR body.

What to do next
  1. Review the draft ADR committed to your branch — it was generated from the PR diff
  2. Complete the missing sections — add context the AI could not infer, refine the decision rationale, and list real alternatives you considered
  3. Commit the finalized ADR to docs/adr/ on your branch
  4. Reference the ADR in this PR body by adding a line such as:
    ADR: [ADR-49799: Decompose Oversized CLI Functions into Focused Helper Functions](docs/adr/49799-decompose-cli-largefunc-helpers.md)

Once an ADR is linked in the PR body, this gate will re-run and verify the implementation matches the decision.

Why ADRs Matter

ADRs create a searchable, permanent record of why the codebase looks the way it does. Future contributors (and your future self) will thank you.

Michael Nygard ADR Format Reference

An ADR must contain these four sections to be considered complete:

  • Context — What is the problem? What forces are at play?
  • Decision — What did you decide? Why?
  • Alternatives Considered — What else could have been done?
  • Consequences — What are the trade-offs (positive and negative)?

All ADRs are stored in docs/adr/ as Markdown files numbered by PR number.

🏗️ ADR gate enforced by Design Decision Gate 🏗️ · sonnet46 · 77.4 AIC · ⌖ 26.4 AIC · ⊞ 9.6K ·
Comment /review to run again

@gh-aw-bot

Copy link
Copy Markdown
Collaborator

@copilot Please continue triage on this PR.

Remaining reviewer-visible blockers:

  • requested changes review from github-actions
  • branch refresh was requested for this PR
  • then run the pr-finisher skill and leave a concise maintainer handoff

Run details: https://github.com/github/gh-aw/actions/runs/30756126865

Generated by 👨‍🍳 PR Sous Chef · gpt54 · 11.4 AIC · ⌖ 6.61 AIC · ⊞ 8.3K ·
Comment /souschef to run again

Copilot AI and others added 2 commits August 2, 2026 16:33
…rrors

- determineDefaultEngine: when an existing secret maps to the default
  engine (Copilot), break rather than return early so that a
  workflow-specified engine or env-var credential can still override it.
  Adds TestDetermineDefaultEngine covering all six priority cases.

- promptAndEditPRTitle: changed signature to (bool, error) so that a
  fatal form-input failure is propagated to the merge loop (matching
  original inline behavior), while a non-fatal empty-title or
  editPRTitle warning returns (false, nil) and continues the loop.

Co-authored-by: gh-aw-bot <259018956+gh-aw-bot@users.noreply.github.com>
…appendExistingFirewallDomainDiff return semantics

- access_log.go: drop the unused error return type from
  processSquidAccessLogLine — every path returned nil, so the
  caller's `return nil, err` was a latent misread trap.
  Removed the error return, updated the call site to not check it.

- audit_diff.go: add inline comments to every return site in
  appendExistingFirewallDomainDiff explaining what the returned int
  counts (anomaly vs. non-anomaly), making the asymmetry between
  security-flip returns (1) and volume-change returns (0) explicit.

Co-authored-by: gh-aw-bot <259018956+gh-aw-bot@users.noreply.github.com>
Copilot AI requested a review from gh-aw-bot August 2, 2026 16:44
@gh-aw-bot

Copy link
Copy Markdown
Collaborator

@copilot Please continue triage on this PR.

Remaining reviewer-visible blockers:

  • requested-changes review from github-actions still remains visible; address the noted correctness issues or confirm each has been fixed on the current head
  • complete and link the drafted ADR in the PR body: docs/adr/49799-decompose-cli-largefunc-helpers.md
  • after that, run the pr-finisher skill and leave a concise maintainer handoff

Run details: https://github.com/github/gh-aw/actions/runs/30758413653

Generated by 👨‍🍳 PR Sous Chef · gpt54 · 10.7 AIC · ⌖ 5.12 AIC · ⊞ 8.3K ·
Comment /souschef to run again

Co-authored-by: gh-aw-bot <259018956+gh-aw-bot@users.noreply.github.com>
@gh-aw-bot

Copy link
Copy Markdown
Collaborator

@copilot Please continue triage on this PR.

Remaining reviewer-visible blockers:

  • latest visible failures are the failing checks in candidate scan: impacted-go-tests and Unit tests (M-R); investigate and fix those first
  • complete and link the drafted ADR in the PR body: docs/adr/49799-decompose-cli-largefunc-helpers.md
  • confirm the outstanding reviewer-noted correctness issues on engine default priority and swallowed promptAndEditPRTitle errors are addressed on the current head, then run the pr-finisher skill and leave a concise maintainer handoff

Failed checks:

Run details: https://github.com/github/gh-aw/actions/runs/30760589044

Generated by 👨‍🍳 PR Sous Chef · gpt54 · 9.49 AIC · ⌖ 6.49 AIC · ⊞ 8.3K ·
Comment /souschef to run again

…fix-function-lengths-again

Co-authored-by: gh-aw-bot <259018956+gh-aw-bot@users.noreply.github.com>
@gh-aw-bot

Copy link
Copy Markdown
Collaborator

@copilot Please continue triage on this PR.

Latest CI is green, but reviewer-visible follow-through is still needed. Please:

  • complete and link the drafted ADR in the PR body: docs/adr/49799-decompose-cli-largefunc-helpers.md
  • run the pr-finisher skill
  • leave a concise maintainer handoff summarizing the refactor, ADR status, and any remaining manual maintainer action

Run details: https://github.com/github/gh-aw/actions/runs/30763117443

Generated by 👨‍🍳 PR Sous Chef · gpt54 · 7.26 AIC · ⌖ 9.36 AIC · ⊞ 8.3K ·
Comment /souschef to run again

@pelikhan
pelikhan merged commit d5064c2 into main Aug 2, 2026
29 of 30 checks passed
@pelikhan
pelikhan deleted the copilot/lint-monster-fix-function-lengths-again branch August 2, 2026 19:32
Copilot stopped work on behalf of gh-aw-bot due to an error August 2, 2026 19:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[lint-monster] CLI interactive/audit function-length slice

4 participants