Skip to content

Latest commit

 

History

History
275 lines (206 loc) · 18.1 KB

DEVELOPMENT.md

File metadata and controls

275 lines (206 loc) · 18.1 KB

Development Guide

Quick guide for contributors to the claudecode.nvim project.

Development Environment

The toolchain (Neovim, LuaJIT, formatters, test runners) is provisioned by mise via mise.toml. After installing mise:

mise install      # install all tools (builds Lua/LuaJIT from source)
mise run setup     # build the Lua test rocks (busted/luacheck/luacov) into ./.luarocks

Activate mise in your shell — add eval "$(mise activate bash)" (or zsh/fish) to your shell rc, per the mise docs — so its tools are on PATH. Common tasks: mise run all (format + lint + test), mise run test, mise run check, mise run format — run mise tasks to list them all. (mise run <task> works even without shell activation.)

Project Structure

claudecode.nvim/
├── .github/workflows/       # CI workflow definitions
├── fixtures/                # Test Neovim configurations for integration testing
│   ├── bin/                 # Helper scripts (vv, vve, list-configs)
│   ├── mini-files/          # Neovim config testing with mini.files
│   ├── netrw/               # Neovim config testing with built-in file explorer
│   ├── nvim-tree/           # Neovim config testing with nvim-tree.lua
│   ├── oil/                 # Neovim config testing with oil.nvim
│   └── nvim-aliases.sh      # Shell aliases for fixture testing
├── lua/claudecode/          # Plugin implementation
│   ├── server/              # WebSocket server implementation
│   ├── tools/               # MCP tool implementations and schema management
│   ├── config.lua           # Configuration management
│   ├── diff.lua             # Diff provider system (native Neovim support)
│   ├── init.lua             # Plugin entry point
│   ├── lockfile.lua         # Lock file management
│   ├── selection.lua        # Selection tracking
│   └── terminal.lua         # Terminal management
├── plugin/                  # Plugin loader
├── tests/                   # Test suite
│   ├── unit/                # Unit tests
│   ├── component/           # Component tests
│   ├── integration/         # Integration tests
│   ├── bin/                 # Stub claude CLI, first on PATH in every test
│   └── mocks/               # Test mocks
├── README.md                # User documentation
├── ARCHITECTURE.md          # Architecture documentation
└── DEVELOPMENT.md           # Development guide

Core Components Implementation Status

Component Status Priority Notes
Basic plugin structure ✅ Done - Initial setup complete
Configuration system ✅ Done - Support for user configuration
WebSocket server ✅ Done - Pure Lua RFC 6455 compliant
Lock file management ✅ Done - Basic implementation complete
Selection tracking ✅ Done - Enhanced with multi-mode support
MCP tools framework ✅ Done - Dynamic tool registration and schema system
Core MCP tools ✅ Done - openFile, openDiff, getCurrentSelection, getOpenEditors
Diff integration ✅ Done - Native Neovim diff with configurable options
Terminal integration ✅ Done - Snacks.nvim and native terminal support
Tests ✅ Done - Comprehensive test suite with unit, component, and integration tests
CI pipeline ✅ Done - GitHub Actions configured
Documentation ✅ Done - Complete documentation

Development Priorities

  1. Advanced MCP Tools

    • Add Neovim-specific tools (LSP integration, diagnostics, Telescope integration)
    • Implement diffview.nvim integration for the diff provider system
    • Add Git integration tools (branch info, status, etc.)
  2. Performance Optimization

    • Monitor WebSocket server performance under load
    • Optimize selection tracking for large files
    • Fine-tune debouncing and event handling
  3. User Experience

    • Add more user commands and keybindings
    • Improve error messages and user feedback
    • Create example configurations for popular setups
  4. Integration Testing

    • Test with real Claude Code CLI
    • Validate compatibility across Neovim versions
    • Create end-to-end test scenarios

Testing

Run tests using:

# Run all tests, in a random order whose seed the run prints
mise run test

