robotframework-plugins 2026.11.0.dev1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. robotframework_plugins/__init__.py +14 -0
  2. robotframework_plugins/_assets/catalog.json +143 -0
  3. robotframework_plugins/_assets/plugins/rf-agentskills/.claude-plugin/plugin.json +25 -0
  4. robotframework_plugins/_assets/plugins/rf-agentskills/CHANGELOG.md +198 -0
  5. robotframework_plugins/_assets/plugins/rf-agentskills/README.md +27 -0
  6. robotframework_plugins/_assets/plugins/rf-agentskills/catalog.yaml +25 -0
  7. robotframework_plugins/_assets/plugins/rf-api/.claude-plugin/plugin.json +25 -0
  8. robotframework_plugins/_assets/plugins/rf-api/CHANGELOG.md +9 -0
  9. robotframework_plugins/_assets/plugins/rf-api/README.md +27 -0
  10. robotframework_plugins/_assets/plugins/rf-api/catalog.yaml +27 -0
  11. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/SKILL.md +110 -0
  12. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/assets/examples/authentication-patterns.robot +39 -0
  13. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/assets/examples/basic-crud.robot +46 -0
  14. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/assets/examples/file-upload.robot +28 -0
  15. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/assets/examples/session-handling.robot +48 -0
  16. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/references/authentication.md +58 -0
  17. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/references/install.md +10 -0
  18. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/references/request-options.md +90 -0
  19. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/references/response-validation.md +64 -0
  20. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/references/troubleshooting.md +64 -0
  21. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/SKILL.md +119 -0
  22. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/assets/examples/basic-rest.robot +51 -0
  23. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/assets/examples/schema-validation.robot +38 -0
  24. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/assets/examples/schemas/user.json +10 -0
  25. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/references/authentication.md +61 -0
  26. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/references/install.md +11 -0
  27. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/references/json-handling.md +89 -0
  28. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/references/migrate-from-requests.md +15 -0
  29. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/references/schema-validation.md +85 -0
  30. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/references/troubleshooting.md +68 -0
  31. robotframework_plugins/_assets/plugins/rf-core/.claude-plugin/plugin.json +19 -0
  32. robotframework_plugins/_assets/plugins/rf-core/CHANGELOG.md +11 -0
  33. robotframework_plugins/_assets/plugins/rf-core/README.md +38 -0
  34. robotframework_plugins/_assets/plugins/rf-core/agents/rf-debug-expert.md +104 -0
  35. robotframework_plugins/_assets/plugins/rf-core/agents/rf-migration-guide.md +73 -0
  36. robotframework_plugins/_assets/plugins/rf-core/agents/rf-test-architect.md +98 -0
  37. robotframework_plugins/_assets/plugins/rf-core/catalog.yaml +19 -0
  38. robotframework_plugins/_assets/plugins/rf-core/hooks/README.md +435 -0
  39. robotframework_plugins/_assets/plugins/rf-core/hooks/hooks.json +70 -0
  40. robotframework_plugins/_assets/plugins/rf-core/scripts/_hook_input.mjs +101 -0
  41. robotframework_plugins/_assets/plugins/rf-core/scripts/_pending_errors.mjs +65 -0
  42. robotframework_plugins/_assets/plugins/rf-core/scripts/_python_env.mjs +181 -0
  43. robotframework_plugins/_assets/plugins/rf-core/scripts/check_rf_environment.mjs +181 -0
  44. robotframework_plugins/_assets/plugins/rf-core/scripts/maybe_inject_rf_context.mjs +74 -0
  45. robotframework_plugins/_assets/plugins/rf-core/scripts/maybe_remind_robot_tests.mjs +108 -0
  46. robotframework_plugins/_assets/plugins/rf-core/scripts/report_pending_errors.mjs +72 -0
  47. robotframework_plugins/_assets/plugins/rf-core/scripts/rf_error_hints.mjs +126 -0
  48. robotframework_plugins/_assets/plugins/rf-core/scripts/validate_robot.mjs +509 -0
  49. robotframework_plugins/_assets/plugins/rf-core/scripts/validate_robot_project.mjs +103 -0
  50. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/SKILL.md +313 -0
  51. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/resources/api.resource +30 -0
  52. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/resources/calc.resource +23 -0
  53. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/resources/embedded.resource +20 -0
  54. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/resources/keywords.resource +26 -0
  55. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/resources/login.resource +10 -0
  56. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/tests/01__keyword_driven.robot +15 -0
  57. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/tests/02__data_driven.robot +10 -0
  58. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/tests/03__templates.robot +17 -0
  59. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/tests/04__bdd.robot +10 -0
  60. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/tests/05__embedded.robot +13 -0
  61. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/tests/__init__.robot +6 -0
  62. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/tests/api/__init__.robot +7 -0
  63. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/tests/api/users.robot +18 -0
  64. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/tests/env.robot +15 -0
  65. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/variables/common.py +11 -0
  66. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/variables/dev.yaml +3 -0
  67. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/variables/staging.yaml +3 -0
  68. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/references/arguments.md +139 -0
  69. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/references/control-structures.md +175 -0
  70. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/references/embedded-arguments.md +135 -0
  71. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/references/migration.md +90 -0
  72. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/references/resources-and-variable-files.md +127 -0
  73. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/references/styles.md +92 -0
  74. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/references/suites-and-init.md +96 -0
  75. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/references/tags-and-selection.md +104 -0
  76. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/references/templates.md +124 -0
  77. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/references/variables-and-scopes.md +129 -0
  78. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/scripts/rf_conventions.py +883 -0
  79. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/SKILL.md +216 -0
  80. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/assets/examples/ExampleLibrary.py +61 -0
  81. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/assets/examples/ResultListener.py +60 -0
  82. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/assets/examples/converters.py +48 -0
  83. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/assets/examples/converters.robot +20 -0
  84. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/assets/examples/example_library.robot +31 -0
  85. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/assets/examples/listener.robot +12 -0
  86. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/references/api-variants.md +291 -0
  87. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/references/communication.md +248 -0
  88. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/references/conversion.md +347 -0
  89. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/references/listeners.md +150 -0
  90. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/references/packaging-and-docs.md +155 -0
  91. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/scripts/check_library.py +842 -0
  92. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/SKILL.md +159 -0
  93. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/assets/examples/github-actions-robot.yml +32 -0
  94. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/assets/examples/gitignore.txt +22 -0
  95. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/assets/examples/pyproject.poetry.toml +28 -0
  96. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/assets/examples/pyproject.uv.toml +20 -0
  97. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/assets/examples/requirements.txt +9 -0
  98. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/assets/examples/robot.toml +16 -0
  99. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/assets/examples/smoke.robot +22 -0
  100. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/references/ci.md +61 -0
  101. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/references/cli-tools.md +33 -0
  102. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/references/libraries.md +47 -0
  103. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/references/poetry.md +77 -0
  104. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/references/project-layout.md +86 -0
  105. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/references/troubleshooting.md +73 -0
  106. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/references/uv.md +108 -0
  107. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/references/venv-pip.md +71 -0
  108. robotframework_plugins/_assets/plugins/rf-core/variants/codex/agents/rf-debug-expert.toml +103 -0
  109. robotframework_plugins/_assets/plugins/rf-core/variants/codex/agents/rf-migration-guide.toml +72 -0
  110. robotframework_plugins/_assets/plugins/rf-core/variants/codex/agents/rf-test-architect.toml +97 -0
  111. robotframework_plugins/_assets/plugins/rf-core/variants/opencode/agents/rf-debug-expert.md +107 -0
  112. robotframework_plugins/_assets/plugins/rf-core/variants/opencode/agents/rf-migration-guide.md +76 -0
  113. robotframework_plugins/_assets/plugins/rf-core/variants/opencode/agents/rf-test-architect.md +101 -0
  114. robotframework_plugins/_assets/plugins/rf-core/variants/opencode/plugins/rf-core.js +93 -0
  115. robotframework_plugins/_assets/plugins/rf-desktop/.claude-plugin/plugin.json +24 -0
  116. robotframework_plugins/_assets/plugins/rf-desktop/CHANGELOG.md +9 -0
  117. robotframework_plugins/_assets/plugins/rf-desktop/README.md +26 -0
  118. robotframework_plugins/_assets/plugins/rf-desktop/catalog.yaml +23 -0
  119. robotframework_plugins/_assets/plugins/rf-desktop/skills/rf-platynui/SKILL.md +266 -0
  120. robotframework_plugins/_assets/plugins/rf-desktop/skills/rf-platynui/assets/examples/calculator.robot +45 -0
  121. robotframework_plugins/_assets/plugins/rf-desktop/skills/rf-platynui/assets/examples/mock-deterministic.robot +33 -0
  122. robotframework_plugins/_assets/plugins/rf-desktop/skills/rf-platynui/references/cli-and-inspector.md +82 -0
  123. robotframework_plugins/_assets/plugins/rf-desktop/skills/rf-platynui/references/install.md +14 -0
  124. robotframework_plugins/_assets/plugins/rf-desktop/skills/rf-platynui/references/keywords-reference.md +102 -0
  125. robotframework_plugins/_assets/plugins/rf-desktop/skills/rf-platynui/references/locators-and-queries.md +95 -0
  126. robotframework_plugins/_assets/plugins/rf-desktop/skills/rf-platynui/references/platform-setup.md +65 -0
  127. robotframework_plugins/_assets/plugins/rf-desktop/skills/rf-platynui/references/status-and-migration.md +41 -0
  128. robotframework_plugins/_assets/plugins/rf-mobile/.claude-plugin/plugin.json +24 -0
  129. robotframework_plugins/_assets/plugins/rf-mobile/CHANGELOG.md +9 -0
  130. robotframework_plugins/_assets/plugins/rf-mobile/README.md +26 -0
  131. robotframework_plugins/_assets/plugins/rf-mobile/catalog.yaml +23 -0
  132. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/SKILL.md +134 -0
  133. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/assets/examples/android-basic.robot +60 -0
  134. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/assets/examples/gestures-example.robot +59 -0
  135. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/assets/examples/hybrid-app.robot +54 -0
  136. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/assets/examples/ios-basic.robot +48 -0
  137. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/references/capabilities.md +117 -0
  138. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/references/gestures-touch.md +84 -0
  139. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/references/install.md +21 -0
  140. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/references/locators-mobile.md +74 -0
  141. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/references/platform-specific.md +105 -0
  142. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/references/troubleshooting.md +70 -0
  143. robotframework_plugins/_assets/plugins/rf-web/.claude-plugin/plugin.json +25 -0
  144. robotframework_plugins/_assets/plugins/rf-web/CHANGELOG.md +9 -0
  145. robotframework_plugins/_assets/plugins/rf-web/README.md +27 -0
  146. robotframework_plugins/_assets/plugins/rf-web/catalog.yaml +27 -0
  147. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/SKILL.md +132 -0
  148. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/assets/examples/authentication-flow.robot +34 -0
  149. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/assets/examples/basic-web-test.robot +29 -0
  150. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/assets/examples/form-handling.robot +49 -0
  151. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/assets/examples/iframe-shadow-dom.robot +31 -0
  152. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/references/assertion-engine.md +79 -0
  153. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/references/authentication-storage.md +86 -0
  154. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/references/browser-context-page.md +110 -0
  155. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/references/downloads-uploads.md +51 -0
  156. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/references/iframes-shadow-dom.md +67 -0
  157. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/references/install.md +67 -0
  158. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/references/locators.md +83 -0
  159. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/references/migrate-from-selenium.md +22 -0
  160. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/references/troubleshooting.md +100 -0
  161. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/SKILL.md +123 -0
  162. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/assets/examples/basic-web-test.robot +64 -0
  163. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/assets/examples/multi-window.robot +55 -0
  164. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/assets/examples/wait-patterns.robot +53 -0
  165. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/references/browser-setup.md +103 -0
  166. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/references/frames-windows.md +84 -0
  167. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/references/install.md +12 -0
  168. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/references/javascript-execution.md +65 -0
  169. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/references/locators.md +86 -0
  170. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/references/troubleshooting.md +122 -0
  171. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/references/waiting-strategies.md +84 -0
  172. robotframework_plugins/_assets.py +120 -0
  173. robotframework_plugins/_catalog.py +123 -0
  174. robotframework_plugins/_snapshot.py +230 -0
  175. robotframework_plugins/adapters/__init__.py +53 -0
  176. robotframework_plugins/adapters/_base.py +400 -0
  177. robotframework_plugins/adapters/claude_code.py +312 -0
  178. robotframework_plugins/adapters/claude_desktop.py +129 -0
  179. robotframework_plugins/adapters/codex.py +276 -0
  180. robotframework_plugins/adapters/copilot.py +87 -0
  181. robotframework_plugins/adapters/cursor.py +295 -0
  182. robotframework_plugins/adapters/goose.py +240 -0
  183. robotframework_plugins/adapters/opencode.py +170 -0
  184. robotframework_plugins/bundle.py +85 -0
  185. robotframework_plugins/cli.py +1311 -0
  186. robotframework_plugins/detect.py +121 -0
  187. robotframework_plugins/manifest.py +338 -0
  188. robotframework_plugins/py.typed +0 -0
  189. robotframework_plugins/skillzip.py +39 -0
  190. robotframework_plugins/transforms.py +725 -0
  191. robotframework_plugins-2026.11.0.dev1.dist-info/METADATA +178 -0
  192. robotframework_plugins-2026.11.0.dev1.dist-info/RECORD +195 -0
  193. robotframework_plugins-2026.11.0.dev1.dist-info/WHEEL +4 -0
  194. robotframework_plugins-2026.11.0.dev1.dist-info/entry_points.txt +2 -0
  195. robotframework_plugins-2026.11.0.dev1.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,1311 @@
