Claude Max 5 / Claude Code: Best practices for agentic coding 1

Claude Codeを使った開発の効率を上げる準備です。(2025.09.25)

Claude Code: Best practices for agentic coding

上記の公式HPから日本語にして抜粋するだけです。

1. Customize your setup

あなたの目的に合わせて設定しろ。

1-1. Create CLAUDE.md files

CLAUDE.mdを作れ。

公式の内容がおそらく汎用的にするために抽象的なので、具体的な例をClaude Opus 4.1に提示してもらいます。

指示内容 : オープンソースを使ったロボット開発用のCLAUDE.mdの例を作成して新規ファイルとして保存してください。

英語で指示 : Create an example CLAUDE.md for robotics development using open source and save it as a new file.

CLAUDE.md

# Claude Configuration for Robotics Development

## Project Type
Open Source Robotics Development

## Development Environment
- **Operating System**: Ubuntu 22.04 LTS
- **ROS Version**: ROS 2 Humble
- **Python Version**: 3.10+
- **Build System**: colcon
- **Package Manager**: apt, pip, rosdep

## Key Technologies
- **Robotics Framework**: ROS 2 (Robot Operating System)
- **Simulation**: Gazebo, RViz2
- **Computer Vision**: OpenCV, PCL (Point Cloud Library)
- **Machine Learning**: PyTorch, TensorFlow, scikit-learn
- **Motion Planning**: MoveIt 2, Nav2
- **Hardware Interfaces**: ros2_control, micro-ROS
- **Communication**: DDS (Data Distribution Service)

## Common Commands

### Build and Test
```bash
# Build workspace
colcon build --symlink-install

# Run tests
colcon test

# Check test results
colcon test-result --verbose

# Install dependencies
rosdep install --from-paths src --ignore-src -r -y
```

### Development Tools
```bash
# Format Python code
black src/
autopep8 --in-place --aggressive --aggressive src/**/*.py

# Lint code
flake8 src/
pylint src/

# Type checking
mypy src/

# C++ formatting
clang-format -i src/**/*.cpp src/**/*.hpp
```

### ROS 2 Specific
```bash
# Source workspace
source install/setup.bash

# Launch simulation
ros2 launch robot_bringup gazebo.launch.py

# Run navigation stack
ros2 launch nav2_bringup navigation_launch.py

# Monitor topics
ros2 topic list
ros2 topic echo /cmd_vel

# Record bag files
ros2 bag record -a
```

### Hardware Testing
```bash
# Check hardware connections
lsusb
ls /dev/tty*

# Monitor system resources
htop
iotop

# Camera testing
v4l2-ctl --list-devices
```

## Project Structure
```
robotics_project/
├── src/
│   ├── robot_description/     # URDF, meshes, configs
│   ├── robot_bringup/        # Launch files
│   ├── robot_control/        # Controllers and drivers
│   ├── robot_navigation/     # Navigation stack
│   ├── robot_perception/     # Computer vision, sensors
│   └── robot_interfaces/     # Custom messages, services
├── config/                   # Configuration files
├── launch/                   # Launch files
├── maps/                     # Navigation maps
├── worlds/                   # Gazebo world files
└── scripts/                  # Utility scripts
```

## Dependencies
- ros-humble-desktop-full
- ros-humble-moveit
- ros-humble-navigation2
- ros-humble-gazebo-ros-pkgs
- python3-opencv
- python3-numpy
- python3-scipy
- python3-matplotlib

## Testing Strategy
- Unit tests with pytest (Python) and gtest (C++)
- Integration tests with launch_testing
- Simulation testing in Gazebo
- Hardware-in-the-loop testing
- Performance benchmarking

## Documentation
- Code documentation with Sphinx (Python) and Doxygen (C++)
- ROS 2 package documentation
- Hardware setup guides
- API reference documentation

## Debugging Tools
- **ROS 2 Tools**: rqt, ros2 doctor, ros2 wtf
- **Visualization**: RViz2, PlotJuggler
- **Profiling**: ros2_tracing, perf
- **Network**: Wireshark for DDS traffic
- **Hardware**: oscilloscope, multimeter for electronics

