rosio 0.1.0__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 (101) hide show
  1. rosio/__init__.py +66 -0
  2. rosio/__main__.py +6 -0
  3. rosio/agent/__init__.py +32 -0
  4. rosio/agent/install.py +562 -0
  5. rosio/agent/platforms.py +417 -0
  6. rosio/agent/templates/core.md +53 -0
  7. rosio/agent/templates/instructions.md +3 -0
  8. rosio/agent/templates/rules.mdc +9 -0
  9. rosio/agent/templates/skill.md +8 -0
  10. rosio/bundle.py +598 -0
  11. rosio/cli.py +2331 -0
  12. rosio/collect/__init__.py +241 -0
  13. rosio/collect/_probe_child.py +714 -0
  14. rosio/collect/bag.py +1391 -0
  15. rosio/collect/cpp_code.py +6507 -0
  16. rosio/collect/entrypoints.py +1155 -0
  17. rosio/collect/interfaces.py +650 -0
  18. rosio/collect/launch_declared.py +2938 -0
  19. rosio/collect/params.py +3207 -0
  20. rosio/collect/plugins.py +1781 -0
  21. rosio/collect/probe.py +1224 -0
  22. rosio/collect/proc.py +546 -0
  23. rosio/collect/py_code.py +3572 -0
  24. rosio/collect/stamps.py +199 -0
  25. rosio/collect/urdf.py +1605 -0
  26. rosio/config.py +926 -0
  27. rosio/drift/__init__.py +17 -0
  28. rosio/drift/build.py +1661 -0
  29. rosio/drift/controllers.py +257 -0
  30. rosio/drift/engine.py +496 -0
  31. rosio/drift/frames.py +2408 -0
  32. rosio/drift/middleware.py +191 -0
  33. rosio/drift/nodes.py +570 -0
  34. rosio/drift/params.py +1561 -0
  35. rosio/drift/plugins.py +642 -0
  36. rosio/drift/rules.py +470 -0
  37. rosio/drift/time.py +269 -0
  38. rosio/drift/topics.py +1306 -0
  39. rosio/errors.py +86 -0
  40. rosio/extract.py +897 -0
  41. rosio/history.py +1450 -0
  42. rosio/ids.py +1021 -0
  43. rosio/join.py +3820 -0
  44. rosio/mergetool.py +595 -0
  45. rosio/migrate/__init__.py +160 -0
  46. rosio/migrate/cmake.py +183 -0
  47. rosio/migrate/data/defaults.json +620 -0
  48. rosio/migrate/data/distros.json +5992 -0
  49. rosio/migrate/data/rules.yaml +319 -0
  50. rosio/migrate/distros.py +117 -0
  51. rosio/migrate/report.py +51 -0
  52. rosio/migrate/rules.py +147 -0
  53. rosio/migrate/scan.py +976 -0
  54. rosio/migrate/verify.py +292 -0
  55. rosio/model.py +2522 -0
  56. rosio/query.py +2249 -0
  57. rosio/render/__init__.py +154 -0
  58. rosio/render/assets/atlas.css +208 -0
  59. rosio/render/assets/atlas.html +69 -0
  60. rosio/render/assets/atlas.js +838 -0
  61. rosio/render/drift_md.py +405 -0
  62. rosio/render/html.py +513 -0
  63. rosio/render/report.py +871 -0
  64. rosio/resolve/__init__.py +23 -0
  65. rosio/resolve/_launch_child.py +2373 -0
  66. rosio/resolve/identity.py +494 -0
  67. rosio/resolve/known_names.py +672 -0
  68. rosio/resolve/launch_exec.py +1325 -0
  69. rosio/resolve/merge.py +167 -0
  70. rosio/resolve/py_pipeline.py +1566 -0
  71. rosio/resolve/qos_presets.py +79 -0
  72. rosio/resolve/records.py +333 -0
  73. rosio/resolve/rewritten_yaml.py +333 -0
  74. rosio/resolve/ros_args.py +1466 -0
  75. rosio/resolve/substitutions.py +422 -0
  76. rosio/resolve/wrappers.py +906 -0
  77. rosio/resolve/yaml_lines.py +393 -0
  78. rosio/scaffold.py +652 -0
  79. rosio/schema.py +819 -0
  80. rosio/serve/__init__.py +13 -0
  81. rosio/serve/__main__.py +103 -0
  82. rosio/serve/server.py +586 -0
  83. rosio/serve/tools.py +1974 -0
  84. rosio/stamps/__init__.py +32 -0
  85. rosio/stamps/__main__.py +7 -0
  86. rosio/stamps/checks.py +32 -0
  87. rosio/stamps/cli.py +128 -0
  88. rosio/stamps/clock.py +243 -0
  89. rosio/stamps/fallback.py +213 -0
  90. rosio/stamps/model.py +18 -0
  91. rosio/stamps/mutate.py +381 -0
  92. rosio/stamps/read.py +137 -0
  93. rosio/stamps/stream.py +210 -0
  94. rosio/stamps/verdict.py +175 -0
  95. rosio/workspace.py +1467 -0
  96. rosio-0.1.0.dist-info/METADATA +143 -0
  97. rosio-0.1.0.dist-info/RECORD +101 -0
  98. rosio-0.1.0.dist-info/WHEEL +4 -0
  99. rosio-0.1.0.dist-info/entry_points.txt +3 -0
  100. rosio-0.1.0.dist-info/licenses/LICENSE +202 -0
  101. rosio-0.1.0.dist-info/licenses/NOTICE +16 -0
