Skip to content

Kdm config setup#106

Closed
Yuvraj-Sarathe wants to merge 9 commits into
KDM-cli:mainfrom
Yuvraj-Sarathe:kdm-config-setup
Closed

Kdm config setup#106
Yuvraj-Sarathe wants to merge 9 commits into
KDM-cli:mainfrom
Yuvraj-Sarathe:kdm-config-setup

Conversation

@Yuvraj-Sarathe
Copy link
Copy Markdown
Member

@Yuvraj-Sarathe Yuvraj-Sarathe commented May 27, 2026

📝 Changes Summary


src/commands/config.ts — 2 changes

1. Reconfiguration Detection

  • At the start of config setup, calls getConfig() to check for an existing notification_service
  • If a service is already configured (e.g. Discord/Email):
    • Displays a yellow warning informing the user of the current configuration
    • Presents a Yes/No select prompt asking the user to confirm reconfiguration
    • "No" → cancels the setup entirely, no changes are written
    • "Yes" → proceeds through the normal setup flow
  • If no service is configured (none or no prior config), no prompt is shown — setup continues as usual

2. Credential Key Deprecation

  • Defines a list of 6 credential keys:

    Key Type
    notification_service Credential
    discord_webhook Credential
    email_host Credential
    email_port Credential
    email_user Credential
    email_to Credential
  • When config set is used with any credential key:

    • A yellow deprecation warning is displayed, directing users to use kdm config setup instead
    • The set operation still executes (soft deprecation — backward compatible)
  • Non-credential keys (e.g. alert_cooldown) are not affected by this change


src/__tests__/config.test.ts — 6 new tests

# Test Name What It Verifies
1 should detect existing config and prompt — cancel keeps current Reconfiguration prompt appears when a config already exists; selecting "No" cancels without modifying the stored config
2 should proceed with setup when user confirms reconfiguration Selecting "Yes" continues into the normal setup flow and writes new values
3 should skip reconfiguration prompt when no existing config No prompt is shown on a fresh setup (no prior notification_service found)
4 should show deprecation warning when setting credential key via config set A warning is displayed and the command still executes (soft deprecation)
5 should show deprecation warning for all credential keys Each of the 6 credential keys individually triggers the deprecation warning
6 should not show deprecation warning for non-credential keys Setting alert_cooldown produces no deprecation warning

Summary at a Glance

Area Type Scope Breaking?
Reconfig detection New UX flow config setup command ❌ No
Credential deprecation Soft deprecation config set command ❌ No
Tests 6 new test cases Both features above

Summary by CodeRabbit

  • Tests

    • Added tests for configuration setup flows, error handling, and deprecation-warning behavior for credential-related keys; verifies integer parsing for numeric values.
  • New Features

    • Setup now detects existing notification settings and prompts to reconfigure or cancel.
    • Setting credential-related config keys shows a deprecation warning and directs users to the setup flow.
  • Style

    • Simplified welcome banner and signature output.

Review Change Stack

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 27, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Note

.coderabbit.yaml has unrecognized properties

CodeRabbit is using all valid settings from your configuration. Unrecognized properties (listed below) have been ignored and may indicate typos or deprecated fields that can be removed.

⚠️ Parsing warnings (1)
Validation error: Unrecognized key: "pre_merge_checks"
⚙️ Configuration instructions
  • Please see the configuration documentation for more information.
  • You can also validate your configuration using the online YAML validator.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
📝 Walkthrough

Walkthrough

Interactive config setup prompts to reconfigure when an existing non-none notification_service exists (cancel exits early). config set emits deprecation warnings for credential-related keys while still persisting parsed values. The welcome banner ASCII signature was replaced with a single horizontal line.

Changes

Configuration and UI updates

