Skip to content
Back to search

ros2-engineering-skills

ROS 2 engineering plugins maintained by dbwls99706

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/dbwls99706--ros2-engineering-skills/badge.svg)](/listings/dbwls99706--ros2-engineering-skills)

HTML

<a href="/listings/dbwls99706--ros2-engineering-skills"><img src="/api/listings/dbwls99706--ros2-engineering-skills/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Claude Code plugin

claude plugin marketplace add dbwls99706/ros2-engineering-skills
claude plugin install ros2-engineering@ros2-engineering-skills

Inside Claude Code the equivalent commands are:

/plugin marketplace add dbwls99706/ros2-engineering-skills
/plugin install ros2-engineering@ros2-engineering-skills

The plugin uses `.claude-plugin/plugin.json`, root `SKILL.md`, and `hooks/hooks.json`. It provides PreToolUse checks and advisory Stop reports. The hook command requires `python3`; it does not grant tool permissions.

The PreToolUse hook also reports `ros2` commands that can move hardware, such as `ros2 topic pub /cmd_vel ...`, a navigation goal, a controller switch, or an e-stop reset. By default this is a note to the model and nothing is blocked. Set `ROS2_SKILL_ACTUATION=ask` to have Claude Code ask you before such a command runs (experimental; see [client compatibility](docs/CLIENT_COMPATIBILITY.md#actuation-commands)), or `off` to disable it. It matches names in POSIX shell commands and is not a safety function: keep an operator and an independent stop path.

Knowledge-only skill: Codex, Claude Code, Cursor, Gemini CLI

git clone https://github.com/dbwls99706/ros2-engineering-skills.git
cd ros2-engineering-skills
python3 -m pip install -r requirements.txt

python3 scripts/install_skill.py --client codex --dry-run
python3 scripts/install_skill.py --client codex
# Alternatives: --client claude, --client cursor, --client gemini
# Add --project /path/to/project for project scope.

Use a virtual environment as required by your Python installation. The installer copies a validated bundle, not client settings. Existing skills need `--force`; it stages the replacement before touching the old installation. It excludes Claude plugin manifests and hook registration intentionally. The portable files and manual validators do not require the Claude plugin.

Every installation records `INSTALL_PROVENANCE.json`: the source version and Git commit, the installer version, and a SHA-256 digest of each installed file. `python3 scripts/install_skill.py --verify --client codex` reports whether the installation still matches that manifest (exit 0 only when clean). `--force` refuses to replace an installation that differs from its manifest or has none; add `--force --discard-local-changes` to replace it anyway. The manifest is an installation snapshot for detecting accidental or local drift, not a signed attestation: it cannot prove the absence of deliberate tampering, because the manifest and the files can be edited together. The installer never searches for custom installation locations; name them with `--target`.

Codex's optional display and invocation policy live in `agents/openai.yaml`. Supported discovery paths, explicit invocation, remote-environment caveats, and what has actually been tested are documented in [Client compatibility](docs/CLIENT_COMPATIBILITY.md). A documented discovery path is not proof of a successful authenticated model run on every client version.

The original `./install.sh` and `.\install.ps1` still support full-checkout copy/link installation, force replacement, and dry-run. They write no provenance manifest, and they refuse to replace a target that is a symbolic link or reparse point, so a link shared by several clients is never split into a separate copy; pass the resolved path instead. A full checkout includes the Claude plugin manifest; it is not necessarily a knowledge-only installation when placed in Claude's skill directories. Prefer the new installer for that use.

Verify installation and run tools

python3 scripts/validate_skill.py --check-sources
python3 scripts/validate_skill.py --root /path/to/ros2-engineering-skills --installed --portable
python3 scripts/install_skill.py --verify --client codex
python3 scripts/skill_validate_hook.py --file src/my_node.py
python3 scripts/skill_validate_hook.py --command 'ros2 topic list'

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 30 lines
  1. {
  2. "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
  3. "name": "ros2-engineering-skills",
  4. "description": "ROS 2 engineering plugins maintained by dbwls99706",
  5. "owner": {
  6. "name": "YuJin Hong",
  7. "email": "yujinhong3@gmail.com"
  8. },
  9. "plugins": [
  10. {
  11. "name": "ros2-engineering",
  12. "version": "1.8.1",
  13. "description": "Production-grade ROS 2 engineering guidance and validation tools",
  14. "author": {
  15. "name": "YuJin Hong",
  16. "email": "yujinhong3@gmail.com"
  17. },
  18. "source": "./",
  19. "category": "development",
  20. "homepage": "https://github.com/dbwls99706/ros2-engineering-skills#readme",
  21. "keywords": [
  22. "ros2",
  23. "robotics",
  24. "agent-skills",
  25. "nav2",
  26. "ros2-control"
  27. ]
  28. }
  29. ]
  30. }
README.md · README · 344 lines
  1. # ros2-engineering-skills
  2. ![ros2-engineering-skills cover](docs/assets/cover.svg)
  3. Source version: **1.8.1**. See [release notes](CHANGELOG.md#181---2026-11-12) and
  4. [release procedure](docs/RELEASING.md).
  5. [![Test](https://github.com/dbwls99706/ros2-engineering-skills/actions/workflows/test.yml/badge.svg)](https://github.com/dbwls99706/ros2-engineering-skills/actions/workflows/test.yml)
  6. [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
  7. [![GitHub stars](https://img.shields.io/github/stars/dbwls99706/ros2-engineering-skills?style=social)](https://github.com/dbwls99706/ros2-engineering-skills/stargazers)
  8. Production-oriented ROS 2 engineering guidance for coding agents, with focused
  9. references, static validators, regression tests, and multi-distribution CI.
  10. The skill covers workspace and package design, executors, DDS QoS, lifecycle,
  11. tf2, ros2_control, Nav2, MoveIt 2, perception, safety, runtime provenance, testing,
  12. and deployment. It distinguishes a plausible explanation from observed behavior.
  13. ## Why this exists
  14. A syntactically correct ROS 2 answer can still be operationally wrong: changing
  15. subscriber QoS without inspecting the publisher, editing an unused source YAML,
  16. assuming a zero topic command stopped the hardware, or using another distro's API.
  17. This skill routes work to relevant references and requires evidence for claims.
  18. It is not a robot safety certification or a substitute for an operator.
  19. ## Before / After
  20. These are illustrative comparisons of the intended workflow, not measured model
  21. outputs. Real paired evaluations require the captures described below.
  22. > **Prompt:** *"My ROS 2 subscriber isn't receiving any sensor messages. Help me fix it."*
  23. <table>
  24. <tr>
  25. <th width="50%">Without this skill</th>
  26. <th width="50%">With this skill loaded</th>
  27. </tr>
  28. <tr>
  29. <td>
  30. ```python
  31. # Guess at the fix before inspecting the live endpoints.
  32. from rclpy.qos import qos_profile_sensor_data
  33. sub = node.create_subscription(
  34. Image, '/camera/image_raw',
  35. callback, qos_profile_sensor_data)
  36. ```
  37. Assumes the publisher exists, the type is correct, and QoS is the mismatch.
  38. </td>
  39. <td>
  40. ```bash
  41. ros2 topic list
  42. ros2 topic type /camera/image_raw
  43. ros2 topic info /camera/image_raw -v
  44. ros2 node list --no-daemon
  45. ```
  46. ```python
  47. # Only after endpoint inspection supports this diagnosis.
  48. from rclpy.qos import qos_profile_sensor_data
  49. sub = node.create_subscription(
  50. Image, '/camera/image_raw',
  51. callback, qos_profile_sensor_data)
  52. ```
  53. Checks graph, type, namespace, and offered/requested QoS before changing code.
  54. </td>
  55. </tr>
  56. </table>
  57. > **Prompt:** *"Create a C++ driver package for my LiDAR sensor."*
  58. <table>
  59. <tr>
  60. <th width="50%">Without this skill</th>
  61. <th width="50%">With this skill loaded</th>
  62. </tr>
  63. <tr>
  64. <td>
  65. ```text
  66. my_lidar_driver/
  67. ├── src/main.cpp
  68. ├── CMakeLists.txt
  69. └── package.xml
  70. ```
  71. A bare node without explicit configuration, test, resource, or shutdown contracts.
  72. </td>
  73. <td>
  74. ```text
  75. my_lidar_driver/
  76. ├── include/my_lidar_driver/my_lidar_driver_node.hpp
  77. ├── src/my_lidar_driver_node.cpp
  78. ├── src/main.cpp
  79. ├── launch/bringup.launch.py
  80. ├── config/params.yaml
  81. ├── test/test_driver.cpp
  82. ├── test/test_bringup.py
  83. ├── CMakeLists.txt
  84. └── package.xml
  85. ```
  86. Chooses Node or LifecycleNode from resource ownership and supervision; declares
  87. QoS, frames, timestamps, limits, dependencies, and distro-compatible tests.
  88. </td>
  89. </tr>
  90. </table>
  91. ## Installation
  92. ### Claude Code plugin
  93. ```bash
  94. claude plugin marketplace add dbwls99706/ros2-engineering-skills
  95. claude plugin install ros2-engineering@ros2-engineering-skills
  96. ```
  97. Inside Claude Code the equivalent commands are:
  98. ```text
  99. /plugin marketplace add dbwls99706/ros2-engineering-skills
  100. /plugin install ros2-engineering@ros2-engineering-skills
  101. ```
  102. The plugin uses `.claude-plugin/plugin.json`, root `SKILL.md`, and
  103. `hooks/hooks.json`. It provides PreToolUse checks and advisory Stop reports.
  104. The hook command requires `python3`; it does not grant tool permissions.
  105. The PreToolUse hook also reports `ros2` commands that can move hardware, such as
  106. `ros2 topic pub /cmd_vel ...`, a navigation goal, a controller switch, or an
  107. e-stop reset. By default this is a note to the model and nothing is blocked. Set
  108. `ROS2_SKILL_ACTUATION=ask` to have Claude Code ask you before such a command
  109. runs (experimental; see [client compatibility](docs/CLIENT_COMPATIBILITY.md#actuation-commands)),
  110. or `off` to disable it. It matches names in POSIX shell commands and is not a
  111. safety function: keep an operator and an independent stop path.
  112. ### Knowledge-only skill: Codex, Claude Code, Cursor, Gemini CLI
  113. ```bash
  114. git clone https://github.com/dbwls99706/ros2-engineering-skills.git
  115. cd ros2-engineering-skills
  116. python3 -m pip install -r requirements.txt
  117. python3 scripts/install_skill.py --client codex --dry-run
  118. python3 scripts/install_skill.py --client codex
  119. # Alternatives: --client claude, --client cursor, --client gemini
  120. # Add --project /path/to/project for project scope.
  121. ```
  122. Use a virtual environment as required by your Python installation. The installer
  123. copies a validated bundle, not client settings. Existing skills need `--force`;
  124. it stages the replacement before touching the old installation. It excludes
  125. Claude plugin manifests and hook registration intentionally. The portable files
  126. and manual validators do not require the Claude plugin.
  127. Every installation records `INSTALL_PROVENANCE.json`: the source version and
  128. Git commit, the installer version, and a SHA-256 digest of each installed file.
  129. `python3 scripts/install_skill.py --verify --client codex` reports whether the
  130. installation still matches that manifest (exit 0 only when clean). `--force`
  131. refuses to replace an installation that differs from its manifest or has none;
  132. add `--force --discard-local-changes` to replace it anyway. The manifest is an
  133. installation snapshot for detecting accidental or local drift, not a signed
  134. attestation: it cannot prove the absence of deliberate tampering, because the
  135. manifest and the files can be edited together. The installer never searches for
  136. custom installation locations; name them with `--target`.
  137. Codex's optional display and invocation policy live in `agents/openai.yaml`.
  138. Supported discovery paths, explicit invocation, remote-environment caveats, and
  139. what has actually been tested are documented in
  140. [Client compatibility](docs/CLIENT_COMPATIBILITY.md). A documented discovery path
  141. is not proof of a successful authenticated model run on every client version.
  142. The original `./install.sh` and `.\install.ps1` still support full-checkout
  143. copy/link installation, force replacement, and dry-run. They write no provenance
  144. manifest, and they refuse to replace a target that is a symbolic link or reparse
  145. point, so a link shared by several clients is never split into a separate copy;
  146. pass the resolved path instead. A full checkout includes the Claude plugin
  147. manifest; it is not necessarily a knowledge-only installation when placed in
  148. Claude's skill directories. Prefer the new installer for that use.
  149. ### Verify installation and run tools
  150. ```bash
  151. python3 scripts/validate_skill.py --check-sources
  152. python3 scripts/validate_skill.py --root /path/to/ros2-engineering-skills --installed --portable
  153. python3 scripts/install_skill.py --verify --client codex
  154. python3 scripts/skill_validate_hook.py --file src/my_node.py
  155. python3 scripts/skill_validate_hook.py --command 'ros2 topic list'
  156. python3 scripts/skill_validate_hook.py --command 'ros2 topic pub /cmd_vel geometry_msgs/msg/Twist "{}"'
  157. SKILL_WORKSPACE=/path/to/ros2_ws python3 scripts/skill_stop_hook.py
  158. ```
  159. The command string above is inspected, never executed. Python 3.10+ is required;
  160. the CI matrix targets 3.10 through 3.14. Consult the run for the exact revision's
  161. results. Runtime dependencies are in `requirements.txt`; development dependencies
  162. are separate. Build and runtime checks additionally require the target ROS stack.
  163. ## Where the guidance lives
  164. | Path | Role |
  165. |---|---|
  166. | `SKILL.md`, `references/`, `docs/` | The guidance itself: router, task references, contracts |
  167. | `scripts/` | User-facing static checkers and helpers (table below) |
  168. | `.claude-plugin/`, `hooks/`, `agents/`, `install.sh`, `install.ps1` | Client and installation integration |
  169. | `tests/`, `evals/`, `.github/` | Development and verification of this repository |
  170. ## What is included
  171. The selected `SKILL.md` contains a short operating contract and task router.
  172. Detailed tables and the 22 recurring pitfalls are retained in
  173. [`references/engineering-principles.md`](references/engineering-principles.md),
  174. loaded only when relevant. The [context budget](docs/CONTEXT_BUDGET.md) separates
  175. byte/line limits from measured, named-tokenizer counts.
  176. The decision router in [SKILL.md](SKILL.md) selects among 27 task-specific
  177. references plus cross-cutting engineering principles.
  178. Metadata is advertised before activation; the selected body and needed references
  179. supply the workflow. See [Skill contract](docs/SKILL_CONTRACT.md) for scope,
  180. permission boundaries, protocol behavior, and context-budget limitations.
  181. | Utility | Purpose | Boundary |
  182. |---|---|---|
  183. | `create_package.py` | Generate package scaffolds | Build in the target distribution |
  184. | `qos_checker.py` | Compare offered/requested QoS | Compatibility is not delivery quality |
  185. | `qos_audit.py` | Pair QoS declarations across a package by topic and type | Static; unresolved values are never guessed, and a Python profile modified after construction is not judged from its constructor |
  186. | `rosbag2_qos_checker.py` | Inspect bag metadata QoS | Static metadata analysis |
  187. | `launch_validator.py` | Detect selected Python launch defects | Does not start a graph |
  188. | `launch_supervisor.py` | Run an authorized launch with owned SIGINT handling | POSIX; starts processes, not a hardware stop |
  189. | `skill_validate_hook.py` | Inspect source and command strings, including `ros2` commands that can move hardware | Best-effort guard, not a security or safety boundary; automatic source advice only with confirmed ROS context |
  190. | `skill_stop_hook.py` | Check changed launch/package/Nav2 files | Advisory, not a complete build; automatic runs skip launch-named files without ROS context |
  191. | `claude_hook.py` | Adapt reports to Claude hook transport | Never grants permissions or blocks Stop; may ask for confirmation when `ROS2_SKILL_ACTUATION=ask` |
  192. | `validate_skill.py` | Validate metadata, local paths, packaging, source dates | Static checks, not client activation |
  193. | `install_skill.py` | Stage and validate knowledge-only installations | No settings changes or hook registration |
  194. | `eval_runner.py` | Check fixtures or lexically score supplied text | Does not invoke a model or prove semantics |
  195. | `verify_eval_capture.py` | Require complete paired captures with hashes | Integrity, not authenticity or quality |
  196. | `benchmark_capture.py` | Fill the paired manifest, fix run order, build blinded grading sheets, score pairs | Orchestration only; runs no model and grades nothing |
  197. | `measure_context.py` | Count the selected body with named tokenizers | Excludes client wrappers and on-demand references |
  198. The JSON `version` emitted by the two validation hooks is the hook-report contract
  199. version, not the source bundle version. It changes only when that report contract
  200. changes; standalone utility versions follow the same independent-interface rule.
  201. ## Verification levels
  202. The [canonical L0–L6 ladder](references/testing.md#11-verification-levels)
  203. defines evidence and preconditions from static review through supervised field
  204. operation. A passing software suite does not establish that a robot is safe to
  205. drive.
  206. ## CI scope
  207. CI retains lint/type checks, the full unit suite, Markdown lint, generated-package
  208. builds, installer tests, Claude plugin structure/component discovery, and Docker
  209. jobs for Humble, Jazzy, Kilted, Lyrical, and Rolling. It adds individual validator
  210. coverage floors, portable Windows installation, protocol integration, source-date
  211. checks, preregistered-suite checks, and a controlled QoS mismatch/repair experiment.
  212. Dependency vulnerability auditing is blocking, not advisory. The `Required test
  213. gates` summary rejects any required job that did not succeed. A separate `Release
  214. gate` workflow runs on every push to `main`: it fails on an overdue source review,
  215. which the pull-request job only reports.
  216. ROS image construction and test execution are separate. Every run executes the
  217. suite in a fresh, network-isolated container; a cached image is not a test pass.
  218. Build/runtime logs, container state, and installed package versions are retained
  219. as workflow artifacts. The local command uses the same runner:
  220. ```bash
  221. bash tests/run_ros2_tests.sh humble
  222. ```
  223. See [ROS CI and failure diagnosis](docs/ROS_CI.md).
  224. Rolling retains its documented RMW runtime exclusions. A successful Rolling build
  225. is not a successful DDS runtime test. The stable-distribution QoS experiment runs
  226. without external networking or hardware in the built container. See
  227. [QoS case study](docs/QOS_CASE_STUDY.md) and [quality gates](docs/QUALITY_GATES.md).
  228. None of these jobs proves actuator safety, timing guarantees, or field behavior.
  229. ### Independent local ROS acceptance
  230. See [local runtime validation](docs/LOCAL_RUNTIME.md) for the transferable Humble
  231. environment and the independently executed package, lifecycle, component, QoS,
  232. callback-group, and parameter-provenance tasks. These are real software-runtime
  233. checks, not a claim of measured cross-model improvement or hardware safety.
  234. ## Evaluation scope
  235. Capture schema 2 retains timeouts, failed runs, empty answers, and missed skill
  236. activation instead of discarding unfavorable attempts. Capture integrity is not
  237. answer correctness; see [the capture contract](docs/EVIDENCE_CAPTURE.md).
  238. The default `eval_runner.py` checks whether expected-answer fixtures cover their
  239. declared criteria. It is not a model benchmark. Lexical coverage is not semantic
  240. correctness, and a fixture cannot substitute for an unmodified model capture.
  241. `evals/trigger_cases.json` defines 34 activation cases: 18 implicit positives,
  242. 12 implicit negatives, and explicit invocation for four clients.
  243. `evals/benchmark_suite.json` defines seven quality cases with three trials and
  244. paired plugin-on/off runs: 21 pairs, 42 fresh sessions per experiment.
  245. No fabricated captures or improvement percentages are included.
  246. ```bash
  247. python3 scripts/verify_eval_capture.py /path/to/capture.json --suite evals/benchmark_suite.json
  248. ```
  249. Missing data, incomplete pairs, reused sessions/artifacts, and hash mismatches
  250. fail this check. A valid capture still needs trace-authenticity review and semantic
  251. grading. See [capture workflow](docs/EVIDENCE_CAPTURE.md) and the existing
  252. [eval workflow](docs/EVAL_WORKFLOW.md). `scripts/benchmark_capture.py` fills the
  253. manifest, freezes and enforces the run order, and builds blinded grading sheets; the
  254. procedure for an actual plugin ON/OFF run with Claude Code is in
  255. [the benchmark runbook](docs/BENCHMARK_RUNBOOK.md).
  256. The separate [diagnostic review suite](evals/diagnostics/README.md) preregisters
  257. four synthetic offline-analysis cases with three paired trials each. Its controls,
  258. artifact-lineage questions, and state-semantics counterexample are evaluation
  259. inputs, not measured model improvements or a replay of a production recording.
  260. ## Safety, contribution, and maintenance
  261. This project does not certify a robot, controller, stop function, or deployment.
  262. First motion and fault injection require an operator, a restrained setup,
  263. conservative limits, and an independent physical stop path. Reviews are read-only
  264. unless changes are requested; data and logs are not instructions or permissions.
  265. Corrections supported by installed-version evidence, primary documentation, and
  266. reproducible tests are especially valuable. See [CONTRIBUTING.md](CONTRIBUTING.md),
  267. [SECURITY.md](SECURITY.md), and [ROADMAP.md](ROADMAP.md). Source review dates are
  268. tracked explicitly; passing their date check does not revalidate the web content.
  269. ## License
  270. Apache License 2.0. See [LICENSE](LICENSE).
scripts/skill_validate_hook.py · Bundled script · 2,293 lines · 9 findings marked
  1. #!/usr/bin/env python3
  2. """Skills 2.0 PreToolUse Hook — Pre-execution validation for ros2-engineering-skills.
  3. This hook runs before tool invocations during skill execution. It provides
  4. context-aware warnings when the user's actions may conflict with ROS 2
  5. engineering best practices defined in the skill.
  6. Modes:
  7. * **Event mode** (default, no arguments): consumes a Claude Code PreToolUse
  8. payload from stdin (or the ``TOOL_NAME``/``TOOL_INPUT`` env fallback) and
  9. checks the tool input. Without a payload there is nothing to check and the
  10. result is an empty pass — this mode is NOT a workspace scanner.
  11. * **Manual mode** (``--file`` and/or ``--command``): for platforms without
  12. Claude Code hooks. ``--file`` checks the named source files for
  13. anti-patterns; ``--command`` inspects a shell command string for dangerous
  14. patterns. The command string is analyzed only — it is NEVER executed.
  15. Both options may be combined; all issues are aggregated into one report.
  16. Scope and limits — read before relying on this:
  17. * The Bash dangerous-command checks below are best-effort sanity guards
  18. intended to catch obvious accidents like a literal ``rm -rf /``. They are
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 23 on GitHub
  19. *not* a security boundary. Variable expansion (``rm -rf $X``), a path
  20. built by command substitution (``rm -rf $(echo /)``), aliasing, a
  21. ``git -c alias.x='!...'`` shell alias, and a script that is run later all
  22. get past them. Treat any code path that depends on these checks for
  23. safety as broken.
  24. * For a POSIX shell command the patterns are refined by reading the command
  25. structure. Literal arguments of ``grep``, ``rg``, ``echo`` and ``printf``
  26. that stay on the terminal or go through plain filters are data, so
  27. ``grep 'rm -rf /' notes.md`` is not refused. A command that would run is
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 32 on GitHub
  28. refused wherever it sits: inside ``bash -c '...'``, ``ssh host '...'``,
  29. ``$(...)``, a subshell, after ``sudo`` or ``xargs``, or as the text a
  30. literal ``echo`` pipes into a shell or writes to a file. When the command
  31. cannot be read completely the pattern verdict stands unchanged.
  32. * ROS 2 commands that can move hardware or change a motion gate
  33. (``ros2 topic pub /cmd_vel``, a navigation goal, a controller switch, an
  34. e-stop reset, a velocity limit) are reported as warnings with
  35. ``category: actuation``. They never block and are not a safety function:
  36. the check matches names, reads POSIX shell syntax only, and ignores any
  37. command that does not contain the literal text ``ros2``. Syntax it cannot
  38. interpret is listed in ``checks_skipped`` rather than treated as clean.
  39. ``ROS2_SKILL_ACTUATION=off`` disables it; ``ask`` is handled by the Claude
  40. adapter (``claude_hook.py``), not here.
  41. * In event mode the anti-pattern checks run only for a file with confirmed
  42. ROS context (see ``_has_ros_context``); manual ``--file`` checks whatever
  43. it is given.
  44. * The anti-pattern checks scan source for common ROS 2 mistakes. They skip
  45. single-line comments (``#`` in Python, ``//`` in C/C++, both for unknown
  46. extensions) but do *not* skip Python triple-quoted strings, so a
  47. docstring mentioning ``time.sleep()`` will produce a warning.
  48. This is intentional: the hook errs on the side of false positives over
  49. false negatives.
  50. Exit codes differ by mode, because the two modes answer to different
  51. contracts:
  52. * **Event mode** speaks Claude Code's hook protocol. Only exit code **2**
  53. blocks a tool call — the docs are explicit that "Claude Code treats exit
  54. code 1 as a non-blocking error and proceeds with the action". On exit 2
  55. the reason is written to **stderr**, which is the channel Claude Code
  56. reads, and nothing is written to stdout: this module's JSON report is
  57. its own shape rather than the documented hook-output schema, and pairing
  58. unrecognized JSON with a blocking exit is the combination that can be
  59. downgraded to non-blocking.
  60. 0 — No blocking issues found (JSON report on stdout)
  61. 2 — Blocking issue detected; the tool call is refused (reason on stderr)
  62. * **Manual mode** is an ordinary CLI, where a non-zero exit means "issues
  63. found" in the usual Unix sense.
  64. 0 — No blocking issues found
  65. 1 — Blocking issue detected
  66. """
  67. import argparse
  68. import json
  69. import os
  70. import re
  71. import sys
  72. import xml.etree.ElementTree as ET
  73. # Patterns that indicate potential ROS 2 anti-patterns in code being written.
  74. #
  75. # Optional fields per entry:
  76. # pattern_flags - extra `re` flags (e.g. re.MULTILINE). Default 0.
  77. # file_filter - callable(filename) -> bool; if present, regex only runs
  78. # when the filter returns True. Default: applies to all
  79. # checkable files. Use to scope launch-only or
  80. # ROS-specific patterns to where they are real signals.
  81. # distro_filter - callable(ros_distro) -> bool, where ros_distro is the
  82. # lower-cased ROS_DISTRO of the environment ('' when
  83. # unset); if present, regex only runs when the filter
  84. # returns True. Use for advice that is wrong on older
  85. # distributions.
  86. #
  87. # `message` is a string, or a callable(ros_distro) -> str for advice whose
  88. # wording depends on whether the distribution is known.
  89. # ROS_AUTOMATIC_DISCOVERY_RANGE arrived in Iron, which also deprecated
  90. # ROS_LOCALHOST_ONLY. On these earlier distributions the deprecated variable is
  91. # the only way to confine discovery, so recommending its replacement there
  92. # would make a follower open the robot's DDS traffic to the network.
  93. _DISTROS_WITHOUT_DISCOVERY_RANGE = frozenset(('foxy', 'galactic', 'humble'))
  94. def _ros_distro():
  95. return os.environ.get('ROS_DISTRO', '').strip().lower()
  96. ANTIPATTERN_CHECKS = [
  97. {
  98. 'pattern': r'time\.sleep\s*\(',
  99. 'message': ('time.sleep() inside a callback blocks its executor thread; '
  100. 'prefer a node timer there. A sleep outside callbacks, such as '
  101. 'in main() or a test, is not inherently an anti-pattern'),
  102. 'severity': 'warning',
  103. },
  104. {
  105. 'pattern': r'spin_until_future_complete\s*\(',
  106. 'message': ('Calling spin_until_future_complete() inside a callback can '
  107. 'deadlock depending on executor and callback-group '
  108. 'configuration. Check the execution context; a call from '
  109. 'main() is not inherently an anti-pattern'),
  110. 'severity': 'warning',
  111. },
  112. {
  113. # Python `global` is a statement, only valid at the start of a line
  114. # inside a function body. Anchoring at line-start eliminates false
  115. # positives from identifiers/strings/class attrs containing "global"
  116. # (e.g. `dict["global_state"]`, `global_var = 1`).
  117. 'pattern': r'^[ \t]*global\s+\w+',
  118. 'pattern_flags': re.MULTILINE,
  119. 'message': 'Global variables break composition — store state as class members',
  120. 'severity': 'warning',
  121. },
  122. {
  123. 'pattern': r'ROS_LOCALHOST_ONLY',
  124. # Unknown distro: keep warning, but do not prescribe the replacement.
  125. # An unset ROS_DISTRO is common in editors and CI, and telling a
  126. # Humble or Foxy project to switch would open its discovery.
  127. 'message': lambda distro: (
  128. 'ROS_LOCALHOST_ONLY is deprecated since Iron. '
  129. 'Use ROS_AUTOMATIC_DISCOVERY_RANGE=LOCALHOST instead'
  130. if distro else
  131. 'ROS_LOCALHOST_ONLY is deprecated since Iron in favor of '
  132. 'ROS_AUTOMATIC_DISCOVERY_RANGE=LOCALHOST, but on Humble and earlier '
  133. 'it is the only way to confine discovery. ROS_DISTRO is not set: '
  134. 'confirm the target distribution before changing it'),
  135. 'severity': 'warning',
  136. 'distro_filter': lambda distro: distro not in _DISTROS_WITHOUT_DISCOVERY_RANGE,
  137. },
  138. {
  139. 'pattern': r'node_executable\s*=',
  140. 'message': 'node_executable is deprecated — use executable instead',
  141. 'severity': 'warning',
  142. # Deprecated launch_ros kwarg — only meaningful inside a launch file.
  143. # Other Python code may legitimately have an attribute/kwarg of the
  144. # same name (e.g. a dataclass `node_executable: str = ...`).
  145. 'file_filter': lambda fp: _is_launch_file(fp),
  146. },
  147. {
  148. 'pattern': r'node_name\s*=',
  149. 'message': 'node_name is deprecated — use name instead',
  150. 'severity': 'warning',
  151. 'file_filter': lambda fp: _is_launch_file(fp),
  152. },
  153. {
  154. 'pattern': r'node_namespace\s*=',
  155. 'message': 'node_namespace is deprecated — use namespace instead',
  156. 'severity': 'warning',
  157. 'file_filter': lambda fp: _is_launch_file(fp),
  158. },
  159. ]
  160. def _is_launch_file(filepath):
  161. """Both official Python launch naming conventions."""
  162. return filepath.endswith('.launch.py') or filepath.endswith('_launch.py')
  163. # File extensions that should be checked
  164. CHECKABLE_EXTENSIONS = {'.py', '.cpp', '.hpp', '.h', '.cc', '.cxx'}
  165. _CPP_EXTENSIONS = ('.cpp', '.hpp', '.h', '.cc', '.cxx')
  166. def _comment_markers(filename):
  167. """Pick single-line comment markers appropriate for the file's language.
  168. Treating ``//`` as a comment in Python would make floor division
  169. (``total // 2``) suppress real matches later on the same line, so
  170. Python files only honour ``#``. C/C++ files only honour ``//``
  171. (``#`` starts a preprocessor directive there, which is code).
  172. Unknown extensions keep the conservative both-markers behaviour.
  173. """
  174. if filename.endswith('.py'):
  175. return ('#',)
  176. if filename.endswith(_CPP_EXTENSIONS):
  177. return ('//',)
  178. return ('#', '//')
  179. def _is_in_comment(content, pos, markers=('#', '//')):
  180. """Heuristically check if a position falls inside a single-line comment.
  181. This reduces false positives from anti-pattern regex checks that match
  182. inside inline comments or docstring-style comment lines. The heuristic
  183. is intentionally conservative: it only skips matches clearly inside
  184. single-line comments (see ``_comment_markers`` for which markers apply
  185. per language). It does NOT skip string literals, because code like
  186. ``os.environ["ROS_LOCALHOST_ONLY"]`` is real usage even though the
  187. variable name appears adjacent to quotes.
  188. """
  189. line_start = content.rfind('\n', 0, pos) + 1
  190. line_end = content.find('\n', pos)
  191. if line_end == -1:
  192. line_end = len(content)
  193. line = content[line_start:line_end]
  194. col = pos - line_start
  195. # Single-line comment: if the first marker on the line is
  196. # before the match position, the match is in a comment.
  197. for marker in markers:
  198. idx = line.find(marker)
  199. if idx != -1 and col > idx:
  200. # Make sure the '#' isn't inside a string on that line
  201. # by checking that there's no odd number of quotes before it
  202. prefix = line[:idx]
  203. in_str = False
  204. for q in ('"', "'"):
  205. if len(re.findall(r'(?<!\\)' + q, prefix)) % 2 == 1:
  206. in_str = True
  207. break
  208. if not in_str:
  209. return True
  210. return False
  211. # --- ROS context -----------------------------------------------------------
  212. #
  213. # The plugin hook runs on every source file a session writes, in every
  214. # project. The anti-pattern advice is only true of ROS 2 code, so event mode
  215. # applies it only where ROS context is established by one of:
  216. #
  217. # 1. an unambiguous ROS import or include in the text being written;
  218. # 2. a valid ROS package manifest in the file's directory or above it;
  219. # 3. such an import or include in the first _CONTEXT_HEAD_BYTES of the file
  220. # already on disk (an Edit fragment rarely repeats the imports).
  221. #
  222. # Anything else is skipped: an unconfirmed context gets no advice rather than
  223. # advice that may be wrong. `from launch import ...` and names starting with
  224. # `ament_` are deliberately not evidence on their own - neither is unique to
  225. # ROS. A launch-named file may additionally use a `launch` import.
  226. _ROS_PY_MARKER = re.compile(
  227. r'^[ \t]*(?:import|from)[ \t]+'
  228. r'(?:rclpy|launch_ros|ament_index_python|rcl_interfaces|rosbag2_py|rosidl_runtime_py)\b'
  229. r'|^[ \t]*from[ \t]+\w+_(?:msgs|interfaces)\.(?:msg|srv|action)[ \t]+import\b',
  230. re.MULTILINE)
  231. _ROS_CPP_MARKER = re.compile(
  232. r'^[ \t]*#[ \t]*include[ \t]*[<"]'
  233. r'(?:(?:rclcpp(?:_lifecycle|_action|_components)?|rclc(?:_lifecycle|_parameter)?'
  234. r'|rcl|rcutils|rmw|ament_index_cpp)/'
  235. r'|\w+_(?:msgs|interfaces)/(?:msg|srv|action)/)',
  236. re.MULTILINE)
  237. _LAUNCH_PY_MARKER = re.compile(
  238. r'^[ \t]*(?:import|from)[ \t]+launch(?:_ros|_xml|_yaml|_testing)?\b', re.MULTILINE)
  239. _CONTEXT_HEAD_BYTES = 64 * 1024
  240. _MANIFEST_MAX_BYTES = 256 * 1024
  241. _ANCESTOR_LIMIT = 8
  242. def _has_ros_marker(text, filename=''):
  243. """True when *text* carries an unambiguous ROS 2 import or include."""
  244. if not text:
  245. return False
  246. ext = os.path.splitext(filename)[1] if filename else ''
  247. if ext == '.py':
  248. return bool(_ROS_PY_MARKER.search(text)
  249. or (_is_launch_file(filename) and _LAUNCH_PY_MARKER.search(text)))
  250. if ext in _CPP_EXTENSIONS:
  251. return bool(_ROS_CPP_MARKER.search(text))
  252. return bool(_ROS_PY_MARKER.search(text) or _ROS_CPP_MARKER.search(text))
  253. def _is_ros_package_manifest(path):
  254. """True for a package.xml that declares an ament build, not merely the name."""
  255. try:
  256. if not os.path.isfile(path) or os.path.getsize(path) > _MANIFEST_MAX_BYTES:
  257. return False
  258. root = ET.parse(path).getroot()
  259. except (OSError, ET.ParseError, ValueError, LookupError):
  260. return False
  261. if root.tag != 'package':
  262. return False
  263. declared = [node.text for tag in ('buildtool_depend', 'build_type')
  264. for node in root.iter(tag)]
  265. return any(isinstance(text, str) and text.strip().startswith('ament_')
  266. for text in declared)
  267. def _ros_package_above(path, stop_dir=''):
  268. """True when the file sits in, or below, a valid ROS package directory.
  269. The manifest is looked up on disk from the file's own directory upwards,
  270. so it is found whether or not this session touched it. The walk ends at
  271. *stop_dir* when that is an ancestor, and after _ANCESTOR_LIMIT levels
  272. otherwise.
  273. """
  274. current = os.path.dirname(os.path.abspath(path))
  275. stop = os.path.abspath(stop_dir) if stop_dir else ''
  276. if stop:
  277. try:
  278. if os.path.commonpath([current, stop]) != stop:
  279. stop = ''
  280. except ValueError: # different drives
  281. stop = ''
  282. for _ in range(_ANCESTOR_LIMIT):
  283. if _is_ros_package_manifest(os.path.join(current, 'package.xml')):
  284. return True
  285. parent = os.path.dirname(current)
  286. if current == stop or parent == current:
  287. break
  288. current = parent
  289. return False
  290. def _read_head(path):
  291. """First _CONTEXT_HEAD_BYTES of an existing regular file, else ''."""
  292. try:
  293. if not os.path.isfile(path):
  294. return ''
  295. with open(path, 'rb') as handle:
  296. return handle.read(_CONTEXT_HEAD_BYTES).decode('utf-8', errors='replace')
  297. except OSError:
  298. return ''
  299. def _has_ros_context(filepath, content, cwd=''):
  300. """Decide whether automatic anti-pattern advice applies to this write."""
  301. if _has_ros_marker(content, filepath):
  302. return True
  303. if not filepath:
  304. return False
  305. path = filepath
  306. if cwd and not os.path.isabs(path):
  307. path = os.path.join(cwd, path)
  308. if _ros_package_above(path, cwd):
  309. return True
  310. return _has_ros_marker(_read_head(path), filepath)
  311. def check_content(content, filename='<input>'):
  312. """Check content for ROS 2 anti-patterns.
  313. Matches inside single-line ``#``/``//`` comments are skipped to reduce
  314. false positives (e.g. a docstring mentioning ``time.sleep()``). Patterns
  315. with a ``file_filter`` entry only run for files the filter approves —
  316. used to scope deprecated-launch-kwarg checks to ``*.launch.py`` only,
  317. so that a regular Python module with an attribute named ``node_name``
  318. is not falsely flagged.
  319. """
  320. issues = []
  321. markers = _comment_markers(filename)
  322. distro = _ros_distro()
  323. for check in ANTIPATTERN_CHECKS:
  324. file_filter = check.get('file_filter')
  325. if file_filter and not file_filter(filename):
  326. continue
  327. distro_filter = check.get('distro_filter')
  328. if distro_filter and not distro_filter(distro):
  329. continue
  330. flags = check.get('pattern_flags', 0)
  331. matches = list(re.finditer(check['pattern'], content, flags))
  332. for match in matches:
  333. if _is_in_comment(content, match.start(), markers):
  334. continue
  335. line_num = content[:match.start()].count('\n') + 1
  336. message = check['message']
  337. issues.append({
  338. 'file': filename,
  339. 'line': line_num,
  340. 'severity': check['severity'],
  341. 'message': message(distro) if callable(message) else message,
  342. })
  343. return issues
  344. def check_file(filepath):
  345. """Check a file for ROS 2 anti-patterns."""
  346. ext = os.path.splitext(filepath)[1]
  347. if ext not in CHECKABLE_EXTENSIONS:
  348. return []
  349. try:
  350. with open(filepath, 'r', encoding='utf-8') as fh:
  351. content = fh.read()
  352. return check_content(content, filepath)
  353. except OSError:
  354. return []
  355. # Best-effort regex guards against common destructive commands.
  356. # NOT a security boundary — see module docstring. These exist to catch
  357. # accidental literal commands like `rm -rf /`, not to defend against an
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 409 on GitHub
  358. # adversary or an LLM that knows about $IFS, $(...), or `eval`.
  359. #
  360. # Two kinds of pattern, marked by `position`:
  361. # 'command' - the dangerous word is a program name, so it only counts in
  362. # command position: start of the input or of a line, after a
  363. # shell separator / grouping character / `$(`, or right after
  364. # the opening quote of an argument (`bash -c '...'`,
  365. # `ssh host '...'`), optionally behind variable assignments and
  366. # wrappers (`sudo -u root`, `env A=1`, `xargs`, `timeout 5`).
  367. # The same word as a mere argument (`grep mkfs`, `man
  368. # mkfs.ext4`, a commit message, a sentence in a here-doc) is
  369. # data, and refusing it with the blocking exit code is a false
  370. # positive that stops read-only work.
  371. # 'anywhere' - the pattern is a shell operator or a structure (`> /dev/sda`,
  372. # a fork bomb, `Remove-Item ... -Recurse -Force <root>`) that is
  373. # dangerous wherever it appears, so it keeps matching anywhere.
  374. # `flags` carries `re` flags; an inline `(?i)` cannot follow the position prefix.
  375. _ASSIGNMENTS = r'(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*'
  376. _WRAPPER = (r'(?:(?:sudo|doas|exec|nohup|time|command|builtin|xargs|env|nice|ionice|stdbuf)'
  377. r'(?:\s+-\S+(?:\s+[^\s;&|-][^\s;&|]*)?)*'
  378. r'|timeout(?:\s+-\S+)*\s+\S+)\s+')
  379. _CMD = (r'(?:^|(?<=[\n;&|(){}`])|(?<=\$\()|(?<=[\s=]["\']))\s*' + _ASSIGNMENTS
  380. + r'(?:' + _WRAPPER + _ASSIGNMENTS + r')*')
  381. DANGEROUS_COMMAND_PATTERNS = [
  382. # `(?=\s|$|[;&|])` terminates a target path at whitespace, end of input,
  383. # or a shell separator, so compound commands (`rm -rf /; echo done`,
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 436 on GitHub
  384. # `rm -rf / && true`) are still caught, while longer paths under the
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 437 on GitHub
  385. # same root (`rm -rf /var/lib/apt/lists/*`) are not.
  386. {
  387. 'pattern': _CMD + r'rm\s+(-[a-zA-Z]*f[a-zA-Z]*\s+|(-[a-zA-Z]+\s+)*)/(?=\s|$|[;&|])',
  388. 'position': 'command',
  389. 'message': 'Refusing to remove root filesystem (rm -rf /)',
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 442 on GitHub
  390. },
  391. {
  392. 'pattern': _CMD + r'rm\s+(-[a-zA-Z]*f[a-zA-Z]*\s+|(-[a-zA-Z]+\s+)*)/\*',
  393. 'position': 'command',
  394. 'message': 'Refusing to remove all files from root (rm -rf /*)',
  395. },
  396. {
  397. 'pattern': _CMD + r'rm\s+(-[a-zA-Z]*r[a-zA-Z]*\s+(-[a-zA-Z]+\s+)*)/opt/ros\b',
  398. 'position': 'command',
  399. 'message': 'Refusing to remove ROS installation directory',
  400. },
  401. {
  402. # Matches removal of the critical directory itself (optionally with
  403. # a trailing / or /*), NOT of arbitrary subpaths beneath it.
  404. 'pattern': (_CMD + r'rm\s+(-[a-zA-Z]*r[a-zA-Z]*\s+(-[a-zA-Z]+\s+)*)'
  405. r'/(usr|bin|sbin|etc|var|boot|lib|lib64)'
  406. r'(?:/\*)?/?(?=\s|$|[;&|])'),
  407. 'position': 'command',
  408. 'message': 'Refusing to remove critical system directory',
  409. },
  410. {
  411. 'pattern': (_CMD + r'rm\s+(-[a-zA-Z]*r[a-zA-Z]*\s+(-[a-zA-Z]+\s+)*)'
  412. r'(~|\$HOME)/?(?=\s|$|[;&|])'),
  413. 'position': 'command',
  414. 'message': 'Refusing to remove home directory',
  415. },
  416. {
  417. 'pattern': _CMD + r'mkfs\b',
  418. 'position': 'command',
  419. 'message': 'Refusing to format filesystem (mkfs)',
  420. },
  421. {
  422. 'pattern': _CMD + r'dd\s+.*\bof\s*=\s*/dev/(sd|nvme|vd|hd)',
  423. 'position': 'command',
  424. 'message': 'Refusing to write directly to block device (dd)',
  425. },
  426. {
  427. # Only the filesystem root itself (`/` or `/*`), not any absolute path.
  428. 'pattern': _CMD + r'chmod\s+(-[a-zA-Z]*R[a-zA-Z]*\s+)777\s+/\*?(?=\s|$|[;&|])',
  429. 'position': 'command',
  430. 'message': 'Refusing to recursively chmod 777 on root filesystem',
  431. },
  432. {
  433. 'pattern': r':\s*\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:',
  434. 'position': 'anywhere',
  435. 'message': 'Refusing to execute fork bomb',
  436. },
  437. {
  438. 'pattern': r'>\s*/dev/(sd|nvme|vd|hd)',
  439. 'position': 'anywhere',
  440. 'message': 'Refusing to overwrite block device',
  441. },
  442. # PowerShell / Windows equivalents. Maintainer works on Windows and the
  443. # harness may forward `pwsh`/`powershell` commands under TOOL_NAME=Bash
  444. # (the agent's logical tool name), so the bash branch can carry PS syntax.
  445. # Same best-effort caveat as above: these are not a security boundary.
  446. #
  447. # Implementation notes:
  448. # * `flags: re.IGNORECASE` — PowerShell cmdlets are case-insensitive
  449. # (`remove-item` == `Remove-Item`).
  450. # * `\b` only attaches to alphanumeric ends; on a hyphen-prefixed flag
  451. # like `-Recurse` the leading `\b` would fail (space → `-` is not a
  452. # word boundary). Lookaheads avoid that trap and also let `-Recurse`
  453. # and `-Force` appear in any order.
  454. # * Drive-root regex requires `:` then `/` or `\` then nothing else
  455. # meaningful, so `C:/Users/me/build` (a real subdir) does NOT match.
  456. {
  457. 'pattern': (r'\bRemove-Item\b'
  458. r'(?=[^;\n]*\s-Recurse\b)'
  459. r'(?=[^;\n]*\s-Force\b)'
  460. r'[^;\n]*[A-Za-z]:[\\/]\s*(?:["\']?\s*)?(?:[;\n]|$)'),
  461. 'position': 'anywhere',
  462. 'flags': re.IGNORECASE,
  463. 'message': 'Refusing to recursively force-remove a drive root (Remove-Item)',
  464. },
  465. {
  466. 'pattern': (r'\bRemove-Item\b'
  467. r'(?=[^;\n]*\s-Recurse\b)'
  468. r'(?=[^;\n]*\s-Force\b)'
  469. r'[^;\n]*(?:\$HOME|\$env:USERPROFILE|~)\s*'
  470. r'(?:["\']?\s*)?(?:[;\n]|$)'),
  471. 'position': 'anywhere',
  472. 'flags': re.IGNORECASE,
  473. 'message': 'Refusing to recursively force-remove the home directory (Remove-Item)',
  474. },
  475. {
  476. 'pattern': (r'\bRemove-Item\b'
  477. r'(?=[^;\n]*\s-Recurse\b)'
  478. r'(?=[^;\n]*\s-Force\b)'
  479. r'[^;\n]*[A-Za-z]:[\\/](?:Windows|Program Files|Program Files \(x86\)|Users)\b'),
  480. 'position': 'anywhere',
  481. 'flags': re.IGNORECASE,
  482. 'message': 'Refusing to recursively force-remove a critical Windows directory',
  483. },
  484. {
  485. 'pattern': _CMD + r'Format-Volume\b',
  486. 'position': 'command',
  487. 'flags': re.IGNORECASE,
  488. 'message': 'Refusing to format volume (Format-Volume)',
  489. },
  490. {
  491. 'pattern': _CMD + r'Clear-Disk\b',
  492. 'position': 'command',
  493. 'flags': re.IGNORECASE,
  494. 'message': 'Refusing to clear disk (Clear-Disk)',
  495. },
  496. {
  497. 'pattern': _CMD + r'Remove-Partition\b',
  498. 'position': 'command',
  499. 'flags': re.IGNORECASE,
  500. 'message': 'Refusing to remove partition (Remove-Partition)',
  501. },
  502. {
  503. 'pattern': r'\brmdir\b\s+/s\s+/q\s+[A-Za-z]:[\\/]?\s*$',
  504. 'position': 'anywhere',
  505. 'flags': re.IGNORECASE,
  506. 'message': 'Refusing to silently recursively remove drive root (rmdir /s /q)',
  507. },
  508. ]
  509. def _match_dangerous(text):
  510. """Every destructive pattern that matches *text* as written."""
  511. issues = []
  512. for check in DANGEROUS_COMMAND_PATTERNS:
  513. if re.search(check['pattern'], text, check.get('flags', 0)):
  514. issues.append({
  515. 'file': '<bash>',
  516. 'line': 0,
  517. 'severity': 'error',
  518. 'message': check['message'],
  519. })
  520. return issues
  521. # The patterns above read the command as text, which errs both ways: quoted
  522. # text handed to grep or echo is refused although nothing runs, and
  523. # `bash -c 'rm -rf /'` passes because the pattern expects a separator, not a
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 580 on GitHub
  524. # closing quote, after the path. For POSIX shell tools the quote-aware scanner
  525. # further down (written for the actuation check) settles both, under one
  526. # rule: a command that would run stays refused; only text confirmed to be
  527. # data is let through.
  528. #
  529. # * Data. The literal arguments of grep/egrep/fgrep, rg, echo and printf
  530. # are data when the command stands at the top level with nothing in front
  531. # of it, does not write to a file, and everything after it in the same
  532. # pipeline is a plain filter. Arguments that contain a substitution or a
  533. # variable are never treated as data, because that part runs first.
  534. # `printf -v` stores instead of printing and `rg --pre` runs a program, so
  535. # neither qualifies. If the scan is incomplete in any way nothing is
  536. # treated as data and the pattern verdict stands.
  537. # * Commands. Each program the scanner finds would run - inside `bash -c`,
  538. # `ssh host '...'`, `$(...)`, a subshell, after sudo or xargs - is checked
  539. # against the command-position patterns as program plus arguments.
  540. # * Echoed scripts. The output a literal echo or printf writes to a file,
  541. # or pipes into a shell, is rendered and checked as a complete script:
  542. # format reuse, %s, %b, echo options and escapes included.
  543. # `printf '%s' 'rm ' '-rf /' | sh` is one command, and
  544. # `printf '%s' 'never run ' 'rm -rf /' >> NOTES.md` is a sentence. bash,
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 601 on GitHub
  545. # dash and zsh read the same echo or printf differently, and which one
  546. # runs the command is not known, so each is rendered on its own and one
  547. # destructive result is enough to refuse. Output that a shell's rules do
  548. # not cover, or that would pass 64 KiB, is not rendered and not checked
  549. # in pieces; the pattern verdict of those arguments then stands.
  550. #
  551. # The analysis runs on every POSIX command, not only on those whose raw text
  552. # names a destructive program: `r''m -rf /` and `echo -e '\x72m -rf /' | sh`
  553. # name it only after quoting and escapes are resolved. If the analysis itself
  554. # fails, the unrefined pattern verdict and everything found up to that point
  555. # are returned, so a failure cannot turn a refusal into a pass.
  556. #
  557. # Not interpreted: `git -c alias.x='!...'` shell aliases, anything a variable
  558. # expands to, printf conversions other than %s and %b, output joined from
  559. # several commands, and shells other than bash, dash and zsh. Other tools
  560. # (PowerShell, cmd) keep the pattern verdict.
  561. _DATA_PROGRAMS = frozenset(('grep', 'egrep', 'fgrep', 'rg', 'echo', 'printf'))
  562. _PIPE_FILTERS = frozenset(('head', 'tail', 'wc', 'sort', 'uniq', 'less', 'cat',
  563. 'grep', 'egrep', 'fgrep', 'rg'))
  564. _REINTERPRETERS = frozenset(('eval', 'source', '.', 'xargs', 'parallel'))
  565. def _plain_program(words):
  566. """Bare program name of a command with nothing in front of it.
  567. `./grep` and `/tmp/echo` are whatever file is there, so a path is not
  568. accepted as one of the known data programs or filters.
  569. """
  570. if not words or words[0][1] or '/' in words[0][0]:
  571. return ''
  572. return words[0][0]
  573. def _unwrapped(words):
  574. """*words* without leading assignments and wrappers such as sudo or env."""
  575. args = list(words)
  576. while args and not args[0][1]:
  577. text = args[0][0]
  578. if _ASSIGNMENT.match(text):
  579. args.pop(0)
  580. elif os.path.basename(text) in _WRAPPERS:
  581. args = _strip_wrapper(os.path.basename(text), args[1:])
  582. else:
  583. break
  584. return args
  585. def _runs_a_program(name, words):
  586. """Options that make an otherwise data-only program store or execute."""
  587. texts = [text for text, dynamic in words[1:] if not dynamic]
  588. if name == 'printf':
  589. return any(text.startswith('-v') for text in texts)
  590. if name == 'rg':
  591. return any(text.startswith(('--pre', '--hostname-bin')) for text in texts)
  592. if name == 'sort':
  593. return any(text.startswith(('-o', '--output')) for text in texts)
  594. if name == 'uniq':
  595. return len([text for text in texts if not text.startswith('-')]) > 1
  596. return False
  597. def _reads_stdin_as_script(words):
  598. """A shell with no command string and no script file: it runs its input."""
  599. words = _unwrapped(words)
  600. if not words or words[0][1] or os.path.basename(words[0][0]) not in _SHELLS:
  601. return False
  602. for text, dynamic in words[1:]:
  603. if dynamic or not text.startswith('-') or (not text.startswith('--') and 'c' in text):
  604. return False
  605. return True
  606. def _top_level_pipelines(out):
  607. """Top-level commands grouped into pipelines, in source order."""
  608. pipelines, current = [], []
  609. for words, _heredocs, depth, meta in out.commands:
  610. if depth != 0:
  611. continue
  612. current.append((words, meta))
  613. if meta['sep'] != '|':
  614. pipelines.append(current)
  615. current = []
  616. if current:
  617. pipelines.append(current)
  618. return pipelines
  619. def _mask_data_arguments(command, out):
  620. """*command* with confirmed data blanked out, or None when nothing is data."""
  621. if out.reasons or out.grouped or any(
  622. name in _REINTERPRETERS for name, _rest in out.executed):
  623. return None
  624. masked = list(command)
  625. for pipeline in _top_level_pipelines(out):
  626. for index, (words, meta) in enumerate(pipeline):
  627. name = _plain_program(words)
  628. if name not in _DATA_PROGRAMS or _runs_a_program(name, words):
  629. continue
  630. rest = pipeline[index + 1:]
  631. if (meta['redirect_out'] or any(
  632. later['redirect_out'] or _plain_program(following) not in _PIPE_FILTERS
  633. or _runs_a_program(_plain_program(following), following)
  634. for following, later in rest)):
  635. # Kept, unless every shell's output is rendered: then those
  636. # strings are what gets checked, and the separate arguments
  637. # say nothing. One unrendered candidate keeps the pattern.
  638. candidates = _written_output(pipeline, index)
  639. if candidates is None or None in candidates:
  640. continue
  641. for (text, dynamic), (start, end) in zip(words[1:], meta['spans'][1:]):
  642. if not dynamic:
  643. masked[start:end] = ' ' * (end - start)
  644. masked = ''.join(masked)
  645. return None if masked == command else masked
  646. def _executed_issues(out):
  647. """Command-position patterns applied to each program that would run."""
  648. issues = []
  649. def refuse(message):
  650. issues.append({'file': '<bash>', 'line': 0, 'severity': 'error', 'message': message})
  651. for name, rest in out.executed:
  652. if name == 'rm':
  653. # The patterns read `rm <short options> /`. As arguments the
  654. # target is unambiguous whatever precedes it: `--`, a long
  655. # option such as --no-preserve-root, or another path.
  656. operands, options_done = [], False
  657. for word, dynamic in rest:
  658. if dynamic:
  659. continue
  660. if not options_done and word == '--':
  661. options_done = True
  662. elif options_done or not word.startswith('-'):
  663. operands.append(word)
  664. if '/' in operands:
  665. refuse('Refusing to remove root filesystem (rm -rf /)')
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 739 on GitHub
  666. if '/*' in operands:
  667. refuse('Refusing to remove all files from root (rm -rf /*)')
  668. # An argument with whitespace in it is one argument, not several.
  669. text = ' '.join([name] + ['ARG' if re.search(r'\s', word) else word
  670. for word, _dynamic in rest])
  671. for check in DANGEROUS_COMMAND_PATTERNS:
  672. if (check['position'] == 'command' and re.match(
  673. check['pattern'], text, check.get('flags', 0))
  674. and all(check['message'] != known['message'] for known in issues)):
  675. refuse(check['message'])
  676. return issues
  677. # How a backslash is read depends on the shell and on where the text stands.
  678. # The hook does not know which shell will run the command, so the output of
  679. # echo and printf is rendered once per shell and every result is checked.
  680. # Reading more escapes is not the safer guess: turning \x22 into a quote can
  681. # hide a command that dash, which leaves \x22 alone, would run.
  682. #
  683. # Measured with bash 5.2, dash 0.5.12 and zsh 5.9, harmless strings only:
  684. #
  685. # \123 \0123 \x41 \c \" \' \?
  686. # bash format octal \012 + "3" A kept character
  687. # %b argument octal octal A output ends kept
  688. # echo -e kept octal A output ends kept
  689. # dash format octal \012 + "3" kept kept kept
  690. # %b argument octal octal kept output ends kept
  691. # echo octal octal kept output ends kept
  692. # zsh format octal \012 + "3" A output ends kept
  693. # %b argument kept octal A output ends kept
  694. # echo kept octal A output ends kept
  695. #
  696. # bash reads \E as escape, dash and zsh do not. `ansi_c` is the inside of
  697. # bash's $'...'.
  698. _LETTERS = {'a': '\a', 'b': '\b', 'e': '\x1b', 'f': '\f',
  699. 'n': '\n', 'r': '\r', 't': '\t', 'v': '\v', '\\': '\\'}
  700. _OCTAL = '01234567'
  701. _HEX = '0123456789abcdefABCDEF'
  702. _RENDER_MAX_CHARS = 64 * 1024
  703. _DIALECTS = ('bash', 'dash', 'zsh')
  704. def _rule(octal, stop, hexadecimal=True, quotes=False, capital_e=False, unknown='keep'):
  705. return {'octal': octal, 'stop': stop, 'hex': hexadecimal, 'quotes': quotes,
  706. 'capital_e': capital_e, 'unknown': unknown}
  707. # octal: 'any' is \NNN with one to three digits, 'zero' is \0 and up to three
  708. # more, 'both' accepts either. stop: \c ends the output (True), is two
  709. # characters (False), or is not modelled (None). unknown: what \x without a
  710. # digit, \u and \U are - kept as written ('keep'), kept unless a digit
  711. # follows ('digits'), or never modelled ('never').
  712. _ESCAPE_RULES = {
  713. ('bash', 'format'): _rule('any', False, quotes=True, capital_e=True, unknown='digits'),
  714. ('bash', 'percent_b'): _rule('both', True, capital_e=True, unknown='digits'),
  715. ('bash', 'echo'): _rule('zero', True, capital_e=True, unknown='digits'),
  716. ('bash', 'ansi_c'): _rule('any', None, quotes=True, capital_e=True, unknown='digits'),
  717. ('dash', 'format'): _rule('any', False, hexadecimal=False),
  718. ('dash', 'percent_b'): _rule('both', True, hexadecimal=False),
  719. ('dash', 'echo'): _rule('both', True, hexadecimal=False),
  720. ('zsh', 'format'): _rule('any', True, unknown='never'),
  721. ('zsh', 'percent_b'): _rule('zero', True, unknown='never'),
  722. ('zsh', 'echo'): _rule('zero', True, unknown='never'),
  723. }
  724. def _decode_escapes(text, mode, dialect='bash'):
  725. r"""Backslash escapes as *dialect* reads them in *mode*: (text, stopped).
  726. Returns None when the result is not modelled: \u and \U where the shell
  727. reads them, a control character written \cX inside $'...', a NUL, or a
  728. byte above 0x7f, whose meaning depends on the locale. An escape the
  729. shell does not know keeps its backslash.
  730. """
  731. rule = _ESCAPE_RULES[(dialect, mode)]
  732. out, i, n = [], 0, len(text)
  733. while i < n:
  734. char = text[i]
  735. if char != '\\' or i + 1 >= n:
  736. out.append(char)
  737. i += 1
  738. continue
  739. nxt = text[i + 1]
  740. if nxt in _LETTERS or (nxt == 'E' and rule['capital_e']):
  741. out.append(_LETTERS.get(nxt, '\x1b'))
  742. i += 2
  743. continue
  744. if nxt in '\'"?':
  745. out.append(nxt if rule['quotes'] else '\\' + nxt)
  746. i += 2
  747. continue
  748. if nxt == 'c':
  749. if rule['stop'] is None:
  750. return None
  751. if rule['stop']:
  752. return ''.join(out), True
  753. out.append('\\c')
  754. i += 2
  755. continue
  756. digits = None
  757. if nxt in _OCTAL:
  758. start = i + 1
  759. if nxt == '0' and rule['octal'] in ('zero', 'both'):
  760. start += 1 # \0 and then up to three digits
  761. elif rule['octal'] == 'zero':
  762. start = -1 # an octal value is read only after \0
  763. if start >= 0:
  764. end = start
  765. while end < n and end - start < 3 and text[end] in _OCTAL:
  766. end += 1
  767. digits, base, i = text[start:end] or '0', 8, end
  768. elif nxt == 'x' and rule['hex']:
  769. end = i + 2
  770. while end < n and end - (i + 2) < 2 and text[end] in _HEX:
  771. end += 1
  772. if end > i + 2:
  773. digits, base, i = text[i + 2:end], 16, end
  774. elif rule['unknown'] == 'never':
  775. return None
  776. elif nxt in 'uU' and rule['hex'] and (
  777. rule['unknown'] == 'never'
  778. or (rule['unknown'] == 'digits' and i + 2 < n and text[i + 2] in _HEX)):
  779. return None
  780. if digits is None:
  781. out.append('\\' + nxt)
  782. i += 2
  783. continue
  784. value = int(digits, base)
  785. if not 0 < value < 0x80:
  786. return None
  787. out.append(chr(value))
  788. return ''.join(out), False
  789. class _Rendered:
  790. """Output under construction, refused before it passes the size limit.
  791. Every piece goes through add(): literal text, %%, converted arguments,
  792. padding, and each pass of a reused format. The size is checked before
  793. the piece is built, so a width of two thousand million costs nothing.
  794. """
  795. def __init__(self):
  796. self.parts, self.size = [], 0
  797. def add(self, text, width=0, left=False):
  798. size = max(len(text), width)
  799. if self.size + size > _RENDER_MAX_CHARS:
  800. return False
  801. self.size += size
  802. self.parts.append(text.ljust(width) if left else text.rjust(width))
  803. return True
  804. def text(self):
  805. return ''.join(self.parts)
  806. _CONVERSION = re.compile(r'%(?:(%)|(-?)(\d*)(\.\d*)?([sb]))')
  807. def _render_printf(args, dialect='bash'):
  808. """What `printf` writes for these literal arguments in *dialect*, or None.
  809. Modelled: literal text and its escapes, %%, %s with an optional `-`,
  810. width and precision, and %b with the escapes of its argument. The format
  811. is reused while arguments remain, the passes are joined with nothing in
  812. between, and a missing argument is empty. Anything else is None, never a
  813. guess: options, other conversions and flags, `*`, a sized %b, a width or
  814. precision of more than five digits, output past the size limit.
  815. """
  816. if args and args[0] == '--':
  817. args = args[1:]
  818. if not args or args[0].startswith('-'):
  819. return None
  820. template, tokens, conversions, pos = args[0], [], 0, 0
  821. while pos < len(template):
  822. end = template.find('%', pos)
  823. if end != pos:
  824. end = len(template) if end < 0 else end
  825. decoded = _decode_escapes(template[pos:end], 'format', dialect)
  826. if decoded is None:
  827. return None
  828. tokens.append(('text', decoded))
  829. pos = end
  830. continue
  831. match = _CONVERSION.match(template, pos)
  832. if not match:
  833. return None
  834. percent, left, width, precision, kind = match.groups()
  835. if percent:
  836. tokens.append(('text', ('%', False)))
  837. elif (width.startswith('0') or len(width) > 5 or len(precision or '') > 6
  838. or (kind == 'b' and (left or width or precision))):
  839. return None # a 0 flag, a number too long to be a size, a sized %b
  840. else:
  841. tokens.append((kind, (left, int(width or 0),
  842. None if precision is None else int(precision[1:] or 0))))
  843. conversions += 1
  844. pos = match.end()
  845. values, out = list(args[1:]), _Rendered()
  846. while True:
  847. for kind, detail in tokens:
  848. if kind == 'text':
  849. text, stopped = detail
  850. if not out.add(text):
  851. return None
  852. if stopped:
  853. return out.text()
  854. continue
  855. value, stopped = (values.pop(0) if values else ''), False
  856. left, width, precision = detail
  857. if kind == 'b':
  858. decoded = _decode_escapes(value, 'percent_b', dialect)
  859. if decoded is None:
  860. return None
  861. value, stopped = decoded
  862. elif (width or precision is not None) and not value.isascii():
  863. return None # padding counts bytes or characters by locale
  864. elif precision is not None:
  865. value = value[:precision]
  866. if not out.add(value, width, bool(left)):
  867. return None
  868. if stopped:
  869. return out.text()
  870. if not conversions or not values:
  871. return out.text()
  872. def _render_echo(args, dialect='bash'):
  873. """What `echo` writes for these literal arguments in *dialect*, or None.
  874. bash: leading arguments made of n, e and E are options, and the last of
  875. -e and -E decides whether escapes are read.
  876. dash: only a first argument that is exactly -n is an option; everything
  877. else, -e included, is text, and escapes are always read.
  878. zsh: options as in bash, except that a lone `-` ends them without being
  879. written; escapes are read unless -E is given without -e.
  880. """
  881. args, newline = list(args), True
  882. if dialect == 'dash':
  883. if args and args[0] == '-n':
  884. newline = False
  885. args.pop(0)
  886. interpret = True
  887. else:
  888. enabled, disabled, last = False, False, None
  889. while args:
  890. if dialect == 'zsh' and args[0] == '-':
  891. args.pop(0) # a lone dash ends the options and is not written
  892. break
  893. if not re.fullmatch(r'-[neE]+', args[0]):
  894. break
  895. for flag in args.pop(0)[1:]:
  896. if flag == 'n':
  897. newline = False
  898. else:
  899. last = flag
  900. enabled, disabled = enabled or flag == 'e', disabled or flag == 'E'
  901. interpret = last == 'e' if dialect == 'bash' else (enabled or not disabled)
  902. text = ' '.join(args)
  903. out = _Rendered()
  904. if interpret:
  905. decoded = _decode_escapes(text, 'echo', dialect)
  906. if decoded is None:
  907. return None
  908. text, stopped = decoded
  909. if stopped:
  910. return text if out.add(text) else None
  911. return out.text() if out.add(text + ('\n' if newline else '')) else None
  912. def _written_output(pipeline, index):
  913. """Output of the literal echo or printf at *index* that is run or saved.
  914. Returns None when the command is something else, has an argument that is
  915. not literal, or its output only reaches the terminal or a filter.
  916. Otherwise one entry per shell in _DIALECTS: the text that shell writes,
  917. or None where it is not modelled.
  918. """
  919. words, meta = pipeline[index]
  920. name = _plain_program(words)
  921. if name not in ('echo', 'printf') or any(dynamic for _text, dynamic in words):
  922. return None
  923. runnable = meta['redirect_out']
  924. for following, later in pipeline[index + 1:]:
  925. # Piped into a shell, or saved with tee or a redirection.
  926. if (_reads_stdin_as_script(following) or later['redirect_out']
  927. or _plain_program(_unwrapped(following)) == 'tee'):
  928. runnable = True
  929. break
  930. if _plain_program(following) != 'cat' or len(following) > 1:
  931. break
  932. if not runnable:
  933. return None
  934. args = [text for text, _dynamic in words[1:]]
  935. render = _render_echo if name == 'echo' else _render_printf
  936. return [render(args, dialect) for dialect in _DIALECTS]
  937. def _echoed_scripts(out):
  938. """Text a literal echo or printf writes to a file or pipes into a shell.
  939. Yields each distinct output a shell could produce, complete, the way the
  940. reader of that output sees it. Output that cannot be rendered is left
  941. out rather than checked in pieces.
  942. """
  943. for pipeline in _top_level_pipelines(out):
  944. for index in range(len(pipeline)):
  945. seen = set()
  946. for rendered in _written_output(pipeline, index) or ():
  947. if rendered and rendered not in seen:
  948. seen.add(rendered)
  949. yield rendered
  950. def _command_shape(command):
  951. """The scanned command, or None when it is too long or cannot be read."""
  952. if len(command) > _ACTUATION_MAX_CHARS:
  953. return None
  954. out = _Analysis()
  955. try:
  956. _traverse(command, out)
  957. except (_Unparsed, RecursionError):
  958. return None
  959. return out
  960. def _check_dangerous_commands(command, tool_name='bash'):
  961. """Check a shell command string for destructive commands.
  962. The patterns give the baseline. For a POSIX shell command that the
  963. scanner reads completely, text confirmed to be data is removed from that
  964. baseline and programs that would run are added to it.
  965. """
  966. baseline = _match_dangerous(command)
  967. family = tool_name.lower().rstrip('_').split('__')[-1]
  968. if family not in _POSIX_TOOLS:
  969. return baseline
  970. # No shortcut on the raw text: `printf '%s%s' r 'm -rf /' | sh` and
  971. # `r''m -rf /` name the program only once the words are put together.
  972. out = _command_shape(command)
  973. if out is None:
  974. return baseline
  975. issues, found = baseline, []
  976. try:
  977. found.extend(_executed_issues(out))
  978. for script in _echoed_scripts(out):
  979. found.extend(_match_dangerous(script))
  980. inner = _command_shape(script)
  981. if inner is not None:
  982. found.extend(_executed_issues(inner))
  983. # Last, so that nothing is removed before everything else is known.
  984. if baseline:
  985. masked = _mask_data_arguments(command, out)
  986. if masked is not None:
  987. issues = _match_dangerous(masked)
  988. except Exception: # noqa: BLE001 - a failed refinement must not lift a refusal
  989. # The adapter reports a validator that exits abnormally as skipped,
  990. # which would let the command through. Keep the unrefined pattern
  991. # verdict and whatever was established before the failure.
  992. issues = baseline
  993. issues = list(issues)
  994. for issue in found:
  995. if all(issue['message'] != known['message'] for known in issues):
  996. issues.append(issue)
  997. return issues
  998. # --- Actuation commands -----------------------------------------------------
  999. #
  1000. # A `ros2` command that publishes a velocity, sends a motion goal, switches a
  1001. # controller, resets a stop or changes a limit is the moment the skill's
  1002. # guidance is about, so the hook says so. These findings are warnings: they
  1003. # never block (exit 2 is reserved for the destructive patterns above), and
  1004. # they are not a safety function. Names are matched, not behavior.
  1005. #
  1006. # The destructive patterns deliberately match inside quotes. That is wrong
  1007. # here: `grep "ros2 topic pub /cmd_vel" notes.md` moves nothing. So this
  1008. # analysis reads the command with a small quote-aware scanner and only judges
  1009. # what it can interpret:
  1010. #
  1011. # * simple commands split on ; && || | & newlines and grouping;
  1012. # * single quotes are data; double quotes and unquoted text execute `$(...)`
  1013. # and backticks, which are scanned in turn;
  1014. # * leading assignments, whose values may be dynamic, and wrappers (sudo,
  1015. # env, timeout, nice, ...);
  1016. # * strings handed to a shell or a remote shell: `bash -c`, `bash -lc`,
  1017. # `bash --login -c`, `ssh host '...'`, `su -c`, `eval`, `watch`, and the
  1018. # tmux subcommands that type or run a command;
  1019. # * the program run by `docker|podman exec|run` (and compose), `kubectl
  1020. # exec ... --`, `xargs`, and `find -exec`, located from each program's own
  1021. # option table so that `docker exec c echo ros2 ...` stays data;
  1022. # * here-documents: the body is a script when it feeds a shell, and
  1023. # otherwise only its `$(...)` is executed, and only when the delimiter is
  1024. # unquoted.
  1025. #
  1026. # What it cannot interpret is reported in `checks_skipped`, never as a pass:
  1027. # unbalanced quoting, an unterminated here-document, nesting beyond
  1028. # _ACTUATION_MAX_DEPTH, a command name that is a variable or substitution
  1029. # (which covers `bash -c "$CMD"` and `ssh host "$CMD"`), a dynamic `eval`,
  1030. # a shell reading commands from a pipe, a `ros2` target that is not literal
  1031. # and matches no known pattern, an option of docker, kubectl, xargs, watch or
  1032. # tmux outside the table, and the arguments of parallel, script, flock,
  1033. # chroot and screen. An unrelated dynamic command in the same call is
  1034. # reported too: an unread command is not assumed to be harmless. A command
  1035. # without the literal text `ros2` is not analyzed at all, so `$CMD /cmd_vel`,
  1036. # an alias, or a script that publishes is not detected. PowerShell and cmd
  1037. # are not parsed.
  1038. ACTUATION_ENV = 'ROS2_SKILL_ACTUATION'
  1039. ACTUATION_MODES = ('advise', 'ask', 'off')
  1040. _ACTUATION_MAX_CHARS = 64 * 1024
  1041. _ACTUATION_MAX_DEPTH = 3
  1042. _POSIX_TOOLS = frozenset(('bash', 'shell', 'command', 'terminal'))
  1043. _SHELLS = frozenset(('bash', 'sh', 'zsh', 'dash', 'ksh'))
  1044. _RESERVED = frozenset(('if', 'then', 'elif', 'else', 'fi', 'do', 'done', 'while',
  1045. 'until', '{', '}', '!'))
  1046. _ASSIGNMENT = re.compile(r'[A-Za-z_][A-Za-z0-9_]*\+?=')
  1047. _VARIABLE = re.compile(r'[A-Za-z_][A-Za-z0-9_]*|[0-9@*#?$!-]')
  1048. # Options that consume the following word, per wrapper; `positionals` are
  1049. # dropped after the options (the duration of `timeout`, the mask of taskset).
  1050. _WRAPPERS = {
  1051. 'sudo': (('-u', '-g', '-h', '-p', '-C', '-D', '-R', '-T', '-U', '-r', '-t',
  1052. '--user', '--group', '--host', '--prompt', '--chdir', '--role', '--type'), 0),
  1053. 'doas': (('-u', '-C'), 0),
  1054. 'env': (('-u', '--unset', '-C', '--chdir', '-S', '--split-string'), 0),
  1055. 'nice': (('-n', '--adjustment'), 0),
  1056. 'ionice': (('-c', '-n', '--class', '--classdata'), 0),
  1057. 'timeout': (('-s', '--signal', '-k', '--kill-after'), 1),
  1058. 'stdbuf': (('-i', '-o', '-e', '--input', '--output', '--error'), 0),
  1059. 'chrt': ((), 1),
  1060. 'taskset': ((), 1),
  1061. 'nohup': ((), 0), 'setsid': ((), 0), 'time': ((), 0),
  1062. 'exec': (('-a',), 0), 'command': ((), 0), 'builtin': ((), 0),
  1063. }
  1064. _SSH_VALUE_OPTIONS = frozenset(
  1065. '-' + letter for letter in 'BbcDEeFIiJLlmOopQRSWw')
  1066. # Programs that run another program given as arguments. The executed argv is
  1067. # located from each program's own option table: (options that take a value,
  1068. # flags, letters that may be bundled as `-it`). An option outside the table
  1069. # is never guessed at - see _skip_options.
  1070. _CONTAINER_TOOLS = frozenset(('docker', 'podman', 'nerdctl', 'docker-compose'))
  1071. _DOCKER_GLOBAL = (('--context', '-c', '-H', '--host', '--config', '-l', '--log-level'),
  1072. ('-D', '--debug', '--tls', '--tlsverify'), '')
  1073. _COMPOSE_GLOBAL = (('-f', '--file', '-p', '--project-name', '--profile', '--env-file',
  1074. '--project-directory', '--ansi', '--progress', '--parallel'),
  1075. ('--compatibility', '--dry-run'), '')
  1076. _CONTAINER_VERBS = {
  1077. 'exec': (('-e', '--env', '--env-file', '-u', '--user', '-w', '--workdir',
  1078. '--detach-keys'),
  1079. ('-i', '-t', '-d', '--interactive', '--tty', '--detach', '--privileged'), 'itd'),
  1080. 'run': (('-e', '--env', '--env-file', '-v', '--volume', '--mount', '-p', '--publish',
  1081. '-w', '--workdir', '-u', '--user', '--name', '--network', '--net', '-h',
  1082. '--hostname', '-l', '--label', '--gpus', '--ipc', '--pid', '--cap-add',
  1083. '--cap-drop', '--device', '--add-host', '--restart', '--runtime',
  1084. '--shm-size', '-m', '--memory', '--cpus', '--ulimit', '--security-opt',
  1085. '--platform', '--pull', '--entrypoint'),
  1086. ('--rm', '-i', '-t', '-d', '--interactive', '--tty', '--detach',
  1087. '--privileged', '--init', '--read-only', '-P', '--publish-all'), 'itdP'),
  1088. 'compose exec': (('-e', '--env', '-u', '--user', '-w', '--workdir', '--index'),
  1089. ('-T', '--no-TTY', '-d', '--detach', '--privileged'), 'Td'),
  1090. 'compose run': (('-e', '--env', '-u', '--user', '-w', '--workdir', '-v', '--volume',
  1091. '-p', '--publish', '--name', '--entrypoint', '-l', '--label',
  1092. '--cap-add', '--cap-drop', '--pull'),
  1093. ('--rm', '-T', '--no-TTY', '-d', '--detach', '--no-deps',
  1094. '--service-ports', '--use-aliases', '--build', '--quiet-pull',
  1095. '-i', '--interactive', '-t', '--tty'), 'Tdit'),
  1096. }
  1097. _XARGS_OPTIONS = (('-I', '-n', '-P', '-L', '-d', '-E', '-s', '-a', '--max-args',
  1098. '--max-procs', '--max-lines', '--delimiter', '--arg-file',
  1099. '--max-chars'),
  1100. ('-0', '--null', '-r', '--no-run-if-empty', '-t', '--verbose', '-p',
  1101. '--interactive', '-x', '--exit', '-o', '--open-tty', '--replace'),
  1102. '0rtpxo')
  1103. _WATCH_OPTIONS = (('-n', '--interval'),
  1104. ('-d', '--differences', '-t', '--no-title', '-b', '--beep', '-e',
  1105. '--errexit', '-g', '--chgexit', '-c', '--color', '-x', '--exec',
  1106. '-p', '--precise', '-w', '--no-wrap'), 'dtbegcxpw')
  1107. _TMUX_GLOBAL = (('-L', '-S', '-f', '-c', '-T'), ('-2', '-u', '-v', '-C', '-D', '-l', '-N'),
  1108. '2uvCDlN')
  1109. # tmux subcommands whose arguments are typed into, or run by, a shell.
  1110. _TMUX_COMMAND_VERBS = frozenset((
  1111. 'send-keys', 'send', 'new-session', 'new', 'new-window', 'neww', 'split-window',
  1112. 'splitw', 'respawn-pane', 'respawnp', 'respawn-window', 'respawnw', 'run-shell',
  1113. 'run', 'display-popup', 'popup'))
  1114. _TMUX_VALUE_OPTIONS = frozenset(('-t', '-s', '-n', '-c', '-e', '-F', '-x', '-y'))
  1115. _FIND_EXEC = frozenset(('-exec', '-execdir', '-ok', '-okdir'))
  1116. _LAUNCHERS = _CONTAINER_TOOLS | frozenset(('kubectl', 'xargs', 'watch', 'find', 'tmux'))
  1117. # Programs that also run their arguments but are not interpreted here.
  1118. _UNREAD_LAUNCHERS = frozenset(('parallel', 'script', 'flock', 'chroot', 'screen'))
  1119. _TUTORIAL_PACKAGES = frozenset(('example_interfaces', 'action_tutorials_interfaces',
  1120. 'turtlesim', 'test_msgs'))
  1121. _TURTLE_SEGMENT = re.compile(r'turtle\d*\Z')
  1122. _MOTION_TOPIC = re.compile(
  1123. r'(?:cmd_vel\w*|\w+_cmd_vel|cmd_ackermann|ackermann_cmd\w*|joint_trajectory'
  1124. r'|joint_commands?|joint_jog|(?:position|velocity|effort)_commands?'
  1125. r'|delta_twist_cmds|delta_joint_cmds)\Z')
  1126. _MOTION_MESSAGES = frozenset(('Twist', 'TwistStamped', 'JointTrajectory',
  1127. 'MultiDOFJointTrajectory', 'AckermannDrive',
  1128. 'AckermannDriveStamped', 'JointJog'))
  1129. _MOTION_ACTIONS = frozenset((
  1130. 'NavigateToPose', 'NavigateThroughPoses', 'FollowPath', 'FollowWaypoints',
  1131. 'FollowGPSWaypoints', 'Spin', 'BackUp', 'DriveOnHeading', 'AssistedTeleop',
  1132. 'FollowJointTrajectory', 'MoveGroup', 'MoveGroupSequence', 'ExecuteTrajectory',
  1133. 'GripperCommand', 'ParallelGripperCommand', 'DockRobot', 'UndockRobot'))
  1134. _MOTION_ACTION_NAME = re.compile(
  1135. r'(?:navigate_to_pose|navigate_through_poses|follow_path|follow_waypoints|spin'
  1136. r'|backup|drive_on_heading|follow_joint_trajectory|move_action|execute_trajectory'
  1137. r'|gripper_cmd|gripper_action|dock_robot|undock_robot)\Z')
  1138. _STOP_PATH_SERVICE = re.compile(
  1139. r'e_?stop|emergency|clear_faults?|clear_errors?|reset_faults?|reset_errors?'
  1140. r'|brake|motor|torque|servo|actuator|arming|disarm|takeoff'
  1141. r'|(?<![a-z])arm(?![a-z])|(?<![a-z])land(?![a-z])')
  1142. _CONTROLLER_SERVICE = re.compile(
  1143. r'(?:switch_controller|load_controller|unload_controller|configure_controller'
  1144. r'|set_hardware_component_state)\Z')
  1145. _GATE_PARAMETER = re.compile(
  1146. r'(?:max|min)[_.]?\w*(?:vel|speed|acc|decel|jerk|effort|torque|current)'
  1147. r'|limit|timeout|watchdog|deadman|safety|e_?stop|collision', re.IGNORECASE)
  1148. _TOPIC_PUB_VALUE_OPTIONS = frozenset((
  1149. '-r', '--rate', '-p', '--print', '-t', '--times', '-w',
  1150. '--wait-matching-subscriptions', '--keep-alive', '-n', '--node-name',
  1151. '--max-wait-time-secs', '--yaml-file', '--spin-time'))
  1152. _SEND_GOAL_VALUE_OPTIONS = frozenset(('-t', '--timeout', '--spin-time'))
  1153. _SERVICE_CALL_VALUE_OPTIONS = frozenset(('-r', '--rate', '--timeout', '--spin-time'))
  1154. _CONTROL_VALUE_OPTIONS = frozenset((
  1155. '-c', '--controller-manager', '--activate', '--deactivate', '--start', '--stop',
  1156. '--set-state', '--switch-timeout', '--spin-time', '--param-file', '-p'))
  1157. _ACTUATION_ADVICE = (
  1158. ' Not blocked. Confirm explicit authorization, an operator, and an independent '
  1159. 'stop path before running it; see references/safety-estop.md and '
  1160. 'references/evidence-progression.md section 2')
  1161. class _Unparsed(Exception):
  1162. """The scanner met shell syntax it does not interpret."""
  1163. class _Analysis:
  1164. def __init__(self):
  1165. # (words, here-documents, depth, meta); a word is (text, dynamic) and
  1166. # meta holds the word spans in the scanned text, whether the command
  1167. # redirects its output to a file, and the separator that ended it.
  1168. self.commands = []
  1169. self.executed = [] # (program, arguments) of every command that would run
  1170. self.grouped = False # a subshell or brace group appears at the top level
  1171. self.issues = []
  1172. self.reasons = []
  1173. def skip(self, reason):
  1174. if reason not in self.reasons:
  1175. self.reasons.append(reason)
  1176. def add(self, confidence, what):
  1177. message = (('Actuation command: ' if confidence == 'high' else 'Possible actuation: ')
  1178. + what[:200] + ' can move hardware or change a motion gate.'
  1179. + _ACTUATION_ADVICE)
  1180. if not any(issue['message'] == message for issue in self.issues):
  1181. self.issues.append({'file': '<bash>', 'line': 0, 'severity': 'warning',
  1182. 'message': message, 'category': 'actuation',
  1183. 'confidence': confidence})
  1184. def _balanced(text, start):
  1185. """Index just past the parenthesis matching the one at *start*."""
  1186. depth, i, n = 0, start, len(text)
  1187. while i < n:
  1188. char = text[i]
  1189. if char == '\\':
  1190. i += 2
  1191. continue
  1192. if char == "'":
  1193. end = text.find("'", i + 1)
  1194. if end < 0:
  1195. break
  1196. i = end + 1
  1197. continue
  1198. if char == '"':
  1199. i += 1
  1200. while i < n and text[i] != '"':
  1201. if text[i] == '\\':
  1202. i += 1
  1203. elif text.startswith('$(', i):
  1204. i = _balanced(text, i + 1) - 1
  1205. i += 1
  1206. if i >= n:
  1207. break
  1208. i += 1
  1209. continue
  1210. if char == '(':
  1211. depth += 1
  1212. elif char == ')':
  1213. depth -= 1
  1214. if depth == 0:
  1215. return i + 1
  1216. i += 1
  1217. raise _Unparsed('unbalanced quote or parenthesis')
  1218. def _scan_commands(text, depth, out):
  1219. """Split shell text into simple commands, keeping what quoting meant."""
  1220. if depth > _ACTUATION_MAX_DEPTH:
  1221. out.skip('command nesting is deeper than the analysis follows')
  1222. return
  1223. n = len(text)
  1224. words, heredocs, pending, spans = [], [], [], []
  1225. state = {'buf': [], 'word': False, 'dynamic': False, 'skip': False,
  1226. 'delimiter': None, 'quoted': False, 'pos': 0, 'start': 0,
  1227. 'redirect': '', 'to_file': False}
  1228. def literal(chunk):
  1229. if not state['word']:
  1230. state['start'] = state['pos']
  1231. state['buf'].append(chunk)
  1232. state['word'] = True
  1233. def end_word():
  1234. if not state['word']:
  1235. return
  1236. value = ''.join(state['buf'])
  1237. if state['delimiter'] is not None:
  1238. doc = {'delimiter': value, 'strip_tabs': state['delimiter'],
  1239. 'quoted': state['quoted'], 'body': None}
  1240. heredocs.append(doc)
  1241. pending.append(doc)
  1242. state['delimiter'] = None
  1243. elif state['skip']:
  1244. state['skip'] = False
  1245. if state['redirect'] == 'out' and value != '/dev/null':
  1246. state['to_file'] = True
  1247. else:
  1248. words.append((value, state['dynamic']))
  1249. spans.append((state['start'], state['pos']))
  1250. state.update(buf=[], word=False, dynamic=False, quoted=False)
  1251. def end_command(separator):
  1252. nonlocal words, heredocs, spans
  1253. end_word()
  1254. if words or heredocs:
  1255. out.commands.append((words, heredocs, depth, {
  1256. 'spans': spans, 'redirect_out': state['to_file'], 'sep': separator}))
  1257. if depth == 0 and any(text in ('{', '}') and not dynamic
  1258. for text, dynamic in words):
  1259. out.grouped = True
  1260. words, heredocs, spans = [], [], []
  1261. state.update(skip=False, delimiter=None, to_file=False)
  1262. def substitution(start, placeholder):
  1263. """`$(`, `<(` or `>(` at *start*: its commands run; return the next index."""
  1264. end = _balanced(text, start + 1)
  1265. _scan_commands(text[start + 2:end - 1], depth + 1, out)
  1266. literal(placeholder)
  1267. state['dynamic'] = True
  1268. return end
  1269. def dollar(i, in_double):
  1270. if text.startswith('$((', i):
  1271. end = _balanced(text, i + 1)
  1272. literal(text[i:end])
  1273. state['dynamic'] = True
  1274. return end
  1275. if text.startswith('$(', i):
  1276. return substitution(i, '$()')
  1277. if text.startswith('${', i):
  1278. end = text.find('}', i)
  1279. if end < 0:
  1280. raise _Unparsed('unbalanced parameter expansion')
  1281. literal(text[i:end + 1])
  1282. state['dynamic'] = True
  1283. return end + 1
  1284. if not in_double and text.startswith("$'", i):
  1285. j = i + 2
  1286. while j < n and text[j] != "'":
  1287. j += 2 if text[j] == '\\' else 1
  1288. if j >= n:
  1289. raise _Unparsed('unbalanced quote')
  1290. decoded = _decode_escapes(text[i + 2:j], 'ansi_c')
  1291. if decoded is None:
  1292. # An escape this does not model: the word is not known text.
  1293. literal(text[i + 2:j])
  1294. state['dynamic'] = True
  1295. else:
  1296. literal(decoded[0])
  1297. return j + 1
  1298. match = _VARIABLE.match(text, i + 1)
  1299. if not match:
  1300. literal('$')
  1301. return i + 1
  1302. literal(text[i:match.end()])
  1303. state['dynamic'] = True
  1304. return match.end()
  1305. def backtick(i):
  1306. j, inner = i + 1, []
  1307. while j < n and text[j] != '`':
  1308. if text[j] == '\\' and j + 1 < n:
  1309. j += 1
  1310. inner.append(text[j])
  1311. j += 1
  1312. if j >= n:
  1313. raise _Unparsed('unbalanced backtick')
  1314. _scan_commands(''.join(inner), depth + 1, out)
  1315. literal('$()')
  1316. state['dynamic'] = True
  1317. return j + 1
  1318. def heredoc_bodies(i):
  1319. for doc in pending:
  1320. lines = []
  1321. while True:
  1322. if i >= n:
  1323. out.skip('a here-document is not terminated')
  1324. del pending[:]
  1325. return n
  1326. end = text.find('\n', i)
  1327. end = n if end < 0 else end
  1328. line = text[i:end]
  1329. i = min(end + 1, n)
  1330. if (line.lstrip('\t') if doc['strip_tabs'] else line) == doc['delimiter']:
  1331. break
  1332. lines.append(line)
  1333. doc['body'] = '\n'.join(lines)
  1334. del pending[:]
  1335. return i
  1336. i = 0
  1337. while i < n:
  1338. char = text[i]
  1339. state['pos'] = i
  1340. if char == '\\':
  1341. if text.startswith('\\\n', i):
  1342. i += 2
  1343. continue
  1344. literal(text[i + 1:i + 2])
  1345. if state['delimiter'] is not None:
  1346. state['quoted'] = True
  1347. i += 2
  1348. elif char == "'":
  1349. end = text.find("'", i + 1)
  1350. if end < 0:
  1351. raise _Unparsed('unbalanced quote')
  1352. literal(text[i + 1:end])
  1353. if state['delimiter'] is not None:
  1354. state['quoted'] = True
  1355. i = end + 1
  1356. elif char == '"':
  1357. literal('')
  1358. if state['delimiter'] is not None:
  1359. state['quoted'] = True
  1360. i += 1
  1361. while i < n and text[i] != '"':
  1362. if text[i] == '\\' and i + 1 < n:
  1363. if text[i + 1] == '\n':
  1364. i += 2
  1365. elif text[i + 1] in '"\\$`':
  1366. literal(text[i + 1])
  1367. i += 2
  1368. else:
  1369. literal('\\')
  1370. i += 1
  1371. elif text[i] == '$':
  1372. i = dollar(i, True)
  1373. elif text[i] == '`':
  1374. i = backtick(i)
  1375. else:
  1376. literal(text[i])
  1377. i += 1
  1378. if i >= n:
  1379. raise _Unparsed('unbalanced quote')
  1380. i += 1
  1381. elif char == '$':
  1382. i = dollar(i, False)
  1383. elif char == '`':
  1384. i = backtick(i)
  1385. elif char in ' \t\r':
  1386. end_word()
  1387. i += 1
  1388. elif char == '\n':
  1389. end_command('\n')
  1390. i = heredoc_bodies(i + 1) if pending else i + 1
  1391. elif char == ';':
  1392. end_command(';')
  1393. i += 1
  1394. elif char == '&':
  1395. if text.startswith('&&', i):
  1396. end_command('&&')
  1397. i += 2
  1398. elif text.startswith('&>', i):
  1399. end_word()
  1400. i += 3 if text.startswith('&>>', i) else 2
  1401. state.update(skip=True, redirect='out')
  1402. else:
  1403. end_command('&')
  1404. i += 1
  1405. elif char == '|':
  1406. # `|` and `|&` connect a pipeline; `||` separates commands.
  1407. end_command('||' if text.startswith('||', i) else '|')
  1408. i += 2 if text[i + 1:i + 2] in ('|', '&') else 1
  1409. elif char in '()':
  1410. end_command(char)
  1411. if depth == 0:
  1412. out.grouped = True
  1413. i += 1
  1414. elif char in '<>':
  1415. if text.startswith(char + '(', i):
  1416. i = substitution(i, char + '()')
  1417. continue
  1418. if state['word'] and ''.join(state['buf']).isdigit() and not state['dynamic']:
  1419. state.update(buf=[], word=False) # a file descriptor, not a word
  1420. else:
  1421. end_word()
  1422. if text.startswith('<<<', i):
  1423. i += 3
  1424. state.update(skip=True, redirect='in')
  1425. elif text.startswith('<<', i):
  1426. i += 2
  1427. strip = text[i:i + 1] == '-'
  1428. i += 1 if strip else 0
  1429. state['delimiter'] = strip
  1430. else:
  1431. kind = 'out' if char == '>' else 'in'
  1432. i += 1
  1433. if text[i:i + 1] in ('>', '|'):
  1434. i += 1
  1435. if text[i:i + 1] == '&':
  1436. i += 1
  1437. kind = 'dup' # `>&2`, `2>&1`: a descriptor, not a file
  1438. state.update(skip=True, redirect=kind)
  1439. elif char == '#' and not state['word']:
  1440. end = text.find('\n', i)
  1441. i = n if end < 0 else end
  1442. else:
  1443. literal(char)
  1444. i += 1
  1445. state['pos'] = n
  1446. end_command('end')
  1447. if pending:
  1448. out.skip('a here-document is not terminated')
  1449. def _scan_heredoc_substitutions(body, depth, out):
  1450. """An unquoted here-document expands `$(...)` and backticks before use."""
  1451. i, n = 0, len(body)
  1452. while i < n:
  1453. if body[i] == '\\':
  1454. i += 2
  1455. elif body.startswith('$((', i):
  1456. i = _balanced(body, i + 1)
  1457. elif body.startswith('$(', i):
  1458. end = _balanced(body, i + 1)
  1459. _scan_commands(body[i + 2:end - 1], depth + 1, out)
  1460. i = end
  1461. elif body[i] == '`':
  1462. end = body.find('`', i + 1)
  1463. if end < 0:
  1464. raise _Unparsed('unbalanced backtick')
  1465. _scan_commands(body[i + 1:end], depth + 1, out)
  1466. i = end + 1
  1467. else:
  1468. i += 1
  1469. def _strip_wrapper(name, rest):
  1470. """Words after a wrapper's own options: `sudo -u $USER`, `timeout $T`."""
  1471. value_options, positionals = _WRAPPERS[name]
  1472. i = 0
  1473. while i < len(rest):
  1474. text = rest[i][0]
  1475. if text == '--':
  1476. i += 1
  1477. break
  1478. if name == 'env' and _ASSIGNMENT.match(text):
  1479. i += 1
  1480. elif text.startswith('-') and len(text) > 1:
  1481. # A value is consumed whether or not it is literal.
  1482. i += 2 if text in value_options else 1
  1483. else:
  1484. break
  1485. return rest[i + positionals:]
  1486. def _skip_options(words, value_options, flags, bundle=''):
  1487. """Index of the first word that is not an option, or None.
  1488. None means an option outside the table was met. Whether it takes a value
  1489. cannot be known, so the position of the executed program is unknown too;
  1490. the caller reports that instead of assuming either answer.
  1491. """
  1492. i = 0
  1493. while i < len(words):
  1494. text, dynamic = words[i]
  1495. if dynamic or not text.startswith('-') or len(text) == 1:
  1496. return i
  1497. if text == '--':
  1498. return i + 1
  1499. if text in value_options:
  1500. i += 2
  1501. elif (text in flags or (text.startswith('--') and '=' in text)
  1502. or (not text.startswith('--') and text[:2] in value_options) # -eA=1
  1503. or (bundle and re.fullmatch('-[' + bundle + ']+', text))):
  1504. i += 1
  1505. else:
  1506. return None
  1507. return i
  1508. def _mentions_ros2(words):
  1509. return any(not dynamic and ('ros2' in text or os.path.basename(text) in _SHELLS)
  1510. for text, dynamic in words)
  1511. def _launched_argv(name, rest):
  1512. """The argv a launcher runs: a list (possibly empty), or None when unknown."""
  1513. if name in _CONTAINER_TOOLS:
  1514. verb, args = '', rest
  1515. if name != 'docker-compose':
  1516. i = _skip_options(rest, *_DOCKER_GLOBAL)
  1517. if i is None:
  1518. return None
  1519. if i >= len(rest) or rest[i][1]:
  1520. return []
  1521. verb, args = rest[i][0], rest[i + 1:]
  1522. if name == 'docker-compose' or verb == 'compose':
  1523. i = _skip_options(args, *_COMPOSE_GLOBAL)
  1524. if i is None:
  1525. return None
  1526. if i >= len(args) or args[i][1]:
  1527. return []
  1528. verb, args = 'compose ' + args[i][0], args[i + 1:]
  1529. if verb not in _CONTAINER_VERBS:
  1530. return [] # logs, ps, build, ...: nothing is executed
  1531. i = _skip_options(args, *_CONTAINER_VERBS[verb])
  1532. if i is None:
  1533. return None
  1534. argv = args[i + 1:] # after the container, image or service name
  1535. options = [text for text, _dynamic in args[:i]]
  1536. for index, text in enumerate(options):
  1537. # The image arguments become the arguments of the entry point.
  1538. if text == '--entrypoint' and index + 1 < i:
  1539. return [args[index + 1]] + argv
  1540. if text.startswith('--entrypoint='):
  1541. return [(text.split('=', 1)[1], args[index][1])] + argv
  1542. return argv
  1543. if name == 'kubectl':
  1544. texts = [text for text, dynamic in rest if not dynamic]
  1545. if 'exec' not in texts:
  1546. return []
  1547. for index, (text, dynamic) in enumerate(rest):
  1548. if text == '--' and not dynamic:
  1549. return rest[index + 1:]
  1550. return None # `kubectl exec pod cmd` without `--`: the split is ambiguous
  1551. if name == 'xargs':
  1552. i = _skip_options(rest, *_XARGS_OPTIONS)
  1553. return None if i is None else rest[i:]
  1554. return []
  1555. def _inspect_launcher(name, rest, heredocs, depth, out):
  1556. """A program that runs other programs; True when here-documents were consumed."""
  1557. if name == 'find':
  1558. for index, (text, dynamic) in enumerate(rest):
  1559. if not dynamic and text in _FIND_EXEC:
  1560. argv = []
  1561. for word in rest[index + 1:]:
  1562. if not word[1] and word[0] in (';', '+'):
  1563. break
  1564. argv.append(word)
  1565. _inspect_command(argv, [], depth, out)
  1566. return False
  1567. if name == 'watch':
  1568. i = _skip_options(rest, *_WATCH_OPTIONS)
  1569. if i is None:
  1570. if _mentions_ros2(rest):
  1571. out.skip('an unrecognized watch option hides the command position')
  1572. elif i < len(rest):
  1573. # watch hands its arguments, joined, to `sh -c`.
  1574. _scan_commands(' '.join(text for text, _dynamic in rest[i:]), depth + 1, out)
  1575. return False
  1576. if name == 'tmux':
  1577. i = _skip_options(rest, *_TMUX_GLOBAL)
  1578. if i is None:
  1579. if _mentions_ros2(rest):
  1580. out.skip('an unrecognized tmux option hides the command position')
  1581. return False
  1582. if i >= len(rest) or rest[i][1] or rest[i][0] not in _TMUX_COMMAND_VERBS:
  1583. return False
  1584. args, index = rest[i + 1:], 0
  1585. while index < len(args):
  1586. text, dynamic = args[index]
  1587. if not dynamic and text in _TMUX_VALUE_OPTIONS:
  1588. index += 2 # `-t "$PANE"`: a target, not a command
  1589. continue
  1590. if dynamic:
  1591. out.skip('a command string built at run time is not inspected')
  1592. elif text == 'ros2':
  1593. _scan_commands(' '.join(word for word, _dynamic in args[index:]),
  1594. depth + 1, out)
  1595. break
  1596. elif 'ros2' in text:
  1597. _scan_commands(text, depth + 1, out)
  1598. index += 1
  1599. return False
  1600. argv = _launched_argv(name, rest)
  1601. if argv is None:
  1602. if _mentions_ros2(rest):
  1603. out.skip('an unrecognized ' + name + ' option hides the command position')
  1604. return False
  1605. return _inspect_command(argv, heredocs, depth, out)
  1606. def _positionals(args, value_options):
  1607. """Positional words of a ros2 verb, skipping options and their values."""
  1608. result, i = [], 0
  1609. while i < len(args):
  1610. text, dynamic = args[i]
  1611. if not dynamic and text.startswith('-') and len(text) > 1:
  1612. takes_value = '=' not in text and (
  1613. text in value_options or text.startswith('--qos-'))
  1614. i += 2 if takes_value else 1
  1615. continue
  1616. result.append(args[i])
  1617. i += 1
  1618. return result
  1619. def _segments(name):
  1620. return [part for part in name.lower().strip('/').split('/') if part]
  1621. def _interface(type_name):
  1622. """('pkg', 'Name') from pkg/msg/Name, pkg/Name or a bare Name."""
  1623. parts = [part for part in type_name.split('/') if part]
  1624. return (parts[0] if len(parts) > 1 else '', parts[-1] if parts else '')
  1625. def _is_tutorial(name, type_name):
  1626. return (_interface(type_name)[0] in _TUTORIAL_PACKAGES
  1627. or any(_TURTLE_SEGMENT.match(part) for part in _segments(name)))
  1628. def _classify_ros2(args, out):
  1629. """Judge one `ros2 ...` invocation; *args* excludes the program name."""
  1630. if len(args) < 2:
  1631. return
  1632. if args[0][1] or args[1][1]:
  1633. out.skip('ros2 verb is not literal')
  1634. return
  1635. verb, sub, rest = args[0][0], args[1][0], args[2:]
  1636. def named(words, count):
  1637. """(texts, any dynamic) of the first *count* positionals; missing ones are ''."""
  1638. chosen = list(words[:count])
  1639. return ([text for text, _dynamic in chosen] + [''] * (count - len(chosen)),
  1640. any(dynamic for _text, dynamic in chosen))
  1641. # In every branch the literal part is classified first: `/$NS/cmd_vel` ends
  1642. # in a motion topic whatever the namespace expands to. Only when nothing
  1643. # matches and a name is not literal is the command reported as unread.
  1644. if (verb, sub) == ('topic', 'pub'):
  1645. (topic, type_name), dynamic = named(_positionals(rest, _TOPIC_PUB_VALUE_OPTIONS), 2)
  1646. if _is_tutorial(topic, type_name):
  1647. return
  1648. parts = _segments(topic)
  1649. controller_command = (len(parts) >= 2 and parts[-2].endswith('controller')
  1650. and parts[-1] in ('commands', 'command', 'reference'))
  1651. if (controller_command or (parts and _MOTION_TOPIC.match(parts[-1]))
  1652. or _interface(type_name)[1] in _MOTION_MESSAGES):
  1653. out.add('high', '`ros2 topic pub` to ' + (topic or 'a ' + type_name + ' topic'))
  1654. elif dynamic:
  1655. # A harmless-looking type does not settle it: controller command
  1656. # topics carry plain std_msgs arrays.
  1657. out.skip('ros2 topic pub target is not literal')
  1658. elif (verb, sub) == ('action', 'send_goal'):
  1659. (name, type_name), dynamic = named(_positionals(rest, _SEND_GOAL_VALUE_OPTIONS), 2)
  1660. if _is_tutorial(name, type_name):
  1661. return
  1662. parts = _segments(name)
  1663. if (_interface(type_name)[1] in _MOTION_ACTIONS
  1664. or (parts and _MOTION_ACTION_NAME.match(parts[-1]))):
  1665. out.add('high', '`ros2 action send_goal` to ' + (name or type_name))
  1666. elif dynamic:
  1667. out.skip('ros2 action send_goal target is not literal')
  1668. else:
  1669. out.add('low', '`ros2 action send_goal` to ' + (name or 'an action')
  1670. + ' may command motion, and if it does it')
  1671. elif (verb, sub) == ('service', 'call'):
  1672. (name, type_name), dynamic = named(_positionals(rest, _SERVICE_CALL_VALUE_OPTIONS), 2)
  1673. if _is_tutorial(name, type_name):
  1674. return
  1675. parts = _segments(name)
  1676. if (_STOP_PATH_SERVICE.search(name.lower())
  1677. or (parts and _CONTROLLER_SERVICE.match(parts[-1]))):
  1678. out.add('high', '`ros2 service call` to ' + name)
  1679. elif dynamic:
  1680. out.skip('ros2 service call target is not literal')
  1681. elif verb == 'control':
  1682. if sub in ('switch_controllers', 'set_controller_state',
  1683. 'set_hardware_component_state'):
  1684. out.add('high', '`ros2 control ' + sub + '`')
  1685. elif sub == 'load_controller':
  1686. texts = [text for text, _dynamic in rest]
  1687. if any(text in ('--set-state=active', '--set-state=start') for text in texts) or any(
  1688. text == '--set-state' and following in ('active', 'start')
  1689. for text, following in zip(texts, texts[1:])):
  1690. out.add('high', '`ros2 control load_controller --set-state active`')
  1691. elif (verb, sub) == ('lifecycle', 'set'):
  1692. (node, transition), dynamic = named(
  1693. _positionals(rest, frozenset(('--spin-time',))), 2)
  1694. if dynamic:
  1695. out.skip('ros2 lifecycle set target is not literal')
  1696. elif transition == 'activate':
  1697. out.add('low', '`ros2 lifecycle set ' + node + ' activate` may enable '
  1698. 'a driver or controller, and if it does it')
  1699. elif (verb, sub) == ('param', 'set'):
  1700. (node, parameter), dynamic = named(
  1701. _positionals(rest, frozenset(('--spin-time',))), 2)
  1702. if _GATE_PARAMETER.search(parameter):
  1703. out.add('high', '`ros2 param set` of ' + parameter + ' on ' + node)
  1704. elif dynamic:
  1705. out.skip('ros2 param set target is not literal')
  1706. elif verb == 'run':
  1707. words = [sub] + [text for text, dynamic in rest[:1] if not dynamic]
  1708. if any('teleop' in word.lower() for word in words):
  1709. out.add('high', '`ros2 run` of a teleoperation node')
  1710. def _inspect_shell(rest, heredocs, depth, out):
  1711. """A shell invocation; True when its here-documents were read as scripts."""
  1712. i, saw_c, reads_stdin = 0, False, False
  1713. while i < len(rest):
  1714. text, dynamic = rest[i]
  1715. if dynamic:
  1716. break
  1717. if text == '--':
  1718. i += 1
  1719. break
  1720. if text.startswith('--'):
  1721. i += 2 if text in ('--rcfile', '--init-file') else 1
  1722. elif text in ('-o', '+o', '-O', '+O'):
  1723. i += 2
  1724. elif re.fullmatch(r'[-+][A-Za-z]+', text):
  1725. if text[0] == '-':
  1726. saw_c = saw_c or 'c' in text
  1727. reads_stdin = reads_stdin or 's' in text
  1728. i += 1
  1729. else:
  1730. break
  1731. if saw_c:
  1732. if i < len(rest):
  1733. _scan_commands(rest[i][0], depth + 1, out)
  1734. return False
  1735. if i < len(rest) and not reads_stdin:
  1736. return False # a script file: its contents are not visible here
  1737. bodies = [doc['body'] for doc in heredocs if doc['body'] is not None]
  1738. for body in bodies:
  1739. _scan_commands(body, depth + 1, out)
  1740. if not bodies:
  1741. out.skip('commands fed to a shell on standard input are not inspected')
  1742. return True
  1743. def _inspect_command(words, heredocs, depth, out):
  1744. """Judge one simple command; True when here-documents were consumed."""
  1745. args = list(words)
  1746. while args:
  1747. text, dynamic = args[0]
  1748. if _ASSIGNMENT.match(text):
  1749. # `ROS_DOMAIN_ID=$DOMAIN ros2 ...`: the value may be dynamic, the
  1750. # program that runs is still the next word.
  1751. args.pop(0)
  1752. elif dynamic:
  1753. break
  1754. elif text in _RESERVED:
  1755. args.pop(0)
  1756. elif os.path.basename(text) in _WRAPPERS:
  1757. args = _strip_wrapper(os.path.basename(text), args[1:])
  1758. else:
  1759. break
  1760. if not args:
  1761. return False
  1762. head, dynamic = args[0]
  1763. rest = args[1:]
  1764. name = os.path.basename(head)
  1765. if dynamic and ('$' in name or not name):
  1766. # What runs is decided at run time. `$HOME/bin/ros2` is still ros2;
  1767. # `$CMD`, `$(which tool)` and `"$PREFIX"` are not known.
  1768. out.skip('the command name is a variable or substitution')
  1769. return False
  1770. out.executed.append((name, rest))
  1771. if name == 'ros2':
  1772. _classify_ros2(rest, out)
  1773. elif name in _SHELLS:
  1774. return _inspect_shell(rest, heredocs, depth, out)
  1775. elif name == 'ssh':
  1776. i = 0
  1777. while i < len(rest) and not rest[i][1] and rest[i][0].startswith('-'):
  1778. i += 2 if rest[i][0] in _SSH_VALUE_OPTIONS else 1
  1779. remote = rest[i + 1:]
  1780. if remote:
  1781. _scan_commands(' '.join(text for text, _dynamic in remote), depth + 1, out)
  1782. else:
  1783. for doc in heredocs:
  1784. if doc['body'] is not None:
  1785. _scan_commands(doc['body'], depth + 1, out)
  1786. return True
  1787. elif name == 'su':
  1788. for index, (text, _dynamic) in enumerate(rest[:-1]):
  1789. if text in ('-c', '--command'):
  1790. _scan_commands(rest[index + 1][0], depth + 1, out)
  1791. elif name == 'eval':
  1792. # The literal part is judged. A dynamic part can expand to separators
  1793. # and further commands, so the result is also marked as incomplete.
  1794. _scan_commands(' '.join(text for text, _dynamic in rest), depth + 1, out)
  1795. if any(dyn for _text, dyn in rest):
  1796. out.skip('eval builds its command at run time')
  1797. elif name in _LAUNCHERS:
  1798. return _inspect_launcher(name, rest, heredocs, depth, out)
  1799. elif name in _UNREAD_LAUNCHERS and _mentions_ros2(rest):
  1800. out.skip('arguments of ' + name + ' are not inspected')
  1801. return False
  1802. def _traverse(command, out):
  1803. """Scan *command* and visit every command in it that would run."""
  1804. _scan_commands(command, 0, out)
  1805. index = 0
  1806. while index < len(out.commands):
  1807. words, heredocs, depth, _meta = out.commands[index]
  1808. index += 1
  1809. if not _inspect_command(words, heredocs, depth, out):
  1810. for doc in heredocs:
  1811. if doc['body'] is not None and not doc['quoted']:
  1812. _scan_heredoc_substitutions(doc['body'], depth, out)
  1813. def analyze_actuation(command, tool_name='bash'):
  1814. """Classify what a shell command would do to a robot.
  1815. Returns {'status', 'confidence', 'reasons', 'issues'}. status is 'detected'
  1816. when at least one finding exists, 'not_evaluated' when the command names
  1817. ros2 but could not be judged, 'off' when disabled, otherwise 'none'.
  1818. """
  1819. result = {'status': 'none', 'confidence': None, 'reasons': [], 'issues': []}
  1820. if os.environ.get(ACTUATION_ENV, '').strip().lower() == 'off':
  1821. result['status'] = 'off'
  1822. return result
  1823. if not isinstance(command, str) or 'ros2' not in command:
  1824. return result
  1825. out = _Analysis()
  1826. family = tool_name.lower().rstrip('_').split('__')[-1]
  1827. if family not in _POSIX_TOOLS:
  1828. out.skip('only POSIX shell commands are analyzed, not ' + (family or 'this tool'))
  1829. elif len(command) > _ACTUATION_MAX_CHARS:
  1830. out.skip('the command is longer than the analysis reads')
  1831. else:
  1832. try:
  1833. _traverse(command, out)
  1834. except _Unparsed as exc:
  1835. out.skip(str(exc))
  1836. except RecursionError:
  1837. out.skip('command nesting is deeper than the analysis follows')
  1838. result['issues'] = out.issues
  1839. result['reasons'] = out.reasons
  1840. if out.issues:
  1841. result['status'] = 'detected'
  1842. result['confidence'] = ('high' if any(
  1843. issue['confidence'] == 'high' for issue in out.issues) else 'low')
  1844. elif out.reasons:
  1845. result['status'] = 'not_evaluated'
  1846. return result
  1847. def _actuation_report(analysis):
  1848. """The part of an analysis that goes into the JSON report."""
  1849. return {key: analysis[key] for key in ('status', 'confidence', 'reasons')}
  1850. def _read_hook_payload():
  1851. """Resolve (tool_name, tool_input_dict, cwd, debug_info) from the harness.
  1852. Stdin is consumed here, once. A caller that also needs `cwd` must use this
  1853. function instead of calling _read_tool_context() a second time.
  1854. Real Claude Code (verified 2026-05-21 by capturing actual hook fires)
  1855. sends the full hook payload as a JSON object on STDIN, NOT via env vars.
  1856. The payload shape is::
  1857. {
  1858. "session_id": "...",
  1859. "transcript_path": "...",
  1860. "cwd": "...",
  1861. "hook_event_name": "PreToolUse",
  1862. "tool_name": "Bash",
  1863. "tool_input": { "command": "...", "description": "..." },
  1864. "tool_use_id": "toolu_..."
  1865. }
  1866. Note `tool_input` is already a parsed object, NOT a JSON string.
  1867. For backwards-compatible mock testing (the existing pytest suite uses
  1868. env vars), we fall back to `TOOL_NAME` and `TOOL_INPUT` (where
  1869. `TOOL_INPUT` is a JSON-encoded string) if stdin is empty or absent.
  1870. """
  1871. debug = {'source': None}
  1872. if not sys.stdin.isatty():
  1873. try:
  1874. raw = sys.stdin.read()
  1875. except Exception: # noqa: BLE001 - stdin read can fail many ways
  1876. raw = ''
  1877. if raw.strip():
  1878. try:
  1879. payload = json.loads(raw)
  1880. if isinstance(payload, dict):
  1881. debug['source'] = 'stdin'
  1882. debug['payload_keys'] = sorted(payload.keys())
  1883. tool_name = str(payload.get('tool_name') or '')
  1884. tool_input = payload.get('tool_input') or {}
  1885. if not isinstance(tool_input, dict):
  1886. # Defensive: future schema versions might wrap it.
  1887. tool_input = {}
  1888. cwd = payload.get('cwd')
  1889. if not isinstance(cwd, str) or not cwd.strip():
  1890. cwd = ''
  1891. return tool_name, tool_input, cwd, debug
  1892. except json.JSONDecodeError as e:
  1893. debug['stdin_parse_error'] = str(e)
  1894. debug['source'] = 'env'
  1895. tool_name = os.environ.get('TOOL_NAME', '')
  1896. raw_env = os.environ.get('TOOL_INPUT', '')
  1897. tool_input: dict = {}
  1898. if raw_env:
  1899. try:
  1900. parsed = json.loads(raw_env)
  1901. if isinstance(parsed, dict):
  1902. tool_input = parsed
  1903. except json.JSONDecodeError as e:
  1904. debug['env_parse_error'] = str(e)
  1905. return tool_name, tool_input, '', debug
  1906. def _read_tool_context():
  1907. """(tool_name, tool_input_dict, debug_info): _read_hook_payload() without cwd."""
  1908. tool_name, tool_input, _cwd, debug = _read_hook_payload()
  1909. return tool_name, tool_input, debug
  1910. def _manual_check_files(paths):
  1911. """Check files named on the command line, without the event hook's
  1912. silent-skip behavior.
  1913. The event-mode ``check_file`` swallows read errors because a file can
  1914. legitimately vanish mid-edit; in manual mode a path the user explicitly
  1915. named must never produce a false pass. Check order matters: existence
  1916. before the extension filter, so a missing ``missing.txt`` is reported
  1917. as an error rather than misclassified as an unsupported-extension skip.
  1918. Returns (issues, checks_skipped). Never aborts early — every path is
  1919. examined so one bad file does not hide findings in the others.
  1920. """
  1921. issues = []
  1922. skipped = []
  1923. for path in paths:
  1924. if not os.path.exists(path):
  1925. issues.append({
  1926. 'file': path,
  1927. 'line': 0,
  1928. 'severity': 'error',
  1929. 'message': 'File not found',
  1930. })
  1931. continue
  1932. if not os.path.isfile(path):
  1933. issues.append({
  1934. 'file': path,
  1935. 'line': 0,
  1936. 'severity': 'error',
  1937. 'message': 'Not a regular file (directories are not scanned)',
  1938. })
  1939. continue
  1940. ext = os.path.splitext(path)[1]
  1941. if ext not in CHECKABLE_EXTENSIONS:
  1942. skipped.append(
  1943. f'{path}: unsupported extension {ext or "(none)"} — '
  1944. f'checked extensions: '
  1945. f'{", ".join(sorted(CHECKABLE_EXTENSIONS))}')
  1946. continue
  1947. try:
  1948. with open(path, 'r', encoding='utf-8') as fh:
  1949. content = fh.read()
  1950. except (OSError, UnicodeError) as exc:
  1951. issues.append({
  1952. 'file': path,
  1953. 'line': 0,
  1954. 'severity': 'error',
  1955. 'message': f'Cannot read file: {exc}',
  1956. })
  1957. continue
  1958. issues.extend(check_content(content, path))
  1959. return issues, skipped
  1960. def _event_mode_issues():
  1961. """Event-mode checks; returns (issues, tool_name, tool_input, debug,
  1962. actuation analysis)."""
  1963. tool_name, tool_input, cwd, debug = _read_hook_payload()
  1964. issues = []
  1965. actuation = analyze_actuation('')
  1966. # Normalize tool name for resilient matching across runtime variations.
  1967. # This avoids silent bypass if the harness ever changes casing or adds
  1968. # prefixes (e.g. "write" vs "Write", "mcp__server__write", "bash_tool").
  1969. tool_name_lower = tool_name.lower().rstrip('_')
  1970. if tool_name_lower.startswith('mcp__'):
  1971. # MCP tools are named mcp__<server>__<tool>; match on the tool part.
  1972. tool_name_lower = tool_name_lower.split('__')[-1]
  1973. # If the tool is writing or editing a file, validate the content.
  1974. # NOTE: Claude Code uses tool names: Write, Edit, MultiEdit, NotebookEdit.
  1975. if tool_name_lower in (
  1976. 'write', 'edit', 'multiedit', 'notebookedit',
  1977. 'create_file', 'write_file',
  1978. ) and tool_input:
  1979. filepath = tool_input.get('file_path', '') or tool_input.get('path', '')
  1980. # MultiEdit carries a list of edits — flatten content checks across them.
  1981. if tool_name_lower == 'multiedit':
  1982. content_parts = [
  1983. e.get('new_string', '')
  1984. for e in (tool_input.get('edits') or [])
  1985. if isinstance(e, dict)
  1986. ]
  1987. content = '\n'.join(p for p in content_parts if p)
  1988. else:
  1989. content = (tool_input.get('content', '')
  1990. or tool_input.get('new_string', ''))
  1991. # Same file types as check_file() and manual --file: these are
  1992. # source-code patterns. Prose (README.md, notes.txt), shell scripts and
  1993. # parameter files that mention time.sleep() or ROS_LOCALHOST_ONLY are
  1994. # not ROS 2 nodes. Unlike manual --file, where the user named the
  1995. # file, this runs unasked in every project, so it also requires
  1996. # confirmed ROS context; a payload without a path needs it in its text.
  1997. if not isinstance(filepath, str):
  1998. filepath = ''
  1999. ext = os.path.splitext(filepath)[1]
  2000. if (content and (not filepath or ext in CHECKABLE_EXTENSIONS)
  2001. and _has_ros_context(filepath, content, cwd)):
  2002. issues = check_content(content, filepath)
  2003. # For shell-style tools, check for dangerous patterns. Includes PowerShell
  2004. # variants so the same regex set protects Windows hosts where the agent's
  2005. # tool name surfaces as `PowerShell`/`pwsh` rather than `Bash`.
  2006. if tool_name_lower in (
  2007. 'bash', 'shell', 'command', 'terminal', 'powershell', 'pwsh', 'cmd',
  2008. ) and tool_input:
  2009. command = tool_input.get('command', '')
  2010. if command:
  2011. issues.extend(_check_dangerous_commands(command, tool_name_lower))
  2012. # The scanner reads POSIX shell syntax only; for the PowerShell
  2013. # and cmd aliases it reports the command as not evaluated.
  2014. actuation = analyze_actuation(command, tool_name_lower)
  2015. issues.extend(actuation['issues'])
  2016. return issues, tool_name, tool_input, debug, actuation
  2017. def main(argv=None):
  2018. """Entry point. *argv* defaults to sys.argv[1:]; tests that call main()
  2019. in-process pass an explicit list so the host runner's argv is ignored."""
  2020. parser = argparse.ArgumentParser(
  2021. description=('ROS 2 skill PreToolUse hook. Without arguments it '
  2022. 'consumes a Claude Code hook payload (event mode); '
  2023. 'with --file/--command it validates the named inputs '
  2024. 'directly (manual mode).'))
  2025. parser.add_argument(
  2026. '--file', nargs='+', metavar='PATH', default=None,
  2027. help='check the named source files for ROS 2 anti-patterns')
  2028. parser.add_argument(
  2029. '--command', metavar='CMD', default=None,
  2030. help=('inspect a shell command string for dangerous patterns and for '
  2031. 'ROS 2 commands that can move hardware; the string is analyzed '
  2032. 'only and never executed'))
  2033. parser.add_argument(
  2034. '--debug', action='store_true',
  2035. help='include payload-resolution debug info in the JSON result')
  2036. args = parser.parse_args(sys.argv[1:] if argv is None else argv)
  2037. manual_mode = bool(args.file) or args.command is not None
  2038. checks_skipped = []
  2039. debug = {}
  2040. tool_name = ''
  2041. tool_input = {}
  2042. if manual_mode:
  2043. issues = []
  2044. # Aggregate across ALL inputs — one failing file must not hide
  2045. # findings in the remaining files or in --command.
  2046. if args.file:
  2047. file_issues, checks_skipped = _manual_check_files(args.file)
  2048. issues.extend(file_issues)
  2049. actuation = analyze_actuation('')
  2050. if args.command is not None:
  2051. issues.extend(_check_dangerous_commands(args.command))
  2052. # Same analysis as event mode, so a manual check and the hook
  2053. # agree on what a command would do.
  2054. actuation = analyze_actuation(args.command)
  2055. issues.extend(actuation['issues'])
  2056. else:
  2057. issues, tool_name, tool_input, debug, actuation = _event_mode_issues()
  2058. # A command that names ros2 but could not be judged is not a clean pass.
  2059. checks_skipped = list(checks_skipped) + [
  2060. 'actuation: ' + reason for reason in actuation['reasons']]
  2061. result = {
  2062. 'hook': 'ros2-engineering-skills:pre-tool-use',
  2063. 'version': '1.5.0',
  2064. 'mode': 'manual' if manual_mode else 'event',
  2065. 'issues_count': len(issues),
  2066. 'issues': issues,
  2067. 'checks_skipped': checks_skipped,
  2068. 'actuation': _actuation_report(actuation),
  2069. 'status': 'fail' if any(
  2070. i['severity'] == 'error' for i in issues
  2071. ) else 'pass',
  2072. }
  2073. if args.debug and not manual_mode:
  2074. result['debug'] = {**debug, 'tool_name': tool_name,
  2075. 'tool_input_keys': sorted(tool_input.keys())}
  2076. has_errors = any(i['severity'] == 'error' for i in issues)
  2077. if has_errors and not manual_mode:
  2078. # Event mode, blocking: exit 2 is the only code Claude Code treats
  2079. # as a refusal, and it takes the reason from stderr. The report is
  2080. # deliberately NOT written to stdout here — this JSON is our own
  2081. # shape, not the documented hook-output schema, and emitting
  2082. # unrecognized JSON alongside a blocking exit has historically been
  2083. # the case where a block degrades into a warning. Saying nothing on
  2084. # stdout leaves only the one channel that is specified.
  2085. for issue in issues:
  2086. if issue['severity'] == 'error':
  2087. print(f"{issue['file']}: {issue['message']}", file=sys.stderr)
  2088. sys.exit(2)
  2089. # Non-blocking paths keep the machine-readable report: manual mode is a
  2090. # CLI whose output is the point, and a passing event-mode run has no
  2091. # exit-code contract to conflict with.
  2092. print(json.dumps(result, indent=2))
  2093. sys.exit(1 if has_errors else 0)
  2094. if __name__ == '__main__':
  2095. main()

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.