## Safety Considerations
- Emergency stop functionality
- Fail-safe behaviors
- Hardware limits and constraints
- Safety-certified components where required
- Testing procedures and validation

## Version Control
- Git with conventional commits
- Feature branches for development
- CI/CD with GitHub Actions or GitLab CI
- Automated testing and deployment

## Hardware Platforms
- **Single Board Computers**: Raspberry Pi, NVIDIA Jetson
- **Microcontrollers**: Arduino, ESP32, STM32
- **Sensors**: LiDAR, cameras, IMU, encoders
- **Actuators**: Servo motors, stepper motors, DC motors
- **Communication**: CAN bus, I2C, SPI, UART

忠実に公式の書き方に従った書き方になってます。
Development Workflowを定義するように指示するべきでした。

次。GPT-5の結果。
他の作業もさせていたためか日本語を挿入してくれています。

CLAUDE.md

# CLAUDE.md — Robotics Development (Open Source Focus)

バージョン: 2025-09-23  
Status: Draft / Living Document (随時更新)  
Language: Bilingual (EN + 日本語)  

---
## 1. Purpose / 目的
This document defines how we collaborate with Claude for open-source based robotics development (ROS 2, simulation, perception, control, tooling). It provides prompt patterns, conventions, safety & quality guardrails.  
このドキュメントは、ROS 2 などのオープンソースを活用したロボット開発において Claude を効果的かつ安全に利用するための指針・プロンプト・規約をまとめたものです。

---
## 2. Scope / スコープ
- Mobile robots / manipulators / embedded edge controllers
- ROS 2 (Humble / Iron), Gazebo (Ignition / Fortress), MoveIt 2, Nav2, micro-ROS
- Perception: OpenCV, PCL, Open3D, YOLO / RT-DETR (optional), depth cameras
- Control: trajectory planning, kinematics, dynamics (Pinocchio, Ruckig), realtime loops
- Tooling: colcon, CMake, Python, Docker, VSCode Dev Containers

Out of scope: proprietary closed toolchains unless explicitly noted.

---
## 3. Core Principles / 基本原則
1. Open Source First — Prefer permissive or compatible licenses (Apache 2.0, MIT, BSD).  
2. Reproducibility — Every generated procedure must be runnable via documented commands.  
3. Safety & Ethics — No unsafe actuation instructions without simulation validation.  
4. Incremental Complexity — Start minimal (sim → hardware).  
5. Determinism & Real-Time Awareness — Respect executor / callback group design.  
6. Traceability — Each AI-assisted change must reference a ticket / issue ID.

---
## 4. Repository Conventions / リポジトリ規約
```text
repo/
  docs/
    CLAUDE.md            # This file
    architecture/*.md
  ros2_ws/
    src/
      /
        package.xml
        CMakeLists.txt
        include//...
        src/...
        launch/...
        config/...
  simulation/
    worlds/
    models/
  scripts/
  docker/
  tests/
    integration/
    simulation/
```

Naming: ROS 2 packages use `snake_case`; C++ namespaces `snake_case`; Python modules lowercase.  
Branch naming: `feat/`, `fix/`, `exp/`, `docs/...`  
Commit tag examples: `[nav2]`, `[perception]`, `[sim]`, `[control]`.

---
## 5. Licensing & Attribution / ライセンスと表記
When Claude suggests code derived from known projects (e.g., ROS 2 examples), ensure:  
- Keep original copyright header if recognizable.  
- Record source URL in PR description.  
- Avoid GPL-incompatible mixing (unless repo is GPL).  
- For embedded firmware (e.g., micro-ROS + FreeRTOS), verify license compatibility matrix.

---
## 6. Claude Interaction Guidelines / Claude 利用ガイド
Always provide:  
- Context (package, node role, constraints)  
- Interfaces (topics/services/actions, QoS)  
- Performance or real-time limits (latency, cycle time)  
- Safety assumptions (e-stop availability, simulation vs hardware)  
- Output format (code block language, table, checklist)  

Avoid vague prompts like: "Optimize navigation." Prefer:  
"Optimize Nav2 path replanning frequency from 2 Hz to ≥10 Hz on Jetson Orin, CPU budget <40%, show profiling method and config deltas."  

---
## 7. Prompt Templates / プロンプトテンプレート
### 7.1 Code Generation (C++ Node)
EN:
```
You are assisting with a ROS 2 C++ rclcpp node for a differential drive robot.
Goal: Subscribe to /scan (sensor_msgs/msg/LaserScan) and publish /cmd_vel (geometry_msgs/msg/Twist) with simple obstacle avoidance.
Constraints:
- ROS 2 Humble
- Avoid dynamic memory in callback; preallocate.
- Keep loop period at 50 ms.
Provide: 1) package.xml snippet, 2) CMakeLists additions, 3) node implementation, 4) launch file, 5) test strategy.
Output: markdown sections with language-tagged code blocks.
```
日本語:
```
ROS 2 C++ ノードを作成してください。/scan を購読し /cmd_vel を出力する簡易障害物回避。
条件: Humble, コールバック内で動的確保禁止, 50ms 周期, テスト方針含む。
```

### 7.2 Diagnostics & Debugging
```
Context: Unexpected 150 ms latency in navigation stack (expected <60 ms). Hardware: Jetson Orin, CPU usage 35%.
Request: Identify potential ROS 2 Nav2 bottlenecks. Provide stepwise profiling plan (ros2_tracing, perf, ros2 topic hz), config parameters to inspect, and expected healthy ranges. Output as table + prioritized action list.
```

### 7.3 Simulation Scenario Creation
```
Task: Create a Gazebo (Fortress) world for a warehouse: 20 shelving units, 2 AMR robots.
Need: 1) world file stub, 2) spawning launch script (ROS 2), 3) model placement strategy, 4) validation checklist.
Constraints: Keep total poly count low (<150k). Provide resource paths.
```

### 7.4 Perception Pipeline Refinement
```
Goal: Improve 3D obstacle clustering using PCL from 12 Hz to ≥20 Hz.
Inputs: Organized point cloud 1280x720, range 0.3-8 m.
Platform: x86_64 desktop.
Ask: Suggest pipeline changes (voxel grid size, outlier removal, segmentation), each with estimated complexity + expected speed gain. Provide benchmark script skeleton.
```

### 7.5 Safety Review
```
Perform a safety review of the differential drive control stack.
Provide: Failure modes table (component, failure, effect, mitigation), required ROS 2 lifecycle states, and monitoring topics.
Assume single MCU for motor drivers, include watchdog strategy.
```

### 7.6 Hardware Bring-Up
```
Context: New LiDAR (RPLIDAR A3) integration.
Need: 1) udev rule pattern, 2) ROS 2 driver launch snippet, 3) verification commands, 4) troubleshooting decision tree.
```

### 7.7 Real-Time Tuning
```
Task: Reduce jitter in a 1 kHz control loop on PREEMPT_RT kernel.
Provide: Thread priority assignment, executor design, lock-free data passing strategy, measurement method.
```

---
## 8. Guardrails / ガードレール
| Area | Rule | Rationale |
|------|------|-----------|
| Hardware Commands | Never produce motion code without sim validation step | Prevent unsafe actuation |
| Licensing | Always note license of copied snippet | Compliance |
| Real-Time | Avoid unbounded allocations in loops | Determinism |
| Data Logging | Cap log rate; note storage impact | Prevent disk exhaustion |
| AI Output Trust | Require human review before merge | Quality & Safety |

Checklist before accepting AI-generated code:
- [ ] Builds with `colcon build --merge-install`
- [ ] Passes `ament_lint` / `clang-tidy` style rules
- [ ] QoS profiles explicitly set (no hidden defaults for critical topics)
- [ ] Launch file includes namespacing & remap clarity
- [ ] Unit/integration test stubs added

---
## 9. Testing Strategy / テスト戦略
Levels:
1. Static: `ament_lint`, `cppcheck`, `clang-tidy`, `ruff` (Python)  
2. Unit: GTest / PyTest for pure logic (topic marshalling mocked)  
3. Integration: Launch tests with simulated sensors  
4. Simulation: Gazebo scenario regression (nightly)  
5. Hardware-in-the-Loop (HIL): After simulation pass  
6. Performance: Latency + CPU sampling (perf, LTTng / ros2_tracing)  

Metrics to record (CSV + dashboard): callback latency, message drop %, CPU core distribution, memory usage, path planning time, cluster processing FPS.

---
## 10. Performance & Real-Time Notes / 性能・リアルタイム
- Use multi-threaded executor for high-frequency perception + planning separation.  
- Pin high-rate control threads to isolated cores (e.g., `cset shield`).  
- Preallocate vectors in perception loops; reuse buffers.  
- Prefer `loaned_message` where supported (Zero-copy).  
- Use `RCLCPP_INFO_THROTTLE` for rate-limited logging.  

---
## 11. Simulation Workflow / シミュレーション手順
1. Launch world: `ros2 launch sim_bringup warehouse.launch.py`  
2. Spawn robot(s) & sensors  
3. Run navigation stack with fake odom → verify TF tree  
4. Record `ros2 bag` dataset for reproducible test  
5. Evaluate KPIs (time to first plan, path smoothness, CPU)  
6. Only after thresholds met → proceed to hardware test plan.

---
## 12. Security & Privacy / セキュリティ
- Strip proprietary config before sharing prompts to Claude.  
- Do not paste hardware serial numbers or credentials.  
- Mask network topology details if sensitive.  

---
## 13. Failure Mode Template / FMEA テンプレート
```
| Component | Failure | Effect | Detection | Mitigation | Severity (1-5) | Occurrence (1-5) | Action |
```
Claude Prompt:
```
Generate FMEA rows for the manipulator joint controller (6 DOF) focusing on encoder faults, torque saturation, and comms timeout. Output table, highest RPN first.
```

---
## 14. Contribution Flow / コントリビュートフロー
1. Open issue with context + acceptance criteria  
2. Draft prompt to Claude attaching issue ID  
3. Generate code in feature branch  
4. Run local QA checklist  
5. Open PR referencing issue, include AI prompt + deltas summary  
6. Human review mandatory  
7. Merge & tag if release-worthy  

---
## 15. Example High-Quality Prompt / 良いプロンプト例
```
[Context]
Package: perception_pipeline (ROS 2 Humble)
Goal: Optimize point cloud downsampling before clustering.
Current: Voxel leaf size 0.02 m → 12 Hz overall.
Target: ≥20 Hz, minimal cluster deformation.
Constraints: CPU only, no GPU. Accept ≤5% increase in false splits.
[Request]
1. Suggest 3 alternative parameter sets (+ pros/cons)
2. Provide benchmark node code (C++)
3. Include rclcpp::Time based latency measurement
4. Output final summary table.
[Output Format]
Markdown with sections: Options, Benchmark Code, Launch, Metrics Table.
```

---
## 16. Quick Reference / クイックリファレンス
| Item | Command / Note |
|------|----------------|
| Build | `colcon build --symlink-install` |
| Test | `colcon test --event-handlers console_direct+` |
| Lint (C++) | `ament_cpplint` / `clang-tidy` via `ament_clang_tidy` |
| Lint (Python) | `ruff check .` |
| Run simulation | `ros2 launch sim_bringup warehouse.launch.py` |
| Topic graph | `ros2 topic list`, `rqt_graph` |
| Performance trace | `ros2 trace -s session_name` |

---
## 17. Change Log / 変更履歴
| Date | Author | Change |
|------|--------|--------|
| 2025-09-23 | AI (CLAUDE.md scaffold) | Initial version |

---
## 18. Future Enhancements / 今後の拡張案
- Add concrete package examples (navigation + manipulator)  
- Provide real trace screenshots  
- Add CI pipeline YAML template  
- Add firmware integration guidelines (micro-ROS)  

---
## 19. Disclaimer / 免責
AI-generated suggestions must be validated in simulation and code-reviewed before deployment to physical hardware. Actual hardware testing must follow lab safety procedures.

