Skip to content

SonarCloud: reduce cognitive complexity (S3776, CRITICAL) (×4) #418

Closed

Description

@don-petry

Reduce cognitive complexity of flagged functions (S3776)

SonarCloud open findings in petry-projects/google-app-scripts — 4 issue(s) grouped as one workstream. Part of the org SonarCloud tuning initiative combsmith/.github#593.

Findings

Rule Count Representative message
javascript:S3776 4 Refactor this function to reduce its Cognitive Complexity from 19 to the 15 allowed.

Affected files

  • src/gmail-to-drive-by-labels/src/index.js (2)
  • deploy/index.html (1)
  • src/calendar-to-sheets/src/index.js (1)

Approach

Refactor each flagged function below the complexity-15 threshold via extracted helpers, flattened conditionals, and early returns. These are the org's CRITICAL-severity maintainability findings. No behavior change; keep tests green.

Acceptance

  • All listed SonarCloud findings for this repo/workstream resolved to zero
  • No behavior change; existing tests/CI green
  • Fixes are real (no blanket NOSONAR unless a confirmed false positive, noted inline)

Filed from the 2026-07-03 org SonarCloud review.

Activity

  1. don-petry commented on Jul 3, 2026

    @don-petry
    CollaboratorAuthor

    Dev-Lead Implementation Plan

    Issue: #418 — SonarCloud: reduce cognitive complexity (S3776, CRITICAL) (×4)

    Scope

    Refactor the 4 flagged functions below the cognitive-complexity-15 threshold via extracted helpers, flattened conditionals, and early returns — no behavior change, existing tests stay green.

    Flagged functions (confirmed locally with eslint-plugin-sonarjs, same algorithm as SonarCloud)

    • src/gmail-to-drive-by-labels/src/index.js — attachment forEach in processMessageToDoc (CC 33) and rebuildDoc (CC 17)
    • src/calendar-to-sheets/src/index.js — syncCalendarToSheet (CC 25)
    • deploy/index.html — handleDeploy (CC 19)

    Implementation Checklist

    • gmail-to-drive-by-labels/src/index.js: extract isDuplicateAttachment() + resolveAttachmentName() helpers used by processMessageToDoc
    • gmail-to-drive-by-labels/src/index.js: extract clearDocForRebuild() + moveThreadsBatch() phase helpers used by rebuildDoc
    • calendar-to-sheets/src/index.js: extract upsertRows(), appendRows(), collectRowsToDelete() helpers used by syncCalendarToSheet
    • deploy/index.html: extract deployOneScript() + buildDeployErrorHtml() helpers used by handleDeploy

    Tests to Write

    • Behavior-preserving refactor: no new behavior, so no new failing tests required (per Phase 2 exception). Existing 301 tests are the safety net; new extracted helpers are covered transitively. Will add direct unit tests for any newly-exported helper if it becomes part of the module's public surface.

    Test Command

    npm test (Jest, 301 tests) + npm run check (prettier + eslint) + local cognitive-complexity re-check

  2. don-petry commented on Jul 3, 2026

    @don-petry
    CollaboratorAuthor

    Dev-Lead: issue #418 implementation failed — will retry

    The engine failed (engine-error — e.g. a timeout or transient engine error). This was attempt 1 of 3; dev-lead will retry automatically. You can also re-apply the dev-lead label to retry now.

  3. don-petry commented on Jul 3, 2026

    @don-petry
    CollaboratorAuthor

    Dev-Lead: issue #418 implementation failed — will retry

    The engine failed (engine-error — e.g. a timeout or transient engine error). This was attempt 2 of 3; dev-lead will retry automatically. You can also re-apply the dev-lead label to retry now.

    Last 40 lines of engine output (redacted)
        [copilot] calling gh copilot (model=openai/o4-mini, timeout=600s, flags=--yolo)
    Error: Model "openai/o4-mini" from --model flag is not available.
    
    
  4. don-petry commented on Jul 4, 2026

    @don-petry
    CollaboratorAuthor

    Dev-Lead Implementation Plan

    Issue: #418 — SonarCloud: reduce cognitive complexity (S3776, CRITICAL) (×4)

    Scope

    Refactor the 4 functions flagged by SonarCloud rule javascript:S3776 below the cognitive-complexity-15 threshold via extracted helpers, early returns, and flattened conditionals — no behavior change.

    Findings (precisely located via eslint-plugin-sonarjs cognitive-complexity rule)

    • src/gmail-to-drive-by-labels/src/index.js:125 — attachment dedup/save callback in processMessageToDoc (CC 33)
    • src/gmail-to-drive-by-labels/src/index.js:690 — rebuildDoc (CC 17)
    • src/calendar-to-sheets/src/index.js:109 — syncCalendarToSheet (CC 25)
    • deploy/index.html:1846 — handleDeploy inline script function (CC 19)

    Implementation Checklist

    • Extract attachment handling in processMessageToDoc into helpers (find-duplicate, resolve-name-conflict, save) → callback under 15
    • Extract rebuildDoc phase logic (clear-doc, move-emails-batch) into helpers → under 15
    • Extract syncCalendarToSheet upsert/delete logic into helpers → under 15
    • Extract handleDeploy per-script deploy + error-rendering logic into helpers → under 15

    Tests to Write

    • Behavior-preserving refactor: no new behavior, so no new test cases required. Existing suites (301 tests across gmail-to-drive, calendar-to-sheets, deploy) must stay green and coverage thresholds (99% lines / 95% stmts+funcs / 85% branches) must hold. deploy/index.html inline script is not Jest-covered; change is a pure structural extraction.

    Test Command

    npm test (jest --runInBand), plus npm run check (prettier + eslint) and bash .dev-lead/scripts/dev-lead-lint.sh. Cognitive complexity re-verified with eslint-plugin-sonarjs.

  5. don-petry commented on Jul 4, 2026

    @don-petry
    CollaboratorAuthor

    Dev-Lead: cannot implement issue #418 — needs human attention

    Automatic retries are exhausted (attempt 3 of 3). The most recent failure was engine-error.

    Please review the failures above. To retry anyway, remove the dev-lead:needs-human label and re-apply the dev-lead label.

  6. added
    dev-leadFor dev-lead agent pickup
    and removed
    dev-leadFor dev-lead agent pickup
    dev-lead:needs-humandev-lead could not complete this issue; needs human attention
    on Jul 15, 2026
  7. don-petry commented on Jul 15, 2026

    @don-petry
    CollaboratorAuthor

    Re-routing to dev-lead. The 3× engine-error failures on 2026-07-04 predate the dev-lead deep-impl timeout fixes (#1018/#1021 + follow-ups #1028–#1030), which are now live on the dev-lead/v1-stable channel (tip #1162, 2026-07-10). This issue is well-scoped (×4 S3776 functions), so it's a clean retry on the stabilized engine. Cleared dev-lead:needs-human and re-applied dev-lead.

  8. don-petry commented on Jul 15, 2026

    @don-petry
    CollaboratorAuthor

    Dev-Lead Implementation Plan

    Issue: #418 — SonarCloud: reduce cognitive complexity (S3776, CRITICAL) (×4)

    Scope

    Refactor the 4 functions flagged by SonarCloud javascript:S3776 below the Cognitive Complexity 15 threshold by extracting helpers, flattening conditionals, and using early returns — no behavior change.

    Flagged functions (identified)

    • src/gmail-to-drive-by-labels/src/index.js — processMessageToDoc, processLabelGroup
    • src/calendar-to-sheets/src/index.js — syncCalendarToSheet
    • deploy/index.html — handleDeploy

    Implementation Checklist

    • src/gmail-to-drive-by-labels/src/index.js: extract getBlobBytes, insertHeading, insertSeparator, isDuplicateAttachment, resolveDuplicateName, processAttachment, insertMessageContent; simplify processMessageToDoc
    • src/gmail-to-drive-by-labels/src/index.js: extract resolveLabels, openDocAndFolder, processThread; simplify processLabelGroup
    • src/calendar-to-sheets/src/index.js: extract upsertRows, insertNewRows, isRowWithinWindow, collectRowsToDelete; simplify syncCalendarToSheet
    • deploy/index.html: extract resolveProjectId, deploySingleScript, buildDeploySuccessHtml, buildDeployErrorHtml; simplify handleDeploy

    Tests to Write

    • Behavior-preserving refactor: no new tests. Existing Jest + Playwright suites (301 unit + 65 deploy e2e) must remain green and coverage thresholds must hold.

    Test Command

    npm test (Jest unit + coverage) and npx playwright test deploy/tests/ui.spec.js (deploy e2e)

  9. don-petry commented on Jul 15, 2026

    @don-petry
    CollaboratorAuthor

    Dev-Lead: Implementation Complete

    Plan Execution

    • src/gmail-to-drive-by-labels/src/index.js: extracted getBlobBytes, insertHeading, insertSeparator, isDuplicateAttachment, resolveDuplicateName, processAttachment, insertMessageContent; processMessageToDoc now delegates to shared helper
    • src/gmail-to-drive-by-labels/src/index.js: extracted resolveLabels, openDocAndFolder, processThread; processLabelGroup reduced to orchestration
    • src/calendar-to-sheets/src/index.js: extracted upsertRows, insertNewRows, isRowWithinWindow, collectRowsToDelete; syncCalendarToSheet reduced to orchestration
    • deploy/index.html: extracted resolveProjectId, deploySingleScript, buildDeploySuccessHtml, buildDeployErrorHtml; handleDeploy reduced to orchestration
    • Behavior preserved (helpers keep GAS-service guards so injected/real services behave identically); shared gmail helpers accept injected getCleanBody/getFileHash to honor the test injection contract

    Test Results

    Jest (npm test -- --coverage):
    Test Suites: 12 passed, 12 total
    Tests:       301 passed, 301 total
    
    Coverage (scripts/check-coverage.js):
    ✅ statements     : 99.14% (923/931) [required: 95%]
    ✅ branches       : 90.30% (549/608) [required: 85%]
    ✅ functions      : 98.23% (111/113) [required: 95%]
    ✅ lines          : 100% [required: 100%]
    
    Playwright deploy e2e (npx playwright test deploy/tests/ui.spec.js):
    65 passed
    
    Lint: npm run lint → 0 errors (pre-existing test-file warnings only)
    Format: npx prettier --check . → clean
    Dev-lead lint (.dev-lead/scripts/dev-lead-lint.sh) → all checks passed
    

    Files Changed

    • src/gmail-to-drive-by-labels/src/index.js: split processMessageToDoc and processLabelGroup into small single-purpose helpers to drop Cognitive Complexity below 15
    • src/calendar-to-sheets/src/index.js: split syncCalendarToSheet's upsert / insert / delete phases into helpers
    • deploy/index.html: split handleDeploy into per-script deploy and status-HTML builder helpers

    Notes

    • Pure behavior-preserving refactor, so no new tests were added (Phase 2 exception); the existing 301 unit + 65 deploy e2e tests exercise every extracted helper and all remain green.
    • gas-installer/ is a separate, out-of-scope UI and was not modified (issue lists only deploy/index.html). code.gs files were likewise untouched — SonarCloud flagged the extracted src/index.js logic.
    • Verbose per-iteration console.log diagnostics that were incidental to the removed nested blocks were dropped; no test asserts on them and no doc/Drive/sheet output changed.
  10. added
    dev-leadFor dev-lead agent pickup
    and removed
    dev-leadFor dev-lead agent pickup
    on Jul 21, 2026
  11. don-petry commented on Jul 21, 2026

    @don-petry
    CollaboratorAuthor

    Dev-Lead Implementation Plan

    Issue: #418 — SonarCloud: reduce cognitive complexity (S3776, CRITICAL) (×4)

    Scope

    Refactor the four S3776-flagged functions below the cognitive-complexity-15 threshold via extracted helpers, early returns, and flattened conditionals — no behavior change, existing tests stay green.

    Findings confirmed (measured locally with eslint-plugin-sonarjs cognitive-complexity, the same rule as S3776)

    File Function Complexity
    src/gmail-to-drive-by-labels/src/index.js attachment loop inside processMessageToDoc 33
    src/gmail-to-drive-by-labels/src/index.js rebuildDoc 17
    src/calendar-to-sheets/src/index.js syncCalendarToSheet 25
    deploy/index.html handleDeploy 19

    Implementation Checklist

    • src/gmail-to-drive-by-labels/src/index.js: extract isDuplicateAttachment() and resolveAttachmentName() helpers; simplify the processMessageToDoc attachment loop
    • src/gmail-to-drive-by-labels/src/index.js: extract clearRebuildDoc() and moveThreadsBatch() phase helpers from rebuildDoc
    • src/calendar-to-sheets/src/index.js: extract applyUpserts(), insertNewRows(), computeRowsToDelete() from syncCalendarToSheet
    • deploy/index.html: extract deploySingleScript() and buildDeployErrorHtml() from handleDeploy

    Tests to Write

    • Behavior-preserving refactor — no new behavior. Per AGENTS.md/CLAUDE.md TDD exception, existing suites (301 tests) act as the regression guard. If any extracted gmail/calendar helper needs export for coverage, add targeted unit tests. deploy/index.html inline script has no jest harness (HTML, excluded from coverage) — verified manually + by re-measuring complexity.

    Test Command

    npm test -- --coverage (thresholds: 99% lines, 95% stmts/funcs, 85% branches) + node scripts/check-coverage.js

  12. don-petry commented on Jul 21, 2026

    @don-petry
    CollaboratorAuthor

    Dev-Lead: Implementation Complete

    Behavior-preserving refactor of the four S3776 (cognitive complexity, CRITICAL) findings. Each flagged function now measures below the 15 threshold (verified locally with eslint-plugin-sonarjs's cognitive-complexity rule — the same rule as SonarCloud S3776).

    Plan Execution

    • src/gmail-to-drive-by-labels/src/index.js — processMessageToDoc attachment loop 33 → 8: extracted isDuplicateAttachment() (size/hash dedup) and resolveAttachmentName() (name-conflict rename)
    • src/gmail-to-drive-by-labels/src/index.js — rebuildDoc 17 → 10: extracted clearRebuildDocument() and moveProcessedThreads() phase helpers
    • src/calendar-to-sheets/src/index.js — syncCalendarToSheet 25 → ~1: extracted applyUpserts(), insertNewRows(), computeDeletableRows()
    • deploy/index.html — handleDeploy 19 → 6: extracted resolveProjectId(), deployOneScript(), buildDeploySuccessHtml(), buildDeployErrorHtml()

    Complexity result (threshold 15)

    File Function Before After
    gmail-to-drive-by-labels processMessageToDoc attachment loop 33 8
    gmail-to-drive-by-labels rebuildDoc 17 10
    calendar-to-sheets syncCalendarToSheet 25 ~1
    deploy/index.html handleDeploy 19 6

    Re-scan of all three files at threshold 15 reports zero cognitive-complexity findings.

    Test Results

    Test Suites: 12 passed, 12 total
    Tests:       301 passed, 301 total
    
    Coverage (node scripts/check-coverage.js):
      statements  98.92% [required 95%]
      branches    90.19% [required 85%]
      functions   98.13% [required 95%]
      lines       99.36% global [required 99%]  ✅ All metrics meet requirements
    

    Coverage is unchanged from the pre-refactor baseline. bash .dev-lead/scripts/dev-lead-lint.sh and npm run check (prettier + eslint) both pass (0 errors).

    Files Changed

    • src/gmail-to-drive-by-labels/src/index.js: added helpers isDuplicateAttachment, resolveAttachmentName, clearRebuildDocument, moveProcessedThreads; simplified processMessageToDoc + rebuildDoc
    • src/calendar-to-sheets/src/index.js: added helpers applyUpserts, insertNewRows, computeDeletableRows; simplified syncCalendarToSheet
    • deploy/index.html: added helpers resolveProjectId, deployOneScript, buildDeploySuccessHtml, buildDeployErrorHtml; simplified handleDeploy

    Notes

    • No NOSONAR suppressions used — all fixes are real extractions/flattened conditionals with no observable behavior change.
    • TDD exception (per AGENTS.md/CLAUDE.md): these are behavior-preserving refactors, so no new tests were written. The existing 301-test suite is the regression guard for the gmail/calendar modules. deploy/index.html's inline script has no jest harness (HTML, excluded from coverage) and was validated manually + by re-measuring complexity; all extracted HTML strings and control-flow semantics are byte-for-byte preserved.
    • Nearby processLabelGroup's attachment arrow (line ~519) sits at exactly 15 (unflagged) and was intentionally left untouched to minimize churn; the refactor of processMessageToDoc does not affect it.
  13. added a commit that references this issue on Aug 2, 2026
  14. added a commit that references this issue on Aug 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    dev-leadFor dev-lead agent pickupenhancementFeature requests

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions