This commit is contained in:
trung09122002
2026-08-28 11:12:28 +07:00
commit 120923f9cc
124 changed files with 20117 additions and 0 deletions

View File

@@ -0,0 +1,83 @@
---
name: cavecrew
description: Framework giao việc cho 3 subagents chuyên biệt với output nén ~60% — investigator tìm code, builder sửa file, reviewer audit diffs. Dùng khi người dùng muốn 'tìm nơi function X được gọi', 'sửa nhỏ ở file này', 'review diff này', hoặc khi context budget đang cạn và cần delegate subtasks hiệu quả.
---
# Cavecrew
## Mục tiêu
Giao subtasks cho subagents chuyên biệt với output nhỏ hơn ~60% so với vanilla agents, phù hợp khi context budget hạn chế.
## Ba Agents
### cavecrew-investigator
Tìm code definitions, callers, usage patterns.
**Output contract:** `path:line — symbol — note`
**Dùng cho:** tìm function định nghĩa ở đâu, ai gọi nó, pattern xuất hiện ở đâu.
### cavecrew-builder
Sửa chính xác tối đa 2 files.
**Output contract:** `path:line-range — change` + verification status hoặc terminal codes (`too-big`, `ambiguous`, `done`)
**Dùng cho:** targeted changes khi scope hẹp và rõ ràng.
### cavecrew-reviewer
Audit diffs và branches để tìm defects.
**Output contract:** emoji-flagged findings theo file và line, với severity totals
**Dùng cho:** review diff sau khi thay đổi.
## Pattern Chuẩn
```
1. Spawn investigator → tìm target locations
2. Đưa paths cụ thể cho builder → apply changes
3. Chạy reviewer trên diff → verify kết quả
```
## Khi nào dùng Cavecrew vs Vanilla
| Cavecrew | Vanilla |
|---|---|
| Muốn findings ngắn gọn | Cần architectural commentary |
| Tối đa 2 files, scope hẹp | Xử lý 3+ files |
| Context budget hạn chế | Cần deep rationale |
| Pattern lặp lại nhiều lần | Phức tạp, nhiều unknowns |
## Ví dụ minh hoạ
**Ví dụ 1: Tìm và fix bug**
User: "Tìm chỗ nào gọi `process_image()` rồi thêm null check"
Hành động:
1. Spawn investigator: tìm tất cả callers của `process_image`
→ `src/detection.py:45 — process_image — called without null guard`
2. Spawn builder: thêm null check tại line 45
→ `src/detection.py:44-46 — added: if img is None: return — done`
3. Spawn reviewer: check diff
→ `L45: ✅ null guard added. No other callers affected.`
**Ví dụ 2: Investigate trước khi refactor**
User: "Tôi muốn rename topic `/camera/image` trước khi sửa"
Spawn investigator: "tìm tất cả chỗ dùng `/camera/image` trong codebase"
→ 3 files với exact locations, sẵn sàng cho builder
## Khắc phục sự cố
**Vấn đề:** Builder báo `too-big` — thay đổi quá lớn
**Cách xử lý:** Chia nhỏ task, giao từng phần cho builder riêng biệt
**Vấn đề:** Investigator trả về quá nhiều results
**Cách xử lý:** Làm hẹp query (thêm file path, function context) trước khi spawn lại
## Tradeoff
Output của cavecrew có thể "structured nhưng đôi khi terse đến mức cryptic". Dùng vanilla agents khi cần full explanation.

View File

@@ -0,0 +1,78 @@
---
name: caveman-commit
description: Tạo conventional commit messages ngắn gọn dưới 50 ký tự, tập trung vào intent không phải verbosity. Dùng khi người dùng yêu cầu 'viết commit message', 'tạo commit', 'git commit cho thay đổi này', '/caveman-commit', hoặc cần tóm tắt changes cho version control.
---
# Caveman Commit
## Mục tiêu
Tạo commit messages chính xác, conventional, và tối giản — không filler, không AI attribution, không self-reference.
## Format
```
<type>(<scope>): <summary>
```
- Subject line: ≤50 ký tự (hard limit 72)
- Imperative mood: "add" không phải "added", "fix" không phải "fixed"
- Không dấu chấm cuối
- Không đại từ ngôi thứ nhất (I, we)
- Không "Generated by Claude" hoặc tương tự (trừ khi project policy yêu cầu)
- Không emoji (trừ khi project convention dùng)
## Khi nào thêm body
Chỉ thêm body khi thực sự cần:
- Logic không rõ ràng từ subject
- Breaking changes (`BREAKING CHANGE:`)
- Migration steps cần thiết
- Issue references (`Closes #123`)
Bỏ qua body hoàn toàn khi subject đã tự giải thích.
## Luôn cần body
- Breaking changes
- Security fixes
- Reversions (ghi rõ cái gì được revert và tại sao)
## Ví dụ minh hoạ
**Ví dụ 1: Bug fix đơn giản**
User: "Tôi vừa fix null pointer exception trong user login"
Kết quả:
```
fix(auth): guard null user before email access
```
**Ví dụ 2: Feature mới với breaking change**
User: "Thêm JWT auth, bỏ session-based auth cũ"
Kết quả:
```
feat(auth): replace session auth with JWT
BREAKING CHANGE: session tokens no longer valid.
Clients must re-authenticate to obtain JWT.
```
## Khắc phục sự cố
**Vấn đề:** Subject line dài hơn 50 ký tự
**Cách xử lý:** Rút gọn scope hoặc bỏ scope, ưu tiên từ mô tả action chính xác nhất
**Vấn đề:** Không biết type phù hợp
**Cách xử lý:** feat/fix/chore/docs/refactor/test/perf — hỏi nếu cần context
## Output
Plain text commit message trong code block, sẵn sàng để paste. Không chạy git, không stage files, không amend commits.
## Deactivation
Nói "stop caveman-commit" hoặc "normal mode".

View File

@@ -0,0 +1,90 @@
---
name: caveman-compress
description: Nén prose trong các file markdown như CLAUDE.md, PROJECT_CONTEXT.md, todos thành caveman-speak ngắn gọn để giảm ~46% input tokens, giữ nguyên toàn bộ kỹ thuật và code. Dùng khi người dùng gõ '/caveman-compress <file>', yêu cầu 'nén file này', 'giảm size của CLAUDE.md', 'compress memory file', hoặc context files quá dài gây tốn tokens.
---
# Caveman Compress
## Mục tiêu
Rewrite prose sections của markdown files thành terse nhất có thể, giữ nguyên mọi technical fact, code block, và structural element.
## Trigger
`/caveman-compress <filepath>` hoặc user yêu cầu compress file cụ thể.
## Quy trình
### Bước 1: Đọc file
Đọc file target, xác nhận là markdown/text (không phải code file).
### Bước 2: Tạo backup
Lưu bản gốc thành `<filename>.original.md` trước khi overwrite.
### Bước 3: Compress prose
Áp dụng rules bên dưới cho phần prose, giữ nguyên code blocks và technical content.
### Bước 4: Validate
Kiểm tra: không mất thông tin kỹ thuật, structure còn nguyên, không sửa code blocks.
## Rules Compression
**Xóa khỏi prose:**
- Articles (a, an, the)
- Filler words (really, basically, simply, just, very)
- Hedging (it seems, I think, có thể, có lẽ)
- Redundant phrases và connective fluff
**Compress bằng cách:**
- Short synonyms
- Sentence fragments thay câu đầy đủ
- Action-focused language
- Merge redundant points (giữ một example đại diện)
**Không bao giờ sửa:**
- Nội dung trong ` ``` ... ``` ` — copy EXACTLY
- Inline code trong backticks
- URLs, file paths, commands, technical terms
- Proper nouns, dates, version numbers, env variables
- Markdown headings, lists, tables, frontmatter
## Ví dụ minh hoạ
**Ví dụ 1: Compress PROJECT_CONTEXT.md**
User: "/caveman-compress PROJECT_CONTEXT.md"
Hành động:
1. Đọc file, tạo `PROJECT_CONTEXT.original.md`
2. Compress từng section prose
3. Giữ nguyên table structures và code examples
4. Output file nén với % reduction
Trước: "The project uses ROS 2 Humble as the primary middleware framework for inter-process communication between nodes."
Sau: "ROS 2 Humble. IPC between nodes."
**Ví dụ 2: Compress CLAUDE.md dài**
User: "CLAUDE.md của tôi quá dài, giảm size đi"
Kết quả: Compress ~46% prose, giữ nguyên commands, code examples, và technical constraints.
## Khắc phục sự cố
**Vấn đề:** Thông tin bị mất sau khi compress
**Cách xử lý:** Restore từ `.original.md` backup, tôi sẽ compress lại cẩn thận hơn
**Vấn đề:** File là code file (Python, YAML config)
**Cách xử lý:** Skill chỉ xử lý .md, .txt, .tex và extensionless docs. Từ chối code/config files.
## Note
Đầy đủ nhất với Python script từ caveman repo (validation + retry tự động). Không có script, compress trực tiếp bằng model theo rules này.
## Scope
Chỉ xử lý: `.md`, `.txt`, `.typ`, `.tex`, extensionless documents. Không sửa code files, config files, env files.

View File

@@ -0,0 +1,59 @@
---
name: caveman-help
description: Hiển thị bảng tham chiếu nhanh cho toàn bộ hệ thống caveman bao gồm modes, skills, lệnh, và cách tắt. Dùng khi người dùng gõ '/caveman-help', hỏi 'có những caveman mode nào', 'list lệnh caveman', 'quên cú pháp caveman', hoặc cần reminder về các tùy chọn compression.
---
# Caveman Help
## Mục tiêu
Hiển thị một lần (one-shot) bảng tham chiếu đầy đủ hệ thống caveman. Không thay đổi mode hay session state.
## Bảng Tham Chiếu Nhanh
### Modes
| Mode | Style | Savings |
|---|---|---|
| `lite` | Bỏ filler, giữ câu đầy đủ | ~30% |
| `full` | Fragments, bỏ articles (default) | ~60% |
| `ultra` | Telegraphic, cực ngắn | ~75% |
| `wenyan-lite` | Semi-classical Chinese | ~70% |
| `wenyan-full` | Classical Chinese tối đa | ~85% |
Bật: `/caveman [mode]` — default là `full`
### Skills
| Skill | Trigger | Chức năng |
|---|---|---|
| `caveman` | `/caveman [mode]` | Nén toàn bộ replies |
| `caveman-commit` | `/caveman-commit` | Commit messages ngắn |
| `caveman-review` | `/caveman-review` | Code review nén |
| `caveman-stats` | `/caveman-stats` | Token usage stats |
| `caveman-compress` | `/caveman-compress <file>` | Nén memory files |
| `cavecrew` | "dùng cavecrew" | Delegation subagents |
| `caveman-help` | `/caveman-help` | Card này |
### Tắt
Nói "stop caveman", "normal mode", hoặc "thôi caveman".
Resume bất cứ lúc nào với `/caveman`.
### Quy tắc bất biến
- Giữ nguyên ngôn ngữ của user
- Code, commands, error strings, technical terms: **không bao giờ** bị nén
- Security warnings và irreversible actions: tự động revert về normal
## Ví dụ minh hoạ
**Ví dụ: User quên cú pháp**
User: "/caveman-help"
Kết quả: Card này hiển thị một lần, session state không đổi.
## Scope
One-shot display. Không set hay thay đổi bất kỳ mode nào.