# Repeat the order of an earlier run
BUSTED_SEED=<seed> mise run test

# Run specific test file
nvim --headless -u tests/minimal_init.lua -c "lua require('tests.unit.config_spec')"

# Run linting
mise run check

# Format code
mise run format

Register table-driven tests from an array with ipairs, not from pairs() over string keys. LuaJIT seeds its string hash in each process, so pairs() visits string keys in a different order in each run, and a printed seed would not repeat the test order. tests/helpers/test_order.lua reports each pairs() loop that registers a test, in a spec file or another file under tests/, in a coroutine that the loop resumes, or in a function that the loop calls. The first test that each loop registers runs and then fails with the report, and busted counts it as a failure. A test that also fails for its own reason keeps that failure, after the report. The rest of the spec still registers and runs. A describe or pending in such a loop fails the run through a separate error instead. .busted in the repository root loads tests/helpers/busted_helper.lua, which loads that helper, when busted starts there, as mise run test does. From another directory, pass --helper=<repo>/tests/helpers/busted_helper.lua.

A test never starts the Claude CLI that is installed on the host. tests/bin/claude is a stub that idles, and its directory is first on PATH in every Neovim that starts with tests/minimal_init.lua (the integration runner, scripts/run_integration_tests_individually.sh) and in busted (tests/helpers/busted_helper.lua sets it). A bare claude in a spec, or in the plugin code that a spec reaches, runs the stub. tests/unit/claude_stub_spec.lua and tests/integration/claude_stub_spec.lua fail when claude resolves to anything else. They do not cover a spec that sets a terminal_cmd with an absolute path to the real CLI, so use the bare name or a stub of your own.

To check that a change starts no real claude, run the integration runner (or busted tests/unit, for the unit specs) under strace, and count the execve calls whose program path ends in /claude and is outside tests/bin:

trace=$(mktemp)
strace -f -e trace=execve -e status=successful -o "$trace" scripts/run_integration_tests_individually.sh
awk -v status=$? '/^[0-9]+ +execve\("[^"]*\/claude"/ { if ($0 ~ /^[0-9]+ +execve\("[^"]*\/tests\/bin\/claude"/) stub++; else other++ } END { printf "strace exit status: %d\nclaude starts outside tests/bin: %d\nstub starts: %d\n", status, other, stub; exit (status != 0 || other > 0 || stub < 1) }' "$trace"
verdict=$?
rm -f "$trace"
test "$verdict" -eq 0

The block exits 0 only when all three hold: strace exits 0 (it returns the exit status of the command it runs, so a failing test fails the check), no claude starts outside tests/bin, and the stub starts at least once. The stub count is the proof that the trace saw the tests: a strace that fails before it traces anything (a version older than 5.2, ptrace not allowed, a wrong working directory) leaves an empty trace, and the count then reads 0 although no test ran. tests/integration/claude_stub_spec.lua and tests/unit/claude_stub_spec.lua each start the stub once, so a trace of the full runner or of busted tests/unit holds at least 1 stub start. The awk pattern reads only the program path, the first argument of execve, so it does not count the lines that merely contain claude: a spec runs sh -c 'sleep 60' claude, where claude is an argument of the shell that runs it, not a program (the shell paths differ by host, such as /bin/bash and /usr/bin/sh, and do not change the count). -e status=successful (strace 5.2 or later) drops the failed calls of a PATH search, and it prints each call on one line, with no <unfinished ...> split. The count sees only a program named claude, so it misses a terminal_cmd that points at the real CLI under another file name. The block deletes the trace when it ends, and its exit status stays the verdict. To keep the trace for a look at the starts, delete the rm line and read $trace.

