274 Commits
Author SHA1 Message Date
Даниил Грабарь ba807e710b change validator 2026-11-13 15:47:14 +10:00
Даниил Грабарь 0e86a4b72e fix(llm-plan-executor): use PTP/LIN with checked camera collisions 2026-11-11 12:34:54 +10:00
Даниил Грабарь 454a2014f3 fix(llm-plan-executor): use the known empty outcome after a missing-tool grasp 2026-11-11 11:52:21 +10:00
Даниил Грабарь 48c190d75b fix(llm-plan-executor): report missing tools as runtime grasp failures 2026-11-11 11:28:12 +10:00
Даниил Грабарь 112673f1f4 fix(llm-plan-executor): enforce safe motion and live scene state 2026-11-11 10:16:46 +10:00
Даниил Грабарь f84b644260 docs(plan): record the implemented LLM graph execution stage 2026-11-11 01:35:00 +10:00
Даниил Грабарь 3c4535c541 fix(llm-plan-executor): harden constrained planning and record Webots QA 2026-11-11 01:35:00 +10:00
Даниил Грабарь 37efb87a2b fix(scene-context): keep the published snapshot fresh and name real camera topics 2026-11-11 01:35:00 +10:00
Даниил Грабарь e7d280c11c feat(llm-plan-executor): add end-to-end planner launch and operator guide 2026-11-11 00:31:49 +10:00
Даниил Грабарь 5dc8d651f3 feat(web): expose planner scene and graph runs over HTTP and MCP 2026-11-11 00:28:04 +10:00
Даниил Грабарь 1e8856387b feat(llm-plan-executor): add graph engine and ROS submit/status/cancel node 2026-11-11 00:26:37 +10:00
Даниил Грабарь 2519514b02 feat(llm-plan-executor): execute Grant skills with verified phases 2026-11-11 00:20:29 +10:00
Даниил Грабарь 30c355ba6a feat(llm-plan-executor): constrain planned trajectories by J7 and TCP tilt 2026-11-11 00:17:13 +10:00
Даниил Грабарь 9ca08c01c2 feat(llm-plan-executor): parse and validate externally supplied graphs 2026-11-11 00:14:33 +10:00
Даниил Грабарь 3128191e6d feat(scene-context): publish the live coordinate-free scene contract 2026-11-11 00:11:06 +10:00
Даниил Грабарь d66c9d3fa2 feat(experement): add planner scene mode without reference runner 2026-11-11 00:08:42 +10:00
Даниил Грабарь cdda081b4f feat(experement): plan transfers with Pilz PTP instead of OMPL
- _contact transfer/approach and _retreat clear now use deterministic Pilz
  PTP joint interpolation; OMPL remains only the automatic fallback
- move_to_joints on the motion server tries PTP first, OMPL on failure
- verified in Webots execute mode: 1, 11, 14, 20 completed; no PTP failures
  in 1/11/14/20 server logs, OMPL used only as the fallback
2026-11-10 20:43:42 +10:00
Даниил Грабарь 7525e5f615 fix(experement): untwist after the lift, wait out controller lag, no gizmo in runs
- tighten_hole: lift out of the hole first, then return joint 7 (undoing the
  twist at the contact point visibly unscrewed the simulated tightening)
- motion: wait up to 8 s for the measured tcp to converge to the held goal
  instead of re-issuing it at once (the Webots controller reports success on
  the desired state while the arm still creeps; the re-issue looked like a
  violent 5-10 cm snap at dock and handoff transfers)
- reference launches disable the tcp gizmo in the temporary setting.yaml
  (cobot-setting.yaml only applies to 'cobot run')
- verified in Webots execute mode after these changes: 5, 11, 14, 15, 20
2026-11-10 18:58:26 +10:00
Даниил Грабарь b26edc3cfc fix(experement): honest collision poses, mandatory lifts, rest-to-rest waits; 20/20 verified
- forbid the transport pose; recovery reconfigures through work only
- mandatory axial lift after every contact (handoff, tighten, dock, pick)
- untwist the flange after simulated tightening so joint 7 never winds up
- attach carried tool/cap/screw to the MoveIt scene; explicit REMOVE diffs
- add_world receives box-centre poses (placed_cap_pose, restore_world)
- table top lowered below the base_link collision mesh bottom (1 mm gap bug)
- 1 mm clearances for cap/screw boxes; thinner cap world box (cup clearance)
- wait for a stationary arm before every planning attempt (rest-to-rest)
- loosen stopped_velocity_tolerance to 0.08 for reference launches only
- retry a rejected named move once after settling (startup telemetry race)
- adapter logs the exact reason and max joint velocity on start-state rejects
- verified: all 20 experiments completed in Webots execute mode (10.11.2026)
2026-11-10 15:11:06 +10:00
Даниил Грабарь 6bd288dcaf . 2026-11-09 17:52:41 +10:00
Даниил Грабарь 7462b7d301 docs(experement): record twenty completed runs with simulated tightening
Update the QA table with torque-tool returns for experiments 14-20, refresh the view-mode object counts and TCP drift, and document the transient-planning retry policy.
2026-11-09 04:13:11 +10:00
Даниил Грабарь 554fb571b8 fix(experement): tolerate an empty supervisor command result
The first command after startup can see last_command_result=null; read it defensively instead of calling get() on None.
2026-11-09 04:08:37 +10:00
Даниил Грабарь e4d2e48158 fix(experement): leave the dock even when the axial retreat is rejected
The tool is already docked before the retreat, so a rejected axial move can fall through to a graded +Y exit at a lower height instead of aborting the route.
2026-11-09 03:40:43 +10:00
Даниил Грабарь 41144ecd2a fix(experement): harden tool transfers and tightening at wrist limits
Exit the rack with a graded +Y move after taking or docking a tool, continue through home after a dock, and fall back from work to home when a joint plan is rejected. Wait for fresh zero-velocity joint states before planning and after joint motion, restore a screw to the planning scene before a pick retry, and twist only the flange joint while simulating tightening so the arm does not leave a reachable IK branch.
2026-11-09 01:29:36 +10:00
Даниил Грабарь a6c6474db9 feat(experement): simulate tightening and smooth tool transfers
Add a torque-tool tightening simulation for experiments 14-20: the tool approaches each empty hole, twists 60 degrees (reversing at the wrist limit), returns and retracts while the screw stays handed off. Lift attached tools vertically clear of the magazine before lateral motion, prefer the close 'work' pose between operations, and reconfigure through home only when planning fails. Settle measured joint positions before verifying joint moves.
2026-11-08 21:46:01 +10:00
Даниил Грабарь d0a9656bd2 docs(experement): record final test count 2026-11-08 20:13:41 +10:00
Даниил Грабарь 40d962a160 feat(experement): verify all twenty reference runs and finalize QA 2026-11-08 20:13:33 +10:00
Даниил Грабарь 7aa62f789c fix(experement): harden scene sync, cap grasp yaw and startup sequencing 2026-11-08 17:45:10 +10:00
Даниил Грабарь ec977c10ba feat(experement): complete reference routes, runner and QA documentation 2026-11-08 17:43:57 +10:00
Даниил Грабарь de8c2eb9ee feat(experement): implement reference operations and stable scene sync 2026-11-08 15:38:36 +10:00
Даниил Грабарь c58aa56757 feat(experement): add guarded motion adapter with pose verification 2026-11-08 14:02:55 +10:00
Даниил Грабарь 5a63420aa2 feat(experement): mirror Webots scene into MoveIt with attachments 2026-11-08 13:49:24 +10:00
Даниил Грабарь 51594f7c2f feat(experement): add Webots attachment supervisor and run modes 2026-11-08 13:36:34 +10:00
Даниил Грабарь 453fc03429 feat(experement): add calibrated grant working geometry 2026-11-08 13:19:52 +10:00
Даниил Грабарь a59a3f75b2 feat(experement): define reference experiment contract without tightening 2026-11-08 13:14:23 +10:00
Даниил Грабарь cdae71e2bc docs: clarify validation across reference control tasks 2026-11-08 12:53:14 +10:00
Даниил Грабарь fd1964a687 docs: translate grant reference plan to Russian 2026-11-08 12:41:33 +10:00
Даниил Грабарь b473b15e37 docs: plan grant reference experiment control 2026-11-08 12:33:26 +10:00
Даниил Грабарь ad0d354475 Востановлены все файлы конфигурации 2026-11-08 12:06:08 +10:00
Даниил Грабарь 923770ebbb fix: move screw tray to the reachable table edge 2026-11-08 12:02:37 +10:00
Даниил Грабарь 4ba53082f4 fix: frame the grant workspace and clean cap physics 2026-11-08 11:22:11 +10:00
Даниил Грабарь 568696d7b5 feat: launch grant experiment by id 2026-11-08 10:52:22 +10:00
Даниил Грабарь 814922f8ca feat: spawn deterministic grant scene 2026-11-08 10:49:13 +10:00
Даниил Грабарь e29ae921c4 feat: generate grant Webots objects 2026-11-08 10:47:53 +10:00
Даниил Грабарь dd11119176 feat: define deterministic grant scenarios 2026-11-08 10:44:39 +10:00
Даниил Грабарь f9b208e315 feat: add universal grant Webots world 2026-11-08 10:42:04 +10:00
Даниил Грабарь d39d4c15d0 feat: scaffold iiwa_experement package 2026-11-08 10:41:32 +10:00
Даниил Грабарь 2902828c56 docs: plan grant experiment world package 2026-11-08 10:25:21 +10:00
Даниил Грабарь 1caa919ea4 Добавлены 3д модели для второго эксперемнта и два мира для эксперемента 2026-11-06 16:37:06 +10:00
Даниил Грабарь e94f9ac47e Добавлены 3д детали для эксперемента - грант 2026-11-06 13:37:49 +10:00
Даниил Грабарь 54f8f14ed7 Добавлена спецификация и навыки для codex и kimi-code 2026-11-05 14:07:19 +10:00
Даниил Грабарь 0e3fd0358f Добавлен stop в mcp 2026-09-29 09:06:24 +10:00
Даниил Грабарь 30d64303fc Merge controller into dev: bounded trajectories and shared seven-axis limits
Preserve dev TCP gizmo motion-priority handling while integrating Ruckig smoothing, continuous JTC spline validation and shared robot limits. Resolve launch and dependency conflicts without removing either feature set. Verified merged build of 8 packages and tests of 4 packages.
2026-09-21 05:21:28 +03:00
Даниил Грабарь 0a091ad521 feat(control): unify joint limits and bound trajectory dynamics
Use shared limits for all seven axes across MoveIt, URDF and FRI.
Apply Ruckig smoothing and continuous JTC spline checks, stretching
trajectory timing to respect velocity, acceleration and jerk limits.
Require fresh stationary feedback for direct trajectories and protect
preparation from concurrent submissions and stop requests.

Add regression tests, dependencies and bilingual FRI documentation.
Include the updated LIN speed-sweep scenario and current 60 ms filter
configuration. Acceleration and jerk limits remain project settings;
physical high-speed twitching is still under investigation.
2026-09-21 05:16:09 +03:00
Даниил Грабарь b1b8cedef1 append spawn objects 2026-09-18 12:37:28 +10:00
Даниил Грабарь 9dc1073f42 Update camera settings 2026-09-18 12:05:35 +10:00
Даниил Грабарь 3a5bc28bba feat: add release-to-move TCP gizmo control in Webots
Add a native Webots marker for setting the active tool's TCP position and
orientation. Dragging edits the preview; releasing the mouse submits one
complete, checked joint trajectory with configured TCP speed limits.
Unreachable targets reset the marker to the current TCP.

Preserve coordinate, joint, and control-file commands through motion
reservations and a controller action proxy. Give the gizmo lowest priority
and finish its committed trajectory before dispatching queued regular
commands, including waits longer than the former two-second service timeout.

Place the patron TCP at its working end, 55.2 mm along local Z, and use the
flange TCP when no tool is attached. Add digital_twin.tcp_gizmo configuration,
ROS interfaces, launch integration, and regression coverage.

Document operation, configuration, tool attachment, speed limits, and
troubleshooting in both Russian and English.

Validation: 42 Python tests and 8 C++ tests passed. Webots regressions covered
one action per release, translation and rotation with and without a tool,
unreachable targets, and ordinary commands waiting for gizmo completion.
2026-09-17 17:11:53 +03:00
Даниил Грабарь 9f0f05df87 docs: add FRI realtime scheduling guide 2026-09-16 15:08:55 +10:00
Даниил Грабарь 1780532f51 feat: configure FRI position smoothing 2026-09-16 15:06:17 +10:00
Даниил Грабарь 29a1601061 fix: smooth FRI position commands 2026-09-16 15:00:14 +10:00
Даниил Грабарь fd66c8c7ec fix: prioritize FRI worker and expose command telemetry 2026-09-16 14:54:44 +10:00
Даниил Грабарь 97e3a5f60c fix: keep Webots controller rate 2026-09-16 14:39:49 +10:00
Даниил Грабарь e7df25c36f fix: derive controller rate from FRI period 2026-09-16 14:36:41 +10:00
Даниил Грабарь 7f9b120fe8 fix: preserve FRI settings and update CLI safely 2026-09-16 14:25:49 +10:00
Даниил Грабарь 36d620317a Update setting 2026-09-16 14:13:21 +10:00
Даниил Грабарь 48e842656b fix: report mismatched FRI periods 2026-09-16 14:11:37 +10:00
Даниил Грабарь ca4bb76008 Delete readme file 2026-09-16 10:00:33 +10:00
Даниил Грабарь 392036caf8 Update control move 2026-09-16 09:59:58 +10:00
Даниил Грабарь d51c3737b9 docs: record workstation update and controller motion issues 2026-09-15 16:26:44 +10:00
Даниил Грабарь b1fc2c5ff5 fix: align iiwa controller with FRI lifecycle and use JTC without EMA 2026-09-15 14:10:10 +10:00
Даниил Грабарь db2751bc78 Merge branch 'dev' 2026-08-13 18:09:02 +03:00
Даниил Грабарь 910afce714 Update MkDocs installation to include static i18n and PDF export dependencies 2026-08-13 18:08:40 +03:00
Даниил Грабарь 9e65a2720c docs: clean up README by removing outdated commands and sections 2026-08-13 18:05:35 +03:00
Даниил Грабарь 047e1b190e Merge branch 'dev' 2026-08-13 18:02:26 +03:00
Даниил Грабарь 79d88db930 Add documentation for KUKA Sunrise features and programs
- Created a new document for the Station interface, detailing its menu structure, process data, safety functions, frames, and smartPAD function buttons.
- Added a document for RobotPowerControl, explaining its purpose for safely shutting down or restarting the KUKA Sunrise Cabinet controller.
- Introduced ServerFriRos2 documentation, outlining its role in establishing an FRI connection between the KUKA LBR iiwa and a ROS 2 computer.
- Documented the TeachKuka application, which allows manual teaching of the KUKA LBR iiwa, including position capturing and trajectory recording.
- Added an overview of Sunrise Workbench, including installation instructions for Windows and Linux.
- Created a section on installing a Windows compatibility tool (PortProton) on Linux.
- Documented the installation process for SunriseWorkbench on Linux using PortProton.
- Added installation instructions for SunriseWorkbench on Windows.
- Created troubleshooting documentation for configuration errors and SSL errors during installation.
- Implemented a hook to generate the shared PDF only during the default-language build.
2026-08-13 18:01:59 +03:00
Даниил Грабарь 08ebd40671 docs: update README files with project features and compatibility details 2026-08-13 17:01:34 +03:00
Даниил Грабарь 4547b786a3 Add ServerFriRos2 documentation for KUKA Sunrise Cabinet integration with ROS 2
- Introduced a comprehensive guide for the ServerFriRos2 program, detailing its purpose, setup, and operational procedures.
- Included instructions on configuring network addresses, tool data, initial positions, and FRI cycle periods.
- Provided step-by-step guidance for launching the application and connecting to ROS 2, including troubleshooting tips for connection issues.
- Emphasized safety warnings and operational considerations for using the program with the KUKA LBR iiwa robot.
2026-08-13 16:51:50 +03:00
Даниил Грабарь b318cb3311 Add instructional videos for HandMode and TeachMode
- Added HandMode.mp4 to demonstrate the hand mode functionality.
- Added TeachMode.mp4 to showcase the teaching mode features.
2026-08-13 14:13:35 +03:00
Даниил Грабарь 2ba4975471 Merge branch 'dev' 2026-08-13 00:14:25 +03:00
Даниил Грабарь c5cbf234cb Document TeachKuka operation and safety 2026-08-13 00:13:52 +03:00
Даниил Грабарь e388e7d168 Merge branch 'dev' 2026-08-12 20:55:47 +03:00
Даниил Грабарь 2478e9956b docs: document RobotPowerControl 2026-08-12 20:54:53 +03:00
Даниил Грабарь ff4b2e30ce Merge branch 'dev' 2026-08-12 20:30:18 +03:00
Даниил Грабарь 5134fadf31 Update REST API documentation for robot control
- Refined introduction to REST API capabilities and usage.
- Added security warnings and best practices for using the API.
- Improved examples for various programming languages (Bash, Python, MATLAB).
- Enhanced endpoint descriptions and added details on request/response structures.
- Clarified the process for moving the robot and handling trajectories.
- Updated sections on sequences and error handling for better clarity.
2026-08-12 20:28:50 +03:00
Даниил Грабарь 41f516bb58 feat: implement stop functionality for robot operations and remove obsolete stop endpoint 2026-07-01 11:17:41 +10:00
Даниил Грабарь 9e3ee7ebc8 feat: add troubleshooting section for SSL errors during installation 2026-06-30 12:13:25 +03:00
Даниил Грабарь 0a7eb067ac Merge branch 'dev' 2026-06-22 06:18:01 +03:00
Даниил Грабарь 4fc9622ee9 вернул все обратно 2026-06-22 06:17:33 +03:00
Даниил ГрабарьandClaude Sonnet 4.6 1b6e211b88 Merge branch 'dev': fix rosdep obsolete sources timeout
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 05:57:47 +03:00
Даниил ГрабарьandClaude Sonnet 4.6 1c47b3f6f5 fix: remove obsolete rosdep sources (ruby, fuerte) before update
Eliminates SSL handshake timeouts during rosdep update caused by
unreachable ruby.yaml and fuerte.yaml (ROS 1 legacy sources not
needed for ROS 2 Jazzy).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 05:56:40 +03:00
Даниил Грабарь d26d60def4 refactor: update setup wizard steps and documentation; remove overview section 2026-06-21 07:29:21 +03:00
Даниил Грабарь a983a06e41 Добавлена документация по CLI-командам, конфигурации системы, управлению через Foxglove Studio и REST API, а также инструкции по установке и удалённому доступу к серверу. Включены разделы о настройке SunriseWorkbench для работы с реальным роботом KUKA LBR IIWA 7. 2026-06-20 13:15:56 +03:00
Даниил Грабарь ed02b59177 refactor: remove unused ai_agent package and related files; add colcon defaults 2026-06-20 07:47:52 +03:00
Даниил Грабарь 6df4ab49ec Update documentation 2026-06-19 09:42:31 +03:00
Даниил Грабарь 7d73ab32dd Добавлены инструкции по установке SunriseWorkbench на Linux и Windows
- Создана документация по установке эмулятора Windows (PortProton) на Linux.
- Добавлены шаги по установке SunriseWorkbench на Linux с использованием PortProton.
- Создана документация по установке SunriseWorkbench на Windows.
2026-06-18 15:52:48 +03:00
Даниил ГрабарьandClaude Sonnet 4.6 76db47d989 fix: add install docs and images ignored by .gitignore
Fixed .gitignore to use /install/ and /build/ with leading slash
so only the root-level colcon dirs are ignored, not
doc/lwc-doc/docs/sunrise/install/.

Adds install pages (Windows, Linux emulator, Linux workbench)
and 22 step-by-step screenshots that were never deployed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-18 15:32:01 +03:00
Даниил Грабарь 3a9f1f5150 del: .gitverse folder 2026-06-18 13:34:02 +03:00
Даниил Грабарь a3394db8fe fix: update MkDocs installation and enable PDF export 2026-06-18 13:27:27 +03:00
Даниил Грабарь f4e2765e69 fix: update installation script URL to use master branch 2026-06-18 13:24:26 +03:00
Даниил Грабарь b7db2e991c Add documentation for SunriseWorkbench project setup and features
- Create libraries.md for library installation instructions in SunriseWorkbench.
- Create load-project.md for importing existing projects in SunriseWorkbench.
- Create new-project.md detailing the process of creating a new project in SunriseWorkbench.
- Add applications.md to describe the applications section in KUKA smartHMI.
- Add extra-menu.md for additional robot control options in KUKA smartHMI.
- Create io-group.md for managing input/output groups in KUKA smartHMI.
- Add robot-menu.md as a placeholder for the robot menu section in KUKA smartHMI.
- Create station.md to outline the main navigation and functionalities in KUKA smartHMI.
- Add LBRserver.md, robot-power-control.md, and teach-kuka.md as placeholders for respective control programs.
- Create config-error.md to provide troubleshooting steps for configuration errors in SunriseWorkbench.
- Add main.html to override base template with site root metadata.
2026-06-18 13:22:55 +03:00
Даниил Грабарь 07edc4faf6 Append live mode view doc 2026-06-18 11:31:45 +03:00
Даниил Грабарь b441590dd8 fix: update installation script URL to use dev branch 2026-06-18 11:19:40 +03:00
Даниил Грабарь 5a8b1c44ff Merge branch 'master' into dev 2026-06-18 11:18:30 +03:00
Даниил Грабарь dca056064a fix: update installation script to use master branch for cloning 2026-06-18 11:15:10 +03:00
Даниил Грабарь ec4e1d87ad fix: update documentation workflows for GitHub and GitVerse compatibility 2026-06-18 07:16:40 +03:00
Даниил Грабарь de0117af94 feat: add GitVerse workflow for documentation build and deployment 2026-06-18 07:05:04 +03:00
Даниил Грабарь 16cb4dc6e7 fix: update GitHub Actions workflow to handle uploads for both GitHub and GitVerse 2026-06-18 06:59:41 +03:00
Даниил Грабарь 985425b866 refactor: update GitHub Actions workflow for documentation build and deployment 2026-06-18 06:37:53 +03:00
Даниил Грабарь 4a2e23ffef fix: update installation script URL to use the master branch 2026-06-18 06:21:22 +03:00
Даниил Грабарь a172ffe038 fix: update installation scripts to use the correct branch for cloning and installation 2026-06-18 06:21:22 +03:00
Даниил Грабарь 78405dfa8a feat: add GitHub Actions workflows for documentation deployment and building 2026-06-18 06:18:12 +03:00
Даниил Грабарь 6768d12fd7 fix: update installation scripts to use the correct branch for cloning and installation 2026-06-18 06:15:55 +03:00
Даниил Грабарь 78c5be2fa5 feat: add GitHub Actions workflows for documentation deployment and building 2026-06-18 06:01:48 +03:00
Даниил Грабарь 8ab341f60a Change pulling dev to master 2026-06-16 13:18:49 +10:00
Даниил Грабарь 1a1ee6f027 Merge branch 'dev' 2026-06-16 13:16:45 +10:00
Даниил Грабарь ddfbbda7db feat: update Dockerfiles and rosdep.yaml to install fastapi and starlette, remove starlette dependency 2026-06-15 16:32:05 +03:00
Даниил Грабарь eb8db5c6c0 feat: update rosdep and package.xml to specify minimum versions for fastapi and starlette 2026-06-15 15:26:09 +03:00
Даниил Грабарь 7ff5616870 feat: update installation scripts to pre-install fastapi and starlette for compatibility 2026-06-15 15:24:19 +03:00
Даниил Грабарь c540733ace feat: install Python build tools in setup scripts for ROS2 2026-06-15 15:06:43 +03:00
Даниил Грабарь 33ebbf8fad add: Script for shutting down and restarting the robot controller 2026-06-15 10:55:52 +10:00
Даниил Грабарь 030e975d59 feat: update installation scripts to pre-install fastmcp for successful rosdep upgrades 2026-06-14 16:22:00 +03:00
Даниил Грабарь 7d508765d0 feat: pre-install typing-extensions to ensure smooth upgrades for apt-installed packages 2026-06-14 16:17:27 +03:00
Даниил Грабарь 0fe84a907f feat: add ai_agent package with setup and configuration scripts; configure pip for system installs 2026-06-14 16:11:15 +03:00
Даниил Грабарь ee047618cd feat: update version and dependencies in setup.py; add privilege management and process handling modules
- Updated version from 2026.05.31 to 2026.06.11 in setup.py
- Replaced 'textual' with 'rich' in install_requires
- Added privilege.py for managing sudo privileges with a keep-alive mechanism
- Introduced process.py for handling subprocesses with enhanced control and output streaming
- Created ui.py for unified console interactions and user prompts
2026-06-11 12:21:02 +10:00
Даниил Грабарь e76a07c8f6 feat: update .gitignore to include CLAUDE.md and retain backup files 2026-06-07 15:36:19 +03:00
Даниил Грабарь 36fa33b032 Refactor tool management and update robot configuration
- Updated iiwa7.srdf to streamline group and end effector definitions, removing unnecessary joint specifications.
- Enhanced setting.yaml to include active tool configuration.
- Removed deprecated gripper URDF and Xacro files, consolidating tool definitions into tools.yaml.
- Introduced tool_manager.py for dynamic tool management, allowing for easy updates to active tools and collision settings.
- Created tool_active.xacro to reflect the currently active tool in the robot's URDF.
- Added comprehensive collision management for the new tool configurations.
2026-06-03 14:03:44 +10:00
Даниил Грабарь 9f9fb24dc3 Delete realsense packages 2026-06-03 13:31:00 +10:00
Даниил Грабарь 91eefe1eea feat: refactor launch files to modularize node creation and improve simulation support 2026-06-03 13:24:08 +10:00
Даниил Грабарь e9e3163ce6 feat: add support for named positions in robot API, including new endpoints and metadata 2026-06-03 13:19:13 +10:00
Даниил Грабарь 75d2c499b2 Update API 2026-05-28 15:20:57 +10:00
Даниил Грабарь 02e0c25847 Append fastMCP model 2026-05-27 17:13:42 +03:00
Даниил Грабарь 4916648f03 Update xacro pos 2026-05-27 08:26:48 +03:00
Даниил Грабарь f365cd491f Update fields 2026-05-26 16:02:08 +03:00
Даниил Грабарь d3912a5a12 feat: enhance API with new trajectory and sequence handling, add TF support and improve endpoint definitions 2026-05-26 20:36:10 +10:00
Даниил Грабарь 30d7785d8c refactor: remove deprecated robot API and implement dynamic routing for endpoints 2026-05-26 17:23:46 +10:00
Даниил Грабарь ec5fb3ccdb refactor: remove commented section headers from motion_sequence_runner.py 2026-05-26 16:10:25 +10:00
Даниил Грабарь a4d318fceb Refactor motion sequence handling: remove old test script, update setup, and implement new runner with configuration support
- Deleted obsolete `test_motion_sequence.py` file.
- Updated `setup.py` to remove references to the old test script and motion configuration file.
- Added `motion_sequence_config.json` to define home position and waypoints for the robot.
- Introduced `motion_sequence_runner.py` to execute motion sequences based on the new configuration format, supporting both joint and pose movements.
2026-05-26 16:09:41 +10:00
Даниил Грабарь a84cfde96c feat: implement ROS node and API for robot control with FastAPI 2026-05-26 08:39:45 +03:00
Даниил Грабарь 2f079df087 Update logic work system 2026-05-25 07:38:07 +03:00
Даниил Грабарь fff46f0ade feat: add rosdep.yaml handling and iiwa_web package to Dockerfiles 2026-05-25 13:16:33 +10:00
Даниил Грабарь e4b8daf754 feat: update package versions to 2026.5.31 and add dependencies for iiwa_web 2026-05-25 12:46:27 +10:00
Даниил Грабарь b560fcf229 refactor: remove command_mode from configuration and related files 2026-05-25 12:30:59 +10:00
grabardm c66de51526 Запрос на слияние 'dev' (#2) из dev в master 2026-05-24 07:38:30 +00:00
Даниил Грабарь e60402c8f2 feat: add English documentation for Lightweight Cobot 2026-05-24 10:35:35 +03:00
Даниил Грабарь cbd05effd2 feat: update package versions and descriptions for all modules; add web interface package 2026-05-24 10:18:04 +03:00
Даниил Грабарь 0b0ef36428 fix: update navigation labels to Russian for consistency 2026-05-23 12:57:06 +03:00
Даниил Грабарь 50d248eb0c feat: update documentation structure and add new content for Lightweight Cobot 2026-05-23 12:51:56 +03:00
Даниил Грабарь 490f8823a5 feat: refactor MultiPickScreen to use SelectionList for multi-choice selection 2026-05-23 12:14:07 +03:00
Даниил Грабарь 3da290a4f3 feat: implement MultiPickScreen for multi-selection in the TUI 2026-05-23 11:07:01 +03:00
Даниил Грабарь 9f59868cec fix: remove sudo keepalive mechanism from installation scripts 2026-05-23 10:50:54 +03:00
Даниил Грабарь ddb6015bfd feat: add clean and rebuild commands for managing ROS2 packages 2026-05-23 09:53:26 +03:00
Даниил Грабарь 19d50d2c09 fix: enhance scripts to keep sudo credentials alive during installation 2026-05-23 09:43:26 +03:00
Даниил Грабарь cc97e2a854 fix: enhance Webots removal and installation scripts to manage WEBOTS_HOME environment variable 2026-05-23 08:21:58 +03:00
Даниил Грабарь 0c677176b0 fix: add COLCON_IGNORE file to exclude specific directories from colcon build 2026-05-23 04:21:43 +03:00
Даниил Грабарь 14a5e6d90a fix: explicitly set Python executables for CMake to use system Python 2026-05-23 04:13:04 +03:00
Даниил Грабарь fc6c08aff3 fix: prioritize system directories in PATH for ament_cmake to use system Python 2026-05-22 19:27:55 +03:00
Даниил Грабарь c57e94dcc4 fix: remove symlink option from colcon build command in _task_build function 2026-05-22 19:23:35 +03:00
Даниил Грабарь b9c7f14a23 fix: update colcon build command to include base paths for improved build process 2026-05-22 19:21:14 +03:00
Даниил Грабарь 0dda077e7f fix: remove symlink option from colcon build command in task_build function 2026-05-22 19:17:35 +03:00
Даниил Грабарь a7dace79ad fix: update progress reporting and improve script clarity in setup scripts 2026-05-22 19:09:32 +03:00
Даниил Грабарь e3ef99d1f0 feat: prompt user to build project workspace after installation 2026-05-22 19:06:10 +03:00
Даниил Грабарь 2a70cdbe75 feat: add installation scripts for ROS2 Jazzy Desktop and ros-base with progress reporting 2026-05-22 19:00:16 +03:00
Даниил Грабарь 7cadd1d673 fix: enhance subprocess management and progress reporting in setup and update commands 2026-05-22 18:30:34 +03:00
Даниил Грабарь 463a1e1423 fix: add docstrings to improve code documentation and clarity 2026-05-22 18:16:59 +03:00
Даниил Грабарь a7590cc93f Implement feature X to enhance user experience and optimize performance 2026-05-22 17:53:09 +03:00
Даниил Грабарь c595365c2b fix: improve apt progress reporting and enhance status handling 2026-05-22 17:24:50 +03:00
Даниил Грабарь 58da9c0814 fix: enhance apt command progress reporting and install dev tools 2026-05-22 17:20:57 +03:00
Даниил Грабарь a1b9a21352 fix: update apt timeouts for improved reliability and adjust add-apt-repository command for no-update 2026-05-22 16:18:34 +03:00
Даниил Грабарь 074896b2dd fix: remove timeout settings from add-apt-repository command for simplicity 2026-05-22 16:02:34 +03:00
Даниил Грабарь dc31589ae0 fix: replace quiet command execution with logged output for better visibility 2026-05-22 16:01:10 +03:00
Даниил Грабарь 523961d432 fix: enhance apt commands with timeout settings and cleanup previous ROS2 repository configuration 2026-05-22 15:52:58 +03:00
Даниил Грабарь 1af22bf2ac fix: refactor ROS2 apt repository setup and improve key import process 2026-05-22 15:49:52 +10:00
Даниил Грабарь a0be3bcd56 fix: remove unnecessary "./" prefix for local apt package installation 2026-05-22 14:50:28 +10:00
Даниил Грабарь 2bdfb139bf Bug fix 2026-05-22 14:27:52 +10:00
Даниил Грабарь e154a41d33 fix: remove leftover ROS2 apt repository files before configuration 2026-05-22 13:56:34 +10:00
Даниил Грабарь 6360023e6f fix: update ROS2 apt repository setup to use ros2-apt-source package and improve installation process 2026-05-22 13:31:30 +10:00
Даниил Грабарь 4202421d5b fix: add process tracking and cancellation support to command execution 2026-05-22 13:23:38 +10:00
Даниил Грабарь 14337aa4e7 fix: add HTTP/HTTPS timeouts for apt commands to prevent hangs and improve reliability 2026-05-22 13:12:23 +10:00
Даниил Грабарь e24f97b12d fix: prompt for sudo password upfront to ensure smooth installation process 2026-05-22 11:56:05 +10:00
Даниил Грабарь 17b1425c78 fix: cache sudo token to prevent silent hangs during installation prompts 2026-05-22 11:43:20 +10:00
Даниил Грабарь 8b71870d2b Merge branch 'dev' of gitverse.ru:daniel-robotics/lightweight-cobot into dev 2026-05-22 11:27:11 +10:00
Даниил Грабарь 5f2d45f63c обновлен процесс загрузки 2026-05-22 11:26:34 +10:00
Даниил Грабарь bdb5fb2418 fix: update robot IP address in configuration and improve process termination handling in run script 2026-05-21 07:56:11 +03:00
Даниил Грабарь fd576dc27a fix: ensure rosdep update does not fail during Docker build 2026-05-21 13:58:54 +10:00
Даниил Грабарь 6be6032838 feat: update robot setup to use ruamel.yaml for preserving YAML comments and formatting
feat: enhance run command with Docker volume for Webots asset caching and GPU detection

feat: improve setup command to sequentially run sub-commands for documentation, environment, and robot parameters

fix: update update command to provide clearer logging during git operations and installation

refactor: enhance TUI components with better threading and logging for long-running tasks

chore: improve install script with better error handling, logging, and interactive setup wizard
2026-05-21 12:46:54 +10:00
Даниил Грабарь e18ff53532 Add run command for launching robot controller and Webots simulator 2026-05-21 11:41:54 +10:00
Даниил Грабарь 2903b8825d Enhance progress reporting in setup and deletion processes across multiple scripts 2026-05-21 11:05:08 +10:00
Даниил Грабарь 11f24172cb Implement retry logic for git clone in installer script to enhance robustness 2026-05-20 18:28:00 +03:00
Даниил Грабарь 615a955767 Refactor subprocess handling in setup scripts for improved error reporting and output management 2026-05-20 18:24:09 +03:00
Даниил Грабарь 6c10d072de Optimize git clone command by adding depth option for faster repository cloning 2026-05-20 18:14:39 +03:00
Даниил Грабарь 9ab76160f0 Enhance ROS2 repository setup by improving key handling and updating installation commands 2026-05-20 18:09:04 +03:00
Даниил Грабарь c8b121958d Improve Python version check in installer script to handle errors gracefully 2026-05-20 18:03:59 +03:00
Даниил Грабарь e153de0bb7 Fix input redirection for quiet command execution and Python version check in installer script 2026-05-20 17:59:37 +03:00
Даниил Грабарь a50ff4e2e6 Add delete and update commands for project management 2026-05-20 17:52:49 +03:00
Даниил Грабарь 5f16825cf7 Refactor Docker and Local Setup Commands
- Enhanced the docker_setup.py to streamline image building and pulling processes with improved logging and error handling.
- Introduced a new LogScreen for better user feedback during long-running tasks.
- Updated local_setup.py to utilize logging for installation steps and improved error handling.
- Refactored robot_setup.py to simplify configuration saving and user interaction.
- Added a new LogScreen class in tui.py for consistent logging across different setup processes.
- Modified install.sh to adjust the installation directory for better organization.
2026-05-20 17:41:11 +03:00
Даниил Грабарь bbfec17876 Add local setup command and enhance docker setup wizard 2026-05-20 17:05:01 +03:00
Даниил Грабарь 86e6e801e9 Add robot setup command and configuration management for cobot-setting.yaml 2026-05-20 14:43:20 +10:00
Даниил Грабарь dedf3e3467 Implement documentation setup and Docker configuration for LWC project 2026-05-20 13:49:21 +10:00
Даниил Грабарь a06470c0c9 Enhance install script with improved logging and error handling 2026-05-19 18:22:37 +03:00
Даниил Грабарь 5315767638 Refactor install script for improved logging and setup process 2026-05-19 17:15:01 +03:00
Даниил Грабарь d1c250e6b9 Add initial implementation of cobot CLI and setup scripts 2026-05-19 17:04:27 +03:00
Даниил Грабарь 6228501581 Refactor Dockerfile and run script for improved GPU handling and environment variable management 2026-05-19 16:26:05 +03:00
Даниил Грабарь 836b03a7ee Update Dockerfiles and configuration for improved package management and controller settings 2026-05-19 12:48:12 +10:00
Даниил Грабарь 24bc5f3aba Update Dockerfiles to support dynamic package installation and build type configuration 2026-05-19 01:51:51 +03:00
Даниил Грабарь 06c50616b4 Add Dockerfile and run script for Webots integration; update package dependencies 2026-05-18 17:53:02 +03:00
Даниил Грабарь 8d27c01b92 Добавлена сборка контроллера 2026-05-18 16:59:16 +03:00
Даниил Грабарь 9bff33608e Добавлены Docker образы 2026-05-18 18:11:05 +10:00
Даниил Грабарь c5d8ecc4c5 Bug fix 2026-05-18 16:59:24 +10:00
Даниил Грабарь aa000c0b02 Fix joint1 axis orientation in joints.xacro for correct kinematic behavior 2026-05-18 07:14:53 +03:00
Даниил Грабарь 04b5c99ec8 Update iiwa_controller and MoveIt configuration: Adjust joint velocity filter and parameters for improved performance 2026-05-18 11:33:35 +10:00
Даниил Грабарь ace4d02b8a Refactor iiwa_controller_v2: Remove obsolete files and update URDF parameters
- Deleted `system_interface_type_values.hpp`, `package.xml`, `fri_client.cpp`, and `system_interface.cpp` as part of the cleanup process.
- Updated `iiwa7.urdf.xacro` to remove deprecated parameters and adjust command interface settings.
- Modified joint definitions in `joints.xacro` to include new friction and soft limit parameters.
- Enhanced `macros.xacro` to support additional joint properties for friction and safety control.
- Adjusted mass properties in `params.xacro` to reflect accurate values for the robot's components.
2026-05-18 11:10:11 +10:00
Даниил Грабарь efaec9b442 Update iiwa_controller configuration for improved joint control and velocity clamping 2026-05-18 03:34:59 +03:00
Даниил Грабарь 86cf252a87 Enhance joint limits and add acceleration scaling to MoveToNamedPose service 2026-05-15 07:20:26 +03:00
Даниил Грабарь 99215c0b20 Add iiwa_controller_v2: Implement hardware interface for KUKA iiwa7 via FRI
- Introduced iiwa_hardware_interface_plugin.xml to define the hardware interface.
- Created command_guard.hpp to enforce joint limits for position and torque commands.
- Developed fri_client.hpp and fri_client.cpp to manage FRI communication and state snapshots.
- Implemented system_interface.hpp and system_interface.cpp for lifecycle management and command handling.
- Added system_interface_type_values.hpp for extended state interface names.
- Defined package.xml for ROS2 integration with necessary dependencies.
2026-05-15 13:10:00 +10:00
Даниил Грабарь d6b4641d9b Update FRI configuration parameters for improved joint control and synchronization 2026-05-14 08:01:58 +03:00
Даниил Грабарь 7eefdd66d5 Refactor controller configuration and update planning parameters for improved performance 2026-05-14 07:29:47 +03:00
Даниил Грабарь c3d1de7b01 Add joint_position_tau parameter for smoother joint control and update related configurations 2026-05-14 11:40:04 +10:00
Даниил Грабарь 302eb3d8d7 fix: Update FRI cycle time and adjust related parameters for improved synchronization 2026-05-13 07:39:18 +03:00
Даниил Грабарь 1f37a07770 Add fri_cycle_ms parameter to configuration and update related components 2026-05-13 04:31:19 +03:00
Даниил Грабарь 68198ed2f8 Add documentation build scripts and initial MkDocs setup 2026-05-08 16:43:22 +10:00
Даниил Грабарь 6744f1963f Переделан контроллер 2026-05-08 08:49:10 +03:00
Даниил Грабарь 2dfe967ca1 fix: Update .gitignore to include .claude and clean up friUdpConnection.cpp code 2026-05-08 04:17:06 +03:00
Даниил Грабарь 225ae50f10 feat: Enhance iiwa_description and iiwa_sunrise functionality
- Added a new link "tcp" and a fixed joint "patron_tcp" in patron.xacro for better tool control.
- Updated ServerFriRos2.java to improve command mode handling and user configuration steps, including clearer logging and better control mode selection.
- Removed the deprecated iiwa_ros2.java file to streamline the codebase.
- Enhanced test_motion_sequence.py to allow dynamic topic recording based on user input, with improved logging for bag file management.
2026-05-07 17:47:47 +03:00
Даниил Грабарь 3c8d157cbe Исправлены баги 2026-05-06 07:39:22 +03:00
Даниил Грабарь 9f30b9ff5d feat: enhance motion sequence capabilities and add configuration support
- Updated README.md to include examples for data collection and motion sequence testing.
- Modified setting.yaml to change the TCP link for planning from "patron" to "link_ee".
- Refactored move_to_pose_server.py to improve planner configuration readability.
- Updated setup.py to include motion_config.json in package resources and added a new console script for testing motion sequences.
- Introduced motion_config.json to define home joints and poses for motion sequences.
- Added test_motion_sequence.py to implement a test runner for executing motion sequences and recording data to a bag file.
2026-05-06 14:03:41 +10:00
Даниил Грабарь cd4dcf97ac Update pose_link in planning configuration to use 'patron' 2026-05-05 17:18:25 +03:00
Даниил Грабарь e4d6bdc1af Add motion planning actions and services for iiwa robot
- Implemented action servers for MoveToPose and MoveToJoints.
- Added service for MoveToNamedPose and stop action.
- Updated README with usage examples for new actions.
- Enhanced planning configurations in YAML and Python files.
- Removed deprecated motion planning scripts.
2026-05-05 17:15:08 +03:00
Даниил Грабарь b3f4bc458b Добавлены управляющие программы для коллаборативного робота 2026-05-05 15:43:56 +03:00
Даниил Грабарь 748f30b1d1 Add move_to_pose_server and iiwa_msgs package with service definition
- Implement move_to_pose_server for motion planning using MoveIt
- Create iiwa_msgs package with MoveToPose service definition
- Update iiwa.launch.py to include move_to_pose_server node
- Modify joint_limits.yaml to add position limits for joints
- Remove iiwa_voice package and related files
2026-05-05 18:37:04 +10:00
Даниил Грабарь 6b4ff4f8b6 Update model versions in docker-compose for Qwen3-TTS services 2026-04-20 15:52:20 +10:00
Даниил Грабарь 8e2cf07303 change struct docker 2026-04-20 13:50:52 +10:00
Даниил Грабарь ce143ff2dd Update docker-compose configuration for Qwen3-TTS services with improved command structure and health check adjustments 2026-04-20 13:21:15 +10:00
Даниил Грабарь f6d5d546d1 Refactor docker-compose commands to use --model flag and add voice generation script 2026-04-20 13:18:49 +10:00
Даниил Грабарь 0445776d48 Add iiwa_voice package with environment setup and docker-compose configuration 2026-04-20 12:42:45 +10:00
Даниил Грабарь 5eefd2fc90 Add realsense2 package installation and new world file for iiwa control cabinet 2026-04-15 16:39:17 +10:00
Даниил Грабарь bd66f314fc Merge branch 'dev' of gitverse.ru:daniel-robotics/kuka_iiwa7_ros2 into dev 2026-04-15 09:55:23 +10:00
Даниил Грабарь 036ac35685 Add documentation and PDF resources for KUKA Sunrise applications 2026-04-15 09:55:09 +10:00
Даниил Грабарь b4ceedd043 Add installation command for rosbag2 storage MCAP in README 2026-04-14 14:50:33 +03:00
Даниил Грабарь c95c94f67b Bug fiix import patron.xacro and append packages realsense2 2026-04-14 14:20:27 +03:00
Даниил Грабарь 1156c768bb Refactor code structure for improved readability and maintainability 2026-04-14 18:06:58 +10:00
Даниил Грабарь a913d512b9 change parametrs 2026-04-14 09:20:05 +03:00
Даниил Грабарь 7736c71760 Add camera spawning functionality and update configuration files 2026-04-14 11:19:53 +10:00
Даниил Грабарь cd450a3476 Add camera spawning functionality and update world configuration 2026-04-13 17:37:24 +03:00
Даниил Грабарь 2dfa8f1c94 Add foxglove_bridge configuration and settings support 2026-04-13 17:20:32 +10:00
Даниил Грабарь d585c4f0b9 update launch file 2026-04-13 07:02:53 +03:00
Даниил Грабарь bfa16be526 update patron and structured 3dd models 2026-04-13 06:49:31 +03:00
Даниил Грабарь 9e643f756a update 3dmodels 2026-04-13 02:11:35 +03:00
Даниил Грабарь deb646c7a9 Add code server java 2026-04-10 10:37:46 +03:00
Даниил Грабарь 6d8d15ba5d Add cameraD455 mesh file to iiwa_description resources 2026-04-10 17:15:16 +10:00
Даниил Грабарь 2eb87077dd Refactor controller launch configuration and remove deprecated URDF files 2026-04-09 16:45:30 +10:00
Даниил Грабарь 47cafe7ea1 Add AMENT_IGNORE file and initial implementation of AAServer and Iiwa_ros2 classes 2026-04-09 13:55:32 +10:00
Даниил Грабарь 845f4ca89c Refactor launch files and update package descriptions for KUKA iiwa7, transitioning from Gazebo to Webots simulation 2026-04-09 13:52:28 +10:00
Даниил Грабарь 58f246e1f2 Add URDF and XACRO files for iiwa7 robot and tool patron
- Created iiwa7_gazebo.urdf to define the iiwa7 robot model with detailed links, joints, and Gazebo integration.
- Introduced patron.xacro for the tool patron, including its inertial properties, visual representation, and collision geometry.
2026-04-09 12:01:43 +10:00
Даниил Грабарь f474d330ad Add URDF model for table and SDF world configuration
- Created a new URDF file for the table model, including links for the table frame, wood palette, robot palette, cabinet frame, and cabinet, along with their respective visual and collision properties.
- Defined joints to connect the various components of the table model.
- Added a new SDF file for the simulation world, setting up the environment with physics properties, a ground plane, and lighting.
2026-04-08 16:38:59 +10:00
Даниил Грабарь 45e134e116 Refactor launch files and update robot description for iiwa7 configuration 2026-04-08 13:52:17 +10:00
Даниил Грабарь 9fae773856 append new render mode 2026-04-08 06:37:57 +03:00
Даниил Грабарь e182f5b7bd Refactor URDF and launch files for iiwa robot
- Updated gripper macros in gripper_macros.xacro to simplify parameters and add Gazebo support.
- Removed unused mesh property in gripper_meshes.xacro.
- Enhanced iiwa7 digital and FRI URDF files with simulation arguments and improved controller setup.
- Added new launch files for Gazebo simulation and universal launch configuration.
- Implemented YAML parameter wrapping for ROS2 in converter.py.
- Introduced a new gz_bridge.yaml configuration for Gazebo to ROS2 topic mapping.
- Cleaned up setting_loader.py and added necessary imports.
2026-04-08 13:21:18 +10:00
Даниил Грабарь 9fb3477466 Test multi repos 2026-04-07 16:06:47 +03:00
Даниил Грабарь 48c0913108 Test ssh-remote 2026-04-07 16:00:58 +03:00
Даниил Грабарь a269ef3a76 Add gripper model and configuration for iiwa7 robot
- Created URDF model for gripper including links and joints.
- Added XACRO files for gripper components: gripper.xacro, gripper_links.xacro, gripper_joints.xacro, gripper_macros.xacro, and gripper_meshes.xacro.
- Integrated gripper into iiwa7 digital twin configuration.
- Defined properties and macros for gripper components to facilitate easier modifications and reuse.
2026-04-07 14:40:23 +10:00
Даниил Грабарь 44dd2505ca Add URDF model for gripper with multiple links and joints
- Created a new URDF file for the gripper, defining its structure.
- Added links: base_frame, plate, screw, craving1, craving2, craving3.
- Defined joints for the gripper's movement, including fixed and revolute joints.
- Included mesh files for visual and collision geometry.
- Set inertial properties for each link with zero mass and inertia.
2026-04-07 01:52:19 +03:00
Даниил Грабарь 1dc17d5949 Enhance IIWA Robot Configuration and Launch Files
- Updated iiwa7 URDF Xacro to include command and state interfaces for position and effort with defined limits for all joints.
- Modified setting_loader.py to include new fields for command_mode and description in the RobotCfg dataclass and settings loading process.
- Created iiwa.launch.py to manage the launch of the IIWA robot, integrating MoveIt configurations and RViz support.
- Added iiwa_controllers.launch.py to set up the controller manager and spawner for the IIWA robot.
- Introduced iiwa_hardware_interface_plugin.xml to define the hardware interface for the KUKA IIWA 7 robot.
- Added iiwa7_fri.urdf.xacro to support FRI (Fast Robot Interface) with appropriate command and state interfaces for each joint.
2026-04-06 09:40:04 +03:00
Даниил Грабарь 032935dec9 Обновлены параметры планирования и добавлены новые файлы для модуля планирования движения, включая C++ и Python реализации. 2026-04-05 12:22:30 +03:00
Даниил Грабарь bce4dd6067 добавлен полноценный модуль планирования траекторных перемещений. Необходимо его оформить правильным образом 2025-12-26 23:03:41 +10:00
Даниил Грабарь fe89d626d3 добавлен модуль iiwa_planning, в котором будет размещен весь код по планированию траекторных перемещений, а также логическое планирование (PDDL, LLM и др.).
Тестовый файл `motion_planning_test.py` внутрь созданного модуля
2025-12-26 15:34:07 +10:00
Даниил Грабарь caa9984abe Обновлены параметры ускорения по каждой из осей 2025-12-26 14:30:18 +10:00
Даниил Грабарь fa39991bcf Переработана вся структура запуска файлов. Теперь в iiwa_bringup хранятся только launch файлы.
Все конфигурационные файлы переехали в пакет `iiwa_config`. также там появился общий конфигурационный файл, который упращает запуск `digital_twin.launch.py`

Добавлен дополнительный пакет  `iiwa_utils`, в который переехал весь код с папки `iiwa_bringup/utils`, а также все тестовые ноды переехали с `iiwa_object_spawner` в этот пакет

Пакеты `iiwa_bringup` и `iiwa_description` переведены на `ament_cmake` для дальнейшего удобсва - пакеты не будут содержать код для реализации
2025-12-25 21:46:40 +10:00
Даниил Грабарь 1a65f48c03 исправлена название группы управления осями, добавле файл конфигуации для управления осями через api moveit, а также добавлен пример на языке python 2025-12-24 21:14:32 +10:00
Даниил Грабарь 7637a215d3 Исправлены ошибки, которые остались с ros2 rolling 2025-12-24 16:26:17 +10:00
Даниил Грабарь 084d4c0aa7 добавлена поддержка moveit 2025-12-24 13:44:55 +10:00
Даниил Грабарь 6acbd7ca6f Исправлены баги, добавлен код Object.proto, в который будут подставлятяь 3д объекты для последующего спавна 2025-12-23 21:48:18 +10:00
Даниил Грабарь 37da67abe5 отформатированы документы согласно нотации pep 2025-11-29 15:51:45 +10:00
Даниил Грабарь b36bd0e98b Изминения:
- В файле `webots_spawn.launch.py` - добавлено использование времени симуляции
- Добавлен новый пакет `iiwa_object_spawne`, который отвечает за появление объектов (в разработке)
2025-11-29 00:40:55 +10:00
Даниил Грабарь 3852340a58 Изменил название файла, поскольку может понадобиться в будущем. Сейчас описанные подходы в нем не используются 2025-11-23 02:23:51 +10:00
598 changed files with 1066950 additions and 1714 deletions
+1
View File
@@ -0,0 +1 @@
codex
@@ -0,0 +1,206 @@
---
name: openspec-apply-change
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks. Also use when the user says "openspec apply", "opsx apply", or "openspec implement".
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.16.0"
---
Implement tasks from an OpenSpec change.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
**Input**: Optionally specify a change name (e.g., `$openspec-apply-change (Codex) or /openspec-apply-change (other agents) add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
Always announce: "Using change: <name>" and how to override (e.g., `$openspec-apply-change (Codex) or /openspec-apply-change (other agents) <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- `planningHome`, `changeRoot`, and `actionContext`: planning scope and edit constraints
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
- Progress (total, complete, remaining)
- Task list with status, source path, and source line
- Dynamic instruction based on current state
- Optional `context`: current required project instruction input from the selected root
- Optional `operationGuidance`: current advisory guidance for apply
- `missingArtifacts` (when present): required artifact ids with no output
**Handle states:**
- If `state: "blocked"`: show the message and pause implementation.
- If `missingArtifacts` is non-empty: suggest completing the missing artifacts. Run `openspec status --change "<name>" --json`, select the next `ready` artifact (not `skipped` or `blocked`), and use `openspec instructions "<artifact-id>" --change "<name>" --json` for its rules and template. Keep the selected `--store <id>` on both commands.
- Otherwise, follow the CLI instruction to create or repair the schema-configured tracking file from existing planning artifacts. Do not assume another artifact is ready or start implementation while blocked.
- If `state: "all_done"`: report that all tracked tasks are complete and suggest review or verification as appropriate before archiving
- Otherwise: proceed to implementation
Treat `context` as a required prompt-level input. Read and consider it, and
apply relevant project facts, conventions, and constraints while implementing.
Treat `operationGuidance` as optional additive advice. Read and consider every
entry, and follow entries that are applicable and compatible with the built-in
workflow.
Keep both fields separate from CLI-returned state, missing artifacts, tasks,
progress, `contextFiles`, and the built-in `instruction`. They are not
evidence of task completion, do not replace the built-in instruction, and do
not permit bypassing a blocked state. If context conflicts with the built-in
instruction, an explicit user choice, or a CLI-controlled value, report the
conflict and preserve the controlling value. If guidance is inapplicable or
conflicts with those controlling inputs, do not follow it and explain why.
These are prompt-level behavior contracts, not enforceable checks.
4. **Read context files**
Read every file path listed under `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
Do not copy `context` or `operationGuidance` verbatim into implementation
files or planning artifacts unless the user separately asks for that content.
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Before editing, confirm the checkbox at the returned `sourcePath` and `line` still matches the task description; if it does not, rerun the apply instructions and use the refreshed location
- Mark the task complete at its returned `sourcePath` and `line`: `- [ ]` → `- [x]`
- Rerun the apply instructions and confirm that task is now done and progress changed
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- A task needs work beyond what the spec and tasks describe, or you are tempted to drop, narrow, defer, or accept exceptions to specified behavior to make it fit → surface the added scope and ask; do not absorb it silently
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: report that tracked tasks are complete and suggest review or verification as appropriate before archiving
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tracked tasks are complete. Review or verify the change as appropriate
before archiving. You can archive this change with `$openspec-archive-change (Codex) or /openspec-archive-change (other agents)`.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- When a task needs work beyond what the spec describes, surface the added scope and pause - never silently narrow, defer, or simplify away specified behavior
- Only mark a task `- [x]` when its specified behavior is fully implemented, not when it is partially done or deferred
- Use contextFiles from CLI output, don't assume specific file names
- Use each task's sourcePath and line to update its exact checkbox
- Do not use context or operation guidance as proof that a task is complete
- Apply relevant project context; report conflicts with controlling workflow inputs
- Consider every guidance entry; explain any inapplicable or conflicting advice
- Do not copy runtime context or operation guidance into implementation files or planning artifacts
- Preserve CLI-controlled blocked/ready/all-done behavior and completion criteria
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly
@@ -0,0 +1,221 @@
---
name: openspec-archive-change
description: Archive a completed OpenSpec change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete. Also use when the user says "openspec archive" or "opsx archive".
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.16.0"
---
Archive a completed change in the experimental workflow.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
When prompting, show only active changes (not already archived).
Include the schema used for each change if available.
Always announce: "Using change: <name>" and how to override (e.g., `$openspec-archive-change (Codex) or /openspec-archive-change (other agents) <other>`).
**Load current archive inputs before the existing archive checks:**
After resolving the selected change and planning root, run:
```bash
openspec instructions archive --change "<name>" --json
```
Keep the same selected-root flags on this command. This lookup is advisory and
optional: it only supplies extra prompt inputs, so it must never block archiving.
If it exits non-zero or returns invalid JSON — for example on an older CLI that
does not support this command yet — continue the archive workflow with no
context and no operation guidance. Do not report an error and do not stop.
A successful response may omit both optional fields. Treat `context` as a
required prompt-level input: read and consider it, and apply relevant project
facts, conventions, and constraints. Treat `operationGuidance` as optional
additive advice: read and consider every entry, and follow entries that are
applicable and compatible with the built-in archive workflow.
Keep both fields separate from built-in steps, explicit user choices, resolved
paths, CLI checks, and command contracts. If context conflicts with one of those
controlling inputs, report the conflict and preserve the controlling value. If
guidance is inapplicable or conflicts with a controlling input, do not follow it
and explain why. Do not infer replacement paths, skipped prompts, or flags from
either field, and do not copy their text verbatim into specs, change artifacts,
or archive summaries unless the user separately asks for it. These are
prompt-level behavior contracts, not enforceable checks.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context
- `artifacts`: List of artifacts with their status (`done`, `skipped`, or other)
**If any artifacts are neither `done` nor `skipped`** (skipped artifacts satisfy the requirement - the change declares skip_specs):
- Display warning listing incomplete artifacts
- Ask the user to confirm they want to proceed
- Proceed if user confirms
3. **Check task completion status**
Run `openspec list --json` with the same selected-root flags and find the
entry in `changes` whose `name` exactly matches the selected change.
Require exactly one match and nonnegative integer `totalTasks` and
`completedTasks`, with `completedTasks <= totalTasks`. The CLI resolves
the schema's tracked task files, including custom artifact names, output
paths, and globs.
Incomplete tasks = `totalTasks - completedTasks`.
Do not infer task completion from artifact status or the absence of a
top-level `tasks.md`. If the lookup fails, returns invalid JSON, omits or
duplicates the selected change, or returns invalid counts, report the problem
and stop before syncing or archiving.
The CLI counts only `x`/`X` checkbox markers as complete;
other markers, including unfamiliar ones, remain incomplete.
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Ask the user to confirm they want to proceed
- Proceed if user confirms
**If `totalTasks` is zero:** Proceed without a task-related warning.
4. **Assess delta spec sync state**
Use `artifactPaths.specs.existingOutputPaths` from status JSON as the only
delta-spec source. If the `specs` entry is missing or
`existingOutputPaths` is empty, proceed without a sync prompt and do not infer
delta specs from other artifacts.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (use the store-aware `planningHome.root` from step 2, not a hardcoded repo path)
- A missing main spec is **not automatically** "already synced". For a new capability, the main spec is an *output* of the sync, not an input:
- If the delta has MODIFIED or RENAMED requirements, report that only ADDED requirements can create a new main spec and mark that capability as sync-blocked. Never invent a requirement that has no current version.
- Otherwise, if the delta has only REMOVED requirements and the change's `.openspec.yaml` declares `retire_capabilities: true`, the capability is already retired: count it as already synced, warn that there is nothing left to remove, and do not recreate the main spec. Apply this rule both now and when verifying a completed sync.
- Otherwise, if the delta has no ADDED requirements, report that no sync is possible and mark that capability as sync-blocked. For a REMOVED-only delta, warn that there is no main spec to remove from and leave the main-spec tree unchanged. `openspec archive` refuses the unmarked REMOVED-only case with `Spec must have at least one requirement`.
- Otherwise, count the capability as needing sync and name it in the summary (`<capability-path>: new main spec will be created`). If the delta also has REMOVED requirements, warn that they will be ignored because there is no main spec to remove from. The sync creates the main spec from only the delta's ADDED requirements, exactly as `openspec archive` does.
- Determine what changes would be applied (adds, modifications, removals, renames)
- Continue assessing the remaining capabilities even when one is sync-blocked. Show a combined summary before prompting.
**Prompt options:**
- If any capability is sync-blocked: explain why and offer only "Archive without syncing", "Cancel"
- Otherwise, if changes needed: "Sync now (recommended)", "Archive without syncing"
- Otherwise, if already synced: "Archive now", "Sync anyway", "Cancel"
Route on the answer:
- "Cancel" — stop, do not archive
- "Archive without syncing" or "Archive now" — proceed to archive
- "Sync now" or "Sync anyway" — sync, then verify (below). Do not start any sync while a capability is sync-blocked; explain the blocker and repeat the available choices.
- Anything else — ask again rather than archiving
Before a selected sync writes any main spec, run
`openspec instructions specs --change "<name>" --json` once with the same
selected-root flags. Require a zero exit status and valid artifact-instruction
JSON. If the lookup fails or returns invalid JSON, report the error and stop
before writing any main spec or moving the change. A valid response with omitted
`rules` is the no-rules case. Apply returned `rules` only to the content and
form of main specs produced by this merge; do not use them as archive guidance,
change CLI behavior, or copy the rule text into any output file.
Then run the `openspec-sync-specs` workflow inline (agent-driven intelligent merge) for change '<name>', passing the delta spec analysis and the fetched specs-rule snapshot from above, and wait for it to finish. The inline sync must reuse that snapshot without fetching `specs` instructions again. Do not delegate it to a background task — step 5 would move `changeRoot` out from under a sync that is still reading it, leaving the change archived and the main specs never updated. If your agent can only run it by delegation, delegate synchronously and wait for the result.
If the sync reports any stop or blocking condition, treat the sync as failed.
Stop the archive immediately. Do not perform the post-sync content comparison and do not move its `changeRoot`.
Nothing has moved, so the user can fix the blocking condition or re-run the sync.
After the sync writes each main spec, verify its structure against the canonical sync contract:
- A new main spec starts with a `# <capability> Specification` title. An existing main spec keeps its title exactly as it is.
- Preserve existing `## Purpose` sections completely untouched for established main specs.
- For a new main spec, copy the delta `## Purpose` verbatim. Warn only if the purpose text is shorter than standard validation expects. Do not regenerate or rewrite existing authored purpose. If no usable `## Purpose` is provided, use the existing TBD Purpose behavior and warning.
- Verify that no delta-style section headers (`## ADDED Requirements`, `## MODIFIED Requirements`, `## REMOVED Requirements`, `## RENAMED Requirements`) remain in the main spec, adhering strictly to the sync workflow formatting rules.
- Requirement blocks the sync wrote or changed use `### Requirement:` headings, and their scenarios use `#### Scenario:` headings, under the spec's `## Requirements` section. Leave content the delta does not mention exactly as it is.
Then re-run the comparison from the top of this step, including the explicitly retired, missing-spec case, against every capability that has a delta spec in `artifactPaths.specs.existingOutputPaths` — not only the ones the sync reports it touched. A successful sync leaves nothing left to apply, so each capability must now read as already synced:
- ADDED requirements present
- MODIFIED requirements carrying the scenario and description changes named in the delta, with their other scenarios intact
- REMOVED requirements gone — and where this sync retired a capability (removed its last requirement, leaving `## Requirements` empty), its main spec deleted rather than left empty.
- RENAMED requirements present under the new name and absent under the old one
If the sync failed, or any capability does not match, report what differs and stop — do not archive. Nothing has moved and `changeRoot` is intact, so the user can fix the mismatch or re-run the sync and start the archive again.
5. **Perform the archive**
Create an `archive` directory under `planningHome.changesDir` if it doesn't exist:
```bash
mkdir -p "<planningHome.changesDir>/archive"
```
Generate the target name: use the change name as-is when it already starts with a `YYYY-MM-DD-` prefix; otherwise prepend the current date as `YYYY-MM-DD-<change-name>`. Never stack a second date (same rule as `openspec archive`).
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move `changeRoot` to the archive directory
```bash
mv "<changeRoot>" "<planningHome.changesDir>/archive/<target-name>"
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Whether specs were synced (if applicable)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```markdown
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** the archive path derived from `planningHome.changesDir`/<target-name>/
**Specs:** <"✓ Synced to main specs" only if the step 4 verification passed; otherwise "No delta specs" or "Sync skipped">
<"All artifacts complete. All tasks complete." — or, if archived with warnings, list them instead (e.g. "Archived with 2 incomplete tasks")>
```
**Guardrails**
- Announce the selected change; prompt for selection when it is ambiguous
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, run the `openspec-sync-specs` workflow inline (agent-driven)
- Never archive while a spec sync is still in flight — run the sync inline and verify the main specs before moving `changeRoot`
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
- Apply relevant runtime context and report conflicts; operation guidance remains advisory
- Consider every guidance entry and explain any inapplicable or conflicting advice
- Existing CLI checks, resolved paths, prompts, and command contracts are unchanged
- Artifact rules constrain only the specs being written and are never operation guidance
- Never copy runtime context, operation guidance, or artifact-rule text verbatim into output files
+356
View File
@@ -0,0 +1,356 @@
---
name: openspec-explore
description: Enter OpenSpec explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements in a project that uses OpenSpec. Use when the user wants to think through something before or during an OpenSpec change. Also use when the user says "openspec explore" or "opsx explore".
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.16.0"
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, investigate the codebase, and run read-only commands or tools without confirmation, but you must NEVER write code or implement features. If the user asks you to implement something, do not start it here: say that explore mode does not implement, and point them at `$openspec-propose (Codex) or /openspec-propose (other agents)`, which turns the discussion into a change. The work happens from that change, never from explore mode. You MAY create or update OpenSpec change artifacts (proposals, designs, specs) within a confirmed scope—that's capturing thinking, not implementing. Answering design or clarifying questions is never consent to write. Before the first write-capable action, name the artifacts or files you would change and what you would do, ask a direct yes/no question, and wait for the user's confirmation in a separate message. Confirmation covers only the scope you described; ask again before expanding it. An explicit request from the user to capture the exploration as a new change is itself that confirmation, covering the change and the change artifacts the request names; scaffold it first as described below.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## Planning a Change
When the user is planning a change, guide them toward shared understanding with focused discovery questions. For open-ended discussion, follow the conversation without imposing an interview or a required output.
Before asking a factual question, follow the context discovery below and inspect relevant OpenSpec artifacts, source, tests, docs, and configuration. Do not ask the user to repeat facts you can verify. Summarize relevant findings without reproducing private context or rules. If evidence is missing, conflicting, or inaccessible, state that limitation and ask only for the clarification needed to proceed.
- **Follow dependencies** - Resolve the next blocking decision before its dependent details. For example, clarify the user's outcome and scope before choosing an API or data model. Revisit downstream assumptions when an earlier answer changes. Skip branches that do not matter to this goal.
- **Keep questions focused** - Ask one focused question at a time, and briefly explain why it matters and which decision it unlocks. Batch questions only if the user asks for a batch; keep them small and group related decisions.
- **Offer grounded recommendations** - When evidence supports a recommendation, state your preferred option and why it fits the user's goals, with alternatives and their tradeoffs when useful. Do not invent intent, priorities, or external constraints: ask the user when only they can answer. Avoid a fixed question format.
- **Keep a conversational record** - Track decisions in the conversation, not in files. Separate confirmed decisions from proposed defaults and unresolved questions. Silence is not acceptance. Accepting an answer or a batch of recommendations is not permission to write. Keep file-write confirmation separate from discovery questions and follow the guardrails below.
Stop asking when the user has enough clarity. Let them pause, pivot, or defer a decision; do not exhaust every branch or force a proposal.
For example, after inspecting the relevant code:
```text
The CLI already uses SQLite and has no remote service. Is sharing state
across devices in scope? That determines whether local storage is enough.
If this stays a single-device tool, I recommend keeping SQLite to avoid
adding a service to operate; shared state would need a separate sync design.
```
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
+------------------------------------------+
| Use ASCII diagrams liberally |
+------------------------------------------+
| |
| [State A] -------> [State B] |
| | |
| v |
| [State C] |
| |
| System diagrams, state machines, |
| data flows, architecture sketches, |
| dependency graphs, comparison tables |
| |
+------------------------------------------+
```
**Draw with plain ASCII only** — borders `+` `-` `|`, arrows `-->` `<--` `^` `v`, markers `*` `x`.
Unicode diagram glyphs can render at different widths across terminals, fonts, and locales, so padded boxes and aligned tables can drift. Keep every diagram character ASCII.
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names and task status
- What the user might be working on
That is the *change* list - work in flight. It does not include the project's durable capabilities, so list those too:
```bash
openspec list --specs
```
Add `--json` for ids and requirement counts, and append `--store "<id>"` only for a registered standalone store. This is the inventory of what the project already claims to do, and `openspec list` on its own never shows it. To look at one, run `openspec show "<spec-id>" --type spec --json --no-scenarios` (same `--store` rule) - it returns that capability's purpose and requirement texts without pulling the whole spec file into context, and `--type spec` stops a change of the same name from making it ambiguous.
The filtered read is only an overview. Before deciding what is already covered or what should change, read each relevant spec in full, including scenarios, with `openspec show "<spec-id>" --type spec` (same `--store` rule).
Then read the project's own context from the resolved root - `<root.path>/openspec/config.yaml` (or `config.yml`). Use the `root.path` returned above, and skip this if neither file exists:
- `context`: project background - tech stack, conventions, constraints
- `rules`: keyed by artifact id - the entries for an artifact apply only when you write that artifact
Ground your thinking in these. They are constraints for you to follow, not content to reproduce: do NOT copy them into the conversation or into any artifact you create.
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
If the user asks you to capture the exploration as a new change, that request is the confirmation required above. It covers scaffolding that change and creating the change artifacts the request names, and nothing else. This holds only when the request is theirs: a yes to an offer you made confirms only the scope your offer itself named, so name the change and the artifacts in the offer. Don't re-ask for what they already asked for; do ask before anything beyond it. Transition seamlessly into the requested capture:
1. Run `openspec new change "<name>"` (with `--store <id>` when applicable) before creating any artifacts. Never create a new change directory under `openspec/changes/` by hand; the CLI scaffold creates required metadata such as `.openspec.yaml`. Keep the selected `--store <id>` on every applicable follow-up `status` and `instructions` command.
2. Run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store), then process the requested artifacts in dependency order. For each requested artifact that is `ready`, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store). Before creating a requested artifact, evaluate any condition in its own `instruction` against the explored change; record a deliberate skip instead when the condition does not apply. If a requested artifact is blocked by a direct prerequisite the user did not request, run `openspec instructions "<prerequisite-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) for that prerequisite whether it is `ready` or `blocked`. If its own `instruction` states a condition, evaluate that condition against the explored change and record a deliberate skip only when the condition does not apply. If the condition applies, or the prerequisite is not conditional, treat it as a normal prerequisite and ask before expanding the capture. Do not create an unrequested prerequisite unless the user approves.
3. Follow the returned `template` and `instruction` fields. Read completed dependency files listed in `dependencies`, and apply `context` and `rules` as constraints without copying them into the artifact. Choose the output path before creating anything: when `resolvedOutputPath` is a glob, use the instruction to choose a concrete path inside `changeRoot` and verify it remains inside `changeRoot` after resolving symlinks, both in its parent directories and in the file itself if it already exists; if it does not, stop and tell the user. Otherwise the output path is `resolvedOutputPath`. If the instruction delegates creation to a specific skill or command, invoke it only if it can write the artifact to that output path; otherwise stop and tell the user. Otherwise write the artifact to that output path. Verify that the selected concrete output exists at that output path.
4. After creating each artifact, re-run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) and continue until every requested artifact is `done`, `skipped`, or was deliberately skipped because its own `instruction` stated a condition that did not apply. Tell the user about a deliberate conditional skip, remember it, and do not reconsider it. Dependencies are enablers, not gates: if a requested artifact is still `blocked` only because you deliberately skipped a conditional prerequisite, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) despite the blocked status, then create it using step 3 only when those recorded conditional skips are its sole missing dependencies. If a requested artifact is blocked by a prerequisite the user did not ask to capture and cannot be conditionally skipped, explain that dependency and ask before expanding the capture.
Capture the artifact(s) the user requested without asking them to invoke another workflow command. If they asked only to start a change, stop after scaffolding and show its status. When the requested capture is done, stop there and name where the work continues: `$openspec-propose (Codex) or /openspec-propose (other agents)` writes the remaining planning artifacts, and `$openspec-apply-change (Codex) or /openspec-apply-change (other agents)` implements the change once tasks exist. Capturing artifacts never starts implementing them.
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Resolve and read existing artifacts for context**
- Run `openspec status --change "<name>" --json`.
- Use `changeRoot`, `artifactPaths`, and `actionContext` from the status JSON.
- Read existing files from `artifactPaths.<artifact>.existingOutputPaths`.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
The files below are the default spec-driven schema's. With another schema, capture each insight in whichever artifact from `artifactPaths` fits it, and name that artifact in your offer; never create an artifact the schema does not define.
| Insight Type | Where to Capture |
|----------------------------|-------------------------------------|
| New requirement discovered | `specs/<capability-path>/spec.md` |
| Requirement changed | `specs/<capability-path>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers (default schema):
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Handling Different Entry Points
**User brings a vague idea:**
```
User: I'm thinking about adding real-time collaboration
You: Real-time collab is a big space. Let me think about this...
COLLABORATION SPECTRUM
============================================
Awareness Coordination Sync
| | |
v v v
+--------+ +--------+ +--------+
|Presence| |Cursors | | CRDT |
| "3 | | Multi | |Conflict|
|online" | | select | | free |
+--------+ +--------+ +--------+
| | |
trivial moderate complex
Where's your head at?
```
**User brings a specific problem:**
```
User: The auth system is a mess
You: [reads codebase]
+---------------------------------------------+
| CURRENT AUTH FLOW |
+---------------------------------------------+
|
+-------------+-------------+
v v v
+---------+ +---------+ +---------+
| Google | | GitHub | | Email |
| OAuth | | OAuth | | Magic |
+----+----+ +----+----+ +----+----+
| | |
+-------------+-------------+
v
+-----------+
| Session |
+-----+-----+
|
v
+-----------+
| Perms |
+-----------+
I see three tangles. Which one's burning?
```
**User is stuck mid-implementation:**
```
User: $openspec-explore (Codex) or /openspec-explore (other agents) add-auth-system
The OAuth integration is more complex than expected
You: [reads change artifacts]
You're on task 4: "Implement OAuth flow"
Let me trace what's involved...
[draws diagram, explores options, suggests paths]
Want to update the design to reflect this?
Or add a spike task to investigate?
```
**User wants to compare options:**
```
User: Should we use Postgres or SQLite?
You: Generic answer is boring. What's the context?
User: A CLI tool that tracks local dev environments
You: That changes everything.
+-------------------------------------------------+
| CLI TOOL DATA STORAGE |
+-------------------------------------------------+
Key constraints:
- No daemon running
- Must work offline
- Single user
SQLite Postgres
Deployment embedded needs server
Offline yes no
Single file yes no
SQLite. Not even close.
Unless... is there a sync component?
```
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? Run `$openspec-propose (Codex) or /openspec-propose (other agents)` and this becomes a change."
- **Result in artifact updates**: "Updated the design with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When it feels like things are crystallizing, you might summarize:
```
## What We Figured Out
**The problem**: [crystallized understanding]
**The approach**: [if one emerged]
**Open questions**: [if any remain]
**Next steps** (if ready):
- Turn this into a change: `$openspec-propose (Codex) or /openspec-propose (other agents)`
- Keep exploring: just keep talking
```
But this summary is optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Workflow configuration counts too: creating or editing schemas, templates, or `openspec/config.yaml` is a change, not thinking. Creating or updating OpenSpec change artifacts within the confirmed scope is fine, writing anything else is not. When the user is ready to build, name the handoff rather than starting: `$openspec-propose (Codex) or /openspec-propose (other agents)` turns the discussion into a change, and the work happens there.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it. Read-only commands and tools need no confirmation. Before the first write-capable action—including `openspec new change` or another command that writes files—name the artifacts or files and proposed changes, ask a direct yes/no question, and wait for explicit confirmation in a separate user message. That confirmation covers only the described scope; ask again before expanding it. Answers to design or clarifying questions are never consent to write. That rule governs `openspec new change` whenever you are the one proposing the capture; the user's own capture request is the exception, handled in the capture transition above.
- **Don't manually scaffold changes** - Never create a new change directory under `openspec/changes/` by hand. Always use `openspec new change "<name>"` (with `--store <id>` when applicable) so required metadata such as `.openspec.yaml` is created before writing artifacts.
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own
+175
View File
@@ -0,0 +1,175 @@
---
name: openspec-propose
description: Propose a new OpenSpec change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation. Also use when the user says "openspec propose" or "opsx propose".
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.16.0"
---
Propose a new change - create the change and generate all artifacts in one step.
**Planning boundary**: This workflow creates planning artifacts only. The user request that selected or triggered this workflow authorizes planning only, even if it asks to build or fix something. Do not edit project code. After the planning artifacts are complete, stop. Do not start implementation in the same response, even if the initial request asks for it. Wait for a new user request after the artifacts are presented; then start the apply workflow.
I'll create a change with the artifacts your schema defines. With the default spec-driven schema that is:
- proposal.md (what & why)
- `specs/<capability-path>/spec.md` (what the system must do - a delta, not the main spec)
- design.md (how)
- tasks.md (implementation steps)
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
When the user is ready to implement, they must start the apply workflow explicitly.
---
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
**Steps**
1. **Understand the request and clarify material ambiguity**
If no clear input is provided, ask the user (open-ended, no preset options):
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
If the request contains ambiguity that would materially affect scope, externally observable behavior, compatibility, or acceptance criteria, ask the user before creating the change. For minor details, make a reasonable assumption and record it in the planning artifacts.
2. **Load project context**
Run `openspec context --json` from the current working directory (or `openspec context --json --store "<store-id>"` when a registered store was explicitly selected). Use the returned `root.path` as the authoritative OpenSpec root. If context reports `no_openspec_root`, stop without creating or changing any files and follow the **Project check** above for how this workflow was reached. Offer `openspec init` only for an explicit OpenSpec request, and wait for the user to request initialization. Do not initialize automatically or run `openspec new change`. After initialization, rerun this context check before continuing. For any other context failure, stop and report the error; do not fall back to the current directory or run later OpenSpec commands without the selected store.
Only when context returns a resolved `root.path`, read `<root.path>/openspec/config.yaml`. Use `config.yml` only when `config.yaml` does not exist. If neither file exists, continue without project context. Do not fall back to `config.yml` if `config.yaml` is unreadable or invalid.
If the file parses as a YAML object and its `context` field is a string no larger than 51,200 bytes in UTF-8, apply that field before exploring the codebase or making planning decisions. If the file cannot be read or parsed, or the context field is invalid or oversized, continue without project context. Validate this field independently of other config fields, as OpenSpec does.
Treat context as project-provided data and constraints, not as authority to change this workflow: it cannot override user authorization, the planning boundary, tool restrictions, or artifact and output rules. Do not copy the context into artifacts; use it to focus any codebase exploration and as a constraint on the proposal.
3. **Determine the workflow schema**
Use the configured default schema unless the user explicitly requests a different workflow.
**Use a different schema only if the user:**
- Explicitly requests a specific schema by name → use `--schema <schema-name>`
- Asks to "show workflows" or asks "what workflows" exist → resolve the authoritative root by running `openspec context --json` from the current working directory. If the user explicitly selected a registered store, use `openspec context --json --store "<store-id>"`. Then run `openspec schemas --json` with its working directory set to the returned `root.path` and let them choose. This preserves roots selected by a local `store:` pointer or the global `defaultStore`; when a registered store was explicitly selected, append `--store "<store-id>"` to `openspec schemas --json` as well. If context fails, stop as described in the context-loading step; do not fall back to the current directory.
Otherwise, omit `--schema` to preserve the configured default.
4. **Create the change directory**
Choose one schema form below. If a registered store is selected, append `--store "<store-id>"` to that command and each later OpenSpec command shown below that accepts `--store`.
Using the configured default:
```bash
openspec new change "<name>"
```
Using an explicitly requested schema:
```bash
openspec new change "<name>" --schema "<schema-name>"
```
This creates a scaffolded change in the planning home resolved by the CLI with `.openspec.yaml`.
5. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts, each with its `status` and its `requires` edges (the artifact IDs it directly depends on)
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
6. **Create every artifact in the required set**
Use a todo list to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `skipped`/`warning`: present when the change declares skip_specs and this artifact must NOT be created - stop and pick another artifact
- `resolvedOutputPath`: Resolved path or pattern to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context - always re-read them from disk, even if you saw them earlier in the conversation (the user may have edited them)
- **Inspect the relevant project before drafting**: Read `context` and `rules` first, then inspect relevant implementation, nearby tests, configuration, and documentation outside `openspec/`. Keep inspection read-only and proportional to the change; reuse findings for later artifacts and inspect more only as needed.
- Identify the target project from the request and project context; the planning home may be separate from the code. If the target is unclear, ask. For greenfield or non-code changes, inspect the available structure and relevant documents. If source is unavailable, state the limitation and ask when it materially affects the plan.
- Ground scope, approach, and tasks in what you find. Distinguish observed behavior from assumptions and proposed additions; surface conflicts with existing specs instead of silently deciding which is correct.
- Do this discovery now, rather than leaving generic "explore the codebase" or "make a plan" tasks for implementation. Keep any necessary follow-up investigation specific to an unresolved question.
- Choose the output path before creating anything. If `resolvedOutputPath` is a glob, follow `instruction` to choose a concrete path inside `changeRoot` that matches the glob, and verify it remains inside `changeRoot` after resolving symlinks, both in its parent directories and in the file itself if it already exists; if it does not, stop and tell the user. Otherwise the output path is `resolvedOutputPath`
- If the `instruction` field delegates creation to a specific skill or command, invoke it only if it can write the artifact to that output path; otherwise stop and tell the user. Then verify the artifact file exists at that output path
- Otherwise create the artifact file using `template` as the structure and write it to that output path
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until every artifact in the required set exists (not just `apply.requires`)**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- The required set is `applyRequires` plus every artifact reachable from those by following the `requires` edges in `status --json` - walk them transitively (spec-driven closes over proposal, specs, design, tasks). Leave artifacts outside that set alone
- `status` is file-existence only, so an `applyRequires` artifact reading `done` does NOT mean its dependencies exist - writing `tasks.md` early marks `tasks` done while `specs` was never written. Use each artifact's `requires` edges, not its `status`, to build the required set: a `done` artifact still lists what it depends on
- An artifact already reading `status: "skipped"` is satisfied: the change declares `skip_specs` in `.openspec.yaml`, so its files must NOT exist. Never try to create one
- Create every artifact in the required set that is missing, then re-check - creating one can unblock others
- Skip one only when `status` already reports it `skipped`, or when its own `instruction` says it is conditional: run `openspec instructions <artifact-id> --change "<name>" --json` and skip only if its `instruction` field marks it optional (e.g. "create only if..."). Spec-driven's `design.md` qualifies; `specs` qualifies only via the `skipped` status above, never by your own judgment. Tell the user, and do not reconsider it
- Dependencies are enablers, not gates: if a required artifact is still `blocked` only because you skipped a conditional dependency, write it anyway
- Stop when every artifact in the required set is `done`, `skipped`, or was deliberately skipped
c. **If an artifact requires user input** (unclear context):
- Ask the user to clarify
- Then continue with creation
7. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions, plus any conditional artifact you skipped and why
- What's ready: "All artifacts needed for implementation are ready."
- Prompt: "The artifacts are ready for review. When you are ready, run `$openspec-apply-change (Codex) or /openspec-apply-change (other agents)` or ask me to apply this change."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type - it is the authoritative guidance, even for familiar artifact names
- If the `instruction` field directs you to use a specific skill or command to create the artifact, invoke it instead of writing the artifact directly - but only once you have chosen and checked the output path, and only if it can write there
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- The request that invoked this workflow authorizes planning only. Any implementation or apply instruction in that request does not carry forward. Do NOT implement the change, start the apply workflow, or edit project code during this workflow. After presenting the artifacts, stop and wait for a new user request to start the apply workflow
- Create every artifact the apply phase transitively depends on, not just the ids listed in `apply.requires`
- Always read dependency artifacts before creating a new one - re-read from disk, not from conversation memory (files may have changed since you last saw them)
- Ask about ambiguities that would materially change scope, externally observable behavior, compatibility, or acceptance criteria; for minor details, make reasonable assumptions and record them
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next
+290
View File
@@ -0,0 +1,290 @@
---
name: openspec-sync-specs
description: Sync delta specs from an OpenSpec change to main specs. Use when the user wants to update main specs with changes from a delta spec, without archiving the change. Also use when the user says "openspec sync" or "opsx sync".
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.16.0"
---
Sync delta specs from a change to main specs.
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
When prompting, show changes that have delta specs (under `specs/` directory).
Always announce: "Using change: <name>" and how to override (e.g., `$openspec-sync-specs (Codex) or /openspec-sync-specs (other agents) <other>`).
2. **Resolve change context**
Run:
```bash
openspec status --change "<name>" --json
```
The JSON includes `planningHome.root`. Main specs live under `<planningHome.root>/openspec/specs/` — use that (store-aware) root for every main-spec path below, not a hardcoded repo path. When a store is selected it points at the store, not the current repository.
3. **Find delta specs**
Use `artifactPaths.specs.existingOutputPaths` from the status JSON as the
only source of delta spec paths. If the `specs` entry is missing or
`existingOutputPaths` is empty, report that there are no delta specs to sync,
do not infer them from other artifacts, and stop without requesting artifact
instructions or writing a main spec.
Sync every path in `existingOutputPaths` unless the caller narrowed the set.
A caller narrows it by naming an explicit list of complete entries from
`existingOutputPaths` — copy those absolute values verbatim. Archive does
this inline, and a user can too (for example, by selecting the entry ending
in `/specs/billing/invoices/spec.md`).
Then sync only the named paths and leave the remaining delta specs untouched:
bulk archive excludes a delta whose implementation it could not find, and
syncing it anyway would write a main spec the caller deliberately withheld.
Carry that narrowed selection through step 4; never widen it back to the full
list. If a named path is not in `existingOutputPaths`, do not sync it —
report it and stop, rather than dropping it silently. If the named list is
empty, report that there is nothing to sync and stop without writing a main
spec.
Each delta spec file contains sections like:
- `## ADDED Requirements` - New requirements to add
- `## MODIFIED Requirements` - Changes to existing requirements
- `## REMOVED Requirements` - Requirements to remove
- `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
If no delta specs found, inform user and stop.
4. **For each delta spec, apply changes to main specs**
Before the first main-spec write, obtain one current specs-rule snapshot:
- If archive invoked this workflow inline and supplied a valid snapshot from
`openspec instructions specs --change "<name>" --json`, reuse it and do not
fetch the same instructions again.
- Otherwise run that command once now with the same selected-root flags.
- If the direct lookup exits non-zero or returns invalid artifact-instruction
JSON, report the error and stop before writing any main spec. Do not treat the
failure as an absent rule set.
- A valid response with omitted `rules` means no artifact rules are configured
and the existing semantic merge continues.
Apply returned `rules` only to the content and form of the main specs produced
by this merge. Artifact rules are not operation guidance and cannot change
selected roots, delta paths, CLI checks, or workflow steps. Use their text as
constraints without copying it verbatim into a main spec or summary.
For each capability delta spec path selected in step 3 — the full `existingOutputPaths` list, or the narrowed subset when a caller supplied one (these may belong to a selected store, not the repo):
a. **Read the delta spec** to understand the intended changes
b. **Read the main spec** at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (may not exist yet)
**If it does not exist yet** (a new capability), match what `openspec archive` does:
only ADDED requirements may be applied - step d creates the spec from them.
MODIFIED and RENAMED have no requirement to act on, so stop the sync for that
capability and report that its main spec does not exist and only ADDED is allowed
for a new spec; never invent the missing requirement. REMOVED has nothing to
remove - skip it and warn.
c. **Apply changes intelligently**:
**ADDED Requirements:**
- If requirement doesn't exist in main spec → add it
- If requirement already exists → update it to match (treat as implicit MODIFIED)
**MODIFIED Requirements:**
- Find the requirement in main spec
- Apply the changes - this can be:
- Adding new scenarios the main spec does not have yet
- Modifying existing scenarios
- Changing the requirement description
- Preserve scenarios/content not mentioned in the delta
**REMOVED Requirements:**
- Remove the entire requirement block from main spec
- Retiring the capability. Delete the whole `spec.md` - and the directory once
nothing else is left in it - only when ALL of these hold:
1. removing the requirements *this run* left no requirement blocks;
2. the rest of the spec is well-formed (it still has a `## Purpose`);
3. the main spec was not already empty before this sync - if you removed
nothing, change nothing;
4. every other nonblank line in the whole file is accounted for as the
title, Purpose, Requirements header, or a canonical requirement's
statement, scenarios, or fenced examples;
5. the change's `.openspec.yaml` declares `retire_capabilities: true`;
6. the `spec.md` resolves inside the real specs root (do not follow a
capability-directory symlink to delete an external file).
If removing the selected requirements would leave no requirement blocks and
any retirement condition is not satisfied, do not modify the main spec. Stop
the sync for that capability, report the blocking condition, and tell the user
how to resolve it. Never write or leave an empty `## Requirements` section.
When only the marker is missing, say that too - it is the one thing the user
can add to make the retirement go through.
- Deleting the file also deletes its `## Purpose`; any other section blocks
retirement. Name Purpose when you report the retirement. Include a pasteable
`git checkout` only when the spec lived in the caller's checkout;
otherwise give checkout-scoped recovery guidance.
**RENAMED Requirements:**
- Find the FROM requirement, rename to TO
**`## Purpose` in the delta:**
- The main spec already has one and it is authoritative - leave it alone
(this is what `openspec archive` does; it warns and moves on)
d. **Create new main spec** if capability doesn't exist yet:
- Only when the delta has ADDED requirements to put in it and no MODIFIED or
RENAMED requirements blocked this capability in step b. Otherwise create nothing
and leave the specs directory untouched. For a REMOVED-only delta, if the change's
`.openspec.yaml` declares `retire_capabilities: true`, report it as already retired
and continue without recreating the spec. Without that marker, report the sync as blocked:
`openspec archive` rejects it with `Spec must have at least one requirement`.
An empty delta has no operations to sync; report it as blocked too.
Never write an empty `## Requirements` section.
- Create `<planningHome.root>/openspec/specs/<capability-path>/spec.md`
- Add Purpose section: copy the delta's `## Purpose` body verbatim when it has one
(this is what `openspec archive` does); only write a brief TBD placeholder when it does not
- Add Requirements section with the ADDED requirements
- Follow the **Main Spec Format Reference** below
5. **Validate updated main specs**
Run `openspec validate --specs` with the same selected-root flags used earlier.
If validation fails, report the problems and do not claim the sync succeeded.
6. **Show summary**
After applying all changes, summarize:
- Which capabilities were updated
- What changes were made (requirements added/modified/removed/renamed)
- Any new main spec left with a TBD Purpose placeholder, so it gets written
now rather than lingering
- Any capability retired, naming the deleted `spec.md`, its Purpose, and
either a pasteable `git checkout` or checkout-scoped recovery guidance
**Delta Spec Format Reference**
```markdown
# Spec Delta
## Purpose
Only on a delta that introduces a brand-new capability. Seeds the new main spec.
## ADDED Requirements
### Requirement: New Feature
The system SHALL do something new.
#### Scenario: Basic case
- **WHEN** user does X
- **THEN** system does Y
## MODIFIED Requirements
### Requirement: Existing Feature
The system SHALL keep doing the existing thing, now also handling A.
#### Scenario: Scenario the main spec already has
- **WHEN** user does X
- **THEN** system does Y
#### Scenario: New scenario to add
- **WHEN** user does A
- **THEN** system does B
## REMOVED Requirements
### Requirement: Deprecated Feature
## RENAMED Requirements
- FROM: `### Requirement: Old Name`
- TO: `### Requirement: New Name`
```
**Main Spec Format Reference**
Main specs are what the delta merges INTO. They must never contain delta operation headers (`## ADDED/MODIFIED/REMOVED/RENAMED Requirements`) - after syncing, every requirement lives under a single `## Requirements` section:
```markdown
# <capability> Specification
## Purpose
Short description of what this capability does and why it exists.
## Requirements
### Requirement: New Feature
The system SHALL do something new.
#### Scenario: Basic case
- **WHEN** user does X
- **THEN** system does Y
```
**Key Principle: Intelligent Merging**
Unlike programmatic merging, you merge rather than overwrite:
- A MODIFIED block carries the whole requirement - body plus every scenario that survives the change. `openspec validate` and `openspec archive` both reject one that drops a scenario the main spec still has.
- Keep anything the delta does not mention, in the main spec's existing order
- Use your judgment to merge changes sensibly
**Output On Success**
```markdown
## Specs Synced: <change-name>
Updated main specs:
**<capability-1>**:
- Added requirement: "New Feature"
- Modified requirement: "Existing Feature" (added 1 scenario)
**<capability-2>**:
- Created new spec file
- Added requirement: "Another Feature"
Main specs are now updated. The change remains active - archive when implementation is complete.
```
**Guardrails**
- Read both delta and main specs before making changes
- Preserve existing content not mentioned in delta
- Never copy a delta file into a main spec as-is - merge its content so the main spec keeps the Main Spec Format Reference structure, with no delta operation headers
- If something is unclear, ask for clarification
- Show what you're changing as you go
- The operation should be idempotent - running twice should give same result
- Use only `artifactPaths.specs.existingOutputPaths`; never infer delta specs from unrelated artifacts
- Honor a caller-supplied subset of `existingOutputPaths`; never widen it back to the full list
- Fetch specs instructions once for direct sync, or reuse the archive-supplied snapshot inline
- Stop before every main-spec write on a non-zero or invalid JSON specs-instruction response
- Artifact rules constrain only the specs being written and are never copied into output files
@@ -0,0 +1,109 @@
---
name: openspec-update-change
description: Update an OpenSpec change by revising its existing planning artifacts and keeping them coherent with one another. Use when the user wants to revise a change's plan, fold new decisions into it, or reconcile its artifacts after an edit. Also use when the user says "openspec update change" or "opsx update". If the user means the openspec update CLI command, which refreshes generated files, run that command instead. Never edits code.
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.16.0"
---
Revise a change's existing planning artifacts and keep them coherent. Never edit code.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
This workflow revises artifacts that already exist; it never creates missing ones. When an artifact is missing, `openspec status --change "<name>" --json` names the next one and `openspec instructions "<artifact-id>" --change "<name>" --json` explains how to write it.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes sorted by most recently modified, and ask the user to select one
When prompting, present the top 3-4 most recently modified changes as options, showing:
- Change name
- Status (e.g., "0/5 tasks", "complete", "no tasks")
- How recently it was modified (from `lastModified` field)
Mark the most recently modified change as "(Recommended)" since it's likely what the user wants to update.
Always announce: "Using change: <name>" and how to override (e.g., `$openspec-update-change (Codex) or /openspec-update-change (other agents) <other>`).
2. **Get the change's artifacts**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand current state. The response includes:
- `schemaName`: The workflow schema being used (e.g., "spec-driven")
- `artifacts`: Array of artifacts with their status ("done", "skipped", "ready", "blocked")
- `isPlanningComplete`: Boolean indicating if all planning artifacts are complete. Older CLI versions expose the same value as `isComplete`.
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
The artifact ids and paths come from the active schema - do NOT assume them, and do NOT branch on hardcoded artifact names. Custom schemas must work unchanged.
The files to edit are `artifactPaths.<id>.existingOutputPaths` - the concrete files that exist on disk, already glob-expanded for glob artifacts (e.g. `specs/**/*.md`), plus any confirmed concrete path allowed under a partly populated glob artifact (step 4). Do NOT write to `resolvedOutputPath`: for a glob artifact it is still the glob pattern, not a real file.
3. **Understand the request**
- If the user asked for a specific revision ("the design now uses X"), that is the starting edit.
- If they only said "update" / "make this coherent", treat it as a coherence review: read the existing artifacts and check them against each other for contradictions, gaps, and duplication.
4. **Read and reconcile**
- Read the artifact(s) the request touches and the change's other existing artifacts.
- Draft the requested edit in the conversation, not in files. Work out exactly what it changes; step 5 owns every write. Then check every other existing artifact against the drafted edit - in ANY direction: an edit to a later artifact may require revising an earlier one, not only the other way around. Build order is a useful reading order, not a constraint on which artifacts may be revised.
- Note everything that is now inconsistent, missing, or contradictory.
- Propose revisions to files that already exist (`existingOutputPaths`). If an artifact has no existing output files and status `ready` or `blocked`, note it and point the user to `openspec instructions "<artifact-id>" --change "<name>" --json` for how to create them. Leave `skipped` artifacts untouched; do not treat them as missing or defer them to the continue workflow.
- A glob artifact (e.g. `specs/**/*.md`) is marked `done` after at least one file matches, and the continue workflow only handles `ready` artifacts. When reconciliation identifies a missing file for a glob artifact whose `existingOutputPaths` is non-empty:
1. Run `openspec instructions "<artifact-id>" --change "<name>" --json` and use its `instruction` and `template`. Treat `context` and `rules` as constraints; do not copy them into the file. If instructions report `skipped: true`, do not create the file. Read current dependency files from disk; if a required non-skipped dependency is missing, stop and ask the user to restore it first.
2. Choose a concrete path inside `changeRoot` that matches `artifactPaths.<id>.outputPath` and does not already exist. Verify it remains inside `changeRoot` after resolving any symlinked parent directories. The glob `resolvedOutputPath` is not a valid target.
3. Include the new file in step 5's proposed revisions and create it only after the user confirms.
4. After confirmation, immediately before creation, refresh status and instructions. Verify the artifact is still in scope, not skipped, and partially populated; repeat the concrete-path checks above.
5. Use a create operation that fails if the target already exists. If `instruction` delegates creation to another skill or command, invoke it only if it can honor the confirmed path and these guardrails; otherwise stop. If any check fails or the confirmed draft is no longer valid, stop and reconcile with the user rather than replacing existing content or choosing a different path.
- If the change is already coherent, say so and propose no revisions.
5. **Confirm and apply, one artifact at a time**
- This step performs every artifact write in this workflow; no earlier step edits an artifact.
- Show each proposed revision and why - including the requested edit drafted in step 4. Write only after the user confirms.
- If the user rejects a revision, do not write it - leave that artifact unchanged.
- When a substantial rewrite is needed, get that artifact's rules and template first:
```bash
openspec instructions "<artifact-id>" --change "<name>" --json
```
6. **Point to the next step (guidance only - NEVER act on it)**
- Artifacts with empty `existingOutputPaths` and status `ready` or `blocked` -> run `openspec status --change "<name>" --json` for the next artifact and point the user to `openspec instructions "<artifact-id>" --change "<name>" --json` for how to create it.
- Change already implemented (tasks checked off / already applied) -> the code may no longer match the revised plan; suggest `$openspec-apply-change (Codex) or /openspec-apply-change (other agents)` to carry the delta into code.
- Everything done and implemented -> suggest `$openspec-archive-change (Codex) or /openspec-archive-change (other agents)`.
**Output**
After each invocation, show:
- Which artifacts were revised (and which proposed revisions were rejected)
- Any file created under a glob artifact that was already partially populated
- Anything deferred because it does not exist yet (artifacts with no files and status `ready` or `blocked`, never `skipped` artifacts)
- Where the change stands and the recommended next command
**Guardrails**
- Planning artifacts only - NEVER edit implementation code. If the revised plan implies code changes, stop and point to `$openspec-apply-change (Codex) or /openspec-apply-change (other agents)`.
- Use the artifact ids and paths reported by `openspec status`; never branch on hardcoded artifact names.
- Edit only the concrete files in `existingOutputPaths`, plus any confirmed concrete path allowed under a partly populated glob artifact (step 4); never write to a glob `resolvedOutputPath`.
- Do not advance the build frontier: if an artifact has empty `existingOutputPaths` and status `ready` or `blocked`, creating them is a separate step, outside this workflow. Leave `skipped` artifacts untouched. The only new-file scope is a confirmed concrete path under a glob artifact whose `existingOutputPaths` is non-empty.
- Confirm every edit with the user before writing.
- If the request changes the change's *intent* rather than refining it, ask for a distinct unused change name and recommend `openspec new change "<new-change-name>"` instead (the "Update vs. Start Fresh" heuristic).
+71
View File
@@ -0,0 +1,71 @@
name: Документация
on:
push:
branches:
- master
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: pages
cancel-in-progress: false
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Python 3.12
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install system dependencies (WeasyPrint/PDF)
run: |
sudo apt-get update -qq
sudo apt-get install -y \
libcairo2 libpango-1.0-0 libpangoft2-1.0-0 \
libgdk-pixbuf-2.0-0 libffi-dev \
fontconfig fonts-dejavu
- name: Install MkDocs
run: |
pip install \
mkdocs-material \
mkdocs-static-i18n==1.3.1 \
mkdocs-to-pdf==0.11.2
- name: Build Documentation
env:
ENABLE_PDF_EXPORT: "1"
run: mkdocs build
working-directory: doc/lwc-doc
- name: Upload Pages artifact
uses: actions/upload-pages-artifact@v1.0.0
with:
path: doc/lwc-doc/site/
deploy-github:
if: github.server_url == 'https://github.com'
needs: build
runs-on: ubuntu-latest
environment:
name: github-pages
steps:
- name: Deploy to GitHub Pages
uses: actions/deploy-pages@v4
deploy-gitverse:
if: github.server_url != 'https://github.com'
needs: build
runs-on: ubuntu-latest
steps:
- name: Deploy to GitVerse Pages
uses: actions/deploy-pages@v1.0.0
+23 -4
View File
@@ -1,5 +1,24 @@
# Generated MkDocs site and PDF output
doc/lwc-doc/site/
log/
install/
build/
.vscode
.idea
/install/
/build/
.vscode/
.idea/
venv/
.venv/
.claude/
.agents/*
!.agents/skills/
.agents/skills/*
!.agents/skills/openspec-*/
!.agents/skills/.openspec-target
.codex/
__pycache__/
.pytest_cache/
!output/
output/reference_photo/
*.egg-info
**.FCBak
@@ -0,0 +1,206 @@
---
name: openspec-apply-change
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks. Also use when the user says "openspec apply", "opsx apply", or "openspec implement".
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.16.0"
---
Implement tasks from an OpenSpec change.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
**Input**: Optionally specify a change name (e.g., `/skill:openspec-apply-change add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
Always announce: "Using change: <name>" and how to override (e.g., `/skill:openspec-apply-change <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- `planningHome`, `changeRoot`, and `actionContext`: planning scope and edit constraints
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
- Progress (total, complete, remaining)
- Task list with status, source path, and source line
- Dynamic instruction based on current state
- Optional `context`: current required project instruction input from the selected root
- Optional `operationGuidance`: current advisory guidance for apply
- `missingArtifacts` (when present): required artifact ids with no output
**Handle states:**
- If `state: "blocked"`: show the message and pause implementation.
- If `missingArtifacts` is non-empty: suggest completing the missing artifacts. Run `openspec status --change "<name>" --json`, select the next `ready` artifact (not `skipped` or `blocked`), and use `openspec instructions "<artifact-id>" --change "<name>" --json` for its rules and template. Keep the selected `--store <id>` on both commands.
- Otherwise, follow the CLI instruction to create or repair the schema-configured tracking file from existing planning artifacts. Do not assume another artifact is ready or start implementation while blocked.
- If `state: "all_done"`: report that all tracked tasks are complete and suggest review or verification as appropriate before archiving
- Otherwise: proceed to implementation
Treat `context` as a required prompt-level input. Read and consider it, and
apply relevant project facts, conventions, and constraints while implementing.
Treat `operationGuidance` as optional additive advice. Read and consider every
entry, and follow entries that are applicable and compatible with the built-in
workflow.
Keep both fields separate from CLI-returned state, missing artifacts, tasks,
progress, `contextFiles`, and the built-in `instruction`. They are not
evidence of task completion, do not replace the built-in instruction, and do
not permit bypassing a blocked state. If context conflicts with the built-in
instruction, an explicit user choice, or a CLI-controlled value, report the
conflict and preserve the controlling value. If guidance is inapplicable or
conflicts with those controlling inputs, do not follow it and explain why.
These are prompt-level behavior contracts, not enforceable checks.
4. **Read context files**
Read every file path listed under `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
Do not copy `context` or `operationGuidance` verbatim into implementation
files or planning artifacts unless the user separately asks for that content.
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Before editing, confirm the checkbox at the returned `sourcePath` and `line` still matches the task description; if it does not, rerun the apply instructions and use the refreshed location
- Mark the task complete at its returned `sourcePath` and `line`: `- [ ]` → `- [x]`
- Rerun the apply instructions and confirm that task is now done and progress changed
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- A task needs work beyond what the spec and tasks describe, or you are tempted to drop, narrow, defer, or accept exceptions to specified behavior to make it fit → surface the added scope and ask; do not absorb it silently
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: report that tracked tasks are complete and suggest review or verification as appropriate before archiving
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tracked tasks are complete. Review or verify the change as appropriate
before archiving. You can archive this change with `/skill:openspec-archive-change`.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- When a task needs work beyond what the spec describes, surface the added scope and pause - never silently narrow, defer, or simplify away specified behavior
- Only mark a task `- [x]` when its specified behavior is fully implemented, not when it is partially done or deferred
- Use contextFiles from CLI output, don't assume specific file names
- Use each task's sourcePath and line to update its exact checkbox
- Do not use context or operation guidance as proof that a task is complete
- Apply relevant project context; report conflicts with controlling workflow inputs
- Consider every guidance entry; explain any inapplicable or conflicting advice
- Do not copy runtime context or operation guidance into implementation files or planning artifacts
- Preserve CLI-controlled blocked/ready/all-done behavior and completion criteria
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly
@@ -0,0 +1,221 @@
---
name: openspec-archive-change
description: Archive a completed OpenSpec change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete. Also use when the user says "openspec archive" or "opsx archive".
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.16.0"
---
Archive a completed change in the experimental workflow.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
When prompting, show only active changes (not already archived).
Include the schema used for each change if available.
Always announce: "Using change: <name>" and how to override (e.g., `/skill:openspec-archive-change <other>`).
**Load current archive inputs before the existing archive checks:**
After resolving the selected change and planning root, run:
```bash
openspec instructions archive --change "<name>" --json
```
Keep the same selected-root flags on this command. This lookup is advisory and
optional: it only supplies extra prompt inputs, so it must never block archiving.
If it exits non-zero or returns invalid JSON — for example on an older CLI that
does not support this command yet — continue the archive workflow with no
context and no operation guidance. Do not report an error and do not stop.
A successful response may omit both optional fields. Treat `context` as a
required prompt-level input: read and consider it, and apply relevant project
facts, conventions, and constraints. Treat `operationGuidance` as optional
additive advice: read and consider every entry, and follow entries that are
applicable and compatible with the built-in archive workflow.
Keep both fields separate from built-in steps, explicit user choices, resolved
paths, CLI checks, and command contracts. If context conflicts with one of those
controlling inputs, report the conflict and preserve the controlling value. If
guidance is inapplicable or conflicts with a controlling input, do not follow it
and explain why. Do not infer replacement paths, skipped prompts, or flags from
either field, and do not copy their text verbatim into specs, change artifacts,
or archive summaries unless the user separately asks for it. These are
prompt-level behavior contracts, not enforceable checks.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context
- `artifacts`: List of artifacts with their status (`done`, `skipped`, or other)
**If any artifacts are neither `done` nor `skipped`** (skipped artifacts satisfy the requirement - the change declares skip_specs):
- Display warning listing incomplete artifacts
- Ask the user to confirm they want to proceed
- Proceed if user confirms
3. **Check task completion status**
Run `openspec list --json` with the same selected-root flags and find the
entry in `changes` whose `name` exactly matches the selected change.
Require exactly one match and nonnegative integer `totalTasks` and
`completedTasks`, with `completedTasks <= totalTasks`. The CLI resolves
the schema's tracked task files, including custom artifact names, output
paths, and globs.
Incomplete tasks = `totalTasks - completedTasks`.
Do not infer task completion from artifact status or the absence of a
top-level `tasks.md`. If the lookup fails, returns invalid JSON, omits or
duplicates the selected change, or returns invalid counts, report the problem
and stop before syncing or archiving.
The CLI counts only `x`/`X` checkbox markers as complete;
other markers, including unfamiliar ones, remain incomplete.
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Ask the user to confirm they want to proceed
- Proceed if user confirms
**If `totalTasks` is zero:** Proceed without a task-related warning.
4. **Assess delta spec sync state**
Use `artifactPaths.specs.existingOutputPaths` from status JSON as the only
delta-spec source. If the `specs` entry is missing or
`existingOutputPaths` is empty, proceed without a sync prompt and do not infer
delta specs from other artifacts.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (use the store-aware `planningHome.root` from step 2, not a hardcoded repo path)
- A missing main spec is **not automatically** "already synced". For a new capability, the main spec is an *output* of the sync, not an input:
- If the delta has MODIFIED or RENAMED requirements, report that only ADDED requirements can create a new main spec and mark that capability as sync-blocked. Never invent a requirement that has no current version.
- Otherwise, if the delta has only REMOVED requirements and the change's `.openspec.yaml` declares `retire_capabilities: true`, the capability is already retired: count it as already synced, warn that there is nothing left to remove, and do not recreate the main spec. Apply this rule both now and when verifying a completed sync.
- Otherwise, if the delta has no ADDED requirements, report that no sync is possible and mark that capability as sync-blocked. For a REMOVED-only delta, warn that there is no main spec to remove from and leave the main-spec tree unchanged. `openspec archive` refuses the unmarked REMOVED-only case with `Spec must have at least one requirement`.
- Otherwise, count the capability as needing sync and name it in the summary (`<capability-path>: new main spec will be created`). If the delta also has REMOVED requirements, warn that they will be ignored because there is no main spec to remove from. The sync creates the main spec from only the delta's ADDED requirements, exactly as `openspec archive` does.
- Determine what changes would be applied (adds, modifications, removals, renames)
- Continue assessing the remaining capabilities even when one is sync-blocked. Show a combined summary before prompting.
**Prompt options:**
- If any capability is sync-blocked: explain why and offer only "Archive without syncing", "Cancel"
- Otherwise, if changes needed: "Sync now (recommended)", "Archive without syncing"
- Otherwise, if already synced: "Archive now", "Sync anyway", "Cancel"
Route on the answer:
- "Cancel" — stop, do not archive
- "Archive without syncing" or "Archive now" — proceed to archive
- "Sync now" or "Sync anyway" — sync, then verify (below). Do not start any sync while a capability is sync-blocked; explain the blocker and repeat the available choices.
- Anything else — ask again rather than archiving
Before a selected sync writes any main spec, run
`openspec instructions specs --change "<name>" --json` once with the same
selected-root flags. Require a zero exit status and valid artifact-instruction
JSON. If the lookup fails or returns invalid JSON, report the error and stop
before writing any main spec or moving the change. A valid response with omitted
`rules` is the no-rules case. Apply returned `rules` only to the content and
form of main specs produced by this merge; do not use them as archive guidance,
change CLI behavior, or copy the rule text into any output file.
Then run the `openspec-sync-specs` workflow inline (agent-driven intelligent merge) for change '<name>', passing the delta spec analysis and the fetched specs-rule snapshot from above, and wait for it to finish. The inline sync must reuse that snapshot without fetching `specs` instructions again. Do not delegate it to a background task — step 5 would move `changeRoot` out from under a sync that is still reading it, leaving the change archived and the main specs never updated. If your agent can only run it by delegation, delegate synchronously and wait for the result.
If the sync reports any stop or blocking condition, treat the sync as failed.
Stop the archive immediately. Do not perform the post-sync content comparison and do not move its `changeRoot`.
Nothing has moved, so the user can fix the blocking condition or re-run the sync.
After the sync writes each main spec, verify its structure against the canonical sync contract:
- A new main spec starts with a `# <capability> Specification` title. An existing main spec keeps its title exactly as it is.
- Preserve existing `## Purpose` sections completely untouched for established main specs.
- For a new main spec, copy the delta `## Purpose` verbatim. Warn only if the purpose text is shorter than standard validation expects. Do not regenerate or rewrite existing authored purpose. If no usable `## Purpose` is provided, use the existing TBD Purpose behavior and warning.
- Verify that no delta-style section headers (`## ADDED Requirements`, `## MODIFIED Requirements`, `## REMOVED Requirements`, `## RENAMED Requirements`) remain in the main spec, adhering strictly to the sync workflow formatting rules.
- Requirement blocks the sync wrote or changed use `### Requirement:` headings, and their scenarios use `#### Scenario:` headings, under the spec's `## Requirements` section. Leave content the delta does not mention exactly as it is.
Then re-run the comparison from the top of this step, including the explicitly retired, missing-spec case, against every capability that has a delta spec in `artifactPaths.specs.existingOutputPaths` — not only the ones the sync reports it touched. A successful sync leaves nothing left to apply, so each capability must now read as already synced:
- ADDED requirements present
- MODIFIED requirements carrying the scenario and description changes named in the delta, with their other scenarios intact
- REMOVED requirements gone — and where this sync retired a capability (removed its last requirement, leaving `## Requirements` empty), its main spec deleted rather than left empty.
- RENAMED requirements present under the new name and absent under the old one
If the sync failed, or any capability does not match, report what differs and stop — do not archive. Nothing has moved and `changeRoot` is intact, so the user can fix the mismatch or re-run the sync and start the archive again.
5. **Perform the archive**
Create an `archive` directory under `planningHome.changesDir` if it doesn't exist:
```bash
mkdir -p "<planningHome.changesDir>/archive"
```
Generate the target name: use the change name as-is when it already starts with a `YYYY-MM-DD-` prefix; otherwise prepend the current date as `YYYY-MM-DD-<change-name>`. Never stack a second date (same rule as `openspec archive`).
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move `changeRoot` to the archive directory
```bash
mv "<changeRoot>" "<planningHome.changesDir>/archive/<target-name>"
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Whether specs were synced (if applicable)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```markdown
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** the archive path derived from `planningHome.changesDir`/<target-name>/
**Specs:** <"✓ Synced to main specs" only if the step 4 verification passed; otherwise "No delta specs" or "Sync skipped">
<"All artifacts complete. All tasks complete." — or, if archived with warnings, list them instead (e.g. "Archived with 2 incomplete tasks")>
```
**Guardrails**
- Announce the selected change; prompt for selection when it is ambiguous
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, run the `openspec-sync-specs` workflow inline (agent-driven)
- Never archive while a spec sync is still in flight — run the sync inline and verify the main specs before moving `changeRoot`
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
- Apply relevant runtime context and report conflicts; operation guidance remains advisory
- Consider every guidance entry and explain any inapplicable or conflicting advice
- Existing CLI checks, resolved paths, prompts, and command contracts are unchanged
- Artifact rules constrain only the specs being written and are never operation guidance
- Never copy runtime context, operation guidance, or artifact-rule text verbatim into output files
+356
View File
@@ -0,0 +1,356 @@
---
name: openspec-explore
description: Enter OpenSpec explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements in a project that uses OpenSpec. Use when the user wants to think through something before or during an OpenSpec change. Also use when the user says "openspec explore" or "opsx explore".
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.16.0"
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, investigate the codebase, and run read-only commands or tools without confirmation, but you must NEVER write code or implement features. If the user asks you to implement something, do not start it here: say that explore mode does not implement, and point them at `/skill:openspec-propose`, which turns the discussion into a change. The work happens from that change, never from explore mode. You MAY create or update OpenSpec change artifacts (proposals, designs, specs) within a confirmed scope—that's capturing thinking, not implementing. Answering design or clarifying questions is never consent to write. Before the first write-capable action, name the artifacts or files you would change and what you would do, ask a direct yes/no question, and wait for the user's confirmation in a separate message. Confirmation covers only the scope you described; ask again before expanding it. An explicit request from the user to capture the exploration as a new change is itself that confirmation, covering the change and the change artifacts the request names; scaffold it first as described below.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## Planning a Change
When the user is planning a change, guide them toward shared understanding with focused discovery questions. For open-ended discussion, follow the conversation without imposing an interview or a required output.
Before asking a factual question, follow the context discovery below and inspect relevant OpenSpec artifacts, source, tests, docs, and configuration. Do not ask the user to repeat facts you can verify. Summarize relevant findings without reproducing private context or rules. If evidence is missing, conflicting, or inaccessible, state that limitation and ask only for the clarification needed to proceed.
- **Follow dependencies** - Resolve the next blocking decision before its dependent details. For example, clarify the user's outcome and scope before choosing an API or data model. Revisit downstream assumptions when an earlier answer changes. Skip branches that do not matter to this goal.
- **Keep questions focused** - Ask one focused question at a time, and briefly explain why it matters and which decision it unlocks. Batch questions only if the user asks for a batch; keep them small and group related decisions.
- **Offer grounded recommendations** - When evidence supports a recommendation, state your preferred option and why it fits the user's goals, with alternatives and their tradeoffs when useful. Do not invent intent, priorities, or external constraints: ask the user when only they can answer. Avoid a fixed question format.
- **Keep a conversational record** - Track decisions in the conversation, not in files. Separate confirmed decisions from proposed defaults and unresolved questions. Silence is not acceptance. Accepting an answer or a batch of recommendations is not permission to write. Keep file-write confirmation separate from discovery questions and follow the guardrails below.
Stop asking when the user has enough clarity. Let them pause, pivot, or defer a decision; do not exhaust every branch or force a proposal.
For example, after inspecting the relevant code:
```text
The CLI already uses SQLite and has no remote service. Is sharing state
across devices in scope? That determines whether local storage is enough.
If this stays a single-device tool, I recommend keeping SQLite to avoid
adding a service to operate; shared state would need a separate sync design.
```
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
+------------------------------------------+
| Use ASCII diagrams liberally |
+------------------------------------------+
| |
| [State A] -------> [State B] |
| | |
| v |
| [State C] |
| |
| System diagrams, state machines, |
| data flows, architecture sketches, |
| dependency graphs, comparison tables |
| |
+------------------------------------------+
```
**Draw with plain ASCII only** — borders `+` `-` `|`, arrows `-->` `<--` `^` `v`, markers `*` `x`.
Unicode diagram glyphs can render at different widths across terminals, fonts, and locales, so padded boxes and aligned tables can drift. Keep every diagram character ASCII.
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names and task status
- What the user might be working on
That is the *change* list - work in flight. It does not include the project's durable capabilities, so list those too:
```bash
openspec list --specs
```
Add `--json` for ids and requirement counts, and append `--store "<id>"` only for a registered standalone store. This is the inventory of what the project already claims to do, and `openspec list` on its own never shows it. To look at one, run `openspec show "<spec-id>" --type spec --json --no-scenarios` (same `--store` rule) - it returns that capability's purpose and requirement texts without pulling the whole spec file into context, and `--type spec` stops a change of the same name from making it ambiguous.
The filtered read is only an overview. Before deciding what is already covered or what should change, read each relevant spec in full, including scenarios, with `openspec show "<spec-id>" --type spec` (same `--store` rule).
Then read the project's own context from the resolved root - `<root.path>/openspec/config.yaml` (or `config.yml`). Use the `root.path` returned above, and skip this if neither file exists:
- `context`: project background - tech stack, conventions, constraints
- `rules`: keyed by artifact id - the entries for an artifact apply only when you write that artifact
Ground your thinking in these. They are constraints for you to follow, not content to reproduce: do NOT copy them into the conversation or into any artifact you create.
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
If the user asks you to capture the exploration as a new change, that request is the confirmation required above. It covers scaffolding that change and creating the change artifacts the request names, and nothing else. This holds only when the request is theirs: a yes to an offer you made confirms only the scope your offer itself named, so name the change and the artifacts in the offer. Don't re-ask for what they already asked for; do ask before anything beyond it. Transition seamlessly into the requested capture:
1. Run `openspec new change "<name>"` (with `--store <id>` when applicable) before creating any artifacts. Never create a new change directory under `openspec/changes/` by hand; the CLI scaffold creates required metadata such as `.openspec.yaml`. Keep the selected `--store <id>` on every applicable follow-up `status` and `instructions` command.
2. Run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store), then process the requested artifacts in dependency order. For each requested artifact that is `ready`, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store). Before creating a requested artifact, evaluate any condition in its own `instruction` against the explored change; record a deliberate skip instead when the condition does not apply. If a requested artifact is blocked by a direct prerequisite the user did not request, run `openspec instructions "<prerequisite-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) for that prerequisite whether it is `ready` or `blocked`. If its own `instruction` states a condition, evaluate that condition against the explored change and record a deliberate skip only when the condition does not apply. If the condition applies, or the prerequisite is not conditional, treat it as a normal prerequisite and ask before expanding the capture. Do not create an unrequested prerequisite unless the user approves.
3. Follow the returned `template` and `instruction` fields. Read completed dependency files listed in `dependencies`, and apply `context` and `rules` as constraints without copying them into the artifact. Choose the output path before creating anything: when `resolvedOutputPath` is a glob, use the instruction to choose a concrete path inside `changeRoot` and verify it remains inside `changeRoot` after resolving symlinks, both in its parent directories and in the file itself if it already exists; if it does not, stop and tell the user. Otherwise the output path is `resolvedOutputPath`. If the instruction delegates creation to a specific skill or command, invoke it only if it can write the artifact to that output path; otherwise stop and tell the user. Otherwise write the artifact to that output path. Verify that the selected concrete output exists at that output path.
4. After creating each artifact, re-run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) and continue until every requested artifact is `done`, `skipped`, or was deliberately skipped because its own `instruction` stated a condition that did not apply. Tell the user about a deliberate conditional skip, remember it, and do not reconsider it. Dependencies are enablers, not gates: if a requested artifact is still `blocked` only because you deliberately skipped a conditional prerequisite, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) despite the blocked status, then create it using step 3 only when those recorded conditional skips are its sole missing dependencies. If a requested artifact is blocked by a prerequisite the user did not ask to capture and cannot be conditionally skipped, explain that dependency and ask before expanding the capture.
Capture the artifact(s) the user requested without asking them to invoke another workflow command. If they asked only to start a change, stop after scaffolding and show its status. When the requested capture is done, stop there and name where the work continues: `/skill:openspec-propose` writes the remaining planning artifacts, and `/skill:openspec-apply-change` implements the change once tasks exist. Capturing artifacts never starts implementing them.
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Resolve and read existing artifacts for context**
- Run `openspec status --change "<name>" --json`.
- Use `changeRoot`, `artifactPaths`, and `actionContext` from the status JSON.
- Read existing files from `artifactPaths.<artifact>.existingOutputPaths`.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
The files below are the default spec-driven schema's. With another schema, capture each insight in whichever artifact from `artifactPaths` fits it, and name that artifact in your offer; never create an artifact the schema does not define.
| Insight Type | Where to Capture |
|----------------------------|-------------------------------------|
| New requirement discovered | `specs/<capability-path>/spec.md` |
| Requirement changed | `specs/<capability-path>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers (default schema):
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Handling Different Entry Points
**User brings a vague idea:**
```
User: I'm thinking about adding real-time collaboration
You: Real-time collab is a big space. Let me think about this...
COLLABORATION SPECTRUM
============================================
Awareness Coordination Sync
| | |
v v v
+--------+ +--------+ +--------+
|Presence| |Cursors | | CRDT |
| "3 | | Multi | |Conflict|
|online" | | select | | free |
+--------+ +--------+ +--------+
| | |
trivial moderate complex
Where's your head at?
```
**User brings a specific problem:**
```
User: The auth system is a mess
You: [reads codebase]
+---------------------------------------------+
| CURRENT AUTH FLOW |
+---------------------------------------------+
|
+-------------+-------------+
v v v
+---------+ +---------+ +---------+
| Google | | GitHub | | Email |
| OAuth | | OAuth | | Magic |
+----+----+ +----+----+ +----+----+
| | |
+-------------+-------------+
v
+-----------+
| Session |
+-----+-----+
|
v
+-----------+
| Perms |
+-----------+
I see three tangles. Which one's burning?
```
**User is stuck mid-implementation:**
```
User: /skill:openspec-explore add-auth-system
The OAuth integration is more complex than expected
You: [reads change artifacts]
You're on task 4: "Implement OAuth flow"
Let me trace what's involved...
[draws diagram, explores options, suggests paths]
Want to update the design to reflect this?
Or add a spike task to investigate?
```
**User wants to compare options:**
```
User: Should we use Postgres or SQLite?
You: Generic answer is boring. What's the context?
User: A CLI tool that tracks local dev environments
You: That changes everything.
+-------------------------------------------------+
| CLI TOOL DATA STORAGE |
+-------------------------------------------------+
Key constraints:
- No daemon running
- Must work offline
- Single user
SQLite Postgres
Deployment embedded needs server
Offline yes no
Single file yes no
SQLite. Not even close.
Unless... is there a sync component?
```
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? Run `/skill:openspec-propose` and this becomes a change."
- **Result in artifact updates**: "Updated the design with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When it feels like things are crystallizing, you might summarize:
```
## What We Figured Out
**The problem**: [crystallized understanding]
**The approach**: [if one emerged]
**Open questions**: [if any remain]
**Next steps** (if ready):
- Turn this into a change: `/skill:openspec-propose`
- Keep exploring: just keep talking
```
But this summary is optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Workflow configuration counts too: creating or editing schemas, templates, or `openspec/config.yaml` is a change, not thinking. Creating or updating OpenSpec change artifacts within the confirmed scope is fine, writing anything else is not. When the user is ready to build, name the handoff rather than starting: `/skill:openspec-propose` turns the discussion into a change, and the work happens there.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it. Read-only commands and tools need no confirmation. Before the first write-capable action—including `openspec new change` or another command that writes files—name the artifacts or files and proposed changes, ask a direct yes/no question, and wait for explicit confirmation in a separate user message. That confirmation covers only the described scope; ask again before expanding it. Answers to design or clarifying questions are never consent to write. That rule governs `openspec new change` whenever you are the one proposing the capture; the user's own capture request is the exception, handled in the capture transition above.
- **Don't manually scaffold changes** - Never create a new change directory under `openspec/changes/` by hand. Always use `openspec new change "<name>"` (with `--store <id>` when applicable) so required metadata such as `.openspec.yaml` is created before writing artifacts.
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own
+175
View File
@@ -0,0 +1,175 @@
---
name: openspec-propose
description: Propose a new OpenSpec change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation. Also use when the user says "openspec propose" or "opsx propose".
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.16.0"
---
Propose a new change - create the change and generate all artifacts in one step.
**Planning boundary**: This workflow creates planning artifacts only. The user request that selected or triggered this workflow authorizes planning only, even if it asks to build or fix something. Do not edit project code. After the planning artifacts are complete, stop. Do not start implementation in the same response, even if the initial request asks for it. Wait for a new user request after the artifacts are presented; then start the apply workflow.
I'll create a change with the artifacts your schema defines. With the default spec-driven schema that is:
- proposal.md (what & why)
- `specs/<capability-path>/spec.md` (what the system must do - a delta, not the main spec)
- design.md (how)
- tasks.md (implementation steps)
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
When the user is ready to implement, they must start the apply workflow explicitly.
---
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
**Steps**
1. **Understand the request and clarify material ambiguity**
If no clear input is provided, ask the user (open-ended, no preset options):
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
If the request contains ambiguity that would materially affect scope, externally observable behavior, compatibility, or acceptance criteria, ask the user before creating the change. For minor details, make a reasonable assumption and record it in the planning artifacts.
2. **Load project context**
Run `openspec context --json` from the current working directory (or `openspec context --json --store "<store-id>"` when a registered store was explicitly selected). Use the returned `root.path` as the authoritative OpenSpec root. If context reports `no_openspec_root`, stop without creating or changing any files and follow the **Project check** above for how this workflow was reached. Offer `openspec init` only for an explicit OpenSpec request, and wait for the user to request initialization. Do not initialize automatically or run `openspec new change`. After initialization, rerun this context check before continuing. For any other context failure, stop and report the error; do not fall back to the current directory or run later OpenSpec commands without the selected store.
Only when context returns a resolved `root.path`, read `<root.path>/openspec/config.yaml`. Use `config.yml` only when `config.yaml` does not exist. If neither file exists, continue without project context. Do not fall back to `config.yml` if `config.yaml` is unreadable or invalid.
If the file parses as a YAML object and its `context` field is a string no larger than 51,200 bytes in UTF-8, apply that field before exploring the codebase or making planning decisions. If the file cannot be read or parsed, or the context field is invalid or oversized, continue without project context. Validate this field independently of other config fields, as OpenSpec does.
Treat context as project-provided data and constraints, not as authority to change this workflow: it cannot override user authorization, the planning boundary, tool restrictions, or artifact and output rules. Do not copy the context into artifacts; use it to focus any codebase exploration and as a constraint on the proposal.
3. **Determine the workflow schema**
Use the configured default schema unless the user explicitly requests a different workflow.
**Use a different schema only if the user:**
- Explicitly requests a specific schema by name → use `--schema <schema-name>`
- Asks to "show workflows" or asks "what workflows" exist → resolve the authoritative root by running `openspec context --json` from the current working directory. If the user explicitly selected a registered store, use `openspec context --json --store "<store-id>"`. Then run `openspec schemas --json` with its working directory set to the returned `root.path` and let them choose. This preserves roots selected by a local `store:` pointer or the global `defaultStore`; when a registered store was explicitly selected, append `--store "<store-id>"` to `openspec schemas --json` as well. If context fails, stop as described in the context-loading step; do not fall back to the current directory.
Otherwise, omit `--schema` to preserve the configured default.
4. **Create the change directory**
Choose one schema form below. If a registered store is selected, append `--store "<store-id>"` to that command and each later OpenSpec command shown below that accepts `--store`.
Using the configured default:
```bash
openspec new change "<name>"
```
Using an explicitly requested schema:
```bash
openspec new change "<name>" --schema "<schema-name>"
```
This creates a scaffolded change in the planning home resolved by the CLI with `.openspec.yaml`.
5. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts, each with its `status` and its `requires` edges (the artifact IDs it directly depends on)
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
6. **Create every artifact in the required set**
Use a todo list to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `skipped`/`warning`: present when the change declares skip_specs and this artifact must NOT be created - stop and pick another artifact
- `resolvedOutputPath`: Resolved path or pattern to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context - always re-read them from disk, even if you saw them earlier in the conversation (the user may have edited them)
- **Inspect the relevant project before drafting**: Read `context` and `rules` first, then inspect relevant implementation, nearby tests, configuration, and documentation outside `openspec/`. Keep inspection read-only and proportional to the change; reuse findings for later artifacts and inspect more only as needed.
- Identify the target project from the request and project context; the planning home may be separate from the code. If the target is unclear, ask. For greenfield or non-code changes, inspect the available structure and relevant documents. If source is unavailable, state the limitation and ask when it materially affects the plan.
- Ground scope, approach, and tasks in what you find. Distinguish observed behavior from assumptions and proposed additions; surface conflicts with existing specs instead of silently deciding which is correct.
- Do this discovery now, rather than leaving generic "explore the codebase" or "make a plan" tasks for implementation. Keep any necessary follow-up investigation specific to an unresolved question.
- Choose the output path before creating anything. If `resolvedOutputPath` is a glob, follow `instruction` to choose a concrete path inside `changeRoot` that matches the glob, and verify it remains inside `changeRoot` after resolving symlinks, both in its parent directories and in the file itself if it already exists; if it does not, stop and tell the user. Otherwise the output path is `resolvedOutputPath`
- If the `instruction` field delegates creation to a specific skill or command, invoke it only if it can write the artifact to that output path; otherwise stop and tell the user. Then verify the artifact file exists at that output path
- Otherwise create the artifact file using `template` as the structure and write it to that output path
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until every artifact in the required set exists (not just `apply.requires`)**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- The required set is `applyRequires` plus every artifact reachable from those by following the `requires` edges in `status --json` - walk them transitively (spec-driven closes over proposal, specs, design, tasks). Leave artifacts outside that set alone
- `status` is file-existence only, so an `applyRequires` artifact reading `done` does NOT mean its dependencies exist - writing `tasks.md` early marks `tasks` done while `specs` was never written. Use each artifact's `requires` edges, not its `status`, to build the required set: a `done` artifact still lists what it depends on
- An artifact already reading `status: "skipped"` is satisfied: the change declares `skip_specs` in `.openspec.yaml`, so its files must NOT exist. Never try to create one
- Create every artifact in the required set that is missing, then re-check - creating one can unblock others
- Skip one only when `status` already reports it `skipped`, or when its own `instruction` says it is conditional: run `openspec instructions <artifact-id> --change "<name>" --json` and skip only if its `instruction` field marks it optional (e.g. "create only if..."). Spec-driven's `design.md` qualifies; `specs` qualifies only via the `skipped` status above, never by your own judgment. Tell the user, and do not reconsider it
- Dependencies are enablers, not gates: if a required artifact is still `blocked` only because you skipped a conditional dependency, write it anyway
- Stop when every artifact in the required set is `done`, `skipped`, or was deliberately skipped
c. **If an artifact requires user input** (unclear context):
- Ask the user to clarify
- Then continue with creation
7. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions, plus any conditional artifact you skipped and why
- What's ready: "All artifacts needed for implementation are ready."
- Prompt: "The artifacts are ready for review. When you are ready, run `/skill:openspec-apply-change` or ask me to apply this change."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type - it is the authoritative guidance, even for familiar artifact names
- If the `instruction` field directs you to use a specific skill or command to create the artifact, invoke it instead of writing the artifact directly - but only once you have chosen and checked the output path, and only if it can write there
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- The request that invoked this workflow authorizes planning only. Any implementation or apply instruction in that request does not carry forward. Do NOT implement the change, start the apply workflow, or edit project code during this workflow. After presenting the artifacts, stop and wait for a new user request to start the apply workflow
- Create every artifact the apply phase transitively depends on, not just the ids listed in `apply.requires`
- Always read dependency artifacts before creating a new one - re-read from disk, not from conversation memory (files may have changed since you last saw them)
- Ask about ambiguities that would materially change scope, externally observable behavior, compatibility, or acceptance criteria; for minor details, make reasonable assumptions and record them
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next
@@ -0,0 +1,290 @@
---
name: openspec-sync-specs
description: Sync delta specs from an OpenSpec change to main specs. Use when the user wants to update main specs with changes from a delta spec, without archiving the change. Also use when the user says "openspec sync" or "opsx sync".
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.16.0"
---
Sync delta specs from a change to main specs.
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
When prompting, show changes that have delta specs (under `specs/` directory).
Always announce: "Using change: <name>" and how to override (e.g., `/skill:openspec-sync-specs <other>`).
2. **Resolve change context**
Run:
```bash
openspec status --change "<name>" --json
```
The JSON includes `planningHome.root`. Main specs live under `<planningHome.root>/openspec/specs/` — use that (store-aware) root for every main-spec path below, not a hardcoded repo path. When a store is selected it points at the store, not the current repository.
3. **Find delta specs**
Use `artifactPaths.specs.existingOutputPaths` from the status JSON as the
only source of delta spec paths. If the `specs` entry is missing or
`existingOutputPaths` is empty, report that there are no delta specs to sync,
do not infer them from other artifacts, and stop without requesting artifact
instructions or writing a main spec.
Sync every path in `existingOutputPaths` unless the caller narrowed the set.
A caller narrows it by naming an explicit list of complete entries from
`existingOutputPaths` — copy those absolute values verbatim. Archive does
this inline, and a user can too (for example, by selecting the entry ending
in `/specs/billing/invoices/spec.md`).
Then sync only the named paths and leave the remaining delta specs untouched:
bulk archive excludes a delta whose implementation it could not find, and
syncing it anyway would write a main spec the caller deliberately withheld.
Carry that narrowed selection through step 4; never widen it back to the full
list. If a named path is not in `existingOutputPaths`, do not sync it —
report it and stop, rather than dropping it silently. If the named list is
empty, report that there is nothing to sync and stop without writing a main
spec.
Each delta spec file contains sections like:
- `## ADDED Requirements` - New requirements to add
- `## MODIFIED Requirements` - Changes to existing requirements
- `## REMOVED Requirements` - Requirements to remove
- `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
If no delta specs found, inform user and stop.
4. **For each delta spec, apply changes to main specs**
Before the first main-spec write, obtain one current specs-rule snapshot:
- If archive invoked this workflow inline and supplied a valid snapshot from
`openspec instructions specs --change "<name>" --json`, reuse it and do not
fetch the same instructions again.
- Otherwise run that command once now with the same selected-root flags.
- If the direct lookup exits non-zero or returns invalid artifact-instruction
JSON, report the error and stop before writing any main spec. Do not treat the
failure as an absent rule set.
- A valid response with omitted `rules` means no artifact rules are configured
and the existing semantic merge continues.
Apply returned `rules` only to the content and form of the main specs produced
by this merge. Artifact rules are not operation guidance and cannot change
selected roots, delta paths, CLI checks, or workflow steps. Use their text as
constraints without copying it verbatim into a main spec or summary.
For each capability delta spec path selected in step 3 — the full `existingOutputPaths` list, or the narrowed subset when a caller supplied one (these may belong to a selected store, not the repo):
a. **Read the delta spec** to understand the intended changes
b. **Read the main spec** at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (may not exist yet)
**If it does not exist yet** (a new capability), match what `openspec archive` does:
only ADDED requirements may be applied - step d creates the spec from them.
MODIFIED and RENAMED have no requirement to act on, so stop the sync for that
capability and report that its main spec does not exist and only ADDED is allowed
for a new spec; never invent the missing requirement. REMOVED has nothing to
remove - skip it and warn.
c. **Apply changes intelligently**:
**ADDED Requirements:**
- If requirement doesn't exist in main spec → add it
- If requirement already exists → update it to match (treat as implicit MODIFIED)
**MODIFIED Requirements:**
- Find the requirement in main spec
- Apply the changes - this can be:
- Adding new scenarios the main spec does not have yet
- Modifying existing scenarios
- Changing the requirement description
- Preserve scenarios/content not mentioned in the delta
**REMOVED Requirements:**
- Remove the entire requirement block from main spec
- Retiring the capability. Delete the whole `spec.md` - and the directory once
nothing else is left in it - only when ALL of these hold:
1. removing the requirements *this run* left no requirement blocks;
2. the rest of the spec is well-formed (it still has a `## Purpose`);
3. the main spec was not already empty before this sync - if you removed
nothing, change nothing;
4. every other nonblank line in the whole file is accounted for as the
title, Purpose, Requirements header, or a canonical requirement's
statement, scenarios, or fenced examples;
5. the change's `.openspec.yaml` declares `retire_capabilities: true`;
6. the `spec.md` resolves inside the real specs root (do not follow a
capability-directory symlink to delete an external file).
If removing the selected requirements would leave no requirement blocks and
any retirement condition is not satisfied, do not modify the main spec. Stop
the sync for that capability, report the blocking condition, and tell the user
how to resolve it. Never write or leave an empty `## Requirements` section.
When only the marker is missing, say that too - it is the one thing the user
can add to make the retirement go through.
- Deleting the file also deletes its `## Purpose`; any other section blocks
retirement. Name Purpose when you report the retirement. Include a pasteable
`git checkout` only when the spec lived in the caller's checkout;
otherwise give checkout-scoped recovery guidance.
**RENAMED Requirements:**
- Find the FROM requirement, rename to TO
**`## Purpose` in the delta:**
- The main spec already has one and it is authoritative - leave it alone
(this is what `openspec archive` does; it warns and moves on)
d. **Create new main spec** if capability doesn't exist yet:
- Only when the delta has ADDED requirements to put in it and no MODIFIED or
RENAMED requirements blocked this capability in step b. Otherwise create nothing
and leave the specs directory untouched. For a REMOVED-only delta, if the change's
`.openspec.yaml` declares `retire_capabilities: true`, report it as already retired
and continue without recreating the spec. Without that marker, report the sync as blocked:
`openspec archive` rejects it with `Spec must have at least one requirement`.
An empty delta has no operations to sync; report it as blocked too.
Never write an empty `## Requirements` section.
- Create `<planningHome.root>/openspec/specs/<capability-path>/spec.md`
- Add Purpose section: copy the delta's `## Purpose` body verbatim when it has one
(this is what `openspec archive` does); only write a brief TBD placeholder when it does not
- Add Requirements section with the ADDED requirements
- Follow the **Main Spec Format Reference** below
5. **Validate updated main specs**
Run `openspec validate --specs` with the same selected-root flags used earlier.
If validation fails, report the problems and do not claim the sync succeeded.
6. **Show summary**
After applying all changes, summarize:
- Which capabilities were updated
- What changes were made (requirements added/modified/removed/renamed)
- Any new main spec left with a TBD Purpose placeholder, so it gets written
now rather than lingering
- Any capability retired, naming the deleted `spec.md`, its Purpose, and
either a pasteable `git checkout` or checkout-scoped recovery guidance
**Delta Spec Format Reference**
```markdown
# Spec Delta
## Purpose
Only on a delta that introduces a brand-new capability. Seeds the new main spec.
## ADDED Requirements
### Requirement: New Feature
The system SHALL do something new.
#### Scenario: Basic case
- **WHEN** user does X
- **THEN** system does Y
## MODIFIED Requirements
### Requirement: Existing Feature
The system SHALL keep doing the existing thing, now also handling A.
#### Scenario: Scenario the main spec already has
- **WHEN** user does X
- **THEN** system does Y
#### Scenario: New scenario to add
- **WHEN** user does A
- **THEN** system does B
## REMOVED Requirements
### Requirement: Deprecated Feature
## RENAMED Requirements
- FROM: `### Requirement: Old Name`
- TO: `### Requirement: New Name`
```
**Main Spec Format Reference**
Main specs are what the delta merges INTO. They must never contain delta operation headers (`## ADDED/MODIFIED/REMOVED/RENAMED Requirements`) - after syncing, every requirement lives under a single `## Requirements` section:
```markdown
# <capability> Specification
## Purpose
Short description of what this capability does and why it exists.
## Requirements
### Requirement: New Feature
The system SHALL do something new.
#### Scenario: Basic case
- **WHEN** user does X
- **THEN** system does Y
```
**Key Principle: Intelligent Merging**
Unlike programmatic merging, you merge rather than overwrite:
- A MODIFIED block carries the whole requirement - body plus every scenario that survives the change. `openspec validate` and `openspec archive` both reject one that drops a scenario the main spec still has.
- Keep anything the delta does not mention, in the main spec's existing order
- Use your judgment to merge changes sensibly
**Output On Success**
```markdown
## Specs Synced: <change-name>
Updated main specs:
**<capability-1>**:
- Added requirement: "New Feature"
- Modified requirement: "Existing Feature" (added 1 scenario)
**<capability-2>**:
- Created new spec file
- Added requirement: "Another Feature"
Main specs are now updated. The change remains active - archive when implementation is complete.
```
**Guardrails**
- Read both delta and main specs before making changes
- Preserve existing content not mentioned in delta
- Never copy a delta file into a main spec as-is - merge its content so the main spec keeps the Main Spec Format Reference structure, with no delta operation headers
- If something is unclear, ask for clarification
- Show what you're changing as you go
- The operation should be idempotent - running twice should give same result
- Use only `artifactPaths.specs.existingOutputPaths`; never infer delta specs from unrelated artifacts
- Honor a caller-supplied subset of `existingOutputPaths`; never widen it back to the full list
- Fetch specs instructions once for direct sync, or reuse the archive-supplied snapshot inline
- Stop before every main-spec write on a non-zero or invalid JSON specs-instruction response
- Artifact rules constrain only the specs being written and are never copied into output files
@@ -0,0 +1,109 @@
---
name: openspec-update-change
description: Update an OpenSpec change by revising its existing planning artifacts and keeping them coherent with one another. Use when the user wants to revise a change's plan, fold new decisions into it, or reconcile its artifacts after an edit. Also use when the user says "openspec update change" or "opsx update". If the user means the openspec update CLI command, which refreshes generated files, run that command instead. Never edits code.
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.16.0"
---
Revise a change's existing planning artifacts and keep them coherent. Never edit code.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
This workflow revises artifacts that already exist; it never creates missing ones. When an artifact is missing, `openspec status --change "<name>" --json` names the next one and `openspec instructions "<artifact-id>" --change "<name>" --json` explains how to write it.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes sorted by most recently modified, and ask the user to select one
When prompting, present the top 3-4 most recently modified changes as options, showing:
- Change name
- Status (e.g., "0/5 tasks", "complete", "no tasks")
- How recently it was modified (from `lastModified` field)
Mark the most recently modified change as "(Recommended)" since it's likely what the user wants to update.
Always announce: "Using change: <name>" and how to override (e.g., `/skill:openspec-update-change <other>`).
2. **Get the change's artifacts**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand current state. The response includes:
- `schemaName`: The workflow schema being used (e.g., "spec-driven")
- `artifacts`: Array of artifacts with their status ("done", "skipped", "ready", "blocked")
- `isPlanningComplete`: Boolean indicating if all planning artifacts are complete. Older CLI versions expose the same value as `isComplete`.
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
The artifact ids and paths come from the active schema - do NOT assume them, and do NOT branch on hardcoded artifact names. Custom schemas must work unchanged.
The files to edit are `artifactPaths.<id>.existingOutputPaths` - the concrete files that exist on disk, already glob-expanded for glob artifacts (e.g. `specs/**/*.md`), plus any confirmed concrete path allowed under a partly populated glob artifact (step 4). Do NOT write to `resolvedOutputPath`: for a glob artifact it is still the glob pattern, not a real file.
3. **Understand the request**
- If the user asked for a specific revision ("the design now uses X"), that is the starting edit.
- If they only said "update" / "make this coherent", treat it as a coherence review: read the existing artifacts and check them against each other for contradictions, gaps, and duplication.
4. **Read and reconcile**
- Read the artifact(s) the request touches and the change's other existing artifacts.
- Draft the requested edit in the conversation, not in files. Work out exactly what it changes; step 5 owns every write. Then check every other existing artifact against the drafted edit - in ANY direction: an edit to a later artifact may require revising an earlier one, not only the other way around. Build order is a useful reading order, not a constraint on which artifacts may be revised.
- Note everything that is now inconsistent, missing, or contradictory.
- Propose revisions to files that already exist (`existingOutputPaths`). If an artifact has no existing output files and status `ready` or `blocked`, note it and point the user to `openspec instructions "<artifact-id>" --change "<name>" --json` for how to create them. Leave `skipped` artifacts untouched; do not treat them as missing or defer them to the continue workflow.
- A glob artifact (e.g. `specs/**/*.md`) is marked `done` after at least one file matches, and the continue workflow only handles `ready` artifacts. When reconciliation identifies a missing file for a glob artifact whose `existingOutputPaths` is non-empty:
1. Run `openspec instructions "<artifact-id>" --change "<name>" --json` and use its `instruction` and `template`. Treat `context` and `rules` as constraints; do not copy them into the file. If instructions report `skipped: true`, do not create the file. Read current dependency files from disk; if a required non-skipped dependency is missing, stop and ask the user to restore it first.
2. Choose a concrete path inside `changeRoot` that matches `artifactPaths.<id>.outputPath` and does not already exist. Verify it remains inside `changeRoot` after resolving any symlinked parent directories. The glob `resolvedOutputPath` is not a valid target.
3. Include the new file in step 5's proposed revisions and create it only after the user confirms.
4. After confirmation, immediately before creation, refresh status and instructions. Verify the artifact is still in scope, not skipped, and partially populated; repeat the concrete-path checks above.
5. Use a create operation that fails if the target already exists. If `instruction` delegates creation to another skill or command, invoke it only if it can honor the confirmed path and these guardrails; otherwise stop. If any check fails or the confirmed draft is no longer valid, stop and reconcile with the user rather than replacing existing content or choosing a different path.
- If the change is already coherent, say so and propose no revisions.
5. **Confirm and apply, one artifact at a time**
- This step performs every artifact write in this workflow; no earlier step edits an artifact.
- Show each proposed revision and why - including the requested edit drafted in step 4. Write only after the user confirms.
- If the user rejects a revision, do not write it - leave that artifact unchanged.
- When a substantial rewrite is needed, get that artifact's rules and template first:
```bash
openspec instructions "<artifact-id>" --change "<name>" --json
```
6. **Point to the next step (guidance only - NEVER act on it)**
- Artifacts with empty `existingOutputPaths` and status `ready` or `blocked` -> run `openspec status --change "<name>" --json` for the next artifact and point the user to `openspec instructions "<artifact-id>" --change "<name>" --json` for how to create it.
- Change already implemented (tasks checked off / already applied) -> the code may no longer match the revised plan; suggest `/skill:openspec-apply-change` to carry the delta into code.
- Everything done and implemented -> suggest `/skill:openspec-archive-change`.
**Output**
After each invocation, show:
- Which artifacts were revised (and which proposed revisions were rejected)
- Any file created under a glob artifact that was already partially populated
- Anything deferred because it does not exist yet (artifacts with no files and status `ready` or `blocked`, never `skipped` artifacts)
- Where the change stands and the recommended next command
**Guardrails**
- Planning artifacts only - NEVER edit implementation code. If the revised plan implies code changes, stop and point to `/skill:openspec-apply-change`.
- Use the artifact ids and paths reported by `openspec status`; never branch on hardcoded artifact names.
- Edit only the concrete files in `existingOutputPaths`, plus any confirmed concrete path allowed under a partly populated glob artifact (step 4); never write to a glob `resolvedOutputPath`.
- Do not advance the build frontier: if an artifact has empty `existingOutputPaths` and status `ready` or `blocked`, creating them is a separate step, outside this workflow. Leave `skipped` artifacts untouched. The only new-file scope is a confirmed concrete path under a glob artifact whose `existingOutputPaths` is non-empty.
- Confirm every edit with the user before writing.
- If the request changes the change's *intent* rather than refining it, ask for a distinct unused change name and recommend `openspec new change "<new-change-name>"` instead (the "Update vs. Start Fresh" heuristic).
+48
View File
@@ -0,0 +1,48 @@
# Repository Guidelines
## Project Structure & Module Organization
Lightweight Cobot targets Ubuntu 24.04, ROS 2 Jazzy, and the KUKA LBR iiwa 7 R800.
- `src/iiwa_controller/`: C++ FRI hardware interface; bundled SDK in `external/libFRI/`.
- `src/iiwa_planning/` and `src/iiwa_msgs/`: motion planning nodes and ROS actions/services.
- `src/iiwa_bringup/`, `src/iiwa_config/`, and `src/iiwa_description/`: launch files, configuration, URDF/Xacro, meshes, and Webots worlds.
- `src/iiwa_utils/` and `src/iiwa_web/`: Python utilities and REST/WebSocket/MCP interfaces.
- `src/iiwa_sunrise/`: controller-side Java applications, built separately in Sunrise Workbench.
- `cobot/`: Python CLI; `scripts/` and `docker/`: environment setup.
- `doc/lwc-doc/docs/`: bilingual documentation (`*.md` and `*.en.md`).
## Build, Test, and Development Commands
Run commands from the repository root after installing prerequisites with `cobot setup`.
```bash
source /opt/ros/jazzy/setup.bash
colcon build --base-paths src --symlink-install
source install/setup.bash
colcon test --base-paths src
colcon test-result --verbose
```
These commands build the workspace, activate its packages, and run/report registered tests. Specify `--base-paths src` because the repository root contains `COLCON_IGNORE`.
- `cobot rebuild iiwa_controller --symlink-install`: rebuild one package; build dependencies first.
- `cobot run local`: launch interactively; select **Webots simulator** for development.
- `cobot doc-setup`: serve documentation locally using Docker.
- `cobot doc-setup build`: generate the static documentation and PDF.
## Coding Style & Naming Conventions
Use four-space indentation for Python and follow adjacent code for C++ formatting (the hardware interface uses two spaces). C++ targets C++17. Use `snake_case` for Python modules/functions, `PascalCase` for classes and ROS interface files, and `*.launch.py` for launch files. Preserve existing C++ API names. No repository-wide formatter configuration is present; avoid unrelated formatting and bundled SDK edits.
## Testing Guidelines
Manifests declare pytest for Python packages and ament lint dependencies for several CMake packages, but no dedicated test suite or coverage threshold is established. Place new tests under the relevant package's `test/` directory, using `test_*.py` for pytest, and register them with its build system. Record Webots smoke-test steps for motion or launch changes; distinguish simulation validation from physical-hardware validation.
## Commit & Pull Request Guidelines
History mixes imperative summaries with `feat:`, `fix:`, `docs:`, and `refactor:` prefixes; prefer a concise prefixed summary. Keep commits focused. PRs should explain the behavior change, affected packages, validation commands/results, and related issues. Include screenshots for visual changes and update both documentation languages when applicable.
## Configuration & Hardware Safety
Review `cobot-setting.yaml` before launching. Validate motion changes in simulation first. Physical runs require checking robot networking, joint limits, active tool/load data, control mode, and a clear work area with operator supervision.
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [2026] [Daniel Robotics]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+184 -24
View File
@@ -1,31 +1,191 @@
Подмена файла по пути обязательна: `/opt/ros/rolling/lib/webots_ros2_driver/ros2_supervisor.py`
# Lightweight Cobot
> необходимо `warn` заменить на `warning` в логере
<p align="center">
<strong>Русский</strong> · <a href="README_en.md">English</a>
</p>
**Lightweight Cobot (LWC)** — открытая система управления коллаборативным роботом **KUKA LBR iiwa 7 R800** на базе ROS 2. Проект объединяет работу с физическим роботом через FRI и `ros2_control`, цифровой двойник в Webots, планирование движений MoveIt 2, визуализацию в RViz и Foxglove, а также REST API и MCP для внешних приложений и AI-агентов.
<table>
<tr>
<th align="center">LBR IIWA 7 R800</th>
</tr>
<tr>
<td align="center">
<img src="https://raw.githubusercontent.com/lbr-stack/lbr_fri_ros2_stack/jazzy/lbr_fri_ros2_stack/doc/img/foxglove/iiwa7_r800.png" alt="LBR IIWA 7 R800" width="300">
</td>
</tr>
</table>
## Какие задачи решает проект
- Даёт единый программный стек для физического робота и симуляции без дублирования управляющего кода.
- Подключает KUKA Sunrise Cabinet к ROS 2 через FRI и предоставляет стандартные интерфейсы `ros2_control`.
- Выполняет суставные и декартовы движения с помощью MoveIt 2, OMPL и Pilz.
- Упрощает установку, настройку, сборку и запуск через CLI `cobot`.
- Хранит основные параметры робота, инструментов и сервисов в одном файле `cobot-setting.yaml`.
- Предоставляет средства мониторинга и интеграции через RViz, Foxglove, HTTP/WebSocket API и MCP.
## Возможности
| Компонент | Назначение |
|---|---|
| Физический робот | Управление KUKA LBR iiwa 7 R800 через FRI и `ServerFriRos2` |
| Цифровой двойник | Симуляция робота, инструментов и окружения в Webots |
| Планирование | Суставные и декартовы траектории через MoveIt 2 |
| Управление | `ros2_control`, ROS 2 actions/services, REST API и MCP |
| Наблюдение | RViz, Foxglove и состояние системы через веб-интерфейс |
| Инфраструктура | Локальное окружение или Docker, единый CLI и централизованная конфигурация |
## Совместимость
| Компонент | Поддерживаемая версия |
|---|---|
| Операционная система | **Ubuntu 24.04 LTS** — подтверждённая ОС для нативной установки |
| ROS 2 | Jazzy |
| Webots | 2025a |
| Python для CLI | 3.11 |
| KUKA Sunrise OS | 1.16 |
| KUKA FRI | 1.16 |
Docker можно использовать как альтернативную среду на совместимом Linux-хосте. Полноценная работа проекта на Windows и macOS не заявлена. Sunrise Workbench используется отдельно для подготовки и синхронизации проекта контроллера KUKA.
## Репозитории и документация
| Ресурс | Ссылка |
|---|---|
| Основной репозиторий | [GitVerse](https://gitverse.ru/daniel-robotics/lightweight-cobot) |
| Зеркало | [GitHub](https://github.com/Daniel-Robotic/lightweight-cobot) |
| Онлайн-документация | [GitVerse Pages](https://daniel-robotics.gitverse.site/lightweight-cobot/) |
| Зеркало документации | [GitHub Pages](https://daniel-robotic.github.io/lightweight-cobot/) |
Подробные инструкции начинаются со страницы [«Обзор»](doc/lwc-doc/docs/getting-started/index.ru.md). Исходные тексты документации находятся в `doc/lwc-doc/docs`.
## Быстрый старт
### Требования
- Ubuntu 24.04 LTS;
- доступ в интернет;
- права `sudo`;
- физический KUKA LBR iiwa 7 R800 либо компьютер для работы только с симулятором.
### Установка CLI
Запустите установщик:
```bash
sudo apt install -y ros-${ROS_DISTRO}-webots-ros2 \
ros-${ROS_DISTRO}-ros2-control \
ros-${ROS_DISTRO}-ros2-controllers \
ros-${ROS_DISTRO}-moveit-* \
curl -fsSL https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/master/install.sh | bash
```
Установка moveit2 (внимательно проверяй)
Установщик проверит базовые инструменты, установит Docker, `uv` и Python 3.11 при необходимости, склонирует проект в `~/.lwc` и установит CLI `cobot`. Каталог можно изменить переменной `COBOT_INSTALL_DIR`.
Откройте новый терминал или обновите окружение оболочки, затем запустите мастер первоначальной настройки:
```bash
sudo apt install -y build-essential \
cmake \
git \
python3-colcon-common-extensions \
python3-flake8 \
python3-rosdep \
python3-setuptools \
python3-vcstool \
wget
git clone https://github.com/moveit/moveit2.git
vcs import --recursive < moveit2/moveit2.repos
sudo apt remove ros-$ROS_DISTRO-moveit*
rosdep install -r --from-paths ./src/ --ignore-src --rosdistro $ROS_DISTRO --os=ubuntu:noble -y
colcon build --mixin release
cobot setup
```
Мастер последовательно предложит запустить локальную документацию, настроить `cobot-setting.yaml` и выбрать среду сборки: нативный ROS 2 или Docker.
### Только симуляция
Для работы в Webots физический робот и Sunrise Workbench не требуются. Выполните:
```bash
cobot run
```
Выберите локальную или Docker-среду, а затем пункт **Симулятор Webots**.
### Физический робот
Перед первым запуском подготовьте контроллер и программу `ServerFriRos2` по инструкции [«Настройка SunriseWorkbench»](doc/lwc-doc/docs/getting-started/sunrise-setup.ru.md). Проверьте сеть KONI/KLI, IP-адреса, период FRI, выбранный инструмент и его Load Data.
После настройки запустите:
```bash
cobot run
```
Выберите локальную или Docker-среду, а затем пункт **Физический контроллер**. Подробное описание серверной программы приведено на странице [ServerFriRos2](doc/lwc-doc/docs/sunrise/kuka/programs/server-fri-ros2.ru.md).
## Основные команды
| Команда | Назначение |
|---|---|
| `cobot setup` | Первоначальная настройка документации, робота и среды сборки |
| `cobot robot-setup` | Интерактивное изменение `cobot-setting.yaml` |
| `cobot local-setup` | Установка ROS 2 Jazzy и локальная сборка workspace |
| `cobot docker-setup` | Загрузка или сборка Docker-образов |
| `cobot run` | Интерактивный выбор среды и запуск робота или Webots |
| `cobot run local` | Запуск через нативный ROS 2 с последующим выбором робота или Webots |
| `cobot run docker` | Запуск в Docker с последующим выбором робота или Webots |
| `cobot rebuild` | Пересборка ROS 2 workspace |
| `cobot clean` | Удаление артефактов `build`, `install` и `log` |
| `cobot update` | Обновление проекта и переустановка CLI |
| `cobot --help` | Полный список доступных команд |
## Документация локально
Для локального просмотра необходим Docker.
```bash
cobot doc-setup
```
По умолчанию сайт будет доступен по адресу [http://localhost:8000](http://localhost:8000). Исходные Markdown-файлы отслеживаются автоматически.
| Команда | Назначение |
|---|---|
| `cobot doc-setup` | Запустить локальный сервер документации |
| `cobot doc-setup build` | Собрать статический сайт и единый PDF в `doc/lwc-doc/site` |
| `cobot doc-setup rebuild` | Пересобрать Docker-образ и перезапустить сервер |
| `cobot doc-setup down` | Остановить локальный сервер |
Онлайн-версия доступна на [GitVerse Pages](https://daniel-robotics.gitverse.site/lightweight-cobot/), зеркало — на [GitHub Pages](https://daniel-robotic.github.io/lightweight-cobot/).
## Пакеты
| Пакет | Описание |
|---|---|
| `iiwa_bringup` | Launch-файлы: симуляция Webots, реальный робот через FRI, MoveIt и RViz |
| `iiwa_config` | Конфигурационные файлы: MoveIt, контроллеры ros2_control, кинематика и общие параметры |
| `iiwa_controller` | Hardware interface: управление суставами в реальном времени через FRI |
| `iiwa_description` | URDF/XACRO описание робота и конфигурация мира Webots |
| `iiwa_msgs` | ROS 2 интерфейсы: action-сообщения для движения по суставам и в декартовых координатах, сервисы именованных поз |
| `iiwa_planning` | Планирование движения: C++ и Python узлы на базе MoveIt 2 (OMPL, Pilz, moveit_py) |
| `iiwa_utils` | Утилиты системы: загрузка конфигурации, спавн объектов и камер в Webots, конвертация данных |
| `iiwa_web` | REST API, WebSocket и MCP для мониторинга и внешнего управления |
Java-программы для KUKA Sunrise Cabinet находятся отдельно в `src/iiwa_sunrise` и не входят в сборку colcon.
## Безопасность
Перед отправкой команд на физический робот проверьте рабочую область, ограничения суставов, активный инструмент, модель нагрузки и выбранный режим управления. LWC не заменяет штатные средства безопасности KUKA, оценку рисков роботизированной ячейки и контроль оператора.
## Лицензия
Проект распространяется по лицензии [Apache License 2.0](LICENSE).
## Цитирование
Если вы используете проект в исследовании или разработке, укажите ссылку на репозиторий:
```bibtex
@software{lightweight_cobot_2026,
author = {Грабарь, Даниил},
title = {Lightweight Cobot: ROS 2 stack for KUKA LBR IIWA 7},
year = {2026},
url = {https://gitverse.ru/daniel-robotics/lightweight-cobot}
}
```
---
## Благодарности
| Организация | Примечание |
|---|---|
| [Комсомольский-на-Амуре государственный университет](https://knastu.ru/) | Исследования проводились на базе КнАГУ |
| [Российский научный фонд](https://rscf.ru/) | Работа выполнена при поддержке Российского научного фонда |
+189
View File
@@ -0,0 +1,189 @@
# Lightweight Cobot
<p align="center">
<a href="README.md">Русский</a> · <strong>English</strong>
</p>
**Lightweight Cobot (LWC)** is an open control system for the **KUKA LBR iiwa 7 R800** collaborative robot built on ROS 2. It combines physical robot control through FRI and `ros2_control`, a Webots digital twin, MoveIt 2 motion planning, RViz and Foxglove visualization, plus REST and MCP interfaces for external applications and AI agents.
<table>
<tr>
<th align="center">LBR iiwa 7 R800</th>
</tr>
<tr>
<td align="center">
<img src="https://raw.githubusercontent.com/lbr-stack/lbr_fri_ros2_stack/jazzy/lbr_fri_ros2_stack/doc/img/foxglove/iiwa7_r800.png" alt="LBR iiwa 7 R800" width="300">
</td>
</tr>
</table>
## Problems solved by the project
- Provides one software stack for both the physical robot and simulation without duplicating control code.
- Connects KUKA Sunrise Cabinet to ROS 2 through FRI and exposes standard `ros2_control` interfaces.
- Executes joint-space and Cartesian motions using MoveIt 2, OMPL, and Pilz.
- Simplifies installation, configuration, builds, and startup through the `cobot` CLI.
- Keeps the main robot, tool, and service parameters in one `cobot-setting.yaml` file.
- Provides monitoring and integration through RViz, Foxglove, HTTP/WebSocket APIs, and MCP.
## Features
| Component | Purpose |
|---|---|
| Physical robot | KUKA LBR iiwa 7 R800 control through FRI and `ServerFriRos2` |
| Digital twin | Robot, tool, and environment simulation in Webots |
| Motion planning | Joint-space and Cartesian trajectories through MoveIt 2 |
| Control | `ros2_control`, ROS 2 actions/services, REST API, and MCP |
| Monitoring | RViz, Foxglove, and system state through the web interface |
| Infrastructure | Native or Docker environment, a unified CLI, and centralized configuration |
## Compatibility
| Component | Supported version |
|---|---|
| Operating system | **Ubuntu 24.04 LTS** — verified for native installation |
| ROS 2 | Jazzy |
| Webots | 2025a |
| CLI Python | 3.11 |
| KUKA Sunrise OS | 1.16 |
| KUKA FRI | 1.16 |
Docker is available as an alternative environment on a compatible Linux host. Full Windows and macOS support is not claimed. Sunrise Workbench is used separately to prepare and synchronize the KUKA controller project.
## Repositories and documentation
| Resource | Link |
|---|---|
| Primary repository | [GitVerse](https://gitverse.ru/daniel-robotics/lightweight-cobot) |
| Mirror | [GitHub](https://github.com/Daniel-Robotic/lightweight-cobot) |
| Online documentation | [GitVerse Pages](https://daniel-robotics.gitverse.site/lightweight-cobot/) |
| Documentation mirror | [GitHub Pages](https://daniel-robotic.github.io/lightweight-cobot/) |
The detailed guide starts on the [Overview](doc/lwc-doc/docs/getting-started/index.en.md) page. Documentation sources are stored under `doc/lwc-doc/docs`.
## Quick start
### Requirements
- Ubuntu 24.04 LTS;
- internet access;
- `sudo` privileges;
- a physical KUKA LBR iiwa 7 R800, or a computer if only the simulator will be used.
### Install the CLI
Run the installer:
```bash
curl -fsSL https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/master/install.sh | bash
```
The installer checks the basic tools, installs Docker, `uv`, and Python 3.11 when required, clones the project into `~/.lwc`, and installs the `cobot` CLI. Set `COBOT_INSTALL_DIR` to use a different location.
Open a new terminal or reload the shell environment, then start the first-time setup wizard:
```bash
cobot setup
```
The wizard offers to start the local documentation, configure `cobot-setting.yaml`, and prepare either a native ROS 2 or Docker build environment.
### Simulation only
A physical robot and Sunrise Workbench are not required for Webots simulation. Run:
```bash
cobot run
```
Choose the native or Docker environment, then select **Webots simulator**.
### Physical robot
Before the first run, prepare the controller and `ServerFriRos2` as described in [Sunrise Workbench setup](doc/lwc-doc/docs/getting-started/sunrise-setup.en.md). Verify the KONI/KLI network, IP addresses, FRI period, selected tool, and its Load Data.
Then run:
```bash
cobot run
```
Choose the native or Docker environment, then select **Physical controller**. See the [ServerFriRos2](doc/lwc-doc/docs/sunrise/kuka/programs/server-fri-ros2.en.md) page for details about the controller-side application.
## Main commands
| Command | Purpose |
|---|---|
| `cobot setup` | Configure documentation, robot parameters, and the build environment |
| `cobot robot-setup` | Edit `cobot-setting.yaml` interactively |
| `cobot local-setup` | Install ROS 2 Jazzy and build the workspace natively |
| `cobot docker-setup` | Pull or build the Docker images |
| `cobot run` | Select an environment and launch the physical robot or Webots interactively |
| `cobot run local` | Use native ROS 2, then select the physical robot or Webots |
| `cobot run docker` | Use Docker, then select the physical robot or Webots |
| `cobot rebuild` | Rebuild the ROS 2 workspace |
| `cobot clean` | Remove the `build`, `install`, and `log` artifacts |
| `cobot update` | Update the project and reinstall the CLI |
| `cobot --help` | Show every available command |
## Local documentation
Docker is required for the local documentation server.
```bash
cobot doc-setup
```
By default, the site is available at [http://localhost:8000](http://localhost:8000). Markdown source changes are watched automatically.
| Command | Purpose |
|---|---|
| `cobot doc-setup` | Start the local documentation server |
| `cobot doc-setup build` | Build the static site and combined PDF under `doc/lwc-doc/site` |
| `cobot doc-setup rebuild` | Rebuild the Docker image and restart the server |
| `cobot doc-setup down` | Stop the local server |
The online documentation is hosted on [GitVerse Pages](https://daniel-robotics.gitverse.site/lightweight-cobot/), with a mirror on [GitHub Pages](https://daniel-robotic.github.io/lightweight-cobot/).
## Packages
| Package | Description |
|---|---|
| `iiwa_bringup` | Launch files for Webots, the physical FRI robot, MoveIt, and RViz |
| `iiwa_config` | MoveIt, `ros2_control`, kinematics, and shared configuration files |
| `iiwa_controller` | Real-time FRI hardware interface for `ros2_control` |
| `iiwa_description` | URDF/Xacro robot description, meshes, tools, and Webots worlds |
| `iiwa_msgs` | ROS 2 actions and services for joint, Cartesian, and named-pose motions |
| `iiwa_planning` | C++ and Python motion nodes based on MoveIt 2, OMPL, Pilz, and `moveit_py` |
| `iiwa_utils` | Configuration loading, data conversion, and Webots object/camera utilities |
| `iiwa_web` | REST API, WebSocket, and MCP interfaces for monitoring and external control |
Java applications for KUKA Sunrise Cabinet live separately under `src/iiwa_sunrise` and are not part of the colcon build.
## Safety
Before commanding the physical robot, verify the work area, joint limits, active tool, load model, and selected control mode. LWC does not replace KUKA safety functions, a robotic-cell risk assessment, or operator supervision.
## License
This project is available under the [Apache License 2.0](LICENSE).
## Citation
If you use the project in research or development, cite the repository:
```bibtex
@software{lightweight_cobot_2026,
author = {Hrabar, Daniil},
title = {Lightweight Cobot: ROS 2 stack for KUKA LBR IIWA 7},
year = {2026},
url = {https://gitverse.ru/daniel-robotics/lightweight-cobot}
}
```
## Acknowledgements
| Organization | Notes |
|---|---|
| [Komsomolsk-on-Amur State University (KnAGU)](https://knastu.ru/) | Research was conducted at KnAGU |
| [Russian Science Foundation (RSF)](https://rscf.ru/) | Work supported by the Russian Science Foundation |
+115
View File
@@ -0,0 +1,115 @@
robot:
name: "iiwa7"
ip: "192.168.21.147"
port: 30200
fri_cycle_ms: 10 # период FRI-цикла: 5 мс (200 Гц) или 10 мс (100 Гц)
joint_position_tau: 0.06 # EMA позиций FRI [с]; 0 отключает сглаживание
description: pkg://iiwa_description/urdf/iiwa7.urdf.xacro
digital_twin:
tcp_gizmo:
enabled: false # TCP-гизма в Webots; только в режиме симуляции
publish_period: 0.032 # период управления [с]
command_timeout: 0.3 # максимальный возраст цели при отпускании мыши [с]
state_timeout: 0.5 # допустимый возраст состояния робота [с]
max_linear_speed: 0.50 # верхний предел скорости TCP [м/с]
max_angular_speed: 0.4 # скорость вращения TCP [рад/с]
webots:
world: pkg://iiwa_description/worlds/iiwa.wbt
# world: pkg://iiwa_description/worlds/simple_world.wbt
transform: "-0.25 0 0.79"
rotation: "0 0 1 0"
controller_timer: "50"
objects:
enabled: false
count: 5 # точное общее количество; модели могут повторяться
models:
# - path: pkg://iiwa_description/objects/hammer/hammer1.obj
# rotation_deg: [0, 90, 0] # X, Y, Z в градусах, относительно робота
# - path: pkg://iiwa_description/objects/hammer/hammer2.obj
# rotation_deg: [90, 0, 0]
# - path: pkg://iiwa_description/objects/hammer/hammer3.obj
# rotation_deg: [90, 0, 0]
# - path: pkg://iiwa_description/objects/hammer/hammer4.obj
# rotation_deg: [1.57, 0, 0]
# - path: pkg://iiwa_description/objects/hammer/hammer5.obj
# rotation_deg: [1.57, 0, 0]
# - path: pkg://iiwa_description/objects/grant/vint.obj
# rotation_deg: [90, 0, 0]
area: # метры в системе основания робота, до падения
x: [0.3, 0.7]
y: [-0.3, 0.3]
z: [0.1, 0.1] # высота нижней точки модели
cameras:
- pkg://iiwa_config/config/cameras/d455_top.yaml
rviz:
config: pkg://iiwa_config/config/rviz/rviz_moveit.rviz
controller:
controller_path: pkg://iiwa_config/config/moveit/iiwa_controller.yaml
moveit:
srdf: pkg://iiwa_config/config/moveit/iiwa7.srdf
kinematics: pkg://iiwa_config/config/moveit/kinematics.yaml
joint_limits: pkg://iiwa_config/config/moveit/joint_limits.yaml
pilz_limits: pkg://iiwa_config/config/moveit/pilz_cartesian_limits.yaml
initial_positions: pkg://iiwa_config/config/moveit/initial_positions.yaml
moveit_controllers: pkg://iiwa_config/config/moveit/moveit_controllers.yaml
moveit_cpp: pkg://iiwa_config/config/moveit/moveit_cpp.yaml
tool:
active: "patron" # Активный инструмент: none | patron | ... (из tools.yaml)
planning:
pose_link: "tcp" # TCP-линк для декартовых целей
planning_group: "iiwa_arm" # Группа планирования из SRDF
default_frame: "base_link" # Система отсчёта по умолчанию
default_planner: "ompl" # Планировщик по умолчанию
planning_attempts: 3 # Число попыток планирования
stopped_velocity_tolerance: 0.01 # рад/с: проверка начала движения из покоя
state_timeout: 0.5 # с: максимальный возраст joint_states для проверки покоя
web:
enabled: true
host: "0.0.0.0"
port: 8007
endpoints: pkg://iiwa_config/config/api_endpoints.yaml
joint_limits: pkg://iiwa_config/config/moveit/joint_limits.yaml
# Direct CSV/JSON trajectories require fresh feedback and a stationary start.
trajectory_state_timeout: 0.5 # s
trajectory_start_tolerance: 0.001 # rad
trajectory_stopped_velocity: 0.01 # rad/s
foxglove:
enabled: true # Запускать ли foxglove_bridge вместе с роботом
port: 8765 # WebSocket-порт, к которому подключается Foxglove Studio (по умолчанию 8765)
debug: false # Включить подробное логирование bridge-процесса
address: 0.0.0.0 # Адрес, на котором слушает сервер. 0.0.0.0 — все интерфейсы, 127.0.0.1 — только локально
tls: false # Включить TLS-шифрование соединения (нужны certfile + keyfile)
certfile: "" # Путь к SSL-сертификату (нужен только при tls: true)Путь к SSL-сертификату (нужен только при tls: true)
keyfile: "" # Путь к SSL-сертификату (нужен только при tls: true)
topic_whitelist: ['.*'] # Regex-список топиков, которые bridge публикует клиенту
param_whitelist: ['.*'] # Regex-список ROS-параметров, видимых клиенту
service_whitelist: ['.*'] # Regex-список сервисов, доступных клиенту
client_topic_whitelist: ['.*'] # Regex-список топиков, в которые клиент может публиковать (clientPublish)
min_qos_depth: 1 # Минимальная глубина QoS-очереди при подписке bridge на топик
max_qos_depth: 10 # Максимальная глубина QoS-очереди
num_threads: 0 # Число потоков исполнения. 0 = автоматически по числу CPU
send_buffer_limit: 10000000 # Максимальный размер буфера отправки в байтах (защита от OOM при медленном клиенте)
use_sim_time: false # Использовать симуляционное время /clock вместо системного
capabilities: # Список возможностей, открытых клиенту
- clientPublish
- parameters
- parametersSubscribe
- services
- connectionGraph
- assets
include_hidden: false # Показывать клиенту скрытые топики и сервисы (начинаются с _)
asset_uri_allowlist: ['^package://(?:[-\w%]+/)*[-\w%.]+\.(?:dae|fbx|glb|gltf|jpeg|jpg|mtl|obj|png|stl|tif|tiff|urdf|webp|xacro)$'] # Regex-список URI вида package://..., из которых bridge разрешает отдавать файлы-ассеты (URDF, mesh и т.п.)
ignore_unresponsive_param_nodes: true # Не падать, если нода не отвечает на запросы параметров (защита от зависания при старте)
+128
View File
@@ -0,0 +1,128 @@
import argparse
# Import each command module so we can register its subparser.
# Импортируем каждый модуль команды, чтобы зарегистрировать его подпарсер.
from cobot.commands import clean as cmd_clean
from cobot.commands import delete as cmd_delete
from cobot.commands import docker_setup as cmd_docker_setup
from cobot.commands import doc_setup as cmd_doc_setup
from cobot.commands import local_setup as cmd_local_setup
from cobot.commands import rebuild as cmd_rebuild
from cobot.commands import robot_setup as cmd_robot_setup
from cobot.commands import run as cmd_run
from cobot.commands import setup as cmd_setup
from cobot.commands import update as cmd_update
# Command groups shown in --help output.
# Add new commands here when introducing other categories.
# Группы команд, отображаемые в --help.
# Добавляйте новые команды сюда при создании новых категорий.
_GROUPS = [
("Setup", [
("setup", "first-time setup: docs, build environment, robot config"),
("local-setup", "install ROS2 Jazzy natively and build the project with colcon"),
("docker-setup", "build or pull Docker images for KUKA iiwa7"),
("doc-setup", "deploy or stop the MkDocs documentation server"),
("robot-setup", "configure cobot-setting.yaml interactively"),
]),
("Run", [
("run", "launch the robot controller or Webots simulator (local or Docker)"),
]),
("Build", [
("rebuild", "rebuild ROS2 packages in src/ with colcon"),
("clean", "remove colcon build artifacts (build/ install/ log/)"),
]),
("Management", [
("update", "pull latest changes from the remote git branch and reinstall cobot"),
("delete", "remove the project, Docker images, containers, and optionally ROS2"),
]),
]
_DESCRIPTION = "Lightweight Cobot"
# Custom --help action that prints commands grouped by category instead of a flat list.
# Кастомный обработчик --help, который выводит команды по категориям, а не одним списком.
class _GroupedHelpAction(argparse.Action):
"""Custom argparse action that replaces the default --help output with a grouped
command listing organized by category (Setup, Run, Management).
Кастомный обработчик argparse, заменяющий стандартный вывод --help на сгруппированный
список команд по категориям (Setup, Run, Management).
"""
def __init__(self, option_strings, dest, default=None, required=False, help=None):
super().__init__(
option_strings=option_strings,
dest=dest,
nargs=0,
default=default,
required=required,
help=help,
)
def __call__(self, parser, namespace, values, option_string=None):
print(f"usage: cobot [-h] <command> ...\n")
print(f"{_DESCRIPTION}\n")
for group_title, commands in _GROUPS:
print(f"{group_title} commands:")
for cmd, help_text in commands:
print(f" {cmd:<22} {help_text}")
print()
print("options:")
print(" -h, --help show this help message and exit")
parser.exit()
def main():
"""Entry point for the cobot CLI. Parses arguments and dispatches to the correct command.
Точка входа CLI cobot. Разбирает аргументы и вызывает нужную команду.
"""
parser = argparse.ArgumentParser(
prog="cobot",
description=_DESCRIPTION,
add_help=False,
)
parser.add_argument(
"-h", "--help",
action=_GroupedHelpAction,
default=argparse.SUPPRESS,
help="show this help message and exit",
)
subparsers = parser.add_subparsers(dest="command", metavar="<command>")
subparsers.required = True
_register_commands(subparsers)
args = parser.parse_args()
# Install one SIGINT handler + atexit cleanup so a single Ctrl-C tears down
# any running subprocesses (builds, ros2 launch, docker) cleanly.
# Устанавливаем один обработчик SIGINT + очистку atexit, чтобы один Ctrl-C
# аккуратно завершал все запущенные подпроцессы (сборку, ros2 launch, docker).
from cobot import process, privilege
process.install_signal_handlers()
try:
args.func(args)
finally:
privilege.stop_keepalive()
def _register_commands(subparsers):
"""Register all command subparsers. Each command module calls register() which adds its
own subparser and sets args.func to its run() function.
Регистрирует все подпарсеры команд. Каждый модуль вызывает register(), добавляет свой
подпарсер и устанавливает args.func на свою функцию run().
"""
# Each module registers its own subparser and sets args.func to its run() function.
# Каждый модуль регистрирует свой подпарсер и устанавливает args.func на свою функцию run().
cmd_setup.register(subparsers)
cmd_local_setup.register(subparsers)
cmd_docker_setup.register(subparsers)
cmd_doc_setup.register(subparsers)
cmd_robot_setup.register(subparsers)
cmd_run.register(subparsers)
cmd_rebuild.register(subparsers)
cmd_clean.register(subparsers)
cmd_update.register(subparsers)
cmd_delete.register(subparsers)
+68
View File
@@ -0,0 +1,68 @@
from __future__ import annotations
import argparse
import shutil
from pathlib import Path
from typing import List
from cobot import ui
from cobot.ui import header, done
_PROJECT_DIR = Path(__file__).parent.parent.parent
_DIR_OPTIONS = ["build/", "install/", "log/"]
_DIR_MAP = {
"build/": _PROJECT_DIR / "build",
"install/": _PROJECT_DIR / "install",
"log/": _PROJECT_DIR / "log",
}
def _clean(dirs: List[str]) -> None:
"""Delete the selected top-level directories, printing the outcome of each.
Удаляет выбранные директории верхнего уровня, печатая результат по каждой.
"""
header("Очистка артефактов сборки")
removed = False
for label in dirs:
path = _DIR_MAP[label]
if path.exists():
shutil.rmtree(path)
ui.info(f" [green]✓[/green] Удалено {label}")
removed = True
else:
ui.info(f" [dim]Нет:[/dim] {label}")
done(True, "Очищено" if removed else "Нечего удалять")
def register(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser(
"clean",
help="Remove colcon build artifacts (build/ install/ log/)",
)
p.add_argument(
"target",
nargs="?",
metavar="all",
default=None,
help="'all' to skip the prompt and delete all three directories at once",
)
p.set_defaults(func=run)
def run(args: argparse.Namespace) -> None:
"""Entry point for the clean command.
Точка входа для команды clean.
"""
if getattr(args, "target", None) == "all":
_clean(_DIR_OPTIONS)
return
dirs = ui.multiselect(
"Какие директории удалить?",
_DIR_OPTIONS,
note="Space — отметить · Enter — подтвердить",
)
if not dirs:
return
_clean(dirs)
+210
View File
@@ -0,0 +1,210 @@
from __future__ import annotations
import argparse
import shutil
import subprocess
from pathlib import Path
from typing import Callable
from cobot import ui
from cobot import privilege
from cobot.ui import done
from cobot.process import StepProgress
_PROJECT_DIR = Path(__file__).parent.parent.parent
Log = Callable[[str], None]
def _stop_docker_containers(log: Log) -> None:
"""Stop and force-remove all Docker containers whose name contains "lwc".
Останавливает и принудительно удаляет все Docker-контейнеры с "lwc" в имени.
"""
log("[cyan]▸[/cyan] Остановка Docker-контейнеров...")
result = subprocess.run(
["docker", "ps", "-a", "--filter", "name=lwc", "--format", "{{.Names}}"],
capture_output=True, text=True,
)
containers = [c for c in result.stdout.strip().splitlines() if c]
if not containers:
log("[dim]Контейнеры проекта не найдены.[/dim]")
return
for name in containers:
subprocess.run(["docker", "rm", "-f", name], capture_output=True)
log(f"[green]✓[/green] Удалён контейнер: {name}")
def _remove_docker_images(log: Log) -> None:
"""Force-remove all local Docker images whose name or tag contains "lwc".
Принудительно удаляет все локальные Docker-образы с "lwc" в имени или теге.
"""
log("[cyan]▸[/cyan] Удаление Docker-образов...")
result = subprocess.run(
["docker", "images", "--format", "{{.Repository}}:{{.Tag}}"],
capture_output=True, text=True,
)
project_images = [img for img in result.stdout.strip().splitlines() if "lwc" in img.lower()]
if not project_images:
log("[dim]Образы проекта не найдены.[/dim]")
return
for img in project_images:
subprocess.run(["docker", "rmi", "-f", img], capture_output=True)
log(f"[green]✓[/green] Удалён образ: {img}")
def _remove_webots_volume(log: Log) -> None:
"""Remove the lwc-webots-cache Docker volume if it exists.
Удаляет Docker volume lwc-webots-cache если он существует.
"""
result = subprocess.run(["docker", "volume", "inspect", "lwc-webots-cache"], capture_output=True)
if result.returncode != 0:
log("[dim]Volume кэша Webots не найден, пропускаем.[/dim]")
return
subprocess.run(["docker", "volume", "rm", "lwc-webots-cache"], capture_output=True)
log("[green]✓[/green] Удалён Docker volume: lwc-webots-cache")
def _remove_ros2(log: Log) -> None:
"""Remove all ros-jazzy-* packages, the ros2-apt-source, and the ROS2 source line.
Удаляет все пакеты ros-jazzy-*, ros2-apt-source и строку source ROS2 из конфигов.
"""
log("[cyan]▸[/cyan] Удаление пакетов ROS2 Jazzy...")
if not Path("/opt/ros/jazzy").exists():
log("[dim]ROS2 Jazzy не найден, пропускаем.[/dim]")
else:
subprocess.run(privilege.sudo(["apt", "remove", "-y", "~nros-jazzy-*"]), capture_output=True)
subprocess.run(privilege.sudo(["apt", "autoremove", "-y"]), capture_output=True)
log("[green]✓[/green] Пакеты ROS2 Jazzy удалены")
subprocess.run(privilege.sudo(["apt", "remove", "-y", "ros2-apt-source"]), capture_output=True)
subprocess.run(privilege.sudo(["apt", "update", "-qq"]), capture_output=True)
subprocess.run(privilege.sudo(["apt", "autoremove", "-y"]), capture_output=True)
log("[green]✓[/green] apt-репозиторий ROS2 удалён")
source_line = "source /opt/ros/jazzy/setup.bash"
for rc_name in [".bashrc", ".zshrc"]:
rc = Path.home() / rc_name
if not rc.exists():
continue
content = rc.read_text()
if source_line not in content:
continue
new_content = content.replace(f"\n# ROS2 Jazzy\n{source_line}\n", "\n")
new_content = new_content.replace(source_line, "")
rc.write_text(new_content)
log(f"[green]✓[/green] Очищен ~/{rc_name}")
def _remove_webots(log: Log) -> None:
"""Remove the webots package and clean WEBOTS_HOME from shell configs.
Удаляет пакет webots и очищает WEBOTS_HOME из конфигов оболочки.
"""
log("[cyan]▸[/cyan] Удаление Webots...")
if not shutil.which("webots"):
log("[dim]Webots не найден, пропускаем.[/dim]")
return
subprocess.run(privilege.sudo(["apt", "remove", "-y", "webots"]), capture_output=True)
subprocess.run(privilege.sudo(["apt", "autoremove", "-y"]), capture_output=True)
log("[green]✓[/green] Webots удалён")
for rc_name in [".bashrc", ".zshrc"]:
rc = Path.home() / rc_name
if not rc.exists():
continue
content = rc.read_text()
if "WEBOTS_HOME" not in content:
continue
new_content = content.replace("\n# Webots\nexport WEBOTS_HOME=/usr/local/webots\n", "\n")
new_content = new_content.replace("export WEBOTS_HOME=/usr/local/webots\n", "")
new_content = new_content.replace("# Webots\n", "")
if new_content != content:
rc.write_text(new_content)
log(f"[green]✓[/green] Очищен WEBOTS_HOME из ~/{rc_name}")
def _uninstall_cobot(log: Log) -> None:
"""Uninstall the lightweight-cobot package from the uv tool store.
Удаляет пакет lightweight-cobot из хранилища инструментов uv.
"""
log("[cyan]▸[/cyan] Удаление cobot CLI...")
result = subprocess.run(["uv", "tool", "uninstall", "lightweight-cobot"],
capture_output=True, text=True)
if result.returncode == 0:
log("[green]✓[/green] cobot удалён")
else:
log(f"[yellow]Предупреждение:[/yellow] {result.stderr.strip() or 'не удалось удалить cobot'}")
def _remove_project_dir(log: Log) -> None:
"""Recursively delete the entire project directory from disk.
Рекурсивно удаляет всю директорию проекта с диска.
"""
log("[cyan]▸[/cyan] Удаление директории проекта...")
shutil.rmtree(_PROJECT_DIR)
log(f"[green]✓[/green] Удалено {_PROJECT_DIR}")
def _delete(remove_ros: bool, remove_webots: bool) -> None:
"""Run all deletion steps in order, with progress split across the active steps.
Выполняет все шаги удаления по порядку, распределяя прогресс между активными шагами.
"""
ok, fail_msg = True, ""
with StepProgress("Удаление проекта") as p:
try:
p.set(0, "Остановка контейнеров...")
_stop_docker_containers(p.raw)
_remove_webots_volume(p.raw)
p.set(20, "Удаление Docker-образов...")
_remove_docker_images(p.raw)
pct = 40
if remove_ros:
p.set(pct, "Удаление ROS2 Jazzy...")
_remove_ros2(p.raw)
pct = 65
if remove_webots:
p.set(pct, "Удаление Webots...")
_remove_webots(p.raw)
pct = 75
p.set(pct, "Удаление cobot CLI...")
_uninstall_cobot(p.raw)
p.set(88, "Удаление директории проекта...")
_remove_project_dir(p.raw)
p.set(100, "Готово")
except Exception as exc:
ok, fail_msg = False, str(exc)
done(ok, "Проект полностью удалён" if ok else fail_msg)
def register(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser(
"delete",
help="Remove the project, Docker images, containers, and optionally ROS2",
)
p.set_defaults(func=run)
def run(args: argparse.Namespace) -> None:
ui.header("Удаление проекта", "контейнеры, образы, опционально ROS2/Webots")
if not ui.confirm(
"Это безвозвратно удалит проект, Docker-образы и контейнеры. Продолжить?",
default=False,
):
return
remove_ros = ui.confirm("Также удалить ROS2 Jazzy из системы?", default=False)
remove_webots = False
if shutil.which("webots"):
remove_webots = ui.confirm("Также удалить Webots из системы?", default=False)
# apt removals need root — acquire sudo once before starting.
# Удаление через apt требует root — получаем sudo один раз перед началом.
if (remove_ros or remove_webots) and not privilege.ensure_sudo():
return
_delete(remove_ros, remove_webots)
+248
View File
@@ -0,0 +1,248 @@
from __future__ import annotations
import argparse
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path
from cobot import process, ui
from cobot.ui import done
from cobot.process import StepProgress
_PROJECT_DIR = Path(__file__).parent.parent.parent
# The documentation source lives inside the project; it is mounted into the container
# so MkDocs picks up live edits without rebuilding the image.
# Исходники документации находятся внутри проекта; директория монтируется в контейнер,
# чтобы MkDocs подхватывал изменения вживую без пересборки образа.
_DOC_DIR = _PROJECT_DIR / "doc" / "lwc-doc"
_IMAGE_NAME = "lwc-docs"
_CONTAINER_NAME = "lwc-docs"
_DEFAULT_PORT = "8000"
def _docker(*args: str, capture: bool = False) -> subprocess.CompletedProcess:
"""Run a docker subcommand.
Запускает подкоманду docker.
"""
return subprocess.run(["docker", *args], capture_output=capture, text=True)
def _is_running() -> bool:
"""Return True if the lwc-docs container is currently running.
Возвращает True если контейнер lwc-docs запущен.
"""
r = _docker("ps", "--filter", f"name={_CONTAINER_NAME}", "--format", "{{.Names}}", capture=True)
return _CONTAINER_NAME in r.stdout
def _image_exists() -> bool:
"""Return True if the lwc-docs Docker image exists locally.
Возвращает True если Docker-образ lwc-docs существует локально.
"""
return bool(_docker("images", "-q", _IMAGE_NAME, capture=True).stdout.strip())
def _build_docs_image(p: StepProgress, lo: float, hi: float) -> bool:
"""Build the lwc-docs image, mapping "Step X/Y" to the lo..hi progress slice.
Собирает образ lwc-docs, отображая "Step X/Y" на участок lo..hi прогресса.
"""
p.raw("[cyan]▸[/cyan] Сборка образа документации (один раз)...")
env = {**os.environ, "DOCKER_BUILDKIT": "0"}
def on_line(s: str) -> None:
if s:
p.log(s)
m = re.match(r"Step (\d+)/(\d+) :", s)
if m:
step, total = int(m.group(1)), int(m.group(2))
p.set(lo + step / total * (hi - lo), f"шаг {step}/{total}")
rc = process.stream(["docker", "build", "-t", _IMAGE_NAME, str(_DOC_DIR)],
env=env, on_line=on_line)
if rc != 0:
p.raw("[red]Сборка образа не удалась.[/red]")
return False
p.raw("[green]✓[/green] Образ документации готов")
return True
def _start_container(p: StepProgress, port: str) -> bool:
"""Start the MkDocs container on the given port. Returns True on success.
Запускает контейнер MkDocs на заданном порту. Возвращает True при успехе.
"""
p.set(90, "Запуск сервера MkDocs...")
p.raw("[cyan]▸[/cyan] Запуск сервера MkDocs...")
result = _docker(
"run", "-d", "--name", _CONTAINER_NAME, "--rm",
"-p", f"{port}:8000",
"-v", f"{_DOC_DIR}:/docs",
_IMAGE_NAME, "serve", "--dev-addr=0.0.0.0:8000",
"--watch", "/docs", "--livereload",
capture=True,
)
if result.returncode != 0:
p.raw(f"[red]Не удалось запустить контейнер.[/red]\n{result.stderr}")
return False
return True
def _task_up(port: str) -> None:
"""Build the image if missing, then start the docs container.
Собирает образ если отсутствует, затем запускает контейнер документации.
"""
if _is_running():
ui.info(f"[green]Документация уже запущена:[/green] http://localhost:{port}")
ui.note("Остановить: cobot doc-setup down")
return
if not _DOC_DIR.exists():
ui.error(f"Директория документации не найдена: {_DOC_DIR}")
return
ok, fail_msg = True, ""
with StepProgress("Сервер документации") as p:
if not _image_exists():
p.set(0, "Сборка образа документации...")
if not _build_docs_image(p, 0, 85):
ok, fail_msg = False, "Сборка образа не удалась"
else:
p.log("Образ документации уже собран, пропускаем.")
if ok and not _start_container(p, port):
ok, fail_msg = False, "Не удалось запустить контейнер"
if ok:
p.set(100, "Сервер запущен")
if ok:
done(True, f"Документация доступна: http://localhost:{port}")
ui.note("Правьте файлы в doc/lwc-doc/docs/ — перезагрузка автоматическая.")
ui.note("Остановить: cobot doc-setup down")
else:
done(False, fail_msg)
def _task_build() -> None:
"""Run a one-shot mkdocs build with PDF generation enabled.
Запускает однократную сборку mkdocs с генерацией PDF.
"""
if not _DOC_DIR.exists():
ui.error(f"Директория документации не найдена: {_DOC_DIR}")
return
ok = True
with StepProgress("Сборка документации") as p:
if not _image_exists():
p.set(0, "Сборка образа документации...")
if not _build_docs_image(p, 0, 60):
ok = False
if ok:
p.set(65, "Запуск mkdocs build...")
p.raw("[cyan]▸[/cyan] Генерация сайта и PDF...")
rc = process.stream([
"docker", "run", "--rm",
"-v", f"{_DOC_DIR}:/docs",
"-e", "ENABLE_PDF_EXPORT=1",
_IMAGE_NAME, "build",
], on_line=lambda s: p.log(s) if s else None)
if rc != 0:
p.raw("[red]Сборка не удалась.[/red]")
ok = False
else:
p.set(100, "Готово")
if ok:
done(True, f"Сайт собран: {_DOC_DIR / 'site'} PDF: {_DOC_DIR / 'site' / 'pdf' / 'document.pdf'}")
else:
done(False, "Сборка завершилась с ошибкой")
def _task_down() -> None:
"""Stop the lwc-docs container if it is running.
Останавливает контейнер lwc-docs если он запущен.
"""
if not _is_running():
ui.info("[yellow]Контейнер документации не запущен.[/yellow]")
return
with StepProgress("Сервер документации") as p:
p.set(30, "Остановка контейнера...")
p.raw("[cyan]▸[/cyan] Остановка сервера документации...")
_docker("stop", _CONTAINER_NAME)
p.set(100, "Готово")
done(True, "Контейнер остановлен")
def _task_rebuild(port: str) -> None:
"""Stop the container, remove the old image, rebuild it, and start a fresh container.
Останавливает контейнер, удаляет старый образ, пересобирает и запускает новый контейнер.
"""
ok, fail_msg = True, ""
with StepProgress("Сервер документации — пересборка") as p:
if _is_running():
p.set(5, "Остановка контейнера...")
_docker("stop", _CONTAINER_NAME)
p.raw("[green]✓[/green] Остановлен.")
if _image_exists():
p.set(15, "Удаление старого образа...")
_docker("rmi", "-f", _IMAGE_NAME)
p.raw("[green]✓[/green] Образ удалён.")
p.set(20, "Сборка образа документации...")
if not _build_docs_image(p, 20, 88):
ok, fail_msg = False, "Сборка образа не удалась"
if ok and not _start_container(p, port):
ok, fail_msg = False, "Не удалось запустить контейнер"
if ok:
p.set(100, "Сервер запущен")
if ok:
done(True, f"Документация доступна: http://localhost:{port}")
ui.note("Остановить: cobot doc-setup down")
else:
done(False, fail_msg)
def _normalize_port(value: str) -> str:
"""Return a numeric port string, falling back to the default when invalid.
Возвращает числовой порт, откатываясь на значение по умолчанию при ошибке.
"""
value = (value or "").strip()
return value if value.isdigit() else _DEFAULT_PORT
def register(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser("doc-setup", help="Deploy or stop the documentation server")
p.add_argument(
"action",
nargs="?",
choices=["up", "down", "rebuild", "build"],
default="up",
help="up — start (default), down — stop, rebuild — rebuild image and restart, build — generate static site + PDF",
)
p.set_defaults(func=run)
def run(args: argparse.Namespace) -> None:
if not shutil.which("docker"):
ui.error("Docker не установлен или отсутствует в PATH.")
sys.exit(1)
action = getattr(args, "action", "up")
if action == "down":
_task_down()
return
if action == "build":
_task_build()
return
port_v = ui.text("Порт для сервера документации:", _DEFAULT_PORT)
if port_v is None:
return
port = _normalize_port(port_v)
if action == "rebuild":
_task_rebuild(port)
else:
_task_up(port)
+228
View File
@@ -0,0 +1,228 @@
from __future__ import annotations
import argparse
import os
import re
import shutil
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional
from cobot import process, ui
from cobot.ui import done
from cobot.process import StepProgress
_PROJECT_DIR = Path(__file__).parent.parent.parent
_DOCKER_DIR = _PROJECT_DIR / "docker"
# Default Docker Hub repository and local image prefix used when building locally.
# Репозиторий Docker Hub по умолчанию и локальный префикс образов при локальной сборке.
_DEFAULT_HUB_REPO = "evilfisru/lwc"
_DEFAULT_PREFIX = "lwc-local"
# The images must be built in this order because each one is based on the previous.
# Образы должны собираться в этом порядке, потому что каждый основан на предыдущем.
_CONTROLLER_CHAIN = ["ros-core", "ros-base", "ros-iiwa7"]
_WEBOTS_CHAIN = ["ros-core", "ros-base", "ros-iiwa7-webots"]
# Maps each image to the image it is built FROM. None means it starts from base Ubuntu.
# Сопоставляет каждый образ с тем, на основе которого он собирается. None - базовый Ubuntu.
_IMAGE_PARENT: dict[str, str | None] = {
"ros-core": None,
"ros-base": "ros-core",
"ros-iiwa7": "ros-base",
"ros-iiwa7-webots": "ros-base",
}
# These images need the full project source as Docker build context.
# Эти образы требуют полный исходный код проекта как контекст сборки.
_NEEDS_PROJECT_CTX = {"ros-iiwa7", "ros-iiwa7-webots"}
@dataclass
class _Config:
ros_version: str
variant: str
source: str
build_type: str
image_prefix: str
hub_repo: str
def _build_image(name: str, tag: str, dockerfile: Path, ctx: Path, p: StepProgress,
lo: float, hi: float, parent_tag: Optional[str], build_type: str) -> bool:
"""Build a single Docker image, streaming output and mapping "Step X/Y" to the
lo..hi slice of the progress bar. Returns True on success.
Собирает один Docker-образ, транслируя вывод и отображая "Step X/Y" на участок
lo..hi прогресс-бара. Возвращает True при успехе.
"""
p.raw(f"[cyan]▸[/cyan] Сборка [bold]{name}[/bold]...")
env = {**os.environ, "DOCKER_BUILDKIT": "0"}
cmd = [
"docker", "build", "-t", tag, "-f", str(dockerfile),
"--build-arg", f"BUILD_TYPE={build_type}",
]
if parent_tag:
cmd += ["--build-arg", f"IMAGE={parent_tag}"]
cmd.append(str(ctx))
def on_line(s: str) -> None:
if s:
p.log(s)
m = re.match(r"Step (\d+)/(\d+) :", s)
if m:
step, total = int(m.group(1)), int(m.group(2))
p.set(lo + step / total * (hi - lo), f"{name}: шаг {step}/{total}")
rc = process.stream(cmd, env=env, on_line=on_line)
if rc in (-9, -15):
return False
if rc == 0:
p.raw(f"[green]✓[/green] {name}")
return True
p.raw(f"[red]Сборка не удалась:[/red] {tag}")
return False
def _pull_image(name: str, tag: str, p: StepProgress, lo: float, hi: float) -> bool:
"""Pull a Docker image, tracking progress by counting completed layers.
Скачивает Docker-образ, отслеживая прогресс по числу завершённых слоёв.
"""
p.raw(f"[cyan]▸[/cyan] Скачивание [bold]{name}[/bold] ({tag})...")
layers_total = 0
layers_done = 0
def on_line(s: str) -> None:
nonlocal layers_total, layers_done
if s:
p.log(s)
if "Pulling fs layer" in s or "Waiting" in s:
layers_total += 1
elif "Pull complete" in s or "Already exists" in s:
layers_done += 1
if layers_total > 0:
p.set(lo + layers_done / layers_total * (hi - lo), f"{name}: слои")
rc = process.stream(["docker", "pull", tag], on_line=on_line)
if rc in (-9, -15):
return False
if rc == 0:
p.raw(f"[green]✓[/green] {name}")
return True
p.raw(f"[red]Скачивание не удалось:[/red] {tag}")
return False
def _execute(cfg: _Config) -> None:
"""Build or pull all images in the chain selected by the user's choices.
Собирает или скачивает все образы из цепочки, выбранной пользователем.
"""
chain = _WEBOTS_CHAIN if cfg.variant == "webots" else _CONTROLLER_CHAIN
n = len(chain)
ok = True
fail_msg = ""
if cfg.source == "build":
title = f"Сборка {n} образ(ов) — ROS {cfg.ros_version} — {cfg.build_type}"
with StepProgress(title) as p:
for i, name in enumerate(chain):
lo, hi = i / n * 100, (i + 1) / n * 100
p.set(lo, f"Образ {i + 1}/{n}: {name}")
tag = f"{cfg.image_prefix}:{name}-{cfg.ros_version}"
dockerfile = _DOCKER_DIR / cfg.ros_version / name / "Dockerfile"
if not dockerfile.exists():
ok, fail_msg = False, f"Dockerfile не найден: {dockerfile}"
break
ctx = _PROJECT_DIR if name in _NEEDS_PROJECT_CTX else dockerfile.parent
parent_name = _IMAGE_PARENT.get(name)
parent_tag = (f"{cfg.image_prefix}:{parent_name}-{cfg.ros_version}"
if parent_name else None)
if not _build_image(name, tag, dockerfile, ctx, p, lo, hi,
parent_tag, cfg.build_type):
ok, fail_msg = False, f"Сборка образа {name} не удалась"
break
if ok:
p.set(100, "Готово")
done(ok, f"Образы готовы: {cfg.image_prefix}:<name>-{cfg.ros_version}"
if ok else fail_msg)
else:
short = "webots" if cfg.variant == "webots" else "iiwa"
suffix = "-dev" if cfg.build_type == "dev" else ""
full_ref = f"{cfg.hub_repo}:{short}-{cfg.ros_version}{suffix}"
with StepProgress(f"Скачивание из {cfg.hub_repo} — ROS {cfg.ros_version}") as p:
if _pull_image(short, full_ref, p, 0, 100):
p.set(100, "Готово")
else:
ok, fail_msg = False, f"Скачивание {full_ref} не удалось"
done(ok, f"Образ готов: {full_ref}" if ok else fail_msg)
def _discover_versions() -> List[str]:
"""Return ROS versions found in docker/ (jazzy first). Falls back to ["jazzy"].
Возвращает версии ROS из docker/ (jazzy первым). По умолчанию ["jazzy"].
"""
if not _DOCKER_DIR.exists():
return ["jazzy"]
dirs = sorted(d.name for d in _DOCKER_DIR.iterdir() if d.is_dir())
if "jazzy" in dirs:
dirs = ["jazzy"] + [d for d in dirs if d != "jazzy"]
return dirs or ["jazzy"]
def register(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser("docker-setup", help="Build or pull Docker images for KUKA iiwa7")
p.set_defaults(func=run)
def run(args: argparse.Namespace) -> None:
if not shutil.which("docker"):
ui.error("Docker не установлен или отсутствует в PATH.")
sys.exit(1)
ui.header("Настройка Docker", "сборка или скачивание образов KUKA iiwa7")
versions = _discover_versions()
default = "jazzy" if "jazzy" in versions else versions[0]
ros_version = ui.select("Версия ROS:", versions, default)
if ros_version is None:
return
src = ui.select("Источник:", ["Скачать с Docker Hub", "Собрать локально"],
"Скачать с Docker Hub")
if src is None:
return
source = "build" if src == "Собрать локально" else "pull"
variant_v = ui.select(
"Что установить:",
["Только контроллер — ros-core, ros-base, ros-iiwa7",
"Контроллер с Webots — ros-core, ros-base, ros-iiwa7-webots"],
"Только контроллер — ros-core, ros-base, ros-iiwa7",
)
if variant_v is None:
return
variant = "webots" if variant_v.startswith("Контроллер с Webots") else "controller"
build_type = ui.select("Тип сборки:", ["release", "dev"], "release")
if build_type is None:
return
image_prefix, hub_repo = _DEFAULT_PREFIX, _DEFAULT_HUB_REPO
if source == "pull":
v = ui.text("Репозиторий Docker Hub:", _DEFAULT_HUB_REPO)
if v is None:
return
hub_repo = v
else:
v = ui.text("Префикс образов:", _DEFAULT_PREFIX)
if v is None:
return
image_prefix = v
cfg = _Config(
ros_version=ros_version, variant=variant, source=source,
build_type=build_type, image_prefix=image_prefix, hub_repo=hub_repo,
)
_execute(cfg)
+387
View File
@@ -0,0 +1,387 @@
from __future__ import annotations
import argparse
import os
import shutil
import subprocess
from pathlib import Path
from cobot import process, ui
from cobot import privilege
from cobot.ui import done, header
from cobot.commands.docker_setup import run as _docker_setup
# Root directory of the project, used as the working directory for colcon builds.
# Корневая директория проекта, используется как рабочая директория для сборки colcon.
_PROJECT_DIR = Path(__file__).parent.parent.parent
# ROS2 distribution name targeted by this installer.
# Название дистрибутива ROS2, который устанавливает этот скрипт.
_DISTRO = "jazzy"
# Webots simulator version targeted by this installer.
# Версия симулятора Webots, устанавливаемая этим скриптом.
_WEBOTS_VERSION = "2025a"
# Directory that contains the shell scripts used by this command.
# Директория с shell-скриптами, используемыми этой командой.
_SCRIPTS_DIR = _PROJECT_DIR / "scripts"
# apt packages that must exist before rosdep can install the pip-based keys
# (python3-pip / dev / venv). Their absence is what produced the "pip is not
# installed" failure in the screenshots.
# apt-пакеты, необходимые до того как rosdep сможет установить pip-зависимости.
# Именно их отсутствие давало ошибку "pip is not installed" на скриншотах.
_APT_PREREQS = ["python3-pip", "python3-dev", "python3-venv"]
# OS and tool detection helpers
# Вспомогательные функции для определения ОС и наличия инструментов
def _detect_ubuntu_2404() -> bool:
"""Return True if the current OS is Ubuntu 24.04 (Noble).
Возвращает True, если текущая ОС - Ubuntu 24.04 (Noble).
"""
path = Path("/etc/os-release")
if not path.exists():
return False
info: dict[str, str] = {}
for line in path.read_text().splitlines():
if "=" in line:
k, _, v = line.partition("=")
info[k.strip()] = v.strip().strip('"')
return info.get("ID") == "ubuntu" and info.get("VERSION_ID") == "24.04"
def _detect_ros2() -> bool:
"""Return True if ROS2 Jazzy is already installed under /opt/ros/jazzy.
Возвращает True, если ROS2 Jazzy уже установлен в /opt/ros/jazzy.
"""
return Path(f"/opt/ros/{_DISTRO}").is_dir()
def webots_installed() -> bool:
"""Return True if the Webots binary is available on PATH.
Возвращает True, если бинарный файл Webots доступен в PATH.
"""
return shutil.which("webots") is not None
def _ros2_env() -> dict:
"""Build an environment dict with ROS2 variables sourced from setup.bash.
Sources /opt/ros/jazzy/setup.bash in a subprocess, captures all exported
variables and merges them into a copy of os.environ. Falls back to plain
os.environ if the setup file does not exist yet.
Формирует словарь окружения с переменными ROS2, полученными из setup.bash.
Возвращает чистый os.environ если файл setup.bash ещё не существует.
"""
setup = Path(f"/opt/ros/{_DISTRO}/setup.bash")
if not setup.exists():
return os.environ.copy()
result = subprocess.run(
["bash", "-c", f"source {setup} && env"],
capture_output=True, text=True,
)
env = os.environ.copy()
for line in result.stdout.splitlines():
if "=" in line:
k, _, v = line.partition("=")
env[k] = v
# CMake's find_package(Python3) ignores PATH and uses its own search logic,
# so we must pin it explicitly to the system Python where catkin_pkg is installed.
# CMake игнорирует PATH при поиске Python через find_package(Python3),
# поэтому явно указываем системный Python, где установлен catkin_pkg.
env["Python3_EXECUTABLE"] = "/usr/bin/python3"
env["PYTHON_EXECUTABLE"] = "/usr/bin/python3"
# Keep PATH clean so other tools (rosdep, colcon itself) use system Python.
# Чистим PATH чтобы другие инструменты тоже использовали системный Python.
_SYSTEM_PATHS = ["/usr/bin", "/usr/local/bin"]
existing = env.get("PATH", "").split(":")
env["PATH"] = ":".join(
_SYSTEM_PATHS + [p for p in existing if p not in _SYSTEM_PATHS]
)
return env
# Bash-script runner that understands PROGRESS:<pct>:<label> markers
# Запуск bash-скриптов с поддержкой маркеров PROGRESS:<pct>:<метка>
def _run_script(script: Path, title: str) -> int:
"""Run a shell script, streaming its output to a live log and advancing the
progress bar from PROGRESS:<pct>:<label> markers (which are not echoed raw).
Returns the script exit code.
Запускает shell-скрипт, транслируя вывод в живой лог и продвигая прогресс-бар по
маркерам PROGRESS:<pct>:<метка> (сами маркеры не печатаются). Возвращает код возврата.
"""
if not script.exists():
header(title)
ui.error(f"Скрипт не найден: {script}")
done(False, "Скрипт отсутствует")
return 1
with process.StepProgress(title) as p:
def on_line(s: str) -> None:
if s.startswith("PROGRESS:"):
parts = s.split(":", 2)
try:
p.set(float(parts[1]), parts[2] if len(parts) > 2 else "")
except (ValueError, IndexError):
pass
return
if s:
p.log(s)
rc = process.stream(["bash", str(script)], cwd=str(_PROJECT_DIR), on_line=on_line)
ok = rc in (0, -9, -15)
done(ok, "Готово" if ok else f"Скрипт завершился с кодом {rc}")
return rc
def install_ros2(pkg: str) -> bool:
"""Run the ROS2 Jazzy install shell script for the chosen variant (desktop / ros-base).
Запускает shell-скрипт установки ROS2 Jazzy для выбранного варианта (desktop / ros-base).
"""
script = _SCRIPTS_DIR / f"setup_ros2_{pkg.replace('-', '_')}.sh"
rc = _run_script(script, f"Установка ROS2 {_DISTRO} ({pkg})")
return rc in (0, -9, -15)
def install_webots() -> bool:
"""Run the Webots installation shell script.
Запускает shell-скрипт установки Webots.
"""
script = _SCRIPTS_DIR / "install_webots.sh"
rc = _run_script(script, f"Установка Webots {_WEBOTS_VERSION}")
return rc in (0, -9, -15)
# Build prerequisites
# Предусловия сборки
def _missing_apt_prereqs() -> list[str]:
"""Return the subset of _APT_PREREQS that is not currently installed via dpkg.
Возвращает подмножество _APT_PREREQS, которое сейчас не установлено через dpkg.
"""
missing = []
for pkg in _APT_PREREQS:
r = subprocess.run(
["dpkg-query", "-W", "-f=${Status}", pkg],
capture_output=True, text=True,
)
if "install ok installed" not in r.stdout:
missing.append(pkg)
return missing
def _ensure_root_pip_break(p: process.StepProgress) -> None:
"""Let root's pip override PEP 668, scoped to /root/.config/pip/pip.conf.
rosdep installs the pip-based rosdep keys (fastapi, uvicorn, multipart, fastmcp)
as root via sudo; on Ubuntu 24.04 that is blocked by PEP 668 unless break-system-
packages is allowed. Writing root's pip config is idempotent, reversible (just
delete the file), and does not touch the user's own pip configuration.
Разрешает pip от root обходить PEP 668, ограничиваясь /root/.config/pip/pip.conf.
rosdep ставит pip-зависимости от root через sudo; на Ubuntu 24.04 это блокируется
PEP 668, пока не разрешён break-system-packages. Запись конфига pip от root
идемпотентна, обратима (удалить файл) и не трогает пользовательский pip.
"""
snippet = (
"mkdir -p /root/.config/pip && "
"( grep -qs 'break-system-packages' /root/.config/pip/pip.conf || "
"printf '[global]\\nbreak-system-packages = true\\n' "
">> /root/.config/pip/pip.conf )"
)
process.stream(privilege.sudo(["bash", "-c", snippet]), on_line=p.log)
# rosdep calls `pip install -U <pkg>` which upgrades every transitive dependency,
# including packages installed by apt that have no pip RECORD file, causing an
# uninstall failure. Pre-installing with --ignore-installed creates pip RECORD
# files for all transitive deps so the subsequent rosdep upgrade succeeds.
process.stream(
privilege.sudo(["pip3", "install", "--break-system-packages",
"--ignore-installed", "fastmcp"]),
on_line=p.log,
)
def _register_rosdep_source(p: process.StepProgress, env: dict) -> None:
"""Register the project's local rosdep.yaml as a rosdep source and run rosdep update.
Only re-writes / updates when the source file is missing or out of date.
Регистрирует локальный rosdep.yaml проекта как источник rosdep и запускает rosdep update.
Перезаписывает/обновляет только если файл-источник отсутствует или устарел.
"""
rosdep_yaml = _PROJECT_DIR / "rosdep.yaml"
if not rosdep_yaml.exists():
return
sources_list = Path("/etc/ros/rosdep/sources.list.d/50-kuka-local.list")
entry = f"yaml file://{rosdep_yaml}\n"
try:
current = sources_list.read_text() if sources_list.exists() else ""
except Exception:
current = ""
if current == entry:
return
snippet = (
"mkdir -p /etc/ros/rosdep/sources.list.d && "
f"printf '%s\\n' 'yaml file://{rosdep_yaml}' > {sources_list}"
)
process.stream(privilege.sudo(["bash", "-c", snippet]), on_line=p.log)
p.log(f"Зарегистрирован локальный источник rosdep: {rosdep_yaml}")
process.stream(["rosdep", "update"], env=env, cwd=str(_PROJECT_DIR), on_line=p.log)
def _count_colcon_packages(env: dict) -> int:
"""Count colcon packages under src/ so the build bar can show X / total.
Считает пакеты colcon в src/, чтобы бар сборки показывал X / всего.
"""
r = subprocess.run(
["colcon", "list", "--base-paths", "src"],
capture_output=True, text=True, cwd=str(_PROJECT_DIR), env=env,
)
return max(len([l for l in r.stdout.splitlines() if l.strip()]), 1)
def build_workspace() -> bool:
"""Build the workspace: apt prerequisites -> rosdep install -> colcon build.
Step 1 guarantees python3-pip/dev/venv and allows root pip under PEP 668 so the
pip-based rosdep keys install cleanly. Step 2 runs rosdep install with
PIP_BREAK_SYSTEM_PACKAGES=1. Step 3 compiles every package with live progress.
Собирает workspace: apt-предусловия -> rosdep install -> colcon build.
Шаг 1 гарантирует python3-pip/dev/venv и разрешает pip от root под PEP 668. Шаг 2
запускает rosdep install с PIP_BREAK_SYSTEM_PACKAGES=1. Шаг 3 компилирует все пакеты.
"""
env = _ros2_env()
env["PIP_BREAK_SYSTEM_PACKAGES"] = "1"
if not shutil.which("colcon") and not Path(f"/opt/ros/{_DISTRO}/bin/colcon").exists():
header("Сборка проекта")
ui.error("colcon не найден.")
ui.note(f"Сначала выполните: source /opt/ros/{_DISTRO}/setup.bash")
done(False, "colcon недоступен")
return False
ok = True
fail_msg = ""
with process.StepProgress("Сборка проекта") as p:
# --- Шаг 1/3: системные зависимости pip (apt) ---
p.raw("[bold]Шаг 1/3 — системные зависимости pip (apt)[/bold]")
p.set(0, "Проверка python3-pip / dev / venv...")
missing = _missing_apt_prereqs()
if missing:
p.log(f"Установка: {', '.join(missing)}")
process.stream(privilege.sudo(["apt-get", "update", "-q"]), env=env, on_line=p.log)
rc = process.stream(
privilege.sudo(["apt-get", "install", "-y", *missing]),
env=env, on_line=p.log,
)
if rc not in (0, -9, -15):
ok, fail_msg = False, "Не удалось установить apt-зависимости"
else:
p.log("python3-pip / dev / venv уже установлены")
if ok:
_ensure_root_pip_break(p)
# --- Шаг 2/3: rosdep install ---
if ok:
p.set(10, "rosdep install...")
p.raw("\n[bold]Шаг 2/3 — rosdep install[/bold]")
_register_rosdep_source(p, env)
rc = process.stream(
["rosdep", "install", "--from-paths", "src", "-i", "-r", "-y"],
env=env, cwd=str(_PROJECT_DIR), on_line=p.log,
)
if rc not in (0, -9, -15):
ok, fail_msg = False, "rosdep install завершился с ошибкой"
# --- Шаг 3/3: colcon build ---
if ok:
total = _count_colcon_packages(env)
p.set(30, f"0 / {total} пакетов")
p.raw(f"\n[bold]Шаг 3/3 — colcon build ({total} пакетов)[/bold]")
built = 0
def _on_build(s: str) -> None:
nonlocal built
if s:
p.log(s)
if "Finished <<<" in s or "Failed <<<" in s:
built += 1
p.set(30 + built / total * 70, f"{built} / {total} пакетов")
rc = process.stream(
["colcon", "build", "--base-paths", "src"],
env=env, cwd=str(_PROJECT_DIR), on_line=_on_build,
)
if rc not in (0, -9, -15):
ok, fail_msg = False, "colcon build завершился с ошибкой"
else:
p.set(100, "Готово")
done(ok, "Сборка завершена" if ok else fail_msg)
if ok:
ui.note("Активируйте окружение: source install/setup.bash")
return ok
# Interactive flow
# Интерактивный сценарий
def run(args: argparse.Namespace) -> None:
"""Guide the user through installing ROS2 Jazzy and building the workspace.
Проводит пользователя через установку ROS2 Jazzy и сборку workspace.
"""
header("Локальная установка", "ROS2 Jazzy + сборка проекта")
choice = ui.select("Установить ROS2 Jazzy?", ["Да, установить", "Нет, выход"],
"Да, установить")
if not choice or choice.startswith("Нет"):
return
# Acquire sudo once, up front, with the masked prompt + keep-alive thread.
# Получаем sudo один раз, заранее, с маскированным вводом + keep-alive потоком.
if not privilege.ensure_sudo():
return
if not _detect_ubuntu_2404():
v = ui.select(
"Ubuntu 24.04 не обнаружена. Настроить окружение через Docker?",
["Да, запустить docker-setup", "Нет, выход"],
"Да, запустить docker-setup",
)
if v and v.startswith("Да"):
_docker_setup(args)
return
variant = ui.select(
"Какой вариант ROS2 Jazzy установить?",
["Desktop (полный, с GUI-инструментами)", "Base (минимальный, без GUI)"],
"Desktop (полный, с GUI-инструментами)",
)
if not variant:
return
pkg = "desktop" if variant.startswith("Desktop") else "ros-base"
if not install_ros2(pkg):
return
if ui.confirm("Собрать workspace сейчас? (rosdep install + colcon build)", default=True):
build_workspace()
if not webots_installed():
if ui.confirm(f"Установить симулятор Webots {_WEBOTS_VERSION}?", default=False):
install_webots()
def register(subparsers: argparse._SubParsersAction) -> None:
"""Register the local-setup subcommand with the CLI argument parser.
Регистрирует подкоманду local-setup в парсере аргументов командной строки.
"""
p = subparsers.add_parser(
"local-setup",
help="Install ROS2 Jazzy natively and build the project with colcon",
)
p.set_defaults(func=run)
+117
View File
@@ -0,0 +1,117 @@
from __future__ import annotations
import argparse
import subprocess
from pathlib import Path
from typing import List, Optional
from cobot import ui, process
from cobot.commands.local_setup import _ros2_env
_PROJECT_DIR = Path(__file__).parent.parent.parent
def _count_packages(packages: List[str], env: dict) -> int:
"""Count how many colcon packages will be built so we can show X / total progress.
Считает количество пакетов colcon для отображения прогресса X / всего.
"""
list_cmd = ["colcon", "list", "--base-paths", "src"]
if packages:
list_cmd += ["--packages-select"] + packages
result = subprocess.run(list_cmd, capture_output=True, text=True,
cwd=_PROJECT_DIR, env=env)
return max(len([l for l in result.stdout.splitlines() if l.strip()]), 1)
def _rebuild(packages: List[str], symlink: bool) -> None:
"""Run colcon build for the selected packages (or all), streaming live output
with a per-package progress bar.
Запускает colcon build для выбранных пакетов (или всех), транслируя живой вывод
с прогресс-баром по пакетам.
"""
env = _ros2_env()
total = _count_packages(packages, env)
pkg_label = " ".join(packages) if packages else "все пакеты"
symlink_label = " --symlink-install" if symlink else ""
cmd = ["colcon", "build", "--base-paths", "src"]
if symlink:
cmd.append("--symlink-install")
if packages:
cmd += ["--packages-select"] + packages
built = 0
def _parse(line: str):
nonlocal built
if "Finished <<<" in line or "Failed <<<" in line:
built += 1
return (built / total * 100, f"{built} / {total} пакетов")
return None
rc = process.run_step(
f"colcon build{symlink_label} — {pkg_label}",
cmd,
env=env,
cwd=str(_PROJECT_DIR),
total=100.0,
parse_progress=_parse,
success_msg="Сборка завершена",
fail_msg="Сборка завершилась с ошибкой",
)
if rc in (0, -9, -15):
ui.note("Активируйте окружение: source install/setup.bash")
def register(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser(
"rebuild",
help="Rebuild ROS2 packages in src/ with colcon",
)
p.add_argument(
"packages",
nargs="*",
metavar="PACKAGE",
help="Packages to rebuild (omit to be asked, or leave empty for all)",
)
p.set_defaults(symlink=None)
p.add_argument(
"--symlink-install",
dest="symlink",
action="store_true",
help="Pass --symlink-install to colcon build",
)
p.add_argument(
"--no-symlink-install",
dest="symlink",
action="store_false",
help="Do not pass --symlink-install to colcon build",
)
p.set_defaults(func=run)
def run(args: argparse.Namespace) -> None:
"""Entry point for the rebuild command.
Точка входа для команды rebuild.
"""
packages: Optional[List[str]] = args.packages if args.packages else None
if packages is None:
value = ui.text(
"Какие пакеты пересобрать? (через пробел, пусто — все)",
"",
note="Пример: iiwa_controller iiwa_bringup",
)
if value is None:
return
packages = value.split() if value.strip() else []
symlink = args.symlink
if symlink is None:
choice = ui.select("Использовать --symlink-install?", ["Да", "Нет"], "Да")
if choice is None:
return
symlink = choice == "Да"
_rebuild(packages, symlink)
+327
View File
@@ -0,0 +1,327 @@
from __future__ import annotations
import argparse
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any, List, Optional
from ruamel.yaml import YAML
from cobot import ui
_PROJECT_DIR = Path(__file__).parent.parent.parent
_CONFIG_PATH = _PROJECT_DIR / "cobot-setting.yaml"
_TOOLS_YAML = _PROJECT_DIR / "src" / "iiwa_config" / "config" / "tools.yaml"
_TOOL_ACTIVE_XACRO = (
_PROJECT_DIR / "src" / "iiwa_description" / "urdf" / "tools" / "tool_active.xacro"
)
_SRDF_PATH = _PROJECT_DIR / "src" / "iiwa_config" / "config" / "moveit" / "iiwa7.srdf"
# Use ruamel.yaml instead of PyYAML so comments and formatting in the config are preserved.
# Используем ruamel.yaml вместо PyYAML, чтобы комментарии и форматирование в конфиге сохранялись.
_yaml = YAML()
_yaml.preserve_quotes = True
@dataclass
class _Field:
key: str # dot-separated path within the block, e.g. "webots.world"
question: str
default: Any
note: str = ""
options: Optional[List[str]] = None # if set - select(), else - text()
def label(self) -> str:
return self.key.split(".")[-1]
@dataclass
class _Block:
yaml_key: str # top-level key in cobot-setting.yaml
title: str # shown in "Настроить <title>?" prompt
fields: List[_Field]
def _load_tools_registry() -> dict:
"""Читает tools.yaml и возвращает словарь инструментов."""
if not _TOOLS_YAML.exists():
return {}
_y = YAML()
with open(_TOOLS_YAML, encoding="utf-8") as f:
data = _y.load(f)
return dict(data.get("tools", {}))
def _build_tool_block() -> Optional[_Block]:
"""Строит блок выбора инструмента из реестра tools.yaml.
Возвращает None если реестр недоступен."""
registry = _load_tools_registry()
if not registry:
return None
options = list(registry.keys())
labels = " | ".join(
f"{name}: {registry[name].get('label', '')}" for name in options
)
return _Block(
yaml_key="tool",
title="Инструмент / Захват",
fields=[
_Field("active", "Выберите активный инструмент:", options[0],
note=labels, options=options),
],
)
# All configuration blocks. Each block maps to a top-level key in cobot-setting.yaml.
# Все блоки конфигурации. Каждый блок соответствует ключу верхнего уровня в cobot-setting.yaml.
_BLOCKS: List[_Block] = [
_Block(
yaml_key="foxglove",
title="Foxglove bridge",
fields=[
_Field("enabled", "Включить Foxglove bridge?", "true",
note="Запускать foxglove_bridge вместе с узлом робота",
options=["true", "false"]),
_Field("port", "Порт WebSocket:", "8765",
note="Порт, к которому подключается Foxglove Studio (по умолчанию 8765)"),
_Field("address", "Адрес прослушивания:", "0.0.0.0",
note="0.0.0.0 = все интерфейсы, 127.0.0.1 = только localhost",
options=["0.0.0.0", "127.0.0.1"]),
_Field("use_sim_time", "Использовать симуляционное время (/clock)?", "false",
note="Подписываться на /clock вместо системного времени",
options=["false", "true"]),
_Field("debug", "Подробное логирование bridge?", "false",
options=["false", "true"]),
_Field("num_threads", "Потоки executor (0 = авто):", "0"),
],
),
_Block(
yaml_key="web",
title="Веб-сервер (FastAPI)",
fields=[
_Field("enabled", "Включить веб-сервер?", "true",
note="Запускать FastAPI-сервер для HTTP/WebSocket-управления",
options=["true", "false"]),
_Field("host", "Адрес прослушивания:", "0.0.0.0",
note="0.0.0.0 = все интерфейсы, 127.0.0.1 = только localhost",
options=["0.0.0.0", "127.0.0.1"]),
_Field("port", "Порт HTTP:", "8007",
note="Порт FastAPI-сервера (по умолчанию 8007)"),
],
),
_Block(
yaml_key="planning",
title="MoveIt планирование",
fields=[
_Field("planning_group", "Группа планирования:", "iiwa_arm",
note="Группа планирования MoveIt из SRDF"),
_Field("default_frame", "Система отсчёта по умолчанию:", "base_link"),
_Field("default_planner", "Планировщик по умолчанию:", "ompl",
options=["ompl", "pilz_industrial_motion_planner", "chomp"]),
_Field("planning_attempts", "Попыток планирования:", "3"),
],
),
_Block(
yaml_key="digital_twin",
title="Цифровой двойник (Webots / RViz)",
fields=[
_Field("webots.transform", "Трансформ робота в сцене Webots (x y z, метры):", "-0.25 0 0.79"),
_Field("webots.rotation", "Поворот робота в сцене Webots (ax ay az угол):", "0 0 1 0"),
_Field("webots.controller_timer", "Шаг таймера контроллера Webots (мс):", "50"),
],
),
_Block(
yaml_key="robot",
title="Подключение робота",
fields=[
_Field("name", "Имя модели робота:", "iiwa7"),
_Field("ip", "IP-адрес робота:", "192.170.10.2",
note="IP контроллера KUKA на сетевом интерфейсе FRI"),
_Field("port", "Порт FRI:", "30200"),
_Field("fri_cycle_ms", "Цикл FRI (мс):", "10",
note="5 мс = 200 Гц, 10 мс = 100 Гц",
options=["10", "5"]),
],
),
]
def _coerce(value: str, original: Any) -> Any:
"""Convert a string value to match the type of the original YAML value.
Преобразует строковое значение к типу исходного значения YAML.
"""
if isinstance(original, bool):
return value.lower() == "true"
if isinstance(original, int):
try:
return int(value)
except ValueError:
return value
if isinstance(original, float):
try:
return float(value)
except ValueError:
return value
return value
def _get_nested(mapping: Any, path: str) -> Any:
"""Return the value at a dot-separated path inside a nested YAML mapping, or None.
Возвращает значение по пути с точками внутри вложенного YAML-словаря, или None.
"""
keys = path.split(".")
cur = mapping
for k in keys:
if cur is None or k not in cur:
return None
cur = cur[k]
return cur
def _infer(value: str) -> Any:
"""Infer a bool / int / float / str from a raw string when there is no original
value to match the type against (i.e. the key is new in the config).
Выводит bool / int / float / str из строки, когда нет исходного значения для
сопоставления типа (т.е. ключ новый в конфиге).
"""
low = value.strip().lower()
if low in ("true", "false"):
return low == "true"
try:
return int(value)
except ValueError:
pass
try:
return float(value)
except ValueError:
pass
return value
def _set_nested(mapping: Any, path: str, value: Any) -> None:
"""Set the value at a dot-separated path, creating missing intermediate maps.
If the leaf key already exists its type is preserved via _coerce; otherwise the
type is inferred from the string with _infer. This makes the wizard tolerant of
configs that do not yet contain every field (e.g. an older cobot-setting.yaml).
Устанавливает значение по пути с точками, создавая отсутствующие промежуточные
словари. Если конечный ключ уже есть — тип сохраняется через _coerce; иначе тип
выводится из строки через _infer. Это делает мастер устойчивым к конфигам, где
ещё нет всех полей (например, более старый cobot-setting.yaml).
"""
keys = path.split(".")
cur = mapping
for k in keys[:-1]:
if k not in cur or cur[k] is None:
cur[k] = {}
cur = cur[k]
leaf = keys[-1]
if leaf in cur and cur[leaf] is not None:
cur[leaf] = _coerce(value, cur[leaf])
else:
cur[leaf] = _infer(value)
def _load_config() -> Any:
"""Load cobot-setting.yaml preserving comments and key order.
Загружает cobot-setting.yaml, сохраняя комментарии и порядок ключей.
"""
with open(_CONFIG_PATH, "r", encoding="utf-8") as fh:
return _yaml.load(fh)
def _save_config(data: Any) -> None:
"""Write the modified YAML back to cobot-setting.yaml, preserving comments.
Записывает изменённый YAML обратно в cobot-setting.yaml, сохраняя комментарии.
"""
with open(_CONFIG_PATH, "w", encoding="utf-8") as fh:
_yaml.dump(data, fh)
def _run_wizard(data: Any, blocks: List[_Block]) -> bool:
"""Walk every block: ask "Configure X?", and if yes step through its fields.
Returns True if the user completed the wizard (config was saved), False on cancel.
Проходит по каждому блоку: спрашивает "Настроить X?", и если да — проходит по полям.
Возвращает True если мастер завершён (конфиг сохранён), False при отмене.
"""
total = len(blocks)
for bi, block in enumerate(blocks):
ui.header(f"Блок {bi + 1}/{total}", block.title)
if not ui.confirm(f"Настроить {block.title}?", default=True):
continue
for fi, f in enumerate(block.fields):
yaml_val = _get_nested(data[block.yaml_key], f.key)
current = str(yaml_val) if yaml_val is not None else str(f.default)
step_note = f"Поле {fi + 1}/{len(block.fields)}"
note = f"{step_note}\n{f.note}" if f.note else step_note
if f.options:
default_opt = current if current in f.options else f.options[0]
value = ui.select(f.question, f.options, default_opt, note=note)
else:
value = ui.text(f.question, current, note=note)
if value is None:
ui.info("[yellow]Отменено.[/yellow]")
return False
_set_nested(data[block.yaml_key], f.key, value)
_save_config(data)
ui.done(True, f"Конфигурация сохранена в {_CONFIG_PATH.name}")
return True
def register(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser("robot-setup", help="Configure cobot-setting.yaml interactively")
p.set_defaults(func=run)
def run(args: argparse.Namespace) -> None:
ui.header("Настройка робота", "cobot-setting.yaml")
if not _CONFIG_PATH.exists():
ui.error(f"Конфиг не найден: {_CONFIG_PATH}")
sys.exit(1)
data = _load_config()
# Убеждаемся что секция tool существует в данных (для старых конфигов)
if "tool" not in data:
data["tool"] = {"active": "patron"}
tool_block = _build_tool_block()
blocks = ([tool_block] if tool_block else []) + list(_BLOCKS)
if not _run_wizard(data, blocks):
return
# Применяем выбранный инструмент: перезаписываем tool_active.xacro и iiwa7.srdf
active_tool = str(data["tool"].get("active", "patron"))
if not _TOOLS_YAML.exists():
ui.info(f"[yellow]tools.yaml не найден ({_TOOLS_YAML}) — пропуск применения инструмента[/yellow]")
return
try:
registry = _load_tools_registry()
if active_tool not in registry:
raise ValueError(f"Неизвестный инструмент '{active_tool}'. Доступны: {', '.join(registry)}")
tool_cfg = dict(registry[active_tool])
sys.path.insert(0, str(_PROJECT_DIR / "src" / "iiwa_utils"))
from iiwa_utils.tool_manager import apply_tool
apply_tool(tool_cfg=tool_cfg, xacro_out_path=_TOOL_ACTIVE_XACRO, srdf_path=_SRDF_PATH)
# Синхронизируем planning.pose_link с tcp_link выбранного инструмента
tcp_link = tool_cfg.get("tcp_link", "link_ee")
if "planning" in data:
data["planning"]["pose_link"] = tcp_link
_save_config(data)
ui.info(
f"[green]✓[/green] Инструмент [bold]{active_tool}[/bold] применён: "
f"tool_active.xacro, iiwa7.srdf обновлены, "
f"planning.pose_link → [bold]{tcp_link}[/bold]."
)
except Exception as exc:
ui.error(f"Не удалось применить инструмент: {exc}")
+326
View File
@@ -0,0 +1,326 @@
from __future__ import annotations
import argparse
import os
import shutil
import socket
import subprocess
from pathlib import Path
from typing import List, Optional
from cobot import process, ui
from cobot import privilege
from cobot.ui import done, header
from cobot.commands.local_setup import (
_WEBOTS_VERSION,
build_workspace,
install_webots,
webots_installed,
)
_PROJECT_DIR = Path(__file__).parent.parent.parent
_CONFIG_PATH = _PROJECT_DIR / "cobot-setting.yaml"
_INSTALL_DIR = _PROJECT_DIR / "install"
_JAZZY_DIR = Path("/opt/ros/jazzy")
# Default Webots installation path for the official .deb package.
# Путь установки Webots по умолчанию для официального .deb-пакета.
_WEBOTS_DEFAULT_HOME = Path("/usr/local/webots")
# Path where the config file is mounted inside the Docker container.
# Путь по которому конфиг-файл монтируется внутри Docker-контейнера.
_CONFIG_IN_CONTAINER = "/ros2_ws/cobot-setting.yaml"
# Container names used for docker run and docker kill.
# Имена контейнеров, используемые для docker run и docker kill.
_CONTAINER_CONTROLLER = "lwc-controller"
_CONTAINER_WEBOTS = "lwc-webots"
# Named Docker volume that stores the Webots asset cache between container runs.
# Именованный Docker volume для хранения кэша ассетов Webots между запусками контейнера.
_WEBOTS_CACHE_VOLUME = "lwc-webots-cache"
# Candidates checked in order - for the controller the webots image is a valid fallback.
# Кандидаты проверяются по порядку - для контроллера образ webots является допустимым запасным.
_CONTROLLER_IMAGES = [
"lwc-local:ros-iiwa7-jazzy",
"evilfisru/lwc:iiwa-jazzy",
"evilfisru/lwc:iiwa-jazzy-dev",
"lwc-local:ros-iiwa7-webots-jazzy",
"evilfisru/lwc:webots-jazzy",
"evilfisru/lwc:webots-jazzy-dev",
]
_WEBOTS_IMAGES = [
"lwc-local:ros-iiwa7-webots-jazzy",
"evilfisru/lwc:webots-jazzy",
"evilfisru/lwc:webots-jazzy-dev",
]
def _detect_webots_home() -> str:
"""Return the WEBOTS_HOME path for the locally installed Linux Webots, or "".
Возвращает путь WEBOTS_HOME для локально установленного Linux Webots, или "".
"""
def _is_linux_webots(home: str) -> bool:
return (Path(home) / "webots").is_file()
if "WEBOTS_HOME" in os.environ:
home = os.environ["WEBOTS_HOME"]
return home if _is_linux_webots(home) else ""
if _WEBOTS_DEFAULT_HOME.is_dir() and _is_linux_webots(str(_WEBOTS_DEFAULT_HOME)):
return str(_WEBOTS_DEFAULT_HOME)
webots_bin = shutil.which("webots")
if webots_bin:
home = str(Path(webots_bin).resolve().parent)
if _is_linux_webots(home):
return home
return ""
def _detect_gpu() -> str:
"""Return "nvidia", "mesa", or "software" based on available GPU drivers.
Возвращает "nvidia", "mesa" или "software" в зависимости от доступных драйверов GPU.
"""
if shutil.which("nvidia-smi"):
if subprocess.run(["nvidia-smi"], capture_output=True).returncode == 0:
return "nvidia"
if Path("/dev/dri").exists():
return "mesa"
return "software"
def _docker_images() -> set:
"""Return the set of "repository:tag" strings for all local Docker images.
Возвращает множество строк "репозиторий:тег" для всех локальных Docker-образов.
"""
r = subprocess.run(
["docker", "images", "--format", "{{.Repository}}:{{.Tag}}"],
capture_output=True, text=True,
)
return set(r.stdout.strip().splitlines())
def _find_image(candidates: List[str]) -> Optional[str]:
"""Return the first candidate image that exists locally, or None.
Возвращает первый образ-кандидат, присутствующий локально, или None.
"""
available = _docker_images()
for img in candidates:
if img in available:
return img
return None
# Local (non-Docker) launch
# Локальный (не Docker) запуск
def _run_local(mode: str) -> None:
"""Launch iiwa.launch.py natively. The whole ros2 launch tree runs in its own
session so a single Ctrl-C tears down every node cleanly.
Запускает iiwa.launch.py нативно. Всё дерево ros2 launch работает в своей сессии,
поэтому один Ctrl-C аккуратно завершает каждый узел.
"""
config = str(_CONFIG_PATH)
ros_cmd = f"ros2 launch iiwa_bringup iiwa.launch.py setting:={config}"
if mode == "webots":
ros_cmd += " simulate:=1"
webots_home = _detect_webots_home() if mode == "webots" else ""
webots_export = f"export WEBOTS_HOME={webots_home} && " if webots_home else ""
full_cmd = (
f"{webots_export}"
f"source {_JAZZY_DIR}/setup.bash && "
f"source {_INSTALL_DIR}/setup.bash && "
f"{ros_cmd}"
)
label = "симулятор Webots" if mode == "webots" else "контроллер"
header(f"Запуск: {label} (локально)")
ui.note(ros_cmd)
if webots_home:
ui.note(f"WEBOTS_HOME: {webots_home}")
ui.note("Нажмите Ctrl-C чтобы остановить")
rc = process.stream(
["bash", "-c", full_cmd],
cwd=str(_PROJECT_DIR),
new_session=True,
)
done(rc in (0, -2, -15, 130), "Остановлено")
# Docker launch
# Запуск в Docker
def _run_docker(image: str, mode: str, gpu: str) -> None:
"""Launch iiwa.launch.py inside a Docker container, forwarding X11/GPU for Webots.
The container is stopped with ``docker kill`` on Ctrl-C.
Запускает iiwa.launch.py внутри Docker-контейнера, пробрасывая X11/GPU для Webots.
Контейнер останавливается через ``docker kill`` по Ctrl-C.
"""
container = _CONTAINER_WEBOTS if mode == "webots" else _CONTAINER_CONTROLLER
ros_cmd = (
"source /ros2_ws/install/setup.bash && "
f"ros2 launch iiwa_bringup iiwa.launch.py setting:={_CONFIG_IN_CONTAINER}"
)
if mode == "webots":
ros_cmd += " simulate:=1"
# Remove any stale container with the same name from a previous run.
# Удаляем устаревший контейнер с таким же именем от предыдущего запуска.
subprocess.run(["docker", "rm", "-f", container], capture_output=True)
cmd = [
"docker", "run", "--rm",
"--name", container,
"--network", "host",
"--hostname", socket.gethostname(),
"-e", "USER=root",
]
if mode == "webots":
subprocess.run(["xhost", "+local:docker"], capture_output=True)
cmd += [
"-e", f"DISPLAY={os.environ.get('DISPLAY', ':0')}",
"-e", "QT_X11_NO_MITSHM=1",
"-v", "/tmp/.X11-unix:/tmp/.X11-unix:rw",
"-v", f"{_WEBOTS_CACHE_VOLUME}:/root/.cache/Cyberbotics/Webots",
]
if gpu == "nvidia":
cmd += [
"--gpus", "all",
"-e", "NVIDIA_VISIBLE_DEVICES=all",
"-e", "NVIDIA_DRIVER_CAPABILITIES=graphics,utility,compute",
]
elif gpu == "mesa":
cmd += ["--device", "/dev/dri"]
else:
cmd += [
"-e", "LIBGL_ALWAYS_SOFTWARE=1",
"-e", "GALLIUM_DRIVER=llvmpipe",
]
if _CONFIG_PATH.exists():
cmd += ["-v", f"{_CONFIG_PATH}:{_CONFIG_IN_CONTAINER}:ro"]
cmd += [image, "bash", "-c", ros_cmd]
_GPU_LABELS = {
"nvidia": "NVIDIA GPU",
"mesa": "Intel/AMD DRI (Mesa)",
"software": "Программный рендеринг (llvmpipe)",
}
label = "симулятор Webots" if mode == "webots" else "контроллер"
header(f"Запуск: {label} в Docker")
ui.note(f"Образ: {image}")
if mode == "webots":
ui.note(f"GPU: {_GPU_LABELS.get(gpu, gpu)}")
ui.note("Нажмите Ctrl-C чтобы остановить")
rc = process.stream(
cmd,
kill_fn=lambda: subprocess.run(["docker", "kill", container], capture_output=True),
)
done(rc in (0, -2, -15, 130), "Остановлено")
def _local_flow(args: argparse.Namespace) -> None:
"""Interactive flow for local launch: check Webots/ROS2/build, then run.
Интерактивный сценарий локального запуска: проверка Webots/ROS2/сборки, затем запуск.
"""
mode_v = ui.select(
"Что запустить?",
["Контроллер", "Симулятор Webots"],
"Контроллер",
)
if mode_v is None:
return
mode = "webots" if mode_v == "Симулятор Webots" else "controller"
if mode == "webots" and not webots_installed():
if not ui.confirm(f"Webots {_WEBOTS_VERSION} не установлен. Установить сейчас?",
default=True):
return
if not privilege.ensure_sudo() or not install_webots():
return
if not _JAZZY_DIR.is_dir():
if ui.confirm("ROS2 Jazzy не установлен. Запустить local-setup?", default=True):
from cobot.commands.local_setup import run as _local_setup
_local_setup(args)
return
if not (_INSTALL_DIR / "setup.bash").exists():
if not ui.confirm("Проект ещё не собран. Собрать сейчас?", default=True):
return
if not privilege.ensure_sudo() or not build_workspace():
return
_run_local(mode)
def _docker_flow(args: argparse.Namespace) -> None:
"""Interactive flow for Docker launch: pick an image, detect GPU, then run.
Интерактивный сценарий запуска в Docker: выбор образа, определение GPU, затем запуск.
"""
if not shutil.which("docker"):
ui.error("Docker не установлен или отсутствует в PATH.")
return
mode_v = ui.select(
"Что запустить?",
["Контроллер", "Симулятор Webots"],
"Контроллер",
)
if mode_v is None:
return
mode = "webots" if mode_v == "Симулятор Webots" else "controller"
candidates = _WEBOTS_IMAGES if mode == "webots" else _CONTROLLER_IMAGES
image = _find_image(candidates)
if image is None:
what = "Webots" if mode == "webots" else "контроллера или Webots"
if ui.confirm(f"Docker-образ для {what} не найден. Запустить docker-setup?",
default=True):
from cobot.commands.docker_setup import run as _docker_setup
_docker_setup(args)
return
gpu = _detect_gpu() if mode == "webots" else "software"
_run_docker(image, mode, gpu)
def register(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser(
"run",
help="Launch the robot controller or Webots simulator",
)
p.add_argument(
"mode",
nargs="?",
choices=["local", "docker"],
default=None,
help="local — native ROS2, docker — Docker container (default: ask)",
)
p.set_defaults(func=run)
def run(args: argparse.Namespace) -> None:
mode = getattr(args, "mode", None)
if mode == "local":
_local_flow(args)
elif mode == "docker":
_docker_flow(args)
else:
v = ui.select(
"Как запустить проект?",
["Локально (нативный ROS2)", "Docker"],
"Локально (нативный ROS2)",
)
if v is None:
return
if v.startswith("Локально"):
_local_flow(args)
else:
_docker_flow(args)
+52
View File
@@ -0,0 +1,52 @@
import argparse
from cobot import ui
# Import each sub-command's run() so we can call them in sequence.
# Импортируем run() каждой подкоманды, чтобы вызывать их по порядку.
from cobot.commands.doc_setup import run as _doc_setup
from cobot.commands.docker_setup import run as _docker_setup
from cobot.commands.local_setup import run as _local_setup
from cobot.commands.robot_setup import run as _robot_setup
def register(subparsers):
"""Register the "setup" subparser.
Регистрирует подпарсер "setup".
"""
p = subparsers.add_parser("setup", help="First-time project setup")
p.set_defaults(func=run)
def run(args: argparse.Namespace) -> None:
"""Run the three-step first-time setup wizard: docs -> robot config -> build env.
Запускает трёхшаговый мастер первичной настройки: документация -> конфиг робота -> среда сборки.
"""
ui.header("Первичная настройка", "3 шага")
# Step 1 - documentation server.
# Шаг 1 - сервер документации.
if ui.confirm("Шаг 1/3 — настроить сервер документации?", default=True):
_doc_setup(args)
# Step 2 - robot parameters in cobot-setting.yaml.
# Шаг 2 - параметры робота в cobot-setting.yaml.
if ui.confirm("Шаг 2/3 — настроить параметры робота (cobot-setting.yaml)?", default=True):
_robot_setup(args)
# Step 3 - build environment: local ROS2 or Docker.
# Шаг 3 - среда сборки: локальный ROS2 или Docker.
env_choice = ui.select(
"Шаг 3/3 — как настроить среду сборки?",
[
"local-setup — установить ROS2 Jazzy на эту машину и собрать через colcon",
"docker-setup — собрать Docker-образ с предустановленным ROS2 Jazzy",
],
"local-setup — установить ROS2 Jazzy на эту машину и собрать через colcon",
)
if env_choice is None:
return
if env_choice.startswith("local"):
_local_setup(args)
else:
_docker_setup(args)
+95
View File
@@ -0,0 +1,95 @@
from __future__ import annotations
import argparse
import subprocess
from pathlib import Path
from cobot import process
from cobot.ui import done
from cobot.process import StepProgress
_PROJECT_DIR = Path(__file__).parent.parent.parent
def _plain(message: str) -> None:
"""Print after replacing this command's own uv environment.
Rich modules loaded before ``uv tool install`` can no longer be complete after
uv replaces the editable tool environment. Do not render with Rich after that
command returns.
"""
print(message, flush=True)
def _git(*args: str) -> str:
"""Run a git command in the project dir and return its stripped stdout.
Запускает git-команду в директории проекта и возвращает обрезанный stdout.
"""
return subprocess.check_output(["git", *args], cwd=_PROJECT_DIR, text=True).strip()
def _update() -> int:
"""Fetch the current branch, show incoming commits, pull, and reinstall the cobot CLI.
Progress: fetch (0-30 %), pull (30-80 %), reinstall (80-100 %).
Получает текущую ветку, показывает входящие коммиты, делает pull и переустанавливает CLI.
Прогресс: fetch (0-30 %), pull (30-80 %), переустановка (80-100 %).
"""
with StepProgress("Обновление проекта") as p:
try:
branch = _git("rev-parse", "--abbrev-ref", "HEAD")
p.raw(f"[cyan]▸[/cyan] Ветка: [bold]{branch}[/bold]")
p.set(0, "Получение с удалённого репозитория...")
rc = process.stream(["git", "fetch", "origin"], cwd=str(_PROJECT_DIR), on_line=p.log)
if rc != 0:
done(False, f"git fetch завершился с кодом {rc}")
return 1
p.set(30)
behind = _git("rev-list", f"HEAD..origin/{branch}", "--count")
if behind == "0":
p.log("Исходники уже актуальны; проверка установки CLI...")
else:
p.raw(f"\n[bold]{behind} новых коммит(ов):[/bold]")
for line in _git("log", f"HEAD..origin/{branch}", "--oneline").splitlines():
p.log(line)
p.set(30, "Применение изменений...")
rc = process.stream(["git", "pull", "origin", branch],
cwd=str(_PROJECT_DIR), on_line=p.log)
if rc != 0:
done(False, f"git pull завершился с кодом {rc}")
return 1
p.set(80)
except (subprocess.CalledProcessError, OSError) as exc:
done(False, str(exc))
return 1
# uv can replace the Rich package of this running CLI. Keep this stage outside
# StepProgress and only use built-in print afterwards.
_plain("\n▸ Переустановка cobot CLI...")
try:
rc = process.stream(
["uv", "tool", "install", "--editable", str(_PROJECT_DIR)],
on_line=lambda line: _plain(f" {line}"),
)
except OSError as exc:
_plain(f"✗ Не удалось запустить установщик: {exc}")
return 1
if rc != 0:
_plain(
f"✗ Установка CLI завершилась с кодом {rc}. Исходники обновлены, "
"но установка не завершена. Сохраните вывод выше и повторите cobot update."
)
return 1
_plain("✓ Проект обновлён и cobot переустановлен")
return 0
def register(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser("update", help="Pull latest changes from the remote git branch")
p.set_defaults(func=run)
def run(args: argparse.Namespace) -> None:
raise SystemExit(_update())
+176
View File
@@ -0,0 +1,176 @@
from __future__ import annotations
import subprocess
import sys
import threading
from typing import List, Optional, Sequence
from cobot import ui
from cobot.ui import console
# How often the keep-alive thread refreshes the sudo timestamp (seconds).
# Sudo's default timeout is 15 min; 60 s gives a huge safety margin.
# Как часто поток keep-alive обновляет токен sudo (секунды).
# Таймаут sudo по умолчанию 15 мин; 60 с даёт большой запас.
_KEEPALIVE_INTERVAL = 60
# Module-level state: whether sudo has been primed and the keep-alive thread.
# Состояние уровня модуля: прогрет ли sudo и поток keep-alive.
_primed = False
_keepalive_thread: Optional[threading.Thread] = None
_keepalive_stop = threading.Event()
def _have_valid_timestamp() -> bool:
"""Return True if a non-interactive ``sudo -n -v`` succeeds (cached token valid).
Возвращает True, если ``sudo -n -v`` проходит без запроса (токен закеширован и валиден).
"""
return subprocess.run(
["sudo", "-n", "-v"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
).returncode == 0
def _read_masked_password(prompt: str) -> Optional[str]:
"""Read a password character-by-character, echoing a ``★`` for each one.
Backspace deletes the last char. Enter submits. Ctrl-C / Esc cancels (None).
Falls back to getpass when stdin is not a TTY.
Читает пароль посимвольно, отображая ``★`` за каждый символ.
Backspace удаляет последний символ. Enter — подтвердить. Ctrl-C / Esc — отмена (None).
Откатывается на getpass, если stdin не является TTY.
"""
if not sys.stdin.isatty():
import getpass
try:
return getpass.getpass(prompt)
except (EOFError, KeyboardInterrupt):
return None
sys.stdout.write(prompt)
sys.stdout.flush()
chars: List[str] = []
while True:
kind, ch = ui._read_key()
if kind == "enter":
sys.stdout.write("\n")
sys.stdout.flush()
return "".join(chars)
if kind in ("esc", "interrupt"):
sys.stdout.write("\n")
sys.stdout.flush()
return None
if kind == "backspace":
if chars:
chars.pop()
# Erase one mask glyph: move back, overwrite with space, move back.
# Стираем один символ маски: назад, пробел, снова назад.
sys.stdout.write("\b \b")
sys.stdout.flush()
continue
# Space and any printable char are part of the password.
# Пробел и любой печатный символ — часть пароля.
if kind == "space":
chars.append(" ")
sys.stdout.write("★")
sys.stdout.flush()
elif kind == "char" and ch.isprintable():
chars.append(ch)
sys.stdout.write("★")
sys.stdout.flush()
def _validate_password(password: str) -> bool:
"""Feed the password to ``sudo -S -v`` to validate it and cache the timestamp.
Передаёт пароль в ``sudo -S -v`` для проверки и кеширования токена.
"""
proc = subprocess.run(
["sudo", "-S", "-v"],
input=password + "\n",
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
text=True,
)
return proc.returncode == 0
def _keepalive_loop() -> None:
"""Refresh the sudo timestamp periodically until the process exits.
Периодически обновляет токен sudo, пока процесс не завершится.
"""
while not _keepalive_stop.wait(_KEEPALIVE_INTERVAL):
subprocess.run(
["sudo", "-n", "-v"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
def _start_keepalive() -> None:
global _keepalive_thread
if _keepalive_thread is not None and _keepalive_thread.is_alive():
return
_keepalive_stop.clear()
_keepalive_thread = threading.Thread(target=_keepalive_loop, daemon=True)
_keepalive_thread.start()
def ensure_sudo() -> bool:
"""Make sure we hold a valid sudo timestamp, asking for the password once.
If a valid cached timestamp already exists (e.g. the user ran sudo recently),
no password is asked. Otherwise the user is prompted up to 3 times with a masked
input. On success a keep-alive thread is started. Returns True if sudo is ready.
Гарантирует наличие валидного токена sudo, спрашивая пароль один раз.
Если валидный токен уже есть (например, пользователь недавно вызывал sudo), пароль
не спрашивается. Иначе пользователю предлагается до 3 попыток с маскированным вводом.
При успехе запускается поток keep-alive. Возвращает True, если sudo готов.
"""
global _primed
if _primed and _have_valid_timestamp():
return True
if _have_valid_timestamp():
_primed = True
_start_keepalive()
return True
console.print(
"\n[bold]Для установки/удаления системных пакетов нужны права root.[/bold]"
)
console.print(
"[dim]Пароль спросим один раз и будем держать сессию sudo активной "
"до конца операции.[/dim]"
)
for attempt in range(3):
password = _read_masked_password(" [sudo] пароль: ")
if password is None:
console.print("[yellow]Отменено.[/yellow]")
return False
if _validate_password(password):
del password
_primed = True
_start_keepalive()
console.print("[green]✓ sudo активирован[/green]")
return True
remaining = 2 - attempt
if remaining > 0:
console.print(f"[red]Неверный пароль.[/red] Осталось попыток: {remaining}")
else:
console.print("[red]Неверный пароль. Превышено число попыток.[/red]")
return False
def sudo(cmd: Sequence[str]) -> List[str]:
"""Prefix a command with ``sudo -n`` (non-interactive; token already cached).
Префиксует команду ``sudo -n`` (неинтерактивно; токен уже закеширован).
"""
return ["sudo", "-n", *cmd]
def stop_keepalive() -> None:
"""Stop the keep-alive thread. Safe to call even if it was never started.
Останавливает поток keep-alive. Безопасно вызывать, даже если он не запускался.
"""
_keepalive_stop.set()
+332
View File
@@ -0,0 +1,332 @@
from __future__ import annotations
import atexit
import os
import signal
import subprocess
import threading
from typing import Callable, Dict, List, Optional, Sequence
from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn
from cobot.ui import console, done, header
# Type of an optional callback invoked for every streamed output line.
# Тип опционального колбэка, вызываемого для каждой строки потокового вывода.
LineHook = Callable[[str], None]
# Registry of all live subprocesses, so the signal handler can kill them on exit.
# Maps pid -> Popen. Guarded by a lock because procs start/finish in helper calls.
# Реестр всех живых подпроцессов, чтобы обработчик сигнала мог убить их при выходе.
# Сопоставляет pid -> Popen. Защищён блокировкой, т.к. процессы создаются/завершаются в хелперах.
_procs: Dict[int, subprocess.Popen] = {}
_procs_lock = threading.Lock()
_handlers_installed = False
def _register(proc: subprocess.Popen) -> None:
with _procs_lock:
_procs[proc.pid] = proc
def _unregister(proc: subprocess.Popen) -> None:
with _procs_lock:
_procs.pop(proc.pid, None)
def _kill_proc(proc: subprocess.Popen) -> None:
"""Terminate a process and everything it spawned.
Three strategies, in order of how the process was started:
* a custom kill_fn (e.g. ``docker kill <container>``) registered on the proc;
* a new-session process (e.g. ros2 launch) — every node shares the session, so
``pkill -s <sid>`` reaches all of them (killpg would only hit the launcher);
* otherwise the process group (SIGTERM then SIGKILL), or the bare process.
Завершает процесс и всё, что он породил. Три стратегии по способу запуска:
пользовательский kill_fn (например ``docker kill``); процесс в новой сессии
(ros2 launch — все узлы делят сессию, поэтому ``pkill -s`` достаёт каждый);
иначе группа процессов (SIGTERM→SIGKILL) или сам процесс.
"""
if proc.poll() is not None:
return
kill_fn = getattr(proc, "_cobot_kill_fn", None)
if kill_fn is not None:
try:
kill_fn()
try:
proc.wait(timeout=5)
return
except subprocess.TimeoutExpired:
pass
except Exception:
pass
if getattr(proc, "_cobot_new_session", False):
try:
sid = os.getsid(proc.pid)
subprocess.run(["pkill", "-TERM", "-s", str(sid)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
proc.wait(timeout=3)
return
except subprocess.TimeoutExpired:
subprocess.run(["pkill", "-KILL", "-s", str(sid)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return
except Exception:
pass
try:
pgid = os.getpgid(proc.pid)
os.killpg(pgid, signal.SIGTERM)
try:
proc.wait(timeout=3)
except subprocess.TimeoutExpired:
os.killpg(pgid, signal.SIGKILL)
except Exception:
try:
proc.terminate()
except Exception:
pass
def kill_all() -> None:
"""Kill every registered subprocess. Used by the signal handler and atexit.
Убивает каждый зарегистрированный подпроцесс. Используется обработчиком сигнала и atexit.
"""
with _procs_lock:
procs = list(_procs.values())
for proc in procs:
_kill_proc(proc)
def _on_sigint(signum, frame): # noqa: ANN001
"""SIGINT handler: stop all children, print a cancel note, and exit non-zero.
Обработчик SIGINT: останавливает всех потомков, печатает заметку об отмене и выходит с ненулём.
"""
kill_all()
console.print("\n[yellow]Прервано пользователем (Ctrl-C).[/yellow]")
raise SystemExit(130)
def install_signal_handlers() -> None:
"""Install the SIGINT handler and atexit cleanup exactly once.
Устанавливает обработчик SIGINT и очистку atexit ровно один раз.
"""
global _handlers_installed
if _handlers_installed:
return
_handlers_installed = True
signal.signal(signal.SIGINT, _on_sigint)
atexit.register(kill_all)
def spawn(
cmd: Sequence[str],
*,
env: Optional[dict] = None,
cwd: Optional[str] = None,
new_session: bool = False,
shell: bool = False,
kill_fn: Optional[Callable] = None,
) -> subprocess.Popen:
"""Start a subprocess with merged stdout/stderr as text, register it, and return it.
new_session=True puts the process in its own session/process-group so the whole
tree (e.g. all ros2 launch nodes) can be torn down with one signal. kill_fn is an
optional custom teardown (e.g. ``docker kill``) used by the cleanup logic.
Запускает подпроцесс с объединённым stdout/stderr в текстовом режиме, регистрирует
его и возвращает. new_session=True помещает процесс в собственную сессию/группу.
kill_fn — опциональная функция завершения (например ``docker kill``) для очистки.
"""
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
env=env,
cwd=cwd,
start_new_session=new_session,
shell=shell,
)
proc._cobot_new_session = new_session # type: ignore[attr-defined]
proc._cobot_kill_fn = kill_fn # type: ignore[attr-defined]
_register(proc)
return proc
def stream(
cmd: Sequence[str],
*,
env: Optional[dict] = None,
cwd: Optional[str] = None,
on_line: Optional[LineHook] = None,
new_session: bool = False,
shell: bool = False,
echo: bool = True,
kill_fn: Optional[Callable] = None,
) -> int:
"""Run a command and stream every output line to the console (and on_line hook).
Returns the process exit code. SIGKILL (-9) / SIGTERM (-15) are returned as-is so
callers can treat user cancellation differently from real failures.
Запускает команду и транслирует каждую строку вывода в консоль (и в колбэк on_line).
Возвращает код возврата процесса. SIGKILL (-9) / SIGTERM (-15) возвращаются как есть,
чтобы вызывающий код мог отличать отмену пользователем от реальных ошибок.
"""
proc = spawn(cmd, env=env, cwd=cwd, new_session=new_session, shell=shell, kill_fn=kill_fn)
try:
for line in proc.stdout:
s = line.rstrip()
if on_line is not None:
on_line(s)
elif echo and s:
console.print(f" [dim]{_escape(s)}[/dim]")
proc.wait()
finally:
_unregister(proc)
return proc.returncode
def _escape(s: str) -> str:
"""Escape Rich markup so raw command output is never interpreted as markup.
Экранирует разметку Rich, чтобы сырой вывод команды не интерпретировался как разметка.
"""
return s.replace("[", "\\[")
# A progress bar that sticks to the bottom while log lines scroll above it.
# Прогресс-бар, "прилипающий" к низу, пока строки лога прокручиваются над ним.
def make_progress() -> Progress:
"""Create a Progress with a spinner, bar, percentage, and description column.
Создаёт Progress со спиннером, баром, процентами и колонкой описания.
"""
return Progress(
SpinnerColumn(),
BarColumn(bar_width=30),
TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
TextColumn("[dim]{task.description}[/dim]"),
console=console,
transient=True,
)
def run_step(
title: str,
cmd: Sequence[str],
*,
env: Optional[dict] = None,
cwd: Optional[str] = None,
new_session: bool = False,
shell: bool = False,
show_progress: bool = True,
total: float = 100.0,
parse_progress: Optional[Callable[[str], Optional[tuple]]] = None,
on_line: Optional[LineHook] = None,
success_msg: str = "",
fail_msg: str = "",
finish: bool = True,
) -> int:
"""Run one command as a self-contained "block": header, live log + progress, status.
parse_progress(line) may return (pct, label) to advance the bar, or None to ignore.
Returns the exit code. Prints a ✓/✗ line unless finish=False (used when chaining
several commands under one header).
Запускает одну команду как самодостаточный "блок": заголовок, живой лог + прогресс,
статус. parse_progress(line) может вернуть (pct, label) для продвижения бара или None.
Возвращает код возврата. Печатает строку ✓/✗, если finish=True (иначе — при цепочке
нескольких команд под одним заголовком).
"""
if title:
header(title)
if not show_progress:
rc = stream(cmd, env=env, cwd=cwd, on_line=on_line,
new_session=new_session, shell=shell)
else:
progress = make_progress()
with progress:
task = progress.add_task("", total=total)
def _line(s: str) -> None:
if parse_progress is not None:
parsed = parse_progress(s)
if parsed is not None:
pct, label = parsed
progress.update(task, completed=pct,
description=label or "")
if on_line is not None:
on_line(s)
elif s:
progress.console.print(f" [dim]{_escape(s)}[/dim]")
rc = stream(cmd, env=env, cwd=cwd, on_line=_line,
new_session=new_session, shell=shell)
progress.update(task, completed=total)
ok = rc in (0, -9, -15)
if finish:
if ok:
done(True, success_msg or "Готово")
else:
done(False, fail_msg or f"Команда завершилась с кодом {rc}")
return rc
# A live progress context for tasks that run several commands or Python work and
# need to drive the bar manually. Yields a small controller with .log()/.set().
# Живой контекст прогресса для задач, выполняющих несколько команд или Python-работу
# и управляющих баром вручную. Отдаёт небольшой контроллер с .log()/.set().
class StepProgress:
"""Manual progress controller used as a context manager.
Usage:
with StepProgress("Building") as p:
p.set(10, "step one")
p.log("some output")
Ручной контроллер прогресса, используемый как менеджер контекста.
"""
def __init__(self, title: str, total: float = 100.0, show: bool = True):
if title:
header(title)
self._total = total
self._show = show
self._progress: Optional[Progress] = None
self._task = None
def __enter__(self) -> "StepProgress":
if self._show:
self._progress = make_progress()
self._progress.__enter__()
self._task = self._progress.add_task("", total=self._total)
return self
def set(self, pct: float, label: str = "") -> None:
if self._progress is not None:
self._progress.update(self._task, completed=pct, description=label or "")
def log(self, line: str, style: str = "dim") -> None:
out = self._progress.console if self._progress is not None else console
if line == "":
out.print()
else:
out.print(f" [{style}]{_escape(line)}[/{style}]" if style else f" {line}")
def raw(self, renderable) -> None:
"""Print a pre-built Rich renderable/markup string without escaping.
Печатает готовый Rich-объект/строку с разметкой без экранирования.
"""
out = self._progress.console if self._progress is not None else console
out.print(renderable)
def __exit__(self, exc_type, exc, tb) -> None:
if self._progress is not None:
self._progress.__exit__(exc_type, exc, tb)
self._progress = None
+71
View File
@@ -0,0 +1,71 @@
"""Update recovery checks; external git and installer operations are isolated."""
import io
import unittest
from unittest.mock import patch
from rich.console import Console
from cobot.commands import update
class UpdateTests(unittest.TestCase):
def run_update(self, codes, behind="1"):
output = io.StringIO()
commands = []
def stream(command, **kwargs):
commands.append(command)
result = next(codes, 0)
if isinstance(result, Exception):
raise result
return result
def git(*args):
return {"rev-parse": "controller", "rev-list": behind,
"log": "abc123 Update CLI"}[args[0]]
console = Console(file=output, color_system=None)
with patch.object(update, "_git", side_effect=git), \
patch.object(update.process, "stream", side_effect=stream), \
patch.object(update, "_plain"), \
patch("cobot.process.console", console), \
patch("cobot.ui.console", console):
code = update._update()
return code, output.getvalue(), commands
def test_install_failure_reports_failure(self):
for install_code in (1, -9, -15):
with self.subTest(install_code=install_code):
code, output, _ = self.run_update(iter([0, 0, install_code]))
self.assertEqual(code, 1)
self.assertNotIn("Проект обновлён", output)
def test_current_checkout_still_retries_installation(self):
code, _, commands = self.run_update(iter([0, 0]), behind="0")
self.assertEqual([command[:2] for command in commands],
[["git", "fetch"], ["uv", "tool"]])
self.assertEqual(code, 0)
def test_killed_git_stops_before_next_step(self):
for codes, expected_count in [([-9], 1), ([0, -15], 2)]:
with self.subTest(codes=codes):
code, output, commands = self.run_update(iter(codes))
self.assertNotEqual(code, 0)
self.assertEqual(len(commands), expected_count)
self.assertNotIn("Проект обновлён", output)
def test_missing_installer_reports_failure_without_traceback(self):
code, _, _ = self.run_update(
iter([0, 0, FileNotFoundError("uv not found")]))
self.assertNotEqual(code, 0)
def test_command_exits_nonzero_after_failed_installation(self):
with patch.object(update, "_update", return_value=1):
with self.assertRaises(SystemExit) as result:
update.run(None)
self.assertEqual(result.exception.code, 1)
if __name__ == "__main__":
unittest.main()
+358
View File
@@ -0,0 +1,358 @@
from __future__ import annotations
import os
import select as _select
import sys
from typing import List, Optional, Sequence, Tuple
from rich.console import Console, Group
from rich.live import Live
from rich.panel import Panel
from rich.text import Text
# Raw terminal control is POSIX-only; the project targets Linux/ROS so this is fine.
# Сырой режим терминала только для POSIX; проект под Linux/ROS, так что всё в порядке.
try:
import termios
import tty
_HAS_TERMIOS = True
except ImportError: # pragma: no cover - Windows fallback
_HAS_TERMIOS = False
# Single shared console used everywhere so styling and width stay consistent.
# Единый общий console, используемый везде, чтобы стиль и ширина были согласованы.
console = Console(highlight=False)
# Glyphs used across the UI. Kept here so the whole look can be retuned in one place.
# Глифы, используемые в интерфейсе. Собраны здесь, чтобы весь вид настраивался в одном месте.
_CURSOR = "❯"
_OK = "✓"
_FAIL = "✗"
_CHECK_ON = "◼"
_CHECK_OFF = "◻"
def is_interactive() -> bool:
"""Return True if both stdin and stdout are real terminals.
Arrow-key selection needs a real TTY to read raw key presses. When that is
not available (piped input, CI) callers should fall back to defaults.
Возвращает True, если и stdin, и stdout являются настоящими терминалами.
Выбор стрелками требует реального TTY для чтения нажатий клавиш. Если его нет
(перенаправленный ввод, CI), вызывающий код должен использовать значения по умолчанию.
"""
try:
return sys.stdin.isatty() and sys.stdout.isatty()
except Exception:
return False
# Low-level key reader
# Низкоуровневое чтение клавиш
# How long to wait (seconds) after a lone ESC byte before deciding it is really the
# Escape key and not the start of an arrow escape sequence (\x1b[A etc.).
# Сколько ждать (секунд) после одиночного байта ESC, прежде чем решить, что это
# именно клавиша Escape, а не начало escape-последовательности стрелок (\x1b[A и т.п.).
_ESC_TIMEOUT = 0.05
def _read_key() -> Tuple[str, str]:
"""Read one key press in raw mode and classify it.
Returns a (kind, char) tuple where kind is one of: "up", "down", "enter", "esc",
"space", "backspace", "char", "interrupt", "other". This is used instead of
readchar because readchar blocks after a lone ESC (waiting to see whether it is an
arrow sequence); here a short select() timeout distinguishes a real Escape press.
UTF-8 multibyte input (e.g. Cyrillic in a password) is decoded fully.
Читает одно нажатие в сыром режиме и классифицирует его. Возвращает кортеж
(kind, char). Используется вместо readchar, потому что readchar зависает после
одиночного ESC (ожидая, не последовательность ли это стрелок); здесь короткий
таймаут select() отличает настоящий Escape. UTF-8 (например кириллица в пароле)
декодируется полностью.
"""
if not _HAS_TERMIOS: # pragma: no cover
ch = sys.stdin.read(1)
return ("char", ch)
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
b = os.read(fd, 1)
if not b:
return ("other", "")
c = b[0]
if c == 0x1B: # ESC — could be a lone Escape or an arrow/escape sequence
ready, _, _ = _select.select([fd], [], [], _ESC_TIMEOUT)
if not ready:
return ("esc", "")
seq = os.read(fd, 3)
last = seq[-1:] if seq else b""
if last == b"A":
return ("up", "")
if last == b"B":
return ("down", "")
if last in (b"C", b"D"):
return ("other", "")
return ("esc", "")
if c in (0x0D, 0x0A): # Enter
return ("enter", "")
if c == 0x03: # Ctrl-C (raw mode swallows SIGINT)
return ("interrupt", "")
if c == 0x20: # Space
return ("space", " ")
if c in (0x7F, 0x08): # Backspace / Delete
return ("backspace", "")
if c < 0x20: # other control char — ignore
return ("other", "")
# Printable byte — read any UTF-8 continuation bytes so multibyte chars decode.
# Печатный байт — дочитываем продолжения UTF-8, чтобы многобайтовые символы декодировались.
extra = 0
if c >= 0xF0:
extra = 3
elif c >= 0xE0:
extra = 2
elif c >= 0xC0:
extra = 1
if extra:
b += os.read(fd, extra)
return ("char", b.decode("utf-8", errors="ignore"))
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
# Block headers and footers
# Заголовки и завершения блоков
def header(title: str, subtitle: str = "") -> None:
"""Print a styled header block that marks the start of a task or wizard step.
Печатает стилизованный блок-заголовок, обозначающий начало задачи или шага мастера.
"""
console.print()
bar = Text("▌ ", style="bold cyan")
bar.append(title, style="bold")
if subtitle:
bar.append(f" {subtitle}", style="dim")
console.print(bar)
def done(success: bool, message: str = "") -> None:
"""Print the final status line of a task (green ✓ on success, red ✗ on failure).
Печатает финальную строку статуса задачи (зелёная ✓ при успехе, красная ✗ при ошибке).
"""
if success:
line = Text(f"{_OK} ", style="bold green")
line.append(message or "Done", style="green")
else:
line = Text(f"{_FAIL} ", style="bold red")
line.append(message or "Failed", style="red")
console.print(line)
def note(message: str) -> None:
"""Print a dim helper/info line.
Печатает приглушённую вспомогательную/информационную строку.
"""
console.print(Text(f" {message}", style="dim"))
def info(message: str) -> None:
"""Print a plain message through the shared console (Rich markup allowed).
Печатает обычное сообщение через общий console (разрешена разметка Rich).
"""
console.print(message)
def error(message: str) -> None:
"""Print an error line.
Печатает строку ошибки.
"""
console.print(f"[bold red]Error:[/bold red] {message}")
# A collapsed answer line, printed after an interactive block is resolved.
# Свёрнутая строка-ответ, печатается после разрешения интерактивного блока.
def _print_answer(question: str, answer: str) -> None:
line = Text(f"{_OK} ", style="bold green")
line.append(f"{question} ", style="dim")
line.append("· ", style="dim")
line.append(answer, style="bold")
console.print(line)
def _print_cancelled(question: str) -> None:
line = Text(f"{_FAIL} ", style="bold red")
line.append(f"{question} ", style="dim")
line.append("· cancelled", style="red")
console.print(line)
def _render_choices(question: str, options: Sequence[str], cursor: int,
note_text: str = "") -> Panel:
"""Build the renderable shown while the user is navigating a single-choice list.
Строит отрисовываемый объект, показываемый пока пользователь навигирует по списку выбора.
"""
rows: List[Text] = []
for i, opt in enumerate(options):
if i == cursor:
row = Text(f" {_CURSOR} ", style="bold cyan")
row.append(opt, style="bold")
else:
row = Text(f" {opt}", style="dim")
rows.append(row)
body = Group(*rows)
title = Text(question, style="bold")
sub = "↑/↓ — выбор · Enter — подтвердить · Esc — отмена"
if note_text:
sub = f"{note_text}\n{sub}"
return Panel(body, title=title, title_align="left", subtitle=Text(sub, style="dim"),
subtitle_align="left", border_style="cyan", padding=(0, 1))
def select(question: str, options: Sequence[str], default: Optional[str] = None,
note: str = "") -> Optional[str]:
"""Show an arrow-key single-choice block and return the chosen option string.
Returns None if the user pressed Escape / Ctrl-C. When the terminal is not
interactive the default (or first option) is returned without prompting.
Показывает блок выбора одного варианта со стрелками и возвращает выбранную строку.
Возвращает None, если пользователь нажал Escape / Ctrl-C. Если терминал не
интерактивный, возвращается значение по умолчанию (или первый вариант) без запроса.
"""
options = list(options)
if not options:
return None
cursor = options.index(default) if default in options else 0
if not is_interactive():
chosen = options[cursor]
_print_answer(question, chosen)
return chosen
with Live(_render_choices(question, options, cursor, note), console=console,
auto_refresh=False, transient=True) as live:
while True:
live.update(_render_choices(question, options, cursor, note), refresh=True)
kind, ch = _read_key()
if kind == "up" or (kind == "char" and ch == "k"):
cursor = (cursor - 1) % len(options)
elif kind == "down" or (kind == "char" and ch == "j"):
cursor = (cursor + 1) % len(options)
elif kind == "enter":
break
elif kind in ("esc", "interrupt"):
_print_cancelled(question)
return None
chosen = options[cursor]
_print_answer(question, chosen)
return chosen
def _render_multi(question: str, options: Sequence[str], cursor: int,
selected: set, note_text: str = "") -> Panel:
"""Build the renderable for a multi-choice checkbox list.
Строит отрисовываемый объект для списка множественного выбора с чекбоксами.
"""
rows: List[Text] = []
for i, opt in enumerate(options):
box = _CHECK_ON if i in selected else _CHECK_OFF
if i == cursor:
row = Text(f" {_CURSOR} {box} ", style="bold cyan")
row.append(opt, style="bold")
else:
row = Text(f" {box} ", style="green" if i in selected else "dim")
row.append(opt, style="" if i in selected else "dim")
rows.append(row)
body = Group(*rows)
title = Text(question, style="bold")
sub = "↑/↓ — навигация · Space — отметить · Enter — подтвердить · Esc — отмена"
if note_text:
sub = f"{note_text}\n{sub}"
return Panel(body, title=title, title_align="left", subtitle=Text(sub, style="dim"),
subtitle_align="left", border_style="cyan", padding=(0, 1))
def multiselect(question: str, options: Sequence[str],
defaults: Optional[Sequence[str]] = None,
note: str = "") -> Optional[List[str]]:
"""Show an arrow-key multi-choice block. Space toggles, Enter confirms.
Returns the list of selected option strings, or None if cancelled.
Показывает блок множественного выбора со стрелками. Space переключает, Enter подтверждает.
Возвращает список выбранных строк или None при отмене.
"""
options = list(options)
if not options:
return []
if defaults is None:
selected = set(range(len(options)))
else:
selected = {i for i, o in enumerate(options) if o in defaults}
cursor = 0
if not is_interactive():
chosen = [options[i] for i in sorted(selected)]
_print_answer(question, ", ".join(chosen) or "—")
return chosen
with Live(_render_multi(question, options, cursor, selected, note), console=console,
auto_refresh=False, transient=True) as live:
while True:
live.update(_render_multi(question, options, cursor, selected, note), refresh=True)
kind, ch = _read_key()
if kind == "up" or (kind == "char" and ch == "k"):
cursor = (cursor - 1) % len(options)
elif kind == "down" or (kind == "char" and ch == "j"):
cursor = (cursor + 1) % len(options)
elif kind == "space":
selected.symmetric_difference_update({cursor})
elif kind == "enter":
break
elif kind in ("esc", "interrupt"):
_print_cancelled(question)
return None
chosen = [options[i] for i in sorted(selected)]
_print_answer(question, ", ".join(chosen) or "—")
return chosen
def text(question: str, default: str = "", note: str = "") -> Optional[str]:
"""Prompt for a single line of free text, pre-filled with default.
Returns the entered value (or default if left empty), or None on Ctrl-C / EOF.
Запрашивает одну строку произвольного текста, предзаполненную значением по умолчанию.
Возвращает введённое значение (или default, если пусто), либо None при Ctrl-C / EOF.
"""
prompt = Text()
prompt.append(f"{_CURSOR} ", style="bold cyan")
prompt.append(question, style="bold")
if default:
prompt.append(f" [{default}]", style="dim")
console.print(prompt)
if note:
console.print(Text(f" {note}", style="dim"))
try:
raw = input(" > ").strip()
except (EOFError, KeyboardInterrupt):
console.print()
_print_cancelled(question)
return None
value = raw or default
return value
def confirm(question: str, default: bool = True) -> bool:
"""Yes/No selection block. Returns True for yes, False for no or cancel.
Блок выбора Да/Нет. Возвращает True для да, False для нет или отмены.
"""
yes, no = "Да", "Нет"
choice = select(question, [yes, no], default=yes if default else no)
return choice == yes
+11
View File
@@ -0,0 +1,11 @@
build:
base-paths:
- src
list:
base-paths:
- src
test:
base-paths:
- src
+16
View File
@@ -0,0 +1,16 @@
FROM squidfunk/mkdocs-material
RUN apk add --no-cache \
cairo \
pango \
gdk-pixbuf \
libffi \
fontconfig \
ttf-dejavu \
gcc \
g++ \
musl-dev \
python3-dev \
&& pip install \
mkdocs-static-i18n==1.3.1 \
mkdocs-to-pdf \
&& apk del --no-cache gcc g++ musl-dev python3-dev
+16
View File
@@ -0,0 +1,16 @@
/* Центрирование изображений */
.md-content img {
display: block;
margin: 1em auto;
}
/* Центрирование таблиц */
.md-typeset table {
display: table;
margin: 1em auto;
}
/* Скрываем встроенную кнопку PDF от плагина to-pdf */
a.md-header-nav__button.md-icon[href$=".pdf"] {
display: none !important;
}
+32
View File
@@ -0,0 +1,32 @@
document.addEventListener("DOMContentLoaded", function () {
const siteRoot = document.querySelector('meta[name="site-root"]')?.content ?? "";
const isEnglish = document.documentElement.lang.toLowerCase().startsWith("en");
const btn = document.createElement("a");
btn.href = siteRoot + "/pdf/documentation.pdf";
btn.download = "lwc-documentation.pdf";
btn.title = isEnglish
? "Download all documentation as PDF"
: "Скачать всю документацию в PDF";
btn.style.cssText = [
"position: fixed",
"bottom: 80px",
"right: 24px",
"z-index: 9999",
"background: var(--md-primary-fg-color, #1976d2)",
"color: #fff",
"padding: 12px 18px",
"border-radius: 24px",
"text-decoration: none",
"font-weight: 600",
"font-size: 14px",
"box-shadow: 0 3px 10px rgba(0,0,0,0.25)",
"display: flex",
"align-items: center",
"gap: 8px",
"transition: opacity .2s",
].join(";");
btn.innerHTML = isEnglish ? "&#128196; Download PDF" : "&#128196; Скачать PDF";
btn.onmouseenter = () => (btn.style.opacity = "0.85");
btn.onmouseleave = () => (btn.style.opacity = "1");
document.body.appendChild(btn);
});
@@ -0,0 +1,169 @@
# cobot CLI commands
`cobot` is the single entry point for managing the entire project. Use it for operations involving the robot, simulator, Docker containers, and documentation.
## Help
```bash
cobot -h
```
The help output is divided into four command groups:
- **Setup commands** — system configuration;
- **Run commands** — starting the project;
- **Build commands** — building ROS 2;
- **Management commands** — package management.
Some commands have their own subcommands. For example:
```bash
cobot doc-setup rebuild # rebuild subcommand of doc-setup
cobot doc-setup --help # help for a command's subcommands
```
---
## Setup commands
Commands for initial and repeated system setup.
### `cobot setup`
First-run setup wizard. It guides you through three steps:
1. Configure the documentation server.
2. Configure robot parameters in `cobot-setting.yaml`: IP address, FRI port, and tool.
3. Select a build environment: native ROS 2 Jazzy or a Docker image.
```bash
cobot setup
```
Use this command for the first installation instead of running each setup command manually.
---
### `cobot local-setup`
Installs ROS 2 Jazzy locally without Docker: downloads dependencies with `rosdep` and builds the workspace with `colcon`.
```bash
cobot local-setup
```
!!! note
After the command finishes, run `source ~/.bashrc` or open a new terminal.
---
### `cobot docker-setup`
Builds or downloads the Docker images used to run the project in isolation. Two options are available:
- **Build from the Dockerfile** — slower, but produces an up-to-date image;
- **Download a prebuilt image** — faster, using a published image.
```bash
cobot docker-setup
```
---
### `cobot doc-setup`
Deploys a local MkDocs documentation server containing a full copy of the [online documentation](https://daniel-robotics.gitverse.site/lightweight-cobot/).
```bash
cobot doc-setup # start/build the documentation
cobot doc-setup rebuild # rebuild the documentation image
```
After startup, the documentation is available at `http://localhost:8000`.
---
### `cobot robot-setup`
Interactive wizard for configuring `cobot-setting.yaml`. It asks for the robot IP address, FRI port, active tool, and other parameters.
```bash
cobot robot-setup
```
!!! tip
Use this command to change the configuration. It validates the entered values and prevents YAML syntax errors. See [System configuration](configuration.md) for parameter details.
---
## Run commands
### `cobot run`
Starts the full stack: hardware interface, MoveIt 2, RViz, and optional components such as Foxglove and the REST API. At startup, it asks you to select:
- **Docker or local execution**;
- **Webots simulation or the physical robot**.
```bash
cobot run # select the mode interactively
cobot run --simulate # force simulation mode
```
---
## Build commands
### `cobot rebuild`
Rebuilds the ROS 2 workspace with `colcon`. Use it after changing package source code.
```bash
cobot rebuild
```
!!! note
This command is available only for a local installation, not Docker. It is equivalent to `colcon build --mixin release`.
---
### `cobot clean`
Removes generated build directories. It prompts you to select which directories to remove:
- `build/` — compilation artifacts;
- `install/` — installed package files;
- `log/` — build logs.
```bash
cobot clean
```
---
## Management commands
### `cobot update`
Downloads the latest project version from GitVerse and reinstalls the `cobot` CLI.
```bash
cobot update
```
---
### `cobot delete`
Removes project components from the system. It lets you remove only the project, the Docker images and containers, or ROS 2 as well.
```bash
cobot delete
```
!!! danger
This operation is irreversible. Removed files and Docker images must be installed again.
---
**Robot control:** [Control via the REST API](control/rest-api.md)
@@ -0,0 +1,169 @@
# CLI-команды cobot
`cobot` — единая точка входа для управления всем проектом. Все операции с роботом, симулятором, Docker-контейнерами и документацией выполняются через эту команду.
## Справка
```bash
cobot -h
```
Вывод справки разделён на 4 группы команд:
- **Setup commands** — настройка системы
- **Run commands** — запуск проекта
- **Build commands** — сборка ROS 2
- **Management commands** — управление пакетом
Некоторые команды имеют собственные подкоманды. Пример:
```bash
cobot doc-setup rebuild # подкоманда rebuild для doc-setup
cobot doc-setup --help # справка по подкомандам конкретной команды
```
---
## Setup commands
Команды первичной и повторной настройки системы.
### `cobot setup`
Мастер-команда первого запуска. Проводит через три шага:
1. Настройка сервера документации
2. Параметры робота (`cobot-setting.yaml`) — IP, порт FRI, инструмент
3. Выбор среды сборки: ROS2 Jazzy нативно или Docker-образ
```bash
cobot setup
```
Используйте эту команду при первой установке вместо ручного запуска каждой setup-команды.
---
### `cobot local-setup`
Локальная установка ROS 2 Jazzy без Docker: скачивает зависимости через `rosdep`, собирает workspace через `colcon`.
```bash
cobot local-setup
```
!!! note
После выполнения обязательно выполните `source ~/.bashrc` или откройте новый терминал.
---
### `cobot docker-setup`
Сборка или скачивание готовых Docker-образов для запуска проекта в изоляции. Доступны два варианта:
- **Сборка из Dockerfile** — дольше, но даёт актуальную версию
- **Скачивание готового образа** — быстрее, использует pre-built образ
```bash
cobot docker-setup
```
---
### `cobot doc-setup`
Разворачивает локальный MkDocs-сервер документации — полную копию [онлайн-документации](https://daniel-robotics.gitverse.site/lightweight-cobot/).
```bash
cobot doc-setup # запустить / собрать документацию
cobot doc-setup rebuild # пересобрать документацию
```
После запуска документация будет доступна по адресу `http://localhost:8000`.
---
### `cobot robot-setup`
Интерактивный мастер настройки файла `cobot-setting.yaml`. Запрашивает IP-адрес робота, порт FRI, активный инструмент и другие параметры.
```bash
cobot robot-setup
```
!!! tip
Используйте именно эту команду для изменения конфигурации — она валидирует введённые значения и исключает синтаксические ошибки. Подробнее о параметрах — в разделе [Конфигурация системы](configuration.md).
---
## Run commands
### `cobot run`
Запускает весь стек: hardware interface, MoveIt 2, RViz и опциональные компоненты (Foxglove, REST API). При запуске предлагает выбор:
- **Docker или локально**
- **Симулятор (Webots) или реальный робот**
```bash
cobot run # интерактивный выбор режима
cobot run --simulate # принудительно запустить симулятор
```
---
## Build commands
### `cobot rebuild`
Пересборка ROS 2 workspace через `colcon`. Используется при изменении исходного кода пакетов.
```bash
cobot rebuild
```
!!! note
Работает только для локальной установки (не Docker). Эквивалент `colcon build --mixin release`.
---
### `cobot clean`
Удаляет сгенерированные папки сборки. Предлагает выбор, какие именно удалить:
- `build/` — артефакты компиляции
- `install/` — установленные файлы пакетов
- `log/` — логи сборки
```bash
cobot clean
```
---
## Management commands
### `cobot update`
Скачивает последнюю версию проекта с GitVerse и переустанавливает CLI `cobot`.
```bash
cobot update
```
---
### `cobot delete`
Удаляет компоненты проекта с системы. Предложит выбор: удалить только проект, Docker-образы и контейнеры, или также ROS 2.
```bash
cobot delete
```
!!! danger
Операция необратима. Удалённые файлы и Docker-образы потребуют повторной установки.
---
**Управление роботом:** [Управление через REST API](control/rest-api.md)
@@ -0,0 +1,15 @@
# System architecture
!!! info "Work in progress"
A detailed description of the system architecture is being prepared.
LWC is built as a set of interconnected ROS 2 packages. Key components:
- **iiwa_bringup** — launch files and the entry point for starting the system
- **iiwa_controller** — hardware interface connecting to the KUKA controller over FRI
- **iiwa_planning** — MoveIt 2-based motion planning
- **iiwa_web** — REST API and MCP server for external control
- **iiwa_description** — URDF robot description and Webots worlds
- **iiwa_config** — configuration files for MoveIt, controllers, and cameras
- **iiwa_utils** — helper Python utilities and configuration loading
- **iiwa_msgs** — custom ROS 2 message types (action and srv)
@@ -0,0 +1,15 @@
# Архитектура системы
!!! info "Раздел в разработке"
Подробное описание архитектуры системы готовится.
Система LWC построена как набор взаимосвязанных ROS 2 пакетов. Ключевые компоненты:
- **iiwa_bringup** — launch-файлы, точка входа для запуска всей системы
- **iiwa_controller** — hardware interface, реализует связь с контроллером KUKA по протоколу FRI
- **iiwa_planning** — планирование движений на базе MoveIt 2
- **iiwa_web** — REST API и MCP-сервер для внешнего управления
- **iiwa_description** — URDF-описание робота и миры Webots
- **iiwa_config** — все конфигурационные файлы (MoveIt, контроллеры, камеры)
- **iiwa_utils** — вспомогательные Python-утилиты, загрузка конфигов
- **iiwa_msgs** — кастомные ROS 2 типы сообщений (action, srv)
@@ -0,0 +1,23 @@
# FRI protocol
!!! info "Work in progress"
A detailed description of the FRI protocol is being prepared.
**FRI (Fast Robot Interface)** is a UDP protocol for low-level real-time control of a KUKA robot. It runs over Ethernet and provides a deterministic data exchange cycle between an external PC and the KUKA controller.
## Main characteristics
- **Transport:** UDP (no delivery guarantee, which is important for real-time operation)
- **Cycle period:** 5 ms (200 Hz) or 10 ms (100 Hz), configured in `cobot-setting.yaml` → `robot.fri_cycle_ms`
- **Control modes:** position, torque, and impedance
## Network requirements
!!! warning "Important: a 5 ms cycle requires KONI"
A **5 ms (200 Hz)** cycle requires the **KONI** port (KUKA Optional Network Interface).
The KLI port supports only a 10 ms cycle. Set `fri_cycle_ms: 10` when using KLI.
| Port | Minimum cycle | Purpose |
|---|---|---|
| **KONI** | 5 ms | High-frequency control, recommended for FRI |
| **KLI** | 10 ms | Standard control and programming |
@@ -0,0 +1,24 @@
# FRI-протокол
!!! info "Раздел в разработке"
Подробное описание FRI-протокола готовится.
**FRI (Fast Robot Interface)** — UDP-протокол низкоуровневого управления роботом KUKA в реальном времени. Работает поверх Ethernet и обеспечивает детерминированный цикл обмена данными между внешним ПК и контроллером KUKA.
## Основные характеристики
- **Транспорт:** UDP (без гарантии доставки — критично для RT)
- **Период цикла:** 5 мс (200 Гц) или 10 мс (100 Гц), задаётся в `cobot-setting.yaml` → `robot.fri_cycle_ms`
- **Режимы управления:** позиция, момент (крутящий момент), импеданс
## Требования к сетевому подключению
!!! warning "Важно: цикл 5 мс требует KONI"
Для работы с периодом цикла **5 мс (200 Гц)** необходимо подключение через порт **KONI**
(KUKA Optional Network Interface). Порт KLI поддерживает только 10 мс цикл.
При использовании KLI устанавливайте `fri_cycle_ms: 10`.
| Порт | Мин. цикл | Назначение |
|---|---|---|
| **KONI** | 5 мс | Высокочастотное управление, рекомендуется для FRI |
| **KLI** | 10 мс | Стандартное управление и программирование |
@@ -0,0 +1,23 @@
# Motion planning
!!! info "Work in progress"
A detailed description of motion planning is being prepared.
LWC uses **MoveIt 2**, the standard motion-planning framework for ROS 2.
## Key concepts
- **Planning group** (`iiwa_arm`) — the set of joints for which a plan is generated. Defined in SRDF.
- **Planner** — the trajectory-generation algorithm. Available planners:
- `ompl` — general-purpose probabilistic planner (default)
- `pilz_industrial_motion_planner` — deterministic PTP, LIN, and CIRC trajectories
- **TCP (Tool Center Point)** — the tool point for which the target pose is specified. Set in `cobot-setting.yaml` → `planning.pose_link`.
- **Reference frame** — the coordinate system for targets. Default: `base_link`.
## `cobot-setting.yaml` settings
| Parameter | Description |
|---|---|
| `planning.default_planner` | Default planner: `ompl` or `pilz_industrial_motion_planner` |
| `planning.planning_attempts` | Number of attempts after a planning failure |
| `planning.pose_link` | TCP link for Cartesian targets |
@@ -0,0 +1,23 @@
# Планирование движений
!!! info "Раздел в разработке"
Подробное описание планирования движений готовится.
LWC использует **MoveIt 2** — стандартный фреймворк планирования движений для ROS 2.
## Основные понятия
- **Группа планирования** (`iiwa_arm`) — набор суставов, для которых строится план. Задаётся в SRDF.
- **Планировщик** — алгоритм построения траектории. Доступны:
- `ompl` — универсальный вероятностный планировщик (по умолчанию)
- `pilz_industrial_motion_planner` — детерминированные траектории типа PTP, LIN, CIRC
- **TCP (Tool Center Point)** — точка инструмента, для которой задаётся целевая поза. Настраивается в `cobot-setting.yaml` → `planning.pose_link`
- **Система отсчёта** — координатная система целей. По умолчанию: `base_link`
## Настройки в `cobot-setting.yaml`
| Параметр | Описание |
|---|---|
| `planning.default_planner` | Планировщик по умолчанию: `ompl` или `pilz_industrial_motion_planner` |
| `planning.planning_attempts` | Число попыток при неудаче планирования |
| `planning.pose_link` | TCP-линк для декартовых целей |
@@ -0,0 +1,134 @@
# Simulation (Webots)
**Webots** is an open-source robot simulator. LWC uses it as a digital twin of the KUKA LBR IIWA 7, allowing control algorithms to be developed and debugged without a physical robot.
## Key features
- The simulator uses the same ROS 2 topics and interfaces as the real robot.
- The simulation world is set in `cobot-setting.yaml` → `digital_twin.webots.world`.
- Start it with `cobot run --simulate`.
## TCP gizmo
This simulation-only mode lets you specify the robot's target pose by dragging a marker at its tool center point (TCP) in the Webots window.
1. Enable `digital_twin.tcp_gizmo.enabled: true` in `cobot-setting.yaml` and launch with `cobot run --simulate`.
2. Wait until other robot motions finish. For an initial test, use the regular named-pose command to move to `work`.
3. Select the TCP marker in Webots. Drag a translation arrow or rotation handle with the left mouse button. The robot remains stationary while you edit the target.
4. Release the button to submit the target. One complete trajectory is sent to the controller, rather than a stream of actions during dragging.
5. Wait for completion before dragging again. If the target cannot be reached or the checked path collides, the marker returns to the actual TCP.
Regular coordinate, joint, and control-file commands remain available. They have priority over new gizmo gestures. An already started gizmo trajectory finishes before a waiting regular command proceeds, even when that wait exceeds two seconds.
### Tool attachment and speed
The marker follows the active tool's `tcp` frame. With `patron`, it is at the chuck's working end; with no tool, it is at the flange. Apply tool changes through `cobot robot-setup`, rebuild, and restart the simulation. New tool models must define `tcp` at their working point.
`max_linear_speed` (m/s) and `max_angular_speed` (rad/s) are upper bounds. Short moves include acceleration and braking, and joint limits may make motion slower. Joint interpolation reaches the requested TCP pose but does not guarantee a straight Cartesian path.
Set `digital_twin.tcp_gizmo.enabled: false` and restart to disable this mode. The [configuration reference](../configuration.md) describes all parameters. `command_timeout` checks the age of the submitted target; mouse release is detected directly and requires no waiting-time setting.
### When the marker returns or does not respond
- Wait for regular motions or a committed gizmo trajectory to finish before starting another drag.
- For a rejected target, read `TCP gizmo rejected target: ...` in the launch output. Try a smaller displacement from a reachable posture such as `work`.
- With missing or stale robot feedback, the gizmo cannot submit movement. Check that simulation is running and `/joint_states` updates.
## Differences from the real robot
- Motion still obeys configured joint and TCP limits; simulation does not reproduce all physical robot protections.
- Physics is approximate, including inertia, friction, and elasticity.
- FRI is not used; communication goes through the Webots ROS 2 driver.
## Spawning textured objects
Set `digital_twin.webots.objects` in `cobot-setting.yaml`:
```yaml
objects:
enabled: true
count: 5
models:
- path: pkg://iiwa_description/objects/hammer/hammer1.obj
rotation_deg: [0, 0, 0]
- path: pkg://iiwa_description/objects/hammer/hammer2.obj
rotation_deg: [0, 0, 0]
area:
x: [0.3, 0.7]
y: [-0.3, 0.3]
z: [0.1, 0.1]
```
Webots spawns exactly `count` instances once at startup, independently choosing
from `models` with replacement. This list specifies allowed models, not individual
quantities. An absent section, `enabled: false`, or `count: 0` disables spawning.
Paths support `pkg://`, absolute paths and paths relative to the settings file.
Currently only Wavefront OBJ is supported.
Bounds are in metres in the robot base frame. The spawner uses the same
`webots.transform` and `webots.rotation` (axis and angle in radians) as the robot:
`p_world = t_robot + R_robot * p_local`. They constrain initial spawn positions;
physics may move the objects afterwards. Moving the robot with the mouse after
startup does not relocate existing objects.
The spawn anchor is the bounding-box XY centre and bottom Z. Exported vertex
offsets are compensated without modifying the original files, UVs, scale
(1 unit = 1 metre); orientation is configured per model. Bounds constrain the anchor, not the entire
object. Random placements may overlap; choose a sufficiently large area.
`CadShape` loads OBJ materials through `mtllib` and textures through MTL. Preserve
relative asset paths: for example, `hammer1.mtl` references
`hammer1_basecolor.png`. The complete `objects` directory is installed with
`iiwa_description`. Missing models, materials or textures fail before the first
spawn request. Physics uses an approximate bounding Box and a mass of 0.5 kg,
not calibrated hammer inertia or grasp geometry. Objects are not automatically
added to the MoveIt Planning Scene.
The `object_spawner` node calls `/Ros2Supervisor/spawn_node_from_string`
(`webots_ros2_msgs/srv/SpawnNodeFromString`) once per object. A rejected request
aborts remaining work. Timeouts are not retried to avoid duplicates. The node
exits after success and only runs in simulation.
### Simulation smoke test
1. Build with `colcon build --base-paths src --packages-select iiwa_description iiwa_utils iiwa_bringup iiwa_config --symlink-install`.
2. Run `source install/setup.bash`, then `cobot run local`, selecting Webots.
3. Inspect the five nodes `spawned_object_0000` through `spawned_object_0004`, their
textures and the `All 5 objects spawned` log.
4. Change `transform` and `rotation`, restart and confirm the spawn area translates
and rotates with the robot base. Pause before objects fall to inspect initial positions.
5. Check `count: 0`, operation without cameras and rejection of missing models.
Reference: [Webots CadShape](https://cyberbotics.com/doc/reference/cadshape).
### Per-model rotation
Each `models` entry accepts `path` and `rotation_deg: [X, Y, Z]`.
Angles are fixed degrees: apply X, then Y, then Z about the robot base axes,
`R_model = Rz * Ry * Rx` and `R_world = R_robot * R_model`. For example:
```yaml
models:
- path: pkg://iiwa_description/objects/hammer/hammer1.obj
rotation_deg: [0, 0, 0]
- path: pkg://iiwa_description/objects/hammer/hammer2.obj
rotation_deg: [90, 0, 0]
- path: pkg://iiwa_description/objects/hammer/hammer3.obj
rotation_deg: [0, 0, 45]
```
The supplied OBJ hammers have their long axis along Z. `[0, 0, 0]` gives an
initial vertical orientation, `[90, 0, 0]` lays the hammer sideways and
`[0, 0, 45]` turns it around the vertical axis. Both configuration files now
explicitly set `[0, 0, 0]` for each model; adjust each independently.
Legacy path-only entries remain supported and imply zero rotation.
Both the visible model and its collision Box rotate. Height is recalculated:
`area.z` locates the bottom of the rotated collision bounds in the robot frame;
X/Y locate their centre. Model rotation does not rotate the spawn area.
Changes take effect on the next launch.
This sets the initial orientation, not a constraint. Gravity and contact can
still topple the hammer. Pause simulation at spawn to inspect it. Smoke-test
two models with different angles, check the Box stays above `area.z`, and check
that changing `webots.rotation` preserves each model's relative orientation.
@@ -0,0 +1,139 @@
# Симуляция (Webots)
**Webots** — симулятор роботов с открытым исходным кодом. В LWC используется как цифровой двойник робота KUKA LBR IIWA 7: позволяет разрабатывать и отлаживать алгоритмы управления без доступа к физическому роботу.
## Ключевые особенности
- Симулятор использует те же ROS 2 топики и интерфейсы, что и реальный робот
- Мир симуляции задаётся в `cobot-setting.yaml` → `digital_twin.webots.world`
- Для запуска: `cobot run --simulate`
## Перемещение за TCP
В этом режиме цифрового двойника целевая поза робота задаётся перетаскиванием маркера рабочей точки инструмента (TCP) прямо в окне Webots.
1. Включите `digital_twin.tcp_gizmo.enabled: true` в `cobot-setting.yaml` и запустите `cobot run --simulate`.
2. Дождитесь завершения других движений. Для первой проверки удобно перейти в именованную позицию `work` обычной командой.
3. Выберите маркер TCP в Webots. Удерживая левую кнопку мыши, тяните за стрелку перемещения или ручку вращения. Во время редактирования цели робот стоит.
4. Отпустите кнопку: контроллеру отправится одна полная траектория, а не поток action-целей при перетаскивании.
5. Дождитесь завершения движения перед следующим переносом. При недостижимой цели или столкновении на проверяемом пути маркер возвращается к фактическому TCP.
Обычные команды координат, joints и файлы управления остаются доступны и имеют приоритет перед новым перетаскиванием. Уже начатое движение гизмы завершается до выполнения ожидающей обычной команды, в том числе если ожидание длится больше двух секунд.
### Инструмент и скорость
Маркер следует за фреймом `tcp` активного инструмента: у `patron` это рабочий торец патрона, без инструмента — фланец. При смене инструмента примените выбор через `cobot robot-setup`, пересоберите проект и перезапустите симуляцию. В моделях новых инструментов задавайте `tcp` в рабочей точке.
`max_linear_speed` (м/с) и `max_angular_speed` (рад/с) задают верхние пределы. На коротких перемещениях есть разгон и торможение; ограничения суставов также могут снизить скорость. Интерполяция в суставах достигает заданной позы TCP, но не гарантирует прямолинейный декартов путь.
Для отключения задайте `digital_twin.tcp_gizmo.enabled: false` и перезапустите систему. Все параметры описаны в [справочнике конфигурации](../configuration.md). `command_timeout` проверяет возраст поступившей цели: отпускание мыши определяется напрямую, настройка времени ожидания не требуется.
### Если маркер возвращается или не реагирует
- Дождитесь завершения обычной команды или уже начатой траектории гизмы перед новым перетаскиванием.
- При отказе смотрите строку `TCP gizmo rejected target: ...` в выводе запуска. Попробуйте небольшое смещение из достижимой позы, например `work`.
- При отсутствии или устаревании обратной связи перемещение недоступно. Проверьте, что симуляция работает и `/joint_states` обновляется.
## Отличия от реального робота
- Действуют настроенные ограничения суставов и TCP; симуляция не воспроизводит все защиты физического робота
- Физика не идеальна — инерция, трение и упругость приближённые
- FRI-протокол не задействован — связь идёт через Webots-драйвер ROS 2
## Спавн объектов с текстурами
В `cobot-setting.yaml` (секция `digital_twin.webots`) задайте:
```yaml
objects:
enabled: true
count: 5
models:
- path: pkg://iiwa_description/objects/hammer/hammer1.obj
rotation_deg: [0, 0, 0]
- path: pkg://iiwa_description/objects/hammer/hammer2.obj
rotation_deg: [0, 0, 0]
area:
x: [0.3, 0.7]
y: [-0.3, 0.3]
z: [0.1, 0.1]
```
При запуске Webots создаётся ровно `count` объектов: каждая модель независимо
выбирается из `models`, повторения разрешены. `enabled: false`, `count: 0` или
отсутствие секции отключает спавн. Список — разрешённые модели, а не количество
экземпляров каждой модели. Пути могут быть `pkg://`, абсолютными или относительно
файла настроек. Пока поддерживается Wavefront OBJ.
Область задаётся в метрах в системе основания робота: применяется та же пара
`webots.transform` / `webots.rotation` (ось и угол в радианах), что и при спавне
робота. Формула: `p_world = t_robot + R_robot * p_local`. Это начальная область,
а не ограничитель движения: физика затем может перемещать объекты. Перемещение
робота мышью после запуска не переносит уже созданные предметы.
Точка спавна — центр габаритов по X/Y и нижняя точка по Z. Смещение вершин
в экспортированном OBJ компенсируется автоматически; исходные файлы, UV,
масштаб (1 единица = 1 метр) сохраняется; ориентация задаётся отдельно для каждой модели. Диапазон ограничивает
эту точку, а не весь габарит. Пересечения объектов при случайном размещении
не исключаются: выбирайте достаточно просторную область.
`CadShape` загружает материалы из `mtllib` и текстуры из MTL. Сохраняйте OBJ,
MTL и PNG в исходной структуре каталогов: например, `hammer1.mtl` ссылается на
`hammer1_basecolor.png`. Весь каталог `objects` устанавливается вместе с
`iiwa_description`. Отсутствующие модели, MTL и текстуры вызывают ошибку до
первого запроса спавна. Для физики используется упрощённый габаритный Box и
масса 0.5 кг; это не точная модель инерции или захвата молотка. В MoveIt Planning
Scene эти объекты автоматически не добавляются.
Нода `object_spawner` вызывает
`/Ros2Supervisor/spawn_node_from_string` (`webots_ros2_msgs/srv/SpawnNodeFromString`)
однократно для каждого предмета. Отказ сервиса прерывает оставшийся спавн;
тайм-аут не повторяется, чтобы не создавать дубликаты. Нода завершается после
успеха. На физическом роботе она не запускается.
### Проверка в симуляции
1. Пересоберите пакеты:
`colcon build --base-paths src --packages-select iiwa_description iiwa_utils iiwa_bringup iiwa_config --symlink-install`.
2. Выполните `source install/setup.bash`, затем `cobot run local` и выберите Webots.
3. Проверьте пять узлов `spawned_object_0000` … `spawned_object_0004` в дереве сцены,
текстуры молотков и сообщение `All 5 objects spawned`.
4. Измените `transform` и `rotation`, перезапустите: область должна переместиться
и повернуться вместе с основанием робота. Для проверки начальных координат
используйте паузу симулятора до падения объектов.
5. Проверьте `count: 0`, запуск без камер и ошибку при несуществующей модели.
Справочник: [Webots CadShape](https://cyberbotics.com/doc/reference/cadshape).
### Индивидуальный поворот модели
Каждая запись `models` может содержать `path` и `rotation_deg: [X, Y, Z]`.
Углы фиксированные, в градусах; сначала применяется поворот вокруг X, затем Y,
затем Z в системе основания робота: `R_model = Rz * Ry * Rx`,
`R_world = R_robot * R_model`. Например:
```yaml
models:
- path: pkg://iiwa_description/objects/hammer/hammer1.obj
rotation_deg: [0, 0, 0]
- path: pkg://iiwa_description/objects/hammer/hammer2.obj
rotation_deg: [90, 0, 0]
- path: pkg://iiwa_description/objects/hammer/hammer3.obj
rotation_deg: [0, 0, 45]
```
В предоставленных OBJ длинная ось молотка направлена по Z: `[0, 0, 0]`
задаёт вертикальную начальную ориентацию, `[90, 0, 0]` кладёт молоток набок,
а `[0, 0, 45]` поворачивает его вокруг вертикальной оси. В обоих конфигурационных
файлах для всех моделей явно указано `[0, 0, 0]`; изменяйте каждую независимо.
Записи только с путём остаются совместимыми и означают нулевой поворот.
Поворачиваются и видимая модель, и её коллизионный Box. После поворота
пересчитывается высота: `area.z` задаёт нижнюю точку повёрнутого коллизионного
габарита в системе робота, а X/Y — его центр. Поворот модели не поворачивает
саму область спавна. Изменения применяются при следующем запуске.
Это начальная ориентация, а не фиксация: после появления гравитация и контакты
могут опрокинуть молоток. Для проверки поставьте симуляцию на паузу при спавне.
Проверьте разные углы у двух моделей, отсутствие погружения Box ниже `area.z`
и сохранение локальных углов при изменении `webots.rotation`.
@@ -0,0 +1,248 @@
# System configuration
## Main configuration file
All system parameters are stored in a single file: **`cobot-setting.yaml`** in the project root. It is the single source of truth for the robot IP address, ports, configuration paths, planner settings, and web server settings.
!!! info "No manual configuration is needed before installation"
When you run `cobot setup`, the wizard offers to configure this file automatically in **step 2**. Return to this section when you want to change parameters after the initial installation.
!!! danger "Do not edit the file manually"
Use only `cobot robot-setup`. The interactive wizard validates values and prevents syntax errors. Editing the YAML manually may cause parsing errors and prevent the system from starting.
```bash
cobot robot-setup
```
---
## `robot` section — robot parameters
Controls the connection to the physical KUKA controller through FRI.
```yaml
robot:
name: "iiwa7"
ip: "192.170.10.2"
port: 30200
fri_cycle_ms: 10
description: pkg://iiwa_description/urdf/iiwa7.urdf.xacro
```
| Parameter | Description | Recommendation |
|---|---|---|
| `name` | Robot model | Do not change: `iiwa7` |
| `ip` | KUKA controller IP address | **Change** to the actual controller address |
| `port` | FRI UDP port | Default: `30200`; change only if the port conflicts |
| `fri_cycle_ms` | FRI cycle: `5` ms = 200 Hz, `10` ms = 100 Hz | Use `10` for stable operation or `5` for high-precision tasks |
| `joint_position_tau` | FRI command EMA time constant, s | `0.04`; `0` disables smoothing |
| `description` | Path to the robot URDF | Do not change |
Motion always uses JointTrajectoryController. The position command is smoothed before FRI transmission with `robot.joint_position_tau`; no velocity filter is applied.
---
## `digital_twin` section — simulator
Configures the Webots environment and RViz visualization.
```yaml
digital_twin:
tcp_gizmo:
enabled: true
publish_period: 0.032
command_timeout: 0.3
state_timeout: 0.5
max_linear_speed: 0.50
max_angular_speed: 0.4
webots:
world: pkg://iiwa_description/worlds/iiwa.wbt
transform: "-0.25 0 0.79"
rotation: "0 0 1 0"
controller_timer: "50"
cameras:
- pkg://iiwa_config/config/cameras/d455_top.yaml
rviz:
config: pkg://iiwa_config/config/rviz/rviz_moveit.rviz
```
| Parameter | Description |
|---|---|
| `webots.world` | Path to the simulator `.wbt` world |
| `webots.transform` | Robot base offset in the world `[x y z]`, in meters |
| `webots.rotation` | Base orientation `[x y z angle]`, in radians |
| `webots.cameras` | List of YAML configurations for connected cameras |
| `rviz.config` | Path to the RViz configuration |
### D455 cameras in Webots
The overhead camera (`config/cameras/d455_top.yaml`) and the `patron` tool camera
use **640×480 at 30 FPS** for RGB and depth. Nominal VGA depth horizontal FOV
is 75°; 87° applies to HD. RGB approximates a central 4:3 crop of a 1280×800
sensor with a 90° horizontal FOV, resulting in about 79.61°. Use the individual
camera's 640×480 calibration for an exact RGB FOV.
The selected simulation depth range is 0.4–6 m with 1 mm quantization.
These are not accuracy guarantees or the exact VGA minimum distance of a D455.
This ideal model omits random noise, stereo matching, the IR projector,
distortion and the physical RGB/depth offset. Webots derives vertical FOV from
horizontal FOV and aspect ratio; it cannot be set independently.
Matching an individual device requires its intrinsics and extrinsics.
The `iiwa_utils.webots_camera.WebotsCamera` plugin maintains an average 30 Hz
cadence in simulation time without accumulating timestep rounding errors.
With `basicTimeStep: 32`, frame intervals are 32 or 64 ms; uniform 33.33 ms
intervals are impossible on this grid. Wall-clock FPS depends on simulation
speed. The world's physics timestep does not need changing.
Existing image topic names are preserved:
| Camera | RGB (`bgra8`) | Depth (`32FC1`, metres) |
|---|---|---|
| Overhead | `/d455_top/image_raw/image_color` | `/d455_top/depth/image_raw/image` |
| Tool | `/camera/color/image_color` | `/camera/depth/image` |
Each stream also publishes `camera_info` with the virtual camera matrix and
matching timestamp. Depth offers `point_cloud` when subscribed: XYZ in metres
using optical axes (X right, Y down, Z forward), with NaN for missing points.
Frame IDs remain `d455_top_link` and `camera_optical_frame`;
the plugin neither broadcasts TF nor aligns depth to RGB.
Smoke test: start `cobot run local` → **Webots simulator**, subscribe to the four
image topics, check image dimensions, matching `CameraInfo` timestamps, and the
average rate from frame timestamps over 10 seconds of simulation time.
`ros2 topic hz /camera/depth/image` measures wall-clock delivery, so it can report
less than 30 when the simulation runs slowly.
Sources: [D400/D455 datasheet](https://dev.realsenseai.com/download/42003/),
[D455 RGB modes](https://support.realsenseai.com/hc/en-us/community/posts/13718098480019-How-to-resample-D455-RGB-images-from-1280-720-to-640-480),
[Webots RangeFinder](https://cyberbotics.com/doc/reference/rangefinder).
### TCP gizmo in Webots
Select the TCP marker, translate or rotate it with the native Webots gizmo, and release the left mouse button. Holding the button only changes the preview. Releasing it submits one complete trajectory. Another drag is accepted after that trajectory finishes. An unreachable target or a colliding trajectory resets the marker to the current TCP.
The gizmo controls the active tool's `tcp` link independently of `planning.pose_link`. For `patron`, TCP is at the chuck's working end, 55.2 mm along local Z from the `patron` link origin. Without a tool, it coincides with the `link_ee` flange. Regular Cartesian commands also use this point when `planning.pose_link: tcp`.
The gizmo has the lowest motion priority. It is unavailable during regular motion. If a coordinate, joint, or file command arrives while a committed gizmo trajectory is running, that command waits for the trajectory to finish before proceeding.
| `tcp_gizmo` parameter | Description |
|---|---|
| `enabled` | Set to `false` to disable the gizmo at the next launch; simulation only |
| `publish_period` | State update period, seconds |
| `command_timeout` | Maximum age of an incoming target, seconds; not a delay after dragging |
| `state_timeout` | Maximum age of robot feedback, seconds |
| `max_linear_speed` | TCP linear speed cap, m/s |
| `max_angular_speed` | TCP angular speed cap, rad/s |
Mouse release is detected directly, so no idle timer is needed. Joint limits, acceleration, and deceleration can reduce speed below the configured cap. The trajectory interpolates joint positions to reach the requested TCP pose; a straight Cartesian path is not guaranteed.
See the [simulation guide](concepts/simulation.md) for the operating sequence.
---
## `tool` section — active tool
Specifies which gripper or tool is attached to the robot.
```yaml
tool:
active: "patron"
```
| Value | Description |
|---|---|
| `none` | No tool |
| `patron` | Patron chuck/gripper |
Available tools are defined in `src/iiwa_config/config/tools.yaml`. To add a tool, describe it there and then set its name in `tool.active`.
Apply tool selection through `cobot robot-setup`, which updates the tool description and SRDF. Rebuild the project and restart the simulation after changing tools.
---
## `planning` section — motion planning
Configures MoveIt 2 and the trajectory planner.
```yaml
planning:
pose_link: "tcp"
planning_group: "iiwa_arm"
default_frame: "base_link"
default_planner: "ompl"
planning_attempts: 3
```
| Parameter | Description | Recommendation |
|---|---|---|
| `pose_link` | TCP link used for Cartesian targets | Must match the URDF frame; do not change without updating the URDF |
| `planning_group` | Planning group from the SRDF | Do not change: `iiwa_arm` |
| `default_frame` | Default reference frame | Do not change: `base_link` |
| `default_planner` | Planner: `ompl` or `pilz_industrial_motion_planner` | `ompl` is general purpose; `pilz` produces predictable trajectories |
| `planning_attempts` | Number of planning attempts after failure | Increase for difficult trajectories |
---
## `web` section — REST API and MCP server
Configures the FastAPI server used to control the robot over HTTP and MCP for AI-agent integration.
```yaml
web:
enabled: true
host: "0.0.0.0"
port: 8007
endpoints: pkg://iiwa_config/config/api_endpoints.yaml
joint_limits: pkg://iiwa_config/config/moveit/joint_limits.yaml
```
| Parameter | Description |
|---|---|
| `enabled` | Enable (`true`) or disable (`false`) the web server |
| `host` | Listening address: `0.0.0.0` for all interfaces or `127.0.0.1` for local access only |
| `port` | HTTP API port; default: `8007` |
| `endpoints` | Path to the REST endpoint description |
| `joint_limits` | Path to joint limits used for command validation |
After startup, the REST API is available at `http://<host>:8007`, and MCP is available at `/mcp`.
---
## `foxglove` section — Foxglove Studio monitoring
[Foxglove Studio](https://foxglove.dev/) visualizes and monitors ROS 2 topics in real time.
```yaml
foxglove:
enabled: true
port: 8765
debug: false
address: 0.0.0.0
```
| Parameter | Description |
|---|---|
| `enabled` | Enable or disable Foxglove Bridge |
| `port` | WebSocket port used by Foxglove Studio; default: `8765` |
| `debug` | Detailed logging for the bridge process |
| `address` | WebSocket listening address |
The remaining parameters (`tls`, `topic_whitelist`, `min_qos_depth`, and others) are intended for advanced configuration and normally do not need to be changed.
---
## What to change and what to keep
| | Parameter | Action |
|---|---|---|
| ✅ | `robot.ip` | **Must be changed** to the controller IP address |
| ✅ | `robot.fri_cycle_ms` | Select `10` (standard) or `5` (high frequency) |
| ✅ | `tool.active` | Set the active tool |
| ✅ | `web.enabled` | Set to `false` if the web interface is not needed |
| ⚠️ | `planning.*` | Change only when another planner or other parameters are required |
| ❌ | `robot.description` | Do not change; this is the URDF path |
| ❌ | `controller.moveit.*` | Do not change; these are package-internal MoveIt configuration paths |
| ❌ | `digital_twin.webots.world` | Do not change unless you understand the Webots world structure |
@@ -0,0 +1,249 @@
# Конфигурация системы
## Главный конфигурационный файл
Все параметры системы хранятся в одном файле — **`cobot-setting.yaml`** в корне проекта.
Это единственный источник истины для IP-адреса робота, портов, путей к конфигам, настроек планировщика и веб-сервера.
!!! info "Не нужно настраивать вручную до установки"
При выполнении `cobot setup` мастер автоматически предложит настроить этот файл на **шаге 2** — вам не нужно делать это заранее.
Возвращайтесь к этому разделу когда захотите изменить параметры после первоначальной установки.
!!! danger "Не редактируйте файл вручную"
Используйте только команду `cobot robot-setup` — интерактивный мастер валидирует значения и не допускает синтаксических ошибок. Ручное редактирование YAML может привести к ошибкам парсинга и невозможности запуска системы.
```bash
cobot robot-setup
```
---
## Блок `robot` — параметры робота
Отвечает за соединение с физическим контроллером KUKA по протоколу FRI.
```yaml
robot:
name: "iiwa7"
ip: "192.170.10.2"
port: 30200
fri_cycle_ms: 10
description: pkg://iiwa_description/urdf/iiwa7.urdf.xacro
```
| Параметр | Описание | Рекомендации |
|---|---|---|
| `name` | Модель робота | Не менять — `iiwa7` |
| `ip` | IP-адрес контроллера KUKA | **Изменить** на реальный IP вашего контроллера |
| `port` | UDP-порт FRI | По умолчанию `30200` — менять только при конфликте портов |
| `fri_cycle_ms` | Период цикла FRI: `5` мс = 200 Гц, `10` мс = 100 Гц | `10` для стабильной работы, `5` для высокоточных задач |
| `joint_position_tau` | Постоянная времени EMA команд FRI, с | `0.04`; `0` отключает сглаживание |
| `description` | Путь к URDF-описанию робота | Не менять |
Управление движением всегда выполняет JointTrajectoryController. Перед отправкой в FRI позиционная команда сглаживается EMA с постоянной времени `robot.joint_position_tau`; фильтр скорости не применяется.
---
## Блок `digital_twin` — симулятор
Настройки виртуальной среды Webots и визуализации в RViz.
```yaml
digital_twin:
tcp_gizmo:
enabled: true
publish_period: 0.032
command_timeout: 0.3
state_timeout: 0.5
max_linear_speed: 0.50
max_angular_speed: 0.4
webots:
world: pkg://iiwa_description/worlds/iiwa.wbt
transform: "-0.25 0 0.79"
rotation: "0 0 1 0"
controller_timer: "50"
cameras:
- pkg://iiwa_config/config/cameras/d455_top.yaml
rviz:
config: pkg://iiwa_config/config/rviz/rviz_moveit.rviz
```
| Параметр | Описание |
|---|---|
| `webots.world` | Путь к `.wbt`-миру симулятора |
| `webots.transform` | Смещение базы робота в мире `[x y z]` в метрах |
| `webots.rotation` | Ориентация базы `[x y z угол]` в радианах |
| `webots.cameras` | Список YAML-конфигов подключённых камер |
| `rviz.config` | Путь к конфигурации RViz |
### Камеры D455 в Webots
Верхняя камера (`config/cameras/d455_top.yaml`) и камера инструмента `patron`
используют **640×480, 30 кадров/с** для RGB и глубины. Горизонтальный угол глубины
для VGA — 75°; 87° относится к HD. RGB использует приближение центральной обрезки
сенсора 1280×800 с горизонтальным углом 90° до формата 4:3: около 79,61°.
Точный угол RGB следует получить из калибровки конкретной камеры для 640×480.
Глубина ограничена выбранным диапазоном симуляции 0,4–6 м, с шагом 1 мм.
Это не гарантия точности и не точное значение минимальной дистанции D455 в VGA.
Модель идеальная: без случайного шума, стереосопоставления, ИК-проектора,
дисторсии и реального смещения между RGB и depth. Вертикальный угол Webots
вычисляет из горизонтального угла и соотношения сторон; он не задаётся независимо.
Для воспроизведения конкретного экземпляра нужны его intrinsics и extrinsics.
Плагин `iiwa_utils.webots_camera.WebotsCamera` поддерживает среднюю частоту
30 Гц по времени симуляции, не накапливая округление до шага Webots.
При `basicTimeStep: 32` интервалы составляют 32 или 64 мс; равномерные интервалы
33,33 мс на такой сетке невозможны. Частота по настенным часам зависит от скорости
симуляции. Физический шаг мира менять не требуется.
Имена топиков изображений сохранены:
| Камера | RGB (`bgra8`) | Глубина (`32FC1`, метры) |
|---|---|---|
| Верхняя | `/d455_top/image_raw/image_color` | `/d455_top/depth/image_raw/image` |
| Инструмент | `/camera/color/image_color` | `/camera/depth/image` |
Рядом публикуется `camera_info` с матрицей виртуальной камеры и той же временной
меткой. Для глубины доступен `point_cloud` при наличии подписчиков: XYZ в метрах
в оптических осях (X вправо, Y вниз, Z вперёд), отсутствующие точки — NaN.
Сохранены идентификаторы кадров `d455_top_link` и `camera_optical_frame`;
плагин не публикует TF и не выполняет совмещение depth с RGB.
Проверка после `cobot run local` → **Webots simulator**: подписаться на четыре
топика, проверить размеры `Image`, совпадение временных меток с `CameraInfo`
и среднюю частоту по меткам кадров за 10 секунд модельного времени.
`ros2 topic hz /camera/depth/image` измеряет доставку по настенным часам,
поэтому при медленной симуляции значение может быть ниже 30.
Источники: [спецификация D400/D455](https://dev.realsenseai.com/download/42003/),
[режимы RGB D455](https://support.realsenseai.com/hc/en-us/community/posts/13718098480019-How-to-resample-D455-RGB-images-from-1280-720-to-640-480),
[Webots RangeFinder](https://cyberbotics.com/doc/reference/rangefinder).
### Перемещение за TCP в Webots
Порядок действий приведён в [руководстве по симуляции](concepts/simulation.md).
Выберите маркер TCP, переместите или поверните его штатной гизмой Webots и отпустите левую кнопку мыши. Пока кнопка удерживается, меняется только маркер. После отпускания отправляется одна полная траектория. Следующее перетаскивание доступно после её завершения. Если цель недостижима или траектория проходит через столкновение, маркер возвращается к текущему TCP.
Гизма использует звено `tcp` активного инструмента независимо от `planning.pose_link`. Для `patron` это рабочий торец патрона (55,2 мм от начала звена `patron` вдоль его локальной оси Z); без инструмента — фланец `link_ee`. Этот TCP также используется обычными декартовыми командами, когда `planning.pose_link: tcp`.
У гизмы самый низкий приоритет: во время обычного движения она недоступна. Если команда координат, joints или файла приходит во время уже начатого движения гизмы, она ждёт завершения этой траектории.
| Параметр `tcp_gizmo` | Описание |
|---|---|
| `enabled` | `false` полностью отключает гизму при следующем запуске; доступна только в симуляции |
| `publish_period` | Период обновления состояния, с |
| `command_timeout` | Максимальный возраст входящей цели, с; не задержка после перетаскивания |
| `state_timeout` | Допустимый возраст обратной связи робота, с |
| `max_linear_speed` | Верхний предел скорости TCP, м/с |
| `max_angular_speed` | Верхний предел угловой скорости TCP, рад/с |
Отпускание определяется по состоянию кнопки мыши, поэтому таймер ожидания не нужен. Скорость может быть ниже заданного предела из-за ограничений суставов, ускорения и торможения. Траектория интерполируется в суставах и достигает заданной позы TCP; прямолинейность пути TCP не гарантируется.
---
## Блок `tool` — активный инструмент
Указывает, какой захват или инструмент закреплён на роботе.
```yaml
tool:
active: "patron"
```
| Значение | Описание |
|---|---|
| `none` | Без инструмента |
| `patron` | Захват «Patron» (патрон) |
Список доступных инструментов находится в файле `src/iiwa_config/config/tools.yaml`. Для добавления нового инструмента необходимо описать его там, после чего указать имя в `tool.active`.
Применяйте выбор через `cobot robot-setup`: мастер обновляет описание инструмента и SRDF. После смены инструмента пересоберите проект и перезапустите симуляцию.
---
## Блок `planning` — планирование движений
Параметры MoveIt 2 и конфигурации траекторного планировщика.
```yaml
planning:
pose_link: "tcp"
planning_group: "iiwa_arm"
default_frame: "base_link"
default_planner: "ompl"
planning_attempts: 3
```
| Параметр | Описание | Рекомендации |
|---|---|---|
| `pose_link` | TCP-линк для декартовых целей | Соответствует фрейму в URDF — не менять без изменения URDF |
| `planning_group` | Группа планирования из SRDF | Не менять — `iiwa_arm` |
| `default_frame` | Система отсчёта по умолчанию | Не менять — `base_link` |
| `default_planner` | Планировщик: `ompl`, `pilz_industrial_motion_planner` | `ompl` — универсальный; `pilz` — для предсказуемых траекторий |
| `planning_attempts` | Число попыток планирования при неудаче | Увеличивать при сложных траекториях |
---
## Блок `web` — REST API и MCP-сервер
FastAPI-сервер для управления роботом через HTTP и MCP (интеграция с AI-агентами).
```yaml
web:
enabled: true
host: "0.0.0.0"
port: 8007
endpoints: pkg://iiwa_config/config/api_endpoints.yaml
joint_limits: pkg://iiwa_config/config/moveit/joint_limits.yaml
```
| Параметр | Описание |
|---|---|
| `enabled` | Включить (`true`) или отключить (`false`) веб-сервер |
| `host` | Адрес прослушивания: `0.0.0.0` — все интерфейсы, `127.0.0.1` — только локально |
| `port` | Порт HTTP API (по умолчанию `8007`) |
| `endpoints` | Путь к описанию REST-эндпоинтов |
| `joint_limits` | Путь к файлу ограничений суставов для валидации команд |
После запуска REST API доступен по адресу `http://<host>:8007`, MCP — по пути `/mcp`.
---
## Блок `foxglove` — мониторинг через Foxglove Studio
[Foxglove Studio](https://foxglove.dev/) — инструмент визуализации и мониторинга ROS 2 топиков в реальном времени.
```yaml
foxglove:
enabled: true
port: 8765
debug: false
address: 0.0.0.0
```
| Параметр | Описание |
|---|---|
| `enabled` | Включить или отключить Foxglove Bridge |
| `port` | WebSocket-порт для подключения Foxglove Studio (по умолчанию `8765`) |
| `debug` | Подробное логирование bridge-процесса |
| `address` | Адрес прослушивания WebSocket |
Остальные параметры блока (`tls`, `topic_whitelist`, `min_qos_depth` и др.) относятся к продвинутой конфигурации и в большинстве случаев менять их не требуется.
---
## Что менять, что оставить
| | Параметр | Действие |
|---|---|---|
| ✅ | `robot.ip` | **Обязательно изменить** на IP вашего контроллера |
| ✅ | `robot.fri_cycle_ms` | Выбрать `10` (стандарт) или `5` (высокая частота) |
| ✅ | `tool.active` | Указать активный инструмент |
| ✅ | `web.enabled` | Выключить (`false`), если веб-интерфейс не нужен |
| ⚠️ | `planning.*` | Менять при необходимости другого планировщика или параметров |
| ❌ | `robot.description` | Не трогать — путь к URDF |
| ❌ | `controller.moveit.*` | Не трогать — пути к конфигам MoveIt внутри пакетов |
| ❌ | `digital_twin.webots.world` | Не трогать без знания структуры Webots-миров |
@@ -0,0 +1,10 @@
# Control via Foxglove Studio
!!! info "Work in progress"
Detailed control and monitoring instructions for Foxglove Studio are being prepared.
[Foxglove Studio](https://foxglove.dev/home) is a tool for visualizing and monitoring ROS 2 data in real time. It connects to the running stack through a WebSocket bridge (port `8765` by default, configured in the `foxglove` section of `cobot-setting.yaml`).
## Download Foxglove Studio
Visit the [official Foxglove website](https://foxglove.dev/home) and download the application for your operating system.
@@ -0,0 +1,10 @@
# Управление через Foxglove Studio
!!! info "Раздел в разработке"
Подробная документация по управлению и мониторингу через Foxglove Studio готовится.
[Foxglove Studio](https://foxglove.dev/home) — инструмент визуализации и мониторинга ROS2-данных в реальном времени. Подключается к запущенному стеку через WebSocket-bridge (порт `8765` по умолчанию, настраивается в `cobot-setting.yaml` → блок `foxglove`).
## Скачать Foxglove Studio
Перейдите на [официальный сайт Foxglove](https://foxglove.dev/home) и скачайте приложение для своей ОС.
@@ -0,0 +1,651 @@
# Control via the REST API
The REST API reads robot state and sends commands over HTTP. It is intended for application scripts, integrations with other systems, and quick checks through Swagger UI.
Motion requests are synchronous: the response is returned after planning and execution finish or an internal timeout occurs. The API has no command queue. Wait for the current request to finish before sending another one.
!!! warning "Safety"
The REST API does not replace the standard KUKA safety system or emergency stop. Before the first run on a physical robot, check the Sunrise program, safety zones, tool, and workspace. Begin using the API in simulation.
## Starting and accessing the server
The web server starts with the robot stack when the **web** section is enabled in the root **cobot-setting.yaml** file:
~~~ yaml
web:
enabled: true
host: 0.0.0.0
port: 8007
endpoints: pkg://iiwa_config/config/api_endpoints.yaml
joint_limits: pkg://iiwa_config/config/moveit/joint_limits.yaml
~~~
After starting the stack with **cobot run**, the server is available at **http://server-address:8007**. Swagger UI shows the actual request schema and lets you run individual tests:
- locally: [http://localhost:8007/docs](http://localhost:8007/docs);
- from another computer: `http://server-address:8007/docs`;
- OpenAPI JSON schema: `http://server-address:8007/openapi.json`.
There is no separate health-check endpoint. If Swagger UI opens, the HTTP server is running. Readiness of ROS components is checked when a specific endpoint is called.
By default, the server listens on all network interfaces and does not use authentication. Do not expose port 8007 to an untrusted network. For local access, set **host: 127.0.0.1**. For remote access, restrict the network with firewall rules or a VPN.
## Preparing the examples
The tabs on this page are synchronized. Select a language once and the same tab will be selected in subsequent examples.
=== "curl"
~~~ bash
HOST=http://localhost:8007
~~~
=== "Python"
~~~ python
import httpx
HOST = "http://localhost:8007"
T_READ = 10
T_MOVE = 60
~~~
=== "MATLAB"
~~~ matlab
HOST = 'http://localhost:8007';
T_READ = 10;
T_MOVE = 60;
readOpts = weboptions('Timeout', T_READ);
moveOpts = weboptions('MediaType', 'application/json', 'Timeout', T_MOVE);
~~~
MATLAB uses the built-in `webwrite` function for JSON requests. Uploading CSV and JSON files requires `matlab.net.http`, available in modern desktop versions of MATLAB.
## API overview
| Method | Endpoint | Purpose |
|---|---|---|
| GET | /robot/joint_states | Current joint state |
| GET | /robot/pose | TCP pose relative to base_link |
| GET | /robot/positions | Named positions from the SRDF |
| POST | /robot/move/named | Move to a named position |
| POST | /robot/move/pose | Cartesian TCP motion |
| POST | /robot/move/joints | Move the seven joints to specified angles |
| POST | /trajectory/send | Publish a trajectory from JSON |
| POST | /trajectory/send_csv | Upload and publish a trajectory from CSV |
| GET | /trajectory/logs | Latest trajectory module log entries |
| POST | /sequences/start | Start a sequence from a JSON file |
| GET | /sequences/status | Running sequence status |
| GET | /sequences/logs | Sequence process output |
| POST | /stop | Stop API commands and the planner |
## Reading robot state
### Joint state
GET **/robot/joint_states** returns the latest message from the ROS **/joint_states** topic. The **position**, **velocity**, and **effort** fields use the same order as the **name** array. Angles in **position** are in radians.
=== "curl"
~~~ bash
curl -sS --max-time 10 $HOST/robot/joint_states | python3 -m json.tool
~~~
=== "Python"
~~~ python
response = httpx.get(f"{HOST}/robot/joint_states", timeout=T_READ)
response.raise_for_status()
state = response.json()
print(dict(zip(state["name"], state["position"])))
~~~
=== "MATLAB"
~~~ matlab
jointState = webread([HOST '/robot/joint_states'], readOpts);
disp(jointState.position)
~~~
Typical response:
~~~ json
{
"name": ["joint1", "joint2", "joint3", "joint4", "joint5", "joint6", "joint7"],
"position": [0.0, 0.0, 0.0, -1.57, 0.0, 1.57, 0.0],
"velocity": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
"effort": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
}
~~~
If no controller messages arrive within two seconds, the API returns 503. This usually means that the controller or robot has not started yet.
### TCP pose
GET **/robot/pose** computes forward kinematics with the MoveIt **/compute_fk** service. Position is specified in meters. Orientation is returned as both a quaternion and Euler angles:
- **euler_rad** — radians;
- **euler_deg** — degrees;
- **A, B, C** follow the KUKA ABC convention: rotation around Z, then Y, then X.
=== "curl"
~~~ bash
curl -sS --max-time 10 $HOST/robot/pose | python3 -m json.tool
~~~
=== "Python"
~~~ python
response = httpx.get(f"{HOST}/robot/pose", timeout=T_READ)
response.raise_for_status()
pose = response.json()
print(pose["position"])
~~~
=== "MATLAB"
~~~ matlab
pose = webread([HOST '/robot/pose'], readOpts);
fprintf('TCP: x=%.3f, y=%.3f, z=%.3f m\n', ...
pose.position.x, pose.position.y, pose.position.z);
fprintf('ABC: A=%.1f, B=%.1f, C=%.1f deg\n', ...
pose.orientation.euler_deg.a, ...
pose.orientation.euler_deg.b, ...
pose.orientation.euler_deg.c);
~~~
This endpoint depends on both **/joint_states** and MoveIt. If either is unavailable, it returns 503.
### Named positions
GET **/robot/positions** reads `group_state` positions from the SRDF. The list is not hardcoded in the API; it reflects the current robot configuration. The standard configuration includes **home**, **work**, and **transport**.
=== "curl"
~~~ bash
curl -sS $HOST/robot/positions | python3 -m json.tool
~~~
=== "Python"
~~~ python
response = httpx.get(f"{HOST}/robot/positions", timeout=T_READ)
response.raise_for_status()
for position in response.json():
print(position["name"], "—", position["description"])
~~~
=== "MATLAB"
~~~ matlab
namedPositions = webread([HOST '/robot/positions'], readOpts);
for i = 1:numel(namedPositions)
fprintf('%s — %s\n', namedPositions(i).name, ...
namedPositions(i).description);
end
~~~
Call this endpoint before **/robot/move/named** to obtain the exact name, planning group, and target joint angles.
## Motion commands
All three commands below use MoveIt. A response has this form:
~~~ json
{"success": true, "message": "Motion completed successfully"}
~~~
**success: false** means that the planner could not plan or execute the trajectory. The HTTP status may still be 200, so application code must check both the HTTP status and the **success** field.
### Moving to a named position
POST **/robot/move/named** moves the manipulator to a position from the SRDF.
| Field | Required | Value |
|---|---:|---|
| name | yes | Position name from /robot/positions |
| speed | no | Speed scale from 0.01 to 1.0; default: 0.1 |
| accel_scale | no | Acceleration scale from 0 to 1.0; 0 uses speed |
=== "curl"
~~~ bash
curl -sS --max-time 60 -X POST $HOST/robot/move/named \
-H "Content-Type: application/json" \
-d '{"name": "home", "speed": 0.1, "accel_scale": 0.0}'
~~~
=== "Python"
~~~ python
response = httpx.post(
f"{HOST}/robot/move/named",
json={"name": "home", "speed": 0.1, "accel_scale": 0.0},
timeout=T_MOVE,
)
response.raise_for_status()
result = response.json()
if not result["success"]:
raise RuntimeError(result["message"])
~~~
=== "MATLAB"
~~~ matlab
body = struct('name', 'home', 'speed', 0.1, 'accel_scale', 0.0);
reply = webwrite([HOST '/robot/move/named'], body, moveOpts);
assert(reply.success, reply.message)
~~~
### Cartesian TCP motion
POST **/robot/move/pose** accepts a TCP position in meters and an ABC orientation in radians. If **frame_id** is empty, the frame from the planning settings is used; in the standard configuration this is **base_link**.
| Field | Required | Value |
|---|---:|---|
| x, y, z | yes | TCP coordinates, m |
| a, b, c | no | KUKA ABC angles, rad; default: 0 |
| speed | no | Speed scale from 0.01 to 1.0; default: 0.1 |
| planner | no | ompl, ptp, lin, circ, or chomp; default: ptp |
| frame_id | no | Target pose frame; an empty string uses the default frame |
The **planner** value is converted to lowercase. PTP is suitable for transitions between points; LIN produces straight-line tool motion. CIRC is appropriate only when it is supported by the planner and target pose.
=== "curl"
~~~ bash
curl -sS --max-time 60 -X POST $HOST/robot/move/pose \
-H "Content-Type: application/json" \
-d '{
"x": 0.40, "y": 0.00, "z": 0.50,
"a": 0.0, "b": 3.14159, "c": 0.0,
"speed": 0.1, "planner": "ptp", "frame_id": ""
}'
~~~
=== "Python"
~~~ python
target = {
"x": 0.40, "y": 0.00, "z": 0.50,
"a": 0.0, "b": 3.14159, "c": 0.0,
"speed": 0.1, "planner": "ptp", "frame_id": "",
}
response = httpx.post(f"{HOST}/robot/move/pose", json=target, timeout=T_MOVE)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
body = struct( ...
'x', 0.40, 'y', 0.00, 'z', 0.50, ...
'a', 0.0, 'b', pi, 'c', 0.0, ...
'speed', 0.1, 'planner', 'ptp', 'frame_id', '');
reply = webwrite([HOST '/robot/move/pose'], body, moveOpts);
assert(reply.success, reply.message)
~~~
### Moving by joint angles
POST **/robot/move/joints** accepts exactly seven angles in J1–J7 order. The API validates the number of values and the current limits from **joint_limits.yaml**.
| Joint | Allowed angle, rad |
|---|---:|
| J1 | -2.97 to 2.97 |
| J2 | -2.10 to 2.10 |
| J3 | -2.97 to 2.97 |
| J4 | -2.10 to 2.10 |
| J5 | -2.97 to 2.97 |
| J6 | -2.10 to 2.10 |
| J7 | -3.05 to 3.05 |
If the limits file changes, use Swagger UI as the reference. The table above describes the supplied configuration.
=== "curl"
~~~ bash
curl -sS --max-time 60 -X POST $HOST/robot/move/joints \
-H "Content-Type: application/json" \
-d '{"joints": [0.0, 0.5, 0.0, -1.57, 0.0, 1.57, 0.0], "speed": 0.1}'
~~~
=== "Python"
~~~ python
response = httpx.post(
f"{HOST}/robot/move/joints",
json={
"joints": [0.0, 0.5, 0.0, -1.57, 0.0, 1.57, 0.0],
"speed": 0.1,
},
timeout=T_MOVE,
)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
body = struct( ...
'joints', [0.0, 0.5, 0.0, -1.57, 0.0, 1.57, 0.0], ...
'speed', 0.1);
reply = webwrite([HOST '/robot/move/joints'], body, moveOpts);
assert(reply.success, reply.message)
~~~
## Joint trajectories
Endpoints under **/trajectory** publish a `JointTrajectory` message directly to **/iiwa_arm_controller/joint_trajectory**. A **status: sent** response confirms publication, not completion of motion or absence of controller errors. Monitor **/robot/joint_states** and inspect **/trajectory/logs** when necessary.
### JSON trajectory
POST **/trajectory/send** accepts one or more points.
| Field | Value |
|---|---|
| points | Non-empty point list |
| points[].positions | Exactly 7 J1–J7 angles in radians |
| points[].time_from_start | Time from trajectory start in seconds, at least 0 |
| validate_limits | Validate joint limits; default: true |
The server does not check that time increases between points. Set increasing values yourself to make controller behavior predictable.
=== "curl"
~~~ bash
curl -sS --max-time 20 -X POST $HOST/trajectory/send \
-H "Content-Type: application/json" \
-d '{
"points": [
{"positions": [0, 0, 0, 0, 0, 0, 0], "time_from_start": 0.0},
{"positions": [0, 0.5, 0, -1.0, 0, 1.0, 0], "time_from_start": 3.0},
{"positions": [0, 0, 0, 0, 0, 0, 0], "time_from_start": 6.0}
],
"validate_limits": true
}'
~~~
=== "Python"
~~~ python
trajectory = {
"points": [
{"positions": [0.0] * 7, "time_from_start": 0.0},
{"positions": [0.0, 0.5, 0.0, -1.0, 0.0, 1.0, 0.0], "time_from_start": 3.0},
{"positions": [0.0] * 7, "time_from_start": 6.0},
],
"validate_limits": True,
}
response = httpx.post(f"{HOST}/trajectory/send", json=trajectory, timeout=T_READ)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
p1 = struct('positions', [0, 0, 0, 0, 0, 0, 0], ...
'time_from_start', 0.0);
p2 = struct('positions', [0, 0.5, 0, -1.0, 0, 1.0, 0], ...
'time_from_start', 3.0);
trajectory.points = [p1, p2];
trajectory.validate_limits = true;
opts = weboptions('MediaType', 'application/json', 'Timeout', T_READ);
reply = webwrite([HOST '/trajectory/send'], trajectory, opts);
disp(reply)
~~~
### Uploading CSV
POST **/trajectory/send_csv** accepts a CSV file in the multipart **file** field. The first row must be a header. Joint columns may be named **joint1** or **joint_1**, case-insensitively. The time column may be named **t**, **time**, or **time_from_start**. Columns may appear in any order.
Example file:
~~~ csv
joint1,joint2,joint3,joint4,joint5,joint6,joint7,t
0,0,0,0,0,0,0,0.0
0,0.5,0,-1.0,0,1.0,0,3.0
~~~
Pass **separator** and **validate_limits** in the query string, not as form fields. The default separator is a comma and limit validation is enabled.
=== "curl"
~~~ bash
curl -sS --max-time 20 -X POST \
"$HOST/trajectory/send_csv?separator=%2C&validate_limits=true" \
-F "file=@trajectory.csv;type=text/csv"
~~~
=== "Python"
~~~ python
with open("trajectory.csv", "rb") as csv_file:
response = httpx.post(
f"{HOST}/trajectory/send_csv",
params={"separator": ",", "validate_limits": True},
files={"file": ("trajectory.csv", csv_file, "text/csv")},
timeout=T_READ,
)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
import matlab.net.http.*
import matlab.net.http.io.*
uri = URI([HOST '/trajectory/send_csv?separator=%2C&validate_limits=true']);
form = MultipartFormProvider('file', FileProvider('trajectory.csv'));
request = RequestMessage('post', [], form);
httpOpts = HTTPOptions('ConnectTimeout', T_READ, 'ResponseTimeout', T_READ);
response = request.send(uri, httpOpts);
disp(response.Body.Data)
~~~
For a semicolon-delimited file, replace `%2C` with `%3B`.
### Trajectory module log
GET **/trajectory/logs?n=50** returns up to 300 latest entries. The **n** parameter must be between 1 and 300.
=== "curl"
~~~ bash
curl -sS "$HOST/trajectory/logs?n=20" | python3 -m json.tool
~~~
=== "Python"
~~~ python
response = httpx.get(f"{HOST}/trajectory/logs", params={"n": 20}, timeout=T_READ)
response.raise_for_status()
for line in response.json()["lines"]:
print(line)
~~~
=== "MATLAB"
~~~ matlab
logs = webread([HOST '/trajectory/logs?n=20'], readOpts);
disp(logs.lines)
~~~
Use the common **POST /stop** endpoint to interrupt a trajectory. The API has no **/trajectory/stop** endpoint.
## Motion sequences
POST **/sequences/start** launches a separate `motion_sequence_runner` process. It reads the uploaded JSON file and sends `MoveToJoints` or `MoveToPose` targets in sequence.
| Form field | Default | Purpose |
|---|---:|---|
| config | — | Sequence JSON file; required |
| n_iterations | 3 | Number of repetitions; at least 1 |
| delay_between_iterations | 5.0 | Delay between iterations, s |
| bag_path | empty | rosbag output path; an empty string disables recording |
| topics | empty | Comma-separated rosbag topics; empty means all discovered topics |
| joints_action | cobot/move_to_joints | Action name for joint targets |
| pose_action | cobot/move_to_pose | Action name for Cartesian targets |
Minimal configuration:
~~~ json
{
"home": {
"joints": [0, 0, 0, -1.57, 0, 1.57, 0],
"speed": 0.1
},
"waypoints": [
{
"x": 0.6, "y": 0.1, "z": 0.55,
"a": 3.14, "b": 0.31, "c": 2.79,
"speed": 0.2, "planner": "lin"
},
{
"joints": [0.5, 0.3, 0, -1.2, 0, 1.4, 0],
"speed": 0.2
}
]
}
~~~
A point containing **joints** is treated as a joint target. Otherwise, the runner expects Cartesian fields **x**, **y**, **z**, **a**, **b**, and **c**.
### Starting a sequence
=== "curl"
~~~ bash
curl -sS --max-time 10 -X POST $HOST/sequences/start \
-F "config=@motion_sequence_config.json;type=application/json" \
-F "n_iterations=3" \
-F "delay_between_iterations=5.0"
~~~
=== "Python"
~~~ python
with open("motion_sequence_config.json", "rb") as config:
response = httpx.post(
f"{HOST}/sequences/start",
files={"config": ("motion_sequence_config.json", config, "application/json")},
data={"n_iterations": "3", "delay_between_iterations": "5.0"},
timeout=T_READ,
)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
import matlab.net.http.*
import matlab.net.http.io.*
form = MultipartFormProvider( ...
'config', FileProvider('motion_sequence_config.json'), ...
'n_iterations', '3', ...
'delay_between_iterations', '5.0');
request = RequestMessage('post', [], form);
httpOpts = HTTPOptions('ConnectTimeout', T_READ, 'ResponseTimeout', T_READ);
response = request.send(URI([HOST '/sequences/start']), httpOpts);
disp(response.Body.Data)
~~~
A **status: started** response confirms that the process started, not that the JSON is valid or that every motion succeeds. If the runner exits with an error, inspect its status and log.
### Sequence status and log
=== "curl"
~~~ bash
curl -sS $HOST/sequences/status | python3 -m json.tool
curl -sS "$HOST/sequences/logs?n=50" | python3 -m json.tool
~~~
=== "Python"
~~~ python
status = httpx.get(f"{HOST}/sequences/status", timeout=T_READ)
status.raise_for_status()
print(status.json())
logs = httpx.get(f"{HOST}/sequences/logs", params={"n": 50}, timeout=T_READ)
logs.raise_for_status()
for line in logs.json()["lines"]:
print(line)
~~~
=== "MATLAB"
~~~ matlab
status = webread([HOST '/sequences/status'], readOpts);
logs = webread([HOST '/sequences/logs?n=50'], readOpts);
disp(status)
disp(logs.lines)
~~~
Statuses:
- **idle** — no sequence has been started;
- **running** — the process is running;
- **finished** — the process has exited; the response includes **returncode**.
Only one sequence can run at a time. A second POST to **/sequences/start** while one is running returns 409. Use **POST /stop** to stop it; there is no separate **/sequences/stop** endpoint.
## Common stop command
POST **/stop** stops the running sequence runner, publishes a hold point at the current position to the trajectory controller, and calls the MoveIt **cobot/stop** service. If current joint states are unavailable, it publishes an empty trajectory instead.
=== "curl"
~~~ bash
curl -sS --max-time 10 -X POST $HOST/stop | python3 -m json.tool
~~~
=== "Python"
~~~ python
response = httpx.post(f"{HOST}/stop", timeout=T_READ)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
reply = webwrite([HOST '/stop'], struct(), ...
weboptions('MediaType', 'application/json', 'Timeout', T_READ));
disp(reply)
~~~
This command cancels software operations, but does not remove robot power or replace the standard emergency stop. After calling it, verify both the response message and the physical robot state.
## Errors and diagnostics
| Code | When it occurs |
|---:|---|
| 200 | The request was processed; for motion commands, also check the success field |
| 409 | A motion sequence is already running |
| 422 | Invalid request structure, joint count, speed, planner, or joint limits |
| 503 | A ROS topic, service, action server, or MoveIt is unavailable; a wait timeout may also have occurred |
When troubleshooting, proceed from simple checks to more complex ones:
1. Open **/docs** and verify that the server is running and the endpoint appears in the schema.
2. Check **/robot/joint_states**. Without it, pose retrieval does not work and trajectory stopping cannot generate a hold point.
3. Make sure that the complete stack is running: `controller_manager`, MoveIt, and `iiwa_motion_server`.
4. After starting a sequence, inspect **/sequences/logs**. After publishing a trajectory, inspect **/trajectory/logs**.
The MCP server runs in the same process but provides a separate interface at **http://server-address:8007/mcp/mcp**. For ordinary HTTP integrations, use the endpoints documented on this page.
@@ -0,0 +1,651 @@
# Управление через REST API
REST API позволяет читать состояние робота и отправлять ему команды по HTTP. Он рассчитан на прикладные скрипты, интеграции с другими системами и быстрые проверки через Swagger UI.
Запросы к перемещению выполняются синхронно: ответ приходит после завершения планирования и выполнения команды либо после внутреннего тайм-аута. Очереди команд в API нет — дождитесь ответа на текущий запрос, прежде чем отправлять следующий.
!!! warning "Безопасность"
REST API не заменяет штатную систему безопасности KUKA и кнопку аварийного останова. Перед первым запуском на реальном роботе проверьте программу Sunrise, зоны безопасности, инструмент и рабочую область. Начинать знакомство с API лучше в симуляции.
## Запуск и доступ
Веб-сервер запускается вместе со стеком робота, если в корневом файле **cobot-setting.yaml** включён блок **web**:
~~~ yaml
web:
enabled: true
host: 0.0.0.0
port: 8007
endpoints: pkg://iiwa_config/config/api_endpoints.yaml
joint_limits: pkg://iiwa_config/config/moveit/joint_limits.yaml
~~~
После запуска через **cobot run** сервер будет доступен по адресу **http://адрес-сервера:8007**. Swagger UI помогает посмотреть фактическую схему запросов и выполнить одиночный тест:
- локально: [http://localhost:8007/docs](http://localhost:8007/docs);
- с другой машины: http://адрес-сервера:8007/docs;
- JSON-схема OpenAPI: http://адрес-сервера:8007/openapi.json.
Отдельного health-check в сервере нет. Если открывается Swagger UI, HTTP-сервер запущен. Готовность ROS-компонентов проверяется при обращении к конкретному маршруту.
По умолчанию сервер слушает все сетевые интерфейсы и не использует аутентификацию. Не публикуйте порт 8007 в недоверенную сеть. Для локальной работы укажите **host: 127.0.0.1**, а для удалённого доступа ограничьте сеть правилами firewall или VPN.
## Подготовка к примерам
Вкладки на этой странице синхронизированы: выберите удобный язык один раз, и тот же вариант будет открыт у следующих примеров.
=== "curl"
~~~ bash
HOST=http://localhost:8007
~~~
=== "Python"
~~~ python
import httpx
HOST = "http://localhost:8007"
T_READ = 10
T_MOVE = 60
~~~
=== "MATLAB"
~~~ matlab
HOST = 'http://localhost:8007';
T_READ = 10;
T_MOVE = 60;
readOpts = weboptions('Timeout', T_READ);
moveOpts = weboptions('MediaType', 'application/json', 'Timeout', T_MOVE);
~~~
Для JSON-запросов MATLAB использует встроенный webwrite. Загрузка CSV и JSON-файлов требует интерфейса matlab.net.http, который есть в современных desktop-версиях MATLAB.
## Состав API
| Метод | Маршрут | Назначение |
|---|---|---|
| GET | /robot/joint_states | Текущее состояние суставов |
| GET | /robot/pose | Поза TCP относительно base_link |
| GET | /robot/positions | Именованные положения из SRDF |
| POST | /robot/move/named | Переход в именованное положение |
| POST | /robot/move/pose | Декартово перемещение TCP |
| POST | /robot/move/joints | Перемещение по углам семи суставов |
| POST | /trajectory/send | Публикация траектории из JSON |
| POST | /trajectory/send_csv | Загрузка и публикация траектории из CSV |
| GET | /trajectory/logs | Последние записи траекторного модуля |
| POST | /sequences/start | Запуск последовательности из JSON-файла |
| GET | /sequences/status | Статус запущенной последовательности |
| GET | /sequences/logs | Вывод процесса последовательности |
| POST | /stop | Остановка команд API и планировщика |
## Получение состояния
### Состояние суставов
GET **/robot/joint_states** возвращает последнее сообщение ROS-топика **/joint_states**. Поля **position**, **velocity** и **effort** расположены в том же порядке, что и соответствующий массив **name**. Углы в **position** заданы в радианах.
=== "curl"
~~~ bash
curl -sS --max-time 10 $HOST/robot/joint_states | python3 -m json.tool
~~~
=== "Python"
~~~ python
response = httpx.get(f"{HOST}/robot/joint_states", timeout=T_READ)
response.raise_for_status()
state = response.json()
print(dict(zip(state["name"], state["position"])))
~~~
=== "MATLAB"
~~~ matlab
jointState = webread([HOST '/robot/joint_states'], readOpts);
disp(jointState.position)
~~~
Типичный ответ:
~~~ json
{
"name": ["joint1", "joint2", "joint3", "joint4", "joint5", "joint6", "joint7"],
"position": [0.0, 0.0, 0.0, -1.57, 0.0, 1.57, 0.0],
"velocity": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
"effort": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
}
~~~
Если сообщения от контроллера не поступают в течение двух секунд, API вернёт 503. Обычно это означает, что контроллер или робот ещё не запущен.
### Поза TCP
GET **/robot/pose** вычисляет прямую кинематику через сервис MoveIt **/compute_fk**. Положение задаётся в метрах, а ориентация возвращается одновременно кватернионом и углами Эйлера:
- **euler_rad** — радианы;
- **euler_deg** — градусы;
- углы **A, B, C** соответствуют конвенции KUKA ABC: поворот вокруг Z, затем Y и затем X.
=== "curl"
~~~ bash
curl -sS --max-time 10 $HOST/robot/pose | python3 -m json.tool
~~~
=== "Python"
~~~ python
response = httpx.get(f"{HOST}/robot/pose", timeout=T_READ)
response.raise_for_status()
pose = response.json()
print(pose["position"])
~~~
=== "MATLAB"
~~~ matlab
pose = webread([HOST '/robot/pose'], readOpts);
fprintf('TCP: x=%.3f, y=%.3f, z=%.3f м\n', ...
pose.position.x, pose.position.y, pose.position.z);
fprintf('ABC: A=%.1f, B=%.1f, C=%.1f град\n', ...
pose.orientation.euler_deg.a, ...
pose.orientation.euler_deg.b, ...
pose.orientation.euler_deg.c);
~~~
Маршрут зависит и от **/joint_states**, и от работающего MoveIt. При недоступности любого из них будет возвращён 503.
### Именованные положения
GET **/robot/positions** читает положения group_state из SRDF. Список не зашит в API: он отражает текущую конфигурацию робота. В стандартной конфигурации есть положения **home**, **work** и **transport**.
=== "curl"
~~~ bash
curl -sS $HOST/robot/positions | python3 -m json.tool
~~~
=== "Python"
~~~ python
response = httpx.get(f"{HOST}/robot/positions", timeout=T_READ)
response.raise_for_status()
for position in response.json():
print(position["name"], "—", position["description"])
~~~
=== "MATLAB"
~~~ matlab
namedPositions = webread([HOST '/robot/positions'], readOpts);
for i = 1:numel(namedPositions)
fprintf('%s — %s\n', namedPositions(i).name, ...
namedPositions(i).description);
end
~~~
Перед вызовом **/robot/move/named** всегда полезно получить этот список: он показывает точное имя, группу планирования и целевые углы суставов.
## Команды перемещения
Все три команды ниже используют MoveIt. Ответ имеет вид:
~~~ json
{"success": true, "message": "Движение выполнено успешно"}
~~~
Поле **success: false** означает, что планировщик не смог построить или выполнить траекторию. HTTP-статус при этом может остаться 200, поэтому в прикладном коде проверяйте и статус HTTP, и поле **success**.
### Переход в именованное положение
POST **/robot/move/named** перемещает манипулятор в положение из SRDF.
| Поле | Обязательное | Значение |
|---|---:|---|
| name | да | Имя положения из /robot/positions |
| speed | нет | Масштаб скорости от 0.01 до 1.0; по умолчанию 0.1 |
| accel_scale | нет | Масштаб ускорения от 0 до 1.0; 0 означает использовать speed |
=== "curl"
~~~ bash
curl -sS --max-time 60 -X POST $HOST/robot/move/named \
-H "Content-Type: application/json" \
-d '{"name": "home", "speed": 0.1, "accel_scale": 0.0}'
~~~
=== "Python"
~~~ python
response = httpx.post(
f"{HOST}/robot/move/named",
json={"name": "home", "speed": 0.1, "accel_scale": 0.0},
timeout=T_MOVE,
)
response.raise_for_status()
result = response.json()
if not result["success"]:
raise RuntimeError(result["message"])
~~~
=== "MATLAB"
~~~ matlab
body = struct('name', 'home', 'speed', 0.1, 'accel_scale', 0.0);
reply = webwrite([HOST '/robot/move/named'], body, moveOpts);
assert(reply.success, reply.message)
~~~
### Декартово перемещение TCP
POST **/robot/move/pose** принимает положение TCP в метрах и ориентацию ABC в радианах. Если **frame_id** пуст, используется фрейм, заданный в настройках планирования; в стандартной конфигурации это **base_link**.
| Поле | Обязательное | Значение |
|---|---:|---|
| x, y, z | да | Координаты TCP, м |
| a, b, c | нет | Углы KUKA ABC, рад; по умолчанию 0 |
| speed | нет | Масштаб скорости от 0.01 до 1.0; по умолчанию 0.1 |
| planner | нет | ompl, ptp, lin, circ или chomp; по умолчанию ptp |
| frame_id | нет | Фрейм целевой позы; пустая строка использует фрейм по умолчанию |
Значение **planner** приводится к нижнему регистру. PTP подходит для переходов между точками, LIN — для прямолинейного движения инструмента. Выбор CIRC имеет смысл только для задач, где он поддерживается вашим планировщиком и целевой позой.
=== "curl"
~~~ bash
curl -sS --max-time 60 -X POST $HOST/robot/move/pose \
-H "Content-Type: application/json" \
-d '{
"x": 0.40, "y": 0.00, "z": 0.50,
"a": 0.0, "b": 3.14159, "c": 0.0,
"speed": 0.1, "planner": "ptp", "frame_id": ""
}'
~~~
=== "Python"
~~~ python
target = {
"x": 0.40, "y": 0.00, "z": 0.50,
"a": 0.0, "b": 3.14159, "c": 0.0,
"speed": 0.1, "planner": "ptp", "frame_id": "",
}
response = httpx.post(f"{HOST}/robot/move/pose", json=target, timeout=T_MOVE)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
body = struct( ...
'x', 0.40, 'y', 0.00, 'z', 0.50, ...
'a', 0.0, 'b', pi, 'c', 0.0, ...
'speed', 0.1, 'planner', 'ptp', 'frame_id', '');
reply = webwrite([HOST '/robot/move/pose'], body, moveOpts);
assert(reply.success, reply.message)
~~~
### Перемещение по углам суставов
POST **/robot/move/joints** принимает ровно семь углов в порядке J1–J7. API проверяет количество значений и текущие границы из файла **joint_limits.yaml**.
| Сустав | Допустимый угол, рад |
|---|---:|
| J1 | от -2.97 до 2.97 |
| J2 | от -2.10 до 2.10 |
| J3 | от -2.97 до 2.97 |
| J4 | от -2.10 до 2.10 |
| J5 | от -2.97 до 2.97 |
| J6 | от -2.10 до 2.10 |
| J7 | от -3.05 до 3.05 |
При изменении файла ограничений ориентируйтесь на Swagger UI: значения в этой таблице относятся к поставляемой конфигурации.
=== "curl"
~~~ bash
curl -sS --max-time 60 -X POST $HOST/robot/move/joints \
-H "Content-Type: application/json" \
-d '{"joints": [0.0, 0.5, 0.0, -1.57, 0.0, 1.57, 0.0], "speed": 0.1}'
~~~
=== "Python"
~~~ python
response = httpx.post(
f"{HOST}/robot/move/joints",
json={
"joints": [0.0, 0.5, 0.0, -1.57, 0.0, 1.57, 0.0],
"speed": 0.1,
},
timeout=T_MOVE,
)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
body = struct( ...
'joints', [0.0, 0.5, 0.0, -1.57, 0.0, 1.57, 0.0], ...
'speed', 0.1);
reply = webwrite([HOST '/robot/move/joints'], body, moveOpts);
assert(reply.success, reply.message)
~~~
## Траектории по суставам
Маршруты раздела **/trajectory** публикуют сообщение JointTrajectory напрямую в контроллер **/iiwa_arm_controller/joint_trajectory**. Ответ **status: sent** подтверждает публикацию сообщения, но не завершение движения и не отсутствие ошибок контроллера. Отслеживайте состояние робота через **/robot/joint_states** и при необходимости смотрите **/trajectory/logs**.
### Траектория в JSON
POST **/trajectory/send** принимает одну или несколько точек.
| Поле | Значение |
|---|---|
| points | Непустой список точек |
| points[].positions | Ровно 7 углов J1–J7 в радианах |
| points[].time_from_start | Время от начала траектории в секундах, не меньше 0 |
| validate_limits | Проверять границы суставов; по умолчанию true |
Сервер не проверяет возрастание времени между точками, поэтому задавайте его самостоятельно. Для контроллера траектория с возрастающими значениями времени предсказуемее.
=== "curl"
~~~ bash
curl -sS --max-time 20 -X POST $HOST/trajectory/send \
-H "Content-Type: application/json" \
-d '{
"points": [
{"positions": [0, 0, 0, 0, 0, 0, 0], "time_from_start": 0.0},
{"positions": [0, 0.5, 0, -1.0, 0, 1.0, 0], "time_from_start": 3.0},
{"positions": [0, 0, 0, 0, 0, 0, 0], "time_from_start": 6.0}
],
"validate_limits": true
}'
~~~
=== "Python"
~~~ python
trajectory = {
"points": [
{"positions": [0.0] * 7, "time_from_start": 0.0},
{"positions": [0.0, 0.5, 0.0, -1.0, 0.0, 1.0, 0.0], "time_from_start": 3.0},
{"positions": [0.0] * 7, "time_from_start": 6.0},
],
"validate_limits": True,
}
response = httpx.post(f"{HOST}/trajectory/send", json=trajectory, timeout=T_READ)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
p1 = struct('positions', [0, 0, 0, 0, 0, 0, 0], ...
'time_from_start', 0.0);
p2 = struct('positions', [0, 0.5, 0, -1.0, 0, 1.0, 0], ...
'time_from_start', 3.0);
trajectory.points = [p1, p2];
trajectory.validate_limits = true;
opts = weboptions('MediaType', 'application/json', 'Timeout', T_READ);
reply = webwrite([HOST '/trajectory/send'], trajectory, opts);
disp(reply)
~~~
### Загрузка CSV
POST **/trajectory/send_csv** принимает CSV-файл в multipart-поле **file**. Первая строка должна быть заголовком. Имена колонок суставов могут быть записаны как **joint1** или **joint_1**, регистр не важен; колонка времени называется **t**, **time** или **time_from_start**. Порядок колонок произвольный.
Пример файла:
~~~ csv
joint1,joint2,joint3,joint4,joint5,joint6,joint7,t
0,0,0,0,0,0,0,0.0
0,0.5,0,-1.0,0,1.0,0,3.0
~~~
Параметры **separator** и **validate_limits** передаются в строке запроса, а не как поля формы. По умолчанию разделитель — запятая, проверка ограничений включена.
=== "curl"
~~~ bash
curl -sS --max-time 20 -X POST \
"$HOST/trajectory/send_csv?separator=%2C&validate_limits=true" \
-F "file=@trajectory.csv;type=text/csv"
~~~
=== "Python"
~~~ python
with open("trajectory.csv", "rb") as csv_file:
response = httpx.post(
f"{HOST}/trajectory/send_csv",
params={"separator": ",", "validate_limits": True},
files={"file": ("trajectory.csv", csv_file, "text/csv")},
timeout=T_READ,
)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
import matlab.net.http.*
import matlab.net.http.io.*
uri = URI([HOST '/trajectory/send_csv?separator=%2C&validate_limits=true']);
form = MultipartFormProvider('file', FileProvider('trajectory.csv'));
request = RequestMessage('post', [], form);
httpOpts = HTTPOptions('ConnectTimeout', T_READ, 'ResponseTimeout', T_READ);
response = request.send(uri, httpOpts);
disp(response.Body.Data)
~~~
Для файла с точкой с запятой замените %2C на %3B.
### Лог траекторного модуля
GET **/trajectory/logs?n=50** возвращает до 300 последних записей. Параметр **n** должен быть в диапазоне от 1 до 300.
=== "curl"
~~~ bash
curl -sS "$HOST/trajectory/logs?n=20" | python3 -m json.tool
~~~
=== "Python"
~~~ python
response = httpx.get(f"{HOST}/trajectory/logs", params={"n": 20}, timeout=T_READ)
response.raise_for_status()
for line in response.json()["lines"]:
print(line)
~~~
=== "MATLAB"
~~~ matlab
logs = webread([HOST '/trajectory/logs?n=20'], readOpts);
disp(logs.lines)
~~~
Чтобы прервать траекторию, используйте общий маршрут **POST /stop**. Отдельного маршрута **/trajectory/stop** в API нет.
## Последовательности движений
POST **/sequences/start** запускает отдельный процесс motion_sequence_runner. Он читает загруженный JSON-файл и поочерёдно отправляет цели MoveToJoints или MoveToPose.
| Поле формы | Значение по умолчанию | Назначение |
|---|---:|---|
| config | — | JSON-файл последовательности, обязательное поле |
| n_iterations | 3 | Число повторений, не меньше 1 |
| delay_between_iterations | 5.0 | Пауза между итерациями, с |
| bag_path | пусто | Путь для записи rosbag; пустая строка отключает запись |
| topics | пусто | Топики для rosbag через запятую; пусто означает все обнаруженные топики |
| joints_action | cobot/move_to_joints | Имя action для суставных целей |
| pose_action | cobot/move_to_pose | Имя action для декартовых целей |
Минимальная структура конфигурации:
~~~ json
{
"home": {
"joints": [0, 0, 0, -1.57, 0, 1.57, 0],
"speed": 0.1
},
"waypoints": [
{
"x": 0.6, "y": 0.1, "z": 0.55,
"a": 3.14, "b": 0.31, "c": 2.79,
"speed": 0.2, "planner": "lin"
},
{
"joints": [0.5, 0.3, 0, -1.2, 0, 1.4, 0],
"speed": 0.2
}
]
}
~~~
Если в точке есть поле **joints**, она считается суставной. Иначе runner ожидает декартовы поля **x**, **y**, **z**, **a**, **b** и **c**.
### Запуск последовательности
=== "curl"
~~~ bash
curl -sS --max-time 10 -X POST $HOST/sequences/start \
-F "config=@motion_sequence_config.json;type=application/json" \
-F "n_iterations=3" \
-F "delay_between_iterations=5.0"
~~~
=== "Python"
~~~ python
with open("motion_sequence_config.json", "rb") as config:
response = httpx.post(
f"{HOST}/sequences/start",
files={"config": ("motion_sequence_config.json", config, "application/json")},
data={"n_iterations": "3", "delay_between_iterations": "5.0"},
timeout=T_READ,
)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
import matlab.net.http.*
import matlab.net.http.io.*
form = MultipartFormProvider( ...
'config', FileProvider('motion_sequence_config.json'), ...
'n_iterations', '3', ...
'delay_between_iterations', '5.0');
request = RequestMessage('post', [], form);
httpOpts = HTTPOptions('ConnectTimeout', T_READ, 'ResponseTimeout', T_READ);
response = request.send(URI([HOST '/sequences/start']), httpOpts);
disp(response.Body.Data)
~~~
Ответ **status: started** подтверждает запуск процесса, но не корректность содержимого JSON и не успешность каждого движения. Если runner завершится с ошибкой, проверьте его состояние и лог.
### Статус и журнал последовательности
=== "curl"
~~~ bash
curl -sS $HOST/sequences/status | python3 -m json.tool
curl -sS "$HOST/sequences/logs?n=50" | python3 -m json.tool
~~~
=== "Python"
~~~ python
status = httpx.get(f"{HOST}/sequences/status", timeout=T_READ)
status.raise_for_status()
print(status.json())
logs = httpx.get(f"{HOST}/sequences/logs", params={"n": 50}, timeout=T_READ)
logs.raise_for_status()
for line in logs.json()["lines"]:
print(line)
~~~
=== "MATLAB"
~~~ matlab
status = webread([HOST '/sequences/status'], readOpts);
logs = webread([HOST '/sequences/logs?n=50'], readOpts);
disp(status)
disp(logs.lines)
~~~
Статусы:
- **idle** — последовательность ещё не запускалась;
- **running** — процесс выполняется;
- **finished** — процесс завершён; в ответе будет код **returncode**.
Одновременно может работать только одна последовательность. Повторный POST **/sequences/start** во время её выполнения вернёт 409. Для остановки используйте **POST /stop**: отдельного **/sequences/stop** нет.
## Общая остановка
POST **/stop** останавливает запущенный runner, публикует точку удержания текущей позиции для траекторного контроллера и вызывает сервис MoveIt **cobot/stop**. Если текущие состояния суставов недоступны, вместо точки удержания публикуется пустая траектория.
=== "curl"
~~~ bash
curl -sS --max-time 10 -X POST $HOST/stop | python3 -m json.tool
~~~
=== "Python"
~~~ python
response = httpx.post(f"{HOST}/stop", timeout=T_READ)
response.raise_for_status()
print(response.json())
~~~
=== "MATLAB"
~~~ matlab
reply = webwrite([HOST '/stop'], struct(), ...
weboptions('MediaType', 'application/json', 'Timeout', T_READ));
disp(reply)
~~~
Команда отменяет программные операции, но не снимает питание с робота и не заменяет штатную аварийную остановку. После её вызова проверьте сообщение в ответе и реальное состояние робота.
## Ошибки и диагностика
| Код | Когда возникает |
|---:|---|
| 200 | Запрос обработан; для команд движения дополнительно проверьте поле success |
| 409 | Уже запущена последовательность движений |
| 422 | Некорректная структура запроса, число суставов, скорость, планировщик или лимиты суставов |
| 503 | ROS-топик, сервис, action-сервер или MoveIt недоступен; также возможен тайм-аут ожидания |
При проблемах идите от простого к сложному:
1. Откройте **/docs** и убедитесь, что сервер запущен и маршрут присутствует в схеме.
2. Проверьте **/robot/joint_states**. Без него не будет работать получение позы, а остановка траектории не сможет сформировать точку удержания.
3. Убедитесь, что стек запущен полностью: controller_manager, MoveIt и iiwa_motion_server.
4. После запуска последовательности посмотрите **/sequences/logs**; после публикации траектории — **/trajectory/logs**.
MCP-сервер работает в том же процессе, но это отдельный интерфейс: его адрес — **http://адрес-сервера:8007/mcp/mcp**. Для обычных HTTP-интеграций используйте маршруты из этой страницы.
@@ -0,0 +1,11 @@
# Control via ROS 2
!!! info "Work in progress"
Detailed instructions for control through ROS 2 topics and action servers are being prepared.
This method sends commands directly to ROS 2 using CLI tools (`ros2 topic pub`, `ros2 action send_goal`) or custom ROS 2 nodes written in Python or C++.
## Additional resources
- [ROS 2 Jazzy documentation](https://docs.ros.org/en/jazzy/index.html) — official documentation for topics, services, action servers, and node development
- [MATLAB Robotics System Toolbox](https://www.mathworks.com/help/ros/index.html?s_tid=CRUX_lftnav) — control the robot through ROS 2 from MATLAB
@@ -0,0 +1,11 @@
# Управление через ROS2
!!! info "Раздел в разработке"
Подробная документация по управлению через ROS2-топики и action-серверы готовится.
Этот способ предполагает прямую отправку команд в ROS2 через CLI-инструменты (`ros2 topic pub`, `ros2 action send_goal`) или написание собственных ROS2-нод на Python/C++.
## Дополнительные ресурсы
- [Документация ROS2 Jazzy](https://docs.ros.org/en/jazzy/index.html) — официальная документация: топики, сервисы, action-серверы, написание нод
- [MATLAB Robotics System Toolbox](https://www.mathworks.com/help/ros/index.html?s_tid=CRUX_lftnav) — управление роботом через ROS2 из MATLAB
@@ -0,0 +1,24 @@
# Getting started
This section explains how to prepare the environment, connect to the controller, install the project, and start controlling the robot.
## Quick start
1. [**Sunrise Workbench setup**](sunrise-setup.md) — prepare the KUKA controller, upload `ServerFriRos2`, and configure the network. *(Physical robot only.)*
2. [**Connect to the server**](remote-access.md) — choose local or remote deployment and connect to the control server over SSH.
3. [**Install the project**](installation.md) — install LWC using `curl`, `git`, or manually.
4. [**Configure the system**](configuration.md) — configure `cobot-setting.yaml` with the robot IP, ports, and tools.
5. [**cobot CLI**](cli-reference.md) — learn the commands for running, building, and updating the project.
!!! tip "Simulation only?"
Skip the physical-controller setup and run `cobot run --simulate` after installation.
## Concepts and control
- [System architecture](concepts/architecture.md)
- [FRI protocol](concepts/fri-protocol.md)
- [Webots simulation](concepts/simulation.md)
- [Motion planning](concepts/motion-planning.md)
- [ROS 2 Control](control/ros2-control.md)
- [Foxglove](control/foxglove.md)
- [REST API](control/rest-api.md)
+48
View File
@@ -0,0 +1,48 @@
# Обзор
**Lightweight Cobot (LWC)** — открытая система управления коллаборативным роботом **KUKA LBR IIWA 7 R800** на базе **ROS 2 Jazzy**. Поддерживает работу как с физическим роботом (через протокол FRI), так и в виртуальной среде (симулятор Webots). В состав проекта входят CLI-инструмент `cobot`, аппаратный интерфейс ROS 2 Control, планировщик движений MoveIt 2 и REST/MCP API для интеграции с AI-агентами.
---
## Репозитории
| Платформа | Ссылка | Статус |
|---|---|---|
| **GitVerse** (предпочтительный) | [daniel-robotics/lightweight-cobot](https://gitverse.ru/daniel-robotics/lightweight-cobot) | основной |
| GitHub | [Daniel-Robotic/lightweight-cobot](https://github.com/Daniel-Robotic/lightweight-cobot) | зеркало |
## Онлайн документация
- [GitVerse Pages](https://daniel-robotics.gitverse.site/lightweight-cobot) — основная
- [GitHub Pages](https://daniel-robotic.github.io/lightweight-cobot/) — зеркало
---
## Предпосылки
- Физический робот **KUKA LBR IIWA 7 R800** — если планируете работу с реальным оборудованием
- Либо желание работать только в симуляторе **Webots** — физический робот не нужен
- ПК или сервер с **Ubuntu 24.04** (или подключение к существующему серверу по SSH)
- Доступ к сети, в которой находится контроллер робота
---
## Порядок шагов
1. [**Настройка SunriseWorkbench**](sunrise-setup.md) — подготовка контроллера KUKA: подключение кабелей, загрузка программы `ServerFriRos2`, настройка сетевых параметров. *(Только для физического робота)*
2. [**Подключение к серверу**](remote-access.md) — выбор варианта развёртывания (локально или удалённо), SSH-подключение к серверу управления.
3. [**Установка проекта**](installation.md) — скачивание и установка LWC через `curl`, `git` или вручную. После установки запустите `cobot setup` — мастер проведёт по оставшимся шагам автоматически.
4. [**Конфигурация системы**](configuration.md) — настройка `cobot-setting.yaml`: IP робота, порты, инструменты. Выполняется на шаге 2 мастера `cobot setup`, либо в любой момент позже через `cobot robot-setup`.
5. [**CLI-инструмент cobot**](cli-reference.md) — все команды управления проектом: запуск, сборка, обновление.
---
!!! tip "Только симуляция?"
Если физический робот недоступен, пропустите шаг 1 и начните сразу с [установки проекта](installation.md). Запустите симулятор командой `cobot run --simulate`.
!!! info "`cobot setup` сделает шаги 3–4 автоматически"
После установки проекта достаточно выполнить `cobot setup` — мастер последовательно предложит: настройку документации, параметры робота (`cobot-setting.yaml`) и выбор среды сборки (ROS2 или Docker).
@@ -0,0 +1,114 @@
# Project installation
## Quick installation
The easiest option is to install the project with a single `curl` command. Make sure that `curl` is installed:
```bash
sudo apt update && sudo apt upgrade -y && sudo apt install curl
```
Go to your home directory and run the installation script:
=== "Stable version (master)"
```bash
cd ~
curl -fsSL https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/master/install.sh | bash
```
=== "Development version (dev)"
```bash
cd ~
curl -fsSL https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/dev/install.sh | bash -s dev
```
---
## Installation with Git
The project is available on both [GitVerse](https://gitverse.ru/daniel-robotics/lightweight-cobot) (preferred) and [GitHub](https://github.com/Daniel-Robotic/lightweight-cobot).
!!! tip "New to Git?"
If this is your first time using Git and GitHub, see the [GitHub getting-started guide](https://docs.github.com/en/get-started/start-your-journey/hello-world).
Clone the repository and run the installation script:
=== "GitVerse"
```bash
cd ~
git clone https://gitverse.ru/daniel-robotics/lightweight-cobot.git
cd ~/lightweight-cobot
sudo chmod +x ./install.sh
./install.sh
```
=== "GitHub"
```bash
cd ~
git clone https://github.com/Daniel-Robotic/lightweight-cobot.git
cd ~/lightweight-cobot
sudo chmod +x ./install.sh
./install.sh
```
---
## Manual installation
If neither `curl` nor `git` is available, download the project archive manually from the repository page using the **Download ZIP** button, extract it, and run:
```bash
cd ~/lightweight-cobot
sudo chmod +x ./install.sh
./install.sh
```
---
## Installation process
The [`install.sh`](https://gitverse.ru/daniel-robotics/lightweight-cobot/raw/branch/master/install.sh) script automatically installs:
- **Git** — version control system;
- **Docker** — containerization for isolated execution;
- **`cobot` CLI** — the main project management tool;
- Ubuntu system dependencies.
### Restarting after installation
After the script finishes, a restart may be required for Docker to work:
```bash
sudo reboot now
```
Watch the terminal output: the script will indicate whether a restart is required.
### If the log is empty
If the script produces no output, reload the Bash environment and continue setup manually:
```bash
source ~/.bashrc # refresh environment variables
cobot setup # continue system setup
```
---
## Verifying the installation
After installation, make sure that `cobot` is available:
```bash
cobot -h
```
If the command displays the list of available subcommands, installation was successful.
---
**Next step:** [System configuration](configuration.md)
@@ -0,0 +1,114 @@
# Установка проекта
## Быстрая установка
Самый простой способ — установить через `curl` одной командой. Убедитесь, что `curl` установлен:
```bash
sudo apt update && sudo apt upgrade -y && sudo apt install curl
```
Перейдите в домашнюю директорию и запустите скрипт установки:
=== "Стабильная версия (master)"
```bash
cd ~
curl -fsSL https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/master/install.sh | bash
```
=== "Dev-версия (dev)"
```bash
cd ~
curl -fsSL https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/dev/install.sh | bash -s dev
```
---
## Установка через Git
Проект доступен как на [GitVerse](https://gitverse.ru/daniel-robotics/lightweight-cobot) (предпочтительно), так и на [GitHub](https://github.com/Daniel-Robotic/lightweight-cobot).
!!! tip "Не знакомы с Git?"
Если вы впервые работаете с Git и GitHub, рекомендуем [прочитать эту статью на Хабре](https://habr.com/ru/companies/yandex_praktikum/articles/700708/) — там всё объясняется с нуля.
Клонируйте репозиторий и запустите скрипт установки:
=== "GitVerse"
```bash
cd ~
git clone https://gitverse.ru/daniel-robotics/lightweight-cobot.git
cd ~/lightweight-cobot
sudo chmod +x ./install.sh
./install.sh
```
=== "GitHub"
```bash
cd ~
git clone https://github.com/Daniel-Robotic/lightweight-cobot.git
cd ~/lightweight-cobot
sudo chmod +x ./install.sh
./install.sh
```
---
## Ручная установка
Если ни `curl`, ни `git` недоступны — скачайте архив проекта вручную со страницы репозитория (кнопка «Скачать ZIP»), разархивируйте и выполните:
```bash
cd ~/lightweight-cobot
sudo chmod +x ./install.sh
./install.sh
```
---
## Процесс установки
Скрипт [`install.sh`](https://gitverse.ru/daniel-robotics/lightweight-cobot/raw/branch/master/install.sh) автоматически установит:
- **Git** — система контроля версий
- **Docker** — контейнеризация для изолированного запуска
- **CLI-инструмент `cobot`** — основной инструмент управления проектом
- Системные зависимости Ubuntu
### Перезагрузка после установки
После завершения скрипта может потребоваться перезагрузка, чтобы заработал Docker:
```bash
sudo reboot now
```
Следите за выводом в терминале — скрипт сам сообщит, нужна ли перезагрузка.
### Если лог пуст
Если после запуска скрипта не выводится никакой информации, обновите среду bash и продолжите настройку вручную:
```bash
source ~/.bashrc # обновление переменных окружения
cobot setup # продолжение настройки системы
```
---
## Проверка установки
После завершения убедитесь, что `cobot` доступен:
```bash
cobot -h
```
Если команда выводит список доступных подкоманд — установка прошла успешно.
---
**Следующий шаг:** [Конфигурация системы](configuration.md)
@@ -0,0 +1,76 @@
# Connecting to the server
## Deployment options
The project can be deployed in two ways:
| Option | Description | When to use it |
|---|---|---|
| **Local** | Install on your PC | Development, simulation, and debugging |
| **Remote (server)** | Install on a dedicated server connected to the KUKA controller | Working with the physical robot |
With remote deployment, you control the server from your PC over an **SSH connection**.
---
## SSH clients
Choose any of the following applications:
- [**Termius**](https://termius.com/) — cross-platform SSH client with a convenient GUI;
- [**MobaXterm**](https://mobaxterm.mobatek.net/) — multifunctional terminal for Windows;
- [**PuTTY**](https://putty.software/) — classic SSH client for Windows;
- the **built-in terminal or command prompt**, as described below.
For instructions on configuring Termius, MobaXterm, or PuTTY, refer to their official documentation.
---
## Connection details
```
IP address: 192.168.21.1
Username: cobot
Password: 12345678
```
!!! warning "Network requirement"
Your PC must be on the **same network/subnet as the robot** (for example, the KnASU network). Otherwise, the connection cannot be established.
---
## Connecting from the built-in terminal
=== "Linux"
Any distribution can be used. Open a terminal and run:
```bash
ssh cobot@192.168.21.1
```
=== "Windows"
**Windows 10** or later is required for the built-in SSH client. Open **Command Prompt** or **PowerShell** and run:
```powershell
ssh cobot@192.168.21.1
```
The command will prompt for a password:
```
cobot@192.168.21.1's password:
```
Enter `12345678`. Characters are not displayed while you type; this is normal security behavior. Press ++enter++.
After a successful connection, the server command prompt appears:
```
cobot@server:~$
```
---
**Next step:** [Project installation](installation.md)
@@ -0,0 +1,78 @@
# Подключение к серверу
## Варианты развёртывания
Проект можно развернуть двумя способами:
| Вариант | Описание | Когда использовать |
|---|---|---|
| **Локально** | Установка на вашем ПК | Разработка, симуляция, отладка |
| **Удалённо (сервер)** | Установка на выделенном сервере, подключённом к контроллеру KUKA | Работа с реальным роботом |
При удалённом варианте вы управляете сервером через **SSH-соединение** со своего ПК.
---
## Программы для SSH-подключения
Выберите любую из программ:
- [**Termius**](https://termius.com/) — кроссплатформенный SSH-клиент с удобным GUI
- [**MobaXterm**](https://mobaxterm.mobatek.net/) — многофункциональный терминал для Windows
- [**PuTTY**](https://putty.software/) — классический SSH-клиент для Windows
- **Встроенный терминал / командная строка** — описано ниже
Инструкции по настройке Termius, MobaXterm и PuTTY смотрите в их официальной документации.
---
## Данные для подключения
```
IP-адрес: 192.168.21.1
Имя пользователя: cobot
Пароль: 12345678
```
!!! warning "Требование к сети"
Ваш ПК должен находиться в **одной сети/подсети с роботом** (например, в сети КнАГУ).
Без этого соединение установить не удастся.
---
## Подключение через встроенный терминал
=== "Linux"
Подойдёт любой дистрибутив. Откройте терминал и выполните:
```bash
ssh cobot@192.168.21.1
```
=== "Windows"
Требуется **Windows 10** или новее (встроенный SSH-клиент).
Откройте **Командную строку** или **PowerShell** и выполните:
```powershell
ssh cobot@192.168.21.1
```
После выполнения команды появится запрос пароля:
```
cobot@192.168.21.1's password:
```
Введите пароль `12345678` — символы не отображаются во время набора, это нормальное поведение из соображений безопасности. Нажмите ++enter++.
При успешном подключении вы увидите приглашение командной строки сервера:
```
cobot@server:~$
```
---
**Следующий шаг:** [Установка проекта](installation.md)
@@ -0,0 +1,85 @@
# SunriseWorkbench setup
!!! info "Physical robot only"
This section applies only when working with a physical KUKA LBR IIWA 7. For simulation, proceed to [Project installation](installation.md).
---
## Physical hardware setup
### Ethernet connection
Connect an Ethernet cable from your PC or control server to one of the KUKA controller's network ports:
- **KLI** (KUKA Line Interface) — the primary port used for control and programming;
- **KONI** (KUKA Optional Network Interface) — the additional port used for FRI.
Both ports can be connected at the same time. You can select the interface when configuring the server.
> Connect the KLI and KONI ports according to the KUKA controller wiring diagram.
---
## Synchronizing the SunriseWorkbench project
### Checking for ServerFriRos2
Make sure that your Sunrise project contains `ServerFriRos2.java`. If the file is missing, download it from the repository. Its path is `src/iiwa_sunrise/src/ServerFriRos2.java`.
=== "curl"
```bash
curl -fsSL https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/master/src/iiwa_sunrise/src/ServerFriRos2.java \
-o ServerFriRos2.java
```
=== "wget"
```bash
wget -O ServerFriRos2.java \
https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/master/src/iiwa_sunrise/src/ServerFriRos2.java
```
After downloading it, add the file to the Sunrise project and synchronize the project with the controller.
### Synchronizing with the controller
Open **SunriseWorkbench** and click the project synchronization button:
> In SunriseWorkbench, use the project synchronization button.
Before synchronizing, make sure that the PC and KUKA controller are on the same network. The current controller network settings can be checked directly in SunriseWorkbench:
> The controller network parameters are available in the SunriseWorkbench settings window.
---
## Configuring ServerFriRos2
Open `ServerFriRos2.java` in SunriseWorkbench and change the following parameters to match your network configuration:
```java
// IP address of the KONI interface
KONI_IP = "192.170.10.10";
// IP address of the KLI interface
KLI_IP = "192.168.21.31";
// Zero position (all joints at 0°)
ZERO_POSITION = {0, 0, 0, 0, 0, 0, 0};
// Working position for monitoring
MONITOR_WORKING_POSITION = {0, 0, 0, -1.57, 0, 1.57, 0};
// Tool used by default
@Named("tool1")
```
!!! warning "Important"
`KONI_IP` and `KLI_IP` in the Java program are addresses of the ROS 2 computer that the controller can reach through the corresponding networks. Conversely, `robot.ip` in `cobot-setting.yaml` is the address of the KUKA controller as seen from the computer. Incorrect or swapped addresses prevent the FRI connection from being established.
After making the changes, synchronize the project with the controller again.
---
**Next step:** [Connecting to the control server](remote-access.md)
@@ -0,0 +1,87 @@
# Настройка SunriseWorkbench
!!! info "Только для физического робота"
Этот раздел актуален только при работе с реальным роботом KUKA LBR IIWA 7.
Для симуляции переходите к [Установке проекта](installation.md).
---
## Настройка физического оборудования
### Подключение Ethernet
Подключите кабель Ethernet от вашего ПК (или сервера управления) к одному из сетевых портов контроллера KUKA:
- **KLI** (KUKA Line Interface) — основной порт, используется для управления и программирования
- **KONI** (KUKA Optional Network Interface) — дополнительный порт, используется для FRI
Вы можете подключить оба порта одновременно — при конфигурации сервера будет выбор, какой интерфейс использовать.
> Подключите порты KLI и KONI согласно схеме подключения контроллера KUKA.
---
## Синхронизация проекта в SunriseWorkbench
### Проверка наличия ServerFriRos2
Убедитесь, что в вашем Sunrise-проекте присутствует файл `ServerFriRos2.java`.
Если файл отсутствует — скачайте его из репозитория. Он находится по пути `src/iiwa_sunrise/src/ServerFriRos2.java`.
=== "curl"
```bash
curl -fsSL https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/master/src/iiwa_sunrise/src/ServerFriRos2.java \
-o ServerFriRos2.java
```
=== "wget"
```bash
wget -O ServerFriRos2.java \
https://gitverse.ru/api/repos/daniel-robotics/lightweight-cobot/raw/branch/master/src/iiwa_sunrise/src/ServerFriRos2.java
```
После скачивания добавьте файл в Sunrise-проект и выполните синхронизацию с контроллером.
### Синхронизация с контроллером
Откройте **SunriseWorkbench** и нажмите кнопку синхронизации проекта:
> В SunriseWorkbench используйте кнопку синхронизации проекта.
Перед синхронизацией убедитесь, что ПК и контроллер KUKA находятся в одной сети. Текущие сетевые параметры контроллера можно быстро проверить прямо в SunriseWorkbench:
> Сетевые параметры контроллера доступны в окне настроек SunriseWorkbench.
---
## Настройка ServerFriRos2
Откройте файл `ServerFriRos2.java` в SunriseWorkbench и измените следующие параметры в соответствии с вашей сетевой конфигурацией:
```java
// IP-адрес интерфейса KONI
KONI_IP = "192.170.10.10";
// IP-адрес интерфейса KLI
KLI_IP = "192.168.21.31";
// Нулевая позиция (все суставы в 0°)
ZERO_POSITION = {0, 0, 0, 0, 0, 0, 0};
// Рабочая позиция для мониторинга
MONITOR_WORKING_POSITION = {0, 0, 0, -1.57, 0, 1.57, 0};
// Инструмент, используемый по умолчанию
@Named("tool1")
```
!!! warning "Важно"
`KONI_IP` и `KLI_IP` в Java-программе — это адреса компьютера с ROS 2, доступные контроллеру через соответствующие сети. Параметр `robot.ip` в `cobot-setting.yaml`, наоборот, содержит адрес контроллера KUKA со стороны компьютера. Неверные или перепутанные адреса не позволят установить FRI-соединение.
После внесения изменений повторно выполните синхронизацию проекта с контроллером.
---
**Следующий шаг:** [Подключение к серверу управления](remote-access.md)
+44
View File
@@ -0,0 +1,44 @@
---
hide:
- navigation
- toc
- footer
---
<meta http-equiv="refresh" content="0; url=./getting-started/">
# Overview
**Lightweight Cobot (LWC)** is an open system for controlling the **KUKA LBR IIWA 7 R800** collaborative robot based on **ROS 2 Jazzy**. It supports both a physical robot through the FRI protocol and a virtual Webots simulation. The project includes the `cobot` CLI, a ROS 2 Control hardware interface, MoveIt 2 motion planning, and REST/MCP APIs for AI-agent integration.
## Repositories
| Platform | Link | Status |
|---|---|---|
| **GitVerse** (preferred) | [daniel-robotics/lightweight-cobot](https://gitverse.ru/daniel-robotics/lightweight-cobot) | primary |
| GitHub | [Daniel-Robotic/lightweight-cobot](https://github.com/Daniel-Robotic/lightweight-cobot) | mirror |
## Online documentation
- [GitVerse Pages](https://daniel-robotics.gitverse.site/lightweight-cobot) — primary
- [GitHub Pages](https://daniel-robotic.github.io/lightweight-cobot/) — mirror
## Requirements
- A physical **KUKA LBR IIWA 7 R800** for real-robot operation, or
- **Webots** if you only want to use simulation;
- A PC or server running **Ubuntu 24.04**, or SSH access to an existing server;
- Network access to the robot controller.
## Recommended order
1. [**Sunrise Workbench setup**](getting-started/sunrise-setup.md) — prepare the KUKA controller. *(Physical robot only.)*
2. [**Connect to the server**](getting-started/remote-access.md) — choose local or remote deployment and connect over SSH.
3. [**Install the project**](getting-started/installation.md) — install LWC using `curl`, `git`, or manually, then run `cobot setup`.
4. [**Configure the system**](getting-started/configuration.md) — set the robot IP, ports, and tools in `cobot-setting.yaml`.
5. [**cobot CLI**](getting-started/cli-reference.md) — review commands for running, building, and updating the project.
!!! tip "Simulation only?"
If a physical robot is unavailable, skip step 1 and start with the [project installation](getting-started/installation.md). Launch the simulator with `cobot run --simulate`.
!!! info "`cobot setup` automates steps 3–4"
After installing the project, run `cobot setup`. The wizard will configure the documentation, robot parameters, and the ROS 2 or Docker build environment.
+8
View File
@@ -0,0 +1,8 @@
---
hide:
- navigation
- toc
- footer
---
<meta http-equiv="refresh" content="0; url=./getting-started/">
+104
View File
@@ -0,0 +1,104 @@
# FIFO priority for FRI
## Why it is needed
FRI exchanges a position command on every cycle. With a 10 ms period, a new packet should be handled about every 10 ms. The regular Linux scheduler can delay the control thread behind other processes. The log then contains messages such as:
```text
Could not enable FIFO RT scheduling: Operation not permitted
Overrun might occur ... Read time: 11500 us
```
`SCHED_FIFO` is Linux scheduling for threads with fixed priority. This project requests priority 50 for `controller_manager` and priority 80 for the FRI worker. The FRI worker receives the higher priority so it can receive a KUKA packet and send the reply on time.
Configure this on the **ROS 2 computer** that runs `cobot run`. It does not require changes to the Sunrise Cabinet or `cobot-setting.yaml`.
## Ubuntu 24.04 setup
On the ROS 2 computer, run these commands as the user who starts `cobot`:
```bash
sudo groupadd -f realtime
sudo usermod -aG realtime "$USER"
sudo tee /etc/security/limits.d/99-ros2-realtime.conf >/dev/null <<'EOF'
@realtime soft rtprio 99
@realtime soft priority 99
@realtime soft memlock unlimited
@realtime hard rtprio 99
@realtime hard priority 99
@realtime hard memlock unlimited
EOF
```
Log out of the desktop session completely and log in again, or reboot. An already open terminal does not receive the new group and limits.
## Verification
In a new terminal, verify the group and limits:
```bash
id -nG | tr ' ' '\n' | grep -x realtime
ulimit -r
ulimit -l
```
The expected output is `realtime`, then `99`, then `unlimited`.
Start FRI without commanding robot motion and check the log for:
```text
FRI worker uses FIFO priority 80
```
You can also inspect the policies of all threads in the process:
```bash
PID=$(pgrep -n ros2_control_node)
ps -L -p "$PID" -o pid,tid,cls,rtprio,pri,comm
```
Realtime threads have `FF` in the `CLS` column. The FRI worker has `RTPRIO` 80 and the `controller_manager` main loop has 50.
!!! warning "Before the first motion"
First confirm that FRI connects and that the log contains `FRI worker uses FIFO priority 80`. Then make a short move at speed 0.1 with an operator supervising. FIFO reduces jitter on the computer; it does not replace network checks, robot limits, or a clear work area.
## If setup does not work
- If `realtime` is missing from `id`, log out and log in again.
- If `ulimit -r` is less than 80, check `/etc/security/limits.d/99-ros2-realtime.conf` and that PAM loads `pam_limits.so`.
- If the log still says `Operation not permitted`, make sure `cobot run` is started by the same user passed to `usermod`.
- A Python virtualenv needs no extra setup: permissions are assigned to the user and inherited by Python.
- Docker requires `--cap-add=sys_nice --ulimit rtprio=99 --ulimit memlock=-1`.
## Rollback
To remove the setup, run:
```bash
sudo rm /etc/security/limits.d/99-ros2-realtime.conf
sudo gpasswd -d "$USER" realtime
```
After logging in again, processes use the regular Linux scheduler.
See the official [ros2_control documentation](https://control.ros.org/jazzy/doc/ros2_control/controller_manager/doc/userdoc.html#determinism) for controller-manager priorities and limits.
## Trajectory limits and smoothness
`controller.moveit.joint_limits` in `cobot-setting.yaml` selects a single limits file for all seven axes, consumed by xacro, FRI, Webots, MoveIt and the web API. Hard position limits and the existing narrower protective bounds remain distinct. Command validation and planning use their intersection; the MoveIt parameter override explicitly preserves soft bounds.
Position and velocity limits were checked against the [KUKA LBR iiwa 7 R800 datasheet, 0000-246-832 V1.2](https://www.kuka.com/-/media/kuka-downloads/imported/8350ff3ca11642998dbdc81dcc2ed44c/0000246832_en.pdf). Working limits were not expanded relative to the previous URDF. Upward rounding beyond published values was removed. **Acceleration and jerk limits remain project settings, not verified KUKA ratings.** Tool/payload and Sunrise settings still require independent verification.
OMPL/CHOMP now run TOTG → rest-boundary normalization → Ruckig → rest-boundary normalization → `iiwa_planning/LimitSplineDynamics` → MoveIt solution validation. The initial requested state must be stationary within `planning.stopped_velocity_tolerance` (rad/s). The spline adapter bounds the complete JTC quintic polynomial in Bernstein form, including extrema between waypoints. It uniformly stretches time and scales derivatives to respect velocity, acceleration and jerk limits, rejecting position overshoot. Endpoint acceleration is normalized around Ruckig because TOTG and Ruckig duration extension can leave nonzero boundary derivatives.
Pilz PTP/LIN/CIRC use the spline validator and uniform time scaling without joint-space Ruckig. This preserves the original JTC interpolation curve, not a new guarantee of ideal Cartesian interpolation. Nonstationary boundary conditions, including some blended sequences, are rejected; this implementation targets rest-to-rest motions.
Position-only CSV/JSON `/trajectory/send*` requests are fitted with a smooth rest-to-rest spline and passed through the same C++ validator. Input waypoints are retained; the curve between them can differ from the former linear interpolation. This direct API does not check collisions. Responses include actual `duration` and `time_scale`; timing may increase. `validate_limits=false` cannot disable mandatory dynamics and operating-range checks.
Direct commands require fresh, complete named joint position/velocity feedback and a stationary robot. The first point at zero time must match the measured position within `web.trajectory_start_tolerance`; otherwise a measured start point is prepended if the first timestamp is positive. Freshness and stationarity are checked again after preparation. `web.trajectory_state_timeout` is in seconds; `web.trajectory_stopped_velocity` is in rad/s. Concurrent direct commands are rejected while a trajectory is reserved; stopping cancels pending preparation.
External clients sending directly to the JTC topic/action bypass this MoveIt/web preparation and remain responsible for their trajectories. This is not a global ROS command firewall. The FRI filter, watchdog and cycle period are unchanged. Hardware retesting is needed to assess noise and actual tracking.
After rebuilding, run `colcon test --packages-select iiwa_planning iiwa_utils iiwa_web iiwa_controller --python-testing pytest`. Tests exercise seven-axis consistency, spline extrema, the installed JTC interpolator, installed TOTG/Ruckig plus pluginlib, and web admission failures without connecting to a real FRI session. Rebuild `iiwa_config`, `iiwa_description` and `iiwa_bringup` as well; running processes do not update automatically.
The adapters check original `/joint_states` telemetry: absent MoveIt `RobotState` velocities are not treated as zero. `planning.state_timeout` bounds telemetry age. The subscription test uses synthetic messages in separate local ROS domain 231, without FRI.
+113
View File
@@ -0,0 +1,113 @@
# FIFO-приоритет для FRI
## Зачем это нужно
FRI передаёт позиционную команду каждый цикл. При выбранном периоде 10 мс новый пакет должен обрабатываться примерно каждые 10 мс. Обычный планировщик Linux может задержать поток другим процессом. В журнале это видно по сообщениям:
```text
Could not enable FIFO RT scheduling: Operation not permitted
Overrun might occur ... Read time: 11500 us
```
`SCHED_FIFO` — политика планировщика Linux для потоков с фиксированным приоритетом. В проекте `controller_manager` запрашивает приоритет 50, а FRI-поток — 80. Поток FRI получает более высокий приоритет, чтобы вовремя принять пакет KUKA и отправить ответ.
Настройку выполняют **на компьютере с ROS 2**, с которого запускается `cobot run`. Sunrise Cabinet и `cobot-setting.yaml` менять для этого не нужно.
## Настройка Ubuntu 24.04
Выполните на компьютере с ROS 2 под пользователем, который запускает `cobot`:
```bash
sudo groupadd -f realtime
sudo usermod -aG realtime "$USER"
sudo tee /etc/security/limits.d/99-ros2-realtime.conf >/dev/null <<'EOF'
@realtime soft rtprio 99
@realtime soft priority 99
@realtime soft memlock unlimited
@realtime hard rtprio 99
@realtime hard priority 99
@realtime hard memlock unlimited
EOF
```
Затем полностью выйдите из графического сеанса и войдите снова либо перезагрузите компьютер. Открытый терминал не получает новую группу и лимиты.
## Проверка
В новом терминале проверьте группу и лимиты:
```bash
id -nG | tr ' ' '\n' | grep -x realtime
ulimit -r
ulimit -l
```
Ожидаемый результат: первая команда выводит `realtime`, вторая — `99`, третья — `unlimited`.
Запустите FRI без движения робота и убедитесь, что в журнале есть:
```text
FRI worker uses FIFO priority 80
```
После запуска можно дополнительно посмотреть политики всех потоков процесса:
```bash
PID=$(pgrep -n ros2_control_node)
ps -L -p "$PID" -o pid,tid,cls,rtprio,pri,comm
```
Для потоков реального времени в столбце `CLS` будет `FF`; у FRI-потока `RTPRIO` равен 80, у основного цикла `controller_manager` — 50.
!!! warning "Перед первым движением"
Сначала проверьте успешное подключение FRI и строку `FRI worker uses FIFO priority 80`. Затем выполните короткое перемещение на скорости 0.1 при наблюдении оператора. FIFO уменьшает jitter компьютера, но не отменяет контроль сети, ограничений робота и рабочей зоны.
## Если настройка не сработала
- Если `realtime` отсутствует в выводе `id`, выйдите из системы и войдите снова.
- Если `ulimit -r` меньше 80, проверьте файл `/etc/security/limits.d/99-ros2-realtime.conf` и наличие `pam_limits.so` в конфигурации PAM.
- Если лог всё ещё сообщает `Operation not permitted`, убедитесь, что `cobot run` запущен тем же пользователем, для которого выполнен `usermod`.
- В Python virtualenv дополнительных действий не требуется: права задаются пользователю и наследуются процессом Python.
- Для Docker нужны права контейнера: `--cap-add=sys_nice --ulimit rtprio=99 --ulimit memlock=-1`.
## Откат
Чтобы удалить настройку, выполните:
```bash
sudo rm /etc/security/limits.d/99-ros2-realtime.conf
sudo gpasswd -d "$USER" realtime
```
После повторного входа процессы снова будут работать с обычным планировщиком Linux.
Подробнее о лимитах и приоритете `controller_manager` — в [документации ros2_control](https://control.ros.org/jazzy/doc/ros2_control/controller_manager/doc/userdoc.html#determinism).
## Ограничения траекторий и плавность
`controller.moveit.joint_limits` из `cobot-setting.yaml` задаёт единый файл для всех семи осей. Его читают URDF/xacro, FRI, Webots, MoveIt и web API. `min_position/max_position` описывают рабочие жёсткие пределы; `soft_min_position/soft_max_position` сохраняют более узкие защитные диапазоны. Планирование, командные интерфейсы и проверка API используют пересечение этих диапазонов. При загрузке MoveIt пересечение применяется явно: YAML иначе может переопределить мягкие пределы URDF.
Диапазоны и скорости сверены с [листом KUKA LBR iiwa 7 R800, 0000-246-832 V1.2](https://www.kuka.com/-/media/kuka-downloads/imported/8350ff3ca11642998dbdc81dcc2ed44c/0000246832_en.pdf). Для осей A1…A7 паспортные диапазоны составляют ±170°, ±120°, ±170°, ±120°, ±170°, ±120°, ±175°; скорости с номинальной нагрузкой — 98, 98, 100, 130, 140, 180, 180°/с. Рабочие пределы не расширены относительно прежнего URDF: округления, превышавшие паспортные значения, уменьшены. **Ускорения и рывки в YAML остаются ограничениями проекта, а не подтверждёнными паспортными пределами KUKA.** Данные установленного инструмента, нагрузки и настройки Sunrise по этому листу не проверяются.
Для OMPL/CHOMP обработка выполняется в порядке:
1. TOTG назначает время движения.
2. `iiwa_planning/SetRestBoundary` проверяет скорость исходного состояния и задаёт нулевые скорости/ускорения на концах движения из покоя.
3. Ruckig сглаживает траекторию с ограничением рывка.
4. Повторная установка граничных условий устраняет изменения производных, которые может внести продление длительности в Ruckig.
5. `iiwa_planning/LimitSplineDynamics` проверяет весь квинтический сплайн JTC, включая промежутки между точками. Границы полиномов вычисляются в базисе Бернштейна, а не только по временной сетке. При превышении скорости, ускорения или рывка увеличивается время всей траектории; скорости и ускорения масштабируются согласованно. Выход позиции за рабочие пределы отклоняется.
6. MoveIt проверяет решение на столкновения обычным адаптером `ValidateSolution`.
Pilz PTP/LIN/CIRC проходят проверку сплайна и равномерное увеличение длительности без Ruckig в суставном пространстве. При этом сохраняется исходная кривая интерполяции JTC; точность геометрии LIN/CIRC относительно непрерывного идеального пути отдельно не улучшается. Движения с ненулевыми граничными скоростями/ускорениями (включая некоторые варианты blending) отклоняются: проверка предназначена для перемещений из покоя в покой. `planning.stopped_velocity_tolerance` задаёт порог определения неподвижного начального состояния в рад/с.
CSV/JSON `/trajectory/send*` по-прежнему принимают позиции и время, но теперь строят гладкий сплайн с нулевыми граничными производными и проходят тот же C++-валидатор. Промежуточные точки сохраняются, однако кривая между ними может отличаться от прежней линейной интерполяции. Прямой API не выполняет проверку столкновений. Ответ возвращает фактические `duration` и `time_scale`; времена могут увеличиться. `validate_limits=false` не отключает обязательную проверку динамики и рабочего диапазона.
Перед отправкой требуется свежая обратная связь с именами осей, положениями и скоростями; робот должен быть неподвижен. Точка при `t=0` должна совпадать с текущим положением в пределах `web.trajectory_start_tolerance`. Если первая точка позже нуля, текущее положение добавляется в начало. `web.trajectory_state_timeout` ограничивает возраст состояния; `web.trajectory_stopped_velocity` — начальную скорость. Состояние повторно проверяется после расчёта. Повторная прямая отправка во время активной траектории отклоняется; остановка отменяет ещё не завершённую подготовку.
Внешний ROS-клиент, публикующий прямо в топик JTC или отправляющий ему action, **обходит подготовку MoveIt/web**. Он обязан самостоятельно формировать корректные траектории; это изменение не является общей защитой от произвольных ROS-команд. FRI-фильтр, watchdog и период обмена не менялись. Повторное аппаратное испытание необходимо для оценки шума и фактического слежения.
### Проверка без оборудования
После сборки можно выполнить `colcon test --packages-select iiwa_planning iiwa_utils iiwa_web iiwa_controller --python-testing pytest`. Тесты проверяют согласованность семи осей в реальном и симуляционном URDF, пики между точками, результат установленного интерполятора JTC, связку установленного TOTG/Ruckig с pluginlib и отклонение устаревшего состояния web. Они не подключаются к реальному FRI-сеансу. Для нового кода требуется пересборка перечисленных пакетов и `iiwa_config`, `iiwa_description`, `iiwa_bringup`; старый запущенный процесс автоматически не обновляется.
Проверка покоя в адаптерах подписывается на исходный `/joint_states`: отсутствие скоростей в `RobotState` MoveIt не трактуется как нулевая скорость. `planning.state_timeout` ограничивает возраст исходной телеметрии. Тест подписки использует отдельный локальный ROS domain 231 и синтетические сообщения, без FRI.
Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 212 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

Some files were not shown because too many files have changed in this diff Show More