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/remedying.py ADDED
@@ -0,0 +1,1989 @@
1
+ """What closes one finding, as a command rather than a sentence (RK420).
2
+
3
+ `lint` and the guard are the two halves of one contract. The barrier states the rule
4
+ outright — a refusal that names no alternative is a refusal an agent works around — and
5
+ :data:`~roadkeep.guarding._INSTEAD` keeps it, carrying the command *and its flags* for
6
+ every governed role. The gate made the same promise in :class:`~roadkeep.linting.Finding`'s
7
+ docstring and did not keep it: counted over the emission sites, 25 of 37 codes named no
8
+ verb at all, and the twelve that did named it inside a sentence, as prose to re-type.
9
+
10
+ The cost of that is paid in **turns**, which is why it went unmeasured. A report arrives,
11
+ the caller infers a door per code, and the guard denies the `Edit` that would have been the
12
+ shortcut — so the loop is *retry a verb until one is not refused*, against a file whose
13
+ repair was one command the whole time. `id.duplicate` is the case that proves it: `record
14
+ drop` and `record renumber` both exist, the refusal on each names the other, and the
15
+ finding names neither.
16
+
17
+ So the remedy is a field, and this module is the one table it comes from. Four kinds,
18
+ because four is what a caller actually does next:
19
+
20
+ * ``fix`` — `lint --fix` takes it. No decision, no prose, nothing to read.
21
+ * ``run`` — one command that **writes**, complete, with the id and the line already
22
+ substituted. A placeholder here would be the guess this module exists to remove.
23
+ * ``read`` — one command answers the question and closes nothing: which of two sections is
24
+ history, what a block dep expands to, which file claims an anchor. Split out from ``run``
25
+ because `repair` executes that one, and a read it executed would spend a step, change no
26
+ byte and report the finding still standing — a repair that repairs nothing.
27
+ * ``compose`` — one command, one field that is **prose only the author can write**. L4 is
28
+ not a gap in the table, it is the table being honest: nothing here composes a title, a
29
+ reason or a shorter sentence, so the blank is marked and left.
30
+ * ``decide`` — more than one door, and which one is right is editorial. Both are rendered,
31
+ and :attr:`Remedy.decision` states what distinguishes them, so the choice is made from the
32
+ report instead of by running one and reading its refusal. `repair` executes none of them,
33
+ which is what lets one carry L4's blank where the choice is between an editorial write and
34
+ a write only the author can compose — `deps.unknown` and `priority.block-unstarted`
35
+ (RK435). "Both are rendered complete" is what this said, and two rows already refuted it.
36
+
37
+ **The table is keyed by code and nothing else.** A remedy computed at the emission site
38
+ would be 70 remedies to keep in step with 70 messages, and the one that fell behind would
39
+ be invisible — the report still prints, the exit is still 1, and only the sentence that
40
+ would have saved the turn is missing. Keyed centrally, `tests/test_remedying.py` can assert
41
+ the domain is *total* over every code the package can emit (RK421), which turns adding a
42
+ check without stating its repair into a red rather than a discovery on somebody else's
43
+ backlog six months later.
44
+
45
+ **Two things are read from the config rather than fixed** (L6): whether the pointer is
46
+ derived (`ref_scheme = "id"` makes `ref.mismatch` mechanical; an outline anchor is the
47
+ author's, so it is `compose`), and which role a file plays, since `id.duplicate` is
48
+ `renumber` in the roadmap and `record renumber` in the ledger. Everything else is one
49
+ lookup.
50
+
51
+ What this module does **not** do is run anything. `repair` (RK422) is the verb that reads
52
+ these back and executes them; keeping the table pure is what lets `lint --json`, `explain`
53
+ and the guard's denial all quote the same answer without any of them growing a side effect.
54
+
55
+ **And it is the one place a command becomes text** (RK488). :class:`Door` was already the
56
+ shape — an argv and what it does, spelled as a shell line or as a tool call by whoever prints
57
+ it — but only findings went through it. Everything else composed its own: the guard's two
58
+ tables and its three sentences, the gate's, the attestation's, and a third copy of the whole
59
+ mechanism inside `serving`, each branching on the served prefix for itself. So a surface that
60
+ never learned to ask printed the shell form to a session holding the tools, and RK444, RK447,
61
+ RK448, RK475, RK477 and RK479 each taught one more site to ask without anything being able to
62
+ say how many were left. :meth:`Door.named`, :meth:`Door.mention`, :func:`offered` and
63
+ :func:`alongside` are the four renderings a message actually wants, and
64
+ `tests/test_remedying.py` holds the property that nothing outside this module spells one —
65
+ the same total-domain assertion the table above gets, about spellings instead of codes.
66
+
67
+ The prefix still arrives as a **field** and is not read here: which engine answers is a fact
68
+ about the project, and this module reads no project. What changed is that it is now handed to
69
+ a renderer instead of interpolated at forty call sites.
70
+
71
+ **A row states what is per-code and derives the rest** (RK490). Totality over the codes says
72
+ every finding has a door; it says nothing about whether the door is about that finding. Three
73
+ rows failed on exactly that and each was found by example — RK468 named one verb and
74
+ dispatched another, RK470 omitted which prose file the finding was in, RK472 dispatched a door
75
+ the verb refuses — and what bound them is that a row *repeated* the finding's subject, file or
76
+ verb instead of reading it. :func:`_values` is the one place any of them is derived and
77
+ :data:`FIELDS` is the declared domain of what a row may name, so the agreement is a property
78
+ over the whole table rather than a defect discovered one row at a time.
79
+ """
80
+
81
+ from __future__ import annotations
82
+
83
+ import shlex
84
+ from collections.abc import Mapping, Sequence
85
+ from dataclasses import dataclass
86
+ from functools import lru_cache
87
+
88
+ from .config import PROSE_ROLES, ROLES, Config
89
+ from roadkeep.kernel.schema import Dep
90
+
91
+ #: The six kinds, in the order a caller pays for them: nothing, one write, one read then a
92
+ #: judgement, one sentence, one choice, and one command that is not this tool's at all.
93
+ #: `repair` runs the first two and prints the rest.
94
+ KINDS = ("fix", "run", "read", "compose", "decide", "restore")
95
+
96
+ #: Marks the one field of a ``compose`` argv that the tool may not write (L4). Kept as a
97
+ #: distinct token rather than an empty string so a caller can find it without parsing prose.
98
+ BLANK = "…"
99
+
100
+
101
+ def _spelled_word(word: str) -> str:
102
+ """One argv token as a line a shell reads back as that token (RK1265).
103
+
104
+ **Whitespace and nothing else**, which is narrower than `shlex.quote`'s own rule and
105
+ deliberately so: what this fixes is a token that would run as several arguments, and the
106
+ other characters that reader quotes are already in doors that print correctly today —
107
+ `<command> --help` is one of them, and `'<command>' --help` reads as a literal somebody
108
+ typed. The :data:`BLANK` is never quoted either, for :attr:`Door.quoted`'s reason: it
109
+ marks a field the author fills, and `'…'` reads as a value already chosen.
110
+ """
111
+ if BLANK in word or not word or not any(c.isspace() for c in word):
112
+ return word
113
+ return shlex.quote(word)
114
+
115
+
116
+ @lru_cache(maxsize=1)
117
+ def _reading() -> Mapping[str, frozenset[str]]:
118
+ """Every verb this CLI declares read-only, and the flags that turn each into a write.
119
+
120
+ Both halves come from the parser that declares them, because both are already there:
121
+ `reads_only` is what keeps a command out of the write lock (RK117) and `writes_when`
122
+ names the flag that makes one a write anyway (RK167) — `lint` is read-only and `lint
123
+ --fix` is not, which is the case this mapping exists for and the one a set alone gets
124
+ backwards.
125
+
126
+ Deferred and cached: `cli` imports this module to build a report, so the edge back runs
127
+ at call time (RK260), and the parser is built once — a remedy is rendered per finding
128
+ and a report can carry hundreds.
129
+ """
130
+ from roadkeep.cli import build_parser # noqa: PLC0415 - RK1015
131
+ from roadkeep.verbs.declaring import writes_when # noqa: PLC0415 - RK1171
132
+
133
+ verbs = next(
134
+ action
135
+ for action in build_parser()._actions
136
+ if getattr(action, "choices", None) and action.dest == "command"
137
+ )
138
+ out: dict[str, frozenset[str]] = {}
139
+ for verb, parser in verbs.choices.items():
140
+ if not parser.get_default("reads_only"):
141
+ continue
142
+ turns = set(writes_when(parser))
143
+ out[verb] = frozenset(
144
+ option
145
+ for action in parser._actions
146
+ if action.dest in turns
147
+ for option in action.option_strings
148
+ )
149
+ return out
150
+
151
+
152
+ @dataclass(frozen=True, slots=True)
153
+ class Door:
154
+ """One command that could close a finding, and what choosing it means.
155
+
156
+ ``what`` is only load-bearing on a ``decide``, where it is the difference between the
157
+ doors — but it is carried on every kind, because a caller printing a remedy has one
158
+ shape to render and `explain` (RK423) has one field to quote.
159
+ """
160
+
161
+ argv: tuple[str, ...]
162
+ what: str
163
+ #: Whether this argv is somebody else's command (RK451). False for every door but the
164
+ #: ``restore`` kind's: there the content of a governed file is gone, no verb of this tool
165
+ #: brings it back, and the store is the repository (L2) — so the command is git's, and
166
+ #: prefixing it with this engine would name a subcommand roadkeep does not have.
167
+ foreign: bool = False
168
+
169
+ @property
170
+ def writes(self) -> bool:
171
+ """Does running this door change the files (RK1015)?
172
+
173
+ **Per door and not per remedy**, which is the whole of it: `deps.unknown` is one
174
+ `decide` holding `gaps`, which answers a question and changes nothing, and `amend
175
+ <id> --dep …`, which writes. The kind is the remedy's, so it says `decide` about
176
+ both, and a caller that has to know which it just pressed — a quick-fix menu, a
177
+ repair loop — could not ask.
178
+
179
+ Derived from the verb and never declared twice: the CLI already states which
180
+ commands only read, because that is what keeps one out of the write lock (RK117), and
181
+ a second list here would be the drift this package exists to stop. A foreign door is
182
+ somebody else's command and this tool has no opinion about it — `git checkout` writes
183
+ and says so in its own name.
184
+ """
185
+ reading = _reading()
186
+ if self.foreign or self.argv[0] not in reading:
187
+ return True
188
+ # A read-only verb with the flag that makes it a write: `lint --fix` is the case,
189
+ # and the parser is where both facts are already declared.
190
+ return any(flag in self.argv for flag in reading[self.argv[0]])
191
+
192
+ @property
193
+ def command(self) -> str:
194
+ """The argv as a line to run, reaching this engine the way this machine can (RK254).
195
+
196
+ Derived and never the literal console script: it exists only after a `pip install`
197
+ that put the scripts directory on PATH, so on a plugin-installed machine — and in
198
+ this repository — a remedy spelling it names a command that answers `command not
199
+ found`. A remedy a caller cannot run is the defect this task was about, one step
200
+ further along.
201
+
202
+ A :attr:`foreign` door is already whole: it names another tool, so there is no
203
+ invocation of this one to put in front of it.
204
+
205
+ **A token carrying a space is quoted, and only such a token** (RK1265). Every door
206
+ before the criteria carried argv of single words — an id, a code, a flag, or a
207
+ :data:`BLANK` the author fills — so joining on spaces was the whole of it; the lead of
208
+ a criterion is the caller's own prose and is what a remedy substitutes, so an unquoted
209
+ line runs as eight arguments. The blank is left bare for :attr:`quoted`'s reason: a
210
+ `'…'` reads as a value somebody chose, and it is the one token that is not one.
211
+ """
212
+ words = tuple(_spelled_word(word) for word in self.argv)
213
+ if self.foreign:
214
+ return " ".join(words)
215
+ from .provenance import invocation
216
+
217
+ return " ".join((invocation(), *words))
218
+
219
+ @property
220
+ def quoted(self) -> str:
221
+ """:attr:`command`, spelled for the shell that will run it verbatim (RK1149).
222
+
223
+ Every door before this one carried argv of single tokens — an id, a code, a flag — or a
224
+ `BLANK` the author fills, so joining on spaces was the whole of it. A retry offered on a
225
+ refusal carries the caller's **prose**: a symptom and a why, with spaces and apostrophes
226
+ in them, and a command printed unquoted is one that runs as eight arguments or not at all.
227
+
228
+ Beside :attr:`command` rather than replacing it: what a table prints and what a caller
229
+ pastes are two readings, and quoting a `…` placeholder would spell it `'…'`, which reads
230
+ as a value somebody chose.
231
+ """
232
+ if self.foreign:
233
+ return shlex.join(self.argv)
234
+ from .provenance import invocation
235
+
236
+ return f"{invocation()} {shlex.join(self.argv)}"
237
+
238
+ @property
239
+ def complete(self) -> bool:
240
+ """Whether every field is filled — false where L4 left one to the author."""
241
+ return not any(BLANK in word for word in self.argv)
242
+
243
+ def call(self) -> tuple[str, dict[str, object]] | None:
244
+ """The same door as a **tool call**: the name and its fields, or ``None`` (RK449).
245
+
246
+ `lint` and `explain` are both served, and what they handed a caller there was this
247
+ argv — a list of shell words, to the one surface RK57 left with no console script and
248
+ no PATH entry. So the door is published in both spellings and the caller takes the one
249
+ its session can make.
250
+
251
+ Derived from the argv and never tabled beside it. The mapping is the subcommand's
252
+ **own parser**, which is what `serving` already reads to publish the schema, so a
253
+ renamed flag moves both ends at once and there is no third declaration to fall behind.
254
+ Two things fall out of that rather than being decided:
255
+
256
+ * A door setting a field the tool surface withholds has **no call**, and `lint --fix`
257
+ is exactly that — `--fix` writes, and RK16 keeps it where a human is standing, so
258
+ `lint` is served without it. The one remedy that must stay a shell command stays one
259
+ by derivation instead of by exception.
260
+ * :attr:`argv` remains the fact. `repair` (RK422) dispatches it untouched, and this is
261
+ computed beside it — which is what keeps the second spelling from becoming a second
262
+ grammar.
263
+
264
+ The :data:`BLANK` survives into the field it lands in, because it means the same thing
265
+ there: L4 left that one to the author, and a call with the marker in it is a call to
266
+ finish rather than one to make.
267
+ """
268
+ if self.foreign:
269
+ return None # somebody else's command; this surface serves none of it (RK451)
270
+ from .serving import TOOLS, _fields_of, _subparser, serves # noqa: PLC0415 - RK260
271
+
272
+ # **Which** tool, asked once and in one place (RK488): `serves` reads `TOOLS` alone,
273
+ # so the guard can afford the same question inside a hook budget a parser build would
274
+ # spend four times over. What is left here is the tail as *values*, which is the one
275
+ # half that genuinely needs the parser.
276
+ name = serves(self.argv)
277
+ if name is None:
278
+ return None
279
+ tool = next(one for one in TOOLS if one.name == name)
280
+ rest = list(self.argv)[len(tool.argv_head) :]
281
+ # The unconditional half, which is what this reader can ask: a door is composed
282
+ # without a project (RK1157), and whether one opens a conditional field is that
283
+ # project's answer — so a field only some projects offer has no call here.
284
+ fields = _fields_of(_subparser(tool.command), rest, tool.unconditional)
285
+ return None if fields is None else (name, fields)
286
+
287
+ def payload(self, served: str = "") -> dict[str, object]:
288
+ """This door as JSON — one writer, because two answers publish one now (RK1147).
289
+
290
+ `Remedy.payload` built this row inline, and then `adopt` needed the same shape: its
291
+ printed report has named the flag that reads a file the other way since RK285, and its
292
+ payload published the count beside it and nothing else — the asymmetry `lint` has not
293
+ had since RK15, on the one command whose whole output is a decision. An estimate's
294
+ unread reading is not a finding and has no code, so what it carries is a door and not a
295
+ `Remedy`, which is exactly why the row had to stop being a `Remedy` local.
296
+
297
+ ``served`` is the prefix this session's tools arrive under, and where it is given the
298
+ door carries its **call** beside its argv (RK449). Absent — or where nothing serves the
299
+ door, which is every `adopt` door, that verb being deliberately unserved — only the
300
+ argv is published, which is what every consumer written before RK449 already reads.
301
+ """
302
+ row: dict[str, object] = {
303
+ "argv": list(self.argv),
304
+ "what": self.what,
305
+ "complete": self.complete,
306
+ # Whether pressing it changes the files (RK1015): the kind is the remedy's, and one
307
+ # `decide` holds a read and a write.
308
+ "writes": self.writes,
309
+ }
310
+ call = self.call() if served else None
311
+ if call is not None:
312
+ name, fields = call
313
+ row["call"] = {"tool": f"{served}{name}", "arguments": fields}
314
+ return row
315
+
316
+ def named(self, served: str = "") -> str:
317
+ """This door's **command alone**, in the spelling ``served`` has (RK488).
318
+
319
+ The third of the three renderings, and the one a *table* prints: :attr:`command` is
320
+ the shell line unconditionally, :meth:`spoken` is a spelling plus what it does, and
321
+ this is the column the rows are padded to, with the purpose in a column of its own.
322
+
323
+ Cheap by construction — it asks `serving.serves` and never the parser — because the
324
+ guard composes one of these per row inside a `PreToolUse` the harness waits on. The
325
+ arguments the served name drops are :meth:`passing`'s to state.
326
+ """
327
+ if self.foreign or not served:
328
+ return self.command
329
+ from .serving import serves # noqa: PLC0415 - RK260, the printing path only
330
+
331
+ name = serves(self.argv)
332
+ return self.command if name is None else f"{served}{name}"
333
+
334
+ def passing(self, served: str = "") -> str:
335
+ """The arguments the served spelling moved out of the command, or ``""`` (RK488).
336
+
337
+ A flag is not a word over that transport: `repair --dry-run` is the `repair` tool
338
+ carrying `dry_run`, so :meth:`named` drops the flag and this is where it goes. Spelled
339
+ as the dests, which is what a caller passes and what the tool's own schema names.
340
+
341
+ The flags and not the positionals. `explain <code>` reaches its tool as `code` too,
342
+ and a placeholder is not a dest — `delivered <x>` would read as *pass x* where the
343
+ field is `block` — so what cannot be derived is left to the purpose beside it rather
344
+ than guessed, which is :func:`_substitute`'s rule about a blank one layer up.
345
+ """
346
+ if not served or self.foreign:
347
+ return ""
348
+ from .serving import TOOLS, dest_of, serves # noqa: PLC0415 - RK260, printing only
349
+
350
+ name = serves(self.argv)
351
+ if name is None:
352
+ return "" # a shell line, where the argv already shows them
353
+ # The tool's own command, because a dest is declared per subcommand and two of them
354
+ # cross: `--marker` sets `status` on `add` and `--status` sets `marker` on `resume`.
355
+ command = next(one for one in TOOLS if one.name == name).command
356
+ return ", ".join(dest_of(word, command) for word in self.argv if word.startswith("--"))
357
+
358
+ def mention(self, served: str = "", *, quote: str = "") -> str:
359
+ """This door as a **sentence** names it: the spelling, and the fields it carries.
360
+
361
+ :meth:`named` with the values filled in, for prose rather than for a table — the form
362
+ `serving` rewrites a printed backtick into (RK449) and the head of :meth:`spoken`.
363
+ Falls back to :meth:`named` and never straight to the shell, so one door cannot answer
364
+ *tool* to a table and *shell* to a sentence in the same message.
365
+
366
+ ``quote`` wraps the **command** and not the fields it carries, which is the one thing a
367
+ caller cannot add afterwards: `` `tool` with anchor: RK1 `` reads as one call and a
368
+ backtick around the whole of it reads as one command line to paste.
369
+ """
370
+ call = self.call() if served else None
371
+ if call is None:
372
+ return f"{quote}{self.named(served)}{quote}"
373
+ name, fields = call
374
+ named = " ".join(f"{key}: {value}" for key, value in fields.items())
375
+ return f"{quote}{served}{name}{quote}" + (f" with {named}" if named else "")
376
+
377
+ def spoken(self, served: str = "") -> str:
378
+ """This door in the spelling ``served`` has, falling back to the shell one (RK478).
379
+
380
+ The sentence form of :meth:`call`, for the surfaces that print a door instead of
381
+ publishing it: `payload` hands a consumer both and lets it pick, and a message an
382
+ agent reads has room for exactly one. Nothing new is decided here — a door with no
383
+ call, which is `lint --fix` and every foreign one, is a shell command wherever it is
384
+ shown, because that is what it is.
385
+ """
386
+ return f"{self.mention(served)} — {self.what}"
387
+
388
+ def __str__(self) -> str:
389
+ return f"{self.command} — {self.what}"
390
+
391
+
392
+ def offered(doors: Sequence[Door], served: str = "", indent: str = " ") -> list[str]:
393
+ """A table of doors, each in this session's spelling, padded to the widest (RK488).
394
+
395
+ The one renderer for *here are the commands*, and the reason it is a function rather than
396
+ six copies of a `max(len(...))`: every surface that offers a table used to compose the
397
+ served branch and the shell branch itself, so a module that never learned to ask printed
398
+ the shell form to a session holding the tools — which RK444, RK447, RK448, RK475, RK477
399
+ and RK479 each fixed at one more site, none of them able to say how many were left.
400
+
401
+ The **width is per rendering**, not per table: a tool name is longer than a verb, so a
402
+ column measured on the shell spelling and printed in the served one is a column that does
403
+ not line up. That is the whole reason a caller cannot pad these itself and hand them over.
404
+
405
+ :meth:`Door.passing` is appended where the served name dropped arguments, because a tool
406
+ row that named neither the flags nor the fields is the shell row's information without its
407
+ precision. Empty on the shell spelling, where the argv already shows them.
408
+ """
409
+ rows = [(door.named(served), door.passing(served), door.what) for door in doors]
410
+ width = max((len(name) for name, _, _ in rows), default=0)
411
+ return [
412
+ f"{indent}{name:<{width}} {what}" + (f" — pass {fields}" if fields else "")
413
+ for name, fields, what in rows
414
+ ]
415
+
416
+
417
+ def alongside(doors: Sequence[Door], served: str = "") -> tuple[str, ...]:
418
+ """Several doors in one **sentence**, with the engine named once (RK488).
419
+
420
+ :func:`offered` is the table and this is the prose beside it, holding the one rule both
421
+ surfaces that write such a sentence had found for themselves: a served name is
422
+ self-contained, so each carries its prefix, while a shell line repeats the invocation per
423
+ verb — three times inside a notice whose whole budget is 260 characters. So the engine
424
+ leads and the rest are the argv alone, which is how a reader writes the second command of
425
+ a pair anyway.
426
+
427
+ What it does **not** decide is the sentence around them. A served spelling drops the
428
+ arguments a shell spelling shows, so the two say different things about what a verb takes,
429
+ and that difference is prose the author writes — this owns which spelling, and never which
430
+ words.
431
+ """
432
+ spelled = [door.named(served) for door in doors]
433
+ if served:
434
+ return tuple(spelled)
435
+ return (*spelled[:1], *(" ".join(door.argv) for door in doors[1:]))
436
+
437
+
438
+ @dataclass(frozen=True, slots=True)
439
+ class Remedy:
440
+ """What closes one finding: a command to run, or a decision to take."""
441
+
442
+ code: str
443
+ kind: str
444
+ doors: tuple[Door, ...]
445
+ #: What has to be chosen between the doors. Non-empty exactly when ``kind`` is
446
+ #: ``decide``, because a single door has nothing to decide between.
447
+ decision: str = ""
448
+ #: Whether several doors are **ordered** rather than alternative (RK1336). Until this
449
+ #: existed, more than one door meant one thing — a choice — and a row whose doors are
450
+ #: steps had nowhere to say so: `budget.session` needs the read that ranks the
451
+ #: descriptions before the read that prices the whole, and neither is an alternative to
452
+ #: the other. Named rather than inferred from the count, because a rule that spelled
453
+ #: *choose one of these* and *do these in turn* the same way would hide the difference
454
+ #: the reader most needs — which is the argument the doors table already makes about
455
+ #: naming why a site is not executed instead of writing "no".
456
+ sequence: bool = False
457
+
458
+ @property
459
+ def door(self) -> Door | None:
460
+ """The one door, where there is one. ``None`` on a ``decide``."""
461
+ return self.doors[0] if len(self.doors) == 1 else None
462
+
463
+ @property
464
+ def runnable(self) -> bool:
465
+ """Whether `repair` may execute this without asking anybody anything (RK422).
466
+
467
+ ``read`` is deliberately not runnable. Its command is safe to run and useless to
468
+ run *here*: it answers a question for the caller, and executing it inside a repair
469
+ loop would leave the finding exactly where it was.
470
+
471
+ **Still the kind, and RK1015 measured why.** That task proposed reading
472
+ :attr:`Door.writes` instead — the door now carries it, which is what a caller outside
473
+ this process needed — and the substitution does not hold: `section.too-long` closes
474
+ with `section amend <id> --body -`, a door that writes, is complete and is one, and a
475
+ repair loop running it would read a paragraph off a stdin it does not have. What the
476
+ kind carries and no door field does is *who supplies the prose*, so `compose` is a
477
+ word about the author and not about the command.
478
+ """
479
+ return self.kind in ("fix", "run") and all(d.complete for d in self.doors)
480
+
481
+ def payload(self, served: str = "") -> dict[str, object]:
482
+ """The `--json` form: argv as a list, because a consumer runs it rather than reads it.
483
+
484
+ ``served`` is the prefix this session's tools arrive under, and where it is given each
485
+ door carries its **call** beside its argv (RK449): the same door, named as the surface
486
+ the caller is already on. Passed in rather than read here for the reason `Notice` and
487
+ `Refusal` take theirs — which engine answers is a fact about the project, and this
488
+ module reads no project. Absent, or where nothing serves the door, only the argv is
489
+ published, which is what every consumer written before this already reads.
490
+ """
491
+ return {
492
+ "kind": self.kind,
493
+ "decision": self.decision,
494
+ # Both registers say which kind of several these are (RK1336): a consumer looking
495
+ # at two doors and a blank decision would otherwise have to guess whether to offer
496
+ # a choice or a sequence, which is the guess the stated register no longer makes.
497
+ "sequence": self.sequence,
498
+ "doors": [door.payload(served) for door in self.doors],
499
+ }
500
+
501
+ def spoken(self, served: str = "") -> str:
502
+ """The same text :meth:`__str__` renders, in the spelling this session has (RK478)."""
503
+ if self.kind == "decide":
504
+ return f"{self.decision}\n" + "\n".join(
505
+ f" {door.spoken(served)}" for door in self.doors
506
+ )
507
+ if self.sequence:
508
+ # Every door and not the first (RK1336): a row carrying more than one names a
509
+ # sequence, and printing the head of it silently drops the step that says what to
510
+ # do with what the first one shows. `decide` already rendered its several because
511
+ # choosing between them is its whole content — this is the same rendering for a
512
+ # row whose several are ordered rather than alternative.
513
+ return "\n ".join(door.spoken(served) for door in self.doors)
514
+ return self.doors[0].spoken(served)
515
+
516
+ def __str__(self) -> str:
517
+ return self.spoken()
518
+
519
+
520
+ @dataclass(frozen=True, slots=True)
521
+ class _Rule:
522
+ """One row of the table: how to close this code, before the finding fills it in."""
523
+
524
+ kind: str
525
+ #: ``(argv template, what)``. Every ``{}`` field is substituted from the finding.
526
+ doors: tuple[tuple[tuple[str, ...], str], ...]
527
+ decision: str = ""
528
+ #: A rule that reads the config instead of the table — the two cases L6 makes
529
+ #: per-project. Named, so the totality test can see it is deliberate.
530
+ varies: str = ""
531
+ #: What *produces* the defect, for `explain` (RK423). Required on a ``fix`` row and
532
+ #: absent everywhere else, which is not an oversight but the rule: a `run`, `compose`
533
+ #: or `decide` door already states the defect in order to say what choosing it means,
534
+ #: and a second sentence saying the same thing is the drift this package exists to
535
+ #: stop. A ``fix`` door cannot — its `what` describes the *repair* — so the cause is
536
+ #: written there and only there. `tests/test_remedying.py` holds both directions.
537
+ cause: str = ""
538
+ #: Whether several doors are ordered rather than alternative (RK1336). See
539
+ #: :attr:`Remedy.sequence`, which this fills in.
540
+ sequence: bool = False
541
+ #: Whether this row's doors name another tool's command (RK451). On the row and not on
542
+ #: each door, because it is a property of the *kind*: `restore` is the one that leaves
543
+ #: this tool's vocabulary, and a door-by-door flag would let a row be half foreign.
544
+ foreign: bool = False
545
+
546
+
547
+ def _fix(cause: str, what: str) -> _Rule:
548
+ return _Rule("fix", ((("lint", "--fix"), what),), cause=cause)
549
+
550
+
551
+ def _run(argv: tuple[str, ...], what: str) -> _Rule:
552
+ return _Rule("run", ((argv, what),))
553
+
554
+
555
+ def _restore(argv: tuple[str, ...], what: str) -> _Rule:
556
+ """One command **another tool** owns, for a finding no verb here can close (RK451).
557
+
558
+ The one kind whose door is not a roadkeep argv. A governed file whose content a crash
559
+ took is not malformed and cannot be repaired: there is nothing left to render from. What
560
+ closes it is the store, and the store is the repository (L2) — so the command is git's,
561
+ marked :attr:`Door.foreign` so nothing prefixes it with this engine, offers it as a tool
562
+ call or hands it to `repair`.
563
+ """
564
+ return _Rule("restore", ((argv, what),), foreign=True)
565
+
566
+
567
+ def _read(argv: tuple[str, ...], what: str) -> _Rule:
568
+ """One command that answers the finding and writes nothing. See :data:`KINDS`."""
569
+ return _Rule("read", ((argv, what),))
570
+
571
+
572
+ def _reads(*steps: tuple[tuple[str, ...], str]) -> _Rule:
573
+ """Two or more reads that answer one finding, in the order the work goes (RK1336).
574
+
575
+ :func:`_read`'s plural, and the reason it exists rather than a second single door: a
576
+ finding whose remedy is *pick something and cut it* needs the read that ranks the
577
+ candidates before the read that prices the whole, and one door can only be one of those.
578
+ The sequence is the claim, as it already is for a `run` row — a second step is not an
579
+ alternative to the first.
580
+ """
581
+ return _Rule("read", steps, sequence=True)
582
+
583
+
584
+ def _compose(argv: tuple[str, ...], what: str) -> _Rule:
585
+ return _Rule("compose", ((argv, what),))
586
+
587
+
588
+ def _varies_on_queue(cause: str, what: str) -> _Rule:
589
+ """A dead queue entry: mechanical where the section holds the order, `migrate` where the
590
+ config still does (RK427). `--fix` reads the roadmap and only the roadmap, so on a project
591
+ that never migrated it repairs nothing and the caller is left holding a finding whose
592
+ named door does not open that file."""
593
+ return _Rule("fix", ((("lint", "--fix"), what),), varies="queue", cause=cause)
594
+
595
+
596
+ def _decide(decision: str, *doors: tuple[tuple[str, ...], str]) -> _Rule:
597
+ return _Rule("decide", tuple(doors), decision)
598
+
599
+
600
+ #: Every code the package can emit, and what closes it. The domain is asserted total in
601
+ #: `tests/test_remedying.py` against the codes scraped from `linting` and `schema` — a code
602
+ #: added without a row here fails the suite (RK421).
603
+ #:
604
+ #: `{id}` is the finding's subject: a task id on most codes, and on the rest whatever the
605
+ #: emission site put in that slot — a block label, a section anchor, a queue token. `{line}`
606
+ #: is the line it was read at, and `{label}` is the block **inside** a queue token, for the
607
+ #: one door that takes `--block` rather than the token itself (RK435). Those three and no
608
+ #: others: `{first}` and `{role}` were named here for years and substituted nowhere, so a
609
+ #: door using either would have rendered its own braces — which the suite now refuses.
610
+ _TABLE: Mapping[str, _Rule] = {
611
+ # ------------------------------------------------------------------ the character pass
612
+ # RK126's repair: not a re-render, and the one that reaches a line no parse touches.
613
+ "char.bom": _fix(
614
+ "a byte-order mark at the start of the file: not text, and a byte the round-trip "
615
+ "compares, so the file stops matching what the schema renders",
616
+ "the mark is deleted, and no other byte moves",
617
+ ),
618
+ "char.tab": _fix(
619
+ "a tab past the indentation, where this format separates fields with a space — so "
620
+ "the grammar reads the separator as part of the field beside it",
621
+ "the tab becomes the one space this format writes",
622
+ ),
623
+ "char.space": _fix(
624
+ "a codepoint that renders as a space and is not one, so the grammar reads a word "
625
+ "where a separator was meant and the line parses as something else",
626
+ "the codepoint is replaced by an ordinary space",
627
+ ),
628
+ "char.invisible": _fix(
629
+ "a codepoint invisible in an editor — a zero-width space, a variation selector, a "
630
+ "control character — so every other diagnosis of the line names a consequence",
631
+ "the codepoint is deleted wherever it sits, inside a line no parse reaches",
632
+ ),
633
+ # Not the character pass's: it works on the body and puts the ending back exactly as it
634
+ # was read, deliberately, so a fixer for this would be the pass that joins the file.
635
+ "char.mixed-endings": _compose(
636
+ ("lint",),
637
+ "no verb writes an ending: normalize the file with git's own `text` attribute, "
638
+ "then re-run the gate",
639
+ ),
640
+ # ------------------------------------------------------------------------ derived data
641
+ "deps.stale": _fix(
642
+ "the `(deps: …)` annotation caches another line's status and that line moved: "
643
+ "derived data written once and read as current",
644
+ "the annotation is recomputed from the files it caches",
645
+ ),
646
+ "deps.duplicate": _fix(
647
+ "one dep stated twice in a field where an entry is an address, usually a merge "
648
+ "that resolved into both sides' tokens",
649
+ "the repeated dep is dropped and the order is re-derived",
650
+ ),
651
+ "deps.marker": _fix(
652
+ "a dep carrying a marker the annotation does not derive, so the line states a "
653
+ "status the files do not agree with",
654
+ "the annotation is derived, so the marker it caches is rewritten",
655
+ ),
656
+ "ref.mismatch": _Rule(
657
+ "fix",
658
+ ((("lint", "--fix"), "the pointer is derived from the id, so it is recomputed"),),
659
+ varies="ref_scheme",
660
+ cause=(
661
+ "the pointer names an anchor other than the one the scheme derives, so the "
662
+ "line addresses a section chosen by hand"
663
+ ),
664
+ ),
665
+ "line.non-canonical": _fix(
666
+ "the line parses, and rendering the task back produces different bytes: a field "
667
+ "spelled by hand where the schema has one spelling for it",
668
+ "the line is re-rendered from the task the parser read out of it",
669
+ ),
670
+ # --------------------------------------------------------------------- the three lists
671
+ "priority.shipped": _varies_on_queue(
672
+ "the queue names work that has shipped: every token in an order names work, and "
673
+ "work leaves — the one list a departure does not reach",
674
+ "the entry is dropped, named in the report and never in silence",
675
+ ),
676
+ "priority.retired": _varies_on_queue(
677
+ "the queue names work that was retired, which is the same departure by the other "
678
+ "door and leaves the same dead entry",
679
+ "the entry is dropped, named in the report and never in silence",
680
+ ),
681
+ "priority.deferred": _decide(
682
+ "a paused line's place in the order is the one thing the store could not keep, "
683
+ "so restoring it and dropping it are both real answers:",
684
+ (("resume", "{id}"), "the work is coming back, and keeps the place it held"),
685
+ (("priority", "drop", "{id}"), "the order should not name it while it is paused"),
686
+ ),
687
+ "priority.unknown": _decide(
688
+ "an id no file carries is as likely a typo as a deletion, which is why the fixer "
689
+ "leaves it:",
690
+ (("priority", "drop", "{id}"), "the work is gone and the queue outlived it"),
691
+ (("priority", "add", "{id}"), "the token was mistyped — drop it, then add the right one"),
692
+ ),
693
+ "priority.duplicate": _run(
694
+ ("priority", "drop", "{id}"),
695
+ "one of the two entries goes; the queue is re-added at the place you meant",
696
+ ),
697
+ "priority.shape": _compose(
698
+ ("priority", "add", BLANK),
699
+ "the bullet addresses no work: drop it by hand-free re-add — `priority add <id>` "
700
+ "or `priority add 'Block X'`",
701
+ ),
702
+ # ------------------------------------------------------------------ the roadmap's other bullet
703
+ # RK1266, and the rows are RK1265's read across: the two lists are one grammar, so what
704
+ # closes a criterion closes a constraint with the verb's name changed. Missing until now
705
+ # because the scrape could not see a code with a hyphen in its head — the gate reported all
706
+ # four and the suite was green, which is the state a totality test exists to make impossible.
707
+ #
708
+ # `--lead` is not passed on any of them: the lead **is** the address, so the verb takes it
709
+ # as its one positional and the finding supplies it as the subject.
710
+ "non-goal.duplicate": _run(
711
+ ("non-goal", "drop", "{id}"),
712
+ "two bullets lead the same way: the later goes and the first stays, which is where "
713
+ "the reader already found it",
714
+ ),
715
+ # The pair, for the reason `scoping.Unshaped` refuses an amend on one: the render would
716
+ # impose the shape and move the address while doing it.
717
+ "non-goal.shape": _decide(
718
+ "the bullet carries no bold lead, so it has no address this format can write around",
719
+ (
720
+ ("non-goal", "drop", "{id}"),
721
+ "take the bullet out, then `non-goal add --lead … --why …` writes it in the "
722
+ "shape — honest about the lead changing",
723
+ ),
724
+ (
725
+ ("non-goal", "list"),
726
+ "read the list first where the lead as this file reads it is not obvious",
727
+ ),
728
+ ),
729
+ "non-goal.why": _compose(
730
+ ("non-goal", "amend", "{id}", "--why", "-"),
731
+ "past the limit for a constraint's reason; the shorter sentence is yours and arrives "
732
+ "on stdin",
733
+ ),
734
+ "non-goal.lead": _decide(
735
+ "the lead is the address, so shortening it is a different constraint and not an edit",
736
+ (
737
+ ("non-goal", "drop", "{id}"),
738
+ "remove it, then `non-goal add --lead … --why …` with the shorter head",
739
+ ),
740
+ (
741
+ ("non-goal", "list"),
742
+ "read what this project already refuses before rewriting one of it",
743
+ ),
744
+ ),
745
+ # ------------------------------------------------------------------ the roadmap's third list
746
+ # RK1265. The lead is the address, so the three that are about one bullet all reach it by
747
+ # that lead — which the emission site passes as the finding's subject. `--block` is left off
748
+ # every door on purpose: the verb resolves it from the one list carrying the lead, and a
749
+ # remedy that had to spell a block it cannot read would be the blank RK420 exists to remove.
750
+ # The address stopped existing, so the **bare** drop is the door (RK1318): the addressed
751
+ # form takes a `--block` or a `--task` naming exactly what is gone, which would be a
752
+ # command that cannot run. A region the last drop leaves empty carries no lead, and a
753
+ # remedy with a blank subject answers nothing here — that one is `--fix`'s, a heading
754
+ # addressed to nothing with nothing under it being derived dead.
755
+ "criterion.orphan": _run(
756
+ ("criterion", "drop", "{id}"),
757
+ "the list is addressed to a block or an id no file answers, so what it asks about "
758
+ "cannot be finished — the bullets go, and the heading with the last of them",
759
+ ),
760
+ "criterion.duplicate": _run(
761
+ ("criterion", "drop", "{id}"),
762
+ "two bullets in one block lead the same way: the later goes and the first stays, "
763
+ "which is where the reader already found it",
764
+ ),
765
+ # The shape, and the one pair that cannot be a single door: the lead is the address, so a
766
+ # bullet whose head is its first sentence is repaired by removing it and writing one — an
767
+ # `amend` would impose the shape and move the address while doing it.
768
+ "criterion.shape": _decide(
769
+ "the bullet carries no bold lead, so it has no address this format can write around",
770
+ (
771
+ ("criterion", "drop", "{id}"),
772
+ "take the bullet out, then `criterion add --block … --lead … --why …` writes it "
773
+ "in the shape — honest about the lead changing",
774
+ ),
775
+ (
776
+ ("criterion", "list"),
777
+ "read the list first where the lead as this file reads it is not obvious",
778
+ ),
779
+ ),
780
+ "criterion.why": _compose(
781
+ ("criterion", "amend", "{id}", "--why", "-"),
782
+ "past the limit for a criterion's reason; the shorter sentence is yours and arrives "
783
+ "on stdin",
784
+ ),
785
+ # The lead and not the reason, so `amend` is the wrong door: that verb refuses to touch an
786
+ # address, and a shorter lead is a different criterion.
787
+ "criterion.lead": _decide(
788
+ "the lead is the address, so shortening it is a different criterion and not an edit",
789
+ (
790
+ ("criterion", "drop", "{id}"),
791
+ "remove it, then `criterion add --block … --lead … --why …` with the shorter head",
792
+ ),
793
+ (
794
+ ("criterion", "list"),
795
+ "read what the block already claims before rewriting one of it",
796
+ ),
797
+ ),
798
+ "priority.config": _read(
799
+ ("priority", "list"),
800
+ "the section wins over the config: read the queue that is live, then take the "
801
+ "`priority = [...]` line out of roadkeep.toml",
802
+ ),
803
+ # Not a finding of its own — the row the two above become on a project that never
804
+ # migrated (RK427). `--fix` reads the roadmap's section, so on a config-declared queue
805
+ # it repairs nothing and the caller is left with a defect the gate names in a file no
806
+ # verb opens. `_varied` swaps this in when `lint` read the order out of the config.
807
+ "priority.unmigrated": _run(
808
+ ("priority", "migrate"),
809
+ "this queue is still roadkeep.toml's, which no verb writes: move it into the "
810
+ "roadmap and every queue verb reaches it",
811
+ ),
812
+ "priority.block": _decide(
813
+ "a block with no open line under it cannot be first, and whether that is a "
814
+ "finished block or one nothing has been added to yet is not the queue's to say:",
815
+ (("priority", "drop", "{id}"), "the block is finished and the order outlived it"),
816
+ (("list", "--block", "{id}"), "read what is under it before deciding"),
817
+ ),
818
+ "priority.block-empty": _run(
819
+ ("priority", "drop", "{id}"),
820
+ "the block holds no open line, so nothing in it can be first",
821
+ ),
822
+ # The coming-back door first, as `priority.deferred`'s is: what the order names is work
823
+ # a decision would restore, so dropping it is the one move that guarantees it never
824
+ # fires. `--block` is deliberately absent from the read — it takes a bare label and the
825
+ # only value this table can substitute is the queue token — and `resume` is absent for
826
+ # the same reason: it takes an id, and which line comes back is what the read answers.
827
+ "priority.block-paused": _decide(
828
+ "every line filed under this block is in the store, so the tier can only fire once "
829
+ "one comes back — and where in the order it sat is what the store did not keep:",
830
+ (
831
+ ("list", "--role", "deferred"),
832
+ "read what is set aside: the address is an id, so `resume <id>` is what makes "
833
+ "this tier fire again",
834
+ ),
835
+ (
836
+ ("priority", "drop", "{id}"),
837
+ "the order should not name a block whose lines are all paused",
838
+ ),
839
+ ),
840
+ # This read *the block was never declared, so the token addresses nothing* —
841
+ # `priority.block`'s condition, printed under the one code that fires only where a
842
+ # heading **does** declare the label (RK435). Three codes share one shape and their
843
+ # remedies were written together; the one that drifted was invisible, because a note
844
+ # still prints and the exit is still 0. A reason contradicting the line above it is
845
+ # worse than none: it is the half a reader trusts.
846
+ #
847
+ # The kind moves with the sentence. A heading before its lines is the order `block add`
848
+ # prescribes — which is why `_dead_block` makes this a note and not a finding — so the
849
+ # entry is *early* rather than dead, and `priority drop` is the one move that guarantees
850
+ # the tier never fires. It is lossy in the bargain: the queue keeps no place to put a
851
+ # token back into, which is the fact `priority.deferred` is a `decide` for. So the drop
852
+ # stays as one of two answers and never as the only one, and the other door is the
853
+ # continuation the prescribed order already started.
854
+ #
855
+ # A `read` was the third candidate and is the one this task may not take: `list --block
856
+ # <label>` does answer here (exit 0, `Block B is empty: …`), but it answers in
857
+ # `Stage`'s words — so the door would print a second classification of the same block
858
+ # beside the gate's, which is the reader RK434 has just finished removing.
859
+ "priority.block-unstarted": _decide(
860
+ "the heading declares the label and no file files a line under it, which is the "
861
+ "order `block add` prescribes — so this entry is early rather than dead, and which "
862
+ "of the two it is only the author knows:",
863
+ (
864
+ ("add", "--block", "{label}", "--symptom", BLANK, "--why", BLANK),
865
+ "the work is still coming: the tier fires on the first line filed under it",
866
+ ),
867
+ (
868
+ ("priority", "drop", "{id}"),
869
+ "the plan moved: the entry goes, and the place it held in the order with it",
870
+ ),
871
+ ),
872
+ # ------------------------------------------------------------------------ the headings
873
+ # RK451: no verb here closes it — the content is gone rather than malformed, and there
874
+ # is nothing left to render from. `--` before the path, because a file named like a flag
875
+ # is a path git would otherwise read as one.
876
+ "file.not-text": _restore(
877
+ ("git", "checkout", "--", "{file}"),
878
+ "the file's content did not reach the disk; the store is the repository, and this "
879
+ "puts back what it last committed",
880
+ ),
881
+ # Varies with the **files**, which is the third thing a row is decided by (RK468). The
882
+ # finding's own sentence has branched on whether the later region is empty since RK425 —
883
+ # the caller's next question is whether their lines survive it — and this row could not
884
+ # ask, so on a droppable one the message said `block drop` and the remedy said `block
885
+ # merge`. `repair` dispatches the remedy, so it ran the verb the sentence above it did
886
+ # not name; both leave a legal file, which is why nothing caught it.
887
+ "block.repeated": _Rule(
888
+ "run",
889
+ ((("block", "merge", "{id}"), "the label's later headings fold into the first, "
890
+ "entries and all"),),
891
+ varies="region",
892
+ ),
893
+ "block.unrecorded": _compose(
894
+ ("block", "add", "{id}", "--title", BLANK),
895
+ "the ledger declares no heading for a block the roadmap plans work under; the "
896
+ "title is yours to write",
897
+ ),
898
+ "block.unorganised": _compose(
899
+ ("block", "add", "{id}", "--title", BLANK, "--organise", "changelog"),
900
+ "the ledger is organised by nothing, so the first heading opens it",
901
+ ),
902
+ "block.missing": _compose(
903
+ ("block", "add", "{id}", "--title", BLANK),
904
+ "the line's block is declared nowhere; declare it, or re-file the line under one "
905
+ "that exists",
906
+ ),
907
+ "block.format": _compose(
908
+ ("block", "add", BLANK, "--title", BLANK),
909
+ "the label is not one this project's heading word can render; re-declare it and "
910
+ "move the lines",
911
+ ),
912
+ "block.emptied": _read(
913
+ ("stats",),
914
+ "the block held open lines and holds none: read the counts before a projection "
915
+ "that names active blocks is republished",
916
+ ),
917
+ "block.reopened": _read(
918
+ ("stats",),
919
+ "the same row, in the other direction",
920
+ ),
921
+ # ------------------------------------------------------------------------------ the ids
922
+ "id.duplicate": _Rule(
923
+ "decide",
924
+ (
925
+ (
926
+ ("record", "drop", "{id}", "--line", "{line}"),
927
+ "one delivery recorded twice — the later entry goes",
928
+ ),
929
+ (
930
+ ("record", "renumber", "{id}", "--line", "{line}"),
931
+ "two deliveries sharing an id — this one gets an address of its own",
932
+ ),
933
+ ),
934
+ "two lines carry one id, and whether that is one thing written twice or two "
935
+ "things colliding is the only thing the tool cannot read off the file:",
936
+ varies="role",
937
+ ),
938
+ "id.reserved": _decide(
939
+ "`reserved_ids` says this address is spoken for and never written as a line, and a "
940
+ "line carries it — so the declaration and the file disagree, and which of them is "
941
+ "right is the author's to say:",
942
+ (
943
+ ("renumber", "{id}"),
944
+ "the reservation stands; the line and its dependents move to an address of "
945
+ "their own",
946
+ ),
947
+ (
948
+ ("next-id",),
949
+ "the reservation is stale; drop the token from `reserved_ids`, and this says "
950
+ "what the deriver answers once it is gone",
951
+ ),
952
+ ),
953
+ "id.format": _run(
954
+ ("renumber", "{id}"),
955
+ "the id does not match this project's shape; renumber moves the line and its "
956
+ "dependents to one that does",
957
+ ),
958
+ # The pair no live project can reach yet (RK1084): neither adopting corpus declares a
959
+ # store, and a departure that stopped between its two writes is what leaves it. No verb
960
+ # takes it — `resume` would place an open line for work the ledger records as gone —
961
+ # so the door is the two reads that say which file is right, and the repair is a
962
+ # decision this tool may not make for somebody's history (L4).
963
+ "id.paused-and-gone": _decide(
964
+ "the ledger records this id as gone and the store still says it is paused; which "
965
+ "of the two is the leftover is a fact about what actually happened:",
966
+ # `{id}` and no longer a blank (RK1340): the walk over `PAIRS` passes the task id as
967
+ # this finding's own, so printing `…` asked the reader to type the one value the tool
968
+ # had just held — on a finding whose whole content is that this id is in two files.
969
+ # And the sentence says what `show` does: it joins a task out of the files holding a
970
+ # piece of it and reports the ledger's, the store's pause appearing in neither
971
+ # register — so *side by side* was a promise the door could not keep.
972
+ (("show", "{id}"), "the entry as the ledger holds it, which is the side claiming the "
973
+ "work is done"),
974
+ (("origin", "{id}"), "which commit wrote each, which is what dates the pair"),
975
+ ),
976
+ # The store's own pair (RK1081). `resume` and not `defer`: the roadmap already says the
977
+ # work is open, which is what a resume produces, so the store entry is the stale half.
978
+ "id.paused-and-open": _run(
979
+ ("resume", "{id}"),
980
+ "the deferred store and the roadmap both carry this id — a pause that stopped "
981
+ "between its two writes, or a resume that did; either way the open line is what "
982
+ "the files should say, so this removes the store's copy and places nothing",
983
+ ),
984
+ "id.two-files": _run(
985
+ ("ship", "{id}"),
986
+ "the ledger already records this id and the roadmap still carries a line for it — "
987
+ "a ship stopped between its two writes, or a partial marker left beside an entry "
988
+ "recording the whole; either way, re-running closes the line and writes no second "
989
+ "entry",
990
+ ),
991
+ # ------------------------------------------------------------------------- the pointers
992
+ "ref.unresolved": _compose(
993
+ ("section", "add", "{id}", "--title", BLANK),
994
+ "the line points at a section that does not exist; the prose arrives on stdin",
995
+ ),
996
+ "ref.ambiguous": _read(
997
+ ("anchors",),
998
+ "one anchor is declared in two places: read which files claim it, then move one "
999
+ "with `section move`",
1000
+ ),
1001
+ "ref.missing": _compose(
1002
+ ("amend", "{id}", "--ref", BLANK),
1003
+ "the scheme cannot derive this pointer, so the anchor is the field you name",
1004
+ ),
1005
+ "ref.format": _compose(
1006
+ ("amend", "{id}", "--ref", BLANK),
1007
+ "the anchor is not an address this project's scheme reads",
1008
+ ),
1009
+ "ref.sigil": _fix(
1010
+ "the pointer carries a sigil the renderer writes, so the field holds a character "
1011
+ "the schema would add again",
1012
+ "the sigil is derived, so the pointer is re-rendered without it",
1013
+ ),
1014
+ # ------------------------------------------------------------------------- the sections
1015
+ # Varies with the file for `block.repeated`'s reason, one code over (RK472): the drop
1016
+ # this names refuses while a **nested** section is claimed by an open line, so on Turing
1017
+ # it was dispatched and refused on every `repair`, forever. `runnable` asks whether the
1018
+ # argv's fields are filled and never whether the command would run.
1019
+ "section.stale": _Rule(
1020
+ "run",
1021
+ ((("section", "drop", "{id}"),
1022
+ "the task is in the ledger and `ship` deletes the section, so this survived a "
1023
+ "hand edit"),),
1024
+ varies="nested",
1025
+ ),
1026
+ "section.orphan": _decide(
1027
+ "nothing points at this section, which is either a design that outlived its line "
1028
+ "or a line that was lost:",
1029
+ (("section", "drop", "{id}"), "the work is gone and the rationale went with it"),
1030
+ (("show", "{id}"), "read it first — a lost line is re-filed with `add`, not deleted"),
1031
+ ),
1032
+ # `--to` is **required** on `section move`, and this row omitted it — so the door was a
1033
+ # complete argv the CLI refuses, and `repair` would have dispatched it (RK474). Neither
1034
+ # corpus carries this code, which is why RK473's sweep could not see it and the parser
1035
+ # check could. A `compose` and not a `run`: the free address is the author's to pick, and
1036
+ # naming which one would be this tool choosing where somebody's design lives.
1037
+ # Outline-only as written, and offered under both schemes until RK1337. Reproduced on a
1038
+ # scratch project at `ref_scheme = "id"`: `anchors --next` exits 2 there, having no
1039
+ # numbering to take the next of, and `section move` refuses an id-addressed section by
1040
+ # design — *the address is not this verb's to move*. So the door named a command the verb
1041
+ # it names rejects. `varies` because what closes this genuinely differs by scheme, which
1042
+ # is what that field is for.
1043
+ "section.duplicate": _Rule(
1044
+ "compose",
1045
+ (
1046
+ (
1047
+ ("section", "move", "{id}", "--to", BLANK),
1048
+ "one anchor is at two places in one file; move the later under an address "
1049
+ "of its own, which `anchors --next` names",
1050
+ ),
1051
+ ),
1052
+ varies="ref_scheme",
1053
+ ),
1054
+ "section.ambiguous": _read(
1055
+ ("anchors",),
1056
+ "two files declare the anchor: read both, then give one file a `[refs]` namespace",
1057
+ ),
1058
+ "section.unreachable": _read(
1059
+ ("show", "{id}"),
1060
+ "the task is alive and its design is somewhere else: read both before one becomes "
1061
+ "history",
1062
+ ),
1063
+ "section.unpaired": _read(
1064
+ ("show", "{id}"),
1065
+ "the section was edited and its line was not — `pick` reads only the line, so read "
1066
+ "what moved and put it there with `restate` or `amend`",
1067
+ ),
1068
+ # RK1106. Not a `--fix`: a citation is prose, and repointing it at a different anchor or
1069
+ # rewriting the sentence that argued from it are different edits with different meanings,
1070
+ # which is exactly the statement about the work L4 keeps out of this tool. Two doors and
1071
+ # the read second, because the anchor may never have existed — a typo has no design to go
1072
+ # and read, and `origin` is what tells the two apart (RK212).
1073
+ "ref.dangling": _decide(
1074
+ "this section's prose cites an anchor no prose file declares, and whether the design "
1075
+ "moved or was never there decides which edit it is:",
1076
+ (
1077
+ ("section", "amend", "{id}", "--body", "-"),
1078
+ "the sentence is this section's, so repointing the citation or rewriting the "
1079
+ "argument that leant on it arrives on stdin",
1080
+ ),
1081
+ (
1082
+ ("origin", BLANK),
1083
+ "the cited anchor, if it ever was one: this answers which commit wrote that "
1084
+ "design and which took it, so a sentence can be corrected instead of deleted",
1085
+ ),
1086
+ ),
1087
+ # RK1168. `compose` and one door: the citation is this section's own sentence, and which
1088
+ # address it meant — the local `S:I.2` or the other file's `I.2` — is a claim about the
1089
+ # argument that only its author can make. What the finding supplies is that the two exist;
1090
+ # writing the corrected sentence is the half L4 keeps out of the tool.
1091
+ "ref.crossed": _compose(
1092
+ ("section", "amend", "{id}", "--body", "-"),
1093
+ "the citation resolves into the other prose file while this one declares the same "
1094
+ "address; the sentence naming which it meant arrives on stdin",
1095
+ ),
1096
+ # RK1380. Two doors and a decision, because the sentence is in whichever file cites the law
1097
+ # and the verb follows the file: a design is `section amend`, a ledger entry is `record
1098
+ # amend`, and both take the prose on stdin. Which of the two — and whether the citation was
1099
+ # mistyped or the argument leant on a law this project does not hold — is the author's, so
1100
+ # no `{id}` is substituted here: this finding names a line and not a task.
1101
+ "law.unknown": _decide(
1102
+ "a sentence cites a law the table does not declare, and where it sits decides the "
1103
+ "verb that corrects it:",
1104
+ (
1105
+ ("amend", "{id}", "--why", "-"),
1106
+ "where the citation is in a roadmap line's why, and `restate` where it is in the "
1107
+ "claim, that being what the line is rather than a field on it",
1108
+ ),
1109
+ (
1110
+ ("section", "amend", "{id}", "--body", "-"),
1111
+ "where it is in a design, the corrected sentence arriving on stdin",
1112
+ ),
1113
+ (
1114
+ ("record", "amend", "{id}", "--why", "-"),
1115
+ "where it is in a ledger entry, which is the third prose a law is cited from",
1116
+ ),
1117
+ ),
1118
+ "section.too-long": _compose(
1119
+ ("section", "amend", "{id}", "--body", "-"),
1120
+ "past the word budget; the shorter prose is yours and arrives on stdin",
1121
+ ),
1122
+ # RK492. `compose` and not `run`: the pathspec and the pattern are the author's claim
1123
+ # about what this migration is, and a fixer guessing either would be composing the one
1124
+ # thing L4 forbids — a statement about the work rather than a rendering of one.
1125
+ "body.empty": _compose(
1126
+ ("section", "amend", "{id}", "--body", "-"),
1127
+ "the pointer resolves to a heading with no prose; the rationale is yours and "
1128
+ "arrives on stdin",
1129
+ ),
1130
+ "title.empty": _compose(
1131
+ ("section", "amend", "{id}", "--title", BLANK),
1132
+ "the section is addressed and unnamed; a heading is what a reader sees before the "
1133
+ "prose, and naming it is not the tool's",
1134
+ ),
1135
+ "body.promise": _decide(
1136
+ "the design names an id no line carries, which the deriver reads as spent and the "
1137
+ "next `add` steps past (RK431) — and whether it was an illustration, the id this "
1138
+ "task should have had, work not filed yet, or an address this project reserved "
1139
+ "and will never write as a line is the sentence's meaning, not the tool's:",
1140
+ (
1141
+ ("next-id",),
1142
+ # The door RK1027 found missing. Both rows below assume the id was an error, so
1143
+ # a caller authoring two tasks that cite each other was told to rename or delete
1144
+ # a cross-reference the backlog wanted — the outcome that costs something. The
1145
+ # read and not the `add`, because the ordering is the whole advice: what the
1146
+ # sibling's id will be, filed first, and this section written after.
1147
+ "the id is a sibling not filed yet; this says what it will be — `add` it "
1148
+ "first, and the section then names a line that exists",
1149
+ ),
1150
+ (
1151
+ ("section", "amend", "{id}", "--body", "-"),
1152
+ "it was an example; spell it outside this project's prefix, where nothing "
1153
+ "numbers it",
1154
+ ),
1155
+ (("gaps",), "read where the id went before deciding it was never a line"),
1156
+ (
1157
+ ("lint",),
1158
+ # The fourth reading, and the one the mechanism was built for (RK1047): an id
1159
+ # this project spoke for and will never write as a line. Shio declared four
1160
+ # epics and six retired ranges and went from twelve findings to one — where the
1161
+ # rewording above would have made its non-goals stop naming what they refuse.
1162
+ "the id is reserved: add it to `reserved_ids` in roadkeep.toml, where the "
1163
+ "deriver skips it because it IS taken — then this re-reads clean",
1164
+ ),
1165
+ ),
1166
+ "remaining.format": _compose(
1167
+ ("section", "amend", "{id}", "--body", "-"),
1168
+ "the declared query is not `<pathspec> :: <regex>` per line; the corrected block "
1169
+ "is yours and arrives on stdin",
1170
+ ),
1171
+ # ---------------------------------------------------------------------------- the deps
1172
+ "deps.unknown": _decide(
1173
+ "the dep is in neither file, so nothing can say whether it is done — and a token "
1174
+ "nothing carries is as likely a typo as a deletion:",
1175
+ (("amend", "{id}", "--dep", BLANK), "the dep was mistyped; state the right one"),
1176
+ (("gaps",), "read where the id went before deciding it is gone"),
1177
+ ),
1178
+ "deps.retired": _compose(
1179
+ ("amend", "{id}", "--dep", BLANK),
1180
+ "the dep left without shipping, so the line waits on nothing; restate the deps "
1181
+ "it actually has",
1182
+ ),
1183
+ "deps.block": _read(
1184
+ ("deps", "{id}"),
1185
+ "read what the block dep resolves to — its members, or the standing that says "
1186
+ "nothing is filed under the label — before the line is picked",
1187
+ ),
1188
+ "deps.cycle": _compose(
1189
+ ("amend", "{id}", "--dep", BLANK),
1190
+ "the deps close a loop, so no order starts it; one of them is the edge to cut",
1191
+ ),
1192
+ "deps.collective": _read(
1193
+ ("deps", "{id}"),
1194
+ "one token names many open tasks: read the expansion, which is the whole finding",
1195
+ ),
1196
+ "deps.self": _compose(
1197
+ ("amend", "{id}", "--dep", BLANK),
1198
+ "a line waiting on itself can never start; state the deps it meant",
1199
+ ),
1200
+ "deps.compound": _compose(
1201
+ ("amend", "{id}", "--dep", BLANK),
1202
+ "one token holds several deps; `--dep` is repeatable, so state them one each",
1203
+ ),
1204
+ "deps.format": _compose(
1205
+ ("amend", "{id}", "--dep", BLANK),
1206
+ "the token is not a dep this grammar reads: an id, a `Block X`, a range, or work "
1207
+ "outside the backlog",
1208
+ ),
1209
+ "deps.range": _compose(
1210
+ ("amend", "{id}", "--dep", BLANK),
1211
+ "the range names no line this backlog carries",
1212
+ ),
1213
+ # RK1297. All four are `--requires`, which replaces the whole group, and that is the
1214
+ # honest door even for `requires.unknown` — where the other repair is to declare the word
1215
+ # in `[requirements]`. Naming a config edit here would be this table offering a hand edit
1216
+ # to the one file the guard denies, and the choice between the two is the author's: a
1217
+ # misspelt requirement is a line to correct, and a real one is a vocabulary to widen.
1218
+ "requires.format": _compose(
1219
+ ("amend", "{id}", "--requires", BLANK),
1220
+ "the token is not a requirement this grammar reads: one word, no padding",
1221
+ ),
1222
+ "requires.unrenderable": _compose(
1223
+ ("amend", "{id}", "--requires", BLANK),
1224
+ "the token carries a bracket, a comma or an arrow, so the line it is written into "
1225
+ "stops parsing; a requirement is one word",
1226
+ ),
1227
+ "requires.unknown": _compose(
1228
+ ("amend", "{id}", "--requires", BLANK),
1229
+ "`[requirements] declared` does not name it, so `pick` matches it against nothing "
1230
+ "and the line is offered to nobody — restate it, or declare the word",
1231
+ ),
1232
+ "requires.duplicate": _compose(
1233
+ ("amend", "{id}", "--requires", BLANK),
1234
+ "one requirement stated twice; `--requires` is repeatable, so state each once",
1235
+ ),
1236
+ # RK1229. A `compose`, because what the dep should say instead is the caller's: the
1237
+ # parenthetical they wrote is usually a sentence about *why* the dependency exists, which
1238
+ # belongs in the section the line points at and not inside a rendered group.
1239
+ "deps.unrenderable": _compose(
1240
+ ("amend", "{id}", "--dep", BLANK),
1241
+ "a dep carrying `)` or the pointer arrow stops the line parsing, and then no verb "
1242
+ "reaches it; the parenthetical belongs in the section, not in the dep",
1243
+ ),
1244
+ "deps.unexpected": _run(
1245
+ ("lint", "--fix"),
1246
+ "this file's rules declare no deps field, so the annotation is dropped",
1247
+ ),
1248
+ # --------------------------------------------------------------------- the prose fields
1249
+ # Every one of these is `compose`, and that is L4 rather than a gap: there is no shorter
1250
+ # sentence the tool may write, so the blank is marked and the author fills it.
1251
+ "why.too-long": _compose(
1252
+ ("amend", "{id}", "--why", BLANK),
1253
+ "past the limit; `budget` says how many characters the field has before you write",
1254
+ ),
1255
+ "why.sentences": _compose(
1256
+ ("amend", "{id}", "--why", BLANK),
1257
+ "the why is one sentence — the second belongs in the section the line points at",
1258
+ ),
1259
+ # The six the schema composes from a field name, invisible to the totality read until
1260
+ # RK428 taught it to look. Each is one door away and always was — the reason none had a
1261
+ # row is that nothing ever asked.
1262
+ "why.empty": _compose(
1263
+ ("amend", "{id}", "--why", BLANK),
1264
+ "the field is blank; a line with no why states a problem and no reason for it",
1265
+ ),
1266
+ "symptom.empty": _compose(
1267
+ ("restate", "{id}", "--symptom", BLANK),
1268
+ "the field is blank; the symptom is the falsifiable claim the line *is*",
1269
+ ),
1270
+ # `-` and not a blank: a newline in a one-line field is almost always what a shell put
1271
+ # there, and stdin is the route where nothing expands anything (RK407 is the other half).
1272
+ "why.newline": _compose(
1273
+ ("amend", "{id}", "--why", "-"),
1274
+ "a task is one line; re-send the field on stdin, which no shell rewrites",
1275
+ ),
1276
+ "symptom.newline": _compose(
1277
+ ("restate", "{id}", "--symptom", "-"),
1278
+ "a task is one line; re-send the field on stdin, which no shell rewrites",
1279
+ ),
1280
+ # Mechanical, and the one pair here that is: the trim is refused at the *door* on
1281
+ # purpose — the tool does not silently rewrite text it did not author — but on a line
1282
+ # already in the file `--fix` normalizes it, which is derived data by any other name.
1283
+ "why.whitespace": _fix(
1284
+ "leading or trailing whitespace around the field, which the door refuses rather "
1285
+ "than trimming: nothing here silently rewrites text it did not author",
1286
+ "the field is trimmed where it already sits, and no other byte moves",
1287
+ ),
1288
+ "symptom.whitespace": _fix(
1289
+ "leading or trailing whitespace around the field, which the door refuses rather "
1290
+ "than trimming: nothing here silently rewrites text it did not author",
1291
+ "the field is trimmed where it already sits, and no other byte moves",
1292
+ ),
1293
+ # The character the author did not type (RK407). `compose` and not `fix`: the codepoint
1294
+ # is inside prose, so removing it is a rewrite of somebody's sentence — and the shell
1295
+ # that wrote it will write it again unless the *quoting* changes, which is why the door
1296
+ # is the field's own and the dash is what the remedy actually turns on.
1297
+ "why.control": _compose(
1298
+ ("amend", "{id}", "--why", "-"),
1299
+ "a control character a shell's escape wrote: re-send the field on stdin, where "
1300
+ "nothing expands a backtick",
1301
+ ),
1302
+ "symptom.control": _compose(
1303
+ ("restate", "{id}", "--symptom", "-"),
1304
+ "a control character a shell's escape wrote: re-send the field on stdin, where "
1305
+ "nothing expands a backtick",
1306
+ ),
1307
+ "why.no-terminator": _compose(
1308
+ ("amend", "{id}", "--why", BLANK),
1309
+ "the why ends in a stop; nothing here adds one, because where it goes is the "
1310
+ "sentence's",
1311
+ ),
1312
+ "symptom.too-long": _compose(
1313
+ ("restate", "{id}", "--symptom", BLANK),
1314
+ "past the limit; the symptom is the falsifiable claim, so shortening it is `restate`",
1315
+ ),
1316
+ "symptom.sentence": _compose(
1317
+ ("restate", "{id}", "--symptom", BLANK),
1318
+ "the symptom is a phrase naming what does not work, never a sentence",
1319
+ ),
1320
+ "symptom.markup": _compose(
1321
+ ("restate", "{id}", "--symptom", BLANK),
1322
+ "the symptom carries markup the renderer writes; state the claim alone",
1323
+ ),
1324
+ "line.too-long": _compose(
1325
+ ("amend", "{id}", "--why", BLANK),
1326
+ "the rendered line is past the limit; `budget` prices both fields before you write",
1327
+ ),
1328
+ "part.too-long": _compose(
1329
+ ("record", "amend", "{id}", "--part", BLANK),
1330
+ "the partial's qualifier is past the limit",
1331
+ ),
1332
+ "part.blank": _compose(
1333
+ ("record", "amend", "{id}", "--part", BLANK),
1334
+ "a partial names which half shipped; an empty qualifier names none",
1335
+ ),
1336
+ "part.unexpected": _run(
1337
+ ("ship", "{id}"),
1338
+ "a partial qualifier where the files say the work is whole: the completion "
1339
+ "replaces the entry and drops it",
1340
+ ),
1341
+ # -------------------------------------------------------------------------- the markers
1342
+ # `compose` and not `run`: the marker is a choice from a declared set, so the tool could
1343
+ # list the candidates and still may not pick one — maturity is the author's claim about
1344
+ # the work, which is the same reason `resume` asks for it rather than restoring a default.
1345
+ "status.unknown": _compose(
1346
+ ("status", "{id}", BLANK),
1347
+ "the marker is not one this project declares; `[markers]` in roadkeep.toml lists them",
1348
+ ),
1349
+ "status.shipped": _run(
1350
+ ("ship", "{id}"),
1351
+ "the shipped marker never belongs in the roadmap — `ship` is the transaction that "
1352
+ "moves the line",
1353
+ ),
1354
+ "status.unrepresentable": _fix(
1355
+ "the marker carries a codepoint that is not part of it — a variation selector an "
1356
+ "editor added — so the status matches nothing this project declares",
1357
+ "the codepoint is deleted, which is the whole of what made it unreadable",
1358
+ ),
1359
+ # ---------------------------------------------------------------------------- the files
1360
+ "file.missing": _compose(
1361
+ ("init",),
1362
+ "a declared file is not on disk: scaffold it, or take the entry out of "
1363
+ "`[files]` in roadkeep.toml",
1364
+ ),
1365
+ # `record amend` and never `amend` (RK1203). This finding fires on the **ledger alone** —
1366
+ # `_paths` reads `documents["changelog"]` and nothing else, a roadmap naming an artefact
1367
+ # its task exists to write being the opposite claim — so the door named here was not merely
1368
+ # wrong for one role, it was wrong on every finding this code can produce. `amend` loads
1369
+ # the roadmap, looks the id up in `roadmap.by_id()` and raises `NotOpen` for anything the
1370
+ # ledger holds; it was built to correct an open line and says so. Found adopting Turing,
1371
+ # where T759 names a script that moved to its own repository: the one remedy offered was
1372
+ # the one verb that structurally cannot perform it, and following it spends a call to learn
1373
+ # the door is shut.
1374
+ #
1375
+ # `--lines` is named in the sentence rather than put in the argv, because how many lines an
1376
+ # entry spans is a fact about that entry and not a constant this table could carry — and on
1377
+ # the corpus that found this the entry was 1,600 characters across several of them.
1378
+ "path.missing": _compose(
1379
+ ("record", "amend", "{id}", "--why", BLANK),
1380
+ "a shipped entry names a path the repository no longer has; the path is prose, so "
1381
+ "the correction is the sentence — add `--lines <n>` where the entry wraps",
1382
+ ),
1383
+ "budget.absent": _compose(
1384
+ ("budget",),
1385
+ "a `[budgets]` entry names a file that is not there; read what is budgeted, then "
1386
+ "correct the entry in roadkeep.toml",
1387
+ ),
1388
+ # The read is the door and there is no `--fix` for it (RK1059): what a tool costs is
1389
+ # its own `help=` and its exposed arguments, so the shorter description is the author's
1390
+ # and the only mechanical part is finding which tool grew.
1391
+ # The one finding whose subject is a rule rather than a record (RK1068), so the door is
1392
+ # the read that shows what the rule produces — and the edit is a config line, which no
1393
+ # verb of this tool writes: `[grammar.<role>]` is the author's declaration (L6).
1394
+ "grammar.unreadable": _compose(
1395
+ ("show", BLANK),
1396
+ "a declared grammar cannot read back what it writes; read any one line, compare it "
1397
+ "with the rendering the report carries, then correct `[grammar.<role>]` — the id is "
1398
+ "the author's because every line in the file is equally evidence",
1399
+ ),
1400
+ # A note and not a finding, so the door is a read and there is nothing to repair: the
1401
+ # ceiling held (RK1105). What it reports is that the declared number was measured on a
1402
+ # working tree and this count is the commit's, so the file has room its author never
1403
+ # voted for — and bringing a ceiling down is an argument about what may be loaded every
1404
+ # turn, which is the one edit in `roadkeep.toml` no verb of this tool makes for you.
1405
+ "budget.translated": _read(
1406
+ ("budget", "--file", "{id}"),
1407
+ "the counted bytes are the commit's and this checkout pays more; this prints both "
1408
+ "beside the ceiling, and lowering it is a line in roadkeep.toml",
1409
+ ),
1410
+ # RK1288. `{id}` is the line the ranking could not measure, and the door is the read that
1411
+ # tries it alone: the whole answer is what refused it, which that call prints beside the
1412
+ # ranking rather than as one row inside a report about eight other things.
1413
+ "read.unpriced": _read(
1414
+ ("cost", "--brief", "{id}"),
1415
+ "the ranking could not compose this brief, so the widest is unaccounted for; this "
1416
+ "asks for that one and prints what refused it",
1417
+ ),
1418
+ # RK1287. A note and not a defect: the gate priced what a session is about to brief and
1419
+ # says how many it left out, which is `deps.collective`'s shape — the door is the read
1420
+ # that answers the whole question, and there is nothing here to repair.
1421
+ "read.priced": _read(
1422
+ ("cost", "--brief"),
1423
+ "the gate prices the briefs `pick` offers next, so a backlog's length never reaches "
1424
+ "it; this ranks every open line and names what each costs",
1425
+ ),
1426
+ # RK1286. `{id}` is the task whose brief is over, which this finding carries as its
1427
+ # subject: the ranking answers *which one*, and the finding already said that — what the
1428
+ # reader needs next is what that one brief costs and where the size went.
1429
+ "read.over": _read(
1430
+ ("cost", "--brief", "{id}"),
1431
+ "this is the read that replaces reading the file, so one that does not fit a tool "
1432
+ "result is a task a session opens the roadmap for; what closes it is a shorter "
1433
+ "design, a narrower field, or a ceiling re-argued in `roadkeep.toml`",
1434
+ ),
1435
+ # Two reads and the ranking first (RK1336). The finding says no single tool is at fault,
1436
+ # then had to send the reader somewhere no tool was named at all — when what they do next
1437
+ # is pick one. Measured on this corpus: the ceiling has been re-argued six times and a
1438
+ # served flag withdrawn once, and a whole verb never, so the ranking is not the detour the
1439
+ # single door assumed. It could not have been offered before RK1335, which is what taught
1440
+ # `--tools` to carry this ceiling rather than only the per-tool one.
1441
+ "budget.session": _reads(
1442
+ (
1443
+ ("cost", "--tools"),
1444
+ "the whole served surface is past what `[tools] session` allows and no single "
1445
+ "tool is; this ranks every description against that ceiling and prints the room "
1446
+ "each has, which is what picking one to cut needs",
1447
+ ),
1448
+ (
1449
+ ("cost", "--session"),
1450
+ "and this prices the surface beside what the resident files cost each turn, "
1451
+ "which is what decides whether it is the surface to cut at all; what closes it "
1452
+ "is descriptions shortened or a ceiling re-argued in `roadkeep.toml`",
1453
+ ),
1454
+ ),
1455
+ # `{id}` is the tool, which this finding carries as its subject (RK1236). The ranking over
1456
+ # every tool answers *which one is over* and the finding already said that; what the reader
1457
+ # needs next is which of this tool's fields spent the bytes, and the file it is written in.
1458
+ "budget.tool": _read(
1459
+ ("cost", "--tools", "{id}"),
1460
+ "one served tool is past what `[tools] characters` allows; this ranks that tool's "
1461
+ "own fields and names the module each is written in",
1462
+ ),
1463
+ # `--readme` is the row and the *target's* flag is what `_varied` swaps in (RK1110). With a
1464
+ # third projection the literal became a remedy contradicting the message above it — the
1465
+ # finding named `export --contents` and the door under it said `--readme` — which is the
1466
+ # worse half of the two, being the one a reader trusts. Varied rather than templated,
1467
+ # because `{id}` means a task id everywhere else and a row spelling `--{id}` renders
1468
+ # `export --RK1` under the sweep that holds every door runnable.
1469
+ "export.stale": _Rule(
1470
+ "run",
1471
+ (
1472
+ (
1473
+ ("export", "--readme"),
1474
+ "every character between the markers is derived, so it is rewritten and "
1475
+ "never edited",
1476
+ ),
1477
+ ),
1478
+ varies="target",
1479
+ ),
1480
+ "export.unmarked": _run(
1481
+ ("export", "--readme"),
1482
+ "the target carries no roadkeep markers, so nothing there is governed yet",
1483
+ ),
1484
+ # A `run` and not a `read`, which is the whole point of putting this at the gate (RK1192):
1485
+ # `install --check` reported it and nobody ran that, so the finding names the command that
1486
+ # closes it and `repair` closes it. The plain verb, because the surfaces are written
1487
+ # together or not at all and the variant is read off the disk rather than off a flag.
1488
+ "install.stale": _run(
1489
+ ("install",),
1490
+ "the wired launcher, hook and skill are rewritten from the checkout answering here; "
1491
+ "`[install] pinned` in roadkeep.toml is how a project that chose this version says so",
1492
+ ),
1493
+ # A `compose` and not a `fix` (RK1222): what the pattern under that directory should be is
1494
+ # the author's — which files a migration is about is the claim the query makes, and `**/*`
1495
+ # is this tool guessing at it. The suffix is the part only they know.
1496
+ "remaining.unmatched": _compose(
1497
+ ("section", "amend", "{id}", "--body", "-"),
1498
+ "the clause names a directory where `Path.glob` wants a pattern, so it reads no file "
1499
+ "at all; `<that path>/**/*` is the shape, and which files it should reach is yours",
1500
+ ),
1501
+ # A `decide` and not a `run` (RK1228): whether the work this change carries *is* the task
1502
+ # is the one judgement nothing here can make — a path a section names changes for a
1503
+ # rename, a neighbouring fix, a refactor that crossed it. So the two readings are named
1504
+ # and the caller picks, which is why this is a note and not a finding in the first place.
1505
+ "task.worked": _decide(
1506
+ "source under this open task moved and the line did not, which is either the work "
1507
+ "landing or a path it merely names changing:",
1508
+ (("ship", "{id}", "--why", BLANK), "this is what landed, and the entry is owed"),
1509
+ (("show", "{id}"), "read what the section claims before deciding it was that"),
1510
+ ),
1511
+ # The same judgement one level up (RK1234), so the same shape — but the first reading is
1512
+ # no longer `ship` on a line: a whole block whose every line moved is either work that
1513
+ # landed under all of them, or one commit that crossed the area they all name.
1514
+ "block.worked": _decide(
1515
+ "source under every open line of this block moved and none of them shipped, which is "
1516
+ "either a block finished and not closed or one change crossing what they all name:",
1517
+ (("list", "--block", "{id}"), "read the lines this is about before shipping any"),
1518
+ (("unclosed",), "which of them commits already name, which is the other half"),
1519
+ ),
1520
+ # RK1238. `engines` and not `/plugin update`: which copy is right is a decision about a
1521
+ # setup this tool can read and never make, and the one command that names all three is
1522
+ # the whole of what a reader needs before taking it.
1523
+ "gate.behind": _read(
1524
+ ("engines",),
1525
+ "the copy that judged this tree is older than the one `[install] pinned` names, so "
1526
+ "a clean verdict here is that copy's; this reads all three and says which answered",
1527
+ ),
1528
+ "engine.disagreement": _read(
1529
+ ("engines",),
1530
+ "three copies of this tool can be in play and they may differ; this reads all "
1531
+ "three and names which one refused",
1532
+ ),
1533
+ # ------------------------------------------------------------------- the unreadable line
1534
+ # The one row that names no verb reaching it, and says so. Every write above starts from
1535
+ # a parsed line, and there is no parse here — so the honest answer is the two things that
1536
+ # *can* be tried and the statement that neither is guaranteed.
1537
+ "line.unparsed": _decide(
1538
+ "the grammar could not read this line at all, so no verb starting from a task "
1539
+ "reaches it; a control character is the one cause with a repair:",
1540
+ (("lint", "--fix"), "a codepoint that is not text can be the whole reason"),
1541
+ (("audit",), "read every marker-bearing line the count missed, and why"),
1542
+ ),
1543
+ }
1544
+
1545
+ #: What each varying row reads, spelled for a reader rather than as a field name: one is a
1546
+ #: key in `roadkeep.toml` and the other is not a setting at all (RK423).
1547
+ _VARIES_READS = {
1548
+ "ref_scheme": "with `ref_scheme` in roadkeep.toml",
1549
+ "role": "with which governed file it is reported about",
1550
+ "region": "with whether the label's later region holds anything",
1551
+ "nested": "with whether an open line claims a section nested under this one",
1552
+ }
1553
+
1554
+ #: The codes whose row is decided per project rather than per code (L6), and what each
1555
+ #: reads. **Derived** from the table rather than restated beside it: a second list of the
1556
+ #: same two names is the drift this package exists to stop, one layer down.
1557
+ VARIES: Mapping[str, str] = {
1558
+ code: rule.varies for code, rule in _TABLE.items() if rule.varies
1559
+ }
1560
+
1561
+
1562
+ def codes() -> tuple[str, ...]:
1563
+ """Every code this table answers, sorted — the vocabulary `explain` lists (RK423)."""
1564
+ return tuple(sorted(_TABLE))
1565
+
1566
+
1567
+ @dataclass(frozen=True, slots=True)
1568
+ class Explained:
1569
+ """One code as a class rather than as an occurrence (RK423).
1570
+
1571
+ A finding is about one line; a code is about a kind of defect, and until this there was
1572
+ nowhere to look the second one up — so a caller meeting `section.unpaired` for the first
1573
+ time grepped the package and reconstructed from an implementer's docstring what one
1574
+ screen would have said.
1575
+
1576
+ Three fields and no more. The worked example is the argv the finding already carries,
1577
+ and a page long enough to scroll is a page an agent pays for in context to learn what it
1578
+ could have run.
1579
+ """
1580
+
1581
+ code: str
1582
+ kind: str
1583
+ #: What produces this defect. Read off the ``fix`` row where it is written and off the
1584
+ #: doors otherwise, so the explanation and the remedy cannot drift the way a README and
1585
+ #: a checker do — there is only ever one sentence, in one place.
1586
+ cause: str
1587
+ remedy: Remedy
1588
+ #: What changes the answer on this row, where anything does (L6). Empty otherwise.
1589
+ varies: str = ""
1590
+
1591
+ def __str__(self) -> str:
1592
+ lines = [f"{self.code} [{self.kind}]", f" cause {self.cause}"]
1593
+ for door in self.remedy.doors:
1594
+ # The command, and its `what` only where that is not the cause already printed:
1595
+ # on a single-door row the two are the same sentence by :func:`_cause`, and
1596
+ # repeating it spends two thirds of the one screen this answers on restatement.
1597
+ # Never suppressed on a `decide`, where the `what` is not a description of the
1598
+ # defect at all — it is what distinguishes this door from the other one, which
1599
+ # is the entire content of the decision.
1600
+ lines.append(f" remedy {door.command if door.what == self.cause else door}")
1601
+ if self.varies:
1602
+ lines.append(f" varies {_VARIES_READS[self.varies]}")
1603
+ return "\n".join(lines)
1604
+
1605
+ def payload(self, served: str = "") -> dict[str, object]:
1606
+ return {
1607
+ "code": self.code,
1608
+ "kind": self.kind,
1609
+ "cause": self.cause,
1610
+ "varies": self.varies or None,
1611
+ **self.remedy.payload(served),
1612
+ }
1613
+
1614
+
1615
+ def explain(code: str, config: Config | None = None) -> Explained | None:
1616
+ """The class behind one code. ``None`` for a code this tool cannot report."""
1617
+ rule = _TABLE.get(code)
1618
+ if rule is None:
1619
+ return None
1620
+ # A finding with no line and no subject: the templates render their blanks, which is
1621
+ # right here — an explanation is about the class, and a substituted id would be one
1622
+ # occurrence's, presented as if it were the rule's.
1623
+ found = remedy(_Class(code), config)
1624
+ assert found is not None # `rule` is not None, so neither is this
1625
+ return Explained(code, found.kind, _cause(rule, found), found, rule.varies)
1626
+
1627
+
1628
+ def _cause(rule: _Rule, found: Remedy) -> str:
1629
+ """Where the cause is written for this kind. One sentence, never two.
1630
+
1631
+ A ``fix`` row states it outright, because its door describes the repair. Every other
1632
+ kind already had to say what the defect is in order to say what choosing a door means —
1633
+ so that sentence is the cause, and writing a second one beside it is the drift this
1634
+ package exists to stop, one layer down.
1635
+ """
1636
+ if rule.cause:
1637
+ return rule.cause
1638
+ return found.decision or found.doors[0].what
1639
+
1640
+
1641
+ @dataclass(frozen=True, slots=True)
1642
+ class _Class:
1643
+ """A finding about no line: what an explanation of the class is derived from."""
1644
+
1645
+ code: str
1646
+ file: str = ""
1647
+ id: str = ""
1648
+ subject: str = ""
1649
+ lineno: int | None = None
1650
+
1651
+
1652
+ #: Every name a row may write between braces, and the whole of what a door can be told about
1653
+ #: the finding it closes (RK490). **Declared**, rather than being whatever :func:`_values`
1654
+ #: happens to compute: `{first}` and `{role}` sat named in this table for years and
1655
+ #: substituted nowhere, so those doors rendered their own braces — a command line no shell
1656
+ #: repairs (RK435) — and nothing anywhere could say so. `tests/test_remedying.py` holds both
1657
+ #: directions: every `{name}` the source writes is one of these, and every one of these is a
1658
+ #: key :func:`_values` answers.
1659
+ FIELDS = ("id", "line", "label", "file", "role")
1660
+
1661
+
1662
+ def _values(finding: object, config: Config | None) -> dict[str, str]:
1663
+ """What this finding tells a door about itself, by the names a row uses (RK490).
1664
+
1665
+ The one place any of them is derived. Three rows' worth of defects — RK468, RK470, RK472
1666
+ — were each a row repeating what the finding already knew instead of reading it, and each
1667
+ was found by example because there was nowhere for the agreement to be checked. Computed
1668
+ here, per finding and once, the table states only what is genuinely per-code and the
1669
+ agreement is a property over the whole of it.
1670
+
1671
+ Read by ``getattr`` on purpose: this takes a :class:`~roadkeep.linting.Finding`, a
1672
+ :class:`~roadkeep.linting.Note`, a :class:`~roadkeep.kernel.schema.Violation` wrapped in one, or
1673
+ the :class:`_Class` an explanation is composed from — the caller repairing a line does
1674
+ not care which of the four reported it, and neither does a door.
1675
+
1676
+ ``id`` is the finding's **own** :attr:`~roadkeep.linting.Finding.token`, which already
1677
+ means *what a remedy substitutes*: the explicit subject, or the id it usually is. Reading
1678
+ it here rather than recomposing the `subject or id` fallback is the smallest instance of
1679
+ this task's whole rule, and it is the one that was written twice.
1680
+ """
1681
+ lineno = getattr(finding, "lineno", None)
1682
+ subject = getattr(finding, "token", "") or getattr(finding, "subject", "") or getattr(
1683
+ finding, "id", ""
1684
+ )
1685
+ return {
1686
+ "id": subject,
1687
+ "line": "" if lineno is None else str(lineno),
1688
+ "label": _label(subject, config),
1689
+ "file": getattr(finding, "file", ""),
1690
+ # Which governed file this finding is about, which is a fact the *report* already
1691
+ # printed and a door had to be told separately until RK470 derived it by hand.
1692
+ "role": "" if config is None else _role_of(finding, config),
1693
+ }
1694
+
1695
+
1696
+ def remedy(finding: object, config: Config | None = None) -> Remedy | None:
1697
+ """What closes ``finding``. ``None`` only for a code the table does not carry.
1698
+
1699
+ Takes anything with ``code``, ``id``, ``lineno`` and ``file`` — a
1700
+ :class:`~roadkeep.linting.Finding`, a :class:`~roadkeep.linting.Note`, or a
1701
+ :class:`~roadkeep.kernel.schema.Violation` wrapped in one — because the caller repairing a
1702
+ line does not care which of the three reported it.
1703
+ """
1704
+ code = getattr(finding, "code", "")
1705
+ rule = _TABLE.get(code)
1706
+ if rule is None:
1707
+ return None
1708
+ values = _values(finding, config)
1709
+ if rule.varies and config is not None:
1710
+ rule = _varied(code, rule, finding, values, config)
1711
+ doors = tuple(
1712
+ Door(_scoped(_substitute(argv, values), values, config), what, foreign=rule.foreign)
1713
+ for argv, what in rule.doors
1714
+ )
1715
+ return Remedy(code, rule.kind, doors, rule.decision, rule.sequence)
1716
+
1717
+
1718
+ def _varied(
1719
+ code: str, rule: _Rule, finding: object, values: Mapping[str, str], config: Config
1720
+ ) -> _Rule:
1721
+ """The two rows a project's own configuration decides (L6)."""
1722
+ if code == "ref.mismatch" and config.schema.ref_scheme != "id":
1723
+ # An outline anchor is not derivable, so there is nothing mechanical to recompute:
1724
+ # the field is the author's and the fixer would be guessing an address.
1725
+ return _compose(
1726
+ ("amend", "{id}", "--ref", BLANK),
1727
+ "the anchor is not derived under this project's scheme, so it is yours to state",
1728
+ )
1729
+ if code == "section.duplicate" and config.schema.ref_scheme == "id":
1730
+ # Under an id scheme both headings claim one line's address, and no verb re-addresses
1731
+ # one of them: `section move` refuses an id-addressed section outright and
1732
+ # `anchors --next` has no numbering to derive from. The two doors that are real are
1733
+ # the ones `section move`'s own refusal names, and choosing between them is reading
1734
+ # which heading is the stray — so a decision and not a command (RK1337).
1735
+ return _decide(
1736
+ "two headings claim one line's address and nothing derives a free one here: "
1737
+ "either the later design belongs to a line of its own, or it is a copy",
1738
+ (
1739
+ ("renumber", "{id}", "--to", BLANK),
1740
+ "the line, its heading, its subtree and every dep move together, which is "
1741
+ "what re-addressing an id-addressed design means",
1742
+ ),
1743
+ (
1744
+ ("section", "drop", "{id}"),
1745
+ "or take the copy out — refused while a line still points at it, so the "
1746
+ "pointer is repointed or that line ships first",
1747
+ ),
1748
+ )
1749
+ if rule.varies == "queue" and _queue_in_config(config):
1750
+ # The order lives where no verb writes, so the mechanical pass cannot reach it and
1751
+ # the honest remedy is the one door between the two declarations.
1752
+ return _TABLE["priority.unmigrated"]
1753
+ if rule.varies == "target":
1754
+ # Which projection went stale, read off the finding's own subject (RK1110). The domain
1755
+ # is `DEFAULTS`' keys, so a fourth target is covered by arithmetic rather than by
1756
+ # somebody remembering — and a subject that is not one of them keeps the row, which is
1757
+ # what `explain` gets, having no finding to ask.
1758
+ from roadkeep.exporting import DEFAULTS # noqa: PLC0415 - RK260's edge back
1759
+
1760
+ flag = values.get("id", "")
1761
+ if flag in DEFAULTS:
1762
+ argv, what = rule.doors[0]
1763
+ return _Rule("run", (((*argv[:-1], f"--{flag}"), what),))
1764
+ return rule
1765
+ if rule.varies == "nested":
1766
+ blockers = _claimed_below(finding, config)
1767
+ if blockers:
1768
+ # Not a door this tool can open: the drop is right and cannot happen until the
1769
+ # nested design moves or the line claiming it ships, and neither is a mechanical
1770
+ # write. Naming an edit that cannot work is worse than naming none (RK16), so
1771
+ # what is named is the blocker and the two ways it goes.
1772
+ named = ", ".join(f"§{anchor} ({', '.join(who)})" for anchor, who in blockers)
1773
+ return _decide(
1774
+ f"the drop is blocked: {named} nests under this one and an open line points "
1775
+ f"there, so it goes when that design moves or that task ships:",
1776
+ (("show", "{id}"), "read what still claims the prose under this section"),
1777
+ (("section", "move", BLANK), "move the nested design out, then drop this one"),
1778
+ )
1779
+ return rule
1780
+ if rule.varies == "region":
1781
+ loose = _loose_below(finding, config)
1782
+ if loose:
1783
+ # `block merge` refuses while the later heading stands over a note, and `--prose`
1784
+ # is what drops it — a decision RK237 put at the door on purpose, because the
1785
+ # note is somebody's prose and this tool does not delete prose to close a finding
1786
+ # (L4). Found by RK473's own sweep on Shio's pinned ledger, where two merges were
1787
+ # dispatched and refused on every run.
1788
+ where = ", ".join(f"line {one}" for one in loose)
1789
+ return _decide(
1790
+ f"the fold is blocked: the later heading stands over a note ({where}), which "
1791
+ f"the merge would take with it:",
1792
+ (("block", "merge", "{id}", "--prose"), "fold, dropping that note with it"),
1793
+ (("show", "{id}"), "read the note first — moving it is the other answer"),
1794
+ )
1795
+ if rule.varies == "region" and _empty_region(finding, config):
1796
+ # The verb the finding's own sentence names on this branch (RK425): a region holding
1797
+ # nothing is removed rather than folded, and `block drop` is what removes it.
1798
+ return _run(
1799
+ ("block", "drop", "{id}"),
1800
+ "the later heading stands over nothing, so it is taken out rather than folded",
1801
+ )
1802
+ if code == "id.duplicate" and values["role"] == "roadmap":
1803
+ # `record renumber` opens the ledger and this is the other file: two *open* lines
1804
+ # sharing an id are two tasks, and one of them takes a free address.
1805
+ return _decide(
1806
+ "two open lines carry one id, which is two tasks sharing an address:",
1807
+ (("renumber", "{id}"), "move the later line, with its section and its dependents"),
1808
+ (("show", "{id}"), "read both first — they may be one line written twice"),
1809
+ )
1810
+ return rule
1811
+
1812
+
1813
+ def _queue_in_config(config: Config) -> bool:
1814
+ """Whether this project's order is still `roadkeep.toml`'s (RK427).
1815
+
1816
+ Asked of :func:`~roadkeep.queueing.declared`, which is the one reader that can see both
1817
+ declarations — a second rule here about which file wins is the disagreement RK427 is.
1818
+ """
1819
+ from .queueing import declared # noqa: PLC0415 - one branch, and never on a clean run
1820
+
1821
+ return declared(config).declared_in == "config"
1822
+
1823
+
1824
+ def _loose_below(finding: object, config: Config) -> tuple[int, ...]:
1825
+ """The lines of prose the later heading stands over, which the fold would take (RK473).
1826
+
1827
+ Asked of `blocking._held`, which is the reader `block merge` refuses from, so the remedy
1828
+ and the verb answer one question. Empty where the fold would run.
1829
+ """
1830
+ from .blocking import _held # noqa: PLC0415 - one branch, never on a clean run
1831
+
1832
+ label = getattr(finding, "subject", "") or getattr(finding, "id", "")
1833
+ where, lineno = getattr(finding, "file", ""), getattr(finding, "lineno", None)
1834
+ if not label or not where or lineno is None:
1835
+ return ()
1836
+ document = next(
1837
+ (
1838
+ config.document(role)
1839
+ for role in ROLES
1840
+ if config.has(role) and config.relative(config.path(role)) == where
1841
+ ),
1842
+ None,
1843
+ )
1844
+ if document is None:
1845
+ return ()
1846
+ later = next((one for one in document.headings if one.lineno == lineno), None)
1847
+ return () if later is None else _held(document, later).prose
1848
+
1849
+
1850
+ def _empty_region(finding: object, config: Config) -> bool:
1851
+ """Whether `block drop` would remove this label's heading rather than refuse (RK468).
1852
+
1853
+ Asked of `linting.closes_by_drop`, which is the reader the finding's own sentence uses,
1854
+ so the message and the remedy answer one question rather than two that agree until they
1855
+ do not. Imported inside the branch for :func:`_queue_in_config`'s reason: this module is
1856
+ on the report's own import path and the question is asked on one code out of seventy.
1857
+
1858
+ Two things off the finding and not one. The subject is the **label** — every other row
1859
+ here is keyed by a task id, and this is the one whose id is a heading — and the line is
1860
+ which repeat it is about, because `block drop` closes this finding only where *this*
1861
+ region is the empty one and not merely where the verb would run somewhere.
1862
+ """
1863
+ from .linting import closes_by_drop # noqa: PLC0415 - one branch, never on a clean run
1864
+
1865
+ label = getattr(finding, "subject", "") or getattr(finding, "id", "")
1866
+ where, lineno = getattr(finding, "file", ""), getattr(finding, "lineno", None)
1867
+ if not label or not where or lineno is None:
1868
+ return False
1869
+ files = {
1870
+ role: config.document(role)
1871
+ for role in ROLES
1872
+ if config.has(role) and config.path(role).is_file()
1873
+ }
1874
+ document = next(
1875
+ (one for role, one in files.items() if config.relative(config.path(role)) == where),
1876
+ None,
1877
+ )
1878
+ if document is None:
1879
+ return False
1880
+ later = next((one for one in document.headings if one.lineno == lineno), None)
1881
+ return later is not None and closes_by_drop(document, later, files, label)
1882
+
1883
+
1884
+ def _claimed_below(finding: object, config: Config) -> tuple[tuple[str, tuple[str, ...]], ...]:
1885
+ """The sections nested under this one that an open line still points at (RK472).
1886
+
1887
+ The same question `section drop` refuses on, asked of the readers it uses — `pointers`
1888
+ for the claims and `nested` for the containment — so the remedy and the verb answer one
1889
+ thing rather than two that agree until they do not. Empty where the drop would run.
1890
+
1891
+ Imported inside the branch for :func:`_queue_in_config`'s reason, and asked on one code.
1892
+ """
1893
+ from .sections import find, nested, pointers # noqa: PLC0415 - one branch
1894
+
1895
+ anchor = getattr(finding, "subject", "") or getattr(finding, "id", "")
1896
+ role = _role_of(finding, config)
1897
+ if not anchor or role not in PROSE_ROLES or not config.has(role):
1898
+ return ()
1899
+ document = config.document(role)
1900
+ if find(document, anchor) is None:
1901
+ return ()
1902
+ claimed = pointers(config)
1903
+ return tuple(
1904
+ (child.anchor, claimed[child.anchor])
1905
+ for child in nested(document, anchor)
1906
+ if child.anchor in claimed
1907
+ )
1908
+
1909
+
1910
+ def _scoped(
1911
+ argv: tuple[str, ...], values: Mapping[str, str], config: Config | None
1912
+ ) -> tuple[str, ...]:
1913
+ """Name which prose file a `section` verb is about, where the project has two (RK470).
1914
+
1915
+ RK420 promises a complete argv, and on a project declaring one prose file it was: every
1916
+ `section` verb defaults to that file. On one declaring two it was not. Measured by
1917
+ running `repair` over a copy of Turing:
1918
+
1919
+ docs/STRATEGY.md:683 section.stale XIV.2 …
1920
+ FAILED section drop XIV.2
1921
+ roadkeep: no §XIV.2 section in docs/IMPROVEMENTS.md
1922
+
1923
+ The finding names one file and the remedy opened the other. `--role` is a flag all four
1924
+ verbs already take, and the finding already says which file it is about — so nothing new
1925
+ is read, and the completion is derived here rather than written into five rows that would
1926
+ each carry a word most projects do not need.
1927
+
1928
+ **Only where the project declares more than one**, which is the question §RK470 left open:
1929
+ on a single-file project the flag names the default and is a word that changes nothing,
1930
+ and these argvs are read by people as well as run by `repair`.
1931
+ """
1932
+ if config is None or argv[:1] != ("section",) or "--role" in argv:
1933
+ return argv
1934
+ declared = [role for role in PROSE_ROLES if config.has(role)]
1935
+ role = values["role"]
1936
+ if len(declared) < 2 or role not in declared:
1937
+ return argv
1938
+ return (*argv, "--role", role)
1939
+
1940
+
1941
+ def _role_of(finding: object, config: Config) -> str:
1942
+ """Which governed file this finding is about, by the path the report printed."""
1943
+ where = getattr(finding, "file", "")
1944
+ for role in ROLES:
1945
+ if config.has(role) and config.relative(config.path(role)) == where:
1946
+ return role
1947
+ return ""
1948
+
1949
+
1950
+ def _label(subject: str, config: Config | None) -> str:
1951
+ """The block label inside a queue token, for the door that takes one (RK435).
1952
+
1953
+ Two spellings of one thing, and mixing them is not cosmetic: the queue holds `Block D`
1954
+ and `priority drop` takes exactly that, while `--block` takes `D` and answers `Block D`
1955
+ by looking for a heading named `Block Block D` — exit 2, on the remedy RK420 added so a
1956
+ caller would not have to compose one.
1957
+
1958
+ Asked of :meth:`~roadkeep.kernel.schema.Schema.block_of_dep`, which is where a token's label is
1959
+ read everywhere else, including at the emission site this row answers. A second reader
1960
+ of that spelling would be the drift this package exists to stop, and it would be the one
1961
+ that has to remember `heading_word` is per project (L6).
1962
+
1963
+ Empty where there is nothing to ask — a token naming no block, or a `remedy` called with
1964
+ no config, which `explain` is — and the blank then renders for :func:`_substitute`'s own
1965
+ reason: the field is unknown to *this call* rather than withheld from the author, and
1966
+ `add --block …` says which word is missing where `add --block None` does not.
1967
+ """
1968
+ return "" if config is None else (config.schema.block_of_dep(Dep(subject)) or "")
1969
+
1970
+
1971
+ def _substitute(argv: Sequence[str], values: Mapping[str, str]) -> tuple[str, ...]:
1972
+ """Fill a template from :func:`_values`. A field with no value keeps its blank.
1973
+
1974
+ That fallback is the module's own rule applied to itself: an argv reading ``--line None``
1975
+ is worse than one reading ``--line …``, because the first looks runnable and the second
1976
+ says which word is missing.
1977
+
1978
+ The domain is :data:`FIELDS` and this reads it whole, so a row naming a fifth field is a
1979
+ row this fills rather than one that renders its own braces (RK490) — and the suite holds
1980
+ the other end, that no row names something :func:`_values` does not answer.
1981
+ """
1982
+ out: list[str] = []
1983
+ for word in argv:
1984
+ for name, value in values.items():
1985
+ token = "{" + name + "}"
1986
+ if token in word:
1987
+ word = word.replace(token, value or BLANK)
1988
+ out.append(word)
1989
+ return tuple(out)