---
End of CLAUDE.md

基本的に書き方の形式は公式の通りです。
GPT-5はGPLを使うな、としてくれています。
読むのが大変なくらい出力してくれています。

最後。Grok Code Fast 1です。

CLAUDE.md

# CLAUDE.md - Robotics Development Assistant

You are Claude, an AI assistant specialized in robotics development using open source tools and frameworks. Your expertise covers:

## Core Competencies
- **Hardware Design**: CAD modeling, electronics schematics, PCB design
- **Software Development**: Embedded systems, ROS (Robot Operating System), Python/C++/Rust programming
- **Computer Vision**: OpenCV, TensorFlow/PyTorch for vision tasks
- **Motion Control**: Servo motors, stepper motors, PID controllers
- **Sensor Integration**: IMU, LiDAR, cameras, ultrasonic sensors
- **Simulation**: Gazebo, Webots, PyBullet for testing and validation

## Open Source Tools & Libraries
- **ROS/ROS2**: Primary framework for robot software development
- **Arduino/Raspberry Pi**: Microcontroller and SBC platforms
- **OpenSCAD/FreeCAD**: 3D modeling and CAD
- **KiCad**: PCB design and schematic capture
- **OpenCV**: Computer vision library
- **PCL (Point Cloud Library)**: 3D point cloud processing
- **MoveIt**: Motion planning framework
- **Gazebo**: Robot simulation environment

## Development Workflow
1. **Requirements Analysis**: Understand robot specifications and use case
2. **System Design**: Architecture planning, component selection
3. **Prototyping**: Hardware assembly, basic software integration
4. **Development**: Iterative coding, testing, debugging
5. **Testing & Validation**: Unit tests, integration tests, real-world validation
6. **Documentation**: Code comments, README files, technical documentation

## Best Practices
- Use version control (Git) for all projects
- Write modular, reusable code
- Implement proper error handling and logging
- Document hardware connections and pinouts
- Test in simulation before deploying to hardware
- Follow ROS conventions and package structure
- Use open source licenses (MIT, Apache 2.0, GPL)

## Example Tasks
- Design a wheeled robot chassis using FreeCAD
- Implement autonomous navigation using ROS navigation stack
- Create a computer vision pipeline for object detection
- Develop a robotic arm control system with inverse kinematics
- Build a sensor fusion system combining IMU and LiDAR data

When assisting with robotics projects:
- Always prioritize safety and reliability
- Recommend open source alternatives to proprietary solutions
- Provide code examples with proper comments
- Suggest testing procedures and validation methods
- Encourage learning and experimentation

Remember: Robotics development requires careful consideration of hardware limitations, real-time constraints, and safety protocols. Always test thoroughly and iterate based on results.

書き方の形式は公式の通りです。
ただGPLだったりFreeCADなどを使おうとしているので、会社の中での開発という情報を与えた方が良かったと思います。
会社の中での開発という情報を与えたらSOLIDWORKSを使おうとするのかな ?
Core Competenciesを最初に持ってくるのは非常に好感が持てます。

置き場所について。

自分の全ての開発に共通するような内容 : ~/.claude/CLAUDE.md
git repository直下 : ~/git/dev_XXX/CLAUDE.md

1-2. Tune your CLAUDE.md files

CLAUDE.mdを向上させ続けるべきです。

公式の内容がおそらく汎用的にするために抽象的なので、具体的な例をClaude Opus 4.1に提示してもらいます。

指示内容 : CLAUDE.mdを向上させ続ける手順をmarkdownで示してください。

英語で指示 : Provide a markdown explanation on how to continuously improve CLAUDE.md using Sharp Keys in Claude Code.

sharp_keys_explanation.md

# シャープキーを使った CLAUDE.md の継続的改善 — Claude Code ガイド

## CLAUDE.md とは?

`CLAUDE.md` はプロジェクトレベルのメモリファイルで、Claude Code が会話開始時にシステムプロンプトへ自動的に読み込みます。プロジェクトのルートに配置し、コードベースにおける指示・規約・コンテキストを記述することで、Claude の振る舞いを導きます。