View File

@@ -0,0 +1,72 @@
---
name: caveman-review
description: Review code cực ngắn gọn với format L<line>: severity problem. fix. — tối đa signal, zero filler. Dùng khi người dùng yêu cầu 'review code này', 'check PR', '/caveman-review', 'feedback ngắn gọn', hoặc muốn code review không có lời khen và hedging, chỉ có findings và fixes.
---
# Caveman Review
## Mục tiêu
Review code với maximum signal, zero filler. Mỗi finding đi kèm line number chính xác và fix cụ thể.
## Output Format
```
L<line>: [severity] <problem>. <fix>.
```
**Severity prefixes:**
- 🔴 bug — gây incorrect behavior
- 🟡 risk — tiềm ẩn vấn đề tùy context
- 🔵 nit — style hoặc minor improvement
- ❓ q — câu hỏi cần hỏi trước
## Rules
- Không hedging qualifiers ("I noticed", "you might want to consider", "có thể bạn nên")
- Không preamble ("Here's my review", "Tôi đã xem xét code của bạn")
- Không lời khen ("Great job on the overall structure")
- Luôn ghi: line number + symbol/variable + giải pháp cụ thể
- Code không bị sửa trong review output
## Ví dụ minh hoạ
**Ví dụ 1: Bug rõ ràng**
Bad: "I noticed that on line 42 you're not checking if the user object is null, which could potentially cause issues down the line."
Good: `L42: 🔴 bug: user null after .find(). Add guard before .email.`
**Ví dụ 2: Review robotics code**
```
L15: 🔴 bug: no encoding check on image_msg. Assert rgb8 or convert.
L31: 🟡 risk: queue_size=1 drops messages at 30fps. Increase to 10.
L48: 🔵 nit: hardcoded threshold 0.5. Move to ROS param.
L67: ❓ q: why lookup TF every callback? Cache transform.
```
## Khi nào expand
Viết đầy đủ hơn cho:
- CVE-level security vulnerabilities
- Architectural decisions cần rationale
- Onboarding context cho team member mới
Resume terse mode sau đó.
## Khắc phục sự cố
**Vấn đề:** Line number không chính xác trong review
**Cách xử lý:** Cung cấp file với line numbers rõ ràng, hoặc paste đoạn code cụ thể
**Vấn đề:** Muốn cả caveman-review VÀ robotics-code-review
**Cách xử lý:** Dùng `robotics-code-review` để tìm findings, format output theo `caveman-review` style
## Scope
Chỉ tạo review comments. Không viết fixes, không approve changes, không chạy linters.
## Deactivation
Nói "stop caveman-review" hoặc "normal mode".

View File

@@ -0,0 +1,66 @@
---
name: caveman-stats
description: Hiển thị thống kê token usage và estimated savings trong session hiện tại. Dùng khi người dùng gõ '/caveman-stats', hỏi 'tiết kiệm được bao nhiêu tokens', 'show token savings', 'token usage của session này', hoặc muốn đánh giá hiệu quả compression.
---
# Caveman Stats
## Mục tiêu
Hiển thị số liệu tokens thực tế đã dùng và ước tính savings trong session hiện tại.
## Trigger
`/caveman-stats` hoặc user hỏi về token usage stats.
## Behavior
Khi không có hook system (standalone skill), estimate session stats:
1. Đếm số exchanges có caveman mode active
2. Ước tính baseline tokens (không có compression) vs actual
3. Báo cáo savings percentage
## Output Format
```
Session stats:
- Caveman active: N exchanges
- Est. tokens used: ~X
- Est. baseline (no compression): ~Y
- Est. savings: ~Z% (~W tokens)
- Current mode: [lite/full/ultra/off]
```
## Ví dụ minh hoạ
**Ví dụ 1: Check sau session dài**
User: "/caveman-stats"
Kết quả:
```
Session stats:
- Caveman active: 12/15 exchanges
- Est. tokens used: ~4,200
- Est. baseline (no compression): ~12,000
- Est. savings: ~65% (~7,800 tokens)
- Current mode: full
```
## Khắc phục sự cố
**Vấn đề:** Số liệu không chính xác
**Nguyên nhân:** Standalone skill chỉ estimate, không đọc session log trực tiếp
**Cách xử lý:** Để có số liệu chính xác 100%, cần cài `hooks/caveman-stats.js` từ repo caveman gốc (juliusbrussee/caveman)
**Vấn đề:** Skill không biết caveman đã active bao lâu
**Cách xử lý:** Mention khi nào bật caveman để context rõ hơn
## Note
Đầy đủ nhất khi cài `hooks/caveman-stats.js` — đọc trực tiếp từ Claude Code session log, không cần estimate. Không có hook, con số là heuristic.
## Scope
Read-only display. Không thay đổi session state hay bật/tắt modes.

View File

@@ -0,0 +1,65 @@
---
name: caveman
description: Giảm ~75% output tokens bằng cách nói ngắn gọn, bỏ từ thừa nhưng giữ nguyên kỹ thuật, code, error strings. Dùng khi người dùng yêu cầu 'ít tokens hơn', 'ngắn gọn thôi', 'caveman mode', '/caveman', 'less verbose', 'talk like caveman', hoặc muốn tiết kiệm tokens trong session dài.
---
# Caveman Mode
## Mục tiêu
Nén toàn bộ responses để tối thiểu hóa tokens, giữ nguyên mọi thông tin kỹ thuật, code block, và error strings.
## Rules
- **Bỏ:** articles (a/an/the), filler words (just, really, basically, simply), lời khen (great question, certainly), hedging (I think, it seems, có lẽ, tôi nghĩ)
- **Giữ:** tất cả kỹ thuật, code blocks, error strings chính xác, API names, acronyms, command flags
- **Pattern:** `[thing] [action] [reason]. [next step].`
- **Ngôn ngữ:** match theo ngôn ngữ user, chỉ nén style
- **Không** thông báo mode hoặc tự reference ("me caveman think")
## 5 Mức độ
| Mức | Style | Savings |
|---|---|---|
| `lite` | Bỏ filler, giữ câu đầy đủ | ~30% |
| `full` | Cho phép fragments, bỏ articles (default) | ~60% |
| `ultra` | Cực ngắn, telegraphic | ~75% |
| `wenyan-lite` | Semi-classical Chinese | ~70% |
| `wenyan-full` | Classical Chinese tối đa | ~85% |
Đổi mức: `/caveman [level]`
## Ngoại lệ tự động
Tạm thời revert về normal cho:
- Cảnh báo bảo mật
- Xác nhận hành động không thể undo
- Multi-step sequence phức tạp cần rõ ràng
Resume caveman ngay sau đó.
## Ví dụ minh hoạ
**Ví dụ 1: Giải thích lỗi**
Normal: "I noticed that the error you're encountering is likely due to a missing null check on line 42. You might want to consider adding a guard clause before accessing the email property."
Caveman full: "L42: null check missing. Add guard before .email."
**Ví dụ 2: Hướng dẫn cài đặt**
Normal: "First, you'll need to install the dependencies by running npm install. After that's complete, you can start the development server using npm run dev."
Caveman full: "npm install → npm run dev."
## Khắc phục sự cố
**Vấn đề:** Claude vẫn dùng ngôn ngữ dài dòng sau khi bật caveman
**Cách xử lý:** Nhắc lại "caveman mode on" hoặc gõ `/caveman full` để reinforce
**Vấn đề:** Code bị nén/viết tắt không mong muốn
**Cách xử lý:** Code blocks luôn được giữ nguyên theo rule. Nếu bị ảnh hưởng, báo lỗi và tôi sẽ fix ngay.
## Deactivation
Nói "stop caveman", "normal mode", hoặc "thôi caveman".

View File

@@ -0,0 +1,102 @@
---
name: cv-pipeline-analysis
description: Phân tích pipeline computer vision cho robot từ đầu vào camera đến đầu ra, bao gồm calibration, preprocessing, inference và postprocessing. Dùng khi người dùng yêu cầu 'phân tích camera pipeline', 'debug perception node', 'kiểm tra image encoding', 'trace CV pipeline', hoặc gặp vấn đề với object detection, segmentation, depth estimation, synchronization.
---
# CV Pipeline Analysis
## Mục tiêu
Trace và đánh giá toàn bộ computer vision pipeline trong repository từ sensor input đến outputs, sử dụng configuration và code đã được xác minh.
## Khi nào dùng
Dùng cho các vấn đề về camera ingestion, image processing, object detection, segmentation, tracking, depth, calibration, perception topics, inference nodes, hoặc visualization.
## Quy trình
### Bước 1: Đọc context
Đọc `PROJECT_CONTEXT.md` và `MODEL_DEPLOYMENT_CONTEXT.md` nếu có.
### Bước 2: Khám phá pipeline từ repo
Từ repo, discover:
- Camera topics, drivers, calibration files (camera_info, yaml, json)
- Image encodings (rgb8, bgr8, mono8, 16UC1)
- Frame IDs và synchronization policy
### Bước 3: Trace preprocessing
Kiểm tra từng bước: resize, crop, pad, color conversion, normalization, undistortion, rectification, batching.
### Bước 4: Trace inference stage
Xác minh: model/runtime, input/output shapes, thresholds, postprocessing, coordinate transforms.
### Bước 5: Trace outputs
Kiểm tra: topics, message types, frames, units, visualization markers, diagnostics, logs, saved artifacts.
### Bước 6: So sánh patterns
- ROS 1: image_transport, message_filters, CameraInfo
- ROS 2: image_transport, QoS, message_filters, composition
## Checklist
- [ ] Input image encoding và calibration đã xác minh
- [ ] Camera frame và optical frame usage đã kiểm tra
- [ ] Synchronization và timestamp policy đã kiểm tra
- [ ] Preprocessing khớp với model/algorithm contract
- [ ] Postprocessing units, frames, thresholds đã kiểm tra
- [ ] Unknowns ghi `Unknown / needs confirmation`
## Ví dụ minh hoạ
**Ví dụ 1: Debug detection node không ra kết quả**
Người dùng nói: "Object detection node chạy nhưng không publish gì"
Hành động:
1. Tìm node entry point, trace subscriber của `/image_raw` hoặc topic tương đương
2. Kiểm tra encoding: node expect `rgb8` nhưng camera publish `bgr8`?
3. Kiểm tra CameraInfo subscription và calibration loading
4. Trace inference call và threshold filter
Kết quả: Xác định mismatch encoding hoặc threshold quá cao, đề xuất fix cụ thể.
**Ví dụ 2: Phân tích độ trễ pipeline**
Người dùng nói: "Pipeline detection chạy chậm, cần biết bottleneck ở đâu"
Hành động:
1. Map toàn bộ pipeline: camera → preprocessing → inference → postprocessing → publish
2. Kiểm tra có image copy không cần thiết không
3. Kiểm tra preprocessing có resize trước inference không
4. Kiểm tra có GPU transfer overhead không
Kết quả: Pipeline map với estimated latency từng bước và top-3 optimization candidates.
## Khắc phục sự cố
**Lỗi:** Calibration không load được
**Nguyên nhân:** Path hardcode hoặc file không tồn tại ở runtime
**Cách xử lý:** Tìm calibration file path trong launch/config, xác minh file tồn tại, kiểm tra parameter load
**Lỗi:** Image encoding mismatch (CV_8UC3 vs bgr8)
**Nguyên nhân:** cv_bridge convert sai hoặc node giả định encoding khác với camera publish
**Cách xử lý:** Trace cv_bridge call, kiểm tra `encoding` parameter, so sánh với camera driver publish format
**Lỗi:** Synchronization drift giữa camera và LiDAR
**Nguyên nhân:** message_filters ApproximateTime slop quá nhỏ hoặc clock source khác nhau
**Cách xử lý:** Kiểm tra slop value trong code, xác minh cả hai sensor dùng cùng clock source
## Output Format
- Pipeline map: từng stage với input/output contracts
- Verified configuration: calibration, encoding, thresholds
- Contract checks: preprocessing ↔ model alignment
- Failure points: evidence từ file/line cụ thể
- Performance considerations: copy, resize, transfer overhead
- Next verification: commands hoặc tests cần chạy

View File

@@ -0,0 +1,99 @@
---
name: edge-ai-deployment
description: Đánh giá và review quy trình triển khai AI model cho robot và thiết bị edge, bao gồm model format, runtime, accelerator, latency và memory constraints. Dùng khi người dùng yêu cầu 'deploy model lên edge', 'review TensorRT/ONNX deployment', 'kiểm tra GPU memory', 'optimize inference', hoặc gặp vấn đề với latency, packaging, power, hoặc compatibility.
---
# Edge AI Deployment
## Mục tiêu
Đánh giá xem AI model deployment path có coherent cho robot/edge system mục tiêu hay không, dựa trên facts đã xác minh từ repo và user.
## Khi nào dùng
Dùng cho TensorRT, ONNX Runtime, TFLite, OpenVINO, Core ML, CUDA, NPU, TPU, VPU, embedded Linux, container, cross-compile, hoặc robotics inference deployment.
## Quy trình
### Bước 1: Đọc context
Đọc `PROJECT_CONTEXT.md` và `MODEL_DEPLOYMENT_CONTEXT.md` nếu có.
### Bước 2: Khám phá artifacts
Discover từ repo: model files, conversion scripts, runtime wrappers, Dockerfiles, launch/config files, hardware references.
### Bước 3: Xác minh model contract
Kiểm tra: source format, deployment format, opset/version, precision, batch size, input/output shapes, preprocessing contract.
### Bước 4: Kiểm tra runtime và hardware
Chỉ xác nhận khi có evidence từ repo hoặc user: target runtime, accelerator, driver version.
### Bước 5: Kiểm tra ROS integration
- ROS 1: node/nodelet, topics, queue sizes, timestamps, frames, diagnostics
- ROS 2: node/component, QoS, lifecycle, timestamps, frames, diagnostics
### Bước 6: Đánh giá constraints
Latency, memory footprint, startup time, thermal/power, fallback behavior, model artifact versioning.
## Checklist
- [ ] Model path và version đã xác minh
- [ ] Runtime và hardware target đã xác minh hoặc ghi unknown
- [ ] Input/output tensor contract đã kiểm tra
- [ ] Pre/postprocessing consistency đã kiểm tra
- [ ] Deployment packaging và environment đã kiểm tra
- [ ] Unknowns ghi `Unknown / needs confirmation`
## Ví dụ minh hoạ
**Ví dụ 1: Review TensorRT deployment trên Jetson**
Người dùng nói: "Tôi có model ONNX muốn deploy lên Jetson Orin, cần review path deployment"
Hành động:
1. Tìm conversion script (thường là `convert.py` hoặc `build_engine.py`)
2. Xác minh: opset version, FP16/INT8, dynamic batch hay không, workspace size
3. Kiểm tra preprocessing trong ROS node có khớp với training preprocessing không
4. Kiểm tra memory budget: activation memory + weight size vs available GPU memory
Kết quả: Report deployment risks, recommended TRT flags, memory estimates.
**Ví dụ 2: Debug inference latency quá cao**
Người dùng nói: "Model inference mất 150ms nhưng cần dưới 50ms"
Hành động:
1. Xác minh precision: đang chạy FP32 thay vì FP16?
2. Kiểm tra batch size và dynamic shape overhead
3. Kiểm tra có CPU↔GPU memory copy không cần thiết không
4. Kiểm tra preprocessing có chạy trên CPU thay vì GPU không
Kết quả: Top bottlenecks với estimated speedup cho từng fix.
## Khắc phục sự cố
**Lỗi:** TensorRT engine build thất bại với "No implementation for layer"
**Nguyên nhân:** Custom op hoặc ONNX node không được TRT hỗ trợ
**Cách xử lý:** Tìm op trong ONNX graph, xem có TRT plugin không, hoặc fallback về ONNX Runtime
**Lỗi:** Accuracy giảm sau FP16 conversion
**Nguyên nhân:** Precision loss ở softmax, normalization, hoặc small activations
**Cách xử lý:** Thêm `precision_constraints` cho sensitive layers, giữ FP32 cho output head
**Lỗi:** OOM (Out of Memory) khi load engine
**Nguyên nhân:** Activation memory + weight vượt quá GPU memory
**Cách xử lý:** Giảm batch size, bật memory pool, hoặc dùng model nhỏ hơn
## Output Format
- Deployment summary: source → target format path
- Verified artifacts và runtime
- Contract risks: preprocessing mismatch, shape issues
- Integration risks: ROS topic, timing, frame
- Performance/resource risks: latency, memory, thermal
- Next checks: commands hoặc files cần xem xét

View File

@@ -0,0 +1,223 @@
---
name: manual-build-handoff
description: Cấm Claude tự chạy build, compile, install, launch, train, flash hoặc bất kỳ lệnh chạy ngầm nào. Thay vào đó Claude in ra lệnh chính xác để người dùng tự chạy trong terminal, dừng lại chờ, rồi phân tích kết quả người dùng báo về. Kích hoạt khi cần colcon build, catkin_make, cmake, make, npm/cargo/pip install, docker build, roslaunch, ros2 launch/run, rosbag play, trtexec, train script, flash firmware, hoặc khi người dùng nói 'đừng tự chạy', 'đưa lệnh tôi chạy', 'don't run it yourself', 'give me the command'.
---
# Manual Build Handoff
## Mục tiêu
Claude **không bao giờ** tự thực thi lệnh build/run. Claude chỉ soạn lệnh chính xác, bàn giao cho người dùng chạy trong terminal thật, dừng lại chờ, rồi đọc kết quả người dùng báo về để phân tích tiếp.
Lý do: build robotics/CV tốn nhiều phút, chiếm CPU/GPU, đụng phần cứng thật, ghi đè `install/`, `build/`, `devel/`, hoặc khởi động node điều khiển robot. Người dùng phải là người bấm nút.
## Khi nào dùng
Luôn luôn, trong mọi session của repo này. Không cần người dùng gọi tên.
## Rules
### Lệnh BỊ CẤM tự chạy
Claude **không** chạy, kể cả ở foreground lẫn background (`run_in_background`, `&`, `nohup`, `tmux`, `screen`):
| Nhóm | Ví dụ |
|---|---|
| Build ROS | `colcon build`, `catkin_make`, `catkin build`, `. install/setup.bash` kèm build |
| Build chung | `make`, `ninja`, `cmake --build`, `bazel build`, `cargo build`, `go build` |
| Package manager | `pip install`, `npm install`, `npm run build`, `apt install`, `rosdep install` |
| Container | `docker build`, `docker run`, `docker compose up` |
| Chạy robot | `roslaunch`, `ros2 launch`, `ros2 run`, `rosrun`, `rosbag play/record` |
| AI/Model | `train.py`, `trtexec`, `onnx export`, `tflite convert`, quantization script |
| Phần cứng | flash firmware, `dfu-util`, `openocd`, ghi SD card, `dd` |
| Test nặng | `colcon test`, `pytest` toàn repo, integration test cần hardware |
| Bất kỳ lệnh nào | chạy > ~10s, cần sudo, cần GPU, hoặc sửa file ngoài repo |
### Lệnh VẪN được tự chạy
Read-only inspection, chạy nhanh, không sửa state:
`ls`, `cat`, `head`, `tail`, `grep`, `rg`, `find`, `tree`, `wc`
`git status`, `git log`, `git diff`, `git show`, `git branch`
`ros2 pkg list`, `ros2 topic list`, `ros2 param list` (chỉ liệt kê, không echo lâu)
`python -c "import x; print(x.__version__)"`, `nvidia-smi`, `uname -a`, `pkg-config --modversion`
Nghi ngờ → coi như bị cấm, bàn giao cho người dùng.
### Quy tắc bàn giao
- Một lần bàn giao = **một lệnh** (hoặc một chuỗi lệnh liền mạch chạy một lượt). Không nhồi 5 lệnh rời rạc.
- Luôn nêu **thư mục làm việc** và **điều kiện trước** (`source` môi trường nào).
- Luôn nói rõ **cần báo lại gì** — full log, 30 dòng cuối, hay chỉ exit code.
- Sau khi in block bàn giao, **dừng hẳn**. Không đoán trước kết quả, không viết tiếp code dựa trên giả định build pass.
- Không hỏi "bạn có muốn tôi chạy không?" — mặc định là không chạy.
## Quy trình
### Bước 1: Xác định lệnh cần chạy
Discover lệnh build thật từ repo (`package.xml`, `CMakeLists.txt`, `Makefile`, `pyproject.toml`, `docker-compose.yml`, CI config), không bịa.
### Bước 2: Thu hẹp phạm vi lệnh
Ưu tiên lệnh nhỏ nhất đủ để kiểm chứng. Ví dụ `colcon build --packages-select my_pkg` thay vì build cả workspace.
### Bước 3: In block bàn giao
Theo đúng Handoff Format bên dưới.
### Bước 4: Dừng và chờ
Kết thúc lượt trả lời. Không gọi thêm tool chạy lệnh.
### Bước 5: Nhận kết quả
Người dùng dán output, hoặc chỉ nói `pass` / `fail`, hoặc trỏ tới file log.
### Bước 6: Phân tích
Đọc log, xác định lỗi thật (dòng error đầu tiên, không phải dòng cuối), đề xuất fix. Nếu cần chạy lại → quay lại Bước 3.
## Handoff Format
````text
## Lệnh cần chạy
Thư mục: <đường dẫn tuyệt đối>
Chuẩn bị: <source ... / export ... / hoặc "không cần">
```bash
<lệnh chính xác, copy-paste được>
```
Mục đích: <kiểm chứng cái gì>
Thời gian dự kiến: <~2 phút / vài giây / lâu>
Kỳ vọng: <dấu hiệu thành công, ví dụ "Summary: 3 packages finished">
Báo lại cho tôi: <full output / 30 dòng cuối / exit code / nội dung file log>
Đang chờ kết quả — tôi không tự chạy lệnh này.
````
## Mẹo: ghi log để Claude tự đọc
Thay vì dán output dài, cho lệnh ghi ra file rồi bảo Claude đọc file (đọc file là read-only, được phép):
```bash
colcon build --packages-select my_pkg 2>&1 | tee /tmp/build.log
```
Rồi chỉ cần nói: *"xong rồi, đọc /tmp/build.log"*.
Với lệnh dài, thêm exit code vào log:
```bash
{ colcon build --packages-select my_pkg; echo "EXIT=$?"; } 2>&1 | tee /tmp/build.log
```
## Ví dụ minh hoạ
**Ví dụ 1: Sửa xong code, cần build lại**
Người dùng nói: *"Sửa lỗi type mismatch trong `image_proc_node.cpp` rồi build lại"*
Hành động: Claude sửa file (theo `patch-preview-before-edit`), rồi **không** chạy `colcon build`, mà in:
````text
## Lệnh cần chạy
Thư mục: /home/user/ros2_ws
Chuẩn bị: source /opt/ros/humble/setup.bash
```bash
{ colcon build --packages-select image_proc --symlink-install; echo "EXIT=$?"; } 2>&1 | tee /tmp/build.log
```
Mục đích: xác nhận fix type mismatch compile được
Thời gian dự kiến: ~40 giây
Kỳ vọng: `Summary: 1 package finished`, `EXIT=0`
Báo lại cho tôi: nói "xong" và tôi đọc /tmp/build.log
Đang chờ kết quả — tôi không tự chạy lệnh này.
````
Kết quả: Người dùng chạy, báo `xong`, Claude đọc log và phân tích.
**Ví dụ 2: Cần chạy node để xem topic**
Người dùng nói: *"Chạy thử node xem có publish `/camera/image_raw` không"*
Hành động: Bàn giao **hai** lệnh cho **hai** terminal, đánh số rõ ràng:
````text
## Lệnh cần chạy
Terminal 1 — Thư mục: /home/user/ros2_ws · Chuẩn bị: source install/setup.bash
```bash
ros2 launch camera_driver camera.launch.py
```
Terminal 2 — Chuẩn bị: source install/setup.bash
```bash
ros2 topic hz /camera/image_raw
```
Mục đích: xác nhận node publish đúng topic và rate
Kỳ vọng: `average rate: ~30.0`
Báo lại cho tôi: 5 dòng đầu của Terminal 2, và bất kỳ error nào ở Terminal 1
Đang chờ kết quả — tôi không tự chạy lệnh này.
````
**Ví dụ 3: Người dùng chủ động yêu cầu Claude chạy**
Người dùng nói: *"Chạy `colcon build` giùm tôi đi"*
Hành động: Người dùng override rõ ràng → được phép chạy, nhưng chạy **foreground**, không `run_in_background`, và báo trước thời gian dự kiến. Skill này chỉ cấm chạy **tự động, ngầm, không ai yêu cầu**.
## Enforcement cứng
Skill là chỉ dẫn mềm — vẫn có xác suất Claude quên. Nên `install.sh` cài kèm một `PreToolUse` hook chặn ở tầng harness, không phụ thuộc model có nhớ hay không:
- `.claude/hooks/block-build.sh` — khớp regex danh sách lệnh cấm, exit code 2 = huỷ tool call và trả stderr về cho Claude đọc
- `.claude/settings.json` — đăng ký hook với `matcher: "Bash"`
Hook đọc `tool_input.command` từ JSON payload (dùng `python3`, fallback `jq`), nên chỉ khớp **lệnh thật**, không khớp nhầm phần `description`. Ví dụ `cat /tmp/build.log` với mô tả *"read log after colcon build"* vẫn được phép chạy.
Hook có hiệu lực sau khi **restart Claude Code**.
**Escape hatch:** thêm `# user-approved` vào cuối lệnh để bỏ qua hook. Chỉ dùng khi người dùng chủ động yêu cầu chạy (Ví dụ 3 ở trên):
```bash
colcon build --packages-select my_pkg # user-approved
```
Marker hiện rõ trong lệnh nên người dùng luôn thấy được khi nào hook bị bypass.
**Tắt hook:** xoá entry `matcher: "Bash"` trỏ tới `block-build.sh` trong `.claude/settings.json`.
## Khắc phục sự cố
**Lỗi:** Claude vẫn tự chạy build
**Nguyên nhân:** Chưa restart Claude Code sau khi cài, hoặc lệnh nằm trong `permissions.allow` của `settings.json`
**Cách xử lý:** Restart Claude Code; kiểm tra `permissions.allow` không chứa `Bash(colcon build:*)`; xác nhận hook chạy được bằng `printf '{"tool_input":{"command":"colcon build"}}' | .claude/hooks/block-build.sh; echo $?` (phải in `2`)
**Lỗi:** Hook chặn nhầm lệnh vô hại
**Nguyên nhân:** Regex trong `block-build.sh` quá rộng so với repo cụ thể
**Cách xử lý:** Sửa `PATTERN` trong `.claude/hooks/block-build.sh`, hoặc thêm `# user-approved` cho lệnh đó
**Lỗi:** Lệnh bàn giao chạy lỗi "command not found"
**Nguyên nhân:** Thiếu bước `source` môi trường ROS/venv
**Cách xử lý:** Claude phải luôn ghi dòng `Chuẩn bị:` — nếu thiếu, yêu cầu bổ sung
**Lỗi:** Output build quá dài không dán được
**Nguyên nhân:** Build cả workspace
**Cách xử lý:** Dùng `tee /tmp/build.log` rồi bảo Claude đọc file; hoặc thu hẹp bằng `--packages-select`
**Lỗi:** Claude phân tích log cũ
**Nguyên nhân:** File log không bị ghi đè, hoặc người dùng chạy lệnh khác
**Cách xử lý:** Đặt tên log theo lần chạy (`/tmp/build-2.log`), hoặc `rm` log trước khi chạy lại

View File

@@ -0,0 +1,98 @@
---
name: model-conversion-debugging
description: Debug lỗi chuyển đổi AI model giữa các format như ONNX, TensorRT, TFLite, OpenVINO, quantization trong khi bảo toàn input/output contracts. Dùng khi người dùng báo 'ONNX export thất bại', 'TensorRT build lỗi', 'accuracy giảm sau conversion', 'unsupported op', 'shape mismatch', 'quantization error', hoặc 'output drift'.
---
# Model Conversion Debugging
## Mục tiêu
Chẩn đoán conversion failures hoặc accuracy regressions giữa training/source models và deployment formats, không phỏng đoán target runtime details.
## Khi nào dùng
Dùng cho ONNX export, TensorRT engine build, TFLite conversion, OpenVINO IR, quantization, precision changes, unsupported ops, shape mismatches, hoặc output drift.
## Quy trình
### Bước 1: Đọc context
Đọc project và model deployment context nếu có.
### Bước 2: Khám phá artifacts
Discover từ repo: source model, conversion scripts, config files, sample inputs, validation scripts, deployment runtime.
### Bước 3: Xác minh input/output contract
Kiểm tra: input names, shapes, dtypes, color order, normalization, dynamic axes, batch size, output names.
### Bước 4: Kiểm tra compatibility
Opset/runtime compatibility, unsupported operators, plugins/custom ops, calibration data, quantization settings, precision changes.
### Bước 5: Kiểm tra ROS integration
Xác minh converted model assumptions khớp với node's preprocessing và postprocessing.
### Bước 6: So sánh outputs
So sánh source và converted outputs trên representative inputs khi commands và data đã được xác minh.
## Checklist
- [ ] Source và target formats đã xác minh
- [ ] Conversion command đã xác minh trước khi dùng
- [ ] Input/output contracts đã bảo toàn
- [ ] Pre/postprocessing alignment đã kiểm tra
- [ ] Numeric tolerance và representative data đã xem xét
- [ ] Unknowns ghi `Unknown / needs confirmation`
## Ví dụ minh hoạ
**Ví dụ 1: ONNX export thất bại với custom op**
Người dùng nói: "torch.onnx.export() báo lỗi: Unsupported op: Deformable Convolution"
Hành động:
1. Tìm op trong model code, xác minh đây là custom op hay standard op
2. Kiểm tra ONNX opset version (thường cần >= 17 cho deformable conv)
3. Xem có onnx-simplifier hoặc onnxruntime-extensions hỗ trợ không
4. Xem xét fallback: export partial model hoặc fuse op trước khi export
Kết quả: Nguyên nhân cụ thể và 2-3 giải pháp với tradeoffs.
**Ví dụ 2: Accuracy giảm sau INT8 quantization**
Người dùng nói: "mAP giảm từ 0.85 xuống 0.62 sau khi quantize INT8"
Hành động:
1. Kiểm tra calibration dataset có representative không (đủ ảnh diverse?)
2. Xác định layers nhạy cảm với quantization (thường là detection head, softmax)
3. Thử mixed precision: giữ FP16 cho output layers
4. So sánh per-layer activations giữa FP32 và INT8
Kết quả: Xác định layers cần giữ FP16, calibration recommendations.
## Khắc phục sự cố
**Lỗi:** "RuntimeError: Exporting the operator... is not supported"
**Nguyên nhân:** Torch op chưa có ONNX mapping
**Cách xử lý:** Upgrade opset version, dùng symbolic override, hoặc rewrite op bằng primitive ops
**Lỗi:** Output shape mismatch giữa PyTorch và ONNX Runtime
**Nguyên nhân:** Dynamic shape không được export đúng (batch dim, spatial dim)
**Cách xử lý:** Thêm `dynamic_axes` đúng trong export call, verify với `onnxruntime.InferenceSession`
**Lỗi:** TRT engine chạy đúng nhưng output khác PyTorch
**Nguyên nhân:** FP16 precision loss hoặc layer fusion thay đổi computation order
**Cách xử lý:** Disable FP16 cho specific layers, so sánh intermediate activations
## Output Format
- Conversion path: source → intermediate → target format
- Failure/regression symptom: error message hoặc metric drop
- Verified contracts: input/output spec
- Likely causes: ordered by evidence strength
- Validation plan: commands và test inputs
- Next fix: specific change với expected result

View File

