Skip to content

Reduce shipped CLI complexity hotspots - #419

Merged
unbraind merged 1 commit into
mainfrom
codex/shipped-complexity-registration-cleanup
Jul 2, 2026
Merged

unbraind merged 1 commit into
mainfrom
codex/shipped-complexity-registration-cleanup

Conversation

@unbraind

@unbraind unbraind commented Jul 2, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Extracted large CLI registration action bodies into named helpers across list/query, mutation, and operation command registration.
  • Split shipped-code complexity hotspots in activity, close-many, commander usage guidance, extension doctor runtime activation diagnostics, and runtime schema normalization.
  • Deduplicated shared option-string reading through registration-helpers.ts and recorded the continuation under canonical pm-92if without creating a duplicate PM item.

PM Evidence

  • Tracked under pm-92if with linked source files, test commands, and evidence comments.
  • pm-changelog@2026.6.30 generated/check mode left CHANGELOG.md unchanged with item_count=1388.

Verification

  • pnpm build
  • pnpm typecheck
  • Focused affected suite: node scripts/run-tests.mjs test -- tests/unit/cli/register-list-query.spec.ts tests/unit/cli/cli-main-errors.spec.ts tests/unit/commands/history-activity-command.spec.ts tests/unit/commands/close-command.spec.ts tests/unit/commands/close-many-branch.spec.ts tests/unit/core/schema/runtime-schema-command-flags.spec.ts tests/unit/commands/contracts-command.spec.ts tests/unit/sdk/sdk-index.spec.ts tests/unit/extensions/extension-command.spec.ts (545 tests)
  • Final review-fix focused suite: node scripts/run-tests.mjs test -- tests/unit/commands/history-activity-command.spec.ts tests/unit/cli/register-list-query.spec.ts tests/unit/cli/registration-helpers.spec.ts tests/unit/commands/contracts-command.spec.ts tests/unit/sdk/sdk-index.spec.ts (264 tests)
  • pnpm lint (ESLint clean, jscpd 0 clones across 547 files, static quality passed)
  • pnpm contracts:check
  • node scripts/run-tests.mjs coverage (262 files / 5277 tests / 100% statements, branches, functions, lines)
  • node scripts/smoke-npx-from-pack.mjs (packed package smoke passed for 2026.7.2, packages=11)
  • Manual temp-directory installed-CLI smoke in /tmp/tmp.5agjTscYIG: pm init, create, list-open, compact activity, close, health
  • pnpm security:scan and pnpm audit --audit-level moderate
  • pm health --check-only --summary --json clean, pm validate --check-resolution --check-history-drift --json history drift ok with known resolution-metadata backlog
  • node scripts/release/sentry-telemetry-gate.mjs --json --telemetry-mode best-effort ok
  • pnpm changelog:pm and pnpm changelog:pm:check
  • Pre-push greptile review --branch main --json: final pass confidence 5, safe to merge, no comments

GitHub Sweep

  • Open PRs/issues were empty before opening this PR.
  • Secret scanning returned no alerts.
  • Dependabot and CodeQL alert APIs returned only fixed alerts.

Summary by cubic

Refactors the CLI to reduce complexity by extracting helpers and splitting large flows. Improves maintainability with no user-facing changes and supports pm-92if.

  • Refactors
    • Extracted command registration actions into named helpers across list/query, mutations, and operations (e.g., registerListCommand, addHiddenOptions, lifecycle option builders).
    • Split large logic in activity, close-many (plan orchestration and closeability checks), commander unknown-command guidance, extension doctor runtime activation path collection, and runtime schema status normalization into focused helpers.
    • Centralized option-string parsing with readOptionString in registration-helpers.ts and removed duplicates in registration modules.
    • Continues progress toward pm-92if goals for A+ CodeFactor and zero complexity/duplication issues.

Written for commit 14c5712. Summary will update on new commits.

Review in cubic

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Sorry @unbraind, your pull request is larger than the review limit of 150000 diff characters

@unbraind

unbraind commented Jul 2, 2026

Copy link
Copy Markdown
Owner Author

@greptileai review
/gemini review
@gemini-code-assist review
@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 2, 2026 •

Copy link
Copy Markdown

@unbraind I'll kick off a full review of the PR now, re-evaluating all changes from scratch.

✅ Action performed