Layer / File(s) Summary
Config setup reconfiguration flow
src/commands/config.ts, src/__tests__/config.test.ts
Detect existing notification_service (not none) and ask whether to reconfigure; declining exits early, confirming continues to service selection and credential prompts. Tests cover decline (no setConfig), confirm (sets service and webhook), no-existing-config (skips reconfigure prompt), and prompt/setConfig error handling.
Config set deprecation warnings
src/commands/config.ts, src/__tests__/config.test.ts
config set logs a deprecation warning when setting credential-related keys (notification service, discord webhook, email SMTP fields) advising config setup, while still parsing values (e.g., email_port → int) and calling setConfig. Non-credential keys (e.g., alert_cooldown) parse and persist without warnings.
Config list formatting
src/commands/config.ts
Tweaked per-entry console formatting for config list output (spacing/padding adjustments).
Welcome banner simplification
src/ui/banner.ts
Replaced multi-line ASCII signature with a single-line horizontal rule and removed the embedded trailing newline from the version output.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant ConfigSetup as "config setup"
  participant TUI as "tui.select"
  participant Storage as "Config storage (getConfig/setConfig)"
  User->>ConfigSetup: run 'config setup'
  ConfigSetup->>Storage: read notification_service
  alt notification_service exists and != 'none'
    ConfigSetup->>TUI: ask "reconfigure?"
    TUI->>User: show reconfigure prompt
    alt User declines
      User->>TUI: selects 'cancel'
      TUI->>ConfigSetup: return cancel
      ConfigSetup->>User: exit without setConfig
    else User confirms
      User->>TUI: selects 'reconfigure'
      TUI->>ConfigSetup: return confirm
      ConfigSetup->>TUI: prompt service selection
      ConfigSetup->>TUI: prompt credentials (if needed)
      ConfigSetup->>Storage: setConfig(service & creds)
    end
  else no notification_service
    ConfigSetup->>TUI: skip reconfigure prompt
    ConfigSetup->>TUI: prompt service selection
    ConfigSetup->>Storage: setConfig(service & creds)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • KDM-cli/kdm-cli#14: Related prior changes to the interactive notification setup and tests that this PR extends.
  • KDM-cli/kdm-cli#23: Earlier edits to the config setup flow and tests; this PR adds reconfiguration prompts and deprecation warnings.

Suggested reviewers

  • utkarsh232005
  • Rishiraj-Pathak-27

Poem

✨ A prompt asks gently, "Reconfigure true?"
A warning whispers, "Use setup — see it through."
Banner trimmed to a single tidy line,
Tests watch flows where prompts and warnings chime.
Small fixes, tidy shine.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'Kdm config setup' is partially related to the changeset but lacks specificity about the main additions: reconfiguration detection, credential deprecation warnings, and banner simplification. Consider a more descriptive title like 'Add config setup reconfiguration flow and credential deprecation warnings' to better convey the scope and main objectives of this PR.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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 and usage tips.

codescene-delta-analysis[bot]

This comment was marked as outdated.

@utkarsh232005
Copy link
Copy Markdown
Member

