roadkeep 0.2.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 (67) hide show
  1. roadkeep/__init__.py +79 -0
  2. roadkeep/adopting.py +2347 -0
  3. roadkeep/attesting.py +293 -0
  4. roadkeep/authoring.py +2117 -0
  5. roadkeep/backlog.py +767 -0
  6. roadkeep/blocking.py +1622 -0
  7. roadkeep/briefing.py +970 -0
  8. roadkeep/budgeting.py +2056 -0
  9. roadkeep/capturing.py +1699 -0
  10. roadkeep/claiming.py +1019 -0
  11. roadkeep/cli.py +638 -0
  12. roadkeep/commanding.py +487 -0
  13. roadkeep/config.py +1832 -0
  14. roadkeep/counting.py +376 -0
  15. roadkeep/criteria.py +933 -0
  16. roadkeep/deferring.py +708 -0
  17. roadkeep/describing.py +568 -0
  18. roadkeep/exporting.py +808 -0
  19. roadkeep/fixing.py +629 -0
  20. roadkeep/governing.py +934 -0
  21. roadkeep/graph.py +395 -0
  22. roadkeep/guarding.py +1028 -0
  23. roadkeep/history.py +2403 -0
  24. roadkeep/ids.py +301 -0
  25. roadkeep/installing.py +2145 -0
  26. roadkeep/kernel/__init__.py +24 -0
  27. roadkeep/kernel/document.py +1719 -0
  28. roadkeep/kernel/schema.py +2308 -0
  29. roadkeep/linting.py +4420 -0
  30. roadkeep/locking.py +209 -0
  31. roadkeep/markers.py +172 -0
  32. roadkeep/merging.py +1159 -0
  33. roadkeep/picking.py +772 -0
  34. roadkeep/provenance.py +789 -0
  35. roadkeep/queueing.py +752 -0
  36. roadkeep/ranking.py +139 -0
  37. roadkeep/referring.py +231 -0
  38. roadkeep/remaining.py +336 -0
  39. roadkeep/remedying.py +1989 -0
  40. roadkeep/rendering.py +1601 -0
  41. roadkeep/renumbering.py +503 -0
  42. roadkeep/repairing.py +295 -0
  43. roadkeep/reverting.py +144 -0
  44. roadkeep/scoping.py +708 -0
  45. roadkeep/screening.py +196 -0
  46. roadkeep/sections.py +4121 -0
  47. roadkeep/serving.py +2909 -0
  48. roadkeep/shipping.py +3993 -0
  49. roadkeep/showing.py +613 -0
  50. roadkeep/storing.py +224 -0
  51. roadkeep/verbs/__init__.py +26 -0
  52. roadkeep/verbs/adopting.py +974 -0
  53. roadkeep/verbs/authoring.py +566 -0
  54. roadkeep/verbs/declaring.py +335 -0
  55. roadkeep/verbs/linting.py +645 -0
  56. roadkeep/verbs/querying.py +2138 -0
  57. roadkeep/verbs/reading.py +307 -0
  58. roadkeep/verbs/refusing.py +146 -0
  59. roadkeep/verbs/sections.py +1433 -0
  60. roadkeep/verbs/shipping.py +819 -0
  61. roadkeep/weighing.py +380 -0
  62. roadkeep-0.2.0.dist-info/METADATA +453 -0
  63. roadkeep-0.2.0.dist-info/RECORD +67 -0
  64. roadkeep-0.2.0.dist-info/WHEEL +5 -0
  65. roadkeep-0.2.0.dist-info/entry_points.txt +2 -0
  66. roadkeep-0.2.0.dist-info/licenses/LICENSE +202 -0
  67. roadkeep-0.2.0.dist-info/top_level.txt +1 -0