Full review finished.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request refactors several CLI command modules and registration files—including activity, close-many, doctor, and schema normalization—to reduce code complexity by splitting large functions into smaller helpers and extracting inline action handlers. The review feedback suggests two key improvements: first, in src/cli/commands/activity.ts, includeActivityEntry should filter using normalized candidate properties (candidate.op and candidate.author) instead of raw entry properties to ensure consistent filtering for 'unknown' values; second, in src/cli/register-mutation.ts, readStringArrayOption should be hardened to wrap single string values in an array to handle repeatable options robustly.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread src/cli/commands/activity.ts Resolved
Comment thread src/cli/register-mutation.ts Resolved
@coderabbitai

coderabbitai Bot commented Jul 2, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR refactors several CLI command registration files (register-mutation.ts, register-operations.ts, register-list-query.ts), activity.ts, close-many.ts, doctor.ts, commander-usage.ts, and runtime-schema.ts by extracting inline logic into dedicated helper functions to reduce cyclomatic complexity, without changing exported behavior. An epic tracking file is also updated.

Changes

CLI complexity reduction refactor

Layer / File(s) Summary
Shared option-parsing helper
src/cli/registration-helpers.ts, src/cli/register-mutation.ts, src/cli/register-operations.ts
Adds an exported readOptionString helper and replaces a duplicated local implementation with the shared version.
register-mutation.ts action extraction
src/cli/register-mutation.ts
Extracts run*Action helpers for update-many, close, copy, focus, update, delete, append, restore, profile, notes, learnings, files, docs, deps commands; adds addHiddenOptions batch helper for hidden alias registration; rewires all corresponding .action(...) calls.
register-operations.ts action extraction
src/cli/register-operations.ts
Adds buildLifecycleMutationOptions and run*Action helpers for test, test-all, telemetry, stats, health, validate, gc, contracts, claim, release, and lifecycle task commands; rewires subcommand .action(...) wiring.
register-list-query.ts descriptor-based registration
src/cli/register-list-query.ts
Introduces ListCommandDescriptor and registerListCommand helper; adds shared run*Action helpers for aggregate, context, next, search, eval, get, history, activity; rewires handlers.
Activity command internal refactor
src/cli/commands/activity.ts
Extracts filter resolution, runtime context setup, history preparation, entry collection/filtering, and compact formatting into helper functions used by runActivity.
Close-many planning refactor
src/cli/commands/close-many.ts
Introduces CloseManyPlanContext and helpers for rollback handling, filter validation, sorting, closable-ID computation, plan building, and dry-run/checkpoint results.
Extension doctor activation refactor
src/cli/commands/extension/doctor.ts
Adds RuntimeActivationPaths helpers to collect, sort, and resolve activation status, replacing inline logic.
Commander unknown-command guidance refactor
src/cli/commander-usage.ts
Extracts candidate scoring, aggregation, fallback, and example-building helpers used by buildUnknownCommandGuidanceFromRuntime.
Runtime schema normalization refactor
src/core/schema/runtime-schema.ts
Adds normalization/serialization helpers for runtime status/field definitions and unknown-field-policy handling, used by normalizeRuntimeSchemaSettings.
Epic tracking updates
.agents/pm/epics/pm-92if.toon
Updates epic metadata, comments, tracked file list, and test-plan matrix.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

  • unbraind/pm-cli#413: Overlaps directly with register-mutation.ts action-handler extraction and complexity remediation.
  • unbraind/pm-cli#51: Overlaps in the same register-mutation.ts/register-list-query.ts hidden/alias option handling code paths.
  • unbraind/pm-cli#69: Overlaps directly with the extension/doctor.ts applyDoctorRuntimeActivationState restructuring.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: reducing CLI complexity hotspots through refactoring.
Description check ✅ Passed The description is directly related and accurately summarizes the refactors, helpers, and verification work in the changeset.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request performs a comprehensive refactoring of the PM CLI codebase to reduce complexity and eliminate ESLint complexity findings. Key changes include splitting large inline command actions and registration logic into modular helper functions across register-list-query.ts, register-mutation.ts, register-operations.ts, commander-usage.ts, activity.ts, close-many.ts, doctor.ts, and runtime-schema.ts. There are no review comments to evaluate, and I have no additional feedback to provide as the changes successfully modularize the codebase and improve maintainability.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@codecov

codecov Bot commented Jul 2, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ All tests successful. No failed tests found.

📢 Thoughts on this report? Let us know!

@greptile-apps