@Yuvraj-Sarathe please consider the codescene review and. apply the fix asap thankyou:)

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 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/__tests__/config.test.ts`:
- Around line 92-125: Add tests that exercise error paths: mock tui.select to
reject (e.g., vi.mocked(tui.select).mockRejectedValueOnce(new Error('select
failed'))), call program.parseAsync(['node','test','config','setup']) and assert
console.error was called and the command terminated (spy on process.exit or
assert no further setConfig calls); similarly add a test where
configUtils.setConfig is mocked to throw
(vi.mocked(configUtils.setConfig).mockImplementation(() => { throw new
Error('write failed') })), run program.parseAsync and assert console.error was
called and the CLI exits gracefully. Reference tui.select,
configUtils.setConfig, program.parseAsync, console.error, and process.exit in
the new assertions.
- Line 123: The test uses a brittle negative assertion on consoleLogSpy with a
partial string ('currently set to') that doesn't match the real prompt; replace
it by asserting the prompt invocation shape instead: remove the
expect(consoleLogSpy).not.toHaveBeenCalledWith(expect.stringContaining('currently
set to')) check and instead assert against the tui.select mock (e.g.,
expect(tui.select).toHaveBeenCalledTimes(...) or
expect(tui.select).toHaveBeenCalledWith(expect.objectContaining({ message:
'<exact prompt token>' }))), or match the exact message token used by the
command; reference the consoleLogSpy and tui.select mocks to implement this
change.

In `@src/ui/banner.ts`:
- Around line 4-21: The file fails to parse because const banner has no
initializer, signature uses unquoted multiline ASCII inside chalk.gray(...) and
the chalk.blue.bold(...) call is given an unquoted invalid argument; fix by
giving banner a proper string or template literal initializer (e.g., const
banner = `...`), wrap the ASCII art passed to signature in a string/template
literal when calling chalk.gray (signature = chalk.gray(`...`)), and replace the
unquoted argument in console.log(chalk.blue.bold(...)) with a quoted/template
string that includes the version variable via interpolation (e.g.,
chalk.blue.bold(`Kubernetes & Docker Monitor v${version}`)), ensuring the
version variable is defined/imported where used.
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 3f58bc72-1dc6-4a09-890c-be0462fc8ca2

📥 Commits

Reviewing files that changed from the base of the PR and between 97e6aff and 7374eae.

📒 Files selected for processing (3)
  • src/__tests__/config.test.ts
  • src/commands/config.ts
  • src/ui/banner.ts

Comment thread src/__tests__/config.test.ts
Comment thread src/__tests__/config.test.ts Outdated
Comment thread src/ui/banner.ts Outdated
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
codescene-delta-analysis[bot]

This comment was marked as outdated.

codescene-delta-analysis[bot]

This comment was marked as outdated.

Comment thread src/ui/banner.ts Outdated
Comment thread src/ui/banner.ts
Comment thread src/ui/banner.ts
Comment thread src/ui/banner.ts
Comment thread src/commands/config.ts
Updated the welcome banner design in the showWelcomeBanner function to a new style using cyan color.
codescene-delta-analysis[bot]

This comment was marked as outdated.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/ui/banner.ts (1)

18-18: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Remove signature output per maintainer feedback.

This line contradicts the previous review comment requesting removal of the signature print.

🗑️ Proposed fix
   console.log(banner);
-  console.log(signature);
   console.log(chalk.blue.bold(`  Kubernetes & Docker Monitor v${version}`));
🤖 Prompt for 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.

In `@src/ui/banner.ts` at line 18, Remove the stray console.log that prints the
signature in src/ui/banner.ts: locate the statement referencing the signature
variable (console.log(signature)) and delete it so the banner no longer outputs
the signature; ensure no other code depends on that console output and leave the
signature variable unused or remove it if unused to avoid linter warnings.
🤖 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.

Outside diff comments:
In `@src/ui/banner.ts`:
- Line 18: Remove the stray console.log that prints the signature in
src/ui/banner.ts: locate the statement referencing the signature variable
(console.log(signature)) and delete it so the banner no longer outputs the
signature; ensure no other code depends on that console output and leave the
signature variable unused or remove it if unused to avoid linter warnings.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: f6472444-4242-4380-8ed3-afbd6c31091c

📥 Commits

Reviewing files that changed from the base of the PR and between c6aa6b3 and e8afbf4.

📒 Files selected for processing (1)
  • src/ui/banner.ts

codescene-delta-analysis[bot]

This comment was marked as outdated.

@Yuvraj-Sarathe
Copy link
Copy Markdown
Member Author

Yuvraj-Sarathe commented May 28, 2026

@utkarsh232005 rewrote the entire file

@utkarsh232005
Copy link
Copy Markdown
Member

@Yuvraj-Sarathe config.test.ts test is falling

@utkarsh232005
Copy link
Copy Markdown
Member

@Yuvraj-Sarathe config.test.ts test is falling

run npm test first then push changes

@Yuvraj-Sarathe
Copy link
Copy Markdown
Member Author

@Yuvraj-Sarathe config.test.ts test is falling

run npm test first then push changes

ran tests all working!

codescene-delta-analysis[bot]

This comment was marked as outdated.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/commands/config.ts (1)

129-136: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Include email_password in deprecation warnings for config set.

email_password is a credential key in the config contract, but it is excluded from credentialKeys. That leaves the most sensitive value settable via CLI args without the deprecation warning.

Suggested patch
-        const credentialKeys = ['notification_service', 'discord_webhook', 'email_host', 'email_port', 'email_user', 'email_to'];
+        const credentialKeys = [
+          'notification_service',
+          'discord_webhook',
+          'email_host',
+          'email_port',
+          'email_user',
+          'email_to',
+          'email_password',
+        ];
🤖 Prompt for 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.

In `@src/commands/config.ts` around lines 129 - 136, The deprecation warning list
omits the sensitive credential named email_password; update the credentialKeys
array used to build credentialKeyPattern in src/commands/config.ts to include
'email_password' so credentialKeyPattern.test(key) will match it and trigger the
existing deprecation console warnings when key === email_password (symbols:
credentialKeys, credentialKeyPattern, key).
🤖 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/commands/config.ts`:
- Around line 119-121: Replace the direct console.error calls in the catch
blocks with the project's logger (e.g., logger.error or processLogger.error) so
errors follow standard observability; update the two catch blocks that currently
use console.error(`\n✗ Set up cancelled or failed: ${(error as Error).message}`)
(and the similar block at 146-148) to call the project logger with the same
descriptive message and include the full error object/stack (pass error as a
second argument or include error.stack) and add/import the logger symbol if it's
not already available in src/commands/config.ts.
- Around line 140-142: The code applies parseInt to value for keys
'alert_cooldown' and 'email_port' without validation, which can persist NaN;
before assigning finalValue from parseInt(value, 10) in the config handling
logic, validate that value is a valid integer string (e.g., /^\s*[+-]?\d+\s*$/)
or call parsed = parseInt(value,10) and guard with Number.isFinite(parsed) /
!Number.isNaN(parsed); if validation fails, either keep finalValue as the
original value, set a safe default, or surface a clear validation error—update
the branch that references key, value, and finalValue to use this guarded
parsing.

