Skip to content

fix: /cd command reloads agent context including AGENTS.md#291

Open
wkramme wants to merge 9 commits intompfaffenberger:mainfrom
wkramme:fix/cd-agents-md-context-reload-public
Open

fix: /cd command reloads agent context including AGENTS.md#291
wkramme wants to merge 9 commits intompfaffenberger:mainfrom
wkramme:fix/cd-agents-md-context-reload-public

Conversation

@wkramme
Copy link
Copy Markdown
Contributor

@wkramme wkramme commented Apr 14, 2026

Summary

Ensure /cd fully refreshes agent context so directory-specific instructions are reloaded immediately after changing directories.

What changed

  • Update /cd command flow in core_commands.py to reload the active agent context after a successful directory change.
  • Remove direct command-layer mutation of internal agent rule state.
  • Keep behavior resilient with non-fatal handling if context reload fails.
  • Align and strengthen tests around command output/behavior and patch targets.

Why

Previously, changing directories could leave the active agent running with stale context until another action forced a rebuild. This PR makes /cd immediately refresh context so AGENTS.md and working-directory-dependent instructions stay accurate.

Flow

sequenceDiagram
    participant User
    participant CLI as /cd handler
    participant FS as File System
    participant Agent as Current Agent

    User->>CLI: /cd <path>
    CLI->>FS: Validate directory
    FS-->>CLI: Exists
    CLI->>FS: chdir(path)
    CLI->>Agent: reload_code_generation_agent()
    Agent-->>Agent: Rebuild system prompt
    Agent-->>Agent: Re-read AGENTS.md in new cwd
    CLI-->>User: Success + context updated

    Note over CLI,User: If reload fails, directory change still succeeds
Loading

Validation

  • Ran targeted tests:
    • tests/command_line/test_core_commands_extended.py
    • tests/test_command_handler.py
    • tests/agents/test_base_agent_full_coverage.py
    • tests/command_line/test_model_settings_menu_coverage.py
  • Result: 378 passed

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced /cd command's error handling and user messaging when reloading agent context during directory navigation
    • Error messages now provide clearer, more actionable feedback when agent context reload encounters issues
    • Added success notifications confirming agent context has been properly updated after changing directories

wkramme added 8 commits March 16, 2026 08:16
Fixes issue where /cd command would change the working directory but
the agent context would not be refreshed, causing:
- AGENTS.md files in new directory to be ignored
- Stale working directory in system prompts
- Plugin callbacks not re-firing with new context

Changes:
- Modified /cd command to clear _puppy_rules cache and reload agent
- Added agent reload with graceful error handling
- Added two comprehensive tests to verify reload behavior

This ensures that when users change directories, the agent picks up
project-specific AGENTS.md rules and refreshes all context-dependent
prompt components.
- Removed direct mutation of agent._puppy_rules from /cd command
- reload_code_generation_agent() now handles invalidation internally
- Updated test to verify public behavior only (reload called)
- Removed brittle assertion on private _puppy_rules field

This reduces coupling and makes the code more maintainable.
MagicMock is already imported at the top of the test file.
Removed local re-imports in test_cd_reloads_agent_context and
test_cd_handles_agent_reload_failure_gracefully.
The /cd command now uses emit_error for reload failures (not emit_warning).
Also applied ruff formatting for consistency.
- Fix mock cleanup leak (stop emit_error instead of emit_warning)
- Remove 'Warning:' prefix from emit_error message for consistency
- Add assertion for emit_info call in test_cd_reloads_agent_context
- Update test to expect new error message format (no 'Warning:' prefix)
Applied black-compatible formatting to 3 test files for consistency.
Per CodeRabbit review:
- Use assert_called_once() instead of assert called
- Check exact prefix with startswith()
- Assert original exception text is present
- Use call_args[0][0] instead of str(call_args)
- Remove redundant 'agent reload failed' dead code check
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 14, 2026

Warning

Rate limit exceeded

