Skip to content

Refactor pre-agent audit error extraction into focused helpers (largefunc backlog slice) - #47856

Merged
pelikhan merged 6 commits into
mainfrom
copilot/lint-monster-function-length-refactoring-backlog
Jul 25, 2026
Merged

Refactor pre-agent audit error extraction into focused helpers (largefunc backlog slice)#47856
pelikhan merged 6 commits into
mainfrom
copilot/lint-monster-function-length-refactoring-backlog

Conversation

Copilot AI commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

This PR addresses one targeted slice of the shared largefunc backlog in pkg/cli/pkg/workflow by decomposing a long audit-report function without changing behavior. The focus here is pre-agent failure extraction in pkg/cli, where log parsing, fallback selection, and annotation handling were previously bundled in one large function.

  • Scope: pkg/cli largefunc slice

    • Refactors extractPreAgentStepErrors in pkg/cli/audit_report.go into smaller, single-purpose helpers.
    • Preserves existing decision order: prefer ##[error] annotations, then agent-stdio fallback (when agent ran), then last-step fallback.
  • Log-structure handling extracted

    • Isolates scanning logic for:
      • flat workflow-logs/*.txt job logs
      • nested workflow-logs/<job>/<step>.txt step logs
    • Centralizes “last step” tracking and annotation extraction.
  • Related micro-refactor in same path

    • Extracts agent-stdio line classification from extractAgentStdioFailureExcerpt into a dedicated helper to keep that function under limit and easier to read.
errorAnnotations, lastStep := scanWorkflowStepLogs(workflowLogsDir, maxMessageLen)
if len(errorAnnotations) > 0 {
	return errorAnnotations
}
if agentError := extractAgentFailureError(agentRan, agentStdioPath, maxMessageLen); len(agentError) > 0 {
	return agentError
}
return extractLastStepFallbackError(lastStep, maxMessageLen)

Generated by 👨‍🍳 PR Sous Chef · gpt54 · 13.2 AIC · ⌖ 7.42 AIC · ⊞ 7K ·
Comment /souschef to run again

Co-authored-by: pelikhan <4175913+pelikhan@users.noreply.github.com>
Copilot AI changed the title [WIP] Consolidate function-length findings backlog for pkg/workflow and pkg/cli Refactor pre-agent audit error extraction into focused helpers (largefunc backlog slice) Jul 24, 2026
Copilot AI requested a review from pelikhan July 24, 2026 21:00
@pelikhan
pelikhan marked this pull request as ready for review July 24, 2026 21:01
Copilot AI review requested due to automatic review settings July 24, 2026 21:01
@github-actions

github-actions Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

PR Code Quality Reviewer completed the code quality review.

@github-actions

github-actions Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

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

@github-actions

github-actions Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Design Decision Gate 🏗️ completed the design decision gate check.

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 pre-agent audit error extraction into focused helpers while preserving fallback priority.

Changes:

  • Separates flat and nested workflow-log scanning.
  • Extracts annotation, fallback, and agent-stdio classification helpers.
  • Introduces one behavior discrepancy on workflow-log read failure.
Show a summary per file
File Description
pkg/cli/audit_report.go Decomposes audit log parsing and fallback selection.

Review details

Tip

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

  • Files reviewed: 1/1 changed files
  • Comments generated: 1
  • Review effort level: Medium

Comment thread pkg/cli/audit_report.go Outdated
Comment on lines +729 to +731
jobDirs, err := os.ReadDir(workflowLogsDir)
if err != nil {
return nil
return nil, nil
@github-actions

github-actions Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Test Quality Sentinel completed test quality analysis.

No test files were added or modified in this PR. Test Quality Sentinel skipped.

@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.

Clean refactor — helper extraction is faithful, decision order preserved, and the call sites in extractPreAgentStepErrors are now much easier to follow. Minor: extractLastStepFallbackError drops the workflowLogsDir path from its log message — worth restoring for debuggability, but not blocking.

🧵 Reviewed using Impeccable skills by Impeccable Skills Reviewer · sonnet46 · 18.6 AIC · ⌖ 5.12 AIC · ⊞ 5K

@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 /codebase-design — two targeted suggestions, no blocking issues.

📋 Key Themes & Highlights

Key Themes

  • Boolean trap in appendErrorAnnotation: the flat bool parameter exists solely to select a log message format string. Replacing it with a logLabel string would make call sites self-documenting.
  • Lost log context: extractLastStepFallbackError dropped the workflowLogsDir path from the fallback log message — minor but useful for diagnosing missing logs in production.

Positive Highlights

  • ✅ Clean single-responsibility decomposition — each helper does exactly one thing
  • ✅ Decision order (annotations → agent-stdio → last-step fallback) is crystal-clear at the top of extractPreAgentStepErrors
  • updateLastStep and extractGHErrorLines are now independently unit-testable
  • classifyAgentStdioLines extraction makes extractAgentStdioFailureExcerpt easier to follow
  • ✅ Existing integration tests through extractPreAgentStepErrors still cover the full pipeline

🧠 Reviewed using Matt Pocock's skills by Matt Pocock Skills Reviewer · sonnet46 · 32.6 AIC · ⌖ 4.72 AIC · ⊞ 6.7K
Comment /matt to run again

Comment thread pkg/cli/audit_report.go Outdated
filePath, stepKey string,
num int,
maxMessageLen int,
flat bool,

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 flat bool parameter is a boolean trap — call sites must know what true means, and the only difference is the log message wording.

💡 Suggestion: replace the flag with a log label string
func appendErrorAnnotation(
	errorAnnotations []ErrorInfo,
	filePath, stepKey string,
	num int,
	maxMessageLen int,
	logLabel string, // "flat job log" or "step"
) []ErrorInfo {
	...
	auditReportLog.Printf("Extracted ##[error] annotations from %s %s (%s %d)", logLabel, stepKey, logLabel, num)

This makes both call sites self-documenting without a boolean whose meaning must be reverse-engineered.

@copilot please address this.

Comment thread pkg/cli/audit_report.go Outdated
func extractLastStepFallbackError(lastStep *stepLog, maxMessageLen int) []ErrorInfo {
if lastStep == nil {
auditReportLog.Printf("No step log files found in %s", workflowLogsDir)
auditReportLog.Printf("No step log files found for fallback extraction")

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 log message "No step log files found for fallback extraction" lost the directory path from the original message. This makes diagnosing missing logs harder in production.

The original code logged "No step log files found in %s", workflowLogsDir — the path was useful context. Since extractLastStepFallbackError no longer has access to workflowLogsDir, consider passing it as a parameter or logging it in the caller.

@copilot please address this.

@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.

Non-blocking observations

The refactor correctly preserves the three-tier decision order (##[error] annotations → agent-stdio fallback → last-step content) and the structural decomposition is a clear improvement in readability. Two issues worth fixing before the next caller is added:

Findings
  1. appendErrorAnnotation flat bool — medium. The flag bleeds log-formatting policy into a data helper. Drop it and let call sites log their own context.
  2. extractLastStepFallbackError lost path in log — low. The workflowLogsDir path context was present in the original nil log message; it is now gone, making the message less useful to operators. Pass or log the directory.

🔎 Code quality review by PR Code Quality Reviewer · sonnet46 · 43.9 AIC · ⌖ 4.74 AIC · ⊞ 5.7K
Comment /review to run again

Comments that could not be inline-anchored

pkg/cli/audit_report.go:141

appendErrorAnnotation's flat bool parameter leaks a formatting concern into a generic helper: the flag exists solely to alter a log message prefix. A future call site that passes the wrong value silently produces misleading operator logs.

<details>
<summary>💡 Suggested fix</summary>

Drop the flat parameter and let each call site log its own context:

// scanFlatStepLog — before calling helper:
auditReportLog.Printf(&quot;Extracted ##[error] annotations from flat job log %s (job %d</details>

<details><summary>pkg/cli/audit_report.go:318</summary>

**`extractLastStepFallbackError` nil-path log message lost the directory context**: the original logged `workflowLogsDir` to aid debugging; the refactored version emits a generic message with no path information.

&lt;details&gt;
&lt;summary&gt;💡 Suggested fix&lt;/summary&gt;

Pass the path to the function or log it at the call site:

```go
func extractLastStepFallbackError(lastStep *stepLog, workflowLogsDir string, maxMessageLen int) []ErrorInfo {
    if lastStep == nil {
        auditReportLog.Printf(&quot;No step…

</details>

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown
Contributor

🏗️ Design Decision Gate — ADR Required

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

📄 Draft ADR committed: docs/adr/47856-decompose-audit-error-extraction-into-focused-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-47856: Decompose Audit Error Extraction into Focused Helpers

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

❓ Why ADRs Matter

"AI made me procrastinate on key design decisions. Because refactoring was cheap, I could always say 'I will deal with this later.' Deferring decisions corroded my ability to think clearly."

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 (e.g., 47856-decompose-audit-error-extraction-into-focused-helpers.md for PR #47856).

🏗️ ADR gate enforced by Design Decision Gate 🏗️ · sonnet46 · 42.6 AIC · ⌖ 9.97 AIC · ⊞ 8.5K ·
Comment /review to run again

@pelikhan

Copy link
Copy Markdown
Collaborator

@copilot run pr-finisher

@github-actions

Copy link
Copy Markdown
Contributor

Hey @pelikhan 👋 — thanks for the thorough refactoring work here! The decomposition of extractPreAgentStepErrors into focused helpers is clear and addresses the largefunc linter backlog directly. The ADR is excellent documentation.

One item that would strengthen this before merge:

  • Add unit tests — The new helper functions (scanFlatStepLog, scanNestedStepLogs, extractGHErrorLines, classifyAgentStdioLines, etc.) are now package-scoped functions. While existing integration tests cover the entry point and behavior is preserved, adding focused unit tests for these helpers would make the refactoring more maintainable and easier for future contributors to modify without fear of breakage.

If you would like a hand adding these tests, you can assign this prompt to your coding agent:

Add unit tests for the newly extracted helper functions in pkg/cli/audit_report.go:
1. extractGHErrorLines — test with a file containing ##[error] annotations and verify they are extracted and timestamps stripped.
2. classifyAgentStdioLines — test with mixed error-like lines (stderr, panic, fatal, error messages) and empty lines, verifying classification.
3. updateLastStep — test that it correctly updates lastStep when step number is higher, and preserves existing when lower.
Use table-driven tests where appropriate.

Generated by ✅ Contribution Check · sonnet46 · 62 AIC · ⌖ 7.58 AIC · ⊞ 6.2K ·

@gh-aw-bot

Copy link
Copy Markdown
Collaborator

@copilot please run the pr-finisher skill, confirm the branch is up to date, address any still-unresolved review feedback, and rerun or retrigger checks as needed.

Generated by 👨‍🍳 PR Sous Chef · gpt54 · 13.2 AIC · ⌖ 7.42 AIC · ⊞ 7K ·
Comment /souschef to run again

Copilot AI and others added 2 commits July 24, 2026 21:43
Co-authored-by: gh-aw-bot <259018956+gh-aw-bot@users.noreply.github.com>
Co-authored-by: gh-aw-bot <259018956+gh-aw-bot@users.noreply.github.com>

Copilot AI commented Jul 24, 2026

Copy link
Copy Markdown
Contributor Author

@copilot please run the pr-finisher skill, confirm the branch is up to date, address any still-unresolved review feedback, and rerun or retrigger checks as needed.

...

Addressed the remaining review feedback in 927a10f. The branch is up to date with main, local validation passed (make fmt, make lint, make test, make recompile, make agent-report-progress), and prior branch workflow runs were reviewed. CI on the new HEAD is still stale after the agent push, so a maintainer will need to re-trigger checks before merge.

Copilot AI requested a review from gh-aw-bot July 24, 2026 21:47
@gh-aw-bot

Copy link
Copy Markdown
Collaborator

@copilot please run the skill, confirm the branch is up to date, address the remaining review observations if they still apply, and rerun or retrigger checks on the current HEAD. The latest Copilot response says the branch is ready but CI is stale after the agent push; please make sure fresh checks run for this commit.

  • Review observations still worth verifying:
    • should avoid the formatting flag if that concern is still unresolved.
    • should preserve the workflow log directory path in diagnostics if that context was lost.

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

Generated by 👨‍🍳 PR Sous Chef · gpt54 · 8.36 AIC · ⌖ 7.63 AIC · ⊞ 7K ·
Comment /souschef to run again

@github-actions

Copy link
Copy Markdown
Contributor

Triage | Category: refactor | Risk: low | Score: 45/100 (impact:18, urgency:12, quality:15)

Recommended action: batch_review (Batch D: Go refactors) — Decomposes audit error extraction into focused helpers; CI passing, has ADR and tests.

Score breakdown: impact=18 (code quality, maintainability), urgency=12 (CI passing, not draft), quality=15 (CI green, ADR, tests)

Generated by 🔧 PR Triage Agent · sonnet46 · 31.3 AIC · ⌖ 5.51 AIC · ⊞ 5.7K ·

@pelikhan
pelikhan merged commit b80d614 into main Jul 25, 2026
24 checks passed
@pelikhan
pelikhan deleted the copilot/lint-monster-function-length-refactoring-backlog branch July 25, 2026 02:44
@github-actions

Copy link
Copy Markdown
Contributor

🎉 This pull request is included in a new release.

Release: v0.83.3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[lint-monster] function-length refactoring backlog (659 findings in pkg/workflow and pkg/cli)

4 participants