## シャープキーとは?

Claude Code では、プロンプト内で **`#`(シャープ/ハッシュ)キー** を使うことで、**ファイルをパスで参照** できます。`#` を入力するとファイルパスの補完候補が表示され、参照先ファイルの内容がメッセージのコンテキストとして送信されます。

例:

```
#src/utils/logger.ts を確認し、#CLAUDE.md のパターンに従ってください
```

これにより、両ファイルの内容がプロンプトと一緒に送信されます。

## 継続的改善のワークフロー

### 1. 作業中に CLAUDE.md を参照する

作業中は、編集中のファイルと一緒に `#CLAUDE.md` を参照し、Claude が現在の指示とコードの両方を把握できるようにします:

```
#CLAUDE.md を確認してください — #src/api/routes.ts で使われているパターンを正確に記述していますか?
```

### 2. 通常のタスク中にギャップを見つける

Claude がミスをしたり、より良い `CLAUDE.md` があれば防げたはずの質問をした場合、それが更新のサインです。例:

```
デフォルトエクスポートを使っていますが、このプロジェクトでは名前付きエクスポートを使います。
その規約を #CLAUDE.md に追加してください。
```

### 3. Claude に直接 CLAUDE.md を更新させる

Claude Code は `CLAUDE.md` を直接編集できます。パターンや規約を発見したら、次のように指示します:

```
すべての API ハンドラは型付きの Response オブジェクトを返す必要があることを #CLAUDE.md に追記してください。
```

### 4. `/memory` スタイルのプロンプトを使う

Claude に明示的に記憶させることで、`CLAUDE.md` に書き込まれます:

```
覚えておいて:このプロジェクトのテストは jest ではなく vitest を使います。
```

### 5. 定期的なレビューと改善

時折、Claude にファイルの内容を実態と照合させます:

```
#CLAUDE.md を読んで、#tsconfig.json、#package.json、#src/ のコードと比較してください。
古くなった記述を削除し、不足している情報を追加してください。
```

## CLAUDE.md に書くべき内容

| セクション | 例 |
|---|---|
| **ビルド/テストコマンド** | `npm run test -- --watch`, `make lint` |
| **コード規約** | 名前付きエクスポートを使う、デフォルトエクスポートは禁止 |
| **アーキテクチャ** | 「APIルートは `src/routes/` にあり、各ファイルが1つのリソースに対応」 |
| **よくある落とし穴** | 「公開モジュールで `@internal/*` からインポートしないこと」 |
| **スタイルルール** | 「例外をスローせず `Result` を使う」 |
| **ツールの指定** | 「`npm` ではなく `pnpm` を使う」 |

## 基本原則

- **簡潔に保つ。** CLAUDE.md は毎回の会話で読み込まれます。冗長な記述はコンテキストの無駄遣いです。
- **記述的ではなく指示的に。** 「名前付きエクスポートを使うこと」と書き、「このプロジェクトでは多くの場合、名前付きエクスポートが好まれる傾向があります」とは書かない。
- **段階的に更新する。** 一度に書き直すのではなく、セッションごとに1つずつ修正する。
- **古い記述は削除する。** 誤った指示は、指示がないことより悪い。
- **シャープキー(`#`)で相互参照する。** 実際のソースコードと照合することで、更新内容が現実に基づいたものになる。

1-3. Curate Claude’s list of allowed tools

僕の解釈。

rm -rfなんかは駄目に決まっているけどgit commitとかは許可なしでいいという設定にすると効率が上がります。

bashに限らずMCPも同様。

bash commandsやMCP toolsについて広く知り、その安全性について判断ができると、安全かつ効率が良い状況を作れますよ。

1-4. If using GitHub, install the gh CLI

僕の解釈。

ClaudeはGitHub APIも使えるしGitHubの使い方も知ってるよ。

広告

さくらのレンタルサーバ
ムームードメイン
Oisix(おいしっくす)
らでぃっしゅぼーや
珈琲きゃろっと
エプソムソルト
【FRONTIER】
AdGuard Ad Blocker
AdGuard VPN
AdGuard DNS




«       »