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/provenance.py ADDED
@@ -0,0 +1,789 @@
1
+ """Which tree answered, and at what commit (RK79).
2
+
3
+ The plugin carries its own `src/roadkeep/`, and a developer of this tool has a checkout of
4
+ the same package. RK57's launcher puts the plugin's copy first on `sys.path`, so the hook
5
+ and the MCP server run the cache while `python -m roadkeep.cli` runs the checkout — two
6
+ engines, both reporting `0.1.0`, with nothing observable between them. Measured live: 14
7
+ files differing and two modules present in one tree only.
8
+
9
+ **Making them distinguishable is the fix, not making them the same.** A cache is allowed to
10
+ lag a checkout; what is not survivable is being unable to say which one produced an answer,
11
+ because that turns every other symptom into a guess about which code ran.
12
+
13
+ So the version string carries where it came from. `__version__` stays the one literal
14
+ (RK19) — this adds no second number, only the two facts a release number cannot hold: the
15
+ directory the modules were imported from, and the commit those files are at. The directory
16
+ alone already separates a cache from a checkout; the commit separates two checkouts, and
17
+ names the case `/plugin update` cannot fix, where the cache is current with a remote the
18
+ work has not reached.
19
+
20
+ The same two facts answer a second question the server needs (RK155): the config is re-read
21
+ per message, deliberately, but the *code* reading it was imported once at session start — so
22
+ `[claims] held` added to `roadkeep.toml` and to `config.py` in one commit made every MCP write
23
+ refuse `unknown key 'claims'` while the CLI in a terminal accepted it. :attr:`Engine.stale`
24
+ names the modules that moved under the running process, so the refusal states the cause instead
25
+ of describing a config that is correct. It never reloads: see that attribute for why.
26
+
27
+ Git is asked about **the package's own directory**, never the governed project's — a
28
+ different question from :mod:`roadkeep.history`, which reads the repository a `Config` points
29
+ at. It is asked at most once per process and never on a path that writes: a subprocess on
30
+ every `add` would buy nothing and cost the tool's own budget. A tree that git cannot answer
31
+ for (an installed wheel, no git on PATH) is not an error — the directory is still the
32
+ answer, and it is the half that distinguishes the two engines above.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import shutil
38
+ import sys
39
+ import time
40
+ from collections.abc import Sequence
41
+ from dataclasses import dataclass
42
+ from functools import lru_cache
43
+ from pathlib import Path
44
+
45
+ import roadkeep
46
+
47
+ #: What the revision reads as when git cannot place these files: no repository, no git on
48
+ #: PATH, or a package directory nothing in the surrounding tree tracks — an installed copy
49
+ #: that happens to sit under someone else's checkout must not borrow that checkout's HEAD.
50
+ UNTRACKED = "untracked"
51
+
52
+ #: Appended to the commit when the files differ from it, because the commit is then a
53
+ #: description of what was edited rather than of what is running.
54
+ MODIFIED = "modified"
55
+
56
+ #: When this process loaded the package, which is the only clock staleness can be measured
57
+ #: against (RK155). Not a module mtime and not :func:`engine`'s cache: the question is whether
58
+ #: the files changed *after* the code answering was imported, and only the process knows when
59
+ #: that was. Set at import, so a server that starts late measures from when it started.
60
+ _LOADED_AT = time.time()
61
+
62
+ #: How much later than :data:`_LOADED_AT` a file must be to count. One second, because a file
63
+ #: written in the same second the process started is the process's own installer, not an edit,
64
+ #: and a server that called itself stale on every start would be a warning nobody reads.
65
+ _GRACE = 1.0
66
+
67
+ #: The directory the modules that are **executing** were imported from. A fact about this
68
+ #: process, in the same class as :data:`_LOADED_AT` and deliberately not :attr:`Engine.home`:
69
+ #: which files ran is not a field a caller can describe, and the one surface that fabricates an
70
+ #: engine to test the note would otherwise be fabricating the traceback too (RK267).
71
+ _HOME = Path(__file__).resolve().parent
72
+
73
+ #: This package's modules on the traceback of the last refusal witnessed in this process, or
74
+ #: `None` for *nothing has been witnessed* (RK267) — which is not the same as the empty tuple,
75
+ #: *a refusal decided outside this package*. A surface that cannot tell those apart would
76
+ #: suppress a note on a refusal it never learned the origin of.
77
+ _WITNESSED: tuple[str, ...] | None = None
78
+
79
+ #: The arguments this process was invoked with, as the surface that parsed them read them, or
80
+ #: `()` where nothing set it — which is every in-process caller: the MCP server dispatches a
81
+ #: parsed namespace and never an argv (RK24), and a test calls `main([...])`. Set once per
82
+ #: process by :func:`~roadkeep.cli.main`, so a retry offered on a refusal is the *caller's own*
83
+ #: call and not this interpreter's `sys.argv`, which under a server or a test harness names
84
+ #: somebody else's program entirely (RK1149).
85
+ _INVOKED: tuple[str, ...] = ()
86
+
87
+
88
+ def _codecs() -> tuple[tuple[str, str], ...]:
89
+ """`name -> encoding/errors` for the three streams, as they are right now.
90
+
91
+ `?` and never a raise for a stream with neither attribute: that is `pythonw`'s `None`, or a
92
+ harness's own object, and a fact about provenance is not worth a crash on import.
93
+ """
94
+ return tuple(
95
+ (
96
+ name,
97
+ f"{getattr(stream, 'encoding', None) or '?'}/"
98
+ f"{getattr(stream, 'errors', None) or '?'}",
99
+ )
100
+ for name, stream in (("stdin", sys.stdin), ("stdout", sys.stdout), ("stderr", sys.stderr))
101
+ )
102
+
103
+
104
+ #: The three streams as this process opened them — a fact about this process in the same class
105
+ #: as :data:`_LOADED_AT`, and the reason it is read *here* is that here is early enough (RK341).
106
+ #: `cli.main` reconfigures all three to UTF-8 in its first three statements, so a capture
107
+ #: composed afterwards reads this tool's own hardening off them instead of the environment that
108
+ #: broke the session: RK337 arrived that way, a field `UnicodeEncodeError` whose re-run exited 0.
109
+ #: Import time is before `main` runs and after nothing this package did, which is exactly the
110
+ #: moment wanted — and it is one dict per *interpreter* rather than per module copy, which
111
+ #: `cli.main` could not be, since `python -m roadkeep.cli` loads that module twice (as
112
+ #: `__main__` and as `roadkeep.cli`) and only one of the two would hold the pristine reading.
113
+ STARTUP_CODECS: tuple[tuple[str, str], ...] = _codecs()
114
+
115
+
116
+ def named(module: Path, home: Path) -> str:
117
+ """What this package calls one of its own modules — the path under it, or `""` (RK1073).
118
+
119
+ One spelling, because the staleness note is composed from **two** readers of it and they
120
+ disagreed for six tasks. `Engine.stale` was made recursive by RK494, when `verbs/` took
121
+ eight handlers each named after the domain module it calls — so a bare `.name` reports
122
+ `shipping.py` for either of two files — and `raised_in`, which answers the other half of
123
+ the same note, kept a flat test on the frame's parent directory. Every refusal decided
124
+ inside `verbs/` therefore named nothing, and the note compared a recursive answer against
125
+ a shallow one. RK1069 surfaced it by moving two more modules down a directory.
126
+
127
+ `""` for anything outside, which is the answer both callers want: a frame in the stdlib
128
+ and a file under someone else's tree are the same non-answer, and neither is worth a
129
+ raise. Resolved, and every filesystem failure allows — a provenance note is the last
130
+ place in this package to start raising.
131
+ """
132
+ try:
133
+ return module.resolve().relative_to(home).as_posix()
134
+ except (OSError, ValueError):
135
+ return ""
136
+
137
+
138
+ @dataclass(frozen=True, slots=True)
139
+ class Engine:
140
+ """The answering copy of this package: its version, its files, and their commit."""
141
+
142
+ version: str
143
+ #: The directory the modules were imported from — always known, and on its own enough
144
+ #: to tell a plugin cache from a checkout.
145
+ home: Path
146
+ #: Short sha of the commit those files are at, or `None` when git cannot place them.
147
+ commit: str | None
148
+ #: Whether the files differ from that commit. Scoped to `home`: a governed file edited
149
+ #: elsewhere in the same repository does not make the engine modified.
150
+ modified: bool = False
151
+
152
+ @property
153
+ def revision(self) -> str:
154
+ if self.commit is None:
155
+ return UNTRACKED
156
+ return f"{self.commit} {MODIFIED}" if self.modified else self.commit
157
+
158
+ @property
159
+ def stale(self) -> tuple[str, ...]:
160
+ """This package's own modules that changed after the process imported them (RK155).
161
+
162
+ Read from disk on every call and never cached, unlike everything else here: identity
163
+ is a fact about the process and this is a fact about right now — a server whose answer
164
+ to "am I current" was decided at startup would be answering the wrong question.
165
+
166
+ An mtime comparison and deliberately nothing more. Re-executing the package is possible
167
+ — the server holds no state between messages — and is the kind of cleverness that fails
168
+ as a half-loaded module; the harness already restarts a plugin whose version moved
169
+ (RK153), which is why every commit bumps the patch. So what is left here is not
170
+ reloading but *saying*, which costs one `stat` per module and cannot be wrong.
171
+ """
172
+ changed = []
173
+ # Recursive since RK494, and named by :func:`named` since RK1073 — the one spelling
174
+ # this package has for its own modules, shared with `raised_in` because the note is
175
+ # composed from both and two vocabularies made the comparison meaningless.
176
+ for module in sorted(self.home.rglob("*.py")):
177
+ try:
178
+ if module.stat().st_mtime > _LOADED_AT + _GRACE:
179
+ changed.append(named(module, self.home))
180
+ except OSError:
181
+ # A module that cannot be stat'd is not evidence of anything. Every other
182
+ # failure in this package allows; a provenance note is the last place to
183
+ # start raising.
184
+ continue
185
+ return tuple(where for where in changed if where)
186
+
187
+ def carried_by(self, root: Path) -> bool:
188
+ """Whether the code answering lives **inside** the project it is answering about (RK246).
189
+
190
+ Which of the two wirings started this process, asked as a fact rather than guessed from
191
+ the harness's directory layout. A plugin's `mcpServers` is versioned by `plugin.json`, so
192
+ RK153's patch bump reloads it; a project running the tool from its own checkout is wired
193
+ by `.mcp.json` → `scripts/roadkeep.py`, which carries no version at all — nothing about
194
+ that process is addressed by a bump, and restarting the session is the only remedy.
195
+
196
+ The two cases differ in exactly this: the plugin's copy is a cache somewhere else, and a
197
+ checkout's is under the governed root. Measured in this repository, where five bumps in
198
+ one session left the server stale while its own note named the bump as the fix.
199
+
200
+ `root` is expected resolved, which every `Config.root` is; a relation this cannot
201
+ establish reads as the plugin, because that branch also ends in "restart the session"
202
+ and is the half of the sentence that is true either way.
203
+ """
204
+ return root in self.home.parents
205
+
206
+ def __str__(self) -> str:
207
+ return f"roadkeep {self.version} ({self.revision}, {self.home})"
208
+
209
+
210
+ def raised_in(error: BaseException) -> tuple[str, ...]:
211
+ """This package's modules on a refusal's traceback, outermost frame first (RK267).
212
+
213
+ The half of the staleness note that :attr:`Engine.stale` cannot supply. An mtime says a file
214
+ moved; this says which files were *executing* when the refusal was decided, and only the two
215
+ together answer the question a reader actually has — whether the drift reaches the verb that
216
+ refused. Measured on RK255: a `why.too-long` decided by `schema.py`, unchanged, arrived
217
+ naming `cli.py`, `merging.py` and `provenance.py`, three modules that could not have decided
218
+ it, and closing with the reader being asked to know the call graph of a refusal they did not
219
+ raise.
220
+
221
+ **Every** package frame and not only the deepest, because a refusal is usually raised one or
222
+ two calls below the module that owns the rule — `Schema.validate` raising out of
223
+ `authoring.add` is two modules that both decided it, and naming only the raiser would put the
224
+ note back to guessing. What this still cannot see is a helper whose frame has already
225
+ returned; §RK267 states that as the miss it accepts, and it is why the changed modules this
226
+ does not name are kept *behind* the ones it does rather than dropped.
227
+
228
+ Reads the traceback and nothing else — no import machinery, no `sys.modules`: the frames carry
229
+ filenames, and a file directly under :data:`_HOME` is one of these modules by the same
230
+ directory relation :attr:`Engine.stale` globs. Names and not paths, because that is what
231
+ `stale` answers and the two are compared. Order is the traceback's own, so the outermost
232
+ package frame reads first, as a printed traceback has it.
233
+ """
234
+ seen: list[str] = []
235
+ frame = error.__traceback__
236
+ while frame is not None:
237
+ where = Path(frame.tb_frame.f_code.co_filename)
238
+ # Not resolved first: a frame filename may be `<string>` or a path this filesystem
239
+ # will not place, and a provenance note is the last place to start raising (`stale`'s
240
+ # own rule). Resolution is attempted only once the name looks like ours.
241
+ if where.suffix == ".py":
242
+ # **Anywhere under the package**, through the same :func:`named` `stale` uses
243
+ # (RK1069, RK1073). A check for the *parent directory* meant a `why.too-long`
244
+ # raised in `kernel/schema.py` named nothing at all — and the note is compared
245
+ # against `stale`, so the two spell a module one way or not at all.
246
+ under = named(where, _HOME)
247
+ if under and under not in seen:
248
+ seen.append(under)
249
+ frame = frame.tb_next
250
+ return tuple(seen)
251
+
252
+
253
+ def witness(error: BaseException | None) -> None:
254
+ """Record which modules decided a refusal, for the surface that will report it (RK267).
255
+
256
+ The seam this needs and had not got. A refusal reaches the MCP server as **text**: the CLI's
257
+ one error path prints it and returns an exit code, so by the time :mod:`roadkeep.serving` sees
258
+ `exit 1` the exception is gone and with it the only evidence of what decided it. Passing it
259
+ through would mean an error channel beside the exit code, which is the contract every other
260
+ caller reads.
261
+
262
+ So it is stated here rather than threaded: one slot, written by the path that consumes the
263
+ exception and read by the path that composes the note. Safe for exactly the reason it looks
264
+ unsafe — a write is serialised by RK117's lock and the server answers one message at a time,
265
+ and the reader clears it (`witness(None)`) *before* the call it is about, so a note can never
266
+ be attributed to an earlier refusal. Nothing else may read it: it is not a public fact about
267
+ the process, it is one call's out-parameter.
268
+ """
269
+ global _WITNESSED
270
+ _WITNESSED = None if error is None else raised_in(error)
271
+
272
+
273
+ def witnessed() -> tuple[str, ...] | None:
274
+ """What :func:`witness` last recorded — `None` when nothing was, which is not `()` (RK267)."""
275
+ return _WITNESSED
276
+
277
+
278
+ def read_by() -> str:
279
+ """`— read by <engine>`, the clause a config refusal ends with (RK155, RK1150).
280
+
281
+ Two surfaces refuse a `roadkeep.toml` and only one of them said which build was reading it.
282
+ Over MCP that clause has been there since RK155, because a key the file declares and the code
283
+ does not know is the shape stale code produces; at a terminal the same refusal named the file,
284
+ the key and the allowed set — every word true, and no way to reach the real answer, since the
285
+ one fact separating *typo* from *this engine is older* is which roadkeep is running.
286
+
287
+ A function rather than a literal at each end: the clause is one sentence about this process,
288
+ and two spellings of it would be two answers to a question with one.
289
+ """
290
+ return f" — read by {engine()}"
291
+
292
+
293
+ def invoked(argv: Sequence[str]) -> None:
294
+ """Record the arguments this run was given, for a refusal that can offer the retry (RK1149).
295
+
296
+ Here rather than read from `sys.argv` where it is wanted, because `sys.argv` is only the
297
+ caller's own call at *one* of this tool's surfaces: over MCP it names the server's process
298
+ and under pytest it names pytest. A refusal spelling a retry off that would print a command
299
+ nobody ran — the failure mode RK254 removed from remedies, arriving through the argument
300
+ rather than through the engine.
301
+
302
+ One slot for :func:`witness`'s reason and under its rules: written by the surface that owns
303
+ the invocation, read only where a refusal is being rendered, and never a public fact about
304
+ the process. It is set **before** dispatch, so nothing can read an earlier call's argv.
305
+ """
306
+ global _INVOKED
307
+ _INVOKED = tuple(argv)
308
+
309
+
310
+ def invocation_argv() -> tuple[str, ...]:
311
+ """The argv :func:`invoked` recorded, or `()` where this surface has none."""
312
+ return _INVOKED
313
+
314
+
315
+
316
+ #: The console script `pyproject.toml` declares, which is what a message may name only where a
317
+ #: PATH lookup finds it (RK254).
318
+ CONSOLE = "roadkeep"
319
+
320
+ #: The launcher the package ships beside itself (RK57), relative to :attr:`Engine.home`. Named
321
+ #: here because :func:`invocation` is the only reader and it is a fact about this distribution's
322
+ #: layout, not about any project.
323
+ LAUNCHER = ("scripts", "roadkeep.py")
324
+
325
+
326
+ @dataclass(frozen=True, slots=True)
327
+ class Persisted:
328
+ """An invocation written into a file that outlives this process, and what ends it (RK255)."""
329
+
330
+ #: The command, absolute and quoted for the shell it will be executed by.
331
+ command: str
332
+ #: The condition under which it stops resolving — always known, because every answer
333
+ #: below has one and a stored command whose expiry nobody stated is one nobody re-runs.
334
+ invalidated_by: str
335
+
336
+
337
+ @lru_cache(maxsize=1)
338
+ def invocation() -> str:
339
+ """How a shell reaches this engine **on this machine** (RK254).
340
+
341
+ Every message offering a shell command used to spell `roadkeep <verb>` literally, and RK57's
342
+ own finding is that the console script exists only after `pip install roadkeep` and only if
343
+ the interpreter's scripts directory is on PATH — so on a plugin-installed machine, and in this
344
+ repository, the tool's most-read message named a command that answers `command not found`.
345
+ That is the family RK242, RK246, RK250 and RK253 each removed one instance of, at the traffic
346
+ of every denied edit.
347
+
348
+ Three answers, most specific first, and each one observed rather than assumed:
349
+
350
+ * the console script, where a PATH lookup finds it;
351
+ * the launcher this package ships beside itself, where it is on disk — spelled relative to the
352
+ working directory when it is under it, because an absolute path is a message about one
353
+ machine (the same reason :class:`~roadkeep.guarding.Refusal` quotes the project's spelling);
354
+ * `python -m roadkeep.cli`, which is right whenever the package is importable at all and is
355
+ the only answer left when neither of the two above is there.
356
+
357
+ `python` and not :data:`sys.executable`: the plugin's own `hooks.json` and `.mcp.json` spell
358
+ it that way, so this is the project's established assumption rather than a second one, and a
359
+ quoted absolute interpreter path is not what a reader copies.
360
+
361
+ Cached: neither PATH nor the package's own layout changes inside one process, and the deny
362
+ path this is read on is the one place a `which` scan would be paid for repeatedly.
363
+ """
364
+ if shutil.which(CONSOLE):
365
+ return CONSOLE
366
+ launcher = engine().home.parents[1].joinpath(*LAUNCHER)
367
+ if launcher.is_file():
368
+ return f"python {_spelled(launcher)}"
369
+ return "python -m roadkeep.cli"
370
+
371
+
372
+ #: The MCP server this distribution declares — the same name in both scopes, and the reason
373
+ #: the two spellings below differ only by what wraps it.
374
+ SERVER = "roadkeep"
375
+
376
+ #: The prefix a project that declares the server itself gets — the first of :func:`serving`'s
377
+ #: two answers, named because it is also the one a message built by hand means (RK488). Held
378
+ #: here and not spelled at the surface that defaults to it: two literals of one prefix is the
379
+ #: drift this module exists to remove, one scope down.
380
+ WIRED = f"mcp__{SERVER}__"
381
+
382
+ #: Where a plugin states its own name, relative to the tree that carries it.
383
+ _MANIFEST = (".claude-plugin", "plugin.json")
384
+
385
+ #: What a project declares its own servers in, relative to its root.
386
+ _PROJECT_MCP = ".mcp.json"
387
+
388
+
389
+ def serving(root: Path) -> str | None:
390
+ """The prefix this session's roadkeep tools arrive under, or ``None`` where there are none.
391
+
392
+ One engine, two names, each right in one scope (RK333): a **project** `.mcp.json`
393
+ produces `mcp__roadkeep__add` — this checkout, and any project `install` wired — while a
394
+ server a **plugin** provides arrives as `mcp__plugin_roadkeep_roadkeep__add`, measured
395
+ against the published payload with `claude --plugin-dir <tree> -p …` from a project that
396
+ is not this one. `Refusal` stated the first unconditionally, so in the plugin's own
397
+ audience the route it named first was one that session cannot call — worse than the shell
398
+ form it demotes, because that one at least fails loudly.
399
+
400
+ **Decided by what the two scopes actually put on disk**, in the same spirit as
401
+ :func:`invocation`: an adopting project has no `.mcp.json` and gets its tools from the
402
+ plugin tree the engine is running out of, while a wired project has one naming this
403
+ server. The environment is not asked — `${CLAUDE_PLUGIN_ROOT}` is substituted into a
404
+ command line rather than exported, which `tests/test_plugin.py` measured from the other
405
+ end — and the hook payload says which tool was denied, never which server offered it.
406
+
407
+ **And there is a third state, which used to be answered with a guess** (RK444, RK447).
408
+ RK333 chose the bare name wherever neither scope spoke, on the argument that it is what
409
+ every project that ran `install` has and that naming a plugin nobody installed would be
410
+ the same defect with the scopes swapped. That argument is sound and it is about a choice
411
+ *between two prefixes*. A project that pip-installed roadkeep and never ran `install` has
412
+ neither — no tools at all — and both surfaces that name a route were handing it one it
413
+ cannot call: the notice that every session reads, and the denial that stops an edit. So
414
+ the answer here is allowed to be ``None``, and each caller says what it does with that.
415
+ """
416
+ # And this branch is why `WIRED` **is** the declared case, which is a fact callers read
417
+ # off the prefix rather than asking twice (RK1244): a project that declares the server
418
+ # gets the bare name, and nothing else does.
419
+ if _declared_by(root):
420
+ return WIRED
421
+ # And the plugin answers only for the project **this process is in** (RK1325). The branch
422
+ # above reads the root it was handed; this one reads the tree the engine runs out of, and
423
+ # the two are one question only while the root is the session's own. Measured on a tree
424
+ # `init` had just made — no `.claude`, no `.mcp.json`, nothing wired — reached with `-C`:
425
+ # it was handed `mcp__plugin_roadkeep_roadkeep__`, so every door in its payload carried a
426
+ # call naming a tool that project has nothing to answer with. RK449 states the rule the
427
+ # other way, and the fallback made *nothing serves it* unreachable.
428
+ #
429
+ # A served caller cannot act on another project — the harness starts one server per
430
+ # project and its tools take no root — so where the root is not this process's own, there
431
+ # is no call to publish and `None` is the answer. An adopting project under the plugin is
432
+ # unaffected: its root *is* the session's, which is the ordinary case this branch is for.
433
+ if _plugin_name() is None or not _own(root):
434
+ return None
435
+ return f"mcp__plugin_{_plugin_name()}_{SERVER}__"
436
+
437
+
438
+ def _own(root: Path) -> bool:
439
+ """Whether this process is running *in* the project at ``root`` (RK1325).
440
+
441
+ The working directory and not an environment variable: `Config.discover` walks up from
442
+ here to find `roadkeep.toml`, so the root a caller reaches without `-C` is this directory
443
+ or one above it. A root that is neither is a project this process was pointed at, and a
444
+ plugin serving this session does not serve that one.
445
+ """
446
+ try:
447
+ here = Path.cwd().resolve()
448
+ wanted = root.resolve()
449
+ except OSError:
450
+ return False
451
+ return wanted == here or wanted in here.parents
452
+
453
+
454
+ def served_by(root: Path) -> str:
455
+ """:func:`serving`'s answer as a **prefix to concatenate**, or `""` where none (RK488).
456
+
457
+ One reader for the six places that carry it. Each of them wanted the same two things —
458
+ the optional collapsed, because below there it is a string to put in front of a tool name,
459
+ and the empty case meaning *there is no call to publish*, which is what every renderer
460
+ already branches on — and each spelled `serving(root) or ""` for itself, which is four
461
+ mechanisms for one fact and a fifth waiting to be written slightly differently.
462
+
463
+ Not a second answer: the distinction :func:`serving` keeps between ``None`` and a prefix is
464
+ real and stays there, for the caller that has to tell *this project has no server* from
465
+ *this project's server is named so*. This is that answer for the callers that do not.
466
+ """
467
+ return serving(root) or ""
468
+
469
+
470
+ @lru_cache(maxsize=8)
471
+ def _declared_by(root: Path) -> bool:
472
+ """Does this project declare the server itself? Cached per root, read once per process.
473
+
474
+ Unreadable is *not* declared: a `.mcp.json` this cannot parse is one the session could
475
+ not launch a server from either, so the plugin is the likelier route and a crash inside a
476
+ hook would deny the edit and print a traceback instead of the command to run.
477
+ """
478
+ # Imported here and not at module level, the reason `_placed` gives: this is read on
479
+ # the denial path alone, and every other caller of this module pays for the import.
480
+ import json # noqa: PLC0415
481
+
482
+ try:
483
+ declared = json.loads((root / _PROJECT_MCP).read_text(encoding="utf-8"))
484
+ except (OSError, ValueError):
485
+ return False
486
+ servers = declared.get("mcpServers") if isinstance(declared, dict) else None
487
+ return isinstance(servers, dict) and SERVER in servers
488
+
489
+
490
+ @lru_cache(maxsize=1)
491
+ def _plugin_name() -> str | None:
492
+ """The name the tree this engine runs out of publishes itself under, if it is a plugin.
493
+
494
+ Read from the manifest rather than from the directory: a plugin is installed under a
495
+ path the marketplace chooses, and the name in the payload is the one the manifest states.
496
+ """
497
+ import json # noqa: PLC0415
498
+
499
+ try:
500
+ manifest = json.loads(
501
+ engine().home.parents[1].joinpath(*_MANIFEST).read_text(encoding="utf-8")
502
+ )
503
+ except (OSError, ValueError, IndexError):
504
+ return None
505
+ name = manifest.get("name") if isinstance(manifest, dict) else None
506
+ return name if isinstance(name, str) and name else None
507
+
508
+
509
+ def _spelled(launcher: Path) -> str:
510
+ """The launcher as a reader would type it: forward slashes, quoted only where a space forces it.
511
+
512
+ `as_posix` and not the native separator, because the shell this is copied into is the agent's,
513
+ and there a `\\` is an escape rather than a path component — `scripts\\roadkeep.py` reaches
514
+ `scriptsroadkeep.py`. Windows `python` accepts forward slashes either way, so one spelling is
515
+ right on both platforms and the native one is right on neither reader.
516
+ """
517
+ try:
518
+ shown = launcher.relative_to(Path.cwd()).as_posix()
519
+ except (OSError, ValueError): # another drive, another tree, or no readable cwd
520
+ shown = launcher.as_posix()
521
+ return f'"{shown}"' if " " in shown else shown
522
+
523
+
524
+ @lru_cache(maxsize=1)
525
+ def persisted() -> Persisted:
526
+ """How a **stored** invocation must be spelled, and what would stop it (RK255).
527
+
528
+ :func:`invocation` answers for a message a reader copies now. This answers for a string
529
+ written into `.git/config`, which git executes at merge time — in a shell nobody chose,
530
+ from a working directory this process never sees. Two of that function's three answers
531
+ are wrong the moment they are stored: the console script is a name PATH resolves, and a
532
+ PATH is per-shell, so a GUI client's is not the terminal's; the launcher is spelled
533
+ relative to the working directory, and a value in `.git/config` outlives it.
534
+
535
+ The same three answers, resolved to absolute paths, each carrying the condition that
536
+ ends it. **Nothing here refuses.** Every machine has a last answer, and a `merge
537
+ register` that failed on the machine most likely to want one would send its author back
538
+ to the hand edit this tool exists to stop — so what a persisted command cannot promise
539
+ is *stated* rather than withheld, which is the one place this tool reports after rather
540
+ than refusing before, because the alternative reports nothing at all.
541
+
542
+ Cached with :func:`invocation` and for the same reason: neither PATH nor this package's
543
+ layout moves inside one process.
544
+ """
545
+ found = shutil.which(CONSOLE)
546
+ if found:
547
+ return Persisted(
548
+ _absolute(Path(found)),
549
+ f"the interpreter that installed {CONSOLE} being replaced or removed",
550
+ )
551
+ launcher = engine().home.parents[1].joinpath(*LAUNCHER)
552
+ if launcher.is_file():
553
+ return Persisted(
554
+ f"python {_absolute(launcher)}",
555
+ "a plugin update installing this package under a new directory",
556
+ )
557
+ return Persisted(
558
+ "python -m roadkeep.cli",
559
+ f"{engine().home.parent.as_posix()} not being importable from the merging repository",
560
+ )
561
+
562
+
563
+ def _absolute(path: Path) -> str:
564
+ """A path a stored command can hold: absolute, forward-slashed, single-quoted if spaced.
565
+
566
+ Single quotes and not the double ones :func:`_spelled` uses, because this string is nested
567
+ inside the double-quoted value of a `git config` argument — a second `"` there would end
568
+ the value at the first space rather than quote the path across it.
569
+ """
570
+ try:
571
+ path = path.resolve()
572
+ except OSError: # an unreadable cwd or a path this filesystem will not answer for
573
+ path = path.absolute()
574
+ shown = path.as_posix()
575
+ return f"'{shown}'" if " " in shown else shown
576
+
577
+
578
+ @lru_cache(maxsize=2)
579
+ def engine(placed: bool = True) -> Engine:
580
+ """Describe the copy of this package that is running. Cached: one git call per process.
581
+
582
+ ``placed=False`` answers the two facts that cost nothing — the version and the directory
583
+ — and leaves the commit unknown, which is the state a marketplace row with no sha already
584
+ puts every reader in (RK1237). Measured here: `ls-files`, `rev-parse` and `status
585
+ --porcelain` are 14, 14 and 16 ms, so a placed reading is **45 ms**, against a floor of 43
586
+ for a whole command. That is affordable once per session and not once per write, and the
587
+ caller that pays it per write is :func:`~roadkeep.installing.behind`, which asks unplaced
588
+ first and only pays where the versions match.
589
+
590
+ Two entries in the cache and not one: a process that asks both questions asks each once,
591
+ and the cheap answer is not a cache miss for the expensive one.
592
+ """
593
+ home = Path(roadkeep.__file__).resolve().parent
594
+ commit, modified = _placed(home) if placed else (None, False)
595
+ return Engine(version=roadkeep.__version__, home=home, commit=commit, modified=modified)
596
+
597
+
598
+ def _placed(home: Path) -> tuple[str | None, bool]:
599
+ # The package's one call to git: its timeout, its encoding and its single failure type.
600
+ # Duplicating a `subprocess.run` here would be duplicating those three decisions.
601
+ #
602
+ # Imported here and not at module level (RK260): `history` reaches `backlog` and `sections`,
603
+ # measured at 29 ms and four modules, and this is the only function in the file that asks git
604
+ # anything. The guard imports this module for :func:`invocation`, which reads a directory —
605
+ # so a denial paid for the git wrapper it never calls.
606
+ from roadkeep.history import HistoryUnavailable, _run as _git # noqa: PLC0415
607
+
608
+ try:
609
+ # `ls-files` first: it answers "does this tree track these very files", which
610
+ # `rev-parse` does not — an installed package under an unrelated repository would
611
+ # otherwise report that repository's HEAD as its own provenance.
612
+ if not _git(home, "ls-files").strip():
613
+ return None, False
614
+ commit = _git(home, "rev-parse", "--short", "HEAD").strip()
615
+ modified = bool(_git(home, "status", "--porcelain", ".").strip())
616
+ except HistoryUnavailable:
617
+ return None, False
618
+ return commit or None, modified
619
+
620
+
621
+ #: Where the harness keeps the registry of installed plugins, under its config directory —
622
+ #: `CLAUDE_CONFIG_DIR` where the environment sets one, and `~/.claude` otherwise, which is
623
+ #: the same pair the harness itself resolves. Read and never written: this file is the
624
+ #: harness's, and a tool that edited it would be answering a question by changing it.
625
+ _REGISTRY = ("plugins", "installed_plugins.json")
626
+
627
+ #: The name this package is published under, matched against the registry key's `<name>@
628
+ #: <marketplace>` left half. A literal, and not configuration (L6): every other name in this
629
+ #: tool is the adopting project's, and this one is *ours* — the question being asked is which
630
+ #: copy of **this** plugin a project has, so a project that could answer it differently would
631
+ #: be answering about something else.
632
+ PLUGIN = "roadkeep"
633
+
634
+
635
+ @dataclass(frozen=True, slots=True)
636
+ class Installed:
637
+ """The plugin copy the harness has wired to one project (RK415).
638
+
639
+ The second of the three engines an adopting project runs, and the one no other reader in
640
+ this package could name: the checkout answers for itself, the workflow states its ref in
641
+ a file, and this one is a row in the harness's own registry.
642
+ """
643
+
644
+ version: str
645
+ #: Where the marketplace unpacked it — the directory a hook and the MCP server run out of.
646
+ home: Path | None
647
+ #: The commit the marketplace recorded for that copy, or None where it recorded none.
648
+ commit: str | None
649
+ #: `project` or `user`, as the registry spells it: which scope wired this project to it.
650
+ scope: str = ""
651
+
652
+ @property
653
+ def revision(self) -> str:
654
+ return UNTRACKED if self.commit is None else self.commit[:7]
655
+
656
+
657
+ def home() -> Path | None:
658
+ """This machine's home directory, or `None` where the environment names none (RK1406).
659
+
660
+ `Path.home()` **raises** rather than answering — a container run with `env -i`, a CI step
661
+ that scrubbed its environment, a hook invoked by a service manager. Three readers called it
662
+ unguarded and all three are on the path `lint` takes through `engines`, so the gate died
663
+ with a `RuntimeError` traceback on a tree it had not finished reading. Met for real while
664
+ capturing an adoption walkthrough in a narrowed environment.
665
+
666
+ No home is **not an error**: it means no plugin is installed for this user, and that is an
667
+ answer. Declared here rather than in :mod:`roadkeep.installing`, which is where two of the
668
+ three callers are, because that module already imports this one — the other direction would
669
+ be a cycle for a four-line reader.
670
+ """
671
+ try:
672
+ return Path.home()
673
+ except RuntimeError:
674
+ return None
675
+
676
+
677
+ def installed(root: Path) -> Installed | None:
678
+ """The plugin the harness has installed **for this project**, or None (RK415).
679
+
680
+ Measured live: a checkout at 0.1.418 did every write in a project whose hooks ran the
681
+ plugin at 0.1.285 — 133 versions apart, both correct on their own terms, and nothing
682
+ anywhere said so. The facts were local the whole time; what was missing was a reader.
683
+
684
+ Matched on the **project path** and not on the marketplace, because a project is wired to
685
+ one copy and the question is which one judges *this* tree. Rows are the harness's own
686
+ format, so every field is read defensively and a registry this cannot parse is None
687
+ rather than a refusal: nothing here is worth failing a write over.
688
+
689
+ Not cached. `engine()` is a fact about the running process and this is a fact about a
690
+ file somebody else writes — a `/plugin update` between two calls is exactly the change
691
+ this exists to report, and an answer decided at import would hide it.
692
+
693
+ **The first matching row is not the answer** (RK1167). A project accumulates one row per
694
+ install and the harness prunes the directories, not the records: measured on a corpus whose
695
+ registry held `0.1.285` dated the 5th with no install left, and `0.1.820` dated the 13th with
696
+ one. Returning on the first put the retired version in `engines`, which then printed the
697
+ sentence telling the author to run `/plugin update` — after the update had landed, and
698
+ unfollowably, since running it again writes a fourth row the same scan skips.
699
+
700
+ So a row naming an install that is gone is a **record** and not an install (RK1166 made the
701
+ launcher read it that way), and among the rows that do resolve the newest `lastUpdated` is
702
+ the one the harness will load. A row naming no path keeps its claim: older harnesses wrote
703
+ none, and dropping those would answer *no plugin* where there is one.
704
+ """
705
+ import json # noqa: PLC0415
706
+
707
+ import os # noqa: PLC0415
708
+
709
+ stated = os.environ.get("CLAUDE_CONFIG_DIR")
710
+ if not stated and (mine := home()) is None:
711
+ return None
712
+ where = Path(stated) if stated else mine / ".claude" # type: ignore[operator]
713
+ try:
714
+ payload = json.loads(where.joinpath(*_REGISTRY).read_text(encoding="utf-8"))
715
+ wanted = root.resolve()
716
+ except (OSError, ValueError):
717
+ return None
718
+ plugins = payload.get("plugins") if isinstance(payload, dict) else None
719
+ if not isinstance(plugins, dict):
720
+ return None
721
+ found: list[dict[str, object]] = []
722
+ for key, rows in plugins.items():
723
+ if not isinstance(key, str) or key.partition("@")[0] != PLUGIN:
724
+ continue
725
+ for row in rows if isinstance(rows, list) else ():
726
+ if not isinstance(row, dict) or not _is(row.get("projectPath"), wanted):
727
+ continue
728
+ if not isinstance(row.get("version"), str) or not row.get("version"):
729
+ continue
730
+ found.append(row)
731
+ row = _loaded(found)
732
+ if row is None:
733
+ return None
734
+ place = row.get("installPath")
735
+ commit = row.get("gitCommitSha")
736
+ return Installed(
737
+ version=str(row["version"]),
738
+ home=Path(place) if isinstance(place, str) and place else None,
739
+ commit=commit if isinstance(commit, str) and commit else None,
740
+ scope=row.get("scope") if isinstance(row.get("scope"), str) else "",
741
+ )
742
+
743
+
744
+ def _loaded(rows: list[dict[str, object]]) -> dict[str, object] | None:
745
+ """Which of a project's rows the harness would actually load (RK1167).
746
+
747
+ Two readings the file already carries and the scan skipped. An `installPath` that is not
748
+ there names an install the harness pruned, and a record of one is not one; `lastUpdated`
749
+ orders what is left, because a project accumulates a row per install and the newest is the
750
+ one loaded. Compared as text, which is what an ISO timestamp is written for — parsing it
751
+ would be this reader deciding a format somebody else owns.
752
+
753
+ Falls back to the rows as written where **none** resolves: an answer of *no plugin* about a
754
+ project the registry names is a worse reading than a stale version, and `engines` prints the
755
+ install directory beside the number, so a reader sees what this could not confirm.
756
+ """
757
+ if not rows:
758
+ return None
759
+ live = [one for one in rows if _present(one.get("installPath"))]
760
+ return max(live or rows, key=lambda one: str(one.get("lastUpdated") or ""))
761
+
762
+
763
+ def _present(stated: object) -> bool:
764
+ """Whether the install a row names is still on disk — True where it names none (RK1167).
765
+
766
+ The same reading `hooks/roadkeep-launch.py` makes of the same field (RK1166), and stated
767
+ twice because the two readers may not import each other: that file runs with nothing on
768
+ `sys.path` but the standard library, which is the whole of what it is for.
769
+ """
770
+ if not isinstance(stated, str) or not stated:
771
+ return True
772
+ try:
773
+ return Path(stated).is_dir()
774
+ except OSError:
775
+ return False
776
+
777
+
778
+ def _is(stated: object, wanted: Path) -> bool:
779
+ """Whether a registry row's project path is this tree — resolved, and never as text.
780
+
781
+ The harness writes the path the way its platform spells it, so a Windows row and a
782
+ posix-spelled config are one project written twice and a string compare calls them two.
783
+ """
784
+ if not isinstance(stated, str) or not stated:
785
+ return False
786
+ try:
787
+ return Path(stated).resolve() == wanted
788
+ except OSError:
789
+ return False