rosio/__init__.py ADDED
@@ -0,0 +1,66 @@
1
+ """rosio: a four layer atlas of a ROS 2 system, and the drift between the layers."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ ATLAS_SCHEMA_VERSION = "1"
6
+
7
+ LAYERS = ("declared", "coded", "observed", "recorded")
8
+
9
+
10
+ def extra_line(extra: str) -> str:
11
+ """How to add an optional extra, the same on every machine, because the sentence can
12
+ land in an atlas. rosio is installed from a checkout until it is released."""
13
+ return (
14
+ f"pip install '<checkout>[{extra}]' from a rosio checkout, "
15
+ f"or 'rosio[{extra}]' once released"
16
+ )
17
+
18
+
19
+ def extra_command(extra: str) -> str:
20
+ """The line that adds an optional extra to the environment this process runs in: the
21
+ path rosio was installed from, and uv when uv made the environment, which has no pip."""
22
+ import sys
23
+ from pathlib import Path
24
+
25
+ try:
26
+ config = (Path(sys.prefix) / "pyvenv.cfg").read_text(encoding="utf-8")
27
+ except OSError:
28
+ config = ""
29
+ tool = "uv pip" if any(line.startswith("uv ") for line in config.splitlines()) else "pip"
30
+ return f"{tool} install '{origin()}[{extra}]'"
31
+
32
+
33
+ def here(text: str) -> str:
34
+ """Text an atlas stored with the machine independent install line, as this machine runs
35
+ it: the atlas keeps `extra_line`, the terminal shows `extra_command`."""
36
+ for extra in ("cpp", "mcp", "stamps"):
37
+ stored = extra_line(extra)
38
+ if stored in text:
39
+ text = text.replace(stored, extra_command(extra))
40
+ return text
41
+
42
+
43
+ def origin() -> str:
44
+ """Where rosio was installed from: the checkout path, or `rosio` for a release."""
45
+ import json
46
+ from importlib.metadata import PackageNotFoundError, distribution
47
+ from urllib.parse import unquote, urlparse
48
+
49
+ try:
50
+ url = json.loads(distribution("rosio").read_text("direct_url.json") or "{}").get("url")
51
+ except (PackageNotFoundError, ValueError, AttributeError):
52
+ url = None
53
+ if isinstance(url, str) and url.startswith("file://"):
54
+ return unquote(urlparse(url).path)
55
+ return "rosio"
56
+
57
+
58
+ __all__ = [
59
+ "ATLAS_SCHEMA_VERSION",
60
+ "LAYERS",
61
+ "__version__",
62
+ "extra_command",
63
+ "extra_line",
64
+ "here",
65
+ "origin",
66
+ ]
rosio/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from rosio.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
@@ -0,0 +1,32 @@
1
+ """The agent surface: the install glue every assistant reads, beside the MCP server.
2
+
3
+ The two entry points are `rosio.agent.install.install` and
4
+ `rosio.agent.install.uninstall`. They are not re exported here, because the names would
5
+ shadow the modules of the same names and a shadowed submodule is a confusing import error.
6
+
7
+ The MCP server itself lives in `rosio.serve`. `serve` is resolved lazily here so that
8
+ nothing on the install path can pull in the optional `mcp` package.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Any
14
+
15
+ __all__ = ["serve"]
16
+
17
+
18
+ def __getattr__(name: str) -> Any:
19
+ if name == "serve":
20
+ try:
21
+ from rosio.serve import run
22
+ except ImportError as exc:
23
+ from rosio import extra_command
24
+ from rosio.errors import CollectorError
25
+
26
+ raise CollectorError(
27
+ f"the MCP server is not available: {exc}. "
28
+ f"install the extra with: {extra_command('mcp')}",
29
+ collector="serve",
30
+ ) from exc
31
+ return run
32
+ raise AttributeError(name)
rosio/agent/install.py ADDED
@@ -0,0 +1,562 @@
1
+ """Write and remove the files an assistant reads, so rosio needs one command to reach it.
2
+
3
+ Three properties the caller can rely on:
4
+
5
+ * idempotent. Installing twice changes nothing the second time, and every action says
6
+ which of created, updated, unchanged, kept or removed it was.
7
+ * no silent overwrite. A file rosio did not write is left alone and reported as kept,
8
+ unless the caller passes force. Files rosio owns end with a managed marker, sections
9
+ inside a shared file sit between two markers, and an MCP entry is one named key.
10
+ * undoable by hand. Every action prints its absolute path and the one edit that reverses
11
+ it, so a person who never runs uninstall can still get the tree back.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import os
19
+ import shutil
20
+ import sys
21
+ from collections.abc import Sequence
22
+ from dataclasses import dataclass, field
23
+ from pathlib import Path
24
+
25
+ from rosio.agent import platforms as plat
26
+ from rosio.errors import RosioError, UsageError, exit_code_for
27
+ from rosio.model import dumps
28
+
29
+ TEMPLATES = Path(__file__).parent / "templates"
30
+
31
+ MANAGED_MARK = "rosio:managed"
32
+ MANAGED_NOTE = "<!-- rosio:managed, written by `rosio install`, delete this file to remove it -->"
33
+ MD_BEGIN = "<!-- rosio:begin managed section, `rosio uninstall` removes it -->"
34
+ MD_END = "<!-- rosio:end -->"
35
+ TOML_BEGIN = "# rosio:begin managed section, `rosio uninstall` removes it"
36
+ TOML_END = "# rosio:end"
37
+
38
+ CREATED = "created"
39
+ UPDATED = "updated"
40
+ UNCHANGED = "unchanged"
41
+ KEPT = "kept"
42
+ REMOVED = "removed"
43
+ ABSENT = "absent"
44
+ SKIPPED = "skipped"
45
+ PRUNED = "pruned"
46
+
47
+ WOULD = {CREATED: "create", UPDATED: "update", REMOVED: "remove", PRUNED: "prune"}
48
+ """What a dry run says it would do, per status. `kept`, `unchanged` and `absent` read the
49
+ same either way."""
50
+
51
+
52
+ @dataclass
53
+ class Action:
54
+ """One file, what happened to it, and the edit that reverses it."""
55
+
56
+ path: Path
57
+ mechanism: str
58
+ status: str
59
+ detail: str = ""
60
+ undo: str = ""
61
+
62
+ def line(self, *, dry_run: bool = False) -> str:
63
+ head = f"would {WOULD[self.status]}" if dry_run and self.status in WOULD else self.status
64
+ detail = f" {self.detail}" if self.detail else ""
65
+ return f" {head:<9} {self.path}{detail}"
66
+
67
+
68
+ @dataclass
69
+ class Report:
70
+ """Everything one install or uninstall call did."""
71
+
72
+ platform: str
73
+ scope: str
74
+ root: Path
75
+ home: Path
76
+ verb: str = "install"
77
+ dry_run: bool = False
78
+ actions: list[Action] = field(default_factory=list)
79
+ notes: list[str] = field(default_factory=list)
80
+
81
+ @property
82
+ def kept(self) -> list[Action]:
83
+ return [action for action in self.actions if action.status == KEPT]
84
+
85
+ @property
86
+ def changed(self) -> list[Action]:
87
+ return [a for a in self.actions if a.status in (CREATED, UPDATED, REMOVED, PRUNED)]
88
+
89
+ def lines(self) -> list[str]:
90
+ out = [f"rosio {self.verb} {self.platform}, scope {self.scope}"]
91
+ if not self.actions:
92
+ out.append(" nothing to do, this platform has no file at this scope")
93
+ out.extend(action.line(dry_run=self.dry_run) for action in self.actions)
94
+ out.extend(f" undo: {a.undo}" for a in self.actions if a.undo and a.status != UNCHANGED)
95
+ if not self.actions or any(a.status != UNCHANGED for a in self.actions):
96
+ out.extend(f" note: {note}" for note in self.notes)
97
+ return out
98
+
99
+ def text(self) -> str:
100
+ return "\n".join(self.lines())
101
+
102
+
103
+ def render(template: str) -> str:
104
+ """The template with the shared body substituted in."""
105
+ body = (TEMPLATES / "core.md").read_text(encoding="utf-8").strip()
106
+ text = (TEMPLATES / template).read_text(encoding="utf-8")
107
+ return text.replace("{{core}}", body)
108
+
109
+
110
+ def _owned_text(template: str) -> str:
111
+ return f"{render(template).rstrip()}\n\n{MANAGED_NOTE}\n"
112
+
113
+
114
+ def _markers(fmt: str) -> tuple[str, str]:
115
+ return (TOML_BEGIN, TOML_END) if fmt == "toml" else (MD_BEGIN, MD_END)
116
+
117
+
118
+ def _toml_value(value) -> str:
119
+ if isinstance(value, bool):
120
+ return "true" if value else "false"
121
+ if isinstance(value, list):
122
+ return "[" + ", ".join(_toml_value(item) for item in value) + "]"
123
+ if isinstance(value, str):
124
+ return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
125
+ return str(value)
126
+
127
+
128
+ def _section_body(target: plat.Target, command: Sequence[str]) -> str:
129
+ if target.mechanism == "mcp":
130
+ entry = plat.server_entry(target, command)
131
+ lines = [f"[{target.container}.{plat.SKILL_NAME}]"]
132
+ lines += [f"{key} = {_toml_value(entry[key])}" for key in sorted(entry)]
133
+ lines.append("# a key written under this block joins this table, put yours above it")
134
+ return "\n".join(lines)
135
+ return render(target.template).strip()
136
+
137
+
138
+ def _read(path: Path) -> str:
139
+ if not path.is_file():
140
+ return ""
141
+ try:
142
+ return path.read_text(encoding="utf-8")
143
+ except OSError as exc:
144
+ raise UsageError(f"{path} could not be read: {exc.strerror or exc}") from exc
145
+
146
+
147
+ def _write(path: Path, text: str) -> None:
148
+ try:
149
+ path.parent.mkdir(parents=True, exist_ok=True)
150
+ path.write_text(text, encoding="utf-8")
151
+ except OSError as exc:
152
+ raise UsageError(
153
+ f"{path} could not be written: {exc.strerror or exc}. "
154
+ "fix the permissions on it, or pass --dry-run to see what install wants to write"
155
+ ) from exc
156
+
157
+
158
+ def _remove(path: Path) -> None:
159
+ try:
160
+ path.unlink()
161
+ except OSError as exc:
162
+ raise UsageError(f"{path} could not be removed: {exc.strerror or exc}") from exc
163
+
164
+
165
+ def _rmdir(path: Path) -> None:
166
+ try:
167
+ path.rmdir()
168
+ except OSError as exc:
169
+ raise UsageError(f"{path} could not be removed: {exc.strerror or exc}") from exc
170
+
171
+
172
+ def _split_section(text: str, fmt: str) -> tuple[str, str, str] | None:
173
+ begin, end = _markers(fmt)
174
+ start = text.find(begin)
175
+ if start < 0:
176
+ return None
177
+ stop = text.find(end, start)
178
+ if stop < 0:
179
+ raise UsageError(f"a rosio section opens but never closes, fix it by hand: {begin}")
180
+ return text[:start], text[start : stop + len(end)], text[stop + len(end) :]
181
+
182
+
183
+ def _container(doc: dict, container: str, *, create: bool) -> dict | None:
184
+ node = doc
185
+ for key in container.split("."):
186
+ child = node.get(key)
187
+ if child is None:
188
+ if not create:
189
+ return None
190
+ child = {}
191
+ node[key] = child
192
+ if not isinstance(child, dict):
193
+ raise UsageError(f"{container} is not an object in this config, fix it by hand")
194
+ node = child
195
+ return node
196
+
197
+
198
+ def _load_json(path: Path) -> dict:
199
+ text = _read(path)
200
+ if not text.strip():
201
+ return {}
202
+ try:
203
+ doc = json.loads(text)
204
+ except ValueError as exc:
205
+ raise UsageError(f"{path} is not valid json, fix it by hand: {exc}") from exc
206
+ if not isinstance(doc, dict):
207
+ raise UsageError(f"{path} is not a json object, fix it by hand")
208
+ return doc
209
+
210
+
211
+ def _prune(path: Path, stop: Path, actions: list[Action], *, dry_run: bool) -> None:
212
+ """Remove the directories the install created, once they hold nothing else."""
213
+ parent = path.parent
214
+ while parent != stop and stop in parent.parents:
215
+ if not parent.is_dir() or any(parent.iterdir()):
216
+ return
217
+ actions.append(Action(parent, "dir", PRUNED, "empty after uninstall"))
218
+ if not dry_run:
219
+ _rmdir(parent)
220
+ parent = parent.parent
221
+
222
+
223
+ def _paths(platform: plat.Platform, scope: str, root: Path, home: Path) -> list[tuple]:
224
+ base = root if scope == "project" else home
225
+ return [(target, base / target.path_for(scope)) for target in platform.targets_for(scope)]
226
+
227
+
228
+ def install(
229
+ platform: str,
230
+ scope: str = "project",
231
+ *,
232
+ root: Path | str | None = None,
233
+ home: Path | str | None = None,
234
+ dry_run: bool = False,
235
+ force: bool = False,
236
+ command: Sequence[str] = (),
237
+ ) -> Report:
238
+ """Write every file the platform reads at this scope.
239
+
240
+ A project scope entry is committed with the project, so it names `rosio` from the PATH
241
+ and the atlas by its path inside the project, which is where an MCP client starts its
242
+ servers, and it starts in every clone. When `rosio` is not on a minimal PATH here the
243
+ report says so and names the user scope, whose entry starts the interpreter running this
244
+ install by its absolute path and serves every project, so it names no atlas. An entry
245
+ whose server could not start, because this interpreter has no mcp package, is not
246
+ written."""
247
+ row = plat.get(platform)
248
+ plat.check_scope(scope)
249
+ root = Path(root or Path.cwd()).resolve()
250
+ home = Path(home or Path.home()).resolve()
251
+ stated = tuple(command)
252
+ command = stated or (plat.project_command() if scope == "project" else plat.serve_command())
253
+ report = Report(row.key, scope, root, home, verb="install", dry_run=dry_run)
254
+ missing = _mcp_missing()
255
+
256
+ for target, path in _paths(row, scope, root, home):
257
+ if target.mechanism == "mcp" and missing:
258
+ report.actions.append(Action(path, target.mechanism, SKIPPED, missing))
259
+ elif target.writer == "whole_file":
260
+ _install_whole(target, path, report, force=force)
261
+ elif target.writer == "section":
262
+ _install_section(target, path, report, command)
263
+ elif target.writer == "json_merge":
264
+ _install_json(target, path, report, command, force=force)
265
+ else:
266
+ _install_section(target, path, report, command)
267
+
268
+ _add_notes(row, scope, report)
269
+ written = any(
270
+ a.mechanism == "mcp" and a.status in (CREATED, UPDATED, UNCHANGED) for a in report.actions
271
+ )
272
+ if scope == "project" and not stated and written and not _on_minimal_path("rosio"):
273
+ from rosio import origin
274
+
275
+ tool = f"uv tool install '{origin()}[mcp]'"
276
+ if any(target.mechanism == "mcp" for target in row.targets_for("user")):
277
+ other = "or install with --scope user, which registers this interpreter by its path"
278
+ else:
279
+ # This platform's user scope writes no server entry, so it is no remedy here.
280
+ other = (
281
+ f"or register this interpreter by its absolute path with {row.title}'s own command"
282
+ )
283
+ report.notes.append(
284
+ "rosio is not on a minimal PATH here, so an assistant may not start the server: "
285
+ f"put it where every shell finds it with {tool}, {other}"
286
+ )
287
+ return report
288
+
289
+
290
+ MINIMAL_PATH = ("/usr/local/bin", "/usr/bin", "/bin", "~/.local/bin")
291
+ """What a login shell puts on every user's PATH, `~/.local/bin` being where pipx and uv tool
292
+ install a command. An assistant started from a desktop launcher sees this and not a venv."""
293
+
294
+
295
+ def _on_minimal_path(name: str) -> bool:
296
+ directories = [str(Path(item).expanduser()) for item in MINIMAL_PATH]
297
+ return shutil.which(name, path=os.pathsep.join(directories)) is not None
298
+
299
+
300
+ def _install_whole(target: plat.Target, path: Path, report: Report, *, force: bool) -> None:
301
+ wanted = _owned_text(target.template)
302
+ have = _read(path)
303
+ undo = f"delete {path}"
304
+ if have == wanted:
305
+ report.actions.append(Action(path, target.mechanism, UNCHANGED, "same content", undo))
306
+ return
307
+ if have and MANAGED_MARK not in have and not force:
308
+ report.actions.append(
309
+ Action(path, target.mechanism, KEPT, "this file is not rosio's, pass force to replace")
310
+ )
311
+ return
312
+ status = UPDATED if have else CREATED
313
+ detail = "replaces content rosio did not write" if have and MANAGED_MARK not in have else ""
314
+ if not report.dry_run:
315
+ _write(path, wanted)
316
+ report.actions.append(Action(path, target.mechanism, status, detail, undo))
317
+
318
+
319
+ def _mcp_missing() -> str:
320
+ """Why the server this interpreter would start cannot run, or nothing. An entry for a
321
+ server that dies on start is a registration the assistant reports as broken."""
322
+ from rosio.serve.server import mcp_problem
323
+
324
+ problem = mcp_problem()
325
+ return f"not written: {problem}, then install again" if problem else ""
326
+
327
+
328
+ def _install_section(
329
+ target: plat.Target, path: Path, report: Report, command: Sequence[str]
330
+ ) -> None:
331
+ begin, end = _markers(target.fmt)
332
+ block = f"{begin}\n{_section_body(target, command)}\n{end}\n"
333
+ have = _read(path)
334
+ found = _split_section(have, target.fmt)
335
+ undo = f"delete the lines from {begin} to {end} in {path}"
336
+ if found is None:
337
+ wanted = f"{have.rstrip()}\n\n{block}" if have.strip() else block
338
+ status = UPDATED if have.strip() else CREATED
339
+ detail = "managed section appended, the rest of the file is untouched" if have else ""
340
+ else:
341
+ before, _, after = found
342
+ wanted = before + block.rstrip("\n") + after
343
+ if wanted == have:
344
+ report.actions.append(
345
+ Action(path, target.mechanism, UNCHANGED, "managed section is current", undo)
346
+ )
347
+ return
348
+ status = UPDATED
349
+ detail = "managed section replaced, the rest of the file is untouched"
350
+ if not report.dry_run:
351
+ _write(path, wanted)
352
+ report.actions.append(Action(path, target.mechanism, status, detail, undo))
353
+
354
+
355
+ def _install_json(
356
+ target: plat.Target, path: Path, report: Report, command: Sequence[str], *, force: bool
357
+ ) -> None:
358
+ doc = _load_json(path)
359
+ node = _container(doc, target.container, create=True)
360
+ key = f"{target.container}.{plat.SKILL_NAME}"
361
+ undo = f"delete the {key} entry in {path}"
362
+ entry = plat.server_entry(target, command)
363
+ have = node.get(plat.SKILL_NAME)
364
+ if have == entry:
365
+ report.actions.append(Action(path, target.mechanism, UNCHANGED, f"{key} is current", undo))
366
+ return
367
+ if have is not None and not force:
368
+ report.actions.append(
369
+ Action(path, target.mechanism, KEPT, f"{key} already exists, pass force to replace")
370
+ )
371
+ return
372
+ node[plat.SKILL_NAME] = entry
373
+ status = UPDATED if path.is_file() else CREATED
374
+ detail = f"{key} set to {' '.join(command)}"
375
+ if not report.dry_run:
376
+ _write(path, dumps(doc))
377
+ report.actions.append(Action(path, target.mechanism, status, detail, undo))
378
+
379
+
380
+ def uninstall(
381
+ platform: str,
382
+ scope: str = "project",
383
+ *,
384
+ root: Path | str | None = None,
385
+ home: Path | str | None = None,
386
+ dry_run: bool = False,
387
+ force: bool = False,
388
+ ) -> Report:
389
+ """Remove what install wrote, and nothing else."""
390
+ row = plat.get(platform)
391
+ plat.check_scope(scope)
392
+ root = Path(root or Path.cwd()).resolve()
393
+ home = Path(home or Path.home()).resolve()
394
+ stop = root if scope == "project" else home
395
+ report = Report(row.key, scope, root, home, verb="uninstall", dry_run=dry_run)
396
+
397
+ for target, path in _paths(row, scope, root, home):
398
+ if target.writer == "whole_file":
399
+ _uninstall_whole(target, path, report, force=force)
400
+ elif target.writer == "json_merge":
401
+ _uninstall_json(target, path, report)
402
+ else:
403
+ _uninstall_section(target, path, report)
404
+ _prune(path, stop, report.actions, dry_run=dry_run)
405
+
406
+ return report
407
+
408
+
409
+ def _uninstall_whole(target: plat.Target, path: Path, report: Report, *, force: bool) -> None:
410
+ have = _read(path)
411
+ if not path.is_file():
412
+ report.actions.append(Action(path, target.mechanism, ABSENT))
413
+ return
414
+ if MANAGED_MARK not in have and not force:
415
+ report.actions.append(
416
+ Action(path, target.mechanism, KEPT, "this file is not rosio's, pass force to delete")
417
+ )
418
+ return
419
+ if not report.dry_run:
420
+ _remove(path)
421
+ report.actions.append(Action(path, target.mechanism, REMOVED))
422
+
423
+
424
+ def _uninstall_section(target: plat.Target, path: Path, report: Report) -> None:
425
+ have = _read(path)
426
+ found = _split_section(have, target.fmt)
427
+ if found is None:
428
+ report.actions.append(Action(path, target.mechanism, ABSENT, "no managed section"))
429
+ return
430
+ before, _, after = found
431
+ rest = (before.rstrip() + "\n" + after.lstrip("\n")).strip()
432
+ if rest:
433
+ if not report.dry_run:
434
+ _write(path, rest + "\n")
435
+ report.actions.append(
436
+ Action(path, target.mechanism, REMOVED, "section only, the rest of the file stays")
437
+ )
438
+ return
439
+ if not report.dry_run:
440
+ _remove(path)
441
+ report.actions.append(Action(path, target.mechanism, REMOVED, "file held nothing else"))
442
+
443
+
444
+ def _uninstall_json(target: plat.Target, path: Path, report: Report) -> None:
445
+ if not path.is_file():
446
+ report.actions.append(Action(path, target.mechanism, ABSENT))
447
+ return
448
+ doc = _load_json(path)
449
+ node = _container(doc, target.container, create=False)
450
+ key = f"{target.container}.{plat.SKILL_NAME}"
451
+ if node is None or plat.SKILL_NAME not in node:
452
+ report.actions.append(Action(path, target.mechanism, ABSENT, f"no {key} entry"))
453
+ return
454
+ del node[plat.SKILL_NAME]
455
+ _drop_empty(doc, target.container)
456
+ if doc:
457
+ if not report.dry_run:
458
+ _write(path, dumps(doc))
459
+ report.actions.append(
460
+ Action(path, target.mechanism, REMOVED, f"{key} only, the rest of the file stays")
461
+ )
462
+ return
463
+ if not report.dry_run:
464
+ _remove(path)
465
+ report.actions.append(Action(path, target.mechanism, REMOVED, "file held nothing else"))
466
+
467
+
468
+ def _drop_empty(doc: dict, container: str) -> None:
469
+ keys = container.split(".")
470
+ node = doc
471
+ chain = [(None, doc)]
472
+ for key in keys:
473
+ node = node.get(key)
474
+ if not isinstance(node, dict):
475
+ return
476
+ chain.append((key, node))
477
+ for index in range(len(chain) - 1, 0, -1):
478
+ key, child = chain[index]
479
+ if child:
480
+ return
481
+ del chain[index - 1][1][key]
482
+
483
+
484
+ def _add_notes(platform: plat.Platform, scope: str, report: Report) -> None:
485
+ if not platform.targets_for(scope):
486
+ report.notes.append(
487
+ f"{platform.key} has no file at {scope} scope, try the other scope: "
488
+ f"{', '.join(s for s in plat.SCOPES if platform.targets_for(s))}"
489
+ )
490
+ unseen = [target for target in platform.targets_for(scope) if not target.verified]
491
+ if unseen:
492
+ report.notes.append(
493
+ f"{len(unseen)} of these paths not yet seen read by {platform.key}, "
494
+ "rosio install --list says which"
495
+ )
496
+ if platform.note and scope == "user":
497
+ report.notes.append(platform.note)
498
+
499
+
500
+ def _parser() -> argparse.ArgumentParser:
501
+ parser = argparse.ArgumentParser(
502
+ prog="rosio install",
503
+ description="Register rosio with a coding assistant by writing the files it reads.",
504
+ )
505
+ parser.add_argument("platform", nargs="?", help="assistant to register with")
506
+ parser.add_argument("--scope", default="project", choices=list(plat.SCOPES))
507
+ parser.add_argument("--root", default=None, help="project root, default the working directory")
508
+ parser.add_argument("--home", default=None, help="home directory, for user scope")
509
+ parser.add_argument("--dry-run", action="store_true", help="print what would change")
510
+ parser.add_argument("--force", action="store_true", help="replace content rosio did not write")
511
+ parser.add_argument("--remove", action="store_true", help="uninstall instead of install")
512
+ parser.add_argument("--list", action="store_true", help="print the platform table and exit")
513
+ return parser
514
+
515
+
516
+ def _table_lines() -> list[str]:
517
+ """The platform table, with what was actually demonstrated per row.
518
+
519
+ A target carries a project path and a user path, and those are two claims. Printing one
520
+ `unverified` over both puts a row somebody watched a tool read beside a row taken from a
521
+ manual, so the row prints the phrase the table carries instead of a flag.
522
+ """
523
+ lines = ["platform mechanism project user"]
524
+ for row in plat.table():
525
+ lines.append(
526
+ f"{row['platform']:<13} {row['mechanism']:<13} "
527
+ f"{row['project'] or '-':<32} {row['user'] or '-'}"
528
+ )
529
+ lines.append(f"{'':<13} checked: {row['proof']}")
530
+ lines.append("")
531
+ lines.append(
532
+ "Seen read means somebody started that tool and watched it read the file at that "
533
+ "path. A path from the tool's documentation installs anyway, and install says so per "
534
+ "file."
535
+ )
536
+ return lines
537
+
538
+
539
+ def main(argv: list[str] | None = None) -> int:
540
+ args = _parser().parse_args(argv)
541
+ if args.list or not args.platform:
542
+ print("\n".join(_table_lines()))
543
+ return 0 if args.list else 2
544
+ try:
545
+ call = uninstall if args.remove else install
546
+ report = call(
547
+ args.platform,
548
+ args.scope,
549
+ root=args.root,
550
+ home=args.home,
551
+ dry_run=args.dry_run,
552
+ force=args.force,
553
+ )
554
+ except RosioError as exc:
555
+ print(f"rosio: {exc}", file=sys.stderr)
556
+ return exit_code_for(exc)
557
+ print(report.text())
558
+ return 0
559
+
560
+
561
+ if __name__ == "__main__":
562
+ raise SystemExit(main())