@wkramme has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 54 minutes and 34 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 54 minutes and 34 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d3aa5d3b-6675-49b7-9e6b-e8c6727f9e44

📥 Commits

Reviewing files that changed from the base of the PR and between 9d21fee and 3ef2dbe.

📒 Files selected for processing (1)
  • code_puppy/command_line/core_commands.py
📝 Walkthrough

Walkthrough

The pull request modifies the /cd command's error handling to emit informational and error messages instead of warnings when reloading agent context after directory changes, along with corresponding test additions and test refactoring for better formatting.

Changes

Cohort / File(s) Summary
Core Command Logic
code_puppy/command_line/core_commands.py
Updated handle_cd_command to emit emit_info() on successful agent context reload and emit_error() on failure, replacing prior warning behavior. Removed emit_warning from imports and added agent existence check before reload attempt.
Command Handler Tests
tests/command_line/test_core_commands_extended.py, tests/command_line/test_command_handler.py
Added two new /cd tests verifying successful reload with info message emission and graceful failure with error message emission. Updated existing test to verify new error message format when reload fails.
Test Refactoring
tests/agents/test_base_agent_full_coverage.py, tests/command_line/test_model_settings_menu_coverage.py
Reformatted mocked side_effect expressions from single-line to multi-line parenthesized format without altering underlying logic.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • #212: Also modifies handle_cd_command to reload agent context after /cd operations, with additional agent rules cache clearing logic.

Suggested reviewers

  • mpfaffenberger

Poem

🐰 We hop to new dirs with /cd in hand,
Agent context reloads across the land,
Info messages bloom when success takes flight,
Errors caught gracefully, all feels so right! 🌿

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly describes the main change: the /cd command now reloads agent context to ensure AGENTS.md is re-read after directory changes, which matches the core functionality modified across all changed files.

✏️ 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.

Copy link
Copy Markdown

@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.

🧹 Nitpick comments (1)
code_puppy/command_line/core_commands.py (1)

86-88: Optional cleanup: remove redundant None guard after get_current_agent().

Line 87 can be simplified since get_current_agent() is expected to always return an agent instance.

Suggested simplification
                 current_agent = get_current_agent()
-                if current_agent:
-                    # reload_code_generation_agent() invalidates cached rules
-                    # and rebuilds prompt/context from the new cwd
-                    current_agent.reload_code_generation_agent()
-                    emit_info("Agent context updated for new directory")
+                # reload_code_generation_agent() invalidates cached rules
+                # and rebuilds prompt/context from the new cwd
+                current_agent.reload_code_generation_agent()
+                emit_info("Agent context updated for new directory")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@code_puppy/command_line/core_commands.py` around lines 86 - 88, The `if
current_agent:` guard is redundant because `get_current_agent()` always returns
an agent; remove the None check and the unused `current_agent` assignment and
call `reload_code_generation_agent()` directly (replace `current_agent =
get_current_agent(); if current_agent:` block with a direct
`reload_code_generation_agent()` invocation), ensuring any references to
`current_agent` in that scope are updated or removed.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@code_puppy/command_line/core_commands.py`:
- Around line 86-88: The `if current_agent:` guard is redundant because
`get_current_agent()` always returns an agent; remove the None check and the
unused `current_agent` assignment and call `reload_code_generation_agent()`
directly (replace `current_agent = get_current_agent(); if current_agent:` block
with a direct `reload_code_generation_agent()` invocation), ensuring any
references to `current_agent` in that scope are updated or removed.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1438de62-151d-4e81-a447-2e293b76740c

📥 Commits

Reviewing files that changed from the base of the PR and between 5047b55 and 9d21fee.

📒 Files selected for processing (5)
  • code_puppy/command_line/core_commands.py
  • tests/agents/test_base_agent_full_coverage.py
  • tests/command_line/test_core_commands_extended.py
  • tests/command_line/test_model_settings_menu_coverage.py
  • tests/test_command_handler.py

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