@@ -0,0 +1,132 @@
---
name: patch-preview-before-edit
description: Hiển thị diff thay đổi được đề xuất dạng unified diff và chờ xác nhận rõ ràng từ người dùng trước khi sửa đổi bất kỳ file nào trong repository. Dùng trước khi sửa source code, config, launch files, scripts, build files, docs. Kích hoạt khi người dùng muốn 'xem trước thay đổi', 'preview diff', 'show me what will change', hoặc khi làm việc với code nhạy cảm.
---
# Patch Preview Before Edit
## Mục tiêu
Trước khi thay đổi nội dung repository, hiển thị additions và deletions được đề xuất dạng diff, giải thích impact và risks, và chờ xác nhận rõ ràng trước khi apply bất kỳ thay đổi nào.
## Khi nào dùng
Dùng trước khi sửa source code, configuration, launch files, scripts, build files, documentation, generated templates, hoặc bất kỳ file nào trong repository.
## Rules
- **Không** edit, create, delete, rename, overwrite files trước khi user xác nhận
- **Không** chạy commands sửa đổi files, dependencies, caches, lockfiles trước khi xác nhận
- Read-only inspection commands được phép trước khi xác nhận
- Các lệnh formatting, code generation, dependency install, migration, autofix đều là modifying commands
- Preview phải đủ cụ thể để user hiểu change trước khi approve
- Nếu change quá rộng, chia thành patches nhỏ hơn hoặc hỏi clarification
**Từ xác nhận hợp lệ:** `confirm`, `apply`, `ok`, `yes`, `dong y`, `đồng ý`, `tiep tuc`, `tiếp tục`, `sửa đi`
## Quy trình
### Bước 1: Inspect
Dùng read-only commands và file reads để hiểu repository.
### Bước 2: Xác định files sẽ thay đổi
List từng file và lý do cần thay đổi.
### Bước 3: Chuẩn bị preview
Tạo diff preview mà không apply.
### Bước 4: Hiển thị preview theo format
Xem Preview Format bên dưới.
### Bước 5: Giải thích impact và risks
Nêu rõ expected impact, risks, assumptions, unverified details.
### Bước 6: Dừng và chờ
Stop và chờ explicit user confirmation.
### Bước 7: Apply sau khi xác nhận
Apply chỉ những changes đã được approve.
### Bước 8: Tóm tắt sau khi apply
Report changes đã thực hiện và validation results.
## Preview Format
````text
Proposed changes:
- <file path>: <short reason>
- <file path>: <short reason>
Preview:
```diff
diff --git a/<file path> b/<file path>
--- a/<file path>
+++ b/<file path>
@@
-<line to remove or replace>
+<line to add or replace>
```
Impact:
- <expected behavior or documentation change>
Risks:
- <risk, or "No major risk identified">
Assumptions:
- <verified fact or "No project-specific assumptions">
Waiting for confirmation before editing. Confirm with: confirm, apply, ok, yes, đồng ý, tiếp tục, or sửa đi.
````
## Ví dụ minh hoạ
**Ví dụ 1: Sửa launch file parameter**
Người dùng nói: "Đổi camera_fps từ 30 thành 60 trong launch file"
Hành động:
1. Đọc launch file, tìm parameter `camera_fps`
2. Hiển thị diff preview
3. Chờ xác nhận
Kết quả: Chỉ apply sau khi user nói "ok" hoặc "đồng ý".
**Ví dụ 2: Refactor nhiều files**
Người dùng nói: "Rename topic /camera/image thành /camera/image_raw trong toàn bộ codebase"
Hành động:
1. Grep tất cả files có string `/camera/image`
2. Chia thành 3 groups: source code, launch files, config files
3. Hiển thị từng group diff, giải thích risk (runtime mismatch nếu thiếu file nào)
4. Chờ xác nhận cho từng group hoặc tất cả
Kết quả: Có thể apply tuần tự từng group sau khi xác nhận.
## Khắc phục sự cố
**Lỗi:** User xác nhận nhưng thay đổi thực tế khác preview
**Nguyên nhân:** File đã bị thay đổi giữa lúc preview và apply
**Cách xử lý:** Dừng lại, hiển thị updated preview, chờ xác nhận lại
**Lỗi:** Diff quá lớn, user không đọc được
**Nguyên nhân:** Change scope quá rộng
**Cách xử lý:** Chia nhỏ thành từng file riêng biệt, hiển thị tuần tự
## After-Apply Summary
Sau khi apply, report:
- Files đã thay đổi
- Những gì đã add, remove, hoặc update
- Deviations so với approved preview (nếu có)
- Validation checks đã chạy và kết quả
- Checks chưa chạy và lý do

View File

@@ -0,0 +1,92 @@
---
name: project-onboarding
description: Khám phá và lập bản đồ cấu trúc repository robotics/ROS chưa biết, xác định stack, commands, interfaces và tạo PROJECT_CONTEXT.md với facts đã xác minh. Dùng khi người dùng mới bắt đầu với repo, yêu cầu 'onboard repo mới', 'tìm hiểu project này', 'map cấu trúc codebase', 'PROJECT_CONTEXT.md chưa có', hoặc bắt đầu làm việc sau khi clone repo.
---
# Project Onboarding
## Mục tiêu
Xây dựng bản đồ ban đầu đáng tin cậy của một repository robotics mà không giả định package names, topics, frames, hardware, models, hoặc commands.
## Khi nào dùng
Dùng khi bắt đầu làm việc trong một repository robotics, ROS, ROS 2, CV, simulation, embedded, hoặc edge AI mới.
## Quy trình
### Bước 1: Đọc context có sẵn
Đọc `CLAUDE.md` và `PROJECT_CONTEXT.md` nếu có.
### Bước 2: Khám phá top-level structure
List top-level files, detect: manifests, docs, launch/config folders, packages, tests, CI.
### Bước 3: Xác định ROS version
ROS 1 indicators: `package.xml`, `CMakeLists.txt`, `.launch`, `catkin`, `rosbag`, `nodelet`, `dynamic_reconfigure`
ROS 2 indicators: `package.xml`, `setup.py`, `setup.cfg`, `ament`, `colcon`, launch Python, components, lifecycle nodes, QoS config
### Bước 4: Locate CV/AI assets
Camera calibration, model files, conversion scripts, preprocessing code, deployment configs.
### Bước 5: Ghi vào PROJECT_CONTEXT.md
Chỉ ghi verified facts. Để `Unknown / needs confirmation` cho bất kỳ field nào chưa xác minh được.
## Checklist
- [ ] Repository role đã xác định từ docs hoặc manifests
- [ ] Build, test, lint, launch commands đã xác minh trước khi ghi
- [ ] Packages, nodes, topics, services, actions, frames, parameters, models đã discover từ files
- [ ] Hardware và sensor assumptions không được phỏng đoán
- [ ] Open questions đã liệt kê rõ ràng
## Ví dụ minh hoạ
**Ví dụ 1: Onboard repo ROS 2 mới**
Người dùng nói: "Tôi vừa clone repo này, bạn có thể giúp tôi hiểu cấu trúc không?"
Hành động:
1. `ls` top-level, tìm `package.xml`, `colcon.meta`, `setup.py`
2. Detect ROS 2 từ `ament_cmake` trong CMakeLists.txt
3. List tất cả packages, trace main nodes
4. Tìm launch files, extract topic remaps và parameters
5. Tạo/cập nhật PROJECT_CONTEXT.md
Kết quả: PROJECT_CONTEXT.md với stack, packages, main interfaces, build command, open questions.
**Ví dụ 2: Onboard repo CV/AI không có ROS**
Người dùng nói: "Project này có camera và detection, giúp tôi hiểu pipeline"
Hành động:
1. Tìm entry points (main.py, inference.py, pipeline.py)
2. Trace: camera source → preprocessing → model → postprocessing → output
3. Tìm model files (.pt, .onnx, .trt) và config files
4. Ghi vào PROJECT_CONTEXT.md phần CV And AI
Kết quả: CV pipeline map với verified paths, model format, open questions về hardware.
## Khắc phục sự cố
**Lỗi:** Không tìm được build command
**Nguyên nhân:** Project dùng custom build system hoặc Makefile không standard
**Cách xử lý:** Tìm `Makefile`, `justfile`, `taskfile.yml`, CI scripts (`.github/workflows/`), ghi `Unknown / needs confirmation` nếu vẫn không tìm được
**Lỗi:** Quá nhiều packages, không biết bắt đầu từ đâu
**Nguyên nhân:** Monorepo với nhiều components
**Cách xử lý:** Tìm top-level README hoặc workspace launch file, identify "main" package từ dependency graph
## Output Format
- Snapshot: repository purpose và tech stack
- Verified layout: key directories và manifests
- Runtime map: known nodes/interfaces/frames/models
- Commands: verified hoặc `Unknown / needs confirmation`
- Updated files: ghi rõ PROJECT_CONTEXT.md đã được update
- Open questions: danh sách ngắn gọn

View File

@@ -0,0 +1,90 @@
---
name: read-source-code
description: Trace và giải thích hành vi của source code robotics, ROS, CV, edge AI dựa trên bằng chứng từ repository, không phỏng đoán chi tiết project. Dùng khi người dùng yêu cầu 'giải thích code này', 'trace logic của node X', 'tìm bug trong pipeline', 'làm thế nào X hoạt động', hoặc cần hiểu callback flow, executor, topic pub/sub, model inference path.
---
# Read Source Code
## Mục tiêu
Giải thích code hoạt động như thế nào, dependencies là gì, và behavior được configure ở đâu, trong khi giữ unknown project details là explicit.
## Khi nào dùng
Dùng khi cần hiểu một node, package, launch path, perception pipeline, controller, driver wrapper, model runtime, hoặc bug path.
## Quy trình
### Bước 1: Đọc context
Đọc project context files nếu có.
### Bước 2: Bắt đầu từ entry point
Bắt đầu từ file/symbol/log/topic/node/model mà user cung cấp.
### Bước 3: Trace theo hướng phù hợp
Dùng source search để trace: definitions, call sites, launch/config references, parameters, tests.
**ROS 1:** publishers/subscribers, services, actionlib, node handles, private parameters, callbacks, timers, spin model
**ROS 2:** nodes/components, executors, callback groups, lifecycle, QoS, parameters, services/actions, timers, composition
**CV/AI:** image encoding, calibration, preprocessing, inference, postprocessing, synchronization, output contracts
### Bước 4: Ghi nhận unknowns
Mark bất kỳ details nào chưa xác minh được là `Unknown / needs confirmation`.
## Checklist
- [ ] Entry points và runtime configuration đã xác định
- [ ] Message types, units, frames, timestamps, rates đã kiểm tra
- [ ] Threading, callback order, queues/QoS, shared state đã kiểm tra
- [ ] Error handling, timeouts, watchdogs, degraded sensor input đã kiểm tra
- [ ] Unknown details đã mark rõ
## Ví dụ minh hoạ
**Ví dụ 1: Trace tại sao node không publish**
Người dùng nói: "detection_node chạy nhưng /detections topic luôn trống"
Hành động:
1. Tìm node entry point, locate publisher cho `/detections`
2. Trace callback: subscriber nhận gì → xử lý → điều kiện publish
3. Tìm guard conditions: threshold filter, confidence check, state machine
4. Kiểm tra có publisher được tạo đúng không (wrong namespace?)
Kết quả: Xác định chính xác line code gây ra issue, không publish, explain logic.
**Ví dụ 2: Hiểu executor và callback groups**
Người dùng nói: "Tại sao timer callback của tôi bị block bởi subscriber callback?"
Hành động:
1. Tìm executor type: SingleThreadedExecutor hay MultiThreadedExecutor?
2. Kiểm tra callback group assignment: MutuallyExclusive hay Reentrant?
3. Trace timer và subscriber được assign group nào
4. Giải thích scheduling behavior với executor đó
Kết quả: Explanation cụ thể + fix với đúng callback group type.
## Khắc phục sự cố
**Lỗi:** Không tìm được node entry point
**Nguyên nhân:** Node được launch qua `ros2 run` với package/executable khác tên folder
**Cách xử lý:** Tìm trong `CMakeLists.txt` (ament_target_dependencies), `setup.py` (entry_points), hoặc launch file
**Lỗi:** Callback trace dừng lại tại virtual function
**Nguyên nhân:** Polymorphism, plugin architecture (pluginlib, class_loader)
**Cách xử lý:** Tìm plugin manifest (`plugins.xml`), grep registered class name, trace concrete implementation
## Output Format
- What it does: concise behavior summary (1-3 sentences)
- Evidence: file:line references
- Runtime dependencies: topics, params, frames, models, hardware nếu verified
- Risks hoặc ambiguities: practical issues
- Next verification: tests, commands, logs, hoặc questions