greptile-apps Bot commented Jul 2, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR refactors CLI command registration and runtime helpers to reduce complexity hotspots. The main changes are:

  • Extracted list, query, mutation, and operation command action bodies into named helpers.
  • Split activity, close-many, commander guidance, extension doctor, and runtime schema logic into smaller functions.
  • Added shared option-string reading through registration-helpers.ts.
  • Updated pm-92if project evidence and close command test coverage.

Confidence Score: 5/5

Safe to merge with minimal risk.

The changed code is primarily helper extraction with preserved command flow, option normalization, and output behavior. No accepted runtime, security, schema, or command-registration bugs were identified.

No files require special attention.

T-Rex T-Rex Logs

What T-Rex did

  • Ran the T-Rex code-execution workflow across multiple scenarios and captured the runner script and full before/after terminal logs; all runs exited with code 0; differences observed were limited to volatile values such as temporary paths, generated IDs and timestamps, and global telemetry queue counts/bytes.
  • Compared the command workflow parity by analyzing before and after runs, yielding a normalized diff that shows only volatile differences such as worktree revision text, install timing, generated IDs, timestamps, and checkpoint IDs.
  • Compared diagnostics schema parity by examining before and after artifacts, confirming both captures include commands, cwd, revision, stdout/stderr, and exit codes with differences limited to revision, cwd, path, and timing values.

View all artifacts

T-Rex Ran code and verified through T-Rex

Important Files Changed

Filename Overview
src/cli/register-list-query.ts Extracts list/query command action bodies into named handlers while keeping registrations and output handling intact.
src/cli/register-mutation.ts Extracts mutation command action helpers and reuses shared option-string reading for create, update, close, and schema flows.
src/cli/register-operations.ts Extracts operation command handlers and uses shared option helpers for test, telemetry, stats, and lifecycle commands.
src/cli/commands/activity.ts Extracts activity filtering, normalization, sorting, and compact projection helpers with legacy raw op/author filtering preserved.
src/cli/commands/close-many.ts Refactors close-many planning, rollback validation, checkpointing, and apply rows into focused helpers without identified behavior regressions.
src/core/schema/runtime-schema.ts Splits runtime schema normalization and optional schema-file readers into smaller helpers while preserving fallback behavior.
src/cli/registration-helpers.ts Adds shared readOptionString alongside existing command normalization helpers.

Sequence Diagram

%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
participant User
participant Commander as CLI registration handlers
participant Helpers as Extracted helper actions
participant Commands as Command runtime modules
participant Output as Output helpers

User->>Commander: Invoke pm command with options
Commander->>Helpers: Dispatch to named action/helper
Helpers->>Helpers: Normalize options and globals
Helpers->>Commands: Import and run command implementation
Commands-->>Helpers: Return command result
Helpers->>Output: Print result / stream / profile output
Output-->>User: CLI response
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
participant User
participant Commander as CLI registration handlers
participant Helpers as Extracted helper actions
participant Commands as Command runtime modules
participant Output as Output helpers

User->>Commander: Invoke pm command with options
Commander->>Helpers: Dispatch to named action/helper
Helpers->>Helpers: Normalize options and globals
Helpers->>Commands: Import and run command implementation
Commands-->>Helpers: Return command result
Helpers->>Output: Print result / stream / profile output
Output-->>User: CLI response
Loading

