Skip to content

Comments

feat(loop): validate Claude Code CLI command at startup (#97)#191

Merged
frankbria merged 1 commit intomainfrom
feature/issue-97-claude-cmd-validation
Feb 20, 2026
Merged

feat(loop): validate Claude Code CLI command at startup (#97)#191
frankbria merged 1 commit intomainfrom
feature/issue-97-claude-cmd-validation

Conversation

@frankbria
Copy link
Owner

@frankbria frankbria commented Feb 20, 2026

Summary

Implements #97 — Ralph now validates that the Claude Code CLI is available before starting the loop, instead of hanging or exiting silently.

  • validate_claude_command(): Pre-flight check that runs in main() before the loop. Checks command -v for direct commands, validates npx availability for npx-based commands
  • Configurable CLAUDE_CODE_CMD: Now settable via .ralphrc (auto-detected during ralph-enable and ralph-setup — prefers claude if installed, falls back to npx @anthropic-ai/claude-code)
  • Early process failure detection: Background mode now detects immediate process death via sleep 1 + kill -0 check, preventing the silent hang that was the original report
  • Clear error messages: Formatted error boxes (matching existing permission-denial style) with installation instructions

Acceptance Criteria

  • Ralph validates Claude Code CLI exists before execution
  • Clear error message with installation instructions if not found
  • Users can configure alternative command via .ralphrc
  • Background process failures detected early, no more silent hangs
  • New .ralphrc files include CLAUDE_CODE_CMD with auto-detected default

Test Plan

  • 10 new tests in test_cli_modern.bats (556 → 566 total)
  • validate_claude_command with valid/missing/npx commands
  • .ralphrc loading and env var precedence
  • Structural tests for function ordering and file contents
  • Full test suite: 566 tests, 100% pass rate

Closes #97

Summary by CodeRabbit

  • New Features

    • Claude Code CLI command is now configurable via environment variable or .ralphrc file, with fallback to npx for alternative invocation methods.
    • Added validation checks for Claude Code CLI availability at startup.
  • Documentation

    • Updated installation and configuration guidance with Claude Code CLI setup instructions.
    • Expanded troubleshooting and system requirements documentation.
  • Tests

    • Added comprehensive test suite for Claude Code CLI validation and configuration scenarios.

- Add validate_claude_command() to check CLI exists before loop starts
- Make CLAUDE_CODE_CMD configurable via .ralphrc (auto-detected during setup)
- Add early process failure detection in background mode (sleep+kill -0)
- Update generate_ralphrc() and setup.sh to include CLAUDE_CODE_CMD
- Update ralph_import.sh to respect .ralphrc for CLAUDE_CODE_CMD
- Add 10 new tests for command validation and .ralphrc loading (556→566)
- Update documentation with troubleshooting and configuration

Closes #97
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 20, 2026

Walkthrough

The pull request adds Claude Code CLI command detection, validation, and configuration across the codebase. It introduces a validate_claude_command() function to verify CLI availability before startup, implements CLAUDE_CODE_CMD environment variable handling with .ralphrc integration, and adds comprehensive test coverage for the new validation flows.

Changes

Cohort / File(s) Summary
Documentation
CLAUDE.md, README.md
Updated test count references from 556 to 566; added CLAUDE_CODE_CMD configuration examples, CLI options documentation (--output-format, --allowed-tools, --no-continue), system requirements (GNU coreutils), and Common Issues section for troubleshooting startup failures.
CLI Detection & Setup
install.sh, lib/enable_core.sh, setup.sh
Added explicit availability checks for claude command with fallback to npx. Dynamic detection generates CLAUDE_CODE_CMD in .ralphrc with appropriate defaults or npx alternatives. Replaces deferred installation approach with proactive CLI presence verification.
Configuration Loading
ralph_import.sh
Implemented CLAUDE_CODE_CMD loading from .ralphrc file with quote stripping and environment override support. Enables project-specific Claude CLI command configuration.
Validation & Integration
ralph_loop.sh
Introduced validate_claude_command() function with distinct handling for direct vs. npx-based commands, environment variable exposure for _env_CLAUDE_CODE_CMD, pre-run validation step, and early failure detection after Claude Code launch. Integrated CLAUDE_CODE_CMD into configuration loading with user-facing remediation guidance.
Test Coverage
tests/unit/test_cli_modern.bats
Added comprehensive test suite covering: validate_claude_command function across various scenarios (missing command, npx fallback, environment overrides), CLAUDE_CODE_CMD loading/precedence from .ralphrc, CLI option handling (--output-format, --allowed-tools, --no-continue), and integration validation in ralph_loop.sh startup flow.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant RalphLoop as ralph_loop.sh
    participant Validation as validate_claude_command()
    participant Config as .ralphrc<br/>(CLAUDE_CODE_CMD)
    participant CLI as Claude CLI<br/>(claude/npx)
    
    User->>RalphLoop: Start ralph loop
    RalphLoop->>RalphLoop: Load environment & config
    RalphLoop->>Validation: Call validate_claude_command()
    
    Validation->>Config: Check CLAUDE_CODE_CMD value
    Config-->>Validation: Return configured command
    
    Validation->>CLI: Test command availability
    
    alt Command Found
        CLI-->>Validation: Success
        Validation-->>RalphLoop: Validation passed
        RalphLoop->>CLI: Execute Claude Code
        CLI-->>RalphLoop: Process result
        RalphLoop->>User: Continue loop
    else Command Not Found
        CLI-->>Validation: Not found
        Validation->>User: Error message +<br/>installation guidance
        User-->>RalphLoop: Exit with remediation
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

Possibly related PRs

  • PR #58 — Both modify ralph_loop.sh's Claude CLI invocation logic and add/adjust tests in test_cli_modern.bats for CLI handling and validation.
  • PR #179 — Both adjust ralph_loop.sh's CLI handling (this PR adds CLAUDE_CODE_CMD validation/startup checks; the retrieved PR modifies pipeline errexit/timeout logic).
  • PR #52 — Both target ralph_loop.sh and test files to handle new Claude-related flags (CLAUDE_CODE_CMD, --allowed-tools, --output-format, --no-continue) and CLI parsing validation.

Poem

🐰 A rabbit hops through config files,
Finding Claude Commands, all the while,
Validating paths before the loop,
No more silent exits, just good poop! 💫
Early checks and fallbacks bright,
Ralph's CLI validation done just right! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 72.73% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main change: validating Claude Code CLI command at startup. It is concise, specific, and directly aligned with the primary objective.
Linked Issues check ✅ Passed All PR objectives map to issue #97 requirements: CLI validation before execution, configurable command via .ralphrc, early background failure detection, and clear error messages are all implemented.
Out of Scope Changes check ✅ Passed All changes are directly aligned with issue #97 scope: validate_claude_command(), CLAUDE_CODE_CMD configurability, early failure detection, and comprehensive tests. No unrelated modifications detected.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/issue-97-claude-cmd-validation

Tip

Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord.


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

@macroscopeapp
Copy link
Contributor

macroscopeapp bot commented Feb 20, 2026

Validate and fail fast on the Claude Code CLI command at startup in ralph_loop.sh and add CLAUDE_CODE_CMD configuration with auto-detection across setup scripts

Add validate_claude_command in ralph_loop.sh to check CLAUDE_CODE_CMD before starting, auto-detect and write CLAUDE_CODE_CMD to .ralphrc in setup paths, and update docs/tests to reflect 566 tests and CLI command handling; note a syntax error introduced in ralph_import.sh where an inserted + breaks startup.

📍Where to Start

Start with the validate_claude_command function and its call in main in ralph_loop.sh.


📊 Macroscope summarized 0247267. 8 files reviewed, 2 issues evaluated, 0 issues filtered, 2 comments posted. View details

@github-actions
Copy link

Code Review: feat(loop): validate Claude Code CLI command at startup (#97)

This PR adds pre-flight validation of the Claude Code CLI command to prevent silent hangs. The implementation is well-structured and follows existing patterns, but there are a few areas for improvement.


✅ Strengths

  1. Clear, actionable error messages - Nicely formatted error boxes with installation instructions
  2. Smart auto-detection - Falls back to npx when is not found during setup
  3. Correct precedence handling - Uses the existing pattern for env var vs .ralphrc precedence
  4. Consistent with codebase - Follows same error formatting style as permission denial handling
  5. Comprehensive tests - 10 new tests covering validation, .ralphrc loading, and env var precedence

⚠️ Issues to Address

1. **Bug: Unsafe grep parsing in ** (High Priority)

Problems:

  • Pattern requires a space after (won't match )
  • Won't extract values with spaces (e.g., )
  • removes ALL quotes, corrupting values like path/to/claude

Recommended fix:

Or better yet, source the file and use the variable directly like does.

2. Bug: Color variable usage before definition (Medium Priority)

In , uses and on lines 176-179 and 196-199, but these color variables are defined later (lines 220-226). While this works due to late binding in bash, it's fragile and could break if the function is moved.

Recommended: Define colors before or pass them as parameters.

3. Race condition: Arbitrary 1-second sleep for early failure detection (Low Priority)

The 1-second delay is arbitrary and may not catch failures on slow systems. However, since this is in the monitoring loop and doesn't affect the actual execution, the impact is minimal.


🔒 Security Considerations

  1. **Command injection risk in ** - The unsafe grep parsing mentioned above could allow malicious files to inject commands. Fixing issue cannot find file ~/.ralph/lib/response_analyzer.sh #1 addresses this.

📊 Test Coverage

Good: Covers the main validation paths

  • ✅ Command exists/doesn't exist
  • ✅ npx availability checks
  • ✅ .ralphrc loading
  • ✅ Environment variable precedence
  • ✅ Structural validation

Missing:

  • ❌ Early failure detection logic (sleep 1 + kill -0)
  • ❌ Integration test for actual error output format
  • ❌ Test for .ralphrc parsing

📝 Minor Suggestions

  1. Consider adding a --force-continue flag to skip validation for advanced users
  2. The early failure detection error message could include the actual exit code for better debugging
  3. Test setup inline version of validate_claude_command() could include color output assertions

🎯 Recommendation

Approve with changes - Address the grep parsing bug in ralph_import.sh (issue #1) before merging. The color variable ordering (issue #2) is less critical but worth fixing for robustness.

The core functionality is solid and well-tested. The unsafe parsing is the only significant concern.

@github-actions
Copy link

PR review posted successfully. The key findings are:

Summary:

  • Solid implementation with clear error messages and smart auto-detection
  • ⚠️ Critical bug: Unsafe grep parsing in ralph_import.sh that won't match values without spaces after = and corrupts quoted paths
  • ⚠️ Medium issue: Color variables used before definition (fragile ordering)
  • ℹ️ Minor: Arbitrary 1-second sleep for early failure detection

Recommendation: Approve with changes - Fix the grep parsing bug before merging. The color variable ordering is less critical but worth addressing.

New%20session%20-%202026-02-20T21%3A56%3A02.493Z
opencode session  |  github run

@github-actions
Copy link

PR 191 Review: feat(loop): validate Claude Code CLI command at startup

This is a solid, well-scoped implementation of the CLI validation requirement from issue 97. The approach is sensible and the error messaging is user-friendly. A few issues worth addressing:


Bug: Changelog entry misrepresents test count delta

In README.md, the v0.11.5 changelog entry was changed from:

Added 8 new tests for API limit detection (548 → 556 tests)

to:

Added 8 new tests for API limit detection (548 → 566 tests)

This is contradictory: "8 new tests" but a delta of 18 (548→566). The historical record for v0.11.5 should stay as 548 → 556 and this PR's contribution should appear in a new changelog section (e.g. v0.11.6). The same issue appears in the total count line: 100% pass rate (556/556 passing) was not updated to reflect 566 passing.


Issue: validate_claude_command() uses color variables defined later in the file

In ralph_loop.sh, the function is inserted around line ~165, but RED, YELLOW, and NC are defined at line ~222. This works at runtime because the function is only called from main() after the colors are set, but it is a fragile ordering dependency that can confuse maintainers. Consider moving the color definitions above validate_claude_command(), or add a comment like:

# Note: RED/YELLOW/NC are defined below but will be set when this function is called from main()

Issue: Hardcoded sleep 1 adds latency to every background-mode loop iteration

The early failure detection block in execute_claude_code():

sleep 1
if ! kill -0 $claude_pid 2>/dev/null; then

This sleep 1 runs on every loop iteration in background mode, not just failures. Since validate_claude_command() already catches the "command not found" case at startup, this block handles only runtime failures (auth, config issues). The 1-second wait is also an unexplained magic number — a fast-failing auth error might produce output before 1 second, or a slow npx download might take longer. At minimum, add a comment explaining why 1 second was chosen and that it introduces latency per iteration.


Issue: Fragile .ralphrc parsing in ralph_import.sh

_ralphrc_cmd=$(grep "^CLAUDE_CODE_CMD=" ".ralphrc" 2>/dev/null | cut -d= -f2- | tr -d '"' | tr -d "'")

Three concerns:

  1. Uses a relative path (.ralphrc) — will break if ralph-import is not run from the project root, unlike ralph_loop.sh which uses a configurable $RALPHRC_FILE variable.
  2. tr -d '"' strips ALL double-quote characters, including internal ones in values with embedded quotes.
  3. No handling for values with spaces (e.g. CLAUDE_CODE_CMD="/path with spaces/claude" would be mis-parsed after quote stripping).

The ralph_loop.sh approach of using source "$RALPHRC_FILE" handles all these edge cases correctly. A subshell approach avoids polluting the environment while still handling quoted values properly.


Minor: Duplicate auto-detection logic

The claude/npx auto-detection logic appears in both lib/enable_core.sh:generate_ralphrc() and the fallback block in setup.sh. The fallback in setup.sh is only reached when enable_core.sh is unavailable, so the duplication is understandable — but a comment noting that the two must stay in sync would help future maintainers.


What works well

  • The pre-flight validate_claude_command() call placement in main() is correct — it runs after load_ralphrc(), so $CLAUDE_CODE_CMD is already resolved from .ralphrc before validation.
  • Env var precedence over .ralphrc is consistent with the existing pattern for other variables.
  • Error messages match the existing permission-denial box style — good UX consistency.
  • The structural test asserting validate_claude_command appears before while true in the script is a good regression guard.
  • The install.sh warning (non-blocking, info-only) is the right approach — installation should not fail just because the CLI is not present yet.
  • 10 new tests with good coverage of happy paths and the npx fallback case.

Comment on lines +1322 to +1324
if ! kill -0 $claude_pid 2>/dev/null; then
wait $claude_pid 2>/dev/null
local early_exit=$?
Copy link
Contributor

Choose a reason for hiding this comment

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

🟡 Medium

ralph_loop.sh:1322 Early failure detection treats exit code 0 as a failure. Consider checking $early_exit -ne 0 before entering the error path.

-        if ! kill -0 $claude_pid 2>/dev/null; then
-            wait $claude_pid 2>/dev/null
-            local early_exit=$?
+        if ! kill -0 $claude_pid 2>/dev/null; then
+            wait $claude_pid 2>/dev/null
+            local early_exit=$?
+            # Only treat non-zero exit as failure (Issue #97)
+            if [[ $early_exit -eq 0 ]]; then
+                log_status "INFO" "Claude Code completed quickly (exit code 0)"
+            else

🚀 Want me to fix this? Reply ex: "fix it for me".

🤖 Prompt for AI
In file ralph_loop.sh around lines 1322-1324:

Early failure detection treats exit code 0 as a failure. Consider checking `$early_exit -ne 0` before entering the error path.

[[ -n "$_env_VERBOSE_PROGRESS" ]] && VERBOSE_PROGRESS="$_env_VERBOSE_PROGRESS"
[[ -n "$_env_CB_COOLDOWN_MINUTES" ]] && CB_COOLDOWN_MINUTES="$_env_CB_COOLDOWN_MINUTES"
[[ -n "$_env_CB_AUTO_RESET" ]] && CB_AUTO_RESET="$_env_CB_AUTO_RESET"
[[ -n "$_env_CLAUDE_CODE_CMD" ]] && CLAUDE_CODE_CMD="$_env_CLAUDE_CODE_CMD"
Copy link
Contributor

Choose a reason for hiding this comment

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

🟡 Medium

ralph_loop.sh:157 The environment override for CLAUDE_CODE_CMD won't work because _env_CLAUDE_CODE_CMD is captured (line 48) after the default is set (line 29). Consider changing line 29 to CLAUDE_CODE_CMD="${CLAUDE_CODE_CMD:-claude}" to preserve user values.

🚀 Want me to fix this? Reply ex: "fix it for me".

🤖 Prompt for AI
In file ralph_loop.sh around line 157:

The environment override for `CLAUDE_CODE_CMD` won't work because `_env_CLAUDE_CODE_CMD` is captured (line 48) after the default is set (line 29). Consider changing line 29 to `CLAUDE_CODE_CMD="${CLAUDE_CODE_CMD:-claude}"` to preserve user values.

@frankbria frankbria merged commit 4383e99 into main Feb 20, 2026
8 of 9 checks passed
@frankbria frankbria deleted the feature/issue-97-claude-cmd-validation branch February 20, 2026 22:03
Copy link
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: 5

Caution

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

⚠️ Outside diff range comments (1)
ralph_loop.sh (1)

37-48: ⚠️ Potential issue | 🟠 Major

CLAUDE_CODE_CMD overrides are being overwritten before load_ralphrc.

CLAUDE_CODE_CMD is set to "claude" before _env_CLAUDE_CODE_CMD is captured, so _env_CLAUDE_CODE_CMD is always non-empty and load_ralphrc will always restore "claude", ignoring .ralphrc/environment overrides. Capture env first and set the default after.

Suggested fix
-CLAUDE_CODE_CMD="claude"
+CLAUDE_CODE_CMD="${CLAUDE_CODE_CMD:-}"

 ...
-_env_CLAUDE_CODE_CMD="${CLAUDE_CODE_CMD:-}"
+_env_CLAUDE_CODE_CMD="${CLAUDE_CODE_CMD:-}"

-# Now set defaults (only if not already set by environment)
+# Now set defaults (only if not already set by environment)
+CLAUDE_CODE_CMD="${CLAUDE_CODE_CMD:-claude}"
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ralph_loop.sh` around lines 37 - 48, The issue is that CLAUDE_CODE_CMD is
being defaulted to "claude" before you save the original environment into
_env_CLAUDE_CODE_CMD, so load_ralphrc will always restore the default and ignore
.ralphrc or external env values; fix by first capturing the raw environment into
_env_CLAUDE_CODE_CMD (use _env_CLAUDE_CODE_CMD="${CLAUDE_CODE_CMD:-}") along
with the other _env_* variables, then set the default CLAUDE_CODE_CMD="claude"
afterward so load_ralphrc can correctly detect and restore user-provided values.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@CLAUDE.md`:
- Around line 219-232: There are inconsistent package-name references for the
Claude Code CLI: replace every occurrence of the incorrect
"@anthropic/claude-code" with the canonical "@anthropic-ai/claude-code" in the
docs and scripts; specifically update the misplaced reference in CLAUDE.md (the
other section that currently shows "@anthropic/claude-code") and the install
line in create_files.sh so they match the CLAUDE_CODE_CMD documentation and
validation (validate_claude_command()) to avoid install/runtime confusion.

In `@lib/enable_core.sh`:
- Around line 684-690: Change the snake_case variable claude_cmd to camelCase
claudeCmd and update all references; also correct the npx fallback package name
from "@anthropic-ai/claude-code" to "anthropic/claude-code" so the fallback
becomes "npx anthropic/claude-code"; ensure the command -v checks and the
assignment inside the auto-detect block use claudeCmd consistently (including
any later uses of the variable).

In `@ralph_import.sh`:
- Around line 9-13: The code reads CLAUDE_CODE_CMD from .ralphrc into a
snake_case _ralphrc_cmd and later calls command -v on the entire string which
fails for npx-style values; rename the temp variable to camelCase (e.g.,
ralphRcCmd) and extract/validate only the executable token (the first
whitespace-delimited word) before assigning to CLAUDE_CODE_CMD or before calling
command -v; reuse or call the existing validate_claude_command-style logic (or
implement equivalent) to check the executable token and preserve the full
original value in CLAUDE_CODE_CMD when valid.

In `@ralph_loop.sh`:
- Around line 1319-1346: The early-failure block currently treats any immediate
exit (within sleep 1) as an error; change it to only treat non-zero early exits
as failures: after wait $claude_pid capture the exit into earlyExit (camelCase)
and read earlyOutput (camelCase) from "$output_file"; if earlyExit is non-zero
then log via log_status and print the diagnostic messages referencing
CLAUDE_CODE_CMD as now, otherwise treat a zero earlyExit as a normal success
(skip error logging and return/continue accordingly). Also rename variables
early_exit -> earlyExit and early_output -> earlyOutput throughout this block to
follow camelCase shell style.

In `@README.md`:
- Around line 21-22: Update the README test-summary and any test-count
badges/text so all references reflect 566 tests and a +18 delta instead of the
old 556/556 and “Added 8 new tests”; specifically find the "Test Coverage"
badge/header and the lines that say "556/556 passing" and "Added 8 new tests"
(occurrences noted around the sections referenced in the review) and change them
to consistent wording (e.g., "566 tests, 100% pass" and "Added 18 new tests" or
equivalent delta language) so every summary, badge and sentence that mentions
test counts or deltas is synchronized.

---

Outside diff comments:
In `@ralph_loop.sh`:
- Around line 37-48: The issue is that CLAUDE_CODE_CMD is being defaulted to
"claude" before you save the original environment into _env_CLAUDE_CODE_CMD, so
load_ralphrc will always restore the default and ignore .ralphrc or external env
values; fix by first capturing the raw environment into _env_CLAUDE_CODE_CMD
(use _env_CLAUDE_CODE_CMD="${CLAUDE_CODE_CMD:-}") along with the other _env_*
variables, then set the default CLAUDE_CODE_CMD="claude" afterward so
load_ralphrc can correctly detect and restore user-provided values.

Comment on lines +219 to +232
CLAUDE_CODE_CMD="claude" # Claude Code CLI command (configurable via .ralphrc, Issue #97)
CLAUDE_OUTPUT_FORMAT="json" # Output format: json (default) or text
CLAUDE_ALLOWED_TOOLS="Write,Read,Edit,Bash(git add *),Bash(git commit *),...,Bash(npm *),Bash(pytest)" # Allowed tool permissions (see File Protection)
CLAUDE_USE_CONTINUE=true # Enable session continuity
CLAUDE_MIN_VERSION="2.0.76" # Minimum Claude CLI version
```

**Claude Code CLI Command (Issue #97):**
- `CLAUDE_CODE_CMD` defaults to `"claude"` (global install)
- Configurable via `.ralphrc` for alternative installations (e.g., `"npx @anthropic-ai/claude-code"`)
- Auto-detected during `ralph-enable` and `ralph-setup` (prefers `claude` if available, falls back to npx)
- Validated at startup with `validate_claude_command()` — displays clear error with installation instructions if not found
- Environment variable `CLAUDE_CODE_CMD` takes precedence over `.ralphrc`

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# Search for all references to anthropic/claude-code in the codebase
rg "anthropic.*claude-code|claude-code.*anthropic" -i

Repository: frankbria/ralph-claude-code

Length of output: 2497


🏁 Script executed:

# Also search for references in .ralphrc examples and setup documentation
rg -t md -t sh "CLAUDE_CODE_CMD|npx" | head -30

Repository: frankbria/ralph-claude-code

Length of output: 2775


🌐 Web query:

Claude Code CLI npm package name official documentation

💡 Result:

  • Official Claude Code CLI npm package name: @anthropic-ai/claude-code (installed e.g. npm install -g @anthropic-ai/claude-code``). [1][2]
  • Official documentation: Anthropic’s “Claude Code SDK” docs (includes CLI usage via the claude command). [1]

Sources: [1] Anthropic docs, Claude Code SDK; [2] npm package page for @anthropic-ai/claude-code.


Fix inconsistent Claude Code CLI package name references across the codebase.

The canonical npm package is @anthropic-ai/claude-code, but inconsistencies exist:

  • Lines 219-232 in CLAUDE.md are correct (@anthropic-ai/claude-code)
  • However, another section of CLAUDE.md incorrectly references @anthropic/claude-code (missing -ai)
  • create_files.sh also incorrectly uses @anthropic/claude-code

Update these references to @anthropic-ai/claude-code for consistency across setup documentation and scripts to avoid user confusion during installation.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@CLAUDE.md` around lines 219 - 232, There are inconsistent package-name
references for the Claude Code CLI: replace every occurrence of the incorrect
"@anthropic/claude-code" with the canonical "@anthropic-ai/claude-code" in the
docs and scripts; specifically update the misplaced reference in CLAUDE.md (the
other section that currently shows "@anthropic/claude-code") and the install
line in create_files.sh so they match the CLAUDE_CODE_CMD documentation and
validation (validate_claude_command()) to avoid install/runtime confusion.

Comment on lines +684 to +690
# Auto-detect Claude Code CLI command
local claude_cmd="claude"
if ! command -v claude &>/dev/null; then
if command -v npx &>/dev/null; then
claude_cmd="npx @anthropic-ai/claude-code"
fi
fi
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Verify the Claude Code CLI package name used for the npx fallback.

The fallback uses npx @anthropic-ai/claude-code``. The repo integration guidance calls out npx anthropic/claude-code; if the package name is wrong, new .ralphrc defaults will be unusable. Also, `claude_cmd` is snake_case; please switch to camelCase (e.g., `claudeCmd`) to match shell style rules.

What is the correct npm package name and npx invocation for the Claude Code CLI? Is it `@anthropic-ai/claude-code` or `@anthropic/claude-code`?

Based on learnings: All integration points must be with: Claude Code CLI (npx anthropic/claude-code), tmux terminal multiplexer, Git repositories, jq for JSON processing, GitHub Actions CI/CD, and standard Unix tools (bash, grep, date, etc.).
As per coding guidelines: **/*.sh: Use camelCase for variable names in bash and shell scripts.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/enable_core.sh` around lines 684 - 690, Change the snake_case variable
claude_cmd to camelCase claudeCmd and update all references; also correct the
npx fallback package name from "@anthropic-ai/claude-code" to
"anthropic/claude-code" so the fallback becomes "npx anthropic/claude-code";
ensure the command -v checks and the assignment inside the auto-detect block use
claudeCmd consistently (including any later uses of the variable).

Comment on lines +9 to +13
# Load CLAUDE_CODE_CMD from .ralphrc if available
if [[ -f ".ralphrc" ]]; then
_ralphrc_cmd=$(grep "^CLAUDE_CODE_CMD=" ".ralphrc" 2>/dev/null | cut -d= -f2- | tr -d '"' | tr -d "'")
[[ -n "$_ralphrc_cmd" ]] && CLAUDE_CODE_CMD="$_ralphrc_cmd"
fi
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Handle npx-style CLAUDE_CODE_CMD in dependency checks + camelCase naming.

Loading CLAUDE_CODE_CMD enables values like npx …, but the later command -v "$CLAUDE_CODE_CMD" will always warn when the value contains spaces. Consider validating only the executable token (or reuse a validate_claude_command-style check). Also, _ralphrc_cmd should be camelCase.

Suggested fix for the dependency check
-    if ! command -v "$CLAUDE_CODE_CMD" &> /dev/null 2>&1; then
+    local claudeCmdBin="${CLAUDE_CODE_CMD%% *}"
+    if ! command -v "$claudeCmdBin" &> /dev/null 2>&1; then
As per coding guidelines: `**/*.sh`: Use camelCase for variable names in bash and shell scripts.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ralph_import.sh` around lines 9 - 13, The code reads CLAUDE_CODE_CMD from
.ralphrc into a snake_case _ralphrc_cmd and later calls command -v on the entire
string which fails for npx-style values; rename the temp variable to camelCase
(e.g., ralphRcCmd) and extract/validate only the executable token (the first
whitespace-delimited word) before assigning to CLAUDE_CODE_CMD or before calling
command -v; reuse or call the existing validate_claude_command-style logic (or
implement equivalent) to check the executable token and preserve the full
original value in CLAUDE_CODE_CMD when valid.

Comment on lines +1319 to +1346
# Early failure detection: if the command doesn't exist or fails immediately,
# the backgrounded process dies before the monitoring loop starts (Issue #97)
sleep 1
if ! kill -0 $claude_pid 2>/dev/null; then
wait $claude_pid 2>/dev/null
local early_exit=$?
local early_output=""
if [[ -f "$output_file" && -s "$output_file" ]]; then
early_output=$(tail -5 "$output_file" 2>/dev/null)
fi
log_status "ERROR" "❌ Claude Code process exited immediately (exit code: $early_exit)"
if [[ -n "$early_output" ]]; then
log_status "ERROR" "Output: $early_output"
fi
echo ""
echo -e "${RED}Claude Code failed to start.${NC}"
echo ""
echo -e "${YELLOW}Possible causes:${NC}"
echo " - '${CLAUDE_CODE_CMD}' command not found or not executable"
echo " - Claude Code CLI not installed"
echo " - Authentication or configuration issue"
echo ""
echo -e "${YELLOW}To fix:${NC}"
echo " 1. Verify Claude Code works: ${CLAUDE_CODE_CMD} --version"
echo " 2. Or set a different command in .ralphrc: CLAUDE_CODE_CMD=\"npx @anthropic-ai/claude-code\""
echo ""
return 1
fi
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Early-failure check can misclassify fast successes.

If the CLI exits within 1s with exit code 0, this block still logs an error and returns 1. Consider only treating non‑zero early exits as failures or short‑circuit to the normal success path. Also, early_exit / early_output should be camelCase per shell style.

As per coding guidelines: **/*.sh: Use camelCase for variable names in bash and shell scripts.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ralph_loop.sh` around lines 1319 - 1346, The early-failure block currently
treats any immediate exit (within sleep 1) as an error; change it to only treat
non-zero early exits as failures: after wait $claude_pid capture the exit into
earlyExit (camelCase) and read earlyOutput (camelCase) from "$output_file"; if
earlyExit is non-zero then log via log_status and print the diagnostic messages
referencing CLAUDE_CODE_CMD as now, otherwise treat a zero earlyExit as a normal
success (skip error logging and return/continue accordingly). Also rename
variables early_exit -> earlyExit and early_output -> earlyOutput throughout
this block to follow camelCase shell style.

Comment on lines +21 to 22
**Test Coverage**: 566 tests, 100% pass rate

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Align test-count references after the 566 update.

Several lines now say 566 tests, but other nearby lines still show 556/556 passing and “Added 8 new tests” even though 548 → 566 implies +18. Please update the badge/summary text so counts and deltas match.

Based on learnings: Documentation MUST remain synchronized with codebase: inline script comments for all functions, README updates for features, template file updates for patterns, and CLAUDE.md updates for new commands and behaviors.

Also applies to: 50-51, 639-640, 665-667, 773-773

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@README.md` around lines 21 - 22, Update the README test-summary and any
test-count badges/text so all references reflect 566 tests and a +18 delta
instead of the old 556/556 and “Added 8 new tests”; specifically find the "Test
Coverage" badge/header and the lines that say "556/556 passing" and "Added 8 new
tests" (occurrences noted around the sections referenced in the review) and
change them to consistent wording (e.g., "566 tests, 100% pass" and "Added 18
new tests" or equivalent delta language) so every summary, badge and sentence
that mentions test counts or deltas is synchronized.

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.

Ralph not starting on existing project

1 participant