View File

@@ -0,0 +1,100 @@
---
name: real-time-performance-profiling
description: Phân tích bottleneck hiệu suất và rủi ro real-time trong pipeline robotics, CV, edge AI bao gồm latency, jitter, CPU/GPU load, callback contention, throughput. Dùng khi người dùng báo 'bỏ lỡ deadline', 'frame rate thấp', 'callback backlog', 'dropped messages', 'CPU/GPU quá tải', 'memory leak', 'startup chậm', hoặc cần optimize throughput.
---
# Real-Time Performance Profiling
## Mục tiêu
Xác định performance bottlenecks và determinism risks trong robotics, CV, edge AI pipelines sử dụng verified repo facts và measured evidence.
## Khi nào dùng
Dùng cho missed deadlines, low frame rate, control latency, callback backlog, dropped messages, high CPU/GPU load, memory growth, startup delays, hoặc thermal throttling.
## Quy trình
### Bước 1: Đọc context
Đọc project context files nếu có.
### Bước 2: Discover runtime structure
Từ repo: entry points, nodes, launch/config, topic rates, timers, callback structure, model runtime, target hardware.
### Bước 3: Xác định critical path
Define critical path và timing budget. Mark unknown budgets là `Unknown / needs confirmation`.
### Bước 4: Kiểm tra ROS-specific issues
**ROS 1:** callback queues, spinner type, queue sizes, nodelets, rosconsole timing, rosbag replay effects
**ROS 2:** executors, callback groups, QoS history depth, intra-process communication, lifecycle state, tracing, composition
### Bước 5: Inspect CV/AI hotspots
Image copies, encoding conversion, resize, synchronization, inference, postprocessing, GPU/accelerator transfer, memory allocation.
### Bước 6: Đề xuất measurement plan
Measurement commands phù hợp với repo hoặc clearly generic examples.
## Checklist
- [ ] Critical path đã xác định
- [ ] Rates, latencies, queue/QoS settings, resource use đã kiểm tra
- [ ] Blocking calls, locks, allocations, copies, thread contention đã xem xét
- [ ] Hardware, OS, accelerator assumptions đã xác minh hoặc mark unknown
- [ ] Measurement commands phù hợp với repo
## Ví dụ minh hoạ
**Ví dụ 1: Detection pipeline chỉ đạt 5 FPS thay vì 30 FPS**
Người dùng nói: "Detection chạy chậm hơn expected 6x, không biết bottleneck ở đâu"
Hành động:
1. Trace critical path: camera callback → preprocess → inference → postprocess → publish
2. Kiểm tra preprocessing: có resize từ 4K xuống 640 trên CPU không?
3. Kiểm tra inference: batch size, dynamic shape overhead
4. Kiểm tra có memory allocation trong hot path không (np.zeros() trong callback)
5. Đề xuất profiling: `ros2 topic hz`, `nvidia-smi dmon`, `perf stat`
Kết quả: Top 3 bottlenecks với estimated contribution và fix recommendations.
**Ví dụ 2: Control loop có jitter, robot behavior không smooth**
Người dùng nói: "Control command publish rate không ổn định, đôi khi skip cycles"
Hành động:
1. Kiểm tra executor type: SingleThreaded sẽ bị block bởi slow callbacks
2. Tìm shared callback group với heavy callbacks (sensor processing)
3. Kiểm tra timer period vs actual execution time
4. Kiểm tra có system-level jitter không (CPU governor, IRQ affinity)
Kết quả: Executor/callback group restructuring plan + OS-level recommendations.
## Khắc phục sự cố
**Lỗi:** Callback queue backup liên tục tăng
**Nguyên nhân:** Publisher rate nhanh hơn subscriber processing rate
**Cách xử lý:** Giảm queue size (drop old messages), tăng processing speed, hoặc giảm publisher rate
**Lỗi:** GPU utilization thấp mặc dù inference chậm
**Nguyên nhân:** CPU preprocessing là bottleneck hoặc CPU-GPU transfer quá nhiều
**Cách xử lý:** Move preprocessing lên GPU (CUDA/OpenCV CUDA), batch nhiều frames
**Lỗi:** Memory tăng dần theo thời gian (leak)
**Nguyên nhân:** Python objects không được free (circular references, cache không giới hạn)
**Cách xử lý:** Dùng `tracemalloc`, giới hạn cache size, kiểm tra callback capture
## Output Format
- Performance symptom
- Critical path map: từng stage với estimated time
- Evidence và unknowns
- Likely bottlenecks: ordered by impact
- Measurement plan: specific commands hoặc tools
- Optimization candidates với tradeoffs

View File

@@ -0,0 +1,90 @@
---
name: repo-context-maintainer
description: Cập nhật và duy trì PROJECT_CONTEXT.md, ROS_TOPIC_MAP.md, TF_FRAME_MAP.md, MODEL_DEPLOYMENT_CONTEXT.md với facts đã được xác minh từ repository. Dùng khi context files bị stale, sau code changes lớn, trước tasks phức tạp, hoặc khi người dùng yêu cầu 'cập nhật context', 'refresh project map', 'update topic map', 'sync PROJECT_CONTEXT'.
---
# Repo Context Maintainer
## Mục tiêu
Giữ project context files chính xác, cập nhật và hữu ích mà không thêm unverified robotics assumptions.
## Khi nào dùng
Dùng sau onboarding, sau major code changes, trước large tasks, hoặc khi context files bị missing, stale, hoặc incomplete.
## Quy trình
### Bước 1: Đọc context files hiện có
Đọc `PROJECT_CONTEXT.md`, `ROS_TOPIC_MAP.md`, `TF_FRAME_MAP.md`, `MODEL_DEPLOYMENT_CONTEXT.md` nếu có.
### Bước 2: Inspect repository
Inspect: manifests, docs, launch/config, source, tests, CI, model assets, deployment files.
### Bước 3: Update chỉ những gì xác minh được
Chỉ update fields có thể verify từ repository evidence hoặc explicit user input.
### Bước 4: Preserve unknowns
Giữ `Unknown / needs confirmation` cho package names, topics, frames, commands, hardware, model paths, build details chưa xác minh.
### Bước 5: Ghi nguồn xác minh
Ghi rõ source files dùng để verify và open questions.
## Checklist
- [ ] Context changes có evidence từ repo
- [ ] Commands đã verify trước khi document
- [ ] Topics, services, actions, frames, models, hardware không được phỏng đoán
- [ ] CV/AI deployment contracts đã document nếu có
- [ ] Stale hoặc contradictory facts đã được flag
## Ví dụ minh hoạ
**Ví dụ 1: Update sau khi thêm camera mới**
Người dùng nói: "Tôi vừa thêm depth camera vào hệ thống, cần cập nhật context"
Hành động:
1. Tìm camera driver node mới trong source/launch
2. Xác minh topics: `/depth/image_raw`, `/depth/camera_info`, `/depth/points`
3. Tìm frame ID trong URDF hoặc launch
4. Update PROJECT_CONTEXT.md phần Sensors và Runtime Interfaces
5. Update ROS_TOPIC_MAP.md với camera topics mới
Kết quả: Updated files với verified entries, chỉ rõ files đã check.
**Ví dụ 2: Sync sau refactor lớn**
Người dùng nói: "Tôi vừa refactor detection module, context files cũ rồi"
Hành động:
1. Compare context hiện tại với code thực tế
2. Tìm topics/nodes đã đổi tên hoặc xóa
3. Tìm topics/nodes mới chưa có trong context
4. Update MODEL_DEPLOYMENT_CONTEXT.md nếu model path/format đổi
5. Flag những changes có thể ảnh hưởng integration
Kết quả: Updated context với diff summary và stale entries đã xóa.
## Khắc phục sự cố
**Lỗi:** Không biết topic có còn active không
**Nguyên nhân:** Code có thể conditional publish hoặc topic được rename
**Cách xử lý:** Grep cả codebase cho topic string, kiểm tra conditional blocks, ghi `Needs runtime verification` trong context
**Lỗi:** Build command trong context không còn chạy được
**Nguyên nhân:** Build system đã thay đổi (catkin → colcon, pip → uv)
**Cách xử lý:** Tìm CI scripts (`.github/workflows/`), Makefile, hoặc README mới nhất để lấy command đúng
## Output Format
- Files đã update
- Facts đã add hoặc correct
- Evidence files đã inspect
- Remaining unknowns
- Suggested next context improvements

View File

@@ -0,0 +1,91 @@
---
name: robotics-code-review
description: Review code robotics, ROS, CV, edge AI để tìm behavioral bugs, integration risks, timing issues, safety concerns và gaps trong verification. Dùng khi người dùng yêu cầu 'review code', 'check PR này', 'kiểm tra launch file', 'review perception changes', 'audit safety', hoặc trước khi merge code ảnh hưởng đến runtime behavior, safety, timing, resource management.
---
# Robotics Code Review
## Mục tiêu
Tìm defects và risks cụ thể trong robotics code, ưu tiên runtime behavior, safety, integration contracts, timing, và missing tests.
## Khi nào dùng
Dùng cho pull requests, diffs, package changes, launch/config updates, perception changes, model deployment changes, drivers, controllers, hoặc performance-sensitive code.
## Quy trình
### Bước 1: Đọc context
Đọc project context files nếu có.
### Bước 2: Review target files
Phân biệt changed behavior từ existing behavior.
### Bước 3: Kiểm tra theo ROS version
**ROS 1:** callback queues, node handles, params, remaps, launch XML, message filters, catkin/package dependencies
**ROS 2:** QoS, executors, callback groups, lifecycle, parameters, composition, launch files, ament dependencies
### Bước 4: Kiểm tra common issues
Timestamps, frame IDs, units, synchronization, calibration, resource lifetime, error handling, diagnostics, degraded input behavior.
### Bước 5: Kiểm tra CV/AI specifics
Tensor contracts, encodings, precision, thresholds, model artifact paths, runtime compatibility.
## Checklist
- [ ] Findings tied to file/line evidence
- [ ] Không phỏng đoán project-specific facts
- [ ] Safety, timing, hardware interaction, recovery paths đã xem xét
- [ ] Tests hoặc runtime verification gaps đã xác định
- [ ] Unknowns mark `Unknown / needs confirmation`
## Ví dụ minh hoạ
**Ví dụ 1: Review perception node mới**
Người dùng nói: "Review PR thêm YOLOv8 detection node này trước khi merge"
Hành động:
1. Kiểm tra callback: subscriber nhận image, có check encoding không?
2. Kiểm tra preprocessing: có tương thích với model training preprocessing không?
3. Kiểm tra postprocessing: NMS threshold, coordinate transform đúng frame chưa?
4. Kiểm tra error handling: model load thất bại xử lý thế nào?
5. Kiểm tra diagnostics: có publish `/diagnostics` khi model không ready không?
Kết quả: Findings ordered by severity, mỗi finding có file:line, issue, impact, fix.
**Ví dụ 2: Review launch/config changes**
Người dùng nói: "Review file launch này, tôi sửa một số parameters"
Hành động:
1. Kiểm tra parameter names: đúng namespace? Có typo?
2. Kiểm tra remaps: topic names khớp với subscribers/publishers không?
3. Kiểm tra node startup order: dependencies đúng thứ tự chưa?
4. Kiểm tra có hardcoded paths/IP addresses không
Kết quả: List issues với severity, deployment risks.
## Khắc phục sự cố
**Lỗi:** Không xác định được severity của finding
**Nguyên nhân:** Thiếu context về robot behavior và safety requirements
**Cách xử lý:** Mark `Unknown / needs confirmation` cho safety impact, hỏi user về use case và safety constraints
**Lỗi:** Code quá phức tạp để trace hết
**Nguyên nhân:** Large codebase, nhiều abstraction layers
**Cách xử lý:** Focus vào changed files trong diff, trace outward từ changed lines, không review toàn bộ codebase
## Output Format
- Findings: ordered by severity (Critical > High > Medium > Low)
- Mỗi finding: `file:line | issue | impact | suggested fix`
- Open questions
- Verification gaps: tests cần viết
- Brief change summary nếu relevant

