You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
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)
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)
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
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.
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.
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)
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.
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.
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.
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)
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
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.
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.
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).
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).
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.
Activity
don-petry commentedon Jul 3, 2026
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— attachmentforEachinprocessMessageToDoc(CC 33) andrebuildDoc(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: extractisDuplicateAttachment()+resolveAttachmentName()helpers used byprocessMessageToDocgmail-to-drive-by-labels/src/index.js: extractclearDocForRebuild()+moveThreadsBatch()phase helpers used byrebuildDoccalendar-to-sheets/src/index.js: extractupsertRows(),appendRows(),collectRowsToDelete()helpers used bysyncCalendarToSheetdeploy/index.html: extractdeployOneScript()+buildDeployErrorHtml()helpers used byhandleDeployTests to Write
Test Command
npm test(Jest, 301 tests) +npm run check(prettier + eslint) + local cognitive-complexity re-checkdon-petry commentedon Jul 3, 2026
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 thedev-leadlabel to retry now.engine-errordon-petry commentedon Jul 3, 2026
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 thedev-leadlabel to retry now.engine-errorLast 40 lines of engine output (redacted)
don-petry commentedon Jul 4, 2026
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 inprocessMessageToDoc(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—handleDeployinline script function (CC 19)Implementation Checklist
processMessageToDocinto helpers (find-duplicate, resolve-name-conflict, save) → callback under 15rebuildDocphase logic (clear-doc, move-emails-batch) into helpers → under 15syncCalendarToSheetupsert/delete logic into helpers → under 15handleDeployper-script deploy + error-rendering logic into helpers → under 15Tests to Write
deploy/index.htmlinline script is not Jest-covered; change is a pure structural extraction.Test Command
npm test(jest --runInBand), plusnpm run check(prettier + eslint) andbash .dev-lead/scripts/dev-lead-lint.sh. Cognitive complexity re-verified with eslint-plugin-sonarjs.don-petry commentedon Jul 4, 2026
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-humanlabel and re-apply thedev-leadlabel.don-petry commentedon Jul 15, 2026
Re-routing to dev-lead. The 3×
engine-errorfailures on 2026-07-04 predate the dev-lead deep-impl timeout fixes (#1018/#1021 + follow-ups #1028–#1030), which are now live on thedev-lead/v1-stablechannel (tip #1162, 2026-07-10). This issue is well-scoped (×4 S3776 functions), so it's a clean retry on the stabilized engine. Cleareddev-lead:needs-humanand re-applieddev-lead.don-petry commentedon Jul 15, 2026
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,processLabelGroupsrc/calendar-to-sheets/src/index.js—syncCalendarToSheetdeploy/index.html—handleDeployImplementation Checklist
src/gmail-to-drive-by-labels/src/index.js: extractgetBlobBytes,insertHeading,insertSeparator,isDuplicateAttachment,resolveDuplicateName,processAttachment,insertMessageContent; simplifyprocessMessageToDocsrc/gmail-to-drive-by-labels/src/index.js: extractresolveLabels,openDocAndFolder,processThread; simplifyprocessLabelGroupsrc/calendar-to-sheets/src/index.js: extractupsertRows,insertNewRows,isRowWithinWindow,collectRowsToDelete; simplifysyncCalendarToSheetdeploy/index.html: extractresolveProjectId,deploySingleScript,buildDeploySuccessHtml,buildDeployErrorHtml; simplifyhandleDeployTests to Write
Test Command
npm test(Jest unit + coverage) andnpx playwright test deploy/tests/ui.spec.js(deploy e2e)don-petry commentedon Jul 15, 2026
Dev-Lead: Implementation Complete
Plan Execution
src/gmail-to-drive-by-labels/src/index.js: extractedgetBlobBytes,insertHeading,insertSeparator,isDuplicateAttachment,resolveDuplicateName,processAttachment,insertMessageContent;processMessageToDocnow delegates to shared helpersrc/gmail-to-drive-by-labels/src/index.js: extractedresolveLabels,openDocAndFolder,processThread;processLabelGroupreduced to orchestrationsrc/calendar-to-sheets/src/index.js: extractedupsertRows,insertNewRows,isRowWithinWindow,collectRowsToDelete;syncCalendarToSheetreduced to orchestrationdeploy/index.html: extractedresolveProjectId,deploySingleScript,buildDeploySuccessHtml,buildDeployErrorHtml;handleDeployreduced to orchestrationgetCleanBody/getFileHashto honor the test injection contractTest Results
Files Changed
src/gmail-to-drive-by-labels/src/index.js: splitprocessMessageToDocandprocessLabelGroupinto small single-purpose helpers to drop Cognitive Complexity below 15src/calendar-to-sheets/src/index.js: splitsyncCalendarToSheet's upsert / insert / delete phases into helpersdeploy/index.html: splithandleDeployinto per-script deploy and status-HTML builder helpersNotes
gas-installer/is a separate, out-of-scope UI and was not modified (issue lists onlydeploy/index.html).code.gsfiles were likewise untouched — SonarCloud flagged the extractedsrc/index.jslogic.console.logdiagnostics that were incidental to the removed nested blocks were dropped; no test asserts on them and no doc/Drive/sheet output changed.don-petry commentedon Jul 21, 2026
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-sonarjscognitive-complexity, the same rule as S3776)src/gmail-to-drive-by-labels/src/index.jsprocessMessageToDocsrc/gmail-to-drive-by-labels/src/index.jsrebuildDocsrc/calendar-to-sheets/src/index.jssyncCalendarToSheetdeploy/index.htmlhandleDeployImplementation Checklist
src/gmail-to-drive-by-labels/src/index.js: extractisDuplicateAttachment()andresolveAttachmentName()helpers; simplify theprocessMessageToDocattachment loopsrc/gmail-to-drive-by-labels/src/index.js: extractclearRebuildDoc()andmoveThreadsBatch()phase helpers fromrebuildDocsrc/calendar-to-sheets/src/index.js: extractapplyUpserts(),insertNewRows(),computeRowsToDelete()fromsyncCalendarToSheetdeploy/index.html: extractdeploySingleScript()andbuildDeployErrorHtml()fromhandleDeployTests to Write
deploy/index.htmlinline 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.jsdon-petry commentedon Jul 21, 2026
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'scognitive-complexityrule — the same rule as SonarCloud S3776).Plan Execution
src/gmail-to-drive-by-labels/src/index.js—processMessageToDocattachment loop 33 → 8: extractedisDuplicateAttachment()(size/hash dedup) andresolveAttachmentName()(name-conflict rename)src/gmail-to-drive-by-labels/src/index.js—rebuildDoc17 → 10: extractedclearRebuildDocument()andmoveProcessedThreads()phase helperssrc/calendar-to-sheets/src/index.js—syncCalendarToSheet25 → ~1: extractedapplyUpserts(),insertNewRows(),computeDeletableRows()deploy/index.html—handleDeploy19 → 6: extractedresolveProjectId(),deployOneScript(),buildDeploySuccessHtml(),buildDeployErrorHtml()Complexity result (threshold 15)
processMessageToDocattachment looprebuildDocsyncCalendarToSheethandleDeployRe-scan of all three files at threshold 15 reports zero cognitive-complexity findings.
Test Results
Coverage is unchanged from the pre-refactor baseline.
bash .dev-lead/scripts/dev-lead-lint.shandnpm run check(prettier + eslint) both pass (0 errors).Files Changed
src/gmail-to-drive-by-labels/src/index.js: added helpersisDuplicateAttachment,resolveAttachmentName,clearRebuildDocument,moveProcessedThreads; simplifiedprocessMessageToDoc+rebuildDocsrc/calendar-to-sheets/src/index.js: added helpersapplyUpserts,insertNewRows,computeDeletableRows; simplifiedsyncCalendarToSheetdeploy/index.html: added helpersresolveProjectId,deployOneScript,buildDeploySuccessHtml,buildDeployErrorHtml; simplifiedhandleDeployNotes
NOSONARsuppressions used — all fixes are real extractions/flattened conditionals with no observable behavior change.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.processLabelGroup's attachment arrow (line ~519) sits at exactly 15 (unflagged) and was intentionally left untouched to minimize churn; the refactor ofprocessMessageToDocdoes not affect it.feat: implement issue #418 — SonarCloud: reduce cognitive complexity …
feat: implement issue #418 — SonarCloud: reduce cognitive complexity …