roadkeep/installing.py ADDED
@@ -0,0 +1,2145 @@
1
+ """Wiring a project that runs this tool from a checkout instead of from the plugin (RK100).
2
+
3
+ `init` scaffolds the format — the config and the files it declares. What it does *not*
4
+ scaffold is the harness: the server that offers the tools, the hook that denies the
5
+ hand-edit, and the skill that says which command to call. Those ride with the plugin, and a
6
+ project can only install the plugin from a marketplace — which means the published ref, not
7
+ the sibling checkout an early adopter is developing against. Measured on the first one: five
8
+ hand-written surfaces against three scaffolded ones, and a copy of `SKILL.md` with a comment
9
+ saying where it came from, which nothing keeps in step with the file it was taken from.
10
+
11
+ **Every byte written here is a translation of what the plugin already ships**, never a second
12
+ statement of it. The hook events, their matcher and their timeouts are read out of
13
+ `hooks/hooks.json`; the server argv out of `.claude-plugin/mcp.json`; the skill is copied with
14
+ one sentence re-addressed; the workflow names the action this repository publishes. The one
15
+ thing substituted is where the launcher is — `${CLAUDE_PLUGIN_ROOT}` becomes the path from the
16
+ adopting project to the checkout that is answering, which is the only fact the plugin's own
17
+ files cannot hold, and the skill's own entry point is the fourth place it is written (RK137).
18
+ So a matcher added to the plugin reaches every installed project on its next `install`, and
19
+ this module has no opinion to disagree with.
20
+
21
+ Three surfaces, three different rules about re-running, because they are three different
22
+ kinds of file:
23
+
24
+ * **The skill is a copy, so it is refreshed** — always, unasked. It is the whole defect: a
25
+ vendored authority that drifts is worse than none, because it is read with the same trust.
26
+ Which is also why its entry-point sentence is re-addressed rather than copied (RK137): a
27
+ copy that is faithful in every byte and names a command that does not exist here is read
28
+ with that same trust, and the failure arrives in the shell an agent fell back to.
29
+ * **`.mcp.json` and `.claude/settings.json` are declarations**, and other tools declare in
30
+ them too. Only this project's entry is re-derived — the launcher path is the part that
31
+ moves — and everything else in the file is carried through untouched. An existing file that
32
+ is not a JSON object is refused rather than replaced: it is somebody's configuration.
33
+ * **The CI workflow is created once and then the adopter's.** It takes a `baseline:` and a
34
+ `directory:` this command cannot know it wants, so refreshing it would overwrite the one
35
+ thing an adopting repository actually tunes.
36
+
37
+ `--check` is what makes the first rule mean anything: it reports what `install` would change
38
+ and exits non-zero, so the copy is held in step by a gate rather than by whoever remembers.
39
+
40
+ **And there is a way out** (RK138). An early adopter develops against a checkout and switches
41
+ to the plugin once it is installable, and the second half of that had no verb: three surfaces
42
+ were removed with `rm`, safe only because `install` had created all three. `uninstall` is the
43
+ inverse under the same two rules — the declarations keep everything that is not this project's
44
+ entry, and a file that is not a JSON object is refused rather than rewritten — and it reads no
45
+ checkout, recognising the wiring by the server's name and the launcher a hook runs, because
46
+ the tree that was wired in is usually gone by then. The CI workflow is the one surface it
47
+ keeps: that gate calls the published action, not the checkout, so un-wiring the write path
48
+ does not un-gate the repository.
49
+
50
+ **The one tree that is not an adopter is this one** (RK235). Run at the plugin's own root the
51
+ two declarations still mean what they mean — point a session at this checkout's tools and its
52
+ guard, which this repository declares by hand (RK81) — and the two copies do not: a vendored
53
+ `SKILL.md` beside the `skills/` one it was read from is the drift this command exists to
54
+ remove, and a second workflow beside the one already gating the tree runs the same lint twice.
55
+ So they are named as unwritten instead, and `--check` at that root reports drift rather than a
56
+ category error. `uninstall` has no such narrowing and refuses outright, the entries there
57
+ being the tree's own rather than a copy of somebody's wiring.
58
+
59
+ Two more surfaces are named rather than written, which is not the same as being left out.
60
+ A line in `CONTRIBUTING.md` telling a contributor not to hand-edit the governed files is prose
61
+ about a project's own contribution policy, and this tool does not write prose (L4). The **merge
62
+ driver** (RK120) is configuration, so it stays opt-in — but being opt-in is no reason to be
63
+ unmentioned (RK148): it is named in the report, and `--register-merge` writes the
64
+ `.gitattributes` half for a caller that asks while the `git config` half is printed, that one
65
+ being a write outside the files this tool was given (L2).
66
+ """
67
+
68
+ from __future__ import annotations
69
+
70
+ import json
71
+ import os
72
+ import re
73
+ import sys
74
+ from collections.abc import Sequence
75
+ from dataclasses import dataclass, replace
76
+ from pathlib import Path
77
+
78
+ from roadkeep.adopting import BlockedParent, blocking
79
+ from roadkeep.config import CONFIG_NAME, Config
80
+ from roadkeep.linting import lint
81
+ from roadkeep.merging import ATTRIBUTES, Registration, register
82
+ from roadkeep.provenance import Engine, Installed, engine, home, installed
83
+ from roadkeep.provenance import invocation
84
+
85
+ #: The server's name, which is also the prefix an agent reads on every tool it offers.
86
+ SERVER = "roadkeep"
87
+
88
+ #: What the plugin ships, relative to its root. Read, never rewritten: these four are the
89
+ #: source this command translates, and a fifth would be a decision this module invented.
90
+ LAUNCHER = "scripts/roadkeep.py"
91
+ PLUGIN_HOOKS = "hooks/hooks.json"
92
+ PLUGIN_MCP = ".claude-plugin/mcp.json"
93
+ PLUGIN_SKILL = "skills/roadkeep/SKILL.md"
94
+ PLUGIN_MANIFEST = ".claude-plugin/plugin.json"
95
+ #: The self-locating bridge, for the environment that installs no plugin and has no checkout
96
+ #: to point at (RK1108). Copied rather than translated: it is a program and not a declaration,
97
+ #: and the one fact `install` substitutes elsewhere — where the engine is — is the question
98
+ #: this file exists to answer at runtime.
99
+ PLUGIN_BRIDGE = "hooks/roadkeep-launch.py"
100
+
101
+ #: The five together, which is both what a tree must carry to be translated *from* and what
102
+ #: says a tree is the plugin rather than an adopter of it (RK235). One list, so the two
103
+ #: questions cannot come to disagree about what carrying the plugin means.
104
+ CARRIED = (LAUNCHER, PLUGIN_HOOKS, PLUGIN_MCP, PLUGIN_SKILL, PLUGIN_MANIFEST)
105
+
106
+ #: Where each lands in the adopting project. The skill path is the loader's convention —
107
+ #: `.claude/skills/<name>/SKILL.md` — and the workflow is a file of its own rather than a job
108
+ #: spliced into an existing one: merging YAML would need a parser this tool does not have,
109
+ #: and a job appended to somebody's pipeline is an edit to a file they own.
110
+ PROJECT_MCP = ".mcp.json"
111
+ PROJECT_SETTINGS = ".claude/settings.json"
112
+ PROJECT_SKILL = ".claude/skills/roadkeep/SKILL.md"
113
+ PROJECT_WORKFLOW = ".github/workflows/roadkeep.yml"
114
+ #: Where the bridge lands, beside the hooks that run it (RK1108). Inside the repository on
115
+ #: purpose: the environment it exists for reads what is committed and nothing else, so a path
116
+ #: pointing anywhere outside would be a path that resolves on one machine.
117
+ PROJECT_BRIDGE = ".claude/hooks/roadkeep-launch.py"
118
+
119
+ #: Where a **vendored** engine lands (RK1193). Inside the project so the path a declaration
120
+ #: names is stable across machines, and git-ignored so it stays an artefact: the tree is a
121
+ #: copy of somebody else's repository, and committing it would make every `/plugin update` a
122
+ #: diff in this one. The name is the `node_modules` shape both adopters converged on.
123
+ PROJECT_ENGINE = ".roadkeep"
124
+ #: The environment variable the launcher resolves first, which is how a vendored copy is
125
+ #: *pinned* rather than merely present: resolution order alone would still prefer it only
126
+ #: where nothing earlier answered, and pinning is the whole point.
127
+ ENGINE_HOME = "ROADKEEP_HOME"
128
+ #: The one way a **working checkout** becomes eligible to be vendored (RK1193). Named rather
129
+ #: than inferred, because the case that costs an hour is a checkout mid-refactor: it answers a
130
+ #: version, imports halfway, and is exactly what a pinned copy exists to stop being.
131
+ ENGINE_SOURCE = "ROADKEEP_SRC"
132
+
133
+ #: The directory whose presence decides whether the workflow is written. A repository with no
134
+ #: workflows has not asked for CI, and a scaffold that leaves a file nobody runs is litter.
135
+ WORKFLOWS = ".github/workflows"
136
+
137
+ #: The placeholder the harness defines for a plugin-provided config, and the two spellings of
138
+ #: the one it defines for a project's own. The `:-.` fallback is what the MCP declaration is
139
+ #: written with here and in the first adopting project; a hook always runs with the variable
140
+ #: set, so its command carries the bare form.
141
+ PLUGIN_ROOT = "${CLAUDE_PLUGIN_ROOT}"
142
+ PROJECT_DIR = "${CLAUDE_PROJECT_DIR}"
143
+ PROJECT_DIR_OR_CWD = "${CLAUDE_PROJECT_DIR:-.}"
144
+
145
+ #: The sentence in the shipped skill that names the entry point, matched rather than located
146
+ #: by line (RK137). Written as the two ends of it with anything between, so re-wrapping the
147
+ #: paragraph — which is prose somebody edits — does not silently stop the substitution: what
148
+ #: stops it is a refusal.
149
+ _ENTRY_RE = re.compile(
150
+ r"`roadkeep` is the installed entry point.*?not on PATH\.", re.DOTALL
151
+ )
152
+
153
+ #: The ref the generated workflow calls the action at. `main` and not the version, because
154
+ #: the project reaching for this command is by definition running an unreleased checkout —
155
+ #: an adopter that has pinned a release edits one line, which is the file's own from then on.
156
+ ACTION_REF = "main"
157
+
158
+ #: The fifth surface: opt-in, and until RK148 unmentioned. RK120 shipped the merge driver as
159
+ #: configuration (L6) — right — but an adopter read a report naming four surfaces and a
160
+ #: `CONTRIBUTING.md` line and was never told a driver exists, so the failure landed later and
161
+ #: looked like the tool's: two branches spend one id, git writes conflict markers into the
162
+ #: roadmap, and the resolution is the hand edit the guard denies.
163
+ #: A template and not a string, because the invocation is a fact about the machine reading it
164
+ #: and this is a module constant (RK256): resolved at import, it would answer for whatever the
165
+ #: working directory was then rather than for the report being printed.
166
+ MERGE = (
167
+ ".gitattributes: `{invocation} merge --register` wires the merge driver for the governed "
168
+ "files, so two branches appending under one heading is two additions and not a conflict "
169
+ "— opt-in configuration, and `install --register-merge` runs it here"
170
+ )
171
+
172
+ #: The same line where that file cannot be written at all (RK394). `not written` is the honest
173
+ #: half of the report and it names a remedy on every run; a remedy that exits 2 is a different
174
+ #: entry from one the caller simply has not chosen yet, so it says which this is and stops
175
+ #: advertising the flag.
176
+ MERGE_BLOCKED = (
177
+ ".gitattributes: {blocker} is in the way, so the merge driver cannot be wired here at "
178
+ "all — `install --register-merge` would refuse, and moving that is what comes first"
179
+ )
180
+
181
+ #: And the third state (RK1387), by :data:`MERGE_BLOCKED`'s own argument one step further: an
182
+ #: opt-in already taken is a different entry from one nobody has chosen yet, so it says which
183
+ #: and stops advertising a flag whose whole answer would be four lines already there.
184
+ #:
185
+ #: Read back rather than assumed, which is the defect: this row stated what `install` does not
186
+ #: write and never asked whether anything else had — so `merge --check` answered *4 of 4
187
+ #: governed files routed* while this one offered to wire them, two reads of one tree.
188
+ #:
189
+ #: The **attribute** half only. Whether git can run what it finds is per clone and is what
190
+ #: `merge --check` exists to say, so quoting it here would be the second answer this closes.
191
+ MERGE_WIRED = (
192
+ ".gitattributes: the attribute half is written and the governed files route to the merge "
193
+ "driver, so there is nothing here for `install --register-merge` to write — whether this "
194
+ "clone holds the config to run them is `{invocation} merge --check`"
195
+ )
196
+
197
+ #: What the two *copies* become when the tree being wired is the tree answering (RK235). Not
198
+ #: a refusal: the declarations still mean what they mean at this root — this repository wires
199
+ #: itself to its own checkout by hand and a test holds that (RK81) — and what would be wrong
200
+ #: is vendoring a second copy of a file already in the tree, and a second workflow beside the
201
+ #: one already gating it. Named rather than silently absent, on the rule every skipped surface
202
+ #: here follows: an adopter discovers a silent absence by needing it.
203
+ _OWN_SKILL = (
204
+ f"this tree ships {PLUGIN_SKILL}, so a copy of it here would be the drift `install` "
205
+ f"exists to remove — a session in this checkout reads the original"
206
+ )
207
+ #: The third member of that set, and the one that was missing from it (RK402). A tree that
208
+ #: ships the guard as a **plugin** — `hooks/hooks.json`, declared by `.claude-plugin/plugin.json`
209
+ #: — already runs it, so writing the same hooks into `.claude/settings.json` would run the
210
+ #: guard twice on every turn. `install --check` reported `1 surface(s) differ` here
211
+ #: permanently, and a check that can never report clean is one nobody reads: the drift it
212
+ #: exists to catch arrives inside a report that already said the same thing yesterday.
213
+ _OWN_HOOKS = (
214
+ f"this tree declares the guard as a plugin in {PLUGIN_MANIFEST} ({PLUGIN_HOOKS}), so "
215
+ f"writing the same hooks here would run it twice on every turn"
216
+ )
217
+ _OWN_WORKFLOW = (
218
+ "this tree *is* the action, and its own workflow already calls the gate — a second one "
219
+ "would run the same lint twice"
220
+ )
221
+ #: The fourth of that set (RK1108). Same reasoning as the skill's, one file over: a tree that
222
+ #: ships the bridge does not vendor a copy of it beside the original.
223
+ _OWN_BRIDGE = (
224
+ f"this tree ships {PLUGIN_BRIDGE}, and a session here reaches the engine directly — a "
225
+ f"copy of the bridge beside the original is the drift `install` exists to remove"
226
+ )
227
+
228
+ #: The surface this command names and does not write (L4), and why. Printed by `install`.
229
+ CONTRIBUTING = (
230
+ "CONTRIBUTING.md: one line telling a contributor the governed files are written by "
231
+ "`roadkeep` and not by hand — prose about your project, so this command leaves it to you"
232
+ )
233
+
234
+
235
+ class NotShipped(ValueError):
236
+ """The running copy of this package carries no plugin surfaces to translate.
237
+
238
+ An installed wheel is `roadkeep/` alone: the hook declaration, the server declaration and
239
+ the skill live beside `src/` in the repository, not inside the package. That is not worth
240
+ fixing by shipping a second copy of them as package data — a copy is the defect this
241
+ command exists to remove. The answer for a wheel is the plugin, which carries all three.
242
+ """
243
+
244
+ def __init__(self, root: Path, missing: tuple[str, ...]) -> None:
245
+ self.root = root
246
+ self.missing = missing
247
+ super().__init__(
248
+ f"{root} does not carry the surfaces the plugin ships and nothing was written "
249
+ f"(missing: {', '.join(missing)}) — `install` translates a checkout of roadkeep "
250
+ f"for a project beside it; an installed copy has none to translate, and "
251
+ f"`/plugin install roadkeep@alegauss` is the route that carries them"
252
+ )
253
+
254
+
255
+ class Unanchored(ValueError):
256
+ """The shipped skill no longer spells the sentence the launcher is substituted into.
257
+
258
+ A refusal and not a verbatim copy (RK137): the copy would then tell an adopting project
259
+ to run a command that does not exist there, which is the whole defect `install` removes.
260
+ Reached only by editing `SKILL.md`, and the repair is in that file — so it names it.
261
+ """
262
+
263
+ def __init__(self, path: Path, found: int) -> None:
264
+ self.path = path
265
+ self.found = found
266
+ super().__init__(
267
+ f"{path} states the entry point {found} time(s) and nothing was written: "
268
+ f"`install` re-addresses that one sentence for a project wired to a checkout, "
269
+ f"and a copy carrying `roadkeep` where the package is not installed names a "
270
+ f"command that fails"
271
+ )
272
+
273
+
274
+ class NotAnAdopter(ValueError):
275
+ """The tree asked about is the plugin, and there is no installation of it to withdraw.
276
+
277
+ `install` handles this root by *narrowing* what it writes (RK235) — the two declarations
278
+ are this repository's own conformance (RK81) and stay. Un-wiring is the direction with no
279
+ such reading: the entries here are not a copy of somebody else's wiring, they are the file
280
+ the tree carries, and taking them out would un-wire the tool from itself.
281
+ """
282
+
283
+ def __init__(self, root: Path) -> None:
284
+ self.root = root
285
+ super().__init__(
286
+ f"{root} ships the plugin rather than adopting it, and nothing was taken out: "
287
+ f"the server and guard declared here point a session at this checkout on "
288
+ f"purpose — `git checkout` is what reverts that, and `uninstall` is for a "
289
+ f"project `install` wired"
290
+ )
291
+
292
+
293
+ class Unreadable(ValueError):
294
+ """An existing declaration this command would have to merge into and cannot parse."""
295
+
296
+ def __init__(self, path: Path, reason: str) -> None:
297
+ self.path = path
298
+ super().__init__(
299
+ f"{path} is not a JSON object and nothing was written ({reason}): this command "
300
+ f"merges its own entry into that file and never replaces one somebody wrote"
301
+ )
302
+
303
+
304
+ @dataclass(frozen=True, slots=True)
305
+ class Surface:
306
+ """One file this command owns a part of, and what running it would do to that file."""
307
+
308
+ path: Path
309
+ text: str
310
+ #: False for the workflow, which is the adopter's after the first write. The distinction
311
+ #: is the whole re-run contract, so it is a field rather than a check at the call site.
312
+ refresh: bool
313
+ existed: bool
314
+ stale: bool
315
+
316
+ @property
317
+ def state(self) -> str:
318
+ if not self.existed:
319
+ return "created"
320
+ if not self.stale:
321
+ return "unchanged"
322
+ return "updated" if self.refresh else "kept"
323
+
324
+ @property
325
+ def writes(self) -> bool:
326
+ return self.state in ("created", "updated")
327
+
328
+
329
+ @dataclass(frozen=True, slots=True)
330
+ class Plan:
331
+ """What `install` would write, computed before a byte reaches disk (all-or-nothing)."""
332
+
333
+ root: Path
334
+ #: The checkout being wired in — the tree whose `scripts/roadkeep.py` the hook will run.
335
+ source: Path
336
+ #: That launcher, exactly as the declarations spell it.
337
+ launcher: str
338
+ surfaces: tuple[Surface, ...]
339
+ #: Paths not written, each with the reason — the report's other half. A surface that is
340
+ #: silently absent is one the adopter discovers is absent by needing it.
341
+ skipped: tuple[tuple[str, str], ...] = ()
342
+ #: What this project's own gate reports today, or None where it could not be run (RK140).
343
+ #: It decides which workflow is written, and it is on the plan because a decision taken
344
+ #: from a measurement the report does not state is one the adopter cannot check.
345
+ debt: int | None = None
346
+ #: The merge driver, where `--register-merge` asked for it (RK148) — the attribute lines
347
+ #: written and the `git config` line to run, exactly as `merge --register` reports them.
348
+ registered: Registration | None = None
349
+ #: Surfaces that would be written and cannot be, each with the ancestor standing in the
350
+ #: way (RK393). RK392's question one command over: `exists` says whether a write would
351
+ #: clobber, and this says whether it can happen — a `.claude` that is a file left the
352
+ #: server declaration on disk with no hook and no skill beside it. On the plan and not
353
+ #: raised here, because `--check` writes nothing and still has to report it: its whole
354
+ #: job is naming the remedy, and `install` was the remedy it named and could not do.
355
+ blocked: tuple[tuple[Path, Path], ...] = ()
356
+ #: Which variant this plan is (RK1108), and whether the flag or the disk said so (RK1113).
357
+ #: On the plan because the launcher alone does not say *why* it is that path, and a reader
358
+ #: of a report that names no flag has to be able to tell a project wired to the bridge
359
+ #: from one this run is about to move there.
360
+ committed: bool = False
361
+ #: True where :func:`_carrying` answered it rather than the caller (RK1113).
362
+ carried: bool = False
363
+ #: What is standing in the way of `.gitattributes`, where anything is (RK394). Its own
364
+ #: field and not a row in :attr:`blocked`, because the driver is not one of the surfaces:
365
+ #: it is written after the loop, by `--register-merge` alone, and the report names it on
366
+ #: every run whether or not the flag was given — so this answers two questions, whether
367
+ #: the write can happen and whether the sentence advertising it is true.
368
+ driver: Path | None = None
369
+
370
+ @property
371
+ def changing(self) -> tuple[Surface, ...]:
372
+ return tuple(surface for surface in self.surfaces if surface.writes)
373
+
374
+ def stated(self, checked: bool) -> str:
375
+ """Every surface and what this run did — or would do — to it (RK100, RK393).
376
+
377
+ Beside :meth:`payload` since RK1170. `checked` is the caller's and not a field: the
378
+ plan is the same computation either way, which is what makes `--check` a check of the
379
+ thing that runs, and only the **tense** of the report differs.
380
+ """
381
+ # The **project** heads it, which is the reader's first question on a write: every row
382
+ # under this one names a file in that tree, and the header used to name the engine's
383
+ # instead (RK1359). Measured on a reader: running `install -C <elsewhere>` from a
384
+ # neutral directory, the header read as *this is where it wrote*, and two commands went
385
+ # by before listing the filesystem showed the files in the target and `-C` honoured.
386
+ #
387
+ # The engine only where it is a **different** tree, because the two collapse in the
388
+ # checkout that ships this package and a second identical path is a line that says
389
+ # nothing. They differ for an adopter, which is who `install` is for: the launcher a
390
+ # hook runs months later lives in the engine's tree, so which one that is stays worth
391
+ # a row — beside the project rather than in its place.
392
+ rows = [f"{self.root.as_posix()} → {self.launcher}"]
393
+ if self.source != self.root:
394
+ rows.append(
395
+ f" engine {self.source.as_posix()} — the checkout that launcher "
396
+ f"runs from, which is not this project"
397
+ )
398
+ if self.carried:
399
+ # Said because the header alone does not (RK1113): the launcher is a path, and a
400
+ # reader who passed no flag has to be told the path came from their own project
401
+ # rather than from a default that is about to overwrite it.
402
+ rows.append(
403
+ f" committed this project already runs {PROJECT_BRIDGE}, so the "
404
+ f"wiring stays on it — `uninstall` then `install` moves it to a checkout"
405
+ )
406
+ for surface in self.surfaces:
407
+ # `--check` writes nothing, so it reports in the conditional: the same three words
408
+ # in the past tense would claim a file changed that did not.
409
+ state = _WOULD[surface.state] if checked else surface.state
410
+ rows.append(f" {state:<14} {surface.path.relative_to(self.root).as_posix()}")
411
+ if self.registered is not None:
412
+ # The same lines `merge --register` prints, because it is the same write (RK148) —
413
+ # and now literally the same rendering (RK276), so a field added to `Registration`
414
+ # cannot reach one surface and miss the other. The `git config` half is still
415
+ # printed and not run.
416
+ from roadkeep.rendering import registration_report # noqa: PLC0415 - RK260
417
+
418
+ rows += registration_report(
419
+ self.registered, self.registered.attributes.name, 14
420
+ )
421
+ if self.debt:
422
+ # Beside the surfaces, because it is the reason one of them was written the way it
423
+ # was (RK140): a decision taken from a measurement nobody is shown is one the
424
+ # adopter cannot check.
425
+ rows.append(
426
+ f" baselined {self.debt} standing finding(s) here, so the workflow "
427
+ f"fails on what a branch adds — drop the line once `lint` exits 0"
428
+ )
429
+ # One label for every surface this command does not write, because they are not one
430
+ # kind: `CONTRIBUTING.md` is the author's, the driver is a flag away, and the two at
431
+ # the plugin's own root are files the tree already ships (RK235). "by hand" said all
432
+ # three, and on the last two it told the reader to write them.
433
+ rows += [f" not written {why}" for _, why in self.skipped]
434
+ # Beside the surfaces and before the verdict (RK393): this one is not a difference
435
+ # `install` closes, and saying so is the whole repair. The remedy named is the blocker,
436
+ # because that is the file somebody has to move.
437
+ rows += [
438
+ f" blocked {path.relative_to(self.root).as_posix()}: "
439
+ f"{parent.relative_to(self.root).as_posix()} is a file, "
440
+ f"so the directory cannot be made"
441
+ for path, parent in self.blocked
442
+ ]
443
+ return "\n".join(rows)
444
+
445
+ def verdict(self) -> list[str]:
446
+ """What a `--check` has to say on **stderr**, where anything is (RK393).
447
+
448
+ Two sentences and not one, because they are two states: a surface that differs is one
449
+ `install` writes; a surface that is blocked is one it exits 2 on, and a gate whose
450
+ named remedy is a red command sends a CI job round a loop.
451
+
452
+ Its own method rather than the tail of :meth:`stated` (RK1170): these go to a different
453
+ stream, and a register that mixed the two would put the verdict into the file a reader
454
+ redirects stdout into.
455
+ """
456
+ if not self.changing:
457
+ return []
458
+ blocked = {path for path, _ in self.blocked}
459
+ differing = [one for one in self.changing if one.path not in blocked]
460
+ rows = []
461
+ if differing:
462
+ rows.append(
463
+ f"{len(differing)} surface(s) differ from what this checkout ships: "
464
+ f"`{invocation()} install` writes them"
465
+ )
466
+ if self.blocked:
467
+ rows.append(
468
+ f"{len(self.blocked)} surface(s) cannot be written at all: "
469
+ f"move what is standing in the directory first, and `{invocation()} "
470
+ f"install` will not run until you do"
471
+ )
472
+ return rows
473
+
474
+ def payload(self, checked: bool) -> dict[str, object]:
475
+ """The same answer as data, with every state a reader might act on."""
476
+ return {
477
+ "root": self.root.as_posix(),
478
+ "source": self.source.as_posix(),
479
+ "launcher": self.launcher,
480
+ # RK1113: which variant, and whether the project said so rather than the flag. Two
481
+ # keys, because a reader deciding whether to pass `--committed` needs the second
482
+ # one — with `carried` true, passing it changes nothing.
483
+ "committed": self.committed,
484
+ "carried": self.carried,
485
+ "checked": checked,
486
+ "debt": self.debt,
487
+ "surfaces": [
488
+ {
489
+ "path": surface.path.relative_to(self.root).as_posix(),
490
+ "state": surface.state,
491
+ "writes": surface.writes,
492
+ }
493
+ for surface in self.surfaces
494
+ ],
495
+ "skipped": [{"path": path, "why": why} for path, why in self.skipped],
496
+ "registered": None
497
+ if self.registered is None
498
+ else {
499
+ "attributes": self.registered.attributes.as_posix(),
500
+ "added": list(self.registered.added),
501
+ "present": list(self.registered.present),
502
+ "command": self.registered.command,
503
+ "invalidated_by": self.registered.invalidated_by,
504
+ "wiring": None
505
+ if self.registered.wiring is None
506
+ else {
507
+ "attributes": self.registered.wiring.attributes.state,
508
+ "driver": self.registered.wiring.driver.state,
509
+ },
510
+ # Keyed by the field names of `Registration`, and held to them by a test
511
+ # (RK276): the reading most likely to be automated is the one a dropped field
512
+ # is quietest in.
513
+ "left_alone": [list(pair) for pair in self.registered.left_alone],
514
+ },
515
+ "changing": len(self.changing),
516
+ # RK393: the surfaces `install` cannot write, each with the file standing in the
517
+ # way. Its own key and not folded into `changing`, because a reader acting on that
518
+ # number would run the command this one says will not run.
519
+ "blocked": [
520
+ {
521
+ "path": path.relative_to(self.root).as_posix(),
522
+ "blocked_by": parent.relative_to(self.root).as_posix(),
523
+ }
524
+ for path, parent in self.blocked
525
+ ],
526
+ # RK394: what stands in the way of the driver's own file, where anything does. Null
527
+ # and not absent when nothing does, so a reader tells "checked and clear" from
528
+ # "this payload predates the field".
529
+ "driver": None
530
+ if self.driver is None
531
+ else self.driver.relative_to(self.root).as_posix(),
532
+ }
533
+
534
+
535
+ #: `install --check` reports the same four states as a run, in the tense of a run that has not
536
+ #: happened. `kept` and `unchanged` are already that tense: neither describes a write. Beside
537
+ #: the plan since RK1170, the report having moved onto it.
538
+ _WOULD = {
539
+ "created": "would create",
540
+ "updated": "would update",
541
+ "unchanged": "unchanged",
542
+ "kept": "kept, yours",
543
+ }
544
+
545
+
546
+ def plan(
547
+ root: str | Path = ".",
548
+ *,
549
+ source: str | Path | None = None,
550
+ registering: bool = False,
551
+ gauging: bool = True,
552
+ committed: bool = False,
553
+ ) -> Plan:
554
+ """Read the plugin's surfaces and the project's, and answer what would change.
555
+
556
+ Writes nothing, which is what lets `install` and `install --check` be the same
557
+ computation — a check that ran a different code path would be checking something else.
558
+
559
+ ``registering`` only moves the merge driver out of the *unwritten* list (RK148): the
560
+ driver is written by :func:`install`, and a `--check` that registered one would be a
561
+ check that changed the repository.
562
+
563
+ ``gauging`` is the one part a caller may decline: :func:`_standing` runs this project's
564
+ whole gate to choose the workflow's default (RK140), and :func:`stale` asks this question
565
+ on every session start (RK234) where the workflow is not in play at all. Declining it
566
+ reports ``debt`` as None, which is the same answer a project that declares nothing gets.
567
+
568
+ ``committed`` wires the bridge instead of the checkout (RK1108) — a fourth surface, and the
569
+ launcher every declaration then names. Opt-in and never the default, because it answers a
570
+ different question: the default points at the tree this command is running from, which is
571
+ exact and is what an early adopter developing against a checkout wants; the bridge searches
572
+ at runtime, which is the only thing that can work in an environment holding neither a
573
+ plugin nor a checkout. A project that has both is better served by the exact path.
574
+
575
+ Opt-in **for a project that has not chosen yet**, which is the correction RK1113 makes: a
576
+ project already wired to the bridge has chosen, on disk, and the flag is not where that
577
+ answer lives. Without the flag this reads :func:`_carrying` and keeps the variant it finds,
578
+ so `--check` on a `--committed` project reports what actually drifted and the plain
579
+ `install` it names no longer downgrades the wiring. Moving *back* to a checkout path is
580
+ `uninstall` and then `install`, which is the same two commands as any other change of mind
581
+ about a variant — and unlike a flag, it cannot happen by running the repair a check named.
582
+ """
583
+ base = Path(root).resolve()
584
+ origin = Path(source).resolve() if source is not None else _source()
585
+ carried = not committed and _carrying(base)
586
+ committed = committed or carried
587
+ _carried(origin, committed=committed)
588
+
589
+ # Addressed from the project and not from the checkout, which is the whole point: the file
590
+ # is committed, so the path resolves on every machine that clones the repository (RK1108).
591
+ launcher = PROJECT_BRIDGE if committed else _launcher(base, origin)
592
+ hooks = _hooks(origin, launcher)
593
+ server = _server(origin, launcher)
594
+
595
+ # The tree being wired *is* the tree answering (RK235): the two declarations still mean
596
+ # what they mean — point a session at this checkout's tools and its guard, which is what
597
+ # this repository declares by hand (RK81) — and the two copies do not, both being copies
598
+ # of files already in the tree.
599
+ own = base == origin
600
+ surfaces = [
601
+ _declaration(base / PROJECT_MCP, lambda current: _merged_mcp(current, server)),
602
+ ]
603
+ # Conditioned on the tree *providing* the plugin and never on which repository this is
604
+ # (RK402): a fork, a vendored copy and this checkout are the same situation, and a name
605
+ # test would answer for one of them. The `.mcp.json` declaration stays either way — a
606
+ # plugin's server and a project's are two entries the harness reads separately, and only
607
+ # the hooks would fire twice.
608
+ skipped: list[tuple[str, str]] = [(CONTRIBUTING.split(":")[0], CONTRIBUTING)]
609
+ if _provides_plugin(base):
610
+ skipped.insert(0, (PROJECT_SETTINGS, f"{PROJECT_SETTINGS}: {_OWN_HOOKS}"))
611
+ else:
612
+ surfaces.append(
613
+ _declaration(
614
+ base / PROJECT_SETTINGS, lambda current: _merged_settings(current, hooks)
615
+ )
616
+ )
617
+ # A copy and refreshed like the skill, for the skill's reason (RK1108): a vendored program
618
+ # that drifts from the one the plugin ships is read with the same trust and answers with an
619
+ # older rule. Skipped at the plugin's own root, where it would sit beside the file it came
620
+ # from — the narrowing RK235 already makes for the other two copies.
621
+ if committed:
622
+ if own:
623
+ skipped.insert(0, (PROJECT_BRIDGE, f"{PROJECT_BRIDGE}: {_OWN_BRIDGE}"))
624
+ else:
625
+ surfaces.append(_copy(base / PROJECT_BRIDGE, _read(origin / PLUGIN_BRIDGE)))
626
+ driver = blocking(base / ATTRIBUTES)
627
+ if not registering:
628
+ # Three states and no longer two (RK1387). `blocking` answers whether another driver
629
+ # holds the path; `_routed` answers whether ours already does, which is the question
630
+ # this row never asked and `merge --check` has always answered.
631
+ described = (
632
+ MERGE_BLOCKED.format(blocker=driver.name)
633
+ if driver is not None
634
+ else MERGE_WIRED.format(invocation=invocation())
635
+ if _routed(base)
636
+ else MERGE.format(invocation=invocation())
637
+ )
638
+ skipped.insert(0, (described.split(":")[0], described))
639
+ debt = _standing(base) if gauging else None
640
+ if own:
641
+ skipped.insert(0, (PROJECT_SKILL, f"{PROJECT_SKILL}: {_OWN_SKILL}"))
642
+ else:
643
+ surfaces.append(
644
+ _copy(base / PROJECT_SKILL, _skill(origin, launcher, committed=committed))
645
+ )
646
+ if own:
647
+ skipped.insert(0, (PROJECT_WORKFLOW, f"{PROJECT_WORKFLOW}: {_OWN_WORKFLOW}"))
648
+ elif (base / WORKFLOWS).is_dir():
649
+ surfaces.append(_once(base / PROJECT_WORKFLOW, _workflow(origin, debt)))
650
+ else:
651
+ skipped.insert(0, (PROJECT_WORKFLOW, f"no {WORKFLOWS}/ — this project has no CI to gate"))
652
+ return Plan(
653
+ root=base,
654
+ source=origin,
655
+ launcher=launcher,
656
+ surfaces=tuple(surfaces),
657
+ skipped=tuple(skipped),
658
+ debt=debt,
659
+ # Over what would be written and never every surface: a directory nobody needs to
660
+ # create is not in anybody's way (RK393).
661
+ blocked=tuple(
662
+ (surface.path, parent)
663
+ for surface in surfaces
664
+ if surface.writes and (parent := blocking(surface.path))
665
+ ),
666
+ # Always, and not only under `--register-merge` (RK394): the report names the flag on
667
+ # every run, so whether running it could work is part of every run's answer.
668
+ driver=driver,
669
+ committed=committed,
670
+ carried=carried,
671
+ )
672
+
673
+
674
+ def install(
675
+ root: str | Path = ".",
676
+ *,
677
+ source: str | Path | None = None,
678
+ register_merge: bool = False,
679
+ committed: bool = False,
680
+ ) -> Plan:
681
+ """Write every surface that would change, or write nothing.
682
+
683
+ The order is `init`'s and for `init`'s reason: everything that can refuse has refused by
684
+ the time the first file is opened, because a project wired for the tools but not for the
685
+ hook is a project that looks governed and is not.
686
+
687
+ ``register_merge`` adds the fifth (RK148): the `.gitattributes` half of `merge --register`,
688
+ for a caller that asked. A flag and never a default, because the other half is a line in
689
+ somebody's `git config` — which this command prints and does not run (L2) — and the
690
+ project's own config is resolved *before* the first write, so a project with nothing to
691
+ register refuses instead of leaving four surfaces written and a flag unhonoured.
692
+ """
693
+ intent = plan(root, source=source, registering=register_merge, committed=committed)
694
+ # With the rest of the refusals and above the first write (RK393), which is what the
695
+ # paragraph above claims and the `mkdir` below used to break.
696
+ if intent.blocked:
697
+ raise BlockedParent(intent.blocked, intent.root)
698
+ if register_merge and intent.driver is not None:
699
+ # The config was already resolved up here and the file was not (RK394), so the flag
700
+ # was honoured or not by a write three modules along and after the loop below — four
701
+ # surfaces on disk, the driver unwired, and `--check` green over it.
702
+ raise BlockedParent([(intent.root / ATTRIBUTES, intent.driver)], intent.root)
703
+ governed = _governed(intent.root) if register_merge else None
704
+ for surface in intent.changing:
705
+ surface.path.parent.mkdir(parents=True, exist_ok=True)
706
+ surface.path.write_text(surface.text, encoding="utf-8", newline="")
707
+ if governed is not None:
708
+ intent = replace(intent, registered=register(governed))
709
+ return intent
710
+
711
+
712
+ def stale(root: str | Path = ".") -> tuple[str, ...]:
713
+ """The vendored surfaces that have drifted from the checkout answering here (RK234).
714
+
715
+ `--check` is what RK100 named as holding the copy in step, and nothing in an adopting
716
+ project ran it: Turing's `SKILL.md` was 78 lines behind and its `PreToolUse` matcher was
717
+ missing `Bash` — a guard narrower than the one the plugin ships, in the file that decides
718
+ whether the guard fires. So the question is asked where it is cheap to ask and useful to
719
+ answer: the session start, in the process that is already the wired checkout.
720
+
721
+ **What a project that is not wired pays is one `is_file`.** The vendored copy is the
722
+ discriminator, and a plugin-served project has none — there is nothing to drift, and the
723
+ plugin's own surfaces are whatever the session loaded. A wired one pays four small reads
724
+ and two JSON parses, and never the gate: ``gauging=False``, the workflow being written
725
+ once and then the adopter's, so it is excluded here by the same field that says so.
726
+
727
+ Measured against RK176's 43ms floor, which is the budget this spends from: **0.07ms**
728
+ unwired and **0.86ms** on Dumont, wired. The gate would have been 40ms of that floor on
729
+ its own, which is why declining it is a parameter rather than a comment.
730
+
731
+ Every failure is silence, exactly as the notice this feeds is (RK82): a session that
732
+ cannot start because a checkout moved is worse than one told nothing, and `install
733
+ --check` still answers on demand.
734
+ """
735
+ base = Path(root).resolve()
736
+ if not (base / PROJECT_SKILL).is_file():
737
+ return ()
738
+ try:
739
+ intent = plan(base, gauging=False)
740
+ except (ValueError, OSError):
741
+ return ()
742
+ return tuple(
743
+ surface.path.relative_to(base).as_posix()
744
+ for surface in intent.changing
745
+ if surface.refresh
746
+ )
747
+
748
+
749
+ #: What :attr:`Engines.verdict` answers (RK418). Three and not two, because a checkout with
750
+ #: uncommitted work is at no commit the plugin could match — so `agreed` would be the defect
751
+ #: and `behind` a direction nothing measured.
752
+ AGREED = "agreed"
753
+ BEHIND = "behind"
754
+ UNPINNABLE = "unpinnable"
755
+
756
+
757
+ @dataclass(frozen=True, slots=True)
758
+ class Engines:
759
+ """Every copy of this tool one project runs, read back together (RK415).
760
+
761
+ **Four are read and three are judged** (RK1392). RK1385 added the merge driver, which git
762
+ runs when nobody is watching, and it is deliberately not in the verdict: `agreed`, `behind`
763
+ and `unpinnable` compare versions, and this tool refuses to execute a recorded driver to
764
+ ask for one. So a count states which of the two questions a sentence is about, and the
765
+ three below are the copies that *wrote, judged or gated* something already.
766
+
767
+ An adopting project wires three: the plugin its `PreToolUse` hook and skill run, the
768
+ action its workflow gates on, and whatever `roadkeep` the caller invokes — which on a
769
+ machine that also develops this tool is a checkout. Measured live, all three at once: the
770
+ checkout at 0.1.418 doing every write, the plugin at 0.1.285 denying the hand edits, and
771
+ `@main` in CI. Every write was fine; what nothing said is that the pen and the judge were
772
+ 133 versions apart, in a project whose own backlog reasoned about *the plugin this
773
+ repository runs* while a newer one held the pen.
774
+
775
+ Read and never reconciled, which is :mod:`roadkeep.provenance`'s rule one level up: a
776
+ cache is allowed to lag a checkout, and what is not survivable is being unable to say
777
+ which of them answered.
778
+ """
779
+
780
+ #: The copy this process is, always known.
781
+ running: Engine
782
+ #: The copy the harness wired to this project, or None where none is registered — which
783
+ #: is every project served by a checkout alone, and is not a defect.
784
+ plugin: Installed | None = None
785
+ #: `(file, ref)` per workflow step calling the action, in file order.
786
+ gates: tuple[tuple[str, str], ...] = ()
787
+ #: The command git would run to merge a governed file, or `""` where nothing is wired
788
+ #: (RK1385). The **fourth** copy, and the one that runs when nobody is watching: git
789
+ #: invokes it mid-merge, on the files whose whole claim is that their merge is decidable,
790
+ #: and until this row neither `engines` nor `merge --check` said which copy it is —
791
+ #: `--check` answers whether git can run it, which is a different question (RK266).
792
+ #:
793
+ #: The command and never its version: reading that would mean *running* somebody's
794
+ #: recorded driver, which `merging._resolves` refuses on its own argument. What a reader
795
+ #: gets is the path beside the tree above, which is the comparison they came for.
796
+ driver: str = ""
797
+
798
+ @property
799
+ def verdict(self) -> str:
800
+ """`agreed`, `behind` or `unpinnable` — three states, because two are not enough (RK418).
801
+
802
+ The comparison used to be the release string alone, which is the one fact an earlier
803
+ task proved insufficient: two `src/roadkeep/` trees fourteen files apart answered the
804
+ same number, and that is why the running engine carries its directory and its commit
805
+ at all. Both copies have a revision — the running one from git, the installed one from
806
+ the marketplace row that records the sha it was built at — and both were read, both
807
+ printed, and neither compared.
808
+
809
+ The case that got through is the one a machine developing this tool is in every day: a
810
+ checkout at the plugin's own version, with uncommitted work, writing; the plugin
811
+ judging; the numbers matching and the verb saying they agree. The files do not.
812
+
813
+ So the third state is its own, and collapsing it would be wrong either way. A checkout
814
+ whose files are **modified** is at no commit the plugin could match — calling that
815
+ `behind` asserts a direction nothing measured, and calling it `agreed` is the defect
816
+ this fixes. `unpinnable` says the only true thing: these two cannot be compared, and
817
+ the reason is on the running engine's own `revision`.
818
+
819
+ Where a commit is missing on either side the version is still the best fact available,
820
+ so it decides — a marketplace row that recorded no sha is not evidence of a difference.
821
+ """
822
+ if self.plugin is None:
823
+ return AGREED
824
+ if self.plugin.version != self.running.version:
825
+ return BEHIND
826
+ if self.running.modified:
827
+ return UNPINNABLE
828
+ if self.plugin.commit and self.running.commit:
829
+ # Both known and both at one version: the sha is what tells the trees apart, and
830
+ # it is compared on the prefix because the marketplace records a short one.
831
+ short = min(len(self.plugin.commit), len(self.running.commit), 7)
832
+ if self.plugin.commit[:short] != self.running.commit[:short]:
833
+ return BEHIND
834
+ return AGREED
835
+
836
+ @property
837
+ def agree(self) -> bool:
838
+ """Whether the two engines that state a version are the same copy of this tool.
839
+
840
+ The gate is deliberately not in this: `main` and `v0.2.1` and `./` are refs, and a
841
+ ref is not a number to compare — what CI runs is decided when CI runs. It is reported
842
+ beside the two because a reader comparing them needs to know a third exists.
843
+
844
+ `unpinnable` is **not** agreement (RK418): a boolean has to fall one way, and the
845
+ state this exists to stop being silent about is exactly the one where the numbers
846
+ match and the files do not.
847
+ """
848
+ return self.verdict == AGREED
849
+
850
+ def invoke(self) -> str:
851
+ """The shell command that reaches the copy **wired to this project** (RK1230).
852
+
853
+ The MCP tools always reach the right copy; the shell does not, and a session that
854
+ needs the shell has to know which one to invoke — `lint --fix` is withheld from the
855
+ tool surface, so any repair goes there. Nothing said which.
856
+
857
+ Observed across one long session: commands were run against a copy found by *listing*
858
+ a plugins cache directory, while the engine the project writes with lived under a
859
+ different plugins root entirely. The stale copy did not fail. It agreed with a rule
860
+ that had moved, and answered plausibly, which is the part that matters.
861
+
862
+ One line and nothing else, so it can be read into a shell variable rather than
863
+ recognised inside a report. :meth:`stated` already prints the same paths in a table,
864
+ and a table is the thing a caller was reduced to grepping.
865
+
866
+ The **plugin's** where one is registered, because that is what "wired to this project"
867
+ means — the copy the hook and the skill run. Where none is, the honest answer is the
868
+ running engine's own invocation: with nothing wired, the copy the caller reaches *is*
869
+ the one that answers, and naming a second would be inventing a disagreement.
870
+ """
871
+ if self.plugin is not None and self.plugin.home is not None:
872
+ return f"python {(self.plugin.home / LAUNCHER).as_posix()}"
873
+ return invocation()
874
+
875
+ def stated(self) -> str:
876
+ """Every copy this project runs, and where the three that state a version differ.
877
+
878
+ Four rows and three compared (RK415, RK418, RK1392): the driver is read and never
879
+ judged, which is why it carries a command rather than a number.
880
+
881
+ Beside :meth:`payload` since RK1170. Every absence is **said** rather than left as a
882
+ missing row: "no plugin" and "a plugin this could not read" look the same to a reader,
883
+ and only one of them means the writes are unjudged by a second copy.
884
+ """
885
+ running, plugin = self.running, self.plugin
886
+ rows = [
887
+ f"writing {running.version:<10}{running.revision} {running.home.as_posix()}"
888
+ ]
889
+ if plugin is None:
890
+ rows.append("plugin — no plugin is registered for this project")
891
+ else:
892
+ home = "" if plugin.home is None else f" {plugin.home.as_posix()}"
893
+ rows.append(
894
+ f"plugin {plugin.version:<10}{plugin.revision} {plugin.scope} scope{home}"
895
+ )
896
+ rows += [f"gate {ref:<10}{where}" for where, ref in self.gates or ()]
897
+ if not self.gates:
898
+ rows.append("gate — no workflow here calls the action")
899
+ # The fourth (RK1385). Said either way, for the reason every absence here is: a driver
900
+ # nothing wired and a driver this could not read look the same to a reader, and only
901
+ # one of them means a conflict falls back to git's own markers.
902
+ #
903
+ # **And it says which half it read** (RK1388). This wiring has two — the attribute
904
+ # lines a repository commits, and the config this clone holds — and the row reads the
905
+ # second. Written flat, it answered *no driver is wired* about a tree whose files
906
+ # `install --check` reports as routed, so the two read as contradicting each other and
907
+ # reconciling them meant already knowing which half each had inherited. The word is
908
+ # `merge --check`'s own, that verb being the one which labels both.
909
+ if not self.driver:
910
+ rows.append(
911
+ "merge — nothing in this clone's git config, so a conflict falls "
912
+ "back to git's markers: `merge --check` reads the attribute half too"
913
+ )
914
+ else:
915
+ here = self.running.home.parent.parent.as_posix()
916
+ whose = (
917
+ " this tree"
918
+ if self.driver.startswith(here)
919
+ else " another copy — `merge --check` names the line that re-wires it"
920
+ )
921
+ rows.append(f"merge {self.driver}{whose}")
922
+ if self.verdict == UNPINNABLE:
923
+ # The state that used to read as agreement, and the one a machine developing this
924
+ # tool is in every day (RK418): the numbers match, the checkout has uncommitted
925
+ # work, and the files the two copies hold are not the same files.
926
+ rows.append(
927
+ f"differ both state {running.version} and this checkout is modified at "
928
+ f"{running.revision}, so the two cannot be compared: commit, or read a hook's "
929
+ f"refusal as that copy's rule rather than this one's"
930
+ )
931
+ elif not self.agree:
932
+ rows.append(
933
+ f"differ the pen is {running.version} at {running.revision} and the judge "
934
+ f"is {plugin.version if plugin else '—'} at "
935
+ f"{plugin.revision if plugin else '—'}: `/plugin update` moves the judge, and "
936
+ f"until then a hook's refusal is that copy's rule and not this one's"
937
+ )
938
+ return chr(10).join(rows)
939
+
940
+ def payload(self) -> dict[str, object]:
941
+ running, plugin = self.running, self.plugin
942
+ return {
943
+ # `writing`, which is what this copy *does* and not what it is: the reader is
944
+ # deciding whose rule a refusal was, so the key names the role and the plugin
945
+ # below names the other one.
946
+ "writing": {
947
+ "version": running.version,
948
+ "home": running.home.as_posix(),
949
+ "revision": running.revision,
950
+ },
951
+ # Null where no plugin is registered for this project, which is every tree served
952
+ # by a checkout alone and is not a defect (RK415).
953
+ "plugin": None
954
+ if plugin is None
955
+ else {
956
+ "version": plugin.version,
957
+ "home": None if plugin.home is None else plugin.home.as_posix(),
958
+ "revision": plugin.revision,
959
+ "scope": plugin.scope,
960
+ },
961
+ "gates": [{"file": where, "ref": ref} for where, ref in self.gates],
962
+ # The fourth copy (RK1385), as the command and never as a version: reading that
963
+ # would mean running it. `""` and never omitted, so a consumer tells "nothing
964
+ # wired" from "this build predates the row".
965
+ "driver": self.driver,
966
+ # The command a shell caller runs (RK1230), on the ordinary payload as well as
967
+ # behind its own flag: a consumer already reading this answer should not have to
968
+ # make a second call for the one field it acts on.
969
+ "invoke": self.invoke(),
970
+ "agree": self.agree,
971
+ # Which of the three, because the boolean above cannot carry the state RK418
972
+ # added: a checkout with uncommitted work is at no commit the plugin could match,
973
+ # and `agreed` there was the defect being fixed.
974
+ "verdict": self.verdict,
975
+ }
976
+
977
+
978
+ def _routed(root: Path) -> bool:
979
+ """Whether the governed files already route to this driver (RK1387).
980
+
981
+ Off `merging.attributed`, which is `register`'s own read: two computations of *the line
982
+ this role wants* is how a check and a write come to disagree, and that function was written
983
+ to be the one both ask. What it answers here is the **attribute** half — a fact about a
984
+ committed file, and this report's business — while whether this clone can run what they
985
+ route to is per checkout and is what `merge --check` exists to say.
986
+
987
+ False on a tree this cannot read, which is the same direction every other absence in this
988
+ report takes: an unreadable project is one nothing is wired in as far as a reader can tell,
989
+ and offering the command there is the honest half.
990
+ """
991
+ from roadkeep.config import Config # noqa: PLC0415 - RK260
992
+ from roadkeep.merging import attributed # noqa: PLC0415 - RK260
993
+
994
+ try:
995
+ found = attributed(Config.discover(root))
996
+ except Exception: # noqa: BLE001 - an unreadable tree is an unwired one to this reader
997
+ return False
998
+ return bool(found.wanted) and not set(found.wanted) - set(found.present)
999
+
1000
+
1001
+ def engines(root: str | Path = ".") -> Engines:
1002
+ """The three, for one project. Reads four small files and asks git nothing new."""
1003
+ base = Path(root).resolve()
1004
+ return Engines(
1005
+ running=engine(),
1006
+ plugin=installed(base),
1007
+ gates=gated_at(base),
1008
+ # The fourth copy (RK1385), read out of git config and never run. Swallowed the way
1009
+ # every other absence here is: a tree git cannot be asked about answers "nothing
1010
+ # wired", which is what a reader of an unwired project sees anyway.
1011
+ driver=_driver(base),
1012
+ )
1013
+
1014
+
1015
+ def _driver(root: Path) -> str:
1016
+ """The command git would run to merge a governed file, or `""` (RK1385).
1017
+
1018
+ Off `merging.registered`, which is the reader that already owns this question — a second
1019
+ `git config --get` here would be the two coming to disagree about which key is the driver.
1020
+
1021
+ A read of the *config* and never of the command: whether the thing it names still exists
1022
+ is `merge --check`'s answer, and whether it is this tree is the comparison the row states.
1023
+ """
1024
+ from roadkeep.config import Config # noqa: PLC0415 - RK260
1025
+ from roadkeep.merging import registered # noqa: PLC0415 - RK260
1026
+
1027
+ try:
1028
+ return registered(Config.discover(root)).stored
1029
+ except Exception: # noqa: BLE001 - an unreadable tree is an unwired one to this reader
1030
+ return ""
1031
+
1032
+
1033
+ def behind(root: str | Path = ".") -> bool:
1034
+ """Whether the copy running is older than the one registered here, paying for git only
1035
+ where the cheap facts cannot decide (RK1237).
1036
+
1037
+ RK1235 put :func:`engines` in front of every governed write on a pinned project and never
1038
+ measured it. It is **45 ms** — three git subprocesses, 14 for `ls-files`, 14 for
1039
+ `rev-parse` and 16 for `status --porcelain` — against RK176's 43 ms floor for a whole
1040
+ command, and cached per *process*, which is once per write on a CLI and never twice.
1041
+
1042
+ The narrowing RK1237 filed was to drop `status --porcelain`, and that reading was wrong:
1043
+ `modified` is exactly what separates `unpinnable` from `behind`, and this guard has to
1044
+ make that separation — a developer's checkout with uncommitted work at the plugin's
1045
+ version but on another commit is `unpinnable`, and refusing it is the failure the whole
1046
+ design exists to avoid.
1047
+
1048
+ What is actually free is the **version**, which is a module attribute. :attr:`Engines.
1049
+ verdict` already decides on it first and reaches for a sha only where the two match, so
1050
+ the fix is not a second rule but a cheaper *reading* handed to the same one: ask with the
1051
+ commit unknown, which is the state a marketplace row with no sha already produces, and
1052
+ escalate only where that answer was `agreed` and a plugin exists to disagree. A project
1053
+ running a copy at another version — the case this guard is for — pays nothing.
1054
+
1055
+ Measured after: **2 ms** where no plugin is registered or the versions differ, against 45
1056
+ for the reading it replaces — the registry is a JSON file and the version is an attribute.
1057
+ Only two copies claiming one version pay for git, and that is the one case where nothing
1058
+ cheaper could tell them apart.
1059
+
1060
+ One verdict and never two, which is :meth:`~roadkeep.kernel.document.Document.holds`'
1061
+ rule (RK300): what changes between the two calls is the facts, never the judgement.
1062
+ """
1063
+ base = Path(root).resolve()
1064
+ cheap = Engines(running=engine(placed=False), plugin=installed(base))
1065
+ if cheap.plugin is None or cheap.verdict == BEHIND:
1066
+ return cheap.verdict == BEHIND
1067
+ return engines(base).verdict == BEHIND
1068
+
1069
+
1070
+ #: A workflow step calling this action, in either of the two spellings a repository writes:
1071
+ #: `<owner>/roadkeep@<ref>` in an adopting project, and `./` in the tree that *is* the action.
1072
+ #: The owner is not matched, because a fork publishes the same action under another name and
1073
+ #: the question is which ref gates this project rather than whose copy does.
1074
+ _GATE_RE = re.compile(
1075
+ r"^\s*-?\s*uses:\s*(?P<action>\./|[^\s#]*?/roadkeep)(?:@(?P<ref>[^\s#]+))?\s*(?:#.*)?$",
1076
+ re.MULTILINE,
1077
+ )
1078
+
1079
+
1080
+ def _provides_plugin(base: Path) -> bool:
1081
+ """Whether this tree already runs the guard as a plugin of its own (RK402).
1082
+
1083
+ Asked of the two files that make it true rather than of the root's name: the manifest
1084
+ that declares the plugin, and the hooks file it points at. A fork, a vendored copy and
1085
+ this checkout are the same situation, and a name test would answer for exactly one.
1086
+
1087
+ Both, because either alone is a different state: a manifest with no hooks file declares
1088
+ nothing that runs, and a hooks file no manifest names is a file the harness never loads —
1089
+ and in both of those the project settings are still the only place the guard could live.
1090
+ """
1091
+ return (base / PLUGIN_MANIFEST).is_file() and (base / PLUGIN_HOOKS).is_file()
1092
+
1093
+
1094
+ def gated_at(root: str | Path = ".") -> tuple[tuple[str, str], ...]:
1095
+ """Which ref of this action every workflow calls, as `(file, ref)` in file order (RK415).
1096
+
1097
+ The third engine, and the only one stated in a file the project owns: the checkout
1098
+ answers for itself and the plugin is a row in the harness's registry, while CI runs
1099
+ whatever a `uses:` line names — `main` as `install` writes it, a tag where an adopter
1100
+ pinned one, and `./` in this tree, which gates on its own working copy.
1101
+
1102
+ Every workflow and not the one this command writes, because an adopter is free to call
1103
+ the gate from a pipeline of their own and a reader that only knew `roadkeep.yml` would
1104
+ report *no gate* about a repository that has one. The file rides with the ref and
1105
+ duplicates are kept: two workflows calling two refs is the disagreement this exists to
1106
+ show, not a set to fold, and folding it would lose the one thing that locates the fix.
1107
+
1108
+ Empty where the directory is absent or unreadable — a repository with no workflows has
1109
+ not asked for CI, which is a different answer from one whose ref cannot be read, and
1110
+ neither is worth failing over.
1111
+ """
1112
+ base = Path(root).resolve()
1113
+ directory = base / WORKFLOWS
1114
+ refs: list[tuple[str, str]] = []
1115
+ try:
1116
+ files = sorted(
1117
+ path
1118
+ for path in directory.iterdir()
1119
+ if path.suffix in (".yml", ".yaml") and path.is_file()
1120
+ )
1121
+ except OSError:
1122
+ return ()
1123
+ for path in files:
1124
+ try:
1125
+ body = path.read_text(encoding="utf-8")
1126
+ except (OSError, ValueError):
1127
+ continue
1128
+ refs.extend(
1129
+ # A local `uses: ./` carries no ref and is the tree itself, said as the caller
1130
+ # spelled it rather than resolved to a revision this function has no business
1131
+ # asking git for.
1132
+ (path.relative_to(base).as_posix(), found.group("ref") or found.group("action"))
1133
+ for found in _GATE_RE.finditer(body)
1134
+ )
1135
+ return tuple(refs)
1136
+
1137
+
1138
+ def _governed(base: Path) -> Config:
1139
+ """This project's own configuration, or a refusal naming what a driver would be for.
1140
+
1141
+ A driver is registered per *governed file*, so a project that declares none has nothing to
1142
+ register: writing `.gitattributes` lines for the paths a default config happens to name
1143
+ would wire a driver for files nobody declared (L6).
1144
+ """
1145
+ config = Config.discover(base)
1146
+ if config.source is None:
1147
+ raise ValueError(
1148
+ f"{base} declares no {CONFIG_NAME} and nothing was registered: a merge driver is "
1149
+ f"wired per governed file, so `{invocation()} init` (or a config) comes first — the "
1150
+ f"four surfaces above do not depend on it"
1151
+ )
1152
+ return config
1153
+
1154
+
1155
+ # -- where the surfaces are read from ----------------------------------------
1156
+
1157
+
1158
+ def _source() -> Path:
1159
+ """The tree that is answering, as a plugin root: the parent of the package's `src/`.
1160
+
1161
+ Taken from :func:`~roadkeep.provenance.engine`, which already resolves *which copy of
1162
+ this package is running* — the same question, and the one thing a plugin cache and a
1163
+ checkout disagree about (RK79). Deriving it a second way here would be a second answer.
1164
+ """
1165
+ return engine().home.parent.parent
1166
+
1167
+
1168
+ def _carried(root: Path, *, committed: bool = False) -> None:
1169
+ """Refuse a tree that is not carrying what this run has to translate, naming what it lacks.
1170
+
1171
+ The bridge is asked for only under `--committed` (RK1108) and is deliberately not in
1172
+ :data:`CARRIED`: that list also decides whether a tree *is* the plugin, so adding a sixth
1173
+ file would make an older checkout stop being recognised as one. Asked here instead, so a
1174
+ source that predates the bridge is refused by name rather than by an errno from the copy.
1175
+ """
1176
+ wanted = (*CARRIED, PLUGIN_BRIDGE) if committed else CARRIED
1177
+ missing = tuple(part for part in wanted if not (root / part).is_file())
1178
+ if missing:
1179
+ raise NotShipped(root, missing)
1180
+
1181
+
1182
+ def _ships_the_plugin(root: Path) -> bool:
1183
+ """Whether this tree *is* the plugin rather than a project that adopted it (RK235).
1184
+
1185
+ Asked of the files rather than of a source, because :func:`removal` is given no checkout
1186
+ to compare against — it recognises a wiring by this project's own entries, which is what
1187
+ lets it run after the tree it pointed at is gone. Where a source *is* known,
1188
+ :func:`plan` compares the two roots instead, that being the exact statement.
1189
+ """
1190
+ return all((root / part).is_file() for part in CARRIED)
1191
+
1192
+
1193
+ def _standing(base: Path) -> int | None:
1194
+ """What this project's own gate reports today, or None where it cannot be asked (RK140).
1195
+
1196
+ Run while the workflow is being written, because that is the one moment the difference
1197
+ between a strict gate and a baselined one is knowable without being told: the projects
1198
+ that most need the gate are the ones carrying the most debt, and a workflow that is red on
1199
+ its first push is a gate an adopter switches off rather than reads.
1200
+
1201
+ None for a project that declares nothing — there is no governed file to be in debt about,
1202
+ so the strict workflow is the honest one — and None again where the gate itself refused,
1203
+ because `install` writes four surfaces and a lint that raised is not a reason to write
1204
+ none of them.
1205
+
1206
+ **`install.stale` is not debt and is subtracted** (RK1192). The gate now reports a wired
1207
+ surface behind the engine answering, and its remedy is this very command — so counting one
1208
+ here would bake the work `install` is running *in order to do* into the baseline it writes,
1209
+ and the number would go down by itself on the next push. Every other finding is the
1210
+ project's own backlog and is exactly what a baseline is for; this one is the state that
1211
+ ends the moment these surfaces are written.
1212
+ """
1213
+ try:
1214
+ config = Config.discover(base)
1215
+ if config.source is None:
1216
+ return None
1217
+ return sum(
1218
+ 1 for one in lint(config).findings if one.code != "install.stale"
1219
+ )
1220
+ except (ValueError, OSError):
1221
+ return None
1222
+
1223
+
1224
+ def _carrying(base: Path) -> bool:
1225
+ """Whether this project's own declarations run the committed launcher (RK1113).
1226
+
1227
+ The variant is a property of the project and `--check` read it off the **flag**, so a tree
1228
+ adopted `--committed` was told every one of its surfaces had drifted and handed the plain
1229
+ `install` as the repair — which rewrites them to a checkout path, the one change the bridge
1230
+ exists to prevent: the file stays on disk, nothing references it, and a web session loses
1231
+ its hook. Measured on dockerdesk at acc7fc1, a tree with no local edits: "3 surface(s)
1232
+ differ", and `install --committed` restored all three to exactly HEAD.
1233
+
1234
+ Read the way :func:`removal` reads (RK284, RK1108) — **this project's own entry** and no
1235
+ checkout — and both halves of it, because either alone is a different state. A bridge
1236
+ nothing references is what a downgrade leaves behind; a declaration naming a bridge that is
1237
+ not there is a project whose launcher was deleted. Neither is wired to it, so both are drift
1238
+ against the default, where the repair is the `install --committed` that puts it back.
1239
+
1240
+ A substring and not a parse: what is being asked is whether the path this command writes
1241
+ appears where this command writes it, and the two declarations spell it under different
1242
+ placeholders (:data:`PROJECT_DIR` and :data:`PROJECT_DIR_OR_CWD`) — so matching the launcher
1243
+ itself is the one test that does not need to know which of them a surface used.
1244
+ """
1245
+ if not (base / PROJECT_BRIDGE).is_file():
1246
+ return False
1247
+ for name in (PROJECT_SETTINGS, PROJECT_MCP):
1248
+ try:
1249
+ if PROJECT_BRIDGE in _read(base / name):
1250
+ return True
1251
+ except OSError:
1252
+ # A declaration that is not there says nothing about the variant, and an
1253
+ # unreadable one is not this command's refusal to make: `_declaration` reads the
1254
+ # same file one step on and reports it as the surface it is.
1255
+ continue
1256
+ return False
1257
+
1258
+
1259
+ def _launcher(base: Path, origin: Path) -> str:
1260
+ """The launcher, addressed from the adopting project — the one substituted fact.
1261
+
1262
+ Relative wherever a relative path exists, so a pair of sibling checkouts wires up the
1263
+ same on every machine that has them; absolute only when there is none to write, which on
1264
+ Windows means the two trees are on different drives.
1265
+ """
1266
+ try:
1267
+ relative = os.path.relpath(origin, base).replace(os.sep, "/")
1268
+ except ValueError:
1269
+ return (origin / LAUNCHER).as_posix()
1270
+ return LAUNCHER if relative == "." else f"{relative}/{LAUNCHER}"
1271
+
1272
+
1273
+ def _rooted(command: str, launcher: str, placeholder: str) -> str:
1274
+ """One plugin-rooted path, re-addressed to the project. Absolute paths lose the prefix."""
1275
+ target = launcher if launcher.startswith("/") or ":" in launcher.split("/")[0] else None
1276
+ if target is not None:
1277
+ return command.replace(f"{PLUGIN_ROOT}/{LAUNCHER}", target)
1278
+ return command.replace(f"{PLUGIN_ROOT}/{LAUNCHER}", f"{placeholder}/{launcher}")
1279
+
1280
+
1281
+ def _hooks(origin: Path, launcher: str) -> dict:
1282
+ """The plugin's hook declaration with the launcher re-addressed, and nothing else moved.
1283
+
1284
+ The events, the matcher and the timeouts arrive from the file — so the matcher that
1285
+ `tests/test_plugin.py` holds against :data:`~roadkeep.guarding.WRITE_TOOLS` is the matcher
1286
+ every adopting project gets, and a fourth event reaches them all by being declared once.
1287
+ """
1288
+ declared = json.loads(_read(origin / PLUGIN_HOOKS))["hooks"]
1289
+ return {
1290
+ event: [
1291
+ {
1292
+ **group,
1293
+ "hooks": [
1294
+ {**hook, "command": _rooted(hook["command"], launcher, PROJECT_DIR)}
1295
+ for hook in group["hooks"]
1296
+ ],
1297
+ }
1298
+ for group in groups
1299
+ ]
1300
+ for event, groups in declared.items()
1301
+ }
1302
+
1303
+
1304
+ def _server(origin: Path, launcher: str) -> dict:
1305
+ """The plugin's server declaration, addressed the way a project's own `.mcp.json` is."""
1306
+ server = json.loads(_read(origin / PLUGIN_MCP))["mcpServers"][SERVER]
1307
+ return {
1308
+ **server,
1309
+ "args": [_rooted(arg, launcher, PROJECT_DIR_OR_CWD) for arg in server["args"]],
1310
+ }
1311
+
1312
+
1313
+ def _workflow(origin: Path, debt: int | None) -> str:
1314
+ """The gate as CI calls it: the action this repository publishes, at one line.
1315
+
1316
+ The repository is read out of the plugin manifest rather than written here, because the
1317
+ manifest is what an install already trusts to say where this tool comes from.
1318
+
1319
+ ``debt`` is what this project's own gate reports **today** (RK140), which is what decides
1320
+ between the two honest defaults. A backlog with standing findings gets the baseline, so
1321
+ the gate fails on what a branch adds and forgives what nobody was going to redo — and the
1322
+ count is named in the comment, because a baseline nobody remembers to remove is the other
1323
+ failure mode. A project already clean gets the strict gate and no comment to act on.
1324
+ """
1325
+ repository = json.loads(_read(origin / PLUGIN_MANIFEST))["repository"]
1326
+ action = repository.removeprefix("https://github.com/").removesuffix(".git").strip("/")
1327
+ head = [
1328
+ "# The gate the write path already runs locally, called in CI through the action",
1329
+ "# roadkeep publishes rather than a copied `run:` block, which drifts per",
1330
+ "# repository. `roadkeep lint` exits 1 on a governed file that drifted, and that",
1331
+ "# exit code is the whole contract.",
1332
+ "#",
1333
+ ]
1334
+ if not debt:
1335
+ head.append(
1336
+ "# Yours from here: `with: {directory: .}` where roadkeep.toml is not at the root,"
1337
+ )
1338
+ head.append(
1339
+ "# and `with: {baseline: origin/main}` to fail on what a branch added rather than"
1340
+ )
1341
+ head.append("# on a backlog's standing debt.")
1342
+ else:
1343
+ head += [
1344
+ f"# Baselined, because `roadkeep lint` reported {debt} finding(s) here when this",
1345
+ "# was written: the gate fails on what a branch adds and forgives the standing",
1346
+ "# debt by name, which is the only setting a late gate can be switched on under.",
1347
+ "# Drop the `baseline:` line — and the fetch-depth above it — the day `lint`",
1348
+ "# exits 0 on the default branch, and the gate is absolute.",
1349
+ "#",
1350
+ "# Yours from here: `with: {directory: .}` where roadkeep.toml is not at the root.",
1351
+ ]
1352
+ checkout = [" - uses: actions/checkout@v4"]
1353
+ step = [f" - uses: {action}@{ACTION_REF}"]
1354
+ if debt:
1355
+ # A baseline is a rev, so the diff needs the history to take it against.
1356
+ checkout += [" with:", " fetch-depth: 0"]
1357
+ step += [
1358
+ " with:",
1359
+ " # `base_ref` on a pull request, the default branch on a push — where",
1360
+ " # the two coincide the diff is empty and the gate passes on the debt.",
1361
+ " baseline: origin/${{ github.base_ref || "
1362
+ "github.event.repository.default_branch }}",
1363
+ ]
1364
+ return "\n".join(
1365
+ (
1366
+ *head,
1367
+ "name: roadkeep",
1368
+ "",
1369
+ "on: [push, pull_request]",
1370
+ "",
1371
+ "jobs:",
1372
+ " lint:",
1373
+ " name: roadkeep lint",
1374
+ " runs-on: ubuntu-latest",
1375
+ " steps:",
1376
+ *checkout,
1377
+ *step,
1378
+ "",
1379
+ )
1380
+ )
1381
+
1382
+
1383
+ # -- what each kind of surface does to the file it lands in -------------------
1384
+
1385
+
1386
+ def _skill(origin: Path, launcher: str, *, committed: bool = False) -> str:
1387
+ """The plugin's skill with its entry point re-addressed — the fourth substitution (RK137).
1388
+
1389
+ `install` states that the launcher's path is the only substituted fact, and the skill was
1390
+ the one surface where it was not: the shipped sentence says `roadkeep` is the installed
1391
+ entry point, and for a project wired to a checkout the package is *not* installed, so
1392
+ every shell example in the copy names a command that resolves to nothing. Verified on a
1393
+ real adoption. Nothing breaks until an agent falls back from the MCP tools to the shell —
1394
+ which is exactly the moment the skill is being read.
1395
+
1396
+ The sentence is matched rather than the line number, and a match that is not exactly one
1397
+ is a refusal: a copy written with the wrong entry point is the defect this module exists
1398
+ to remove, and silently shipping it would be worse than the hand-written copy it replaced.
1399
+ """
1400
+ text = _read(origin / PLUGIN_SKILL)
1401
+ # A function and not a replacement string: a launcher is a path, and `re.sub` would read
1402
+ # a backslash in one as a group reference.
1403
+ replaced, count = _ENTRY_RE.subn(lambda _: _entry(launcher, committed=committed), text)
1404
+ if count != 1:
1405
+ raise Unanchored(origin / PLUGIN_SKILL, count)
1406
+ return replaced
1407
+
1408
+
1409
+ def _entry(launcher: str, *, committed: bool = False) -> str:
1410
+ """What the entry-point sentence becomes, per variant (RK1119).
1411
+
1412
+ Quoted, for the reason the hook command is: a checkout on a path with a space in it is
1413
+ otherwise two arguments.
1414
+
1415
+ **Two sentences and not one with a clause swapped**, because the clause is the difference:
1416
+ under `--committed` nothing was wired to a checkout — the launcher is a file in the
1417
+ repository that *resolves* one at runtime, and the environment the flag exists for has
1418
+ none until something provides one. So the sentence a session read before running anything
1419
+ named the wrong place to look for its engine, in the file it reads instead of asking, and
1420
+ an agent that believed it went looking for the checkout the launcher exists to not need.
1421
+ Since RK1113 a plain `install` writes this variant too, so the flag is not the only path.
1422
+ """
1423
+ if committed:
1424
+ return (
1425
+ f"`python \"{launcher}\"` is this project's entry point — the package is not "
1426
+ f"installed here and `roadkeep` is on no PATH, and that launcher is committed to "
1427
+ f"this repository so it finds an engine wherever this environment has one."
1428
+ )
1429
+ return (
1430
+ f"`python \"{launcher}\"` is this project's entry point — `install` wired it to a "
1431
+ f"checkout, so the package is not installed here and `roadkeep` is on no PATH."
1432
+ )
1433
+
1434
+
1435
+ def _copy(path: Path, text: str) -> Surface:
1436
+ """A verbatim copy, refreshed on every run: the drift RK100 is about."""
1437
+ existed = path.is_file()
1438
+ return Surface(
1439
+ path=path,
1440
+ text=text,
1441
+ refresh=True,
1442
+ existed=existed,
1443
+ stale=not existed or _read(path) != text,
1444
+ )
1445
+
1446
+
1447
+ def _once(path: Path, text: str) -> Surface:
1448
+ """Written when absent, then left alone — the adopter tunes it and this does not."""
1449
+ existed = path.is_file()
1450
+ return Surface(
1451
+ path=path,
1452
+ text=text,
1453
+ refresh=False,
1454
+ existed=existed,
1455
+ stale=not existed or _read(path) != text,
1456
+ )
1457
+
1458
+
1459
+ def _declaration(path: Path, merge) -> Surface:
1460
+ """This project's entry re-derived inside a file other tools also declare in.
1461
+
1462
+ Compared as parsed JSON and not as bytes: an adopter's own indentation is not staleness,
1463
+ and a `--check` that failed on whitespace is a check nobody leaves switched on.
1464
+ """
1465
+ current: dict = {}
1466
+ existed = path.is_file()
1467
+ if existed:
1468
+ try:
1469
+ loaded = json.loads(_read(path))
1470
+ except json.JSONDecodeError as error:
1471
+ raise Unreadable(path, str(error)) from error
1472
+ if not isinstance(loaded, dict):
1473
+ raise Unreadable(path, f"read as {type(loaded).__name__}")
1474
+ current = loaded
1475
+ merged = merge(current)
1476
+ return Surface(
1477
+ path=path,
1478
+ text=json.dumps(merged, indent=2, ensure_ascii=False) + "\n",
1479
+ refresh=True,
1480
+ existed=existed,
1481
+ stale=merged != current,
1482
+ )
1483
+
1484
+
1485
+ # -- vendoring an engine into the project (RK1193) ----------------------------
1486
+
1487
+
1488
+ class NoEngine(ValueError):
1489
+ """Nothing on this machine is a roadkeep this command could copy (RK1193).
1490
+
1491
+ A refusal and never a silent skip: `--vendor` is asked for, so a run that copied nothing
1492
+ and exited 0 would leave a project believing it is pinned. The candidates it looked at are
1493
+ named, because the commonest cause is a plugin root under a `CLAUDE_CONFIG_DIR` this
1494
+ process does not see.
1495
+ """
1496
+
1497
+ def __init__(self, looked: Sequence[str]) -> None:
1498
+ self.looked = tuple(looked)
1499
+ where = ", ".join(self.looked) or "nowhere this process can see"
1500
+ super().__init__(
1501
+ f"no engine to vendor: looked in {where} — set {ENGINE_SOURCE} to a roadkeep "
1502
+ f"checkout to use one, which is also the only way a working tree is eligible"
1503
+ )
1504
+
1505
+
1506
+ class NotVerified(ValueError):
1507
+ """The copy landed and does not answer the version it was chosen for (RK1193).
1508
+
1509
+ The last of the four rules, and the one the other three exist to make meaningful: picking
1510
+ by version is worth nothing if what arrives is a different tree. Raised **after** the copy,
1511
+ because the evidence is the copy running — so the directory is left on disk for a reader
1512
+ to look at rather than removed to make the failure tidy.
1513
+ """
1514
+
1515
+ def __init__(self, wanted: str, answered: str, where: Path) -> None:
1516
+ self.wanted = wanted
1517
+ self.answered = answered
1518
+ super().__init__(
1519
+ f"vendored {where} answers {answered or 'nothing'} and {wanted} was chosen: the "
1520
+ f"copy is left where it is, because what is wrong with it is what it just said"
1521
+ )
1522
+
1523
+
1524
+ @dataclass(frozen=True, slots=True)
1525
+ class Candidate:
1526
+ """One roadkeep this machine can reach, and what it answered when asked (RK1193)."""
1527
+
1528
+ #: The plugin root — the directory holding `scripts/roadkeep.py`.
1529
+ home: Path
1530
+ #: What `--version` printed. Compared as a **tuple of integers**, never as text: `0.1.9`
1531
+ #: sorts above `0.1.10` as a string, and the two adopters this generalises both got that
1532
+ #: right by accident of never having a two-digit patch.
1533
+ version: str
1534
+ #: Where it was found, for a report that has to say why this one and not another.
1535
+ why: str
1536
+ #: Whether it is a working tree — skipped unless `ROADKEEP_SRC` named it, which is the
1537
+ #: rule the measured hour paid for: a checkout mid-refactor answers a version and then
1538
+ #: raises `ImportError` out of a half-edited module.
1539
+ working: bool = False
1540
+
1541
+ @property
1542
+ def ordered(self) -> tuple[int, ...]:
1543
+ return _numbered(self.version)
1544
+
1545
+
1546
+ def _numbered(version: str) -> tuple[int, ...]:
1547
+ """A version as integers, so `0.1.10` outranks `0.1.9` (RK1193).
1548
+
1549
+ Anything unparsable sorts lowest rather than raising: a candidate that answered something
1550
+ this cannot read is still a candidate, and it loses to every one that answered a number.
1551
+ """
1552
+ parts: list[int] = []
1553
+ for piece in version.strip().split("."):
1554
+ digits = "".join(one for one in piece if one.isdigit())
1555
+ if not digits:
1556
+ break
1557
+ parts.append(int(digits))
1558
+ return tuple(parts)
1559
+
1560
+
1561
+ @dataclass(frozen=True, slots=True)
1562
+ class Vendored:
1563
+ """What `install --vendor` copied, from where, and what the copy then answered."""
1564
+
1565
+ #: Where it landed, absolute.
1566
+ into: Path
1567
+ chosen: Candidate
1568
+ #: Every candidate this looked at, highest version first — the report's evidence that the
1569
+ #: choice was by version and not by position.
1570
+ considered: tuple[Candidate, ...] = ()
1571
+ #: What the copy answered when asked after the write. Equal to `chosen.version` or this
1572
+ #: is a :class:`NotVerified` rather than a result.
1573
+ verified: str = ""
1574
+ files: int = 0
1575
+ #: Whether the project should be told to ignore the copy — False where a `.gitignore`
1576
+ #: already names it, so a project that did this once is not advised about it every run.
1577
+ ignore: bool = False
1578
+
1579
+ def stated(self, checked: bool) -> str:
1580
+ """The choice, the evidence for it, and what the copy answered (RK1193)."""
1581
+ would = "would vendor" if checked else "vendored"
1582
+ rows = [
1583
+ f" {would:<14} {self.chosen.version} from {self.chosen.why}",
1584
+ f" {'into':<14} {self.into.as_posix()} ({self.files} file(s))",
1585
+ ]
1586
+ rows += [
1587
+ f" {'also saw':<14} {one.version} at {one.why}"
1588
+ + (" (a working tree, skipped)" if one.working else "")
1589
+ for one in self.considered
1590
+ if one.home != self.chosen.home
1591
+ ]
1592
+ if self.verified:
1593
+ # The fourth rule, said out loud: picking by version is worth nothing unless what
1594
+ # landed is asked what it is.
1595
+ rows.append(f" {'answers':<14} {self.verified}, as chosen")
1596
+ if self.ignore:
1597
+ # Printed and never written, which is `merge --register`'s rule about the `git
1598
+ # config` half (RK148): `.gitignore` is the project's file, and a copy of somebody
1599
+ # else's repository appearing in `git status` is what the line prevents. Said only
1600
+ # where nothing already covers it, so a project that did this once is not nagged.
1601
+ rows.append(
1602
+ f" {'to ignore':<14} add `{PROJECT_ENGINE}/` to .gitignore — the copy is an "
1603
+ f"artefact, and committing it makes every upgrade a diff in this repository"
1604
+ )
1605
+ return "\n".join(rows)
1606
+
1607
+ def payload(self) -> dict[str, object]:
1608
+ return {
1609
+ "into": self.into.as_posix(),
1610
+ "version": self.chosen.version,
1611
+ "from": self.chosen.why,
1612
+ "files": self.files,
1613
+ "verified": self.verified or None,
1614
+ "ignore": self.ignore,
1615
+ "considered": [
1616
+ {"version": one.version, "from": one.why, "working": one.working}
1617
+ for one in self.considered
1618
+ ],
1619
+ }
1620
+
1621
+
1622
+ #: What is never copied into the vendored tree (RK1193). `.git` above all: with it the copy is
1623
+ #: a second repository inside the project — `git status` walks it, tooling finds two roots, and
1624
+ #: an artefact stops being one. The rest is build litter that costs megabytes and answers
1625
+ #: nothing.
1626
+ _UNVENDORED = (".git", "__pycache__", ".pytest_cache", ".venv", "node_modules")
1627
+
1628
+
1629
+ def candidates(root: Path) -> tuple[Candidate, ...]:
1630
+ """Every roadkeep this machine can reach, highest version first (RK1193).
1631
+
1632
+ **Asked rather than read.** Each candidate is run as `<home>/scripts/roadkeep.py
1633
+ --version`, which is the one question that proves the tree is not merely present but
1634
+ *importable* — and importability is the whole failure being designed around: a checkout
1635
+ mid-refactor is on disk, states a version in `__init__.py`, and raises `ImportError` out of
1636
+ a half-edited module the moment anything uses it. Reading the literal would rank exactly
1637
+ that tree first.
1638
+
1639
+ Measured on one machine: **six** engines resolvable — 0.1.841 and 0.1.820 under
1640
+ `~/.claude`, 0.1.678 and 0.1.645 under `~/.claude-pessoal`, and two marketplace clones.
1641
+ Picking by position gives whichever the search order happened to reach; picking by version
1642
+ gives the same answer on every machine, which is what makes a pin reproducible.
1643
+
1644
+ A **working tree is excluded** unless `ROADKEEP_SRC` names it. Deliberately not a
1645
+ heuristic about how modified it is: a clean checkout is one `git pull` from being a dirty
1646
+ one, and a project that pinned an engine did so to stop tracking somebody's editor.
1647
+ """
1648
+ named = os.environ.get(ENGINE_SOURCE)
1649
+ found: list[Candidate] = []
1650
+ seen: set[Path] = set()
1651
+ for home, why, working in _places(root, named):
1652
+ resolved = home.resolve()
1653
+ if resolved in seen or not (resolved / LAUNCHER).is_file():
1654
+ continue
1655
+ seen.add(resolved)
1656
+ version = _asked(resolved)
1657
+ if version:
1658
+ found.append(Candidate(resolved, version, why, working=working))
1659
+ return tuple(sorted(found, key=lambda one: one.ordered, reverse=True))
1660
+
1661
+
1662
+ def _places(root: Path, named: str | None) -> list[tuple[Path, str, bool]]:
1663
+ """Where to look, with what to call each — the launcher's own order plus the caches.
1664
+
1665
+ Not the launcher's *resolution*, which stops at the first hit: this collects, because the
1666
+ choice here is by version and a search that returned early would be picking by position
1667
+ under another name.
1668
+ """
1669
+ out: list[tuple[Path, str, bool]] = []
1670
+ if named:
1671
+ # The one door a working tree comes through, and it is unconditional: a caller who
1672
+ # named it has said which tree they mean.
1673
+ out.append((Path(named), f"{ENGINE_SOURCE}={named}", False))
1674
+ wired = installed(root)
1675
+ if wired is not None and wired.home is not None:
1676
+ out.append((wired.home, f"the plugin wired to this project ({wired.version})", False))
1677
+ for base in _plugin_roots():
1678
+ out += [(one, f"a plugin root at {one.as_posix()}", False) for one in _under(base)]
1679
+ sibling = root.resolve().parent / "roadkeep"
1680
+ if sibling.is_dir():
1681
+ # A sibling checkout is the case `ROADKEEP_SRC` exists for, so it is offered and
1682
+ # marked rather than silently dropped: the report says it was seen and why it lost.
1683
+ out.append((sibling, f"a sibling checkout at {sibling.as_posix()}", True))
1684
+ stated = os.environ.get("XDG_CACHE_HOME")
1685
+ found = home()
1686
+ if stated or found is not None:
1687
+ cache = Path(stated) if stated else found / ".cache" # type: ignore[operator]
1688
+ out.append((cache / "roadkeep-src" / "roadkeep", "the launcher's cache clone", False))
1689
+ return out
1690
+
1691
+
1692
+ def _plugin_roots() -> tuple[Path, ...]:
1693
+ """The harness config directories a plugin can be unpacked under.
1694
+
1695
+ Both spellings, because a machine can have more than one: `CLAUDE_CONFIG_DIR` and the
1696
+ default `~/.claude` are what the harness itself resolves, and the measurement that
1697
+ motivated this found engines under two of them at once.
1698
+ """
1699
+ stated = os.environ.get("CLAUDE_CONFIG_DIR")
1700
+ homes = [Path(stated)] if stated else []
1701
+ if (found := home()) is not None:
1702
+ homes.append(found / ".claude")
1703
+ return tuple(dict.fromkeys(one / "plugins" for one in homes))
1704
+
1705
+
1706
+ def _under(base: Path) -> list[Path]:
1707
+ """Every directory under a plugins root that carries a launcher, at any depth up to two.
1708
+
1709
+ Shallow on purpose: a marketplace unpacks to `<root>/<marketplace>/<plugin>` and a cache
1710
+ to `<root>/<name>`, and a full walk of a config directory is a scan of somebody's whole
1711
+ plugin collection for a command that should cost milliseconds.
1712
+ """
1713
+ out: list[Path] = []
1714
+ try:
1715
+ for one in sorted(base.iterdir()):
1716
+ if not one.is_dir():
1717
+ continue
1718
+ out.append(one)
1719
+ out += [two for two in sorted(one.iterdir()) if two.is_dir()]
1720
+ except OSError:
1721
+ return []
1722
+ return out
1723
+
1724
+
1725
+ def _asked(home: Path) -> str:
1726
+ """What this tree answers to `--version`, or `""` where it cannot be run at all.
1727
+
1728
+ The subprocess is the point (see :func:`candidates`), and every failure is `""`: a tree
1729
+ that raises, hangs past the timeout or is not Python is not a candidate, and none of that
1730
+ is worth failing the command over while another copy may be fine.
1731
+ """
1732
+ import subprocess # noqa: PLC0415 - RK260
1733
+
1734
+ try:
1735
+ done = subprocess.run(
1736
+ [sys.executable, str(home / LAUNCHER), "--version"],
1737
+ capture_output=True,
1738
+ text=True,
1739
+ timeout=_ASKED_TIMEOUT,
1740
+ check=False,
1741
+ )
1742
+ except (OSError, ValueError, subprocess.SubprocessError):
1743
+ return ""
1744
+ if done.returncode != 0:
1745
+ return ""
1746
+ return _version_in(done.stdout)
1747
+
1748
+
1749
+ #: The number inside a `--version` line, wherever it sits in it. `argparse` prints `roadkeep
1750
+ #: 0.1.963 (479d7266 modified, D:\…\src\roadkeep)` — the provenance RK79 added — so taking the
1751
+ #: last token reads the *path* as the version and every candidate ties at nothing. Anchored on
1752
+ #: a dotted run of digits, which is the one shape a version has and no path fragment does.
1753
+ _VERSION_RE = re.compile(r"\b(\d+(?:\.\d+)+)\b")
1754
+
1755
+
1756
+ def _version_in(said: str) -> str:
1757
+ """The version a `--version` line states, or `""` where it states none.
1758
+
1759
+ Read out of the line rather than assumed to *be* it, because the line carries more than
1760
+ the number by design: this tool's own `--version` names the commit, whether the tree is
1761
+ modified, and where the package is — the facts RK79 added so two copies could be told
1762
+ apart, and exactly the ones that break a positional read.
1763
+ """
1764
+ found = _VERSION_RE.search(said)
1765
+ return found.group(1) if found else ""
1766
+
1767
+
1768
+ #: Seconds one candidate may take to say what it is. Generous for a cold import and short
1769
+ #: enough that six of them do not make `install` feel hung.
1770
+ _ASKED_TIMEOUT = 30
1771
+
1772
+
1773
+ def vendor(root: str | Path = ".", *, checked: bool = False) -> Vendored:
1774
+ """Copy the highest-versioned engine this machine can reach into the project (RK1193).
1775
+
1776
+ The command two adopting repositories each wrote for themselves. Shio and freewilly carry
1777
+ a 147-line `install_roadkeep.py` and a `.cmd` wrapper, byte-identical apart from one
1778
+ comment — the same code in two repositories, which is the drift this tool spends its
1779
+ backlog refusing everywhere else. `install --vendor` is that, once.
1780
+
1781
+ Four rules, and each is a measurement rather than a preference:
1782
+
1783
+ * **Pick by version, not by position.** Six engines were resolvable on the machine this
1784
+ was written on. A search order answers differently per machine; the highest version
1785
+ answers the same everywhere, which is what a pin is for.
1786
+ * **Skip a working checkout unless `ROADKEEP_SRC` names it.** A tree mid-refactor answers
1787
+ a version and then raises out of a half-edited module — an hour, measured.
1788
+ * **Exclude `.git`.** With it the copy is a second repository inside the project rather
1789
+ than an artefact.
1790
+ * **Verify what landed.** The copy is asked its version, and a disagreement is
1791
+ :class:`NotVerified` — picking by version proves nothing about a tree that arrived
1792
+ different.
1793
+
1794
+ ``checked`` computes and copies nothing, which is `--check`'s contract one command over:
1795
+ the choice and the evidence for it are the whole answer, and reporting them costs the same
1796
+ walk either way.
1797
+ """
1798
+ import shutil # noqa: PLC0415 - RK260
1799
+
1800
+ base = Path(root).resolve()
1801
+ found = candidates(base)
1802
+ usable = [one for one in found if not one.working or _named(one)]
1803
+ if not usable:
1804
+ raise NoEngine([one.why for one in found] or _looked(base))
1805
+ chosen = usable[0]
1806
+ into = base / PROJECT_ENGINE
1807
+ unignored = not _ignored(base)
1808
+ if checked:
1809
+ return Vendored(into=into, chosen=chosen, considered=found, ignore=unignored)
1810
+
1811
+ if into.exists():
1812
+ # Replaced whole rather than merged: a half-old tree is the state every rule above is
1813
+ # about, and `shutil.copytree` onto a populated directory is how one is made.
1814
+ shutil.rmtree(into)
1815
+ shutil.copytree(chosen.home, into, ignore=shutil.ignore_patterns(*_UNVENDORED))
1816
+ answered = _asked(into)
1817
+ if answered != chosen.version:
1818
+ raise NotVerified(chosen.version, answered, into)
1819
+ return Vendored(
1820
+ into=into,
1821
+ chosen=chosen,
1822
+ considered=found,
1823
+ verified=answered,
1824
+ files=sum(1 for one in into.rglob("*") if one.is_file()),
1825
+ ignore=unignored,
1826
+ )
1827
+
1828
+
1829
+ def _ignored(root: Path) -> bool:
1830
+ """Whether a `.gitignore` here already covers the vendored tree (RK1193).
1831
+
1832
+ Read as **text and not through git**, which is the honest bound: this is deciding whether
1833
+ to print one line of advice, and shelling out to `check-ignore` would make a report depend
1834
+ on a subprocess for a sentence. A project whose rule lives in `.git/info/exclude` or a
1835
+ parent's `.gitignore` gets the advice anyway, which is a redundant line and not a wrong one.
1836
+ """
1837
+ try:
1838
+ written = (root / ".gitignore").read_text(encoding="utf-8")
1839
+ except (OSError, UnicodeDecodeError):
1840
+ return False
1841
+ return any(
1842
+ one.strip().rstrip("/") == PROJECT_ENGINE for one in written.splitlines()
1843
+ )
1844
+
1845
+
1846
+ def _named(candidate: Candidate) -> bool:
1847
+ """Whether `ROADKEEP_SRC` is what put this working tree on the list."""
1848
+ return candidate.why.startswith(f"{ENGINE_SOURCE}=")
1849
+
1850
+
1851
+ def _looked(root: Path) -> list[str]:
1852
+ """Where a refusal says it looked, when nothing answered at all."""
1853
+ return [one.as_posix() for one in _plugin_roots()] + [
1854
+ (root.resolve().parent / "roadkeep").as_posix()
1855
+ ]
1856
+
1857
+
1858
+ # -- un-wiring ---------------------------------------------------------------
1859
+
1860
+
1861
+ @dataclass(frozen=True, slots=True)
1862
+ class Withdrawal:
1863
+ """One file un-wiring touches, and what it would do to that file (RK138)."""
1864
+
1865
+ path: Path
1866
+ #: What the file keeps. ``None`` where nothing of it survives this project's entry, which
1867
+ #: is the state `install` created it in and therefore the one to return it to.
1868
+ text: str | None
1869
+ existed: bool
1870
+ #: Whether the file still holds something this command wrote.
1871
+ held: bool
1872
+
1873
+ @property
1874
+ def state(self) -> str:
1875
+ if not self.existed:
1876
+ return "absent"
1877
+ if not self.held:
1878
+ return "untouched"
1879
+ return "deleted" if self.text is None else "reduced"
1880
+
1881
+ @property
1882
+ def writes(self) -> bool:
1883
+ return self.state in ("deleted", "reduced")
1884
+
1885
+
1886
+ @dataclass(frozen=True, slots=True)
1887
+ class Removal:
1888
+ """What `uninstall` would take out, computed before a byte is touched (all-or-nothing)."""
1889
+
1890
+ root: Path
1891
+ withdrawals: tuple[Withdrawal, ...]
1892
+ #: Paths deliberately left, each with the reason — the other half of the report, for the
1893
+ #: reason `install` names what it does not write: a surface silently kept reads as missed.
1894
+ kept: tuple[tuple[str, str], ...] = ()
1895
+
1896
+ @property
1897
+ def changing(self) -> tuple[Withdrawal, ...]:
1898
+ return tuple(withdrawal for withdrawal in self.withdrawals if withdrawal.writes)
1899
+
1900
+ def stated(self, checked: bool) -> str:
1901
+ """Every file the un-wiring touches, and what it did — or would do — to it (RK138).
1902
+
1903
+ Beside :meth:`payload` and :meth:`verdict` since RK1170, in :class:`Plan`'s shape and
1904
+ for its reason: this is the same command pointed the other way.
1905
+ """
1906
+ rows = [f"{self.root.as_posix()} ← this project's own entries"]
1907
+ for withdrawal in self.withdrawals:
1908
+ state = _WOULD_REMOVE[withdrawal.state] if checked else withdrawal.state
1909
+ rows.append(f" {state:<14} {withdrawal.path.relative_to(self.root).as_posix()}")
1910
+ rows += [f" kept {why}" for _, why in self.kept]
1911
+ return "\n".join(rows)
1912
+
1913
+ def verdict(self) -> list[str]:
1914
+ """What a `--check` has to say on **stderr**, where anything is left wired."""
1915
+ if not self.changing:
1916
+ return []
1917
+ return [
1918
+ f"{len(self.changing)} surface(s) still wire this project to a checkout: "
1919
+ f"`{invocation()} uninstall` takes them out"
1920
+ ]
1921
+
1922
+ def payload(self, checked: bool) -> dict[str, object]:
1923
+ return {
1924
+ "root": self.root.as_posix(),
1925
+ "checked": checked,
1926
+ "surfaces": [
1927
+ {
1928
+ "path": withdrawal.path.relative_to(self.root).as_posix(),
1929
+ "state": withdrawal.state,
1930
+ "writes": withdrawal.writes,
1931
+ }
1932
+ for withdrawal in self.withdrawals
1933
+ ],
1934
+ "kept": [{"path": path, "why": why} for path, why in self.kept],
1935
+ "changing": len(self.changing),
1936
+ }
1937
+
1938
+
1939
+ #: The same rule as :data:`_WOULD` for the other direction (RK138). `absent` and `untouched`
1940
+ #: describe no write either, so only the two states that take something out are conditional.
1941
+ _WOULD_REMOVE = {
1942
+ "deleted": "would delete",
1943
+ "reduced": "would reduce",
1944
+ "absent": "absent",
1945
+ "untouched": "untouched",
1946
+ }
1947
+
1948
+
1949
+ def removal(root: str | Path = ".") -> Removal:
1950
+ """Read the project's own surfaces and answer what un-wiring would take out.
1951
+
1952
+ Reads no checkout, unlike :func:`plan`: the wiring is recognised by *this project's own
1953
+ entry* — the server's name, and the launcher a hook command runs — so a project can be
1954
+ un-wired after the checkout it pointed at is gone, which is the case that produced RK138.
1955
+
1956
+ What is reported as kept is read off the disk (RK284). It used to be a constant, so a
1957
+ project `install` had just told "no `.github/workflows/` — this project has no CI to gate"
1958
+ was told at `uninstall` that CI stays wired and to delete a path that was not there. A
1959
+ surface never present was not kept, and naming it does the thing this field exists to
1960
+ prevent — "a surface silently kept reads as missed" — from the other side.
1961
+ """
1962
+ base = Path(root).resolve()
1963
+ if _ships_the_plugin(base):
1964
+ raise NotAnAdopter(base)
1965
+ kept: list[tuple[str, str]] = []
1966
+ if (base / PROJECT_WORKFLOW).is_file():
1967
+ # Absence gets no line of its own. `install` says why it wrote nothing, because an
1968
+ # adopter has to know CI was considered; here there is nothing to have kept, and a
1969
+ # sentence about a file that does not exist is the report this task is about.
1970
+ kept.append(
1971
+ (
1972
+ PROJECT_WORKFLOW,
1973
+ f"{PROJECT_WORKFLOW}: the gate calls the published action and not this "
1974
+ f"checkout, so CI stays wired — delete it to stop gating",
1975
+ )
1976
+ )
1977
+ return Removal(
1978
+ root=base,
1979
+ withdrawals=(
1980
+ _withdrawn(base / PROJECT_MCP, _without_server),
1981
+ _withdrawn(base / PROJECT_SETTINGS, _without_guard),
1982
+ _dropped(base / PROJECT_SKILL),
1983
+ # Unconditionally, and `_dropped` answers `held=False` where it is not there
1984
+ # (RK1108): `removal` reads no checkout and cannot know whether the wiring it is
1985
+ # taking out was written with `--committed`, so asking the disk is the only reading
1986
+ # available — which is the rule RK284 already established for what is *kept*.
1987
+ _dropped(base / PROJECT_BRIDGE),
1988
+ ),
1989
+ kept=tuple(kept),
1990
+ )
1991
+
1992
+
1993
+ def uninstall(root: str | Path = ".") -> Removal:
1994
+ """Take this project's entries out of the four surfaces, or take nothing out.
1995
+
1996
+ The inverse of :func:`install` and held to its two rules: the declarations keep everything
1997
+ that is not this project's entry, and a file that is not a JSON object is refused rather
1998
+ than rewritten. A file left holding nothing but what this command wrote is *deleted*,
1999
+ because `install` created it and an empty declaration reads as a project that declares
2000
+ something.
2001
+ """
2002
+ intent = removal(root)
2003
+ for withdrawal in intent.changing:
2004
+ if withdrawal.text is None:
2005
+ withdrawal.path.unlink()
2006
+ _prune(withdrawal.path.parent, intent.root)
2007
+ else:
2008
+ withdrawal.path.write_text(withdrawal.text, encoding="utf-8", newline="")
2009
+ return intent
2010
+
2011
+
2012
+ def _withdrawn(path: Path, without) -> Withdrawal:
2013
+ """One declaration with this project's entry taken out, as a :class:`Withdrawal`.
2014
+
2015
+ Compared as parsed JSON for the reason :func:`_declaration` is: an adopter's indentation
2016
+ is not a wiring, and a command that reported one would report every project as wired.
2017
+ """
2018
+ if not path.is_file():
2019
+ return Withdrawal(path=path, text=None, existed=False, held=False)
2020
+ try:
2021
+ loaded = json.loads(_read(path))
2022
+ except json.JSONDecodeError as error:
2023
+ raise Unreadable(path, str(error)) from error
2024
+ if not isinstance(loaded, dict):
2025
+ raise Unreadable(path, f"read as {type(loaded).__name__}")
2026
+ left = without(loaded)
2027
+ return Withdrawal(
2028
+ path=path,
2029
+ text=None if not left else json.dumps(left, indent=2, ensure_ascii=False) + "\n",
2030
+ existed=True,
2031
+ held=left != loaded,
2032
+ )
2033
+
2034
+
2035
+ def _dropped(path: Path) -> Withdrawal:
2036
+ """The copied skill: a file this command owns whole, so there is nothing to reduce."""
2037
+ existed = path.is_file()
2038
+ return Withdrawal(path=path, text=None, existed=existed, held=existed)
2039
+
2040
+
2041
+ def _without_server(current: dict) -> dict:
2042
+ """`.mcp.json` without this project's server, every other key in its own place."""
2043
+ servers = {name: entry for name, entry in current.get("mcpServers", {}).items() if name != SERVER}
2044
+ left = {}
2045
+ for key, value in current.items():
2046
+ if key != "mcpServers":
2047
+ left[key] = value
2048
+ elif servers:
2049
+ left[key] = servers
2050
+ return left
2051
+
2052
+
2053
+ def _without_guard(current: dict) -> dict:
2054
+ """`.claude/settings.json` without the guard's three events and the server's approval.
2055
+
2056
+ An event left with no groups is dropped rather than emptied, and so is `hooks` itself: a
2057
+ declaration that holds an empty list is a project that declares a hook, which is exactly
2058
+ the reading un-wiring exists to end.
2059
+ """
2060
+ left: dict = {}
2061
+ for key, value in current.items():
2062
+ if key == "enabledMcpjsonServers":
2063
+ approved = [name for name in value if name != SERVER]
2064
+ if approved:
2065
+ left[key] = approved
2066
+ elif key == "hooks":
2067
+ events = {
2068
+ event: kept
2069
+ for event, groups in value.items()
2070
+ if (kept := [group for group in groups if not _ours(group)])
2071
+ }
2072
+ if events:
2073
+ left[key] = events
2074
+ else:
2075
+ left[key] = value
2076
+ return left
2077
+
2078
+
2079
+ def _prune(directory: Path, root: Path) -> None:
2080
+ """Remove the directories the deleted copy was alone in, and stop at the project root.
2081
+
2082
+ `install` created `.claude/skills/roadkeep/`, so leaving it behind empty leaves a project
2083
+ that looks as though it vendors a skill. Anything else in there is somebody's, and an
2084
+ empty parent that this command did not create — `.claude/` on a project whose settings
2085
+ were only ever this tool's — is the same fact one level up.
2086
+ """
2087
+ while directory != root and directory.is_dir() and not any(directory.iterdir()):
2088
+ directory.rmdir()
2089
+ directory = directory.parent
2090
+
2091
+
2092
+ def _merged_mcp(current: dict, server: dict) -> dict:
2093
+ merged = dict(current)
2094
+ servers = dict(merged.get("mcpServers", {}))
2095
+ servers[SERVER] = server
2096
+ merged["mcpServers"] = servers
2097
+ return merged
2098
+
2099
+
2100
+ def _merged_settings(current: dict, hooks: dict) -> dict:
2101
+ """Approve the server and wire the guard, leaving every other setting where it is.
2102
+
2103
+ A project `.mcp.json` waits for approval, and a server awaiting approval is one that
2104
+ never ran — indistinguishable, from the session's side, from one never declared.
2105
+ """
2106
+ merged = dict(current)
2107
+ enabled = list(merged.get("enabledMcpjsonServers", []))
2108
+ if SERVER not in enabled:
2109
+ enabled.append(SERVER)
2110
+ merged["enabledMcpjsonServers"] = enabled
2111
+
2112
+ events = dict(merged.get("hooks", {}))
2113
+ for event, groups in hooks.items():
2114
+ # Ours dropped and re-added rather than edited in place: the launcher path is what
2115
+ # moves between runs, and a match on it is the one thing that would stop matching.
2116
+ kept = [group for group in events.get(event, []) if not _ours(group)]
2117
+ events[event] = kept + groups
2118
+ merged["hooks"] = events
2119
+ return merged
2120
+
2121
+
2122
+ #: Every launcher spelling this command writes into a hook, which is what recognising its own
2123
+ #: entry means (RK1108). Two since the bridge: a match on the checkout's `scripts/roadkeep.py`
2124
+ #: alone did not see a `--committed` wiring — so a re-run appended a second identical group to
2125
+ #: all three events instead of replacing its own, and `uninstall` left the guard in place. The
2126
+ #: comment beside `_merged_settings` had named this exact failure ("a match on it is the one
2127
+ #: thing that would stop matching") one flag before it happened.
2128
+ _LAUNCHERS = (LAUNCHER, PROJECT_BRIDGE)
2129
+
2130
+
2131
+ def _ours(group: dict) -> bool:
2132
+ """A hook group this command wrote, recognised by the launcher it runs."""
2133
+ return any(
2134
+ any(spelling in hook.get("command", "") for spelling in _LAUNCHERS)
2135
+ for hook in group.get("hooks", [])
2136
+ )
2137
+
2138
+
2139
+ def _read(path: Path) -> str:
2140
+ """Every file this module compares, read one way: UTF-8, newlines normalised.
2141
+
2142
+ A checkout on Windows can hold the skill with CRLF endings; a copy that differed from its
2143
+ source only in those would be reported stale forever and rewritten on every run.
2144
+ """
2145
+ return path.read_text(encoding="utf-8")