View File

@@ -0,0 +1,94 @@
---
name: ros-package-analysis
description: Phân tích cấu trúc ROS 1/ROS 2 package, manifests, dependencies, launch files, interfaces và integration points chỉ từ repository evidence. Dùng khi người dùng yêu cầu 'phân tích package', 'kiểm tra dependencies', 'map launch files', 'tìm publishers/subscribers của node X', hoặc gặp vấn đề build, dependency conflict, hoặc package boundary.
---
# ROS Package Analysis
## Mục tiêu
Lập bản đồ cấu trúc, dependencies, runtime interfaces, và integration risks của một ROS package chỉ sử dụng repository evidence.
## Khi nào dùng
Dùng khi inspect một package, dependency issue, launch path, migration risk, build problem, hoặc package boundary.
## Quy trình
### Bước 1: Đọc context
Đọc project context files nếu có.
### Bước 2: Locate package manifests
Tìm package manifests và build files.
### Bước 3: Inspect theo ROS version
**ROS 1:** `package.xml`, `CMakeLists.txt`, launch XML, `cfg`, `msg`, `srv`, `action`, nodelets, catkin conventions
**ROS 2:** `package.xml`, `CMakeLists.txt` hoặc Python packaging, launch files, `msg/srv/action`, ament exports, components, lifecycle, colcon conventions
### Bước 4: Trace entry points
Trace executables → publishers, subscribers, services, actions, parameters, TF, model/config assets.
### Bước 5: Verify dependencies
So sánh declared dependencies với code imports/includes và launch usage.
## Checklist
- [ ] Package role đã verify
- [ ] Build type và dependencies đã kiểm tra
- [ ] Runtime interfaces và parameters đã map
- [ ] Launch/config files đã link với executables
- [ ] Tests và CI coverage đã locate
- [ ] Unknowns mark `Unknown / needs confirmation`
## Ví dụ minh hoạ
**Ví dụ 1: Hiểu package trước khi sửa**
Người dùng nói: "Tôi cần sửa package `detection_ros2`, cho tôi biết structure của nó"
Hành động:
1. Đọc `package.xml`: build_type, dependencies
2. Xem `CMakeLists.txt`: executables và libraries được build
3. List launch files và nodes chúng launch
4. Trace main node: subscriptions, publications, services, parameters
5. Tìm test files
Kết quả: Package map với entry points, interfaces, parameter list, dependencies.
**Ví dụ 2: Debug build failure**
Người dùng nói: "colcon build báo 'package X not found'"
Hành động:
1. Đọc `package.xml` phần `<depend>` và `<exec_depend>`
2. Kiểm tra package X có trong workspace không
3. Kiểm tra `CMakeLists.txt` có `find_package(X REQUIRED)` không
4. Kiểm tra `package.xml` có declare dependency không
5. Xem `colcon.meta` hoặc workspace setup
Kết quả: Missing dependency root cause, fix commands.
## Khắc phục sự cố
**Lỗi:** Node launch nhưng không tìm được parameter
**Nguyên nhân:** Parameter namespace sai hoặc node name remapped
**Cách xử lý:** Trace launch file remaps, kiểm tra `~param` (private) vs `param` (global) namespace, verify `use_sim_time` nếu cần
**Lỗi:** `ament_target_dependencies` báo không tìm thấy package
**Nguyên nhân:** Package không trong `package.xml` hoặc chưa source workspace
**Cách xử lý:** Add vào `package.xml` `<depend>`, rebuild với `--packages-select` để isolate
## Output Format
- Package summary: role, build type, main executables
- Manifest/build findings: declared vs actual
- Runtime interfaces: publishers, subscribers, services, actions, params
- Launch/config map: launch files → nodes → remaps
- Dependency gaps hoặc risks
- Suggested next checks

View File

@@ -0,0 +1,97 @@
---
name: ros-topic-debugging
description: Debug vấn đề ROS 1/ROS 2 topic như thiếu messages, wrong types, rate bất thường, stale timestamps, queue drops, QoS mismatch, encoding errors. Dùng khi người dùng báo 'topic không có data', 'subscriber không nhận messages', 'rate quá thấp', 'QoS incompatible', 'message type mismatch', 'latching không hoạt động', hoặc 'timestamp cũ'.
---
# ROS Topic Debugging
## Mục tiêu
Chẩn đoán topic-related failures như missing messages, wrong types, bad rates, stale timestamps, queue drops, QoS mismatches, hoặc encoding/contract errors.
## Khi nào dùng
Dùng cho publisher/subscriber issues, perception input failures, control command gaps, synchronization problems, bag replay differences, hoặc bridge problems.
## Quy trình
### Bước 1: Đọc context
Đọc `PROJECT_CONTEXT.md` và `ROS_TOPIC_MAP.md` nếu có.
### Bước 2: Discover topics
Tìm topic names và message types từ source, launch, config, docs, hoặc user logs.
### Bước 3: Kiểm tra theo ROS version
**ROS 1:** remaps, namespaces, queue sizes, latching, `message_filters`, transport hints, `rostopic` evidence
**ROS 2:** remaps, namespaces, QoS profiles, durability, reliability, history depth, lifecycle state, `ros2 topic` evidence
### Bước 4: Verify message contract
Message fields, timestamps, frame IDs, units, rates, image encodings.
### Bước 5: Phân biệt evidence
Phân biệt verified runtime evidence từ expected behavior.
## Checklist
- [ ] Publisher và subscriber code paths đã xác định
- [ ] Message type và schema đã verify
- [ ] Topic names, namespaces, remaps đã trace
- [ ] QoS hoặc queue settings đã kiểm tra
- [ ] Time synchronization và frame IDs đã kiểm tra
- [ ] Unknowns mark `Unknown / needs confirmation`
## Ví dụ minh hoạ
**Ví dụ 1: Subscriber không nhận messages**
Người dùng nói: "Node của tôi subscribe `/lidar/points` nhưng callback không bao giờ được gọi"
Hành động:
1. Trace publisher của `/lidar/points` trong codebase
2. Kiểm tra topic name exact match (case, namespace, leading slash)
3. ROS 2: Kiểm tra QoS mismatch (publisher dùng BEST_EFFORT, subscriber dùng RELIABLE?)
4. Kiểm tra lifecycle: publisher node đã trong ACTIVE state chưa?
5. Kiểm tra có remap ẩn trong launch file không
Kết quả: Root cause với specific file:line, fix commands.
**Ví dụ 2: Image topic có rate thấp bất thường**
Người dùng nói: "Camera publish 30fps nhưng `/detections` chỉ ra 5Hz"
Hành động:
1. Kiểm tra subscriber queue size: đang drop messages?
2. Kiểm tra callback processing time: quá lâu so với message interval?
3. Kiểm tra SingleThreadedExecutor: bị block bởi slow callback khác?
4. Kiểm tra image_transport: compressed transport có được decode đúng không?
Kết quả: Bottleneck identification với executor/callback fix hoặc queue adjustment.
## Khắc phục sự cố
**Lỗi:** QoS incompatible warning trong ROS 2
**Nguyên nhân:** Publisher và subscriber có QoS profile không match (Reliability, Durability, History)
**Cách xử lý:** Kiểm tra cả hai phía, set subscriber Reliability = BEST_EFFORT nếu publisher là BEST_EFFORT
**Lỗi:** Topic tồn tại nhưng timestamp luôn cũ (stale)
**Nguyên nhân:** Publisher dùng `ros::Time(0)` hoặc `rclpy.time.Time()` thay vì current time
**Cách xử lý:** Trace timestamp assignment trong publisher code, thay bằng `node.get_clock().now()`
**Lỗi:** `message_filters` ApproximateTimeSynchronizer không trigger
**Nguyên nhân:** Slop quá nhỏ hoặc messages không arrive trong cùng time window
**Cách xử lý:** Tăng slop value, kiểm tra header.stamp của từng topic, verify clock source match
## Output Format
- Symptom: mô tả cụ thể vấn đề
- Verified topic map: publishers, subscribers, types, namespaces
- Likely causes: ordered by evidence strength
- ROS 1/ROS 2 checks applicable
- Commands: chỉ dùng nếu verified hoặc clearly generic
- Next action: cụ thể nhất có thể

View File