1
+ """Console-script entrypoint: ``rf-agentskills <subcommand> ...``.
2
+
3
+ The CLI wires four moving pieces together:
4
+
5
+ 1. ``adapters`` — per-agent plan() builders.
6
+ 2. ``manifest`` — the JSON record of what this machine has installed.
7
+ 3. ``transforms`` — pure transforms used by the adapters and re-used
8
+ here only for ``${CLAUDE_PLUGIN_ROOT}`` substitution display in
9
+ --dry-run.
10
+ 4. argparse — subcommand dispatch.
11
+
12
+ Subcommands implemented:
13
+
14
+ * ``install`` — write files, perform config merges, remove files a
15
+ previous install wrote that the bundle no longer
16
+ ships (hash-checked), update manifest.
17
+ * ``uninstall`` — read manifest, remove only matching files (skipping
18
+ user-edited ones), revert config merges.
19
+ * ``list`` — show the manifest.
20
+ * ``targets`` — show which adapters detect their target on this machine.
21
+ * ``doctor`` — combined health check (assets, manifest, adapters,
22
+ unowned legacy skill directories — reported, never deleted).
23
+ * ``version`` — print bundle version.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import json
30
+ import os
31
+ import sys
32
+ from dataclasses import replace
33
+ from pathlib import Path
34
+ from typing import Sequence
35
+
36
+ from rich.console import Console
37
+ from rich.table import Table
38
+
39
+ from . import __version__, _assets, detect as _detect, manifest as _m
40
+ from .adapters import ALL_ADAPTERS, all_names, by_name
41
+ from .adapters._base import (
42
+ Adapter,
43
+ ConfigMergeOp,
44
+ InstallOptions,
45
+ InstallPlan,
46
+ InstallTarget,
47
+ )
48
+
49
+
50
+ console = Console()
51
+ err_console = Console(stderr=True)
52
+
53
+
54
+ # ---------------------------------------------------------------------------
55
+ # argparse
56
+ # ---------------------------------------------------------------------------
57
+
58
+
59
+ def _build_parser() -> argparse.ArgumentParser:
60
+ parser = argparse.ArgumentParser(
61
+ prog="robotframework-plugins",
62
+ description="Cross-agent installer for Robot Framework agent plugins.",
63
+ )
64
+ parser.add_argument(
65
+ "--version", action="version", version=f"robotframework-plugins {__version__}"
66
+ )
67
+ sub = parser.add_subparsers(dest="cmd", required=True)
68
+
69
+ # install ---------------------------------------------------------------
70
+ sp = sub.add_parser("install", help="Install Robot Framework plugins into one or more agents.")
71
+ grp = sp.add_mutually_exclusive_group(required=False)
72
+ grp.add_argument("--agent", choices=all_names(), help="Single agent (back-compat).")
73
+ grp.add_argument("--all", action="store_true", help="Every detected agent (back-compat).")
74
+ grp.add_argument(
75
+ "--agents",
76
+ metavar="SEL",
77
+ help="Selection: 'all' (every known agent), 'none', 'detected', "
78
+ "or a comma-separated list of agent ids. Omit for the interactive "
79
+ "wizard (or detected agents when non-interactive).",
80
+ )
81
+ sp.add_argument("--scope", choices=("project", "user"), default="project",
82
+ help="Install scope (default: project).")
83
+ sp.add_argument("--project", type=Path, help="Project directory for --scope project (default: CWD).")
84
+ sp.add_argument("--prefix", type=Path, help="Override install root (used by tests).")
85
+ sp.add_argument(
86
+ "--what",
87
+ default="skills,agents,hooks",
88
+ help="Comma-separated subset of skills,agents,hooks (default: all). "
89
+ "'mcp' is accepted for compatibility and ignored: the bundle no "
90
+ "longer ships an MCP server.",
91
+ )
92
+ sp.add_argument(
93
+ "--mode",
94
+ choices=("files", "plugin"),
95
+ default="files",
96
+ help="files (default): copy skills/agents/hooks. plugin: point the agent at the "
97
+ "robotframework-plugins marketplace (committed settings for project "
98
+ "scope); agents without a marketplace fall back to files.",
99
+ )
100
+ sp.add_argument("--ref", help="With --mode plugin: pin the marketplace to this git tag/branch.")
101
+ sp.add_argument(
102
+ "--plugins",
103
+ metavar="NAMES",
104
+ help="Comma-separated plugins to install (see `robotframework-plugins catalog`), or "
105
+ "'all' for every active verified plugin. Default: on an upgrade, the plugins that "
106
+ "cover what is installed; otherwise rf-core plus the plugins for the libraries the "
107
+ "project declares (pyproject.toml, requirements*.txt), or every verified plugin "
108
+ "when it declares none.",
109
+ )
110
+ sp.add_argument("--yes", "-y", action="store_true",
111
+ help="Accept the detected default without prompting.")
112
+ sp.add_argument("--no-input", action="store_true",
113
+ help="Never prompt; fail instead of asking (CI).")
114
+ sp.add_argument("--dry-run", action="store_true", help="Show plan without writing.")
115
+ sp.add_argument("--force", action="store_true", help="Overwrite user-modified files.")
116
+
117
+ # uninstall -------------------------------------------------------------
118
+ sp = sub.add_parser("uninstall", help="Remove a previous install (manifest-tracked).")
119
+ sp.add_argument("--agent", choices=all_names(), required=True)
120
+ sp.add_argument("--scope", choices=("project", "user"), default="project",
121
+ help="Install scope (default: project).")
122
+ sp.add_argument("--project", type=Path, help="Project directory for --scope project (default: CWD).")
123
+ sp.add_argument("--dry-run", action="store_true")
124
+
125
+ # list ------------------------------------------------------------------
126
+ sub.add_parser("list", help="Show what the manifest records as installed.")
127
+
128
+ # targets ---------------------------------------------------------------
129
+ sub.add_parser("targets", help="Show which agents are detected on this machine.")
130
+
131
+ # doctor ----------------------------------------------------------------
132
+ sub.add_parser("doctor", help="Health check (assets, adapters, manifest).")
133
+
134
+ # version ---------------------------------------------------------------
135
+ sub.add_parser("version", help="Print bundle version.")
136
+
137
+ # catalog ---------------------------------------------------------------
138
+ sp = sub.add_parser("catalog", help="List the plugins bundled in this installer.")
139
+ sp.add_argument("--json", action="store_true", help="Print the catalogue as JSON.")
140
+
141
+ return parser
142
+
143
+
144
+ # ---------------------------------------------------------------------------
145
+ # Command implementations
146
+ # ---------------------------------------------------------------------------
147
+
148
+
149
+ def _opts_from_args(args: argparse.Namespace) -> InstallOptions:
150
+ what = frozenset(s.strip() for s in str(args.what).split(",") if s.strip())
151
+ if "mcp" in what:
152
+ err_console.print(
153
+ "[yellow]note:[/yellow] --what mcp is ignored — the rf-tools MCP server "
154
+ "was removed; the skills run their scripts directly."
155
+ )
156
+ what = what - {"mcp"}
157
+ project = args.project
158
+ if args.scope == "project" and project is None:
159
+ project = Path.cwd()
160
+ return InstallOptions(
161
+ scope=args.scope,
162
+ project_dir=project,
163
+ prefix=args.prefix,
164
+ what=what,
165
+ dry_run=getattr(args, "dry_run", False),
166
+ force=getattr(args, "force", False),
167
+ mode=getattr(args, "mode", "files") or "files",
168
+ ref=getattr(args, "ref", None),
169
+ )
170
+
171
+
172
+ def _manifest_path(opts: InstallOptions) -> Path:
173
+ """Where this install's manifest lives — per scope (project-local for
174
+ project scope, global for user). ``--prefix`` overrides only the install
175
+ *root*, not the manifest, so install/uninstall stay symmetric and the
176
+ manifest never lands inside the install tree."""
177
+ return _m.manifest_path_for(opts.scope, opts.project_dir)
178
+
179
+
180
+ def _detected_names() -> list[str]:
181
+ return [cls().name for cls in ALL_ADAPTERS if cls().detect()]
182
+
183
+
184
+ class _SelectionError(ValueError):
185
+ """Raised for an invalid --agents value."""
186
+
187
+
188
+ def _explicit_selection(args: argparse.Namespace) -> list[str] | None:
189
+ """Resolve an explicit selection from flags, or None if none was given.
190
+
191
+ Returns a (possibly empty) list of agent names. An empty list ('none')
192
+ is distinct from None ('no flag given' → wizard / detected fallback).
193
+ """
194
+ if getattr(args, "agent", None):
195
+ return [args.agent]
196
+ if getattr(args, "all", False):
197
+ return _detected_names()
198
+ sel = getattr(args, "agents", None)
199
+ if sel is None:
200
+ return None
201
+ token = sel.strip().lower()
202
+ if token == "all":
203
+ return list(all_names())
204
+ if token == "none":
205
+ return []
206
+ if token == "detected":
207
+ return _detected_names()
208
+ names = [s.strip() for s in sel.split(",") if s.strip()]
209
+ unknown = [n for n in names if n not in all_names()]
210
+ if unknown:
211
+ raise _SelectionError(
212
+ f"unknown agent(s): {', '.join(unknown)}. "
213
+ f"valid: {', '.join(all_names())}"
214
+ )
215
+ return names
216
+
217
+
218
+ def _is_interactive(args: argparse.Namespace) -> bool:
219
+ """Prompt only on a real TTY and when not opted out via --yes/--no-input."""
220
+ if getattr(args, "no_input", False) or getattr(args, "yes", False):
221
+ return False
222
+ try:
223
+ return sys.stdin.isatty()
224
+ except (ValueError, OSError):
225
+ return False
226
+
227
+
228
+ # ---------------------------------------------------------------------------
229
+ # Plugin selection
230
+ # ---------------------------------------------------------------------------
231
+
232
+
233
+ class _PluginError(Exception):
234
+ pass
235
+
236
+
237
+ def _default_plugins(catalog: list[dict]) -> list[str]:
238
+ """Every active verified plugin with content, in catalogue order (a bundle
239
+ adds nothing its dependencies don't)."""
240
+ return [p["name"] for p in catalog
241
+ if p.get("status") == "active" and p.get("tier") == "verified" and not _assets.is_bundle(p)]
242
+
243
+
244
+ def _resolve_plugins(args: argparse.Namespace, catalog: list[dict]) -> list[str] | None:
245
+ """Plugins named by ``--plugins``; ``None`` when the flag is absent.
246
+
247
+ Raises :class:`_PluginError` for a name the installer doesn't bundle
248
+ (unknown, or removed from the catalogue).
249
+ """
250
+ raw = getattr(args, "plugins", None)
251
+ if raw is None:
252
+ return None
253
+ if raw.strip().lower() == "all":
254
+ return _default_plugins(catalog)
255
+ names = [n.strip() for n in raw.split(",") if n.strip()]
256
+ known = {p["name"] for p in catalog}
257
+ unknown = [n for n in names if n not in known]
258
+ if unknown or not names:
259
+ what = ", ".join(unknown) if unknown else "(none given)"
260
+ raise _PluginError(
261
+ f"unknown or removed plugin: {what}. Available: {', '.join(sorted(known)) or '(none)'}"
262
+ )
263
+ return list(dict.fromkeys(names))
264
+
265
+
266
+ def _skill_owners(catalog: list[dict]) -> dict[str, str]:
267
+ """``{skill folder: plugin}`` over the bundled content plugins."""
268
+ owners: dict[str, str] = {}
269
+ for p in catalog:
270
+ if _assets.is_bundle(p):
271
+ continue
272
+ try:
273
+ with _assets.asset_root_path(p["name"]) as root:
274
+ for md in (root / "skills").glob("*/SKILL.md"):
275
+ owners.setdefault(md.parent.name, p["name"])
276
+ except (FileNotFoundError, OSError):
277
+ continue
278
+ return owners
279
+
280
+
281
+ def _upgrade_selection(manifest_path: Path, agents: list[str], scope: str, catalog: list[dict]) -> list[str]:
282
+ """Plugins that cover an earlier file-mode install of ``agents``.
283
+
284
+ A record written by robotframework-plugins names each file's plugin. An
285
+ older record (rf-agentskills 0.8.0 or earlier) does not: its skills are
286
+ mapped to the plugin that ships them now, and ``rf-core`` covers the
287
+ subagents and hooks."""
288
+ try:
289
+ manifest = _m.Manifest.load(manifest_path)
290
+ except (OSError, ValueError):
291
+ return []
292
+ known = {p["name"]: p for p in catalog}
293
+ owners = _skill_owners(catalog)
294
+ chosen: list[str] = []
295
+
296
+ def add(name: str) -> None:
297
+ for n in _assets.expand_bundles([name], catalog):
298
+ if n in known and n not in chosen:
299
+ chosen.append(n)
300
+
301
+ for agent in agents:
302
+ inst = manifest.for_agent(agent, scope)
303
+ if inst is None:
304
+ continue
305
+ for entry in inst.files:
306
+ if entry.plugin and not _assets.is_bundle(known.get(entry.plugin, {})):
307
+ add(entry.plugin)
308
+ continue
309
+ parts = Path(entry.path).parts
310
+ if _m.entry_category(entry) == "skills" and "skills" in parts:
311
+ skill = parts[parts.index("skills") + 1] if parts.index("skills") + 1 < len(parts) else ""
312
+ if skill in owners:
313
+ add(owners[skill])
314
+ continue
315
+ add(_assets.DEFAULT_PLUGIN)
316
+ return [p["name"] for p in catalog if p["name"] in chosen]
317
+
318
+
319
+ def _default_selection(args: argparse.Namespace, catalog: list[dict], selection: list[str]) -> list[str]:
320
+ """``--plugins`` absent: an upgrade keeps what the install covers; a fresh
321
+ install takes rf-core plus what the project declares (spec plugin-split)."""
322
+ opts = _opts_from_args(args)
323
+ previous = _upgrade_selection(_manifest_path(opts), selection, opts.scope, catalog)
324
+ project = opts.project_dir if opts.project_dir is not None else Path.cwd()
325
+ found = _detect.detect(project, catalog)
326
+ if previous:
327
+ # Keep everything installed; add the plugins for libraries the project
328
+ # declares since (the SessionStart report points users here).
329
+ added = [n for n in found.plugins if found.detected and n not in previous]
330
+ chosen = [p["name"] for p in catalog if p["name"] in previous or p["name"] in added]
331
+ note = f"; adds {', '.join(added)} for the project's libraries" if added else ""
332
+ console.print(f"[dim]plugins:[/dim] {', '.join(chosen)} (upgrade: they cover what is installed{note}; "
333
+ "narrow with --plugins)")
334
+ return chosen
335
+ if found.detected:
336
+ why = "; ".join(f"{name}: {', '.join(f'{pkg} ({src})' for pkg, src in pkgs)}"
337
+ for name, pkgs in found.reasons.items())
338
+ console.print(f"[dim]plugins:[/dim] {', '.join(found.plugins)} (rf-core, plus the project's "
339
+ f"libraries: {why})")
340
+ else:
341
+ console.print(f"[dim]plugins:[/dim] {', '.join(found.plugins)} (no library detected in {project}; "
342
+ "installing every verified plugin)")
343
+ return found.plugins
344
+
345
+
346
+ def _warn_deprecated(names: list[str], catalog: list[dict]) -> None:
347
+ by_name_ = {p["name"]: p for p in catalog}
348
+ for n in names:
349
+ p = by_name_.get(n, {})
350
+ if p.get("status") == "deprecated":
351
+ err_console.print(
352
+ f"[yellow]warn:[/yellow] {n} is deprecated since {p.get('deprecated_since', '?')}; "
353
+ f"use {p.get('replacement', 'its replacement')} instead."
354
+ )
355
+
356
+
357
+ def _plugin_label(p: dict) -> str:
358
+ status = "" if p.get("status") == "active" else f", {p.get('status')}"
359
+ return f"{p['name']} ({p.get('tier', '?')}{status}): {p.get('summary', '')}"
360
+
361
+
362
+ def _select_plugins_interactively(catalog: list[dict], default: list[str]) -> list[str] | None:
363
+ """Plugin step of the wizard; questionary if available, else stdlib fallback."""
364
+ try:
365
+ import questionary # optional [interactive] extra
366
+ except ImportError:
367
+ console.print("Select plugins (comma/space-separated numbers; Enter = marked):")
368
+ for i, p in enumerate(catalog, 1):
369
+ mark = "*" if p["name"] in default else " "
370
+ console.print(f" [{mark}] {i}. {_plugin_label(p)}")
371
+ try:
372
+ raw = input("> ").strip()
373
+ except EOFError:
374
+ return default
375
+ if not raw:
376
+ return default
377
+ picks: list[str] = []
378
+ for tok in raw.replace(",", " ").split():
379
+ if tok.isdigit() and 1 <= int(tok) <= len(catalog):
380
+ name = catalog[int(tok) - 1]["name"]
381
+ if name not in picks:
382
+ picks.append(name)
383
+ return picks
384
+ return questionary.checkbox(
385
+ "Select plugins to install:",
386
+ choices=[questionary.Choice(_plugin_label(p), value=p["name"], checked=p["name"] in default)
387
+ for p in catalog],
388
+ ).ask()
389
+
390
+
391
+ def cmd_catalog(args: argparse.Namespace) -> int:
392
+ catalog = _assets.bundled_catalog()
393
+ if getattr(args, "json", False):
394
+ print(json.dumps({"installer": __version__, "plugins": [
395
+ {k: p.get(k) for k in ("name", "version", "tier", "status", "summary")}
396
+ | {"bundle": bool(p.get("bundle")), "bundled": list(p.get("bundled", [])),
397
+ "dependencies": list(p.get("dependencies", []))}
398
+ | ({"replacement": p["replacement"]} if "replacement" in p else {})
399
+ for p in catalog
400
+ ]}, indent=2))
401
+ return 0
402
+ table = Table(title=f"robotframework-plugins {__version__} bundles")
403
+ for col in ("plugin", "version", "tier", "status", "summary"):
404
+ table.add_column(col)
405
+ for p in catalog:
406
+ status = p.get("status", "?")
407
+ if status == "deprecated":
408
+ status = f"deprecated, use {p.get('replacement', '?')}"
409
+ table.add_row(p["name"], str(p.get("version") or "-"), p.get("tier", "?"), status, p.get("summary", ""))
410
+ console.print(table)
411
+ return 0
412
+
413
+
414
+ def _select_agents_interactively(detected: list[str]) -> list[str] | None:
415
+ """Multi-select wizard; questionary if available, else stdlib fallback.
416
+
417
+ Returns the chosen agent names, or None if the user cancelled.
418
+ """
419
+ choices = list(all_names())
420
+ try:
421
+ import questionary # optional [interactive] extra
422
+ except ImportError:
423
+ return _select_agents_stdlib(detected, choices)
424
+ answer = questionary.checkbox(
425
+ "Select agents to install Robot Framework plugins into:",
426
+ choices=[
427
+ questionary.Choice(
428
+ f"{by_name(n)().pretty} ({n})",
429
+ value=n,
430
+ checked=n in detected,
431
+ )
432
+ for n in choices
433
+ ],
434
+ ).ask()
435
+ return answer # None when cancelled (Ctrl-C/Esc)
436
+
437
+
438
+ def _select_agents_stdlib(detected: list[str], choices: list[str]) -> list[str] | None:
439
+ """Dependency-free numbered selector used when questionary is absent."""
440
+ console.print("Select agents (comma/space-separated numbers; Enter = detected):")
441
+ for i, n in enumerate(choices, 1):
442
+ mark = "*" if n in detected else " "
443
+ console.print(f" [{mark}] {i}. {by_name(n)().pretty} ({n})")
444
+ try:
445
+ raw = input("> ").strip()
446
+ except EOFError:
447
+ return detected
448
+ if not raw:
449
+ return detected
450
+ picks: list[str] = []
451
+ for tok in raw.replace(",", " ").split():
452
+ if tok.isdigit() and 1 <= int(tok) <= len(choices):
453
+ name = choices[int(tok) - 1]
454
+ if name not in picks:
455
+ picks.append(name)
456
+ return picks
457
+
458
+
459
+ def cmd_install(args: argparse.Namespace) -> int:
460
+ # 1. Resolve selection: explicit flags → wizard (TTY) → detected fallback.
461
+ try:
462
+ selection = _explicit_selection(args)
463
+ except _SelectionError as exc:
464
+ err_console.print(f"[red]error:[/red] {exc}")
465
+ return 2
466
+
467
+ if selection is None:
468
+ if _is_interactive(args):
469
+ selection = _select_agents_interactively(_detected_names())
470
+ if selection is None:
471
+ console.print("[dim]cancelled[/dim]")
472
+ return 0
473
+ else:
474
+ selection = _detected_names()
475
+ if not selection:
476
+ err_console.print(
477
+ "[red]error:[/red] no agents detected and none selected."
478
+ )
479
+ err_console.print(f"valid agents: {', '.join(all_names())}")
480
+ err_console.print(
481
+ "pass --agents all|detected|<csv>, or --agent <name>."
482
+ )
483
+ return 1
484
+
485
+ if not selection:
486
+ console.print("[dim]nothing selected — nothing to install[/dim]")
487
+ return 0
488
+
489
+ catalog = _assets.bundled_catalog()
490
+ try:
491
+ plugins = _resolve_plugins(args, catalog)
492
+ except _PluginError as exc:
493
+ err_console.print(f"[red]error:[/red] {exc}")
494
+ return 2
495
+ explicit = plugins is not None
496
+ if plugins is None:
497
+ plugins = _default_selection(args, catalog, selection)
498
+ if _is_interactive(args) and len(catalog) > 1:
499
+ plugins = _select_plugins_interactively(catalog, plugins)
500
+ if plugins is None:
501
+ console.print("[dim]cancelled[/dim]")
502
+ return 0
503
+ if not plugins:
504
+ console.print("[dim]no plugin selected — nothing to install[/dim]")
505
+ return 0
506
+ _warn_deprecated(plugins, catalog)
507
+
508
+ opts = replace(_opts_from_args(args), plugins=tuple(plugins), plugin=plugins[0], plugins_explicit=explicit)
509
+ # File mode copies content per plugin: a bundle there means the plugins it bundles.
510
+ file_plugins = tuple(_assets.expand_bundles(plugins, catalog))
511
+ if opts.ref and opts.mode != "plugin":
512
+ err_console.print("[red]error:[/red] --ref needs --mode plugin")
513
+ return 2
514
+ manifest_path = _manifest_path(opts)
515
+
516
+ rc = 0
517
+ for name in selection:
518
+ cls = by_name(name)
519
+ if cls is None:
520
+ err_console.print(f"[red]error:[/red] unknown agent {name!r}")
521
+ rc = max(rc, 2)
522
+ continue
523
+ adapter = cls()
524
+ agent_opts = opts
525
+ plan = adapter.plugin_plan(opts) if opts.mode == "plugin" else None
526
+ if plan is None:
527
+ if opts.mode == "plugin":
528
+ console.print(
529
+ f"[dim]{adapter.name}:[/dim] no plugin marketplace for {adapter.pretty} — "
530
+ "installing files instead."
531
+ )
532
+ agent_opts = replace(opts, mode="files", plugins=file_plugins, plugin=file_plugins[0])
533
+ plan = _plan_plugins(adapter, agent_opts)
534
+ if opts.dry_run:
535
+ _render_plan_dry_run(adapter, plan, agent_opts, manifest_path)
536
+ continue
537
+ rc |= _execute_plan(adapter, plan, agent_opts, manifest_path)
538
+ if agent_opts.mode == "plugin":
539
+ rc |= _run_plugin_commands(adapter, agent_opts, run=bool(getattr(args, "yes", False)))
540
+ return rc
541
+
542
+
543
+ def _plan_plugins(adapter: Adapter, opts: InstallOptions) -> InstallPlan:
544
+ """One plan covering every plugin in ``opts.plugins``.
545
+
546
+ The adapter plans each plugin on its own; the parts are joined so that
547
+ the stale-file pass sees the whole install and doesn't remove one
548
+ plugin's files while installing another. Each file records its plugin.
549
+ """
550
+ targets: list[InstallTarget] = []
551
+ merges: list[ConfigMergeOp] = []
552
+ notes: list[str] = []
553
+ for plugin in opts.plugins:
554
+ part = adapter.plan(replace(opts, plugin=plugin))
555
+ targets.extend(replace(t, plugin=plugin) for t in part.targets)
556
+ merges.extend(part.merges)
557
+ notes.extend(n for n in part.notes if n not in notes)
558
+ return InstallPlan(targets=tuple(targets), merges=tuple(merges), notes=tuple(notes))
559
+
560
+
561
+ def _run_plugin_commands(adapter: Adapter, opts: InstallOptions, *, run: bool) -> int:
562
+ """Run the adapter's per-user plugin commands (only with --yes)."""
563
+ commands = adapter.plugin_commands(opts) if hasattr(adapter, "plugin_commands") else []
564
+ if not commands or not run:
565
+ return 0
566
+ import shutil
567
+ import subprocess
568
+
569
+ if shutil.which(commands[0][0]) is None:
570
+ err_console.print(f"[yellow]warn:[/yellow] {commands[0][0]} not on PATH — run the commands above yourself.")
571
+ return 0
572
+ for cmd in commands:
573
+ console.print(f" [dim]$[/dim] {' '.join(cmd)}")
574
+ res = subprocess.run(cmd, check=False)
575
+ if res.returncode != 0:
576
+ err_console.print(f"[red]error:[/red] `{' '.join(cmd)}` exited {res.returncode}")
577
+ return 1
578
+ return 0
579
+
580
+
581
+ def _revert_merge(merge: _m.ConfigMerge) -> None:
582
+ """Undo one recorded config merge.
583
+
584
+ Reconstructs deletion from kind + key_path + added_keys: the in-process
585
+ ``revert`` callback isn't reachable from a fresh CLI invocation.
586
+ """
587
+ from . import transforms as _x
588
+
589
+ path = Path(merge.path)
590
+ if not path.is_file():
591
+ return
592
+ try:
593
+ if merge.kind == "json_top":
594
+ _x.remove_json_keys(path, merge.added_keys)
595
+ elif merge.kind == "json_nested":
596
+ _x.remove_json_keys_at_path(path, key_path=merge.key_path, keys=merge.added_keys)
597
+ elif merge.kind == "json_hooks":
598
+ _x.remove_owned_hook_entries(
599
+ path,
600
+ marker=merge.marker or "",
601
+ events=merge.added_keys,
602
+ top_key=merge.key_path[0] if merge.key_path else "hooks",
603
+ )
604
+ elif merge.kind == "toml_table":
605
+ _x.remove_toml_table(path, merge.key_path)
606
+ elif merge.kind == "yaml_block":
607
+ _x.remove_yaml_keys(
608
+ path, merge.added_keys,
609
+ parent_key=merge.key_path[0] if merge.key_path else None,
610
+ )
611
+ else:
612
+ err_console.print(
613
+ f"[yellow]warn:[/yellow] unknown merge kind {merge.kind!r} for {path} — skipping revert"
614
+ )
615
+ except Exception as exc:
616
+ err_console.print(f"[yellow]warn:[/yellow] revert {path}: {exc}")
617
+
618
+
619
+ def cmd_uninstall(args: argparse.Namespace) -> int:
620
+ project = args.project
621
+ if args.scope == "project" and project is None:
622
+ project = Path.cwd()
623
+ manifest_path = _m.manifest_path_for(args.scope, project)
624
+
625
+ manifest = _m.Manifest.load(manifest_path)
626
+ record = manifest.for_agent(args.agent, args.scope)
627
+ if record is None:
628
+ err_console.print(
629
+ f"[yellow]nothing to do:[/yellow] no manifest entry for "
630
+ f"agent={args.agent!r} scope={args.scope!r}"
631
+ )
632
+ return 0
633
+
634
+ removed_files: list[str] = []
635
+ skipped_files: list[str] = []
636
+ for entry in record.files:
637
+ p = Path(entry.path)
638
+ if not p.is_file():
639
+ continue
640
+ if _m.is_user_modified(entry):
641
+ skipped_files.append(str(p))
642
+ continue
643
+ if not args.dry_run:
644
+ try:
645
+ p.unlink()
646
+ _m.prune_empty_parents(p)
647
+ except OSError as exc:
648
+ err_console.print(f"[yellow]warn:[/yellow] {p}: {exc}")
649
+ removed_files.append(str(p))
650
+
651
+ if not args.dry_run:
652
+ for merge in record.config_merges:
653
+ _revert_merge(merge)
654
+
655
+ if not args.dry_run:
656
+ manifest.remove(args.agent, args.scope)
657
+ manifest.save(manifest_path)
658
+
659
+ table = Table(title=f"uninstall {args.agent} ({args.scope})")
660
+ table.add_column("removed", style="green")
661
+ table.add_column("skipped (user-edited)", style="yellow")
662
+ rows = max(len(removed_files), len(skipped_files))
663
+ for i in range(rows):
664
+ table.add_row(
665
+ removed_files[i] if i < len(removed_files) else "",
666
+ skipped_files[i] if i < len(skipped_files) else "",
667
+ )
668
+ if rows == 0:
669
+ table.add_row("(nothing to remove)", "")
670
+ console.print(table)
671
+ if args.dry_run:
672
+ console.print("[dim](dry run — no files actually removed)[/dim]")
673
+ return 0
674
+
675
+
676
+ def cmd_list(_args: argparse.Namespace) -> int:
677
+ # Show the global (user-scope) manifest plus the project-local manifest
678
+ # in the current directory, if any (project installs live in-repo).
679
+ installs = list(_m.Manifest.load().iter_agents())
680
+ proj_manifest = Path.cwd() / ".rf-agentskills" / "installed.json"
681
+ if proj_manifest.is_file():
682
+ installs.extend(_m.Manifest.load(proj_manifest).iter_agents())
683
+ if not installs:
684
+ console.print("[dim]no installations recorded[/dim]")
685
+ return 0
686
+ table = Table(title="robotframework-plugins installations")
687
+ table.add_column("agent")
688
+ table.add_column("scope")
689
+ table.add_column("bundle")
690
+ table.add_column("installed_at")
691
+ table.add_column("files")
692
+ for ins in installs:
693
+ table.add_row(
694
+ ins.agent,
695
+ ins.scope,
696
+ ins.bundle_version,
697
+ ins.installed_at,
698
+ str(len(ins.files)),
699
+ )
700
+ console.print(table)
701
+ return 0
702
+
703
+
704
+ def cmd_targets(_args: argparse.Namespace) -> int:
705
+ table = Table(title="agent detection")
706
+ table.add_column("agent")
707
+ table.add_column("display")
708
+ table.add_column("detected")
709
+ for cls in ALL_ADAPTERS:
710
+ adapter = cls()
711
+ table.add_row(
712
+ adapter.name,
713
+ adapter.pretty,
714
+ "[green]yes[/green]" if adapter.detect() else "[dim]no[/dim]",
715
+ )
716
+ console.print(table)
717
+ return 0
718
+
719
+
720
+ # ---------------------------------------------------------------------------
721
+ # Legacy skill directories (content < 2.0.0)
722
+ # ---------------------------------------------------------------------------
723
+
724
+ # Directory names earlier bundles used for skills. Since content 2.0.0 every
725
+ # skill has one identifier, ``rf-<topic>``, in every channel. Re-installing
726
+ # prunes the old directories this installer recorded; ``doctor`` only warns
727
+ # about the ones it does not own (e.g. copied by hand from a release tarball).
728
+ _LEGACY_TOPICS = (
729
+ "appium", "browser", "keyword-builder", "libdoc-explain", "libdoc-search",
730
+ "platynui", "requests", "resource-architect", "restinstance", "results",
731
+ "robotcode", "selenium", "setup", "testcase-builder",
732
+ )
733
+ LEGACY_SKILL_DIRS: frozenset[str] = frozenset(
734
+ # old Claude Code plugin / installer short names
735
+ set(_LEGACY_TOPICS)
736
+ # old root / standalone-tarball directory names
737
+ | {f"robotframework-{t}-skill" for t in _LEGACY_TOPICS if t not in ("results", "libdoc-search", "libdoc-explain")}
738
+ | {"robotframework-results", "robotframework-libdoc-search", "robotframework-libdoc-explain"}
739
+ )
740
+ # ``name:`` values those directories carried (short plugin names, and the
741
+ # rf-* names the root/standalone copies already used).
742
+ LEGACY_SKILL_NAMES: frozenset[str] = frozenset(
743
+ set(_LEGACY_TOPICS) | {f"rf-{t}" for t in _LEGACY_TOPICS}
744
+ )
745
+
746
+ # Skills retired in content 3.0.0: the robotcode CLI (robotcode doc / results)
747
+ # and the RobotCode project's own `robotcode` plugin cover them. Installs that
748
+ # recorded them prune them as stale; copies made by hand are reported.
749
+ RETIRED_SKILL_DIRS: frozenset[str] = frozenset({"rf-robotcode", "rf-libdoc", "rf-results"})
750
+ RETIRED_SKILL_REPLACEMENT = {
751
+ "rf-robotcode": "the robotcode plugin (robotcode@robotframework-agent-plugins)",
752
+ "rf-libdoc": "`robotcode doc keywords` / `robotcode doc keyword`",
753
+ "rf-results": "`robotcode results`",
754
+ }
755
+
756
+
757
+ def _skill_md_name(skill_md: Path) -> str | None:
758
+ try:
759
+ text = skill_md.read_text(encoding="utf-8", errors="replace")
760
+ except OSError:
761
+ return None
762
+ if not text.startswith("---"):
763
+ return None
764
+ for line in text.splitlines()[1:]:
765
+ if line.strip() == "---":
766
+ break
767
+ if line.startswith("name:"):
768
+ return line.split(":", 1)[1].strip().strip("\"'")
769
+ return None
770
+
771
+
772
+ def _skill_folders() -> list[Path]:
773
+ """Every skills folder an adapter installs into (user and project scope),
774
+ derived from the adapters' own plans so it never drifts from them."""
775
+ folders: set[Path] = set()
776
+ for scope in ("user", "project"):
777
+ opts = InstallOptions(scope=scope, project_dir=Path.cwd(), what=frozenset({"skills"}))
778
+ for cls in ALL_ADAPTERS:
779
+ try:
780
+ plan = cls().plan(opts)
781
+ except Exception: # pragma: no cover - defensive; doctor must not crash
782
+ continue
783
+ for target in plan.targets:
784
+ dst = Path(target.dst)
785
+ if dst.name == "SKILL.md" and _m.category_for_path(dst) == "skills":
786
+ folders.add(dst.parent.parent)
787
+ return sorted(folders)
788
+
789
+
790
+ def _owned_paths() -> list[Path]:
791
+ paths: list[Path] = []
792
+ for mpath in (_m.default_manifest_path(), _m.manifest_path_for("project", Path.cwd())):
793
+ try:
794
+ for ins in _m.Manifest.load(mpath).iter_agents():
795
+ paths.extend(Path(f.path) for f in ins.files)
796
+ except Exception: # pragma: no cover - unreadable manifest is reported elsewhere
797
+ continue
798
+ return paths
799
+
800
+
801
+ def find_legacy_skill_dirs() -> list[Path]:
802
+ """Unowned legacy rf-agentskills skill dirs in any adapter's skills folder.
803
+
804
+ A directory is reported only if its name is a known legacy name, its
805
+ SKILL.md ``name:`` is one of our old names and mentions Robot Framework
806
+ (so someone else's ``browser`` skill is left alone), and no manifest
807
+ records a file inside it.
808
+ """
809
+ owned = _owned_paths()
810
+ found: list[Path] = []
811
+ for folder in _skill_folders():
812
+ for name in sorted(LEGACY_SKILL_DIRS | RETIRED_SKILL_DIRS):
813
+ d = folder / name
814
+ skill_md = d / "SKILL.md"
815
+ if not skill_md.is_file():
816
+ continue
817
+ if _skill_md_name(skill_md) not in LEGACY_SKILL_NAMES | RETIRED_SKILL_DIRS:
818
+ continue
819
+ try:
820
+ if "robot" not in skill_md.read_text(encoding="utf-8", errors="replace").lower():
821
+ continue
822
+ except OSError:
823
+ continue
824
+ if any(p == d or d in p.parents for p in owned):
825
+ continue
826
+ found.append(d)
827
+ return found
828
+
829
+
830
+ def _legacy_dir_warning(d: Path) -> str:
831
+ if d.name in RETIRED_SKILL_DIRS:
832
+ return (
833
+ f"[yellow]warn:[/yellow] {d} is the {d.name} skill, retired in content 3.0.0 "
834
+ f"(use {RETIRED_SKILL_REPLACEMENT[d.name]}); rf-agentskills did not install this copy, "
835
+ f"so it was kept. Remove it with: rm -r \"{d}\""
836
+ )
837
+ return (
838
+ f"[yellow]warn:[/yellow] {d} is a pre-2.0 rf-agentskills skill directory "
839
+ f"(renamed to rf-<topic> in content 2.0.0) that rf-agentskills did not install; "
840
+ f"remove it with: rm -r \"{d}\""
841
+ )
842
+
843
+
844
+ def cmd_doctor(_args: argparse.Namespace) -> int:
845
+ rc = 0
846
+ table = Table(title="robotframework-plugins doctor")
847
+ table.add_column("check")
848
+ table.add_column("status")
849
+ table.add_column("details")
850
+
851
+ # 1. Bundled assets present.
852
+ try:
853
+ with _assets.asset_root_path() as root:
854
+ n = sum(1 for _ in _assets.asset_files())
855
+ table.add_row(
856
+ "bundled assets",
857
+ "[green]ok[/green]" if n > 0 else "[red]MISSING[/red]",
858
+ f"root={root} files={n}",
859
+ )
860
+ if n == 0:
861
+ rc = 1
862
+ except Exception as exc:
863
+ table.add_row("bundled assets", "[red]ERROR[/red]", str(exc))
864
+ rc = 1
865
+
866
+ # 2. Manifest readable.
867
+ try:
868
+ manifest = _m.Manifest.load()
869
+ table.add_row(
870
+ "manifest",
871
+ "[green]ok[/green]",
872
+ f"path={_m.default_manifest_path()} entries={len(manifest.installations)}",
873
+ )
874
+ except Exception as exc:
875
+ table.add_row("manifest", "[red]ERROR[/red]", str(exc))
876
+ rc = 1
877
+
878
+ # 3. Per-adapter detection.
879
+ for cls in ALL_ADAPTERS:
880
+ adapter = cls()
881
+ ok = adapter.detect()
882
+ table.add_row(
883
+ f"adapter:{adapter.name}",
884
+ "[green]detected[/green]" if ok else "[dim]not detected[/dim]",
885
+ adapter.pretty,
886
+ )
887
+
888
+ # 4. Legacy skill directories from pre-2.0 bundles that we do not own.
889
+ legacy = find_legacy_skill_dirs()
890
+ table.add_row(
891
+ "legacy skill dirs",
892
+ "[yellow]warn[/yellow]" if legacy else "[green]ok[/green]",
893
+ f"{len(legacy)} unowned legacy or retired skill dir(s)" if legacy else "none found",
894
+ )
895
+
896
+ console.print(table)
897
+ for d in legacy:
898
+ err_console.print(_legacy_dir_warning(d))
899
+ return rc
900
+
901
+
902
+ def cmd_version(_args: argparse.Namespace) -> int:
903
+ """Print the installer version and the version of each bundled plugin.
904
+
905
+ The two are versioned independently on purpose (see RELEASING.md): the
906
+ installer's ``__version__`` tracks adapter / CLI / manifest changes; each
907
+ plugin has its own version in its ``plugin.json``. Both are printed so
908
+ support tickets and triage can be precise without requiring alignment.
909
+ """
910
+ console.print(f"robotframework-plugins {__version__}")
911
+ plugins = [p for p in _assets.bundled_catalog() if p.get("version")]
912
+ if plugins:
913
+ console.print("bundled plugins: " + ", ".join(f"{p['name']} {p['version']}" for p in plugins), soft_wrap=True)
914
+ return 0
915
+
916
+
917
+ # ---------------------------------------------------------------------------
918
+ # plan execution / rendering
919
+ # ---------------------------------------------------------------------------
920
+
921
+
922
+ # ---------------------------------------------------------------------------
923
+ # stale-file pruning on re-install
924
+ # ---------------------------------------------------------------------------
925
+
926
+
927
+ #: MCP server that installers before content 2.0.0 registered for every agent.
928
+ #: The bundle no longer ships it; re-installing removes its config entries
929
+ #: and files (see :func:`_retire_legacy_mcp` and :func:`_is_retired_file`).
930
+ RETIRED_MCP_SERVER = "rf-tools"
931
+ #: Agents whose only support files (``rf-agentskills-files/``) served that
932
+ #: server; for the others the folder still holds hook scripts (OpenCode's
933
+ #: hook plugin runs them since marketplace-distribution).
934
+ _SUPPORT_FOR_MCP_ONLY = frozenset({"claude-desktop", "goose"})
935
+
936
+
937
+ def _is_retired_file(entry: _m.FileEntry, agent: str) -> bool:
938
+ """A file an older install wrote only for the retired MCP server."""
939
+ parts = Path(entry.path).parts
940
+ if _m.SUPPORT_DIR_NAME not in parts:
941
+ return False # only rf-agentskills ever shipped the rf-tools server
942
+ rel = parts[parts.index(_m.SUPPORT_DIR_NAME) + 1:]
943
+ return agent in _SUPPORT_FOR_MCP_ONLY or (bool(rel) and rel[0] == "servers")
944
+
945
+
946
+ def _is_retired_merge(merge: _m.ConfigMerge) -> bool:
947
+ return RETIRED_MCP_SERVER in merge.added_keys or RETIRED_MCP_SERVER in merge.key_path
948
+
949
+
950
+ def _retire_legacy_mcp(merges: Sequence[_m.ConfigMerge], *, dry_run: bool = False) -> tuple[
951
+ list[_m.ConfigMerge], list[str]
952
+ ]:
953
+ """Remove the ``rf-tools`` entries older installs merged into agent configs.
954
+
955
+ Returns the merges still tracked (other keys of a partly retired merge
956
+ stay recorded) and the config files that were cleaned.
957
+ """
958
+ from . import transforms as _x
959
+
960
+ kept: list[_m.ConfigMerge] = []
961
+ cleaned: list[str] = []
962
+ for merge in merges:
963
+ if not _is_retired_merge(merge):
964
+ kept.append(merge)
965
+ continue
966
+ path = Path(merge.path)
967
+ if path.is_file() and not dry_run:
968
+ try:
969
+ if merge.kind == "toml_table":
970
+ _x.remove_toml_table(path, list(merge.key_path))
971
+ elif merge.kind == "yaml_block":
972
+ _x.remove_yaml_keys(
973
+ path, [RETIRED_MCP_SERVER],
974
+ parent_key=merge.key_path[0] if merge.key_path else None,
975
+ )
976
+ elif path.name == "mcp.json" and path.parent.name == ".vscode":
977
+ # Copilot wrote VS Code's {"servers": {...}} shape.
978
+ _x.remove_json_keys_at_path(path, ["servers"], [RETIRED_MCP_SERVER])
979
+ elif merge.key_path:
980
+ _x.remove_json_keys_at_path(
981
+ path, list(merge.key_path), [RETIRED_MCP_SERVER]
982
+ )
983
+ else:
984
+ _x.remove_json_keys(path, [RETIRED_MCP_SERVER])
985
+ except Exception as exc: # pragma: no cover - defensive
986
+ err_console.print(f"[yellow]warn:[/yellow] remove {RETIRED_MCP_SERVER} from {path}: {exc}")
987
+ kept.append(merge)
988
+ continue
989
+ if path.is_file():
990
+ cleaned.append(str(path))
991
+ rest = [k for k in merge.added_keys if k != RETIRED_MCP_SERVER]
992
+ if rest and merge.kind != "toml_table":
993
+ kept.append(_m.ConfigMerge(
994
+ path=merge.path, added_keys=rest, kind=merge.kind,
995
+ key_path=list(merge.key_path), marker=merge.marker,
996
+ ))
997
+ return kept, cleaned
998
+
999
+
1000
+ def _partition_previous(
1001
+ previous: _m.Installation | None,
1002
+ plan: InstallPlan,
1003
+ opts: InstallOptions,
1004
+ ) -> tuple[list[_m.FileEntry], list[_m.FileEntry]]:
1005
+ """Split the previous record's files into (stale, carried).
1006
+
1007
+ * A previous file that is a target of the new plan is neither: it is
1008
+ re-written and re-recorded.
1009
+ * **stale** — not in the new plan and its category is being installed
1010
+ now (a category in ``--what``, or one the new plan writes, e.g. the
1011
+ shared ``support`` files). The bundle no longer ships it.
1012
+ * **carried** — its category is not part of this install (e.g. agents
1013
+ during ``--what skills``). It stays on disk and stays tracked.
1014
+ """
1015
+ if previous is None:
1016
+ return [], []
1017
+ new_paths = {str(t.dst) for t in plan.targets}
1018
+ in_scope = set(opts.what) | {_m.category_for_path(t.dst) for t in plan.targets}
1019
+ stale: list[_m.FileEntry] = []
1020
+ carried: list[_m.FileEntry] = []
1021
+ for entry in previous.files:
1022
+ if entry.path in new_paths:
1023
+ continue
1024
+ if _m.entry_category(entry) in in_scope or _is_retired_file(entry, previous.agent):
1025
+ stale.append(entry)
1026
+ else:
1027
+ carried.append(entry)
1028
+ return stale, carried
1029
+
1030
+
1031
+ def _prune_stop(path: Path, install_root: Path | None) -> Path:
1032
+ """Directory at which empty-parent pruning stops (exclusive).
1033
+
1034
+ The install root when ``path`` lives under it; otherwise the nearest
1035
+ ``skills`` ancestor (Codex / Goose skills live outside the root, under
1036
+ ``~/.agents/skills``); otherwise the file's own directory (no pruning).
1037
+ """
1038
+ if install_root is not None:
1039
+ try:
1040
+ path.relative_to(install_root)
1041
+ return install_root
1042
+ except ValueError:
1043
+ pass
1044
+ for parent in path.parents:
1045
+ if parent.name == "skills":
1046
+ return parent
1047
+ return path.parent
1048
+
1049
+
1050
+ def _remove_stale(
1051
+ stale: Sequence[_m.FileEntry],
1052
+ install_root: Path | None,
1053
+ ) -> tuple[list[str], list[str]]:
1054
+ """Delete hash-matching stale files; return (removed, kept_user_modified)."""
1055
+ removed: list[str] = []
1056
+ kept: list[str] = []
1057
+ for entry in stale:
1058
+ p = Path(entry.path)
1059
+ if not p.is_file():
1060
+ continue
1061
+ if _m.is_user_modified(entry):
1062
+ kept.append(str(p))
1063
+ continue
1064
+ try:
1065
+ p.unlink()
1066
+ _m.prune_empty_parents(p, stop_at=_prune_stop(p, install_root))
1067
+ removed.append(str(p))
1068
+ except OSError as exc:
1069
+ err_console.print(f"[yellow]warn:[/yellow] {p}: {exc}")
1070
+ return removed, kept
1071
+
1072
+
1073
+ def _removed_skills(removed: Sequence[str], written: Sequence[_m.FileEntry]) -> list[str]:
1074
+ """Skill folders this run removed entirely (none of their files was written),
1075
+ e.g. after narrowing with ``--plugins``."""
1076
+ def skill_of(path: str) -> str | None:
1077
+ parts = Path(path).parts
1078
+ if _m.support_dir_index(parts) is not None or "skills" not in parts[:-1]:
1079
+ return None
1080
+ i = len(parts) - 1 - parts[::-1].index("skills")
1081
+ return parts[i + 1] if i + 1 < len(parts) - 1 else None
1082
+ kept = {skill_of(e.path) for e in written}
1083
+ return sorted({s for s in map(skill_of, removed) if s and s not in kept})
1084
+
1085
+
1086
+ def _dropped_plugins(stale: Sequence[_m.FileEntry], written: Sequence[_m.FileEntry]) -> list[str]:
1087
+ """Plugins of the previous install that this run installs nothing of, each
1088
+ marked when the catalogue no longer has it (plugin-lifecycle, "Upgrade
1089
+ cleans up a removed plugin")."""
1090
+ try:
1091
+ known = {p["name"] for p in _assets.bundled_catalog()}
1092
+ except (OSError, ValueError): # pragma: no cover - defensive
1093
+ known = set()
1094
+ kept = {e.plugin for e in written if e.plugin}
1095
+ names = sorted({e.plugin for e in stale if e.plugin and e.plugin not in kept})
1096
+ return [n if n in known else f"{n} (no longer in the catalogue)" for n in names]
1097
+
1098
+
1099
+ def _install_root(adapter: Adapter, opts: InstallOptions) -> Path | None:
1100
+ getter = getattr(adapter, "install_root", None)
1101
+ if getter is None:
1102
+ return None
1103
+ try:
1104
+ return Path(getter(opts))
1105
+ except Exception: # pragma: no cover - defensive
1106
+ return None
1107
+
1108
+
1109
+ def _render_plan_dry_run(
1110
+ adapter: Adapter,
1111
+ plan: InstallPlan,
1112
+ opts: InstallOptions | None = None,
1113
+ manifest_path: Path | None = None,
1114
+ ) -> None:
1115
+ table = Table(title=f"[dry-run] {adapter.pretty} ({adapter.name})")
1116
+ table.add_column("op", style="cyan")
1117
+ table.add_column("destination")
1118
+ table.add_column("details")
1119
+
1120
+ for tgt in plan.targets:
1121
+ table.add_row(
1122
+ "write",
1123
+ str(tgt.dst),
1124
+ f"{len(tgt.payload)} bytes"
1125
+ + (f", transform={tgt.transform_name}" if tgt.transform_name else "")
1126
+ + (", +x" if tgt.executable else ""),
1127
+ )
1128
+ for merge in plan.merges:
1129
+ table.add_row("merge", str(merge.path), merge.description)
1130
+ if opts is not None and manifest_path is not None:
1131
+ previous = _m.Manifest.load(manifest_path).for_agent(adapter.name, opts.scope)
1132
+ stale, _carried = _partition_previous(previous, plan, opts)
1133
+ for merge in (previous.config_merges if previous else []):
1134
+ if _is_retired_merge(merge):
1135
+ table.add_row(
1136
+ "unmerge", merge.path,
1137
+ f"remove the retired {RETIRED_MCP_SERVER} MCP server entry",
1138
+ )
1139
+ for entry in stale:
1140
+ p = Path(entry.path)
1141
+ if not p.is_file():
1142
+ continue
1143
+ if _m.is_user_modified(entry):
1144
+ table.add_row("keep", str(p), "no longer shipped; user-modified, kept and untracked")
1145
+ else:
1146
+ table.add_row("remove", str(p), "no longer shipped by this bundle")
1147
+ for note in plan.notes:
1148
+ table.add_row("note", "—", note)
1149
+ if not plan.targets and not plan.merges and not plan.notes:
1150
+ table.add_row("—", "—", "no-op (adapter produced an empty plan)")
1151
+ console.print(table)
1152
+
1153
+
1154
+ def _execute_plan(
1155
+ adapter: Adapter,
1156
+ plan: InstallPlan,
1157
+ opts: InstallOptions,
1158
+ manifest_path: Path,
1159
+ ) -> int:
1160
+ """Write every target, perform every merge, update the manifest.
1161
+
1162
+ Returns 0 on success, non-zero if any target failed safety checks.
1163
+ """
1164
+ if not plan.targets and not plan.merges:
1165
+ if plan.notes:
1166
+ for note in plan.notes:
1167
+ console.print(f"[dim]{adapter.name}:[/dim] {note}")
1168
+ return 0
1169
+
1170
+ files_written: list[_m.FileEntry] = []
1171
+ config_merges: list[_m.ConfigMerge] = []
1172
+ rc = 0
1173
+
1174
+ # 1. Files.
1175
+ for tgt in plan.targets:
1176
+ if tgt.dst.is_file() and not opts.force:
1177
+ # Conflict: file exists. Check whether it's already ours
1178
+ # (manifest record matches hash) — if so, overwrite freely.
1179
+ # Otherwise, warn and skip (force flag overrides).
1180
+ existing_owned = _is_already_owned(tgt.dst, adapter.name, opts.scope, manifest_path)
1181
+ if not existing_owned:
1182
+ err_console.print(
1183
+ f"[yellow]warn:[/yellow] {tgt.dst} already exists (not "
1184
+ f"installed by us). Skipping. Use --force to overwrite."
1185
+ )
1186
+ rc = max(rc, 1)
1187
+ continue
1188
+
1189
+ tgt.dst.parent.mkdir(parents=True, exist_ok=True)
1190
+ # Atomic-ish write: tmp + replace.
1191
+ tmp = tgt.dst.with_suffix(tgt.dst.suffix + ".rfagentskills.tmp")
1192
+ tmp.write_bytes(tgt.payload)
1193
+ os.replace(tmp, tgt.dst)
1194
+ if tgt.executable and os.name != "nt":
1195
+ os.chmod(tgt.dst, 0o755)
1196
+ files_written.append(_m.file_entry_for(tgt.dst, transform=tgt.transform_name, plugin=tgt.plugin))
1197
+
1198
+ # 2. Config merges.
1199
+ for merge in plan.merges:
1200
+ try:
1201
+ added_keys = merge.apply()
1202
+ config_merges.append(_m.ConfigMerge(
1203
+ path=str(merge.path),
1204
+ added_keys=list(added_keys),
1205
+ kind=merge.kind,
1206
+ key_path=list(merge.key_path),
1207
+ backup_path=None,
1208
+ marker=merge.marker,
1209
+ ))
1210
+ except Exception as exc:
1211
+ err_console.print(f"[red]error:[/red] {merge.path}: {exc}")
1212
+ rc = max(rc, 2)
1213
+
1214
+ # 3. Stale files: remove what the previous install wrote but this
1215
+ # bundle no longer ships (same hash-based safety as uninstall).
1216
+ manifest = _m.Manifest.load(manifest_path)
1217
+ previous = manifest.for_agent(adapter.name, opts.scope)
1218
+ stale, carried = _partition_previous(previous, plan, opts)
1219
+ stale_removed, stale_kept = _remove_stale(stale, _install_root(adapter, opts))
1220
+ # Config merges not re-performed this time (e.g. hooks/MCP during a
1221
+ # `--what skills` re-install) stay tracked so uninstall can revert them.
1222
+ redone = {(m.path, m.kind, tuple(m.key_path)) for m in config_merges}
1223
+ carried_merges = [
1224
+ m for m in (previous.config_merges if previous else [])
1225
+ if (m.path, m.kind, tuple(m.key_path)) not in redone
1226
+ ]
1227
+ carried_merges, retired_configs = _retire_legacy_mcp(carried_merges)
1228
+ if opts.mode == "plugin":
1229
+ # The plugin brings its own hooks; hook entries of an earlier file
1230
+ # install would point at the support files pruned as stale above.
1231
+ for m in carried_merges:
1232
+ if m.kind == "json_hooks":
1233
+ _revert_merge(m)
1234
+ carried_merges = [m for m in carried_merges if m.kind != "json_hooks"]
1235
+
1236
+ # 4. Manifest.
1237
+ manifest.upsert(_m.Installation(
1238
+ agent=adapter.name,
1239
+ scope=opts.scope,
1240
+ installed_at=_m.now_iso(),
1241
+ bundle_version=__version__,
1242
+ files=files_written + carried,
1243
+ config_merges=config_merges + carried_merges,
1244
+ notes=list(plan.notes),
1245
+ ))
1246
+ manifest.save(manifest_path)
1247
+
1248
+ # 5. Post-install nudges.
1249
+ table = Table(title=f"installed {adapter.pretty}")
1250
+ table.add_column("op", style="cyan")
1251
+ table.add_column("destination")
1252
+ table.add_row("files", f"{len(files_written)} written")
1253
+ table.add_row("merges", f"{len(config_merges)} performed")
1254
+ table.add_row("stale", f"{len(stale_removed)} removed (no longer shipped)")
1255
+ gone = _removed_skills(stale_removed, files_written)
1256
+ if gone:
1257
+ table.add_row("removed", "skills " + ", ".join(gone))
1258
+ dropped = _dropped_plugins(stale, files_written)
1259
+ if dropped:
1260
+ table.add_row("removed", "plugins " + ", ".join(dropped))
1261
+ for path in retired_configs:
1262
+ table.add_row("retired", f"{RETIRED_MCP_SERVER} MCP server removed from {path}")
1263
+ console.print(table)
1264
+ for path in stale_kept:
1265
+ err_console.print(
1266
+ f"[yellow]warn:[/yellow] {path} is no longer shipped but was "
1267
+ f"modified by you — kept and no longer tracked."
1268
+ )
1269
+ notes = list(plan.notes) if opts.mode == "plugin" else adapter.post_install(opts)
1270
+ for note in notes:
1271
+ console.print(f" [dim]→[/dim] {note}")
1272
+ for d in find_legacy_skill_dirs():
1273
+ if d.name in RETIRED_SKILL_DIRS:
1274
+ err_console.print(_legacy_dir_warning(d))
1275
+
1276
+ return rc
1277
+
1278
+
1279
+ def _is_already_owned(path: Path, agent: str, scope: str, manifest_path: Path) -> bool:
1280
+ """Check if ``path`` is recorded in our manifest for this (agent, scope)."""
1281
+ manifest = _m.Manifest.load(manifest_path)
1282
+ record = manifest.for_agent(agent, scope)
1283
+ if record is None:
1284
+ return False
1285
+ target_str = str(path)
1286
+ return any(entry.path == target_str for entry in record.files)
1287
+
1288
+
1289
+ # ---------------------------------------------------------------------------
1290
+ # Entrypoint
1291
+ # ---------------------------------------------------------------------------
1292
+
1293
+
1294
+ def main(argv: Sequence[str] | None = None) -> int:
1295
+ parser = _build_parser()
1296
+ args = parser.parse_args(argv)
1297
+
1298
+ handlers = {
1299
+ "install": cmd_install,
1300
+ "uninstall": cmd_uninstall,
1301
+ "list": cmd_list,
1302
+ "targets": cmd_targets,
1303
+ "doctor": cmd_doctor,
1304
+ "version": cmd_version,
1305
+ "catalog": cmd_catalog,
1306
+ }
1307
+ return handlers[args.cmd](args)
1308
+
1309
+
1310
+ if __name__ == "__main__": # pragma: no cover
1311
+ sys.exit(main())