Reviews (3): Last reviewed commit: "Reduce shipped CLI complexity hotspots" | Re-trigger Greptile

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/cli/commander-usage.ts`:
- Around line 469-479: Reuse the existing suggestedPaths value when building
didYouMean in commander-usage.ts so the two stay consistent; the current logic
in the unknown-command handling path recomputes combinedCandidates.slice(0, 3)
even though suggestedPaths already holds the same result. Update the didYouMean
construction to derive from suggestedPaths within the
resolveUnknownCommandCandidates / resolveUnknownCommandFallbacks flow, keeping
the fallback behavior unchanged and avoiding duplicate slicing logic.

In `@src/cli/commands/activity.ts`:
- Around line 245-255: Expose the newly extracted activity helpers through the
_testOnly export in activity.ts so they can be unit-tested directly instead of
only via runActivity. Add resolveActivityFilters, resolveActivityRuntimeContext,
prepareActivityHistoryRead, includeActivityEntry, collectActivityEntries, and
formatCompactActivity to the _testOnly object alongside the existing helpers,
keeping the export as the central test hook for these functions.
- Around line 207-233: The includeActivityEntry filter is comparing filters
against raw HistoryEntry fields instead of the normalized ActivityEntry
candidate, which makes op/author filtering inconsistent with the displayed
values. Update includeActivityEntry to use candidate.op and candidate.author for
the op/author checks, and keep the time-window check on the normalized candidate
as well; then adjust collectActivityEntries so it passes only the normalized
entry data needed by includeActivityEntry, removing the raw entry dependency if
it is no longer required.

In `@src/cli/commands/close-many.ts`:
- Around line 393-403: The closable-ID predicate is duplicated across
resolveCloseManyPlannedIds, planCloseManyRows, and runCloseMany, so keep the
source of truth in one place. Add closePlannedIds to CloseManyPlanContext from
resolveCloseManyPlannedIds, use closePlannedIds.has(item.id) when setting the
action field inside planCloseManyRows instead of recomputing from
alreadyTerminal and force, and in runCloseMany reuse the planned set from the
context rather than filtering planRows for action === "close".
- Around line 362-364: The rollback handling in
resolveCloseManyRollbackId/closeManyCommand treats an empty string as missing,
so a provided --rollback "" silently falls through. Update the closeManyCommand
flow to validate the parsed rollback option before the if (rollbackId) branch,
and make resolveCloseManyRollbackId (or its caller) reject empty strings with a
clear “rollback ID required” error instead of returning a falsy value. Use the
existing resolveCloseManyRollbackId and rollbackId logic in close-many.ts to
keep the fix localized.

In `@src/core/schema/runtime-schema.ts`:
- Around line 319-338: The fallback branch in normalizeRuntimeStatusDefinitions
skips the same ordering guarantee used in the primary path. Update the
DEFAULT_RUNTIME_STATUS_DEFINITIONS path so it also produces a sorted
RuntimeStatusDefinitionResolved[] using the same order-then-id comparator as the
deduped values path, ensuring consistent output regardless of default
declaration order or explicit order values.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: ASSERTIVE

Plan: Pro

Run ID: 086b4904-ec7f-4fb7-8fef-2fc70f4516d4

📥 Commits

Reviewing files that changed from the base of the PR and between a6a4193 and 9db69eb.

📒 Files selected for processing (11)
  • .agents/pm/epics/pm-92if.toon
  • .agents/pm/history/pm-92if.jsonl
  • src/cli/commander-usage.ts
  • src/cli/commands/activity.ts
  • src/cli/commands/close-many.ts
  • src/cli/commands/extension/doctor.ts
  • src/cli/register-list-query.ts
  • src/cli/register-mutation.ts
  • src/cli/register-operations.ts
  • src/cli/registration-helpers.ts
  • src/core/schema/runtime-schema.ts

Comment thread src/cli/commander-usage.ts Resolved
Comment thread src/cli/commands/activity.ts Resolved
Comment thread src/cli/commands/activity.ts Resolved
Comment thread src/cli/commands/close-many.ts Resolved
Comment thread src/cli/commands/close-many.ts Resolved
Comment thread src/core/schema/runtime-schema.ts Resolved
Refactor command registration actions into named helpers across mutation, list/query, and operations registration.

Split extension doctor runtime activation diagnostics, activity aggregation, close-many orchestration, unknown-command guidance, and runtime schema normalization into smaller helpers.

Record pm-92if evidence for the broader static-quality continuation and verify lint, contracts, coverage, package smoke, manual temp smoke, health, validation, security, audit, changelog, Sentry, and GitHub alert state.
@unbraind
unbraind force-pushed the codex/shipped-complexity-registration-cleanup branch from 9db69eb to 14c5712 Compare July 2, 2026 20:03
@unbraind

unbraind commented Jul 2, 2026

Copy link
Copy Markdown
Owner Author

Updated head pushed after addressing review feedback. Please review the current head again.

@greptileai review
/gemini review
@gemini-code-assist review
@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 2, 2026 •

Copy link
Copy Markdown

@unbraind I'll perform a full review of the updated head now, re-evaluating all changes from scratch.

✅ Action performed

Full review finished.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request focuses on a comprehensive refactoring of the CLI command registration, command execution, and schema normalization modules to reduce code complexity. Large functions in modules such as commander-usage, activity, close-many, doctor, register-list-query, register-mutation, register-operations, and runtime-schema have been broken down into smaller, focused helper functions. Additionally, a unit test has been added to verify that close-many rejects blank rollback checkpoint IDs. There are no review comments to address, and I have no further feedback to provide.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

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.

1 participant