@@ -0,0 +1,97 @@
---
name: rosbag-analysis
description: Phân tích ROS 1 bag và ROS 2 bag2 để kiểm tra topics, timing, frame consistency, sensor quality và debug perception/model inputs. Dùng khi người dùng có file .bag hoặc bag2 directory, yêu cầu 'phân tích bag', 'debug từ recording', 'kiểm tra sensor data', 'replay bag', 'xem topic rate', hoặc debug recorded failures.
---
# Rosbag Analysis
## Mục tiêu
Dùng bag data để verify runtime behavior, topic contracts, timing, frame consistency, và perception/model inputs, tránh phỏng đoán về robot.
## Khi nào dùng
Dùng khi debug recorded failures, replay differences, sensor timing, dropped data, perception outputs, model inputs, hoặc control behavior.
## Quy trình
### Bước 1: Đọc context
Đọc project context và topic/frame maps nếu có.
### Bước 2: Xác định bag format
Xác định ROS 1 rosbag hay ROS 2 rosbag2 từ files hoặc user input.
### Bước 3: Inventory bag contents
Topics, message types, start/end time, rates, frame IDs, sizes.
### Bước 4: Kiểm tra format-specific details
**ROS 1:** `rosbag info`, `rostopic hz`, playback clock, latching, connection metadata
**ROS 2:** `ros2 bag info`, storage backend, serialization format, QoS override, simulated time
### Bước 5: Kiểm tra data quality
Synchronization, timestamp monotonicity, dropped frames, image encodings, calibration topics/files, TF coverage, model input/output topics.
## Checklist
- [ ] Bag format và metadata đã xác minh
- [ ] Topic types và rates đã ghi nhận
- [ ] TF availability và timestamp range đã kiểm tra
- [ ] Sensor payload quality và encodings đã kiểm tra
- [ ] Replay assumptions đã document
- [ ] Unknowns mark `Unknown / needs confirmation`
## Ví dụ minh hoạ
**Ví dụ 1: Debug tại sao detection thất bại ở một thời điểm trong bag**
Người dùng nói: "Trong bag này, detection bị miss object từ giây 45-60, cần hiểu tại sao"
Hành động:
1. `ros2 bag info` để xem topics và time range
2. Kiểm tra `/camera/image_raw` rate trong khoảng 45-60s: có drop không?
3. Kiểm tra `/camera/camera_info` có publish parallel không
4. Kiểm tra TF: frame `camera_link` → `base_link` có available không
5. Đề xuất replay với specific time range để observe
Kết quả: Timeline của events, likely cause (camera drop? TF gap?), reproduce steps.
**Ví dụ 2: Validate sensor data quality**
Người dùng nói: "Kiểm tra bag này xem LiDAR và camera có sync không"
Hành động:
1. List camera topics và LiDAR topics với rates
2. So sánh timestamps: camera header.stamp vs LiDAR header.stamp
3. Kiểm tra delta: difference trong 100ms là ok, 500ms+ là vấn đề
4. Kiểm tra TF tree có cover cả LiDAR frame và camera frame không
Kết quả: Sync quality report với max/avg/min delta, TF coverage status.
## Khắc phục sự cố
**Lỗi:** `ros2 bag play` báo lỗi QoS incompatible
**Nguyên nhân:** Bag được record với QoS settings khác node đang subscribe
**Cách xử lý:** Dùng `--qos-profile-overrides-path` hoặc override reliability thành BEST_EFFORT
**Lỗi:** Timestamp không monotonic trong bag
**Nguyên nhân:** Clock jump, simulated time bị reset, hoặc sensor internal clock drift
**Cách xử lý:** Kiểm tra có dùng `/clock` topic không, verify sensor driver timestamp source
**Lỗi:** Bag thiếu TF data ở một thời điểm
**Nguyên nhân:** TF broadcaster bị crash hoặc không record `/tf_static`
**Cách xử lý:** Kiểm tra `/tf_static` có trong bag không, replay với `--clock` flag
## Output Format
- Bag identity và format (ROS 1/2, storage backend)
- Topic summary: names, types, rates, count
- Timing và TF findings
- Sensor/CV/model observations
- Likely causes hoặc risks
- Reproducible next commands hoặc checks

View File

@@ -0,0 +1,98 @@
---
name: technical-document-reader
description: Đọc tài liệu kỹ thuật robotics, ROS, CV, AI, hardware, vendor và trích xuất engineering facts đã xác minh mà không thêm thông tin project chưa biết. Dùng khi người dùng upload datasheet, API docs, paper, calibration note, model card, hardware manual, hoặc yêu cầu 'đọc tài liệu này', 'extract specs từ PDF', 'tóm tắt technical doc', 'tìm thông số kỹ thuật'.
---
# Technical Document Reader
## Mục tiêu
Trích xuất facts có thể hành động, có nguồn gốc rõ ràng từ technical documents và chỉ connect với target project khi repository confirm relationship.
## Khi nào dùng
Dùng cho datasheets, API docs, papers, READMEs, design notes, calibration notes, ROS package docs, model cards, hardware manuals, vendor deployment guides.
## Quy trình
### Bước 1: Xác định document
Document source, version, date, và scope.
### Bước 2: Đọc project context
Đọc `PROJECT_CONTEXT.md` nếu có. Nếu không, mark project context là `Unknown / needs confirmation`.
### Bước 3: Extract facts với citations
Extract facts với citations đến sections, files, hoặc page numbers khi available.
### Bước 4: Phân tách document facts và repo facts
Tách biệt rõ facts từ document với facts từ target repo.
### Bước 5: Kiểm tra theo domain
**ROS 1:** topics, nodelets, parameters, launch XML, catkin, rosbag, dynamic reconfigure
**ROS 2:** nodes, components, lifecycle, parameters, launch Python/XML/YAML, QoS, rosbag2, colcon
**CV/AI:** camera model, calibration, encoding, preprocessing, model runtime, precision, memory
### Bước 6: Flag risks
Unsupported assumptions, missing versions, ambiguous units, timing constraints, calibration requirements, hardware dependencies.
## Checklist
- [ ] Source identity và version đã capture
- [ ] Units, coordinate frames, timestamp expectations, message/schema contracts đã kiểm tra
- [ ] Camera model, calibration, image encoding, preprocessing đã kiểm tra khi relevant
- [ ] Model runtime, precision, accelerator, memory, latency constraints đã kiểm tra khi relevant
- [ ] Unknown target-specific fields là `Unknown / needs confirmation`
## Ví dụ minh hoạ
**Ví dụ 1: Đọc camera datasheet để cấu hình driver**
Người dùng nói: "Đây là datasheet của Intel RealSense D435i, tôi cần biết thông số để configure ROS driver"
Hành động:
1. Extract: resolution options, frame rate, depth range, color/IR specs
2. Extract: interface (USB 3.0), SDK version required
3. Map sang ROS parameters: `color_width`, `color_height`, `color_fps`, `depth_fps`
4. Flag: calibration files cần thiết, `depth_scale` parameter
5. Note: ROS 1 dùng `realsense2_camera`, ROS 2 dùng `realsense2_camera_node`
Kết quả: Parameter list với values và source citations, missing info list.
**Ví dụ 2: Đọc model card để verify deployment**
Người dùng nói: "Model card của YOLOv8n, tôi cần biết preprocessing requirements"
Hành động:
1. Extract input spec: `[1, 3, 640, 640]`, RGB, normalized `[0, 1]`, letterbox resize
2. Extract output spec: `[1, 84, 8400]`, XYXY format, confidence scores
3. Compare với node preprocessing trong repo nếu có
4. Flag: letterbox vs simple resize difference, normalization order (mean/std vs /255)
Kết quả: Verified preprocessing contract, mismatch warnings nếu có.
## Khắc phục sự cố
**Lỗi:** Document dùng đơn vị ambiguous (mm hay m? rad hay deg?)
**Nguyên nhân:** Vendor docs không nhất quán
**Cách xử lý:** Flag ambiguity rõ ràng, không assume, đề xuất user verify với hardware test
**Lỗi:** Document version cũ không match với SDK hiện tại
**Nguyên nhân:** API thay đổi giữa versions
**Cách xử lý:** Note version mismatch, recommend kiểm tra changelog hoặc latest docs
## Output Format
- Document: name/version/source
- Verified facts: concise bullets với source references (section/page)
- Repository matches: facts đã confirm trong target repo
- Unknowns: `Unknown / needs confirmation`
- Risks: integration, safety, timing, compatibility, deployment concerns
- Next checks: specific files, commands, hoặc questions

View File

@@ -0,0 +1,97 @@
---
name: tf-frame-debugging
description: Debug vấn đề TF/TF2 frame trong ROS bao gồm transforms, timestamps, naming, static/dynamic broadcasters và frame conventions. Dùng khi người dùng báo 'missing transform', 'extrapolation error', 'TF tree broken', 'sensor không align', 'navigation thất bại do frame', 'URDF frame không đúng', hoặc 'visualization lệch'.
---
# TF Frame Debugging
## Mục tiêu
Tìm TF tree, transform timing, frame naming, và coordinate convention issues mà không phỏng đoán robot frames.
## Khi nào dùng
Dùng cho missing transforms, extrapolation errors, incorrect visualization, sensor alignment, navigation failures, perception frame mismatches, hoặc calibration suspicion.
## Quy trình
### Bước 1: Đọc context
Đọc `PROJECT_CONTEXT.md` và `TF_FRAME_MAP.md` nếu có.
### Bước 2: Discover frames
Tìm frame IDs từ source, URDF/Xacro, launch, config, bags, logs, message headers.
### Bước 3: Kiểm tra theo ROS version
**ROS 1:** `tf`/`tf2_ros`, static transform publishers, URDF robot state publisher, launch XML
**ROS 2:** `tf2_ros`, static transform publishers, robot state publisher, lifecycle/composition, launch Python/YAML
### Bước 4: Verify transforms
Parent-child direction, timestamp source, broadcast rate, static vs dynamic intent, optical frame conventions, map/odom/base relationships.
### Bước 5: Mark unknowns
Absent hoặc ambiguous frames là `Unknown / needs confirmation`.
## Checklist
- [ ] Frame names đã verify từ repo hoặc runtime evidence
- [ ] Static và dynamic transforms đã tách biệt
- [ ] Timestamp và clock source đã kiểm tra
- [ ] Camera optical frame và REP-103/REP-105 conventions đã xem xét
- [ ] Calibration files và URDF/Xacro consistency đã kiểm tra
- [ ] Unknowns đã mark rõ
## Ví dụ minh hoạ
**Ví dụ 1: "Cannot transform from camera_frame to base_link"**
Người dùng nói: "Tôi bị lỗi: 'Could not transform camera_link to base_link at time X'"
Hành động:
1. Tìm `camera_link` broadcaster: static transform publisher hay robot state publisher?
2. Kiểm tra URDF: `camera_link` có được define không? Parent frame là gì?
3. Kiểm tra timestamp: broadcaster có dùng đúng clock không (sim time vs real time)?
4. Kiểm tra tree connectivity: `base_link` → ... → `camera_link` có path không?
5. Đề xuất debug: `ros2 run tf2_tools view_frames` hoặc `tf2_echo`
Kết quả: Missing link trong TF tree, specific broadcaster file/line cần fix.
**Ví dụ 2: Camera point cloud lệch so với LiDAR**
Người dùng nói: "Khi overlay camera và LiDAR trong RViz, chúng bị lệch ~10cm"
Hành động:
1. Kiểm tra `camera_optical_frame` vs `camera_link` - có missing REP-103 rotation không?
2. Kiểm tra extrinsic calibration: giá trị trong URDF có đúng không?
3. Kiểm tra timestamp của camera và LiDAR có sync không
4. Kiểm tra có `base_link` → `camera_link` → `camera_optical_frame` chain đúng không
Kết quả: Identify xem là calibration error, frame convention error, hay timestamp issue.
## Khắc phục sự cố
**Lỗi:** "ExtrapolationException: Lookup would require extrapolation into the future"
**Nguyên nhân:** TF lookup time mới hơn latest available transform (clock skew hoặc lookup too early)
**Cách xử lý:** Dùng `rclpy.time.Time()` (latest) thay vì specific timestamp, hoặc tăng timeout trong `lookup_transform`
**Lỗi:** Static transform bị override liên tục
**Nguyên nhân:** Hai nodes publish cùng static transform với values khác nhau
**Cách xử lý:** Grep tất cả nodes publish transform đó, xác định node nào "win", tắt node redundant
**Lỗi:** TF tree bị broken sau khi node restart
**Nguyên nhân:** Dynamic transform broadcaster restart, TF buffer chưa populated lại
**Cách xử lý:** Thêm delay hoặc wait-for-transform trước lookup, publish `/tf_static` cho static transforms
## Output Format
- Symptom: error message cụ thể
- Verified frame facts: broadcasters, rates, parent-child
- Suspected issue và evidence
- ROS 1 hoặc ROS 2 verification steps
- Risk to perception/navigation/control
- Next action: commands hoặc code changes cụ thể