tests/minimal_init.lua installs tests/helpers/termopen_wait.lua, which makes vim.fn.termopen return only after the job's child has run exec. Neovim forks the child with its own signal handlers and resets them a few system calls later. A hangup that reaches the child before that, such as a spec that closes the job at once, makes Neovim exit with Caught deadly signal 'SIGHUP'. The wrapper reads /proc, so it works on Linux only. It does not cover a job that a spec starts with jobstart, a stop that a TermOpen autocmd issues inside termopen (the autocmd runs before the wrapper waits), or a job that runs Neovim with the same command line as the test Neovim (its executable and command line do not change at exec, so termopen blocks until the job exits and raises when the job lives 10 s). A poll can land inside exec, where the command line reads empty, and return before exec has ended. tests/integration/pty_child_exec_spec.lua fails when the wrapper is missing or its wait changed, and .agents/skills/verify-claudecode-nvim/scripts/proof-pty-child-hangup.sh reproduces the race.

A unit test that writes files writes them in a folder from tests/helpers/temp_dir.lua (temp_dir.new() in setup, temp_dir.remove(dir) in teardown), not at a fixed path under /tmp. Every test run on a host shares /tmp, so two suites that run at once would overwrite and delete each other's files.

A PR that changes a .lua or .vim file under lua/ or plugin/ also changes what a covered.lock records, and the advisory covered-lock CI job turns red. .agents/skills/verify-diff-lifecycle/covered.lock records every such file. Each other .agents/skills/verify-*/covered.lock records the files that its model describes (the COVERED list in its check.sh). Run for check in .agents/skills/verify-*/check.sh; do "$check" --hash-only; done (a few seconds for each skill, no TLC) to see which locks are stale. A bare verify-* glob would pass the second script to the first as an argument. For each stale one, read the "Update after an intended change" section of its SKILL.md, run its check.sh --record once its model still describes the code, and commit its covered.lock, or ask a maintainer to.

Two PRs that edit the same Lua file, or that add or delete neighbouring Lua files, conflict in covered.lock once one of them merges. That conflict is expected, because the merged code needs a new record. To resolve it, merge origin/main into your branch, resolve any code conflicts, run the check.sh --record of each skill whose lock conflicts or reads stale, git add each covered.lock, and commit the merge.

Release Automation

Releases are managed by Release Please. After feature and fix PRs land on main, the Release Please workflow opens or updates a single release PR that bumps VERSION, updates .release-please-manifest.json, and rewrites the next CHANGELOG.md entry with Communique-generated notes. Merging that release PR creates the v<version> tag and GitHub Release, then dispatches the Release Notes workflow to rewrite the GitHub Release body with Communique's GitHub-release format.

The runner refuses a CHANGELOG.md that Prettier would rewrite, which is what mise run format-check rejects in CI. A bare CR can hide a heading from Communique, so the update does not build on such a file, and the release run fails with an error that names CHANGELOG.md. Run mise run format, then review its diff of CHANGELOG.md. Prettier can change what an entry says (for example around an identifier with underscores), so fix such a line by hand, for example by putting the identifier in backticks. Then run mise run format again until it changes nothing, and review its diff again.

Release notes require either ANTHROPIC_API_KEY or OPENAI_API_KEY; when using OpenAI-compatible credentials, set COMMUNIQUE_MODEL so Communique knows which model to call. The pinned Communique Linux binary currently requires a glibc 2.39-compatible environment (for example Ubuntu 24.04 or the GitHub-hosted ubuntu-latest runner); on older Linux hosts, run the dry-run in a newer container or runner.

communique.toml sets max_tokens = 16384. Communique 1.1.3 defaults to 4096 output tokens, and its one submit_release_notes call (changelog, title, and body) does not fit in that for a release with about 140 PRs. The model's call is then cut off, Communique makes three attempts in total, and the job passes only when the last attempt still holds a changelog or a release_body. npm --prefix scripts run test:release-please-runner checks that the pinned Communique and this config fit a submission larger than the default.

To dogfood release automation without mutating GitHub, install the pinned tools from mise.toml, install the locked Release Please dependency graph under scripts/, and run the runner in dry-run mode against a branch that already contains the release config:

mise install
NPM_CONFIG_IGNORE_SCRIPTS=true npm ci --prefix scripts
GITHUB_TOKEN=... \
GITHUB_REPOSITORY=coder/claudecode.nvim \
RELEASE_PLEASE_TARGET_BRANCH=your-branch \
ANTHROPIC_API_KEY=... \
./scripts/run-release-please.sh --dry-run

Implementation Guidelines

  1. Error Handling

    • Handle errors where data comes in and where a call can fail (see "Code Shape" in AGENTS.md)
    • Return success, result_or_error pattern
    • Log meaningful error messages
  2. Performance

    • Minimize impact on editor performance
    • Debounce event handlers
    • Use asynchronous operations where possible
  3. Compatibility

    • Support Neovim >= 0.8.0
    • Zero external dependencies (pure Lua implementation)
    • Follow Neovim plugin best practices
  4. Testing

    • Write tests before implementation (TDD)
    • Aim for high code coverage
    • Mock external dependencies

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Implement your changes with tests
  4. Run the test suite to ensure all tests pass
  5. For integrations: Create a fixture configuration for testing
  6. Submit a pull request

Integration Testing with Fixtures

When adding support for new integrations (file explorers, terminals, etc.), you must provide a fixture configuration for testing:

Requirements:

  • Complete Neovim configuration in fixtures/[integration-name]/
  • Include plugin dependencies and proper setup
  • Add dev-claudecode.lua with development keybindings
  • Test all relevant claudecode.nvim features with the integration

Usage:

# Source fixture aliases
source fixtures/nvim-aliases.sh

# Test with specific integration
vv nvim-tree  # Start Neovim with nvim-tree configuration
vv oil        # Start Neovim with oil.nvim configuration
vv mini-files # Start Neovim with mini.files configuration
vv netrw      # Start Neovim with built-in netrw configuration

# List available configurations
list-configs

# Minimal repro environment (copies fixtures/repro/example into /tmp)
repro

Example fixture structure (fixtures/my-integration/):

my-integration/
├── init.lua                    # Main Neovim config
├── lua/
│   ├── config/
│   │   └── lazy.lua           # Plugin manager setup
│   └── plugins/
│       ├── dev-claudecode.lua # claudecode.nvim development config
│       ├── init.lua           # Base plugins
│       └── my-integration.lua # Integration-specific plugin config
└── lazy-lock.json             # Plugin lockfile (if using lazy.nvim)

Implementation Details

WebSocket Server

The WebSocket server is implemented in pure Lua with zero external dependencies:

  • Pure Neovim Implementation: Uses vim.loop (libuv) for TCP operations
  • RFC 6455 Compliant: Full WebSocket protocol implementation
  • JSON-RPC 2.0: MCP message handling with proper framing
  • Security: Pure Lua SHA-1 implementation for WebSocket handshake
  • Performance: Optimized with lookup tables and efficient algorithms

MCP Tool System

The plugin implements a sophisticated tool system following MCP 2025-03-26:

Current Tools:

  • openFile - Opens files with optional line/text selection
  • openDiff - Native Neovim diff views with configurable options
  • getCurrentSelection - Gets current text selection
  • getOpenEditors - Lists currently open files

Tool Architecture:

  • Dynamic registration: M.register(name, schema, handler)
  • Automatic MCP exposure based on schema presence
  • JSON schema validation for parameters
  • Centralized tool definitions in tools/init.lua

Future Tools:

  • Neovim-specific diagnostics
  • LSP integration (hover, references, definitions)
  • Telescope integration for file finding
  • Git integration (status, branch info, blame)

Next Steps

  1. Implement diffview.nvim integration for the diff provider system
  2. Add advanced MCP tools (LSP integration, Telescope, Git)
  3. Add integration tests with real Claude Code CLI
  4. Optimize performance for large codebases
  5. Create example configurations for popular Neovim setups (LazyVim, NvChad, etc.)