---

Outside diff comments:
In `@src/commands/config.ts`:
- Around line 129-136: The deprecation warning list omits the sensitive
credential named email_password; update the credentialKeys array used to build
credentialKeyPattern in src/commands/config.ts to include 'email_password' so
credentialKeyPattern.test(key) will match it and trigger the existing
deprecation console warnings when key === email_password (symbols:
credentialKeys, credentialKeyPattern, key).
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: f05ff653-0002-44e2-a013-24f087387962

📥 Commits

Reviewing files that changed from the base of the PR and between e8afbf4 and b3441f7.

📒 Files selected for processing (1)
  • src/commands/config.ts

Comment thread src/commands/config.ts
Comment thread src/commands/config.ts
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Copy Markdown
Contributor

@Rishiraj-Pathak-27 Rishiraj-Pathak-27 left a comment

Choose a reason for hiding this comment

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

Good improvements overall, especially the reconfiguration flow and test coverage.

Requesting a few changes before merge:

  1. Validate parseInt() values for alert_cooldown and email_port to avoid storing NaN.
  2. Replace console.error with the project logger for consistent logging.
  3. CodeScene is still failing due to method complexity, so breaking the setup flow into smaller functions would help maintainability.

Other than that, the feature implementation looks good.

Copy link
Copy Markdown

@codescene-delta-analysis codescene-delta-analysis Bot left a comment

Choose a reason for hiding this comment

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

Gates Failed
Prevent hotspot decline (1 hotspot with Complex Method, Bumpy Road Ahead)
Enforce critical code health rules (1 file with Bumpy Road Ahead)

Gates Passed
1 Quality Gates Passed

See analysis details in CodeScene

Reason for failure
Prevent hotspot decline Violations Code Health Impact
config.ts 2 rules in this hotspot 9.35 → 9.13 Suppress
Enforce critical code health rules Violations Code Health Impact
config.ts 1 critical rule 9.35 → 9.13 Suppress

Quality Gate Profile: The Bare Minimum
Install CodeScene MCP: safeguard and uplift AI-generated code. Catch issues early with our IDE extension and CLI tool.

Comment thread src/commands/config.ts
Comment on lines +41 to +44
// Check for existing configuration
const shouldProceed = await promptReconfigurationIfNeeded();
if (!shouldProceed) return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

❌ Getting worse: Complex Method
registerConfigCommand increases in cyclomatic complexity from 17 to 21, threshold = 9

Suppress

Comment thread src/commands/config.ts
Comment on lines +41 to +44
// Check for existing configuration
const shouldProceed = await promptReconfigurationIfNeeded();
if (!shouldProceed) return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

❌ New issue: Bumpy Road Ahead
registerConfigCommand has 2 blocks with nested conditional logic. Any nesting of 2 or deeper is considered. Threshold is 2 blocks per function

Suppress

@Yuvraj-Sarathe Yuvraj-Sarathe closed this by deleting the head repository May 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants