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/adopting.py ADDED
@@ -0,0 +1,2347 @@
1
+ """Getting a project to where the rest of the tool applies (RK18).
2
+
3
+ Two commands against one problem: **every repository that needs this already has a
4
+ backlog**, so a tool that only works on an empty one is a tool nobody can adopt. The two
5
+ halves are deliberately asymmetric — one writes a scaffold and nothing else, the other
6
+ reads a file it does not own and writes nothing at all.
7
+
8
+ * :func:`init` creates `roadkeep.toml` and the files it declares. The config is *rendered
9
+ from* :class:`~roadkeep.kernel.schema.Schema`'s own defaults rather than copied from a template
10
+ kept beside them, because a template is a second statement of the format and the two
11
+ drift in the direction nobody tests — the same reason `Schema.render` is the only writer
12
+ of a task line.
13
+ * :func:`adopt` runs the schema over an existing backlog and reports what would have to
14
+ change for `lint` to pass it. A migration estimate is only worth taking *before* the
15
+ migration commitment, which is why it is a separate command from `lint` and not a flag
16
+ on it: `lint` is a gate over files this project declared, and the file `adopt` reads is
17
+ by definition not one of them yet. It counts what it could not read as well as what it
18
+ could — a backlog kept as table rows, or as the plain `- [ ] …` list almost every
19
+ unadopted roadmap actually is (RK279), parses as nothing, and a zero the reader cannot
20
+ tell from an empty file is the one answer an estimate may not give (RK98). Counting the
21
+ rows is not parsing them: reading the shape is an estimate's job, and a tool that read
22
+ the cells would be a tool with two line formats. It reads **both** kinds of bullet a
23
+ roadmap holds (RK139): the non-goals are measured against the two limits they would be
24
+ held to, declared or not, because a third of one adoption's work was in that list and
25
+ arrived after the commitment. `--sections` is the one read that goes past the path it was
26
+ handed, and for one finding: an address is doubled only *across* two files, so a per-file
27
+ estimate calls both of them conforming and the gate then files a `section.ambiguous` per
28
+ collision (RK347). Which files those are is the project's `[files]` where the target is one
29
+ of this project's own, for the reason :func:`_unread` does not name them otherwise (RK292),
30
+ and otherwise `--with`, repeated (RK359) — the case the command exists for being a file no
31
+ declaration reaches at all. Named and never found by looking in the directory.
32
+
33
+ Three decisions that are the point rather than details of it:
34
+
35
+ * **Neither command invents backlog content** (L4). `init` writes a title, the block
36
+ headings the author named and an empty `## Non-goals`; the block *titles* are the
37
+ author's own words, passed through. There is no starter task and no explanatory
38
+ paragraph — prose the tool wrote would be prose the project then has to maintain.
39
+ * **Nothing is written unless everything can be.** The config is parsed back in memory and
40
+ compared against the schema it was rendered from, and every target path is checked for
41
+ existence, before the first byte reaches disk. A half-scaffolded project is worse than
42
+ an unscaffolded one because it looks configured.
43
+ * **`adopt` measures and never proposes.** It reports the longest `symptom` it found and
44
+ how many lines exceed the limit; it does not suggest raising the limit to fit them. The
45
+ measurement is what decides whether the schema is wrong or the lines are (§RK20), and a
46
+ tool that answered that question would be answering it in the direction that requires
47
+ no work.
48
+
49
+ Neither prints the RK38 event line: that payload is an id and its block, and a scaffold
50
+ writes no task while an estimate writes nothing whatsoever.
51
+ """
52
+
53
+ from __future__ import annotations
54
+
55
+ import re
56
+ import tomllib
57
+ from collections.abc import Callable, Iterable, Mapping, Sequence
58
+ from dataclasses import dataclass, replace
59
+ from pathlib import Path
60
+
61
+ from roadkeep import queueing, scoping
62
+ from roadkeep.config import (
63
+ CLAIM_HELD,
64
+ CONFIG_NAME,
65
+ DECISIONS_PATH,
66
+ DEFAULT_PATHS,
67
+ DEFERRED_PATH,
68
+ STRATEGY_PATH,
69
+ PROSE_ROLES,
70
+ PYPROJECT,
71
+ ROLES,
72
+ Config,
73
+ Scope,
74
+ )
75
+ from roadkeep.kernel.document import LEDGER_SHAPES, Document, Heading, checkbox
76
+ from roadkeep.kernel.schema import (
77
+ CODE_POINTS,
78
+ DEFAULT_HEADING_WORD,
79
+ OUTLINE_ANCHOR_RE,
80
+ UTF16_UNITS,
81
+ WORDS,
82
+ Schema,
83
+ width,
84
+ )
85
+ from roadkeep.sections import anchored, structural, unanchored, words as sections_words
86
+
87
+ #: The roles `init` scaffolds. `strategy` is absent and not empty: Turing has one and this
88
+ #: project does not, and a declared file nobody writes is `file.missing` on the first lint.
89
+ SCAFFOLD_ROLES = ("roadmap", "changelog", "improvements")
90
+
91
+ #: The fourth, written only where `init --strategy` asks for it (RK1186). Opt-in and not a
92
+ #: default, because the two prose roles answer different questions: an improvements section is
93
+ #: a task's rationale and is **deleted when the line ships**, and a strategy document outlives
94
+ #: every task filed under it. A project with one backlog and no specification above it would
95
+ #: get an empty file it never opens, which is the scaffold inventing a decision.
96
+ STRATEGY_ROLE = "strategy"
97
+
98
+ #: The fifth, written only where `init --deferred` asks for it (RK1259). Opt-in for
99
+ #: :data:`STRATEGY_ROLE`'s reason and one of its own: a project that never pauses anything has
100
+ #: no store rather than an empty one, so writing it by default hands most adopters a fourth
101
+ #: governed file they never open. What it fixes is the other side of that — `defer` refuses
102
+ #: where the key is undeclared, correctly and without scaffolding, and the remedy it named was
103
+ #: a toml key and a skeleton no verb offered to write. Now one does, and it is the command that
104
+ #: writes every other governed file.
105
+ DEFERRED_ROLE = "deferred"
106
+
107
+ #: The sixth, and the one no scaffold ever writes (RK1269). `declare decisions` is its only
108
+ #: door: `init` opens a project's backlog, and a project has no decisions on the day it is
109
+ #: created — a file scaffolded there is an empty ADR directory, which is the convention this
110
+ #: role exists to replace rather than reproduce.
111
+ DECISIONS_ROLE = "decisions"
112
+
113
+ #: Where each role's file goes when nobody names a path: `DEFAULT_PATHS` plus the three roles
114
+ #: that are not part of a project's implied layout (RK1186, RK1259, RK1269). One table and no
115
+ #: longer two identical literals — the scaffold and `declare` write the same file at the same
116
+ #: place, and a role added to one of two copies is the role whose default depends on the door.
117
+ _DEFAULT_FOR = {
118
+ **DEFAULT_PATHS,
119
+ STRATEGY_ROLE: STRATEGY_PATH,
120
+ DEFERRED_ROLE: DEFERRED_PATH,
121
+ DECISIONS_ROLE: DECISIONS_PATH,
122
+ }
123
+
124
+ #: The heading each scaffolded file opens with. Structural, not prose — the block headings
125
+ #: below it are what `add`, `ship` and `section add` file text under.
126
+ _TITLES = {
127
+ "roadmap": "Roadmap (active backlog)",
128
+ "changelog": "Shipped Ledger",
129
+ "improvements": "Improvements",
130
+ "strategy": "Strategy",
131
+ "deferred": "Set aside",
132
+ "decisions": "Decisions",
133
+ }
134
+
135
+ #: The fields `adopt` measures against their limits, and where each one is read from.
136
+ _MEASURED = (("symptom", "symptom_max"), ("why", "why_max"), ("line", "line_max"))
137
+
138
+ #: An id taken apart for the `[ids]` delta (RK110): the digits, and the one lowercase letter
139
+ #: a split keeps. Deliberately looser than any project's own shape — it has to read the ids a
140
+ #: declaration would refuse, those being the ones worth counting.
141
+ _ID_PARTS_RE = re.compile(r"^[A-Za-z]+(?P<number>[0-9]+)(?P<sub>[a-z]?)$")
142
+
143
+
144
+ class AlreadyConfigured(ValueError):
145
+ """`init` scaffolds; a project that already declares the format wants `adopt`."""
146
+
147
+ def __init__(self, source: Path) -> None:
148
+ self.source = source
149
+ super().__init__(
150
+ f"{source} already configures roadkeep: `init` writes a scaffold and would "
151
+ f"overwrite the declaration this project is already governed by — `adopt "
152
+ f"<file>` reports what an existing backlog must change instead"
153
+ )
154
+
155
+
156
+ class RoleDeclared(ValueError):
157
+ """`declare` on a role this project already has a file for (RK1264).
158
+
159
+ The one state where the answer is not a write. A key already declared points somewhere, and
160
+ a second one would either overwrite that path or leave two — so the refusal names what it
161
+ found, which is also the answer to *why did nothing happen*.
162
+ """
163
+
164
+ def __init__(self, role: str, where: str) -> None:
165
+ self.role = role
166
+ super().__init__(
167
+ f"this project already declares {role} = \"{where}\": `declare` adds a role to "
168
+ f"`[files]` and one that is there needs no adding — the file is what to edit"
169
+ )
170
+
171
+
172
+ #: The tables a project opts into by declaring them at all (RK1328). Two, and both are
173
+ #: `_scope`'s: `[non_goals]` says what is not built and `[criteria]` what would finish a
174
+ #: block, and writing either governs its list — the numbers under it are what a project may
175
+ #: then tune. `[requirements]` is deliberately not here: that one is a *vocabulary*, and
176
+ #: `declared = []` governs nothing and only changes which refusal the author reads (RK1313).
177
+ OPT_IN: tuple[str, ...] = ("non_goals", "criteria")
178
+
179
+
180
+ class TableDeclared(ValueError):
181
+ """`declare` on an opt-in table this project already carries (RK1328).
182
+
183
+ :class:`RoleDeclared`'s twin one table over, and the answer is not a write for its reason:
184
+ a table already there governs its list, and writing it again would either replace the
185
+ numbers a project tuned or leave two of it.
186
+ """
187
+
188
+ def __init__(self, table: str) -> None:
189
+ self.table = table
190
+ super().__init__(
191
+ f"this project already declares [{table}]: `declare` opens the table and one "
192
+ f"that is open needs no opening — `govern {table}.lead <n>` tunes what is in it"
193
+ )
194
+
195
+
196
+ class NoSuchTable(ValueError):
197
+ """A word that is neither a role nor an opt-in table (RK1328).
198
+
199
+ Names **both** vocabularies, because one argument now carries two and a caller who typed
200
+ into the wrong one learns nothing from a refusal about the other.
201
+ """
202
+
203
+ def __init__(self, word: str, tables: Sequence[str]) -> None:
204
+ self.word = word
205
+ super().__init__(
206
+ f"{word!r} is neither a role nor a table this verb opens: `[files]` names "
207
+ f"{', '.join(ROLES)}, and the opt-in tables are {', '.join(tables)}"
208
+ )
209
+
210
+
211
+ class NoSuchRole(ValueError):
212
+ """A word that is not one of the five roles this format governs (RK1264)."""
213
+
214
+ def __init__(self, role: str, roles: Sequence[str]) -> None:
215
+ self.role = role
216
+ super().__init__(
217
+ f"{role!r} is not a role this format governs: `[files]` names "
218
+ f"{', '.join(roles)}, and a key beside those is one nothing reads"
219
+ )
220
+
221
+
222
+ class Unconfigured(ValueError):
223
+ """`declare` on a tree with no `roadkeep.toml` (RK1264).
224
+
225
+ The mirror of :class:`AlreadyConfigured`, and the pair is the whole shape of these two
226
+ doors: `init` writes the declaration and refuses where one exists, this adds a role to one
227
+ and refuses where there is none.
228
+ """
229
+
230
+ def __init__(self, root: Path) -> None:
231
+ self.root = root
232
+ super().__init__(
233
+ f"{root.as_posix()} declares no roadkeep.toml, so there is no `[files]` to add a "
234
+ f"role to: `init` writes the scaffold and its configuration together"
235
+ )
236
+
237
+
238
+ class WouldOverwrite(ValueError):
239
+ """One existing path is enough to refuse all of them (all-or-nothing).
240
+
241
+ A scaffold that skipped what was there and wrote the rest leaves a project half
242
+ configured, which reads as configured and behaves as neither.
243
+
244
+ It names `adopt` for what it found (RK282). :class:`AlreadyConfigured` always did, and this
245
+ is the branch that needed it more: a repository holding a backlog and no declaration has
246
+ never met this tool, which is exactly who `adopt` was built for and exactly who is standing
247
+ here — while the refusal that named the door is the one reached by a project that already
248
+ adopted. Per file and never per directory, because the estimate is per file and a
249
+ suggestion naming the directory would be a command that does not exist.
250
+ """
251
+
252
+ def __init__(self, paths: Sequence[Path], base: Path | None = None) -> None:
253
+ self.paths = tuple(paths)
254
+ #: Those of :attr:`paths` an estimate can actually be taken over. The configuration is
255
+ #: not one: `adopt` reads a backlog, and pointing it at `roadkeep.toml` is
256
+ #: :class:`NotACorpus` one command later — which this said before there was such a
257
+ #: refusal, the command having answered `0 lines, 0 would change` instead (RK374).
258
+ self.adoptable = tuple(path for path in self.paths if path.name != CONFIG_NAME)
259
+ listed = ", ".join(str(path) for path in self.paths)
260
+ message = f"{len(self.paths)} path(s) already exist and nothing was written: {listed}"
261
+ if self.adoptable:
262
+ # One door and not one per file, though the estimate is per file: every path is
263
+ # already named above, and repeating them here doubled a message that is mostly
264
+ # pathname. Spelled relative to the project where that is possible, for the reason
265
+ # `provenance.invocation` gives — an absolute path is a message about one machine.
266
+ first = _relative(self.adoptable[0], base)
267
+ more = f" (and {len(self.adoptable) - 1} more)" if len(self.adoptable) > 1 else ""
268
+ message += (
269
+ f" — `adopt {first}`{more} reports what an existing backlog must change instead"
270
+ )
271
+ super().__init__(message)
272
+
273
+
274
+ class BlockedParent(ValueError):
275
+ """A declared file whose directory cannot be created, because a file is standing in it.
276
+
277
+ :class:`WouldOverwrite` asks whether a target already exists, which is whether writing
278
+ would clobber. This is the other question nobody asked (RK392): whether writing can happen
279
+ at all. A `docs` that is a file rather than a directory left `roadkeep.toml` on disk and
280
+ every file it declares unwritten — the half-scaffolded project `init` says out loud it
281
+ exists to prevent, reachable because the directory was created below the line where
282
+ nothing is supposed to refuse.
283
+
284
+ Named per file **and** per blocker, because they are different paths and the second is the
285
+ one to act on: the reader is told `docs/ROADMAP.md` cannot be written and that `docs` is
286
+ why, and deleting the roadmap they were never given would be the wrong move.
287
+ """
288
+
289
+ def __init__(self, blocked: Sequence[tuple[Path, Path]], base: Path | None = None) -> None:
290
+ self.blocked = tuple(blocked)
291
+ listed = ", ".join(
292
+ # Two shapes, because they are two obstacles (RK394): a parent that is a file is
293
+ # a directory that cannot be made, and a target that is a directory is a write
294
+ # with nowhere to go. Saying "blocked by itself" would name neither.
295
+ f"{_relative(path, base)} (is a directory)"
296
+ if parent == path
297
+ else f"{_relative(path, base)} (blocked by {_relative(parent, base)})"
298
+ for path, parent in self.blocked
299
+ )
300
+ super().__init__(
301
+ f"{len(self.blocked)} declared file(s) cannot be written and nothing was: {listed}"
302
+ )
303
+
304
+
305
+ def blocking(path: Path) -> Path | None:
306
+ """The nearest ancestor of ``path`` that exists and is not a directory (RK392).
307
+
308
+ Public because `install` asks it too (RK393): it writes four surfaces under directories it
309
+ creates as it goes, and a `.claude` that is a file stopped it with the server declaration
310
+ already on disk — `init`'s defect one command over, and the same question answers both.
311
+
312
+ The whole chain and not the immediate parent: `docs/backlog/ROADMAP.md` is stopped just
313
+ as dead by a `docs` that is a file, and `mkdir(parents=True)` is what would have walked
314
+ it. Returns the blocker itself rather than a bool, because the file to act on is that one
315
+ and not the one that was asked for — and where that is the target, the target is returned:
316
+ a `.mcp.json` that is a *directory* stops the write as completely as a parent does, and
317
+ checking only the ancestors let it through both times this was written (RK394).
318
+ """
319
+ if path.is_dir():
320
+ return path
321
+ for ancestor in path.parents:
322
+ if ancestor.exists():
323
+ return None if ancestor.is_dir() else ancestor
324
+ return None
325
+
326
+
327
+ def _elsewhere(*given: object) -> tuple[str, ...]:
328
+ """Which of these relative paths is a file beside the **caller** rather than the project.
329
+
330
+ Read for the refusal alone (RK1101) and never to decide what to open: two bases is the
331
+ ambiguity the resolution rule removes, and a fallback here would put it back one layer
332
+ down. What it buys is a sentence — the reader is told which tree holds the file they meant.
333
+ """
334
+ candidates: list[str] = []
335
+ for one in given:
336
+ for path in (one,) if isinstance(one, (str, Path)) else tuple(one): # type: ignore[arg-type]
337
+ spelled = Path(path)
338
+ if not spelled.is_absolute() and spelled.is_file():
339
+ candidates.append(spelled.as_posix())
340
+ return tuple(dict.fromkeys(candidates))
341
+
342
+
343
+ def _relative(path: Path, base: Path | None) -> str:
344
+ """A path as a reader would type it from the project root, or absolute where it is not one."""
345
+ try:
346
+ return path.relative_to(base).as_posix() if base else path.as_posix()
347
+ except ValueError: # not under the base, so the whole path is the only true answer
348
+ return path.as_posix()
349
+
350
+
351
+ class Unreadable(ValueError):
352
+ """One path that is not a readable file is enough to refuse the whole estimate (RK370).
353
+
354
+ `adopt` was handed one path until RK359 gave it a set, and a set opened a file at a time
355
+ stops partway: the report an adopter reads then measured two of three files and looks
356
+ complete, which is the state :class:`WouldOverwrite` refuses one command over for the same
357
+ reason. So every path is checked before the first one is opened.
358
+
359
+ Named by the **argument** that carried it and spelled from the project root, neither of
360
+ which `pathlib`'s own sentence has. With a target and two `--with` files the reader is
361
+ otherwise left with three candidates and one filename, on the one failure — a typo — where
362
+ the filename is the part that is wrong; and the absolute path it prints is the message
363
+ `provenance.invocation` refuses, one about a machine rather than about a project.
364
+
365
+ A pre-check and not a replacement for the reader's own raise: a file that exists and
366
+ cannot be read still comes out of :meth:`Document.load` as an `OSError`, which the command
367
+ already reports. What is removed is the case the estimate can see coming.
368
+ """
369
+
370
+ def __init__(
371
+ self,
372
+ missing: Sequence[tuple[str, Path]],
373
+ base: Path | None = None,
374
+ elsewhere: Sequence[str] = (),
375
+ ) -> None:
376
+ self.missing = tuple(missing)
377
+ self.elsewhere = tuple(elsewhere)
378
+ listed = ", ".join(
379
+ f"{_relative(path.resolve(), base)} ({named})" for named, path in self.missing
380
+ )
381
+ # Where the same relative path *is* a file next to the caller, that is said (RK1101).
382
+ # The resolution moved to the project root, so `cd docs && … adopt ROADMAP.md` now
383
+ # refuses — and the one thing that refusal must not do is leave the reader guessing
384
+ # which of the two trees is meant. Naming the candidate is what keeps a rule change
385
+ # from reading as a file having gone missing.
386
+ found = (
387
+ f" — {', '.join(self.elsewhere)} is a file where this was run, and paths here are "
388
+ f"read from the project root: pass it as that path or as an absolute one"
389
+ if self.elsewhere
390
+ else ""
391
+ )
392
+ super().__init__(
393
+ f"{len(self.missing)} path(s) are not a file this can read and nothing was "
394
+ f"measured: {listed}{found}"
395
+ )
396
+
397
+
398
+ class NotACorpus(ValueError):
399
+ """`adopt` was pointed at this format's own declaration, not at anything it measures (RK374).
400
+
401
+ The file opens, so :class:`Unreadable` lets it through, and every reader below then finds
402
+ no line and no heading in it: `0 line(s), 0 conform, 0 would change`, which is what an
403
+ empty roadmap reports and is the one answer an estimate may not give (RK98). Counting the
404
+ rows of a table and the plain bullets of a checklist exists so that a file the format has
405
+ no reader for stops answering nothing; a configuration is that case with the reader's own
406
+ declaration in it.
407
+
408
+ A refusal and not a count, which is the choice §RK374 left open. `adopt` exits 0 over a
409
+ corpus however far from the format it is (RK18) — the estimate is the thing being bought
410
+ — and refuses the *arguments* that name no corpus to measure: `--ledger` with `--sections`,
411
+ a path that does not open, and this. Measuring it would need a counter and a sentence for
412
+ a file nobody wants measured, while the refusal is the one already written down as true in
413
+ :class:`WouldOverwrite`, which leaves the configuration out of the door it offers on
414
+ exactly this ground.
415
+
416
+ Which files those are is :func:`_declares`, the reader `init` refuses against (RK375).
417
+ This was written to catch `roadkeep.toml` by name, on the ground that refusing every
418
+ `pyproject.toml` by name would refuse the ones configuring nothing here — sound against a
419
+ *name* check, and no answer to the question under it, since the name is not how this tool
420
+ recognises the file anywhere else. A pyproject declaring `[tool.roadkeep]` was left
421
+ measuring as an empty backlog by the refusal written to stop exactly that.
422
+ """
423
+
424
+ def __init__(self, named: str, path: Path, config: Config | None = None) -> None:
425
+ self.named = named
426
+ self.path = path
427
+ base = config.root if config else None
428
+ # What that configuration declares, where it is the one this run loaded — the door,
429
+ # said precisely. Another project's `roadkeep.toml` names files this run has not read,
430
+ # and offering this project's paths for it would send the caller at the wrong tree.
431
+ declared = (
432
+ [config.relative(config.path(role)) for role in config.paths]
433
+ if config is not None and config.source is not None
434
+ and config.source.resolve() == path.resolve()
435
+ else []
436
+ )
437
+ door = f" — measure {' or '.join(declared)}" if declared else ""
438
+ super().__init__(
439
+ f"{_relative(path.resolve(), base)} ({named}) configures roadkeep and is not a "
440
+ f"corpus: `adopt` measures a backlog, a ledger or a rationale file{door}"
441
+ )
442
+
443
+
444
+ class NotText(ValueError):
445
+ """A file that exists and does not decode, said rather than raised through (RK1350).
446
+
447
+ `UnicodeDecodeError` is a `ValueError`, and the verb catches `(ValueError, OSError)` to
448
+ report — so the decoder's own sentence reached the caller unchanged: *'utf-8' codec can't
449
+ decode byte 0xff in position 13: invalid start byte*, naming no file, no verb and no way
450
+ forward, with an offset into bytes nobody asked about.
451
+
452
+ :class:`Unreadable` is the pre-check and cannot see this one: a path that exists and is a
453
+ file passes it, and only the read finds out. So this is its sibling at the other end,
454
+ named by the path from the project root for the same reason that one is.
455
+
456
+ The door is **conditional and that is the whole care here**. `lint` answers this with
457
+ `file.not-text` and `git checkout -- <path>`, which is right about a governed file — the
458
+ store is the repository, so what is on disk should be what was committed. `adopt` is aimed
459
+ at files this project has never seen, where the same command would be advice about
460
+ somebody else's tree; measured both ways, this verb reads a declared file and an unknown
461
+ one, so which sentence it gets is decided by which it was handed.
462
+ """
463
+
464
+ def __init__(self, path: str, *, governed: bool, at: int = 0) -> None:
465
+ self.path = path
466
+ self.governed = governed
467
+ door = (
468
+ f"`git checkout -- {path}` puts back what was last committed, the store being "
469
+ f"the repository"
470
+ if governed
471
+ else "point this at the text file it was written from, or at the one that holds "
472
+ "the backlog"
473
+ )
474
+ super().__init__(
475
+ f"{path} is not UTF-8 text and nothing was measured — the first byte that is "
476
+ f"not sits at {at}: {door}"
477
+ )
478
+
479
+
480
+ class UnreadableBlock(ValueError):
481
+ """A `--block` value that is not one heading declaring a label.
482
+
483
+ Refused at input rather than written: `## Block <whatever>` that yields no label is a
484
+ heading `add` cannot file a task under, and the author would discover that later.
485
+
486
+ Two ways to be that, and the message says which (RK390). A value yielding no label is the
487
+ original; a value yielding a label **and more** is the one that got through, because the
488
+ check read the first heading and returned — so `A\\nB` was a block by that reading and the
489
+ scaffold wrote the `B` out as prose beneath it. Naming the cause is the rule RK370 settled
490
+ one refusal over: a caller holding a sentence about the wrong problem debugs the wrong
491
+ thing, and here the two problems are "this is not a block" and "this is a block plus a
492
+ line I did not ask you to write".
493
+ """
494
+
495
+ def __init__(self, given: str, *, beyond: bool = False) -> None:
496
+ self.given = given
497
+ #: Whether a label *was* read and the value carried more past it.
498
+ self.beyond = beyond
499
+ said = (
500
+ "names a block and then more, which would be written out under it"
501
+ if beyond
502
+ else "does not name a block"
503
+ )
504
+ super().__init__(
505
+ f"--block {given!r} {said}: give the label first, "
506
+ f"optionally with a title — 'A' or 'A {chr(0x2014)} The model'"
507
+ )
508
+
509
+
510
+ class RepeatedBlock(ValueError):
511
+ """Two `--block` values that declare the same label (RK390).
512
+
513
+ One heading twice is a file no verb can address: `add --block A` files under the **last**
514
+ of them — what scanning to the end leaves, rather than anything decided — and `ship` looks
515
+ for that label in the changelog. It is refused rather than
516
+ folded to one, which is the choice §RK390 left open — folding makes `--block A --block A`
517
+ and `--block A` produce identical output, so the author never learns the command was
518
+ wrong, and `init` inventing what somebody meant is the one thing it does not do.
519
+
520
+ Read off the **labels** and never the values handed over, because `A` and `A — The model`
521
+ are one block written two ways, and it is the heading the label lands in that a verb has
522
+ to find exactly once.
523
+ """
524
+
525
+ def __init__(self, label: str) -> None:
526
+ self.label = label
527
+ super().__init__(
528
+ f"--block {label!r} was given twice: one label is one heading, and two of them "
529
+ f"is a file `add` files into by position and `ship` cannot resolve at all"
530
+ )
531
+
532
+
533
+ @dataclass(frozen=True, slots=True)
534
+ class Created:
535
+ """What `init` wrote, in the order it wrote it."""
536
+
537
+ config: Path
538
+ files: tuple[Path, ...]
539
+ blocks: tuple[str, ...]
540
+
541
+ @property
542
+ def written(self) -> tuple[Path, ...]:
543
+ """Every path, config first — the order the scaffold was written in."""
544
+ return (self.config, *self.files)
545
+
546
+ def stated(self, families: Sequence[str]) -> str:
547
+ """The scaffold, and the one command that puts a line in it (RK56).
548
+
549
+ Beside :meth:`payload` since RK1170. `families` is the caller's: `init` runs *before* a
550
+ project is configured, so the prefixes it was pointed at are argv and not a fact this
551
+ record read back off a file it just wrote.
552
+ """
553
+ from roadkeep.provenance import invocation # noqa: PLC0415 - RK260
554
+
555
+ rows = [f"created {path.as_posix()}" for path in self.written]
556
+ rows.append(
557
+ f"{len(self.written)} file(s), blocks {', '.join(self.blocks)}: "
558
+ f"`{invocation()} add --block {self.blocks[0]} …` writes the first line"
559
+ )
560
+ return "\n".join(rows)
561
+
562
+ def payload(self, root: str, families: Sequence[str]) -> dict[str, object]:
563
+ return {
564
+ "root": Path(root).resolve().as_posix(),
565
+ "created": [path.as_posix() for path in self.written],
566
+ "prefix": families[0],
567
+ "prefixes": list(families),
568
+ "blocks": list(self.blocks),
569
+ }
570
+
571
+
572
+ @dataclass(frozen=True, slots=True)
573
+ class Retrofitted:
574
+ """What `declare` wrote: one role's file, and the key that governs it (RK1264)."""
575
+
576
+ role: str
577
+ path: Path
578
+ config: Path
579
+ #: The block headings mirrored in, as the roadmap already spells them. Read and never
580
+ #: composed, for `block add`'s reason: the level and the separator are the project's.
581
+ blocks: tuple[str, ...]
582
+
583
+ def stated(self, config: Config) -> str:
584
+ from roadkeep.provenance import invocation # noqa: PLC0415 - RK260
585
+
586
+ # The header, and every row under it at the column every other write uses (RK1372,
587
+ # RK1376): this answer was flat, so its `stage` line did not line up with the one
588
+ # `_staging_rows` composes anywhere else — the same row, two offsets, per verb.
589
+ rows = [
590
+ f"declared {self.role} = \"{config.relative(self.path)}\" "
591
+ f"{self.config.name}",
592
+ f" created {config.relative(self.path)} {len(self.blocks)} block heading(s)",
593
+ ]
594
+ # The verb this role exists for, which is the question a caller has next and the one
595
+ # the refusal that sent them here was about.
596
+ opens = _ROLE_OPENS.get(self.role)
597
+ if opens is not None:
598
+ rows.append(f" opens `{invocation()} {opens}`")
599
+ rows.append(f" stage git add -- {config.relative(self.path)} {self.config.name}")
600
+ return "\n".join(rows)
601
+
602
+ def payload(self, config: Config) -> dict[str, object]:
603
+ return {
604
+ "role": self.role,
605
+ "path": config.relative(self.path),
606
+ "config": self.config.as_posix(),
607
+ "blocks": list(self.blocks),
608
+ }
609
+
610
+
611
+ #: What each retrofit-able role unlocks, named in the report (RK1264). Not every role has one:
612
+ #: `improvements` is where a pointer resolves rather than a verb's destination, and a strategy
613
+ #: file is written by `section add --role strategy` like any other prose.
614
+ _ROLE_OPENS = {
615
+ DEFERRED_ROLE: "defer <id> --reason …",
616
+ STRATEGY_ROLE: "section add <anchor> --role strategy --title …",
617
+ "improvements": "section add <id> --title …",
618
+ "changelog": "ship <id> --why …",
619
+ }
620
+
621
+
622
+ @dataclass(frozen=True, slots=True)
623
+ class Measure:
624
+ """One length limit, and what the corpus does against it.
625
+
626
+ ``longest`` is reported beside ``over`` because the two answer different questions: how
627
+ many lines have to change, and whether the limit is off by a word or by a paragraph.
628
+
629
+ And beside both, **the unit** (RK437). An adopter reads this report to decide what to
630
+ declare, and `[limits]` is one table in three units — UTF-16 code units for the five
631
+ figures that refuse, words for `section`, code points for `prose`, which is a fill width
632
+ and not a gate. Unnamed, every row here read as the same kind of number, and the one that
633
+ is not is the one a consumer's own line-length check disagrees with: measured on this
634
+ repository, a paragraph of 87 code points is 90 units against a declared 88.
635
+ """
636
+
637
+ field: str
638
+ limit: int
639
+ longest: int
640
+ over: int
641
+ #: One of :data:`~roadkeep.kernel.schema.UTF16_UNITS`, :data:`~roadkeep.kernel.schema.WORDS` or
642
+ #: :data:`~roadkeep.kernel.schema.CODE_POINTS`. Defaulted to the one five of the seven measures
643
+ #: use, so the two that differ are the two that say so at construction.
644
+ unit: str = UTF16_UNITS
645
+ #: Whether anything refuses a value past :attr:`limit` (RK1348). `prose` is the one that
646
+ #: does not: `prose_width` is what `textwrap.fill` is handed in `criteria`, `governing` and
647
+ #: `scoping`, and `adopt` was the only reader treating it as a ceiling — counting 19 lines
648
+ #: `over` on a real file where no code among the 118 this gate emits mentions prose width
649
+ #: at all. The longest stays, being the useful half: what a section written here is filled
650
+ #: to, beside what this file does. The count is what a caller cannot act on, because there
651
+ #: is nothing to act against.
652
+ refuses: bool = True
653
+
654
+
655
+ @dataclass(frozen=True, slots=True)
656
+ class Scoped:
657
+ """The roadmap's *other* bullet, measured (RK139).
658
+
659
+ `adopt` read one of the roadmap's two kinds of line. Measured on Claude Code Tray: 18
660
+ lines over on `why` and `line` decided the adoption, and `lint` then produced nine
661
+ findings nobody had been shown — two bullets with no parseable lead, one lead at 72
662
+ against 60, six reasons over 200 with the worst at 1,100. A third of the work, after the
663
+ commitment.
664
+
665
+ Reported whether or not `[non_goals]` is declared, which is what ``governed`` says.
666
+ Opt-in makes the measurement *more* useful rather than less: the number an adopter needs
667
+ is what the limit would cost, and until this the only way to get it was to declare the
668
+ table and run the gate.
669
+ """
670
+
671
+ parsed: int
672
+ #: Bullets under the heading the grammar did not accept — `scoping.rejects`, which is the
673
+ #: same split :class:`~roadkeep.kernel.document.Reject` is: a count that omitted them would read
674
+ #: as complete.
675
+ unparsed: int
676
+ #: Bullets with at least one field over its limit. Per bullet and not per field, because
677
+ #: what an adopter is counting is edits.
678
+ over: int
679
+ measures: tuple[Measure, ...] = ()
680
+ governed: bool = False
681
+
682
+ @property
683
+ def changing(self) -> int:
684
+ """Bullets that would have to change. Counted apart from the task lines' total where
685
+ the project has not opted in, the gate reporting nothing there (see `Estimate`)."""
686
+ return self.unparsed + self.over
687
+
688
+
689
+ @dataclass(frozen=True, slots=True)
690
+ class Shape:
691
+ """One thing this file's ids spell that `[ids]` can declare, and how many spell it (RK110).
692
+
693
+ The same shape the prefix delta and `undeclared` already have — a count, and the key that
694
+ would close it — for the third declaration the estimate never named. It states what the
695
+ ids spell and never that the project should therefore declare it: whether a corpus that
696
+ pads *sometimes* wants a width is a judgement, and this tool has no model (L4).
697
+ """
698
+
699
+ #: The `[ids]` key: `pad` or `suffix`.
700
+ key: str
701
+ #: The value that key would take, written as TOML spells it — `2`, `true`.
702
+ value: str
703
+ count: int
704
+
705
+ @property
706
+ def declaration(self) -> str:
707
+ """The line an adopting project would write, ready to be read out of a report."""
708
+ return f"{self.key} = {self.value}"
709
+
710
+
711
+ @dataclass(frozen=True, slots=True)
712
+ class Doubling:
713
+ """What the across-files read found, and what it opened to find it (RK373).
714
+
715
+ Three answers off one walk, because each of them is only knowable there and each was
716
+ being restated somewhere else instead: RK372's contradiction and RK373's were both a fact
717
+ about *this* run written down as a rule about the configuration. The one that reads worst
718
+ is :attr:`opened` — the sentence it feeds exists to say which cross-file checks went
719
+ unmade, and derived from a constant it said a collision had been looked for in a file
720
+ nobody opened.
721
+ """
722
+
723
+ #: Every address more than one of the files read declares now, with their names.
724
+ addresses: tuple[tuple[str, tuple[str, ...]], ...] = ()
725
+ #: Those names that are paths rather than roles — see :attr:`Estimate.by_path`.
726
+ by_path: tuple[str, ...] = ()
727
+ #: The declared roles whose files this read opened, prose or not. What makes a file read
728
+ #: is that it was opened, and a changelog handed to `--with` was.
729
+ opened: tuple[str, ...] = ()
730
+
731
+
732
+ @dataclass(frozen=True, slots=True)
733
+ class Gain:
734
+ """One door declaring the format would open, that this project has not declared (RK1089).
735
+
736
+ Named as well as described, because the name is what a reader scans for and what a
737
+ payload keys on — and because the category has more members than anybody enumerated: the
738
+ store, a prose file, the non-goals, and a queue after them. A sentence alone is a row
739
+ that reads like every other sentence in a report full of numbers.
740
+ """
741
+
742
+ name: str
743
+ #: What the project has instead, and what to declare. Never what to *do* about it: the
744
+ #: estimate is what somebody runs before deciding, and deciding is theirs (L4).
745
+ because: str
746
+
747
+
748
+ @dataclass(frozen=True, slots=True)
749
+ class Estimate:
750
+ """What an existing backlog would cost to bring under the schema. Written by nothing."""
751
+
752
+ path: Path
753
+ prefix: str
754
+ #: True when the prefix was read off the file's own ids because nothing declared one.
755
+ #: Reported, never silent: a count taken under a guessed prefix is a different count.
756
+ #:
757
+ #: **Three states and not two** (RK485): declared, read off the ids, and *neither* —
758
+ #: the last being a file where no id parsed at all, which fell through to the schema
759
+ #: default. That one was reported as the second, so an ungoverned Shio changelog whose
760
+ #: every id is `SH` said *prefix RK (inferred from the ids)*, and a one-line file with
761
+ #: no id said it too. It is the state worth saying loudest, because the count under it
762
+ #: was taken against a prefix the file never mentions.
763
+ inferred: bool
764
+ parsed: int
765
+ conforming: int
766
+ #: What ``parsed`` counts. A backlog is measured in lines and a rationale file in
767
+ #: sections (RK99) — one command and not two, because the corpus an adopting project
768
+ #: has to measure is both files, and a second command would be a second set of numbers
769
+ #: to keep in step with these.
770
+ #: True where nothing declared a prefix **and** nothing was read: the schema's default
771
+ #: stands in, and the estimate below it is measured against a guess. Defaulted to False
772
+ #: because a rationale run reports no prefix at all — there is no third state there.
773
+ defaulted: bool = False
774
+ #: What declaring the format would give this project that it has not got (RK1087,
775
+ #: RK1089). A category rather than a fourth measurement: every other row answers what
776
+ #: this *file* would cost, and these answer what the *project* is missing. Empty where a
777
+ #: project declared the target and has them all, and empty where none declared it at all
778
+ #: — there, every gain is true and useless.
779
+ gains: tuple[Gain, ...] = ()
780
+ unit: str = "line"
781
+ #: Whether the file was read in the **ledger** role — the flag a door has to carry to
782
+ #: reproduce this reading (RK1147). :attr:`unit` cannot say it: a backlog and a changelog
783
+ #: are both measured in lines, and a ledger is measured under `[limits.changelog]` and
784
+ #: `[rules.changelog]` (RK76), so the same bytes re-read without `--ledger` are a different
785
+ #: measurement. Published for the same reason :attr:`defaulted` is — a consumer inferring
786
+ #: it from `unit` would be inferring it wrongly half the time.
787
+ ledger: bool = False
788
+ #: The scheme the pointers and anchors were read under (RK44). Reported because it
789
+ #: decides what was read at all: under the wrong one a file of 151 sections yields 0.
790
+ ref_scheme: str = "id"
791
+ #: Marker-bearing bullets the grammar refused, grouped by reason, worst first.
792
+ rejects: tuple[tuple[str, int], ...] = ()
793
+ #: Schema violations per code, worst first — the same codes `lint` prints.
794
+ codes: tuple[tuple[str, int], ...] = ()
795
+ measures: tuple[Measure, ...] = ()
796
+ #: Tokens sitting where a marker sits that this project does not declare, with counts:
797
+ #: the `[markers]` table the adopting project has to write.
798
+ undeclared: tuple[tuple[str, int], ...] = ()
799
+ #: What the ids spell that `[ids]` does not declare (RK110) — the third config delta,
800
+ #: beside the prefix and the markers. Without it Dumont's nine `id.format` findings
801
+ #: arrived as nine defects rather than as one unwritten key, and confirming that
802
+ #: `pad = 2` cleared them and nothing else meant diffing two lint runs by hand.
803
+ id_shape: tuple[Shape, ...] = ()
804
+ #: Every prefix the ids actually spell, worst first. More than one is a backlog
805
+ #: numbered by track, or one that absorbed another — `prefix` takes the list (RK74),
806
+ #: and which of the two this is, is the reader's call and never the tool's.
807
+ prefixes: tuple[tuple[str, int], ...] = ()
808
+ #: Every scheme the **pointers** actually spell, worst first (RK285) — the same fact as
809
+ #: :attr:`prefixes` one field over, and reported the same way. Shio's roadmap read
810
+ #: `0 conform, 65 would change` under the default and `63 conform, 2 would change` under
811
+ #: `--ref-scheme outline`, with `ref.mismatch` on every line as the only signal and no
812
+ #: sentence naming the flag — while the prefix half of the same misreading had one.
813
+ schemes: tuple[tuple[str, int], ...] = ()
814
+ #: The `[ledger]` declaration this file's refused lines would parse under, with how many
815
+ #: (RK286). The count is the half the reason cannot give: naming the slots tells an adopter
816
+ #: what to write, and this tells them what writing it recovers — the number RK18 says is
817
+ #: only worth having *before* the commitment, and which otherwise cost a scratch config.
818
+ ledger_shape: tuple[tuple[str, int], ...] = ()
819
+ #: The governed files this estimate did **not** read (RK291). RK290 made the estimate and
820
+ #: the gate agree on everything one file decides, so what is left is the checks that
821
+ #: resolve across files — a dep satisfied by the changelog, a pointer resolved in the
822
+ #: rationale file. Running them from one file is what must not happen: pointed at Shio's
823
+ #: roadmap without its changelog, a deps pass reports 82 unresolved deps on a backlog
824
+ #: whose deps all resolve. Naming what was out of reach is the other act, and the one
825
+ #: an adopter can take — handing `adopt` these files is what the sentence implies.
826
+ unopened: tuple[str, ...] = ()
827
+ #: Whether the target is one of the files this project declares (RK292). It usually is not
828
+ #: — `adopt` reads a file that is "by definition not one of them yet" — and that decides
829
+ #: what :attr:`unopened` can mean: siblings worth handing over where the target is declared,
830
+ #: and nothing nameable where the config belongs to another project entirely.
831
+ declared: bool = False
832
+ #: Every family the measurement was taken under. One unless the caller passed a list:
833
+ #: inference stays at the dominant spelling, because promoting the rest would be the
834
+ #: tool deciding a foreign id is a second track (L4).
835
+ families: tuple[str, ...] = ("RK",)
836
+ blocks: tuple[str, ...] = ()
837
+ #: Lines whose schema rendering differs from how they are written. Not a defect to fix
838
+ #: here — it is the reason the tool would refuse to write the file at all (L3).
839
+ non_canonical: int = 0
840
+ #: The non-goals list, measured beside the task lines (RK139) — None on a run over a
841
+ #: ledger or a rationale file, neither of which holds one. Its own count and not part of
842
+ #: ``changing`` where the project has not opted in: the gate reports nothing there, and a
843
+ #: headline that added the cost of a rule nobody has adopted would be measuring a
844
+ #: different commitment from the one being taken.
845
+ non_goals: Scoped | None = None
846
+ #: Rows of a Markdown table filed under a block heading (RK98). A backlog kept as rows
847
+ #: parses as nothing at all — no entry and no reject — so without this the headline is
848
+ #: the one an empty file gets, and the estimate that decides whether to adopt reports
849
+ #: nothing to change about a file it has not read.
850
+ tabular: int = 0
851
+ #: Every address more than one prose file declares **now**, with the roles (RK347) — the
852
+ #: one finding a per-file estimate cannot reach by construction, because a doubling only
853
+ #: exists across two files. Measured on a project whose `IMPROVEMENTS.md` and `STRATEGY.md`
854
+ #: both open at `I` and both declare a `III`: four `section.ambiguous` on the first run of
855
+ #: the gate, against two files this estimate had called conforming. Empty where the target
856
+ #: is not declared here (RK292) — there the siblings belong to another project — and empty
857
+ #: on a backlog, which holds lines and not headings.
858
+ ambiguous: tuple[tuple[str, tuple[str, ...]], ...] = ()
859
+ #: The files in this run's set that were read **by path** rather than through a prose
860
+ #: role, by the name :attr:`ambiguous` calls them (RK371). Since RK369 a file is named the
861
+ #: truest way this project can name it, and a run given `--with` gets one of each: the
862
+ #: printed line shows which is which by sitting in a sentence, and `--json` — read by the
863
+ #: caller who took it *not* to open a file (L5) — had a `roles` key holding filenames
864
+ #: `[files]` does not answer, with no field saying the lookup would never work. Over the
865
+ #: set that was read and not over the collisions, because how a run named a file is a fact
866
+ #: about the run: it is the same answer when nothing collided at all.
867
+ #:
868
+ #: What it does **not** say is that the project has no claim on the file (RK372). A
869
+ #: changelog handed to `--with` is declared here and still read by path, having no outline
870
+ #: to collide in — and calling that ungoverned put the contradiction in the report, beside
871
+ #: an `unopened` that had already counted the same file as this project's. Recorded and
872
+ #: never resolved away either way: inventing a role for a file this project does not govern
873
+ #: is the answer RK292 keeps out of the report.
874
+ by_path: tuple[str, ...] = ()
875
+ #: The lines this file holds, and how many of them were read in **any** shape at all —
876
+ #: as an entry, a reject, a table row, a plain bullet or a heading (RK376). RK98's rule at
877
+ #: the far end of itself: :attr:`tabular` and :attr:`listed` stop a backlog written in a
878
+ #: shape nothing reads from answering the number an empty file answers, and a file that is
879
+ #: not a backlog in any shape walked past both — a fourteen-line `README.md` and a roadmap
880
+ #: with one heading and no tasks reporting the same `0 conform, 0 would change`, on the run
881
+ #: where a typo puts the caller least able to check it.
882
+ #:
883
+ #: Two numbers because one of them alone is the ambiguity: zero read against a file with
884
+ #: bulk is a different answer from zero against a file with none, and only the second means
885
+ #: what the headline says. Reported and deliberately **not** added to :attr:`changing` — how
886
+ #: many lines would have to change is an answer about a backlog becoming conforming, and
887
+ #: this file may be no backlog at all. Counting what was read against what is there is a
888
+ #: measurement; concluding somebody named the wrong file is an opinion (L4).
889
+ lines: int = 0
890
+ recognised: int = 0
891
+ #: What this file holds in a shape the format has no reader for, in whatever :attr:`unit`
892
+ #: is being counted: plain list items under a block heading in a backlog (RK279), and
893
+ #: headings with prose and no anchor in a rationale file (RK281). One field because it is
894
+ #: one idea and it lands in :attr:`changing` the same way — a backlog kept as `- [ ] …`
895
+ #: priced 2 as a table and 0 as a list, and a `DESIGN.md` answered 0 sections, both being
896
+ #: the zero RK98 forbids. The *sentence* differs by unit; the number does not.
897
+ listed: int = 0
898
+ #: What connecting to this project's MCP server would cost a session, in characters at the
899
+ #: handshake (RK1100) — 0 where the surface could not be measured, which is no adoption
900
+ #: decision and only a reader that could not compose the schema.
901
+ #:
902
+ #: The one number here that is **not** about the file. Every other row prices what this
903
+ #: backlog would have to change; this prices what the tool arrives carrying, and RK1097
904
+ #: measured it as a fact about the package rather than about the project: roadkeep, Shio
905
+ #: and Turing serve the same 52 tools within 1.4% of each other. So it is knowable before
906
+ #: adoption and is the same for everybody, which is exactly the figure an estimate that
907
+ #: names four gains and no costs was missing.
908
+ #:
909
+ #: Not added to anything and deliberately not weighed against the gains (L4): it is paid
910
+ #: once at connect where a resident file is paid every turn, so the two do not sum, and
911
+ #: whether it is worth it is the adopter's call.
912
+ surface: int = 0
913
+
914
+ @property
915
+ def changing(self) -> int:
916
+ """Lines that would have to change: everything that does not conform *or* read.
917
+
918
+ Table rows and plain list items count here for the same reason rejects do — none is
919
+ an entry, and a number that only added up what parsed would be smallest on the file
920
+ furthest from the format.
921
+
922
+ Non-goals join it only where the project **declared** them governed (RK139), because
923
+ there they are lines the gate will fail on. Where it has not, they are measured and
924
+ reported and left out of this number: the estimate would otherwise price a rule
925
+ nobody has adopted into the decision about adopting a different one.
926
+ """
927
+ scoped = self.non_goals.changing if self.non_goals and self.non_goals.governed else 0
928
+ return (
929
+ self.parsed
930
+ - self.conforming
931
+ + sum(count for _, count in self.rejects)
932
+ + self.tabular
933
+ + self.listed
934
+ + scoped
935
+ )
936
+
937
+
938
+ # -- init ------------------------------------------------------------------
939
+
940
+
941
+ def init(
942
+ root: str | Path = ".",
943
+ *,
944
+ prefix: str | Sequence[str] = "RK",
945
+ blocks: Sequence[str] = ("A",),
946
+ roles: Sequence[str] = SCAFFOLD_ROLES,
947
+ ) -> Created:
948
+ """Write `roadkeep.toml` and the files it declares, or write nothing.
949
+
950
+ ``blocks`` are heading suffixes: ``"A"`` becomes ``## Block A`` and ``"A — The model"``
951
+ becomes ``## Block A — The model``. They are mirrored into every file written, because the
952
+ ledger and the prose files are filed under the same headings the roadmap is and a write
953
+ never invents one (RK37).
954
+
955
+ ``roles`` is which files to write, and two of them are opt-in. The strategy file (RK1186):
956
+ every reader of a pointer has resolved against it since RK172, and this was the one command
957
+ that could not create it — so a project wanting a document *above* the task line hand-edited
958
+ the configuration and made the file, which are the two steps a scaffold exists to remove.
959
+ And the deferred store (RK1259), for the same two steps read out by a different door:
960
+ `defer` refuses where no store is declared and does not scaffold one on the way past, so
961
+ until this the remedy was a toml key and a skeleton no verb offered to write — arriving,
962
+ every time, with a pause reason already composed.
963
+ """
964
+ base = Path(root).resolve()
965
+ existing = _configured(base)
966
+ if existing is not None:
967
+ raise AlreadyConfigured(existing)
968
+
969
+ # Raises on a prefix this format cannot carry, and on a set of families that would
970
+ # read one id two ways (RK74).
971
+ schema = Schema(prefixes=_families(prefix))
972
+ labels = tuple(_label(block, schema) for block in blocks)
973
+ if not labels:
974
+ raise UnreadableBlock("")
975
+ # The check of the *set*, which per-value validation cannot make (RK390): `_label` is right
976
+ # about each one and two of them being the same label is a fact about neither.
977
+ seen: set[str] = set()
978
+ for label in labels:
979
+ if label in seen:
980
+ raise RepeatedBlock(label)
981
+ seen.add(label)
982
+
983
+ paths = {role: base / _DEFAULT_FOR[role] for role in roles}
984
+ text = render_config(schema, {role: _DEFAULT_FOR[role] for role in roles})
985
+ _verify(text, schema, base, paths)
986
+
987
+ target = base / CONFIG_NAME
988
+ bodies = {role: _scaffold(role, blocks, schema) for role in roles}
989
+ clashes = [path for path in (target, *paths.values()) if path.exists()]
990
+ if clashes:
991
+ raise WouldOverwrite(clashes, base)
992
+ # `exists` answers whether a write would clobber, and not whether it can happen at all
993
+ # (RK392): a `docs` that is a file is a `docs/ROADMAP.md` no write reaches, and the
994
+ # question was never asked. Knowable in advance, so it is decided up here with the rest.
995
+ blocked = [(path, parent) for path in paths.values() if (parent := blocking(path))]
996
+ if blocked:
997
+ raise BlockedParent(blocked, base)
998
+
999
+ # Everything that can be decided in advance is decided above this line, which is what
1000
+ # makes the all-or-nothing claim a property of the order rather than a hope. What cannot
1001
+ # be is a write the filesystem refuses — a permission, a full disk — and the directories
1002
+ # go first so that failure lands before the configuration rather than after it: an empty
1003
+ # `docs/` is a tree nobody has to recognise, and a `roadkeep.toml` declaring three files
1004
+ # that do not exist is the half-scaffolded project this order exists to prevent.
1005
+ for path in paths.values():
1006
+ path.parent.mkdir(parents=True, exist_ok=True)
1007
+ target.write_text(text, encoding="utf-8", newline="")
1008
+ written: list[Path] = []
1009
+ for role in roles:
1010
+ path = paths[role]
1011
+ path.write_text(bodies[role], encoding="utf-8", newline="")
1012
+ written.append(path)
1013
+ return Created(config=target, files=tuple(written), blocks=labels)
1014
+
1015
+
1016
+ def declare(
1017
+ config: Config, role: str, path: str | None = None
1018
+ ) -> Retrofitted:
1019
+ """Add one role to a configured project's `[files]`, and write its file (RK1264).
1020
+
1021
+ The door `init` could not be. `[files]` is written once, by the one command that refuses to
1022
+ run twice, so every role a project declined at scaffold time — `strategy` as much as
1023
+ `deferred` — was one it retrofitted by hand-editing configuration this tool otherwise owns.
1024
+ `adopt` reads and estimates and writes no config by design (RK1040) and `install` wires
1025
+ surfaces rather than roles, so there was no third door: on a configured tree `init
1026
+ --deferred` answers :class:`AlreadyConfigured`, and the remedy was the toml key and the
1027
+ skeleton by hand — which over MCP is the hand edit the guard denies and no edit at all.
1028
+
1029
+ **`block add` is the shape**, and deliberately: the file is written with the headings the
1030
+ project's other files already carry, read off the roadmap and never composed here, so a
1031
+ project spelling `### Fase 2 - Execução` gets those and not this module's punctuation. A
1032
+ role whose file arrived with no headings is a role every `add`, `ship` and `section add`
1033
+ then refuses with "no heading declares", which is a scaffold handing over a deadlock.
1034
+
1035
+ Nothing is invented about *which* roles: :data:`~roadkeep.config.ROLES` is the set, and one
1036
+ already declared is refused rather than repointed — moving a governed file is not this
1037
+ write, and a second key for one role is two paths where every reader expects one.
1038
+
1039
+ The file lands **before** the key, which is `namespaced`'s order and its reason: a file
1040
+ written whose key never landed is an untracked Markdown file and the state the project was
1041
+ already in, while a key declared over a file that does not exist is `file.missing` on the
1042
+ next lint — so the failure falls on the side that changes nothing.
1043
+ """
1044
+ if role not in ROLES:
1045
+ raise NoSuchRole(role, ROLES)
1046
+ if config.has(role):
1047
+ raise RoleDeclared(role, config.relative(config.path(role)))
1048
+ if config.source is None:
1049
+ raise Unconfigured(config.root)
1050
+ target = config.locate(path or _DEFAULT_FOR[role])
1051
+ if target.exists():
1052
+ raise WouldOverwrite([target], config.root)
1053
+ if (parent := blocking(target)) is not None:
1054
+ raise BlockedParent([(target, parent)], config.root)
1055
+ # Refused before anything is written, because a path TOML cannot carry is a key that would
1056
+ # read back as something else — the check `_quote` makes for `init`, made here for the one
1057
+ # value this write puts in a file.
1058
+ row = f"{role} = {_quote(config.relative(target))}\n"
1059
+ declaring = _mirrored(config)
1060
+ body = "\n".join(
1061
+ [f"# {_TITLES[role]}", "", *(f"{'#' * one.level} {one.text}\n" for one in declaring)]
1062
+ )
1063
+ target.parent.mkdir(parents=True, exist_ok=True)
1064
+ target.write_text(body, encoding="utf-8", newline="")
1065
+ config.source.write_text(_with_role(config.source, row), encoding="utf-8", newline="")
1066
+ return Retrofitted(
1067
+ role=role,
1068
+ path=target,
1069
+ config=config.source,
1070
+ blocks=tuple(one.label or "" for one in declaring),
1071
+ )
1072
+
1073
+
1074
+ @dataclass(frozen=True, slots=True)
1075
+ class Opened:
1076
+ """What `declare <table>` wrote: one opt-in table, and nothing else (RK1328)."""
1077
+
1078
+ table: str
1079
+ config: Path
1080
+
1081
+ def stated(self, config: Config) -> str:
1082
+ from roadkeep.provenance import invocation # noqa: PLC0415 - RK260
1083
+
1084
+ return chr(10).join(
1085
+ [
1086
+ f"declared [{self.table}] {self.config.name}",
1087
+ # The verb this table exists for, which is the question a caller has next and
1088
+ # the one the refusal that sent them here was about — `declare`'s own rule.
1089
+ f"opens `{invocation()} {_TABLE_OPENS[self.table]}`",
1090
+ f"stage git add -- {self.config.name}",
1091
+ ]
1092
+ )
1093
+
1094
+ def payload(self, config: Config) -> dict[str, object]:
1095
+ return {
1096
+ "table": self.table,
1097
+ "config": self.config.as_posix(),
1098
+ "opens": _TABLE_OPENS[self.table],
1099
+ "wrote": [config.relative(self.config)],
1100
+ }
1101
+
1102
+
1103
+ #: The verb each opt-in table gates, which is what a caller came here to run.
1104
+ _TABLE_OPENS = {
1105
+ "non_goals": "non-goal add --lead … --why …",
1106
+ "criteria": "criterion add --block <x> --lead … --why …",
1107
+ }
1108
+
1109
+
1110
+ def declare_table(config: Config, table: str) -> Opened:
1111
+ """Open one opt-in table on a configured project (RK1328).
1112
+
1113
+ :func:`declare`'s other axis, and the same shape read one table over: *this file, one key,
1114
+ refused where it is already declared*. RK1313 closed this for a project being scaffolded —
1115
+ `init` writes `[criteria]` empty — and named the half it left open, which is every project
1116
+ already past it. Measured on this repository, declaring `[criteria]` for RK1323: the table
1117
+ went in by hand, because no verb opened one.
1118
+
1119
+ A **third verb was the other shape and the surface decided it**: one more served tool costs
1120
+ about 800 characters against 87 of headroom under `[tools] session`, which would be a third
1121
+ ceiling re-argued in one session to hold a verb that answers what an existing one already
1122
+ does. So the argument widens rather than the list.
1123
+
1124
+ **Empty and nothing else.** What a project says by writing the table is *that* the list is
1125
+ a schema; `lead` and `why` are what it may then tune, and `govern` is the verb for that. A
1126
+ number written here would read as a limit somebody chose, which is `[ids] pad`'s argument
1127
+ and `init`'s for the same table.
1128
+ """
1129
+ if table not in OPT_IN:
1130
+ raise NoSuchTable(table, OPT_IN)
1131
+ if getattr(config, table) is not None:
1132
+ raise TableDeclared(table)
1133
+ if config.source is None:
1134
+ raise Unconfigured(config.root)
1135
+ text = config.source.read_text(encoding="utf-8")
1136
+ # Appended, and never serialised: a `tomllib` round-trip drops the comments a scaffolded
1137
+ # config is mostly made of (`_with_role`'s rule). At the end because an opt-in table has no
1138
+ # sibling to sit beside — every other insertion here belongs *to* a table that exists.
1139
+ blank, line = chr(10) * 2, chr(10)
1140
+ separator = "" if text.endswith(blank) else (line if text.endswith(line) else blank)
1141
+ config.source.write_text(
1142
+ f"{text}{separator}[{table}]{line}", encoding="utf-8", newline=""
1143
+ )
1144
+ return Opened(table=table, config=config.source)
1145
+
1146
+
1147
+ def _mirrored(config: Config) -> tuple[Heading, ...]:
1148
+ """The block headings this project's roadmap carries, for a file that has none of its own.
1149
+
1150
+ Reused verbatim — the level and the text the roadmap wrote — which is what keeps this from
1151
+ being a second spelling of a heading (`blocking._heading`'s rule, arrived at from the other
1152
+ side): there is no own heading in a file that does not exist yet, so the roadmap's is the
1153
+ only honest answer to how this project spells one.
1154
+
1155
+ Empty where the roadmap declares none, which is a project whose first `block add` has not
1156
+ happened — and then the new file is a title, exactly as `init` would have left it.
1157
+ """
1158
+ return tuple(one for one in config.document("roadmap").headings if one.label)
1159
+
1160
+
1161
+ def _with_role(source: Path, row: str) -> str:
1162
+ """This project's `roadkeep.toml` with one `[files]` key added, byte for byte otherwise.
1163
+
1164
+ A targeted insertion and never a serialiser, which is `sections._with_namespace`'s rule and
1165
+ `bump_version`'s before it: a `tomllib` round-trip drops the comments a scaffolded config is
1166
+ mostly made of, and rewriting somebody's file to add a line is the destructive formatting L3
1167
+ refuses one layer down.
1168
+
1169
+ Placed after the table's **last key** rather than before its first or after the whole table:
1170
+ the first would put a retrofitted role above the roadmap, and the last would land it under
1171
+ whatever table follows — the one way this write can be silently wrong.
1172
+ """
1173
+ text = source.read_text(encoding="utf-8")
1174
+ lines = text.splitlines(keepends=True)
1175
+ at, last = None, None
1176
+ for index, line in enumerate(lines):
1177
+ stripped = line.strip()
1178
+ if stripped.startswith("["):
1179
+ # The table this key belongs to, and then the next one, which ends the search: a
1180
+ # `[files]` appearing twice is a config `tomllib` itself refuses.
1181
+ at = index if stripped == "[files]" else at
1182
+ if at is not None and index > at:
1183
+ break
1184
+ elif at is not None and index > at and "=" in stripped:
1185
+ last = index
1186
+ if at is None:
1187
+ raise ValueError(
1188
+ f"{source.as_posix()} declares no `[files]` table, so there is no place for a "
1189
+ f"role: a configured project has one, and this file may have been hand-edited"
1190
+ )
1191
+ into = (last if last is not None else at) + 1
1192
+ return "".join([*lines[:into], row, *lines[into:]])
1193
+
1194
+
1195
+ def render_config(schema: Schema, paths: Mapping[str, str]) -> str:
1196
+ """The configuration as TOML, taken from a live :class:`Schema` and not a template.
1197
+
1198
+ Every value here is read off the object the tool validates with, so a default that
1199
+ changes changes the scaffold in the same commit. The comments name each limit's *unit*,
1200
+ which is the one thing the key name does not say — a `section` in words and a `line` in
1201
+ characters are not the same kind of number.
1202
+ """
1203
+ # One family is written as the string every other project has; several as the list a
1204
+ # backlog numbered by track needs (RK74), in the order they were declared.
1205
+ prefix = (
1206
+ _quote(schema.prefix)
1207
+ if len(schema.prefixes) == 1
1208
+ else "[" + ", ".join(_quote(p) for p in schema.prefixes) + "]"
1209
+ )
1210
+ lines = [
1211
+ f"prefix = {prefix}",
1212
+ "",
1213
+ "# how a rationale section is addressed: \"id\" derives the pointer from the",
1214
+ "# task's own id, \"outline\" keeps a hand-numbered anchor",
1215
+ f"ref_scheme = {_quote(schema.ref_scheme)}",
1216
+ "",
1217
+ "# what jumps the queue, in order: an id or a \"Block X\", and nothing else",
1218
+ "priority = []",
1219
+ "",
1220
+ "[files]",
1221
+ ]
1222
+ # Every role the caller asked to scaffold, in the order this module declares them
1223
+ # (RK1186). `SCAFFOLD_ROLES` alone was the same list twice — what a bare `init`
1224
+ # writes and what the config may declare — and `--strategy` made the second one
1225
+ # wrong: the file was written and the key was not, which `_verify` refuses whole.
1226
+ written = (*SCAFFOLD_ROLES, STRATEGY_ROLE, DEFERRED_ROLE)
1227
+ lines += [f"{role} = {_quote(paths[role])}" for role in written if role in paths]
1228
+ lines += [
1229
+ "",
1230
+ "[limits]",
1231
+ # RK437: the unit, in the file the numbers are declared in. This table is three of
1232
+ # them, and a scaffold that wrote "characters" over the first group left the reader
1233
+ # to assume the same word covered the two below it.
1234
+ "# characters, counted in UTF-16 code units — the stricter of the two counts, so a",
1235
+ "# line these accept is one a gate written in Java, C# or JavaScript accepts too",
1236
+ f"symptom = {schema.symptom_max}",
1237
+ f"why = {schema.why_max}",
1238
+ f"line = {schema.line_max}",
1239
+ "",
1240
+ "# a section is prose, so its budget is words; prose is the width one is filled to,",
1241
+ "# counted in code points — it is a wrapping column and nothing refuses it",
1242
+ f"section = {schema.section_max}",
1243
+ f"prose = {schema.prose_width}",
1244
+ "",
1245
+ "[markers]",
1246
+ f"open = [{', '.join(_quote(marker) for marker in schema.markers)}]",
1247
+ f"shipped = {_quote(schema.shipped_marker)}",
1248
+ f"retired = {_quote(schema.retired_marker)}",
1249
+ "",
1250
+ "[claims]",
1251
+ # Written even at its default, and with the unit in the comment, for the reason every
1252
+ # limit above carries one: minutes is the one thing `held` does not say, and a project
1253
+ # that meant seconds is refused rather than given a claim nobody would wait out (RK151).
1254
+ "# minutes a claim on a line reads as held, before a later caller steps over it",
1255
+ f"held = {CLAIM_HELD}",
1256
+ "",
1257
+ # Empty and declared, which `_scope` documents as the shortest way to opt in: what a
1258
+ # project says by writing the table is *that* the list is a schema, and `lead` and
1259
+ # `why` are what it may then tune (RK1040). Written here and nowhere else — RK70 made
1260
+ # the list opt-in because two corpora wrote theirs as free prose years before this
1261
+ # grammar, and that is `adopt`'s case: a `## Non-goals` this scaffold just emptied has
1262
+ # no prose to report on, and leaving it ungoverned refused the one verb that fills it.
1263
+ "# the roadmap's other list: declared at all means governed, and `lead` and `why`",
1264
+ "# are the two limits a bullet is held to — 80 and 320 characters unless set here",
1265
+ "[non_goals]",
1266
+ "",
1267
+ # The positive twin, empty and declared for the reason above it (RK1265, RK1313).
1268
+ # RK1040 settled the shape and this table arrived after it, so a tree `init` had just
1269
+ # created answered `criterion add --block A` with *roadkeep.toml declares no
1270
+ # [criteria]* — and the remedy that refusal names is a hand edit to configuration this
1271
+ # tool owns, which is what `declare` was built to remove (RK1264) and which over MCP is
1272
+ # not an edit at all. Measured on such a tree, 2026-08-23.
1273
+ "# what must be **true** for a block to be finished, where the list above says what is",
1274
+ "# not built — the same two limits, declared separately: a project may govern one list",
1275
+ "# and not the other",
1276
+ "[criteria]",
1277
+ ]
1278
+ shape = [
1279
+ # Same rule as the heading word and the `[ledger]` absences: only what differs from
1280
+ # the shape every project starts with, because `pad = 1` reads as a width somebody
1281
+ # chose rather than as the unpadded id nobody had to (RK106).
1282
+ line
1283
+ for declared, line in (
1284
+ (schema.id_pad != 1, f"# the width the number is zero-filled to\npad = {schema.id_pad}"),
1285
+ (schema.id_suffix, "# a split task keeps its number and takes a letter\nsuffix = true"),
1286
+ )
1287
+ if declared
1288
+ ]
1289
+ if shape:
1290
+ lines += ["", "[ids]", *shape]
1291
+ if schema.heading_word != DEFAULT_HEADING_WORD:
1292
+ # Only when it differs, for the same reason the `[ledger]` absences below are only
1293
+ # written when they are absences: `word = "Block"` reads as a decision about a word
1294
+ # nobody chose.
1295
+ lines += [
1296
+ "",
1297
+ "[headings]",
1298
+ "# the word this project files work under",
1299
+ f"word = {_quote(schema.heading_word)}",
1300
+ ]
1301
+ absent = [
1302
+ # Only what is false: a default written out reads as a decision somebody made about
1303
+ # a slot the file carries anyway (RK43, RK48).
1304
+ line
1305
+ for present, line in (
1306
+ (
1307
+ schema.ledger_marker,
1308
+ # What the declaration costs, said where the choice is made (RK214) — and
1309
+ # since RK125 that cost is one line's worth: a departure is the one status
1310
+ # such a file does not state, so it is the one line that carries a marker.
1311
+ "# every entry in it shipped, so no line repeats it\n"
1312
+ f"# (a retirement still carries {schema.retired_marker}: a departure is "
1313
+ f"not a shipment)\n"
1314
+ "marker = false",
1315
+ ),
1316
+ (schema.ledger_symptom, "# its lines are `- **id** — <prose>`, with no symptom slot\nsymptom = false"),
1317
+ )
1318
+ if not present
1319
+ ]
1320
+ if absent:
1321
+ lines += ["", "[ledger]", *absent]
1322
+ # The vocabulary, **commented** and not empty (RK1297, RK1313), which is the shape `[ids]`,
1323
+ # `[headings]` and `[ledger]` above are already written in: only what a project departs
1324
+ # from what every project starts with. `[criteria]` is an opt-in, so an empty table is the
1325
+ # whole of it; this is a *list of words*, and `declared = []` governs nothing — it changes
1326
+ # only which refusal the author reads. What was missing was never the table but the fact
1327
+ # that the axis exists: `add --requires hardware` on a fresh tree answered `requires.unknown`
1328
+ # about a table the file does not carry, and nothing said the file could carry one.
1329
+ lines += [
1330
+ "",
1331
+ "# what has to be *present* to finish a line — hardware, an account, somebody's time.",
1332
+ "# Not a dep: `pick` offers a line needing one only to a caller that says it has it,",
1333
+ "# with `--have`. Uncomment and name your own; an undeclared word is refused.",
1334
+ '# [requirements]',
1335
+ '# declared = ["hardware"]',
1336
+ ]
1337
+ lines.append("")
1338
+ return "\n".join(lines)
1339
+
1340
+
1341
+ def _declares(path: Path) -> bool:
1342
+ """Whether this **file** is a declaration of this format (RK375).
1343
+
1344
+ The reader both doors into it share. `init` refuses against a declaration and `adopt`
1345
+ refuses a path that is one, and they disagreed: this asked whether a `pyproject.toml`
1346
+ carries `[tool.roadkeep]`, while :class:`NotACorpus` asked only for the filename — so the
1347
+ newer refusal reached one of the two files and a pyproject that configures this tool was
1348
+ still measured as an empty backlog, which is the reading RK374 exists to stop.
1349
+
1350
+ Two files and two rules, because they are not the same claim. A `roadkeep.toml` **is** the
1351
+ declaration by existing, whatever is in it; a `pyproject.toml` is a file most repositories
1352
+ have and this format only sometimes lives in, so the table is what decides. Unparseable is
1353
+ not a declaration — a caller who pointed here at a broken TOML has a different problem, and
1354
+ guessing it configures this tool would refuse a file on a hunch.
1355
+ """
1356
+ if path.name == CONFIG_NAME:
1357
+ return True
1358
+ if path.name != PYPROJECT:
1359
+ return False
1360
+ try:
1361
+ with path.open("rb") as handle:
1362
+ data = tomllib.load(handle)
1363
+ except (OSError, tomllib.TOMLDecodeError):
1364
+ return False
1365
+ return "roadkeep" in data.get("tool", {})
1366
+
1367
+
1368
+ def _configured(base: Path) -> Path | None:
1369
+ """A declaration *at this root*. An ancestor's is shadowed, not clobbered."""
1370
+ return next(
1371
+ (
1372
+ candidate
1373
+ for name in (CONFIG_NAME, PYPROJECT)
1374
+ if (candidate := base / name).is_file() and _declares(candidate)
1375
+ ),
1376
+ None,
1377
+ )
1378
+
1379
+
1380
+ def _verify(text: str, schema: Schema, base: Path, paths: Mapping[str, Path]) -> None:
1381
+ """Parse the rendered config back and refuse unless it means what it was built from.
1382
+
1383
+ The same test the files get (L3), applied to the one file that decides how they are
1384
+ read: a scaffold whose config does not round-trip through `Config.parse` would
1385
+ configure the project as something other than what `init` was asked for, and the
1386
+ author would find out on the first `add`.
1387
+ """
1388
+ parsed = Config.parse(tomllib.loads(text), root=base)
1389
+ if parsed.schema != schema:
1390
+ raise ValueError(
1391
+ f"the rendered configuration does not read back as the schema it was built "
1392
+ f"from and nothing was written: {parsed.schema!r}"
1393
+ )
1394
+ if parsed.paths != {role: path.resolve() for role, path in paths.items()}:
1395
+ raise ValueError(
1396
+ "the rendered configuration declares different paths than were scaffolded "
1397
+ "and nothing was written"
1398
+ )
1399
+
1400
+
1401
+ def _label(block: str, schema: Schema) -> str:
1402
+ """The label a `--block` value declares, or a refusal — under this project's word.
1403
+
1404
+ **One heading and the whole value** (RK390). This used to read the label off the first
1405
+ heading it found and return, which is true of `A` and true of `A\\nB` — where the parse
1406
+ also produced a second line, and the scaffold then wrote it out as prose under a heading
1407
+ that had, correctly, parsed. What refuses it is the line count and not a hunt for
1408
+ newlines: the claim being made is that this value is one heading, and a value that came
1409
+ back as two lines is not, whatever split it.
1410
+ """
1411
+ document = Document.parse(f"## {schema.block_named(block.strip())}\n", schema)
1412
+ label = document.headings[0].label if document.headings else None
1413
+ if not label:
1414
+ raise UnreadableBlock(block)
1415
+ if len(document.lines) != 1:
1416
+ raise UnreadableBlock(block, beyond=True)
1417
+ return label
1418
+
1419
+
1420
+ def _scaffold(role: str, blocks: Sequence[str], schema: Schema) -> str:
1421
+ """One file: a title, the block headings, and — for the roadmap — where non-goals go."""
1422
+ lines = [f"# {_TITLES[role]}", ""]
1423
+ for block in blocks:
1424
+ lines += [f"## {schema.block_named(block.strip())}", ""]
1425
+ if role == "roadmap":
1426
+ # `brief` prints these with every task (RK29), so the heading exists from the
1427
+ # start: an author who has to create it first is an author who writes none.
1428
+ lines += ["## Non-goals", ""]
1429
+ return "\n".join(lines)
1430
+
1431
+
1432
+ def _families(prefix: str | Sequence[str]) -> tuple[str, ...]:
1433
+ """One family or a list of them, as :class:`Schema` takes it (RK74).
1434
+
1435
+ A bare string stays one family rather than becoming a list of its letters, which is
1436
+ the one thing a `str`-is-a-`Sequence` reading of this argument would silently do.
1437
+ """
1438
+ return (prefix,) if isinstance(prefix, str) else tuple(prefix)
1439
+
1440
+
1441
+ def _quote(value: str) -> str:
1442
+ """A TOML basic string, or a refusal — this never guesses at an escape."""
1443
+ if '"' in value or "\\" in value or "\n" in value:
1444
+ raise ValueError(f"cannot be written to TOML without escaping: {value!r}")
1445
+ return f'"{value}"'
1446
+
1447
+
1448
+ # -- adopt -----------------------------------------------------------------
1449
+
1450
+
1451
+ def adopt(
1452
+ config: Config,
1453
+ path: str | Path,
1454
+ *,
1455
+ prefix: str | Sequence[str] | None = None,
1456
+ ref_scheme: str | None = None,
1457
+ ledger: bool = False,
1458
+ sections: bool = False,
1459
+ alongside: Sequence[str | Path] = (),
1460
+ ) -> Estimate:
1461
+ """Read a backlog this tool does not own and report what it would cost to adopt it.
1462
+
1463
+ The prefix comes from ``prefix`` if given, from `roadkeep.toml` if the project has one,
1464
+ and otherwise from the file's own ids — flagged as ``inferred`` in the result, because
1465
+ a count of `id.format` violations taken under the wrong prefix is a count of one
1466
+ mistake repeated, which is exactly the noise that makes a migration estimate useless.
1467
+
1468
+ ``ref_scheme`` is an override and never an inference, which is the asymmetry worth
1469
+ stating: a prefix is a fact about the ids already written, while the scheme is a
1470
+ *decision* about whether a live outline gets migrated (§RK27) — measuring Shio under
1471
+ `outline` says what adopting the tool costs, and under `id` what adopting the tool
1472
+ *and* renumbering the outline costs. Both are real questions and only the caller
1473
+ knows which one is being asked.
1474
+
1475
+ ``ledger`` names the **role** the file is read in, not a schema to apply (RK76): the
1476
+ numbers come from :meth:`Config.schema_for`, the same seam every other command loads a
1477
+ document through, so `[limits.changelog]` and `[rules.changelog]` reach the estimate.
1478
+ They did not before, and an estimate taken under limits the gate does not apply is a
1479
+ measurement of a commitment nobody is being asked to make. A role and not a path
1480
+ because the caller names a file the project may not have declared at all.
1481
+
1482
+ ``sections`` names the *other half of the corpus* (RK99): a rationale file, whose unit
1483
+ is a section and whose limits are `[limits] section` and `prose`. Those are two of the
1484
+ numbers an adopting project has to declare, and until this they were the only ones the
1485
+ estimate never reported — so setting them meant copying this repository's, which is
1486
+ the template argument L6 refuses, or writing a throwaway script, which is what
1487
+ adopting commitclerk actually did. A flag and not a second command, because a corpus
1488
+ measured by two commands is two sets of numbers to keep in step.
1489
+
1490
+ ``alongside`` names the *rest of the set* the doubled-address finding is about (RK359).
1491
+ That finding is the one measure here that is not a property of one file, and until this
1492
+ it was reachable only where the target was already one of this project's own — so the
1493
+ adopter it exists for, running `--sections` from outside against a file no
1494
+ `roadkeep.toml` declares, met the collision on the first `lint` after the commitment
1495
+ instead. Named and never inferred from the directory: a `DESIGN.md` beside an
1496
+ `IMPROVEMENTS.md` is a guess about somebody's layout, and the report would then be
1497
+ measuring a set the caller never chose. Every other number stays about ``path`` alone.
1498
+ """
1499
+ # Against the project root and not the process's directory (RK1101): `-C` names the
1500
+ # project, and over MCP the two are never the same tree.
1501
+ target = config.locate(path)
1502
+ # And reported the way `Unreadable` spells one: from the project root where it is under it,
1503
+ # absolute where it is not. The resolution above makes every path absolute, and an absolute
1504
+ # path in a report is the message `provenance.invocation` refuses — about a machine rather
1505
+ # than about a project.
1506
+ from_root = Path(_relative(target.resolve(), config.root))
1507
+ if ledger and sections:
1508
+ raise ValueError(
1509
+ "--ledger and --sections measure different units — a ledger in lines and a "
1510
+ "rationale file in sections — so each is its own run over its own file"
1511
+ )
1512
+ if alongside and not sections:
1513
+ raise ValueError(
1514
+ "--with names the other prose files an address could be doubled across, which "
1515
+ "is a --sections measurement: a backlog holds lines and not headings"
1516
+ )
1517
+ if prefix is not None and sections:
1518
+ raise ValueError(
1519
+ "--prefix selects the ids to read, and --sections measures a rationale file "
1520
+ "whose sections are addressed by § and not by a family: there is nothing here "
1521
+ "for a prefix to choose between"
1522
+ )
1523
+ # Every path before the first one is opened (RK370), so a run over a set refuses whole
1524
+ # rather than reporting the files it reached before the one it could not.
1525
+ handed = (
1526
+ ("the file to measure", target),
1527
+ *(("--with", config.locate(one)) for one in alongside),
1528
+ )
1529
+ unreadable = [(named, one) for named, one in handed if not one.is_file()]
1530
+ if unreadable:
1531
+ raise Unreadable(unreadable, config.root, elsewhere=_elsewhere(path, alongside))
1532
+ # And before that, the file that is readable and is still not a corpus (RK374) — which is
1533
+ # either of the two this format is declared in, asked the way `init` asks (RK375).
1534
+ declaration = [(named, one) for named, one in handed if _declares(one)]
1535
+ if declaration:
1536
+ raise NotACorpus(declaration[0][0], declaration[0][1], config)
1537
+ if sections:
1538
+ return _prose(config, target, ref_scheme, alongside, from_root)
1539
+ schema = config.schema_for("changelog" if ledger else "roadmap")
1540
+ if ref_scheme is not None and ref_scheme != schema.ref_scheme:
1541
+ schema = replace(schema, ref_scheme=ref_scheme) # raises on an unknown scheme
1542
+ document = _loaded(config, target, schema, from_root)
1543
+
1544
+ spelled = _prefixes(document)
1545
+ declared = _families(prefix) if prefix else None
1546
+ if declared is None and config.source is not None:
1547
+ declared = config.schema.prefixes
1548
+ inferred = declared is None and bool(spelled)
1549
+ defaulted = declared is None and not spelled
1550
+ # Inference stays at *one* family even now that the schema carries several (RK74).
1551
+ # Which of two spellings is a second track and which is a paste from another backlog
1552
+ # is a judgement about meaning, and this tool has no model (L4) — so a project that
1553
+ # numbers by track declares it, and `--prefix` takes the list.
1554
+ chosen = declared or ((spelled[0][0],) if spelled else schema.prefixes)
1555
+ if chosen != schema.prefixes:
1556
+ # Swapped rather than re-read: the prefix is a validation rule and not a grammar,
1557
+ # so no line parses differently under it and a second read would be the same read.
1558
+ schema = replace(schema, prefixes=chosen)
1559
+ document = replace(document, schema=schema)
1560
+
1561
+ # The findings the gate would raise over **this file alone** (RK290), and not a second
1562
+ # walk of the per-line rules. `adopt` used to call `Schema.validate` per entry, which is
1563
+ # the per-line half only, so a duplicated id — decidable from one file, and refused by
1564
+ # `lint` over that same file — read as `2 conform, 0 would change`. `within` is the half
1565
+ # of the gate one file can run, already named and already relied on by the merge driver,
1566
+ # so the estimate and the gate now disagree only where they read different files.
1567
+ #
1568
+ # `role` names the *schema* this file is being read in, which is what the finding's path
1569
+ # is cosmetic against here: `adopt` reads a file the project may not declare at all, and
1570
+ # only the codes are counted.
1571
+ # Imported here and not at module level (RK260): `linting` reaches `backlog` and
1572
+ # `exporting`, and an estimate is the only caller in this module.
1573
+ from roadkeep.linting import characters_in, within # noqa: PLC0415
1574
+
1575
+ role = "changelog" if ledger else "roadmap"
1576
+ # The byte-level walk beside the line-level one (RK1351): a BOM or an invisible
1577
+ # codepoint is what an unadopted file most often carries — they come from editors and
1578
+ # exports rather than authors — and `lint` on the same bytes reported `char.bom` and
1579
+ # named the fixer while this priced the file at nothing. Asked by name rather than
1580
+ # folded into `within`, which the corpora settled: the merge driver gates its own
1581
+ # output with that one, and a defect it inherited is not one it introduced.
1582
+ findings = [*within(config, role, document), *characters_in(config, role, document)]
1583
+ counts: dict[str, int] = {}
1584
+ for finding in findings:
1585
+ # `line.unparsed` is the reject, already reported as its own row with the reason that
1586
+ # names a remedy (RK286) — counting it again here would price one line twice.
1587
+ if finding.code != "line.unparsed":
1588
+ counts[finding.code] = counts.get(finding.code, 0) + 1
1589
+ faulted = {f.lineno for f in findings if f.code != "line.unparsed"}
1590
+ conforming = sum(1 for entry in document.entries if entry.lineno not in faulted)
1591
+
1592
+ return Estimate(
1593
+ path=from_root,
1594
+ prefix=chosen[0],
1595
+ families=chosen,
1596
+ inferred=inferred,
1597
+ defaulted=defaulted,
1598
+ parsed=len(document.entries),
1599
+ conforming=conforming,
1600
+ ledger=ledger,
1601
+ ref_scheme=schema.ref_scheme,
1602
+ gains=_gains(config, _declared(config, target), document),
1603
+ surface=_surface(config),
1604
+ rejects=_grouped(reject.reason for reject in document.rejects),
1605
+ codes=_ranked(counts),
1606
+ measures=_measures(document, schema),
1607
+ undeclared=_undeclared(document),
1608
+ id_shape=_id_shape(document, schema),
1609
+ prefixes=spelled,
1610
+ schemes=_schemes(document),
1611
+ ledger_shape=_ledger_shape(document, schema),
1612
+ unopened=_unread(config, target),
1613
+ declared=_declared(config, target),
1614
+ blocks=_labels(document),
1615
+ non_canonical=len(document.non_canonical),
1616
+ # Only where the file is being read as a backlog: a ledger has no such list, and a
1617
+ # heading matching there would be an answer about the wrong file (RK139).
1618
+ non_goals=None if ledger else _scoped(config, document),
1619
+ tabular=len(document.tabular),
1620
+ listed=len(document.listed),
1621
+ lines=len(document.lines),
1622
+ recognised=_recognised(
1623
+ (entry.lineno for entry in document.entries),
1624
+ (reject.lineno for reject in document.rejects),
1625
+ (row.lineno for row in document.tabular),
1626
+ (item.lineno for item in document.listed),
1627
+ (heading.lineno for heading in document.headings if heading.label),
1628
+ ),
1629
+ )
1630
+
1631
+
1632
+ def _prose(
1633
+ config: Config,
1634
+ target: Path,
1635
+ ref_scheme: str | None,
1636
+ alongside: Sequence[str | Path] = (),
1637
+ from_root: Path | None = None,
1638
+ ) -> Estimate:
1639
+ """A rationale file, measured in sections against the two limits nobody reported (RK99).
1640
+
1641
+ Read under the `improvements` role, so `[limits.improvements]` reaches it the same way
1642
+ `[limits.changelog]` reaches a ledger — and under the caller's ``ref_scheme``, which
1643
+ here decides not a count but *whether there is one*: an anchor is spelled `§RK9` under
1644
+ `id` and `XVI.12` under an outline, and reading one as the other turned Shio's 151
1645
+ headings into 0 sections. The scheme is on the result for that reason.
1646
+
1647
+ No prefix is reported and none is inferred, because a section is not addressed by one:
1648
+ :func:`~roadkeep.sections.anchored` reads the § and not the family behind it, so a
1649
+ prefix printed here would be a claim this run never made. Which is why one *named* is
1650
+ refused rather than dropped (RK384): the report has no prefix line by design, so nothing
1651
+ on screen would have contradicted a caller who believed the run was taken under theirs —
1652
+ and `--prefix "not a prefix at all"` was a refusal one flag over and a no-op here.
1653
+
1654
+ ``prose`` is a measurement and never a violation — the width is what a written section
1655
+ is *filled to*, and nothing gates a hand-wrapped file at it. It is here because it is
1656
+ the second number an adopting project has to declare, and the file it is declaring it
1657
+ for is the one being read. Taken over the paragraphs the tool would actually fill
1658
+ (:func:`~roadkeep.sections.structural` is the same predicate that decides), because the
1659
+ widest line in a rationale file is a table row nobody would wrap to.
1660
+ """
1661
+ schema = config.schema_for("improvements")
1662
+ if ref_scheme is not None and ref_scheme != schema.ref_scheme:
1663
+ schema = replace(schema, ref_scheme=ref_scheme) # raises on an unknown scheme
1664
+ document = _loaded(config, target, schema, from_root)
1665
+ found = anchored(document)
1666
+ words = [section.words for section in found]
1667
+ # Headings where a section would be, carrying no anchor (RK281). Measured the same way —
1668
+ # a span of prose has a word count whether or not this tool has an address for it.
1669
+ loose = unanchored(document)
1670
+ loose_words = [
1671
+ sections_words("".join(document.lines[h.lineno : document.prose_end(h)]))
1672
+ for h in loose
1673
+ ]
1674
+ # Every prose paragraph, not only a section's: the width an author wraps to is a fact
1675
+ # about the file, and a preamble above the first anchor is written to the same margin.
1676
+ widths = [len(line) for line in _filled(document)]
1677
+ # RK347: the finding one path cannot hold, with the kind of name each file got (RK371).
1678
+ # Taken before `unopened`, which is derived from it — a file this opened is not one the
1679
+ # same report may name as out of reach, and a file it did not is not one it may cover for.
1680
+ across = _ambiguous(config, target, alongside, schema)
1681
+ return Estimate(
1682
+ path=from_root or target,
1683
+ prefix="",
1684
+ families=(),
1685
+ inferred=False,
1686
+ unit="section",
1687
+ ref_scheme=schema.ref_scheme,
1688
+ # RK288: the second source. Without it `--sections` had no way to say "read this the
1689
+ # other way", which is the one sentence Shio's file needed.
1690
+ schemes=_heading_schemes(document),
1691
+ ambiguous=across.addresses,
1692
+ by_path=across.by_path,
1693
+ # What that read opened, and never a rule about what a read of this kind opens (RK373).
1694
+ unopened=_unread(config, target, opened=across.opened),
1695
+ declared=_declared(config, target),
1696
+ # The same on both runs: what the server costs is a fact about the package, not about
1697
+ # which file this one was pointed at (RK1100).
1698
+ surface=_surface(config),
1699
+ parsed=len(found),
1700
+ conforming=sum(1 for count in words if count <= schema.section_max),
1701
+ # RK281: the same contract `listed` has one file over. A rationale file that never
1702
+ # adopted the sigil has sections in every sense but this tool's, and the zero it used
1703
+ # to get is the one RK98 forbids.
1704
+ listed=len(loose),
1705
+ # The same pair the backlog run carries (RK387). Its shapes are entries and bullets and
1706
+ # this one's are headings, so what is read differs — what may not is whether the run
1707
+ # says so, a rationale file of prose and no heading having answered a blank file's
1708
+ # `0 conform, 0 would change` for as long as the other one stopped doing that.
1709
+ lines=len(document.lines),
1710
+ recognised=_recognised(
1711
+ (section.first for section in found),
1712
+ (heading.lineno for heading in loose),
1713
+ ),
1714
+ measures=(
1715
+ Measure(
1716
+ field="section",
1717
+ limit=schema.section_max,
1718
+ # Over both, because the width an unanchored section is written to is the
1719
+ # number an adopter is being asked to declare — the same reason `prose` below
1720
+ # measures every paragraph and not only an anchored one's.
1721
+ longest=max([*words, *loose_words], default=0),
1722
+ over=sum(1 for count in (*words, *loose_words) if count > schema.section_max),
1723
+ unit=WORDS,
1724
+ ),
1725
+ Measure(
1726
+ field="prose",
1727
+ limit=schema.prose_width,
1728
+ longest=max(widths, default=0),
1729
+ # Never a count of violations (RK1348): nothing refuses this width, so a
1730
+ # paragraph past it is a fact about how somebody wrapped their file.
1731
+ over=0,
1732
+ refuses=False,
1733
+ # Code points, because that is what `textwrap.fill` measures and this row is
1734
+ # about the column the tool fills to (RK437). Measuring it the other way would
1735
+ # report this repository's own paragraphs over a width it wrote them at.
1736
+ unit=CODE_POINTS,
1737
+ ),
1738
+ ),
1739
+ blocks=_labels(document),
1740
+ )
1741
+
1742
+
1743
+ def _labels(document: Document) -> tuple[str, ...]:
1744
+ """Every block this file **declares**, in file order, one entry per region (RK445).
1745
+
1746
+ Through :meth:`Document.declaring`, which is where the rule lives (RK439): a heading
1747
+ inside another's subtree is owned by that region rather than being a second address for
1748
+ it, so Shio's eight `### Block K follow-ups` are one Block K. Reading `headings` directly
1749
+ reported `B, B, B` on a three-heading ledger and would report Block K nine times there —
1750
+ on the first line an adopting project reads about its own corpus, which is what a
1751
+ `[files]` declaration and a first `lint` are decided from.
1752
+
1753
+ Repeats that survive are kept, and have to be: two headings neither of which is inside
1754
+ the other are two regions, that is the `block.repeated` state, and an adopter counting
1755
+ labels is exactly the reader who needs to see it before committing.
1756
+
1757
+ File order, because that is what the list is read as — the shape of the plan. Hence the
1758
+ line numbers rather than a set of labels: `declaring` answers about a label already
1759
+ named, and asking it per label would reorder the answer by first mention.
1760
+ """
1761
+ kept = {
1762
+ heading.lineno
1763
+ for label in dict.fromkeys(h.label for h in document.headings if h.label)
1764
+ for heading in document.declaring(label)
1765
+ }
1766
+ return tuple(h.label for h in document.headings if h.label and h.lineno in kept)
1767
+
1768
+
1769
+ def _filled(document: Document) -> list[str]:
1770
+ """Every line of every paragraph the tool would re-wrap, stripped of its ending.
1771
+
1772
+ Blank-separated, because a paragraph is the unit the structure test judges — one table
1773
+ row would otherwise read as prose the moment it was looked at on its own.
1774
+ """
1775
+ out: list[str] = []
1776
+ paragraph: list[str] = []
1777
+ for raw in (*document.lines, "\n"):
1778
+ line = raw.rstrip("\r\n")
1779
+ if line.strip():
1780
+ paragraph.append(line)
1781
+ continue
1782
+ if paragraph and not structural(paragraph):
1783
+ out += paragraph
1784
+ paragraph = []
1785
+ return out
1786
+
1787
+
1788
+ def _scoped(config: Config, document: Document) -> Scoped:
1789
+ """The non-goals under this roadmap's heading, against the two limits they will be held to.
1790
+
1791
+ The parser is `scoping`'s own — the reader every other caller shares — so the count is the
1792
+ one `lint` will take and not a second reading of the same bullets. The limits are the
1793
+ project's `[non_goals]` where it declared them and :class:`Scope`'s defaults where it has
1794
+ not, which is the whole point of measuring an opt-in rule: an adopter is asking what the
1795
+ table would cost before writing it.
1796
+ """
1797
+ scope = config.non_goals or Scope()
1798
+ # The bullets whose shape held, which is what `parsed` has always counted (RK233): the
1799
+ # reader now returns the others too, so the filter is here and named rather than inside a
1800
+ # reader two other callers share. An unshaped bullet is one edit, counted by `unparsed`,
1801
+ # and charging its sentence-lead against `lead` as well would count that edit twice.
1802
+ found = tuple(goal for goal in scoping.read(document) if goal.shaped)
1803
+ # `width` and not `len` (RK437). These two rows are held against the counter `scoping`
1804
+ # refuses with, which RK430 made UTF-16 — so a row labelled in units and measured in code
1805
+ # points would be the report telling an adopter a bullet fits that the gate then refuses.
1806
+ # The task lines above have counted this way since RK430; the roadmap's other bullet did
1807
+ # not, and naming the unit is what makes that visible.
1808
+ over = sum(
1809
+ 1
1810
+ for goal in found
1811
+ if width(goal.lead) > scope.lead or width(goal.why) > scope.why
1812
+ )
1813
+ leads = [width(goal.lead) for goal in found]
1814
+ whys = [width(goal.why) for goal in found]
1815
+ return Scoped(
1816
+ parsed=len(found),
1817
+ unparsed=len(scoping.rejects(document)),
1818
+ over=over,
1819
+ measures=(
1820
+ Measure(
1821
+ field="lead",
1822
+ limit=scope.lead,
1823
+ longest=max(leads, default=0),
1824
+ over=sum(1 for length in leads if length > scope.lead),
1825
+ ),
1826
+ Measure(
1827
+ field="why",
1828
+ limit=scope.why,
1829
+ longest=max(whys, default=0),
1830
+ over=sum(1 for length in whys if length > scope.why),
1831
+ ),
1832
+ ),
1833
+ governed=config.non_goals is not None,
1834
+ )
1835
+
1836
+
1837
+ def _measures(document: Document, schema: Schema) -> tuple[Measure, ...]:
1838
+ """Every length limit against the corpus: the longest, and how many exceed it."""
1839
+ out: list[Measure] = []
1840
+ for field, attribute in _MEASURED:
1841
+ # A field the shape has not got is not a field to report against (RK1349). A project
1842
+ # declaring `[ledger] symptom = false` says its entries are a why with a commit and no
1843
+ # bold symptom — and it is not a relaxation: an entry carrying one is `line.unparsed`
1844
+ # there. The row still printed `symptom longest 0 of 120, 0 over`, which is the
1845
+ # vacuous count RK1345 dropped where nothing parsed and RK1348 where nothing refuses,
1846
+ # with the population real this time and the field absent. Believed more readily than
1847
+ # either, the two rows beside it being true.
1848
+ if field == "symptom" and not schema.symptom_field:
1849
+ continue
1850
+ limit = getattr(schema, attribute)
1851
+ lengths = [
1852
+ width(schema.render(entry.task) if field == "line" else getattr(entry.task, field))
1853
+ for entry in document.entries
1854
+ ]
1855
+ out.append(
1856
+ Measure(
1857
+ field=field,
1858
+ limit=limit,
1859
+ longest=max(lengths, default=0),
1860
+ over=sum(1 for length in lengths if length > limit),
1861
+ )
1862
+ )
1863
+ return tuple(out)
1864
+
1865
+
1866
+ def _undeclared(document: Document) -> tuple[tuple[str, int], ...]:
1867
+ """Tokens in the marker slot this project does not declare — the `[markers]` delta.
1868
+
1869
+ Read off the rejected line's own text rather than matched against the reason string:
1870
+ a reason is a sentence for a human, and a report that parsed one would break the first
1871
+ time the sentence was reworded.
1872
+
1873
+ A task-list checkbox is skipped by the same shape test that rejected it (RK103) and not
1874
+ by a token spelling here: `- [ ] **C40**` splits to `[`, which carries no alphanumeric
1875
+ and so would otherwise arrive as a marker to declare — and declaring `[` is the one
1876
+ answer that widens the slot to two tokens. The line is still counted, in `rejects`.
1877
+ """
1878
+ schema = document.schema
1879
+ known = {
1880
+ *schema.markers,
1881
+ schema.shipped_marker,
1882
+ schema.retired_marker,
1883
+ schema.deferred_marker,
1884
+ }
1885
+ counts: dict[str, int] = {}
1886
+ for reject in document.rejects:
1887
+ rest = reject.raw.lstrip("-*+ ")
1888
+ if checkbox(rest) is not None:
1889
+ continue
1890
+ token = rest.split(" ", 1)[0]
1891
+ if token and token not in known and not any(c.isalnum() for c in token):
1892
+ counts[token] = counts.get(token, 0) + 1
1893
+ return _ranked(counts)
1894
+
1895
+
1896
+ def _id_shape(document: Document, schema: Schema) -> tuple[Shape, ...]:
1897
+ """What the ids spell about `[ids]` that this schema does not declare (RK110).
1898
+
1899
+ Two counts over strings already parsed, and neither is a proposal. **A leading zero** is
1900
+ a width: `D01` under the default `pad = 1` is one of nine findings that are one unwritten
1901
+ key, and the widths are reported separately because a corpus that pads to two and to
1902
+ three is a corpus whose width nobody has chosen. **A trailing lowercase letter** is
1903
+ `suffix = true` — Turing's `T24b`, 4 of its 361 findings.
1904
+
1905
+ Read with a pattern of its own rather than :meth:`Schema.parse_id`, which is precisely
1906
+ the *declared* shape: under `pad = 1` it reads `D01` as no id at all, and what the ids
1907
+ spell that the declaration does not is the whole measurement.
1908
+
1909
+ Only what the schema does not already hold, exactly as the prefix delta prints only the
1910
+ families the chosen ones do not cover: a project that declared the width is not owed a
1911
+ report saying it could.
1912
+ """
1913
+ widths: dict[int, int] = {}
1914
+ suffixed = 0
1915
+ for entry in document.entries:
1916
+ parts = _ID_PARTS_RE.match(entry.task.id)
1917
+ if parts is None:
1918
+ continue
1919
+ number = parts.group("number")
1920
+ if number.startswith("0") and len(number) != schema.id_pad:
1921
+ widths[len(number)] = widths.get(len(number), 0) + 1
1922
+ if parts.group("sub") and not schema.id_suffix:
1923
+ suffixed += 1
1924
+ out = [
1925
+ Shape(key="pad", value=str(width), count=count)
1926
+ for width, count in sorted(widths.items(), key=lambda pair: (-pair[1], pair[0]))
1927
+ ]
1928
+ if suffixed:
1929
+ out.append(Shape(key="suffix", value="true", count=suffixed))
1930
+ return tuple(out)
1931
+
1932
+
1933
+ def _prefixes(document: Document) -> tuple[tuple[str, int], ...]:
1934
+ """The alphabetic head of every id in the file, counted. A measurement, not a choice."""
1935
+ counts: dict[str, int] = {}
1936
+ for entry in document.entries:
1937
+ head = _alpha_head(entry.task.id)
1938
+ if head:
1939
+ counts[head] = counts.get(head, 0) + 1
1940
+ return _ranked(counts)
1941
+
1942
+
1943
+ def _ledger_shape(document: Document, schema: Schema) -> tuple[tuple[str, int], ...]:
1944
+ """Which `[ledger]` declaration would read this file's refused lines, and how many (RK286).
1945
+
1946
+ Only where the file is being read as a ledger, and only over lines that were *refused*: a
1947
+ line that already parses is not evidence about a slot, and a roadmap has no `[ledger]` to
1948
+ declare. Grouped by the declaration, so a file needing both slots is one row and not two
1949
+ with the same count.
1950
+
1951
+ Measured rather than left to a flag. The reason names the slots and this names what
1952
+ declaring them recovers, which is the number RK18 says is only worth having before the
1953
+ commitment — and reaching it otherwise meant writing the configuration under decision.
1954
+
1955
+ One count per **whole** declaration, and never a tally of what each line individually
1956
+ wants: the two slots are not independent. A `- ✅ **T3** — why` line is read by
1957
+ `symptom = false` and *stopped* by `marker = false`, because with no marker slot the ✅
1958
+ sits where the id goes. Summing per-line wants would promise a total no single
1959
+ configuration delivers, and a project declares one `[ledger]`, not one per line.
1960
+
1961
+ Counted by **re-reading the file** under each declaration, not by matching the line
1962
+ grammar again: a ledger with no marker slot still carries one on a departure (RK125), and
1963
+ a regex that did not know it under-reported Turing by the 11 lines that are retirements.
1964
+ The reader is the only thing that knows what the reader does — this is the seam every
1965
+ other command loads a document through, so the promise cannot drift from the outcome.
1966
+ """
1967
+ if not schema.is_ledger:
1968
+ return ()
1969
+ text = "".join(document.lines)
1970
+ counts: dict[str, int] = {}
1971
+ for marker, symptom, slots in LEDGER_SHAPES:
1972
+ if (marker, symptom) == (schema.marker_field, schema.symptom_field):
1973
+ continue # what the file already declares is not a hypothesis about it
1974
+ under = replace(schema, marker_field=marker, symptom_field=symptom)
1975
+ read = len(Document.parse(text, under).entries)
1976
+ if read > len(document.entries):
1977
+ counts[", ".join(slots)] = read
1978
+ return _ranked(counts)
1979
+
1980
+
1981
+ def _heading_schemes(document: Document) -> tuple[tuple[str, int], ...]:
1982
+ """Which scheme the **headings** of a prose file are anchored in, counted (RK288).
1983
+
1984
+ :func:`_schemes` reads the pointers on task lines, and a rationale file has none — so the
1985
+ one output that would say "read this the other way" was structurally absent on the command
1986
+ where the misreading is total. Shio's rationale file read `0 conform, 94 would change`
1987
+ under the default and `93 conform` under `--ref-scheme outline`, with no line naming the
1988
+ flag.
1989
+
1990
+ Read off the heading's first token and never off the schema, which is the whole point: an
1991
+ anchor is `0.1` or it is an id, and which a file spells is a fact about the file. The
1992
+ sigil is optional here because `anchor_text` writes one only under the id scheme — a bare
1993
+ `0.1` is what an outline heading looks like on disk.
1994
+
1995
+ This is a *report* about the file and never a per-heading guess: :func:`unanchored` keeps
1996
+ asking the declared schema, because a count that quietly repaired itself would leave the
1997
+ reader with the right number under a reading the report still claims is right.
1998
+ """
1999
+ counts: dict[str, int] = {}
2000
+ for heading in document.headings:
2001
+ token = heading.text.split(maxsplit=1)[0].lstrip("§") if heading.text.strip() else ""
2002
+ if not token:
2003
+ continue
2004
+ if _ID_PARTS_RE.match(token):
2005
+ counts["id"] = counts.get("id", 0) + 1
2006
+ elif OUTLINE_ANCHOR_RE.match(token):
2007
+ counts["outline"] = counts.get("outline", 0) + 1
2008
+ return _ranked(counts)
2009
+
2010
+
2011
+ def _ambiguous(
2012
+ config: Config,
2013
+ target: Path,
2014
+ alongside: Sequence[str | Path] = (),
2015
+ schema: Schema | None = None,
2016
+ ) -> Doubling:
2017
+ """Every address two prose files declare now, with the roles that declare it (RK347).
2018
+
2019
+ The one check `adopt` could not make from one path. Every other limit it reports is a
2020
+ property of the file in front of it; a doubled address is a property of the *set*, so a
2021
+ per-file read answers "conforming" about two files the gate then files four
2022
+ `section.ambiguous` against — and that is the finding an adopting project meets first,
2023
+ because two outlines written independently both start at `I`.
2024
+
2025
+ :func:`~roadkeep.history.doubled` is the reader, so this is the same answer `anchors`
2026
+ prints rather than a second opinion about what a collision is. Handed live headings only
2027
+ and never :func:`~roadkeep.history.anchors`, which reaches for `git log` to date them: an
2028
+ estimate is taken on a tree that may not be a clone, and the address a *pointer* cannot
2029
+ resolve is one two headings declare today.
2030
+
2031
+ Empty where the target is not one of this project's files (RK292), for the reason
2032
+ :func:`_unread` is: there `[files]` names somebody else's siblings, and reporting a
2033
+ collision between two of them would be measuring a project the caller did not ask about.
2034
+
2035
+ Reads the anchors **qualified** (RK340), which is what makes the report actionable rather
2036
+ than merely true: declaring `[refs]` puts each file's outline in its own namespace, and
2037
+ the same run then answers zero.
2038
+
2039
+ ``alongside`` replaces that set with the one the caller named (RK359) — the target plus
2040
+ those files. It replaces rather than extends for the same reason the whole finding is
2041
+ guarded: a set half chosen by the caller and half by a `[files]` table that may belong to
2042
+ another project is a doubling the reader cannot act on. Resolved before pairing, so a file
2043
+ named twice, or named as well as being the target, does not collide with itself.
2044
+
2045
+ Each of them is read **through its role where it has one** (RK369), which is where the
2046
+ qualification comes from: the prefix rides on the document's schema, so a path loaded
2047
+ directly carries none and a project that already declared `[refs]` was told twice about a
2048
+ collision its configuration resolved — the one thing an estimate may not do, its number
2049
+ being the one bought before a commitment. So the label is a role where there is one and
2050
+ the path where there is not: each file named the truest way this project can name it, and
2051
+ a file it does not govern has no role to be called by.
2052
+
2053
+ Which kind each name is, is returned beside them (RK371). It is known here and nowhere
2054
+ after — the printed line survives on the sentence around it, and `--json` was left with a
2055
+ `roles` key holding filenames and no way to tell.
2056
+
2057
+ So is **which declared files this actually opened** (RK373). The sentence naming what went
2058
+ unread used to be handed every prose role, which was exactly true while this read all of
2059
+ them and became a claim about a set the caller had since narrowed: with `--with`, a
2060
+ `STRATEGY.md` nobody looked at was reported as covered by the one line whose job is to say
2061
+ what was not. What was read is known here and derived nowhere else.
2062
+ """
2063
+ from roadkeep.history import Anchor, doubled # noqa: PLC0415 - RK260
2064
+
2065
+ if alongside:
2066
+ read = schema or config.schema_for("improvements")
2067
+ roles = _by_role(config)
2068
+ seen: dict[Path, tuple[str, Document]] = {}
2069
+ for one in (target, *(Path(p) for p in alongside)):
2070
+ here = one.resolve()
2071
+ if here in seen:
2072
+ continue
2073
+ role = roles.get(here)
2074
+ seen[here] = (
2075
+ (role, config.document(role))
2076
+ if role in PROSE_ROLES
2077
+ # `read` and not the role's schema for a governed file that is not prose: a
2078
+ # ledger read as a ledger has no headings to anchor, and the caller handed it
2079
+ # over as the other half of an outline.
2080
+ else (_relative(here, config.root), Document.load(here, read))
2081
+ )
2082
+ named = [
2083
+ Anchor(anchor=section.anchor, role=label, live=True)
2084
+ for label, document in seen.values()
2085
+ for section in anchored(document)
2086
+ ]
2087
+ by_path = tuple(
2088
+ label for path, (label, _) in seen.items() if roles.get(path) not in PROSE_ROLES
2089
+ )
2090
+ # Every declared role behind one of those paths, prose or not: what makes a file
2091
+ # "read" here is that this opened it, and a changelog handed over was opened.
2092
+ opened = tuple(role for path in seen if (role := roles.get(path)) is not None)
2093
+ return Doubling(doubled(named), by_path, opened)
2094
+ if not _declared(config, target):
2095
+ return Doubling()
2096
+
2097
+ kept = [role for role in PROSE_ROLES if config.has(role) and config.path(role).is_file()]
2098
+ taken = [
2099
+ Anchor(anchor=section.anchor, role=role, live=True)
2100
+ for role in kept
2101
+ for section in anchored(config.document(role))
2102
+ ]
2103
+ # Every name here is a role by construction, so nothing was read by path. A declared prose
2104
+ # file that is not on disk is *not* in `kept` and so is named as unread: `file.missing` is
2105
+ # the gate's word for it, and claiming a collision was checked for in it would be this
2106
+ # sentence covering for the other one.
2107
+ return Doubling(doubled(taken), (), tuple(kept))
2108
+
2109
+
2110
+ def _by_role(config: Config) -> dict[Path, str]:
2111
+ """Every path this project declares, resolved, against the role that declares it (RK372).
2112
+
2113
+ The one place a path becomes a role. Two callers asked it separately and narrowed it
2114
+ differently — one against every role, one against the prose roles alone — and each was
2115
+ right about its own question while the report carried both answers about one file, one of
2116
+ them saying it had been read and the other that this project had no role for it. Neither
2117
+ rule moved; what changed is that there is one answer to narrow.
2118
+
2119
+ It is the **resolved** path that decides and never the filename: an `IMPROVEMENTS.md` in
2120
+ another checkout is a different file from this one's, and the whole case `adopt` exists
2121
+ for is a caller standing outside the project.
2122
+ """
2123
+ return {config.path(role).resolve(): role for role in config.paths}
2124
+
2125
+
2126
+ def _unread(config: Config, target: Path, opened: Sequence[str] = ()) -> tuple[str, ...]:
2127
+ """The governed files this run did not open, in `[files]` order (RK291).
2128
+
2129
+ Named by **file** and not by finding code, which is the decision the section settled:
2130
+ `deps.unknown` and `ref.unresolved` is precise and ages badly as the gate grows a check,
2131
+ while a filename is what an adopter can act on — handing `adopt` that file is the move the
2132
+ sentence implies.
2133
+
2134
+ Empty where the target is **not** one of the declared files (RK292), which is the case
2135
+ `adopt` exists for. There this project's `[files]` belong to somebody else: naming them as
2136
+ unread said that Turing's `docs/IMPROVEMENTS.md` was measured while this repository's
2137
+ `docs/IMPROVEMENTS.md` went unread, which reads as the report not having read what it read
2138
+ — and offering siblings nobody can hand over. The limit is still real and simply narrower,
2139
+ and :attr:`Estimate.declared` is what lets the sentence say which one it is.
2140
+
2141
+ ``opened`` is what this run *did* read past the target (RK347), which the caller takes off
2142
+ the read itself and never off a rule about what a read of this kind opens (RK373): naming
2143
+ an opened file here would say it was out of reach in the same report that measured it, and
2144
+ excluding one that was not opened would cover for a check nobody made. Both were the same
2145
+ mistake, and the second arrived the moment `--with` let a caller narrow the set of files
2146
+ the doubling is taken over. What stays unread is what stays unread — the
2147
+ checks that resolve through a task line — which is what the sentence was always about.
2148
+ """
2149
+ here = target.resolve()
2150
+ by_role = {role: config.path(role).resolve() for role in config.paths}
2151
+ if here not in by_role.values():
2152
+ return ()
2153
+ return tuple(
2154
+ config.relative(config.path(role))
2155
+ for role, path in by_role.items()
2156
+ if path != here and role not in opened
2157
+ )
2158
+
2159
+
2160
+
2161
+ def _loaded(config: Config, target: Path, schema: Schema, from_root: Path | None) -> Document:
2162
+ """`Document.load`, with a file that does not decode said rather than raised through.
2163
+
2164
+ One place and not two (RK1350): both readings of a target reach the same failure, and a
2165
+ sibling that grew the sentence would be the second spelling this repository refuses.
2166
+ """
2167
+ try:
2168
+ return Document.load(target, schema)
2169
+ except UnicodeDecodeError as error:
2170
+ raise NotText(
2171
+ (from_root or target).as_posix(),
2172
+ governed=_declared(config, target),
2173
+ at=error.start,
2174
+ ) from error
2175
+
2176
+
2177
+ def _declared(config: Config, target: Path) -> bool:
2178
+ """Whether this target is one of the files the loaded project governs (RK292)."""
2179
+ here = target.resolve()
2180
+ return any(config.path(role).resolve() == here for role in config.paths)
2181
+
2182
+
2183
+ def _schemes(document: Document) -> tuple[tuple[str, int], ...]:
2184
+ """Which scheme each pointer in this file is *shaped* like, counted (RK285).
2185
+
2186
+ :func:`_prefixes` one field over, and a measurement rather than a choice for the same
2187
+ reason: whether a file that points by `<x.y>` should be read under `outline` is a decision
2188
+ about a live outline, and only the caller knows which question is being asked (see `adopt`).
2189
+
2190
+ Read off the pointers already parsed and never by re-reading the file under the other
2191
+ scheme: the scheme is a validation rule and not a grammar — no line parses differently
2192
+ under it — so a second read would be the same read.
2193
+ """
2194
+ counts: dict[str, int] = {}
2195
+ for entry in document.entries:
2196
+ ref = entry.task.ref
2197
+ if not ref:
2198
+ continue
2199
+ if ref == entry.task.id:
2200
+ counts["id"] = counts.get("id", 0) + 1
2201
+ elif OUTLINE_ANCHOR_RE.match(ref):
2202
+ counts["outline"] = counts.get("outline", 0) + 1
2203
+ return _ranked(counts)
2204
+
2205
+
2206
+ def _alpha_head(text: str) -> str:
2207
+ """The leading letters of an id — `SH` of `SH41`."""
2208
+ for index, char in enumerate(text):
2209
+ if not char.isalpha():
2210
+ return text[:index]
2211
+ return text
2212
+
2213
+
2214
+ def _recognised(*shapes: Iterable[int]) -> int:
2215
+ """How many of a file's lines were read in **any** shape at all (RK376, RK387).
2216
+
2217
+ Distinct line numbers rather than a sum, because the shapes are not disjoint by
2218
+ construction and a total that double-counted one line would be a number nobody could
2219
+ check against the file. Zero is the whole point of it — beside :attr:`Estimate.lines` it
2220
+ is what tells an empty roadmap apart from a file this format read nothing in.
2221
+
2222
+ The shapes are named by the **caller** and not gathered here, because the two runs do not
2223
+ read the same ones (RK387). A backlog is read as entries, the marker lines it refused,
2224
+ table rows and plain bullets (RK98's two counters), and headings that *declare a block* —
2225
+ that last qualifier being the measurement rather than a detail of it, since a `README.md`
2226
+ opening at `# My project` would otherwise answer two for headings this format cannot read
2227
+ as structure, which is exactly the prose that walked past. A rationale file has no entries
2228
+ at all and is read as its anchored sections and the headings carrying prose without one.
2229
+ Gathering both sets here would mean a function that knows which run it is in; naming them
2230
+ at the call site is what lets one counter serve two readings.
2231
+ """
2232
+ return len({lineno for shape in shapes for lineno in shape})
2233
+
2234
+
2235
+ #: Every door declaring this format opens, as a declaration rather than a function body
2236
+ #: (RK1093). RK1089 built the category so a fourth member had somewhere to land and RK1090
2237
+ #: landed it — by adding a fifth `if` to a block that was already four, which is the failure
2238
+ #: that task was filed about arriving one iteration later.
2239
+ #:
2240
+ #: `opens` is a predicate over what the project declared, and it takes the roadmap because
2241
+ #: one of the four is a `## Priority` **section** rather than a config key (RK325). A
2242
+ #: callable and not a key, which is `serving._BOUNDS`' own shape and worth copying rather
2243
+ #: than inventing: what varies is data, and what has to traverse is code.
2244
+ GAINS: tuple[tuple[str, Callable[[Config, Document | None], bool], str], ...] = (
2245
+ (
2246
+ "pause",
2247
+ lambda config, _document: not config.has("deferred"),
2248
+ "no deferred store, so `defer` refuses and there is no door for *not now*: "
2249
+ 'add `deferred = "<path>"` under [files], or a line set aside has to be '
2250
+ "retired, which is terminal — the id cannot come back and the design goes",
2251
+ ),
2252
+ (
2253
+ "design",
2254
+ lambda config, _document: not any(config.has(role) for role in PROSE_ROLES),
2255
+ "no prose file, so a line has nowhere to point: `add --section` cannot write "
2256
+ "the rationale a symptom has no room for, and the reasoning lives wherever it "
2257
+ "lived before — which is the 539 KB this tool was built from",
2258
+ ),
2259
+ (
2260
+ "non-goals",
2261
+ lambda config, _document: config.non_goals is None,
2262
+ "`[non_goals]` not governed, so the roadmap's other bullet is prose the gate "
2263
+ "does not read: what may not be proposed is stated and unenforced, which is "
2264
+ "the arrangement every limit here exists to replace",
2265
+ ),
2266
+ (
2267
+ "queue",
2268
+ # The heading and not its entries: a project whose queue is empty today has the
2269
+ # door and is using it (RK1090), and counting entries reports this repository as
2270
+ # missing one on any day nothing outranks the id order.
2271
+ lambda _config, document: document is not None
2272
+ and not queueing.opened(document),
2273
+ "no `## Priority` section, so `pick` offers the lowest ready id: order is "
2274
+ "derived from the numbers, and work nobody wants next is offered first "
2275
+ "whenever its id happens to be lowest — a cost a long backlog feels",
2276
+ ),
2277
+ (
2278
+ "decisions",
2279
+ lambda config, _document: not config.has("decisions"),
2280
+ "no decisions file, so a constraint that outlives the work explaining it has "
2281
+ "nowhere governed to go: `ship --decides` refuses, and an ADR is kept by hand "
2282
+ "or not at all — which is the convention every schema here replaces",
2283
+ ),
2284
+ )
2285
+
2286
+
2287
+ def _gains(
2288
+ config: Config, declared: bool, document: Document | None = None
2289
+ ) -> tuple[Gain, ...]:
2290
+ """What declaring the format would give this project that it has not got (RK1089).
2291
+
2292
+ A **category** and not a fourth measurement. Every other row in an estimate answers *what
2293
+ would this file cost* — lines read, longest symptom, how many would change — and RK1087
2294
+ added a sentence answering something else: what door is missing.
2295
+
2296
+ One walk over :data:`GAINS` since RK1093, so a fifth door is a row there and
2297
+ `tests/test_adopting.py` can ask whether every door this format opens is named — a
2298
+ question a function body cannot be asked.
2299
+
2300
+ Silent where **no project declared the target**, which is the case `adopt` exists for: a
2301
+ file handed over from another repository has no `[files]` of its own, so every gain here
2302
+ would be true and useless — the answer for that case is `_estimate_scope`'s.
2303
+
2304
+ Only where the answer is *nothing*, which is every absence in this report: a door the
2305
+ project has is not a gain, and a row stated where it does not bite is one a reader learns
2306
+ to skip past.
2307
+ """
2308
+ if not declared:
2309
+ return ()
2310
+ return tuple(
2311
+ Gain(name, because)
2312
+ for name, opens, because in GAINS
2313
+ if opens(config, document)
2314
+ )
2315
+
2316
+
2317
+ def _surface(config: Config) -> int:
2318
+ """What a session connecting to this project's server would be sent (RK1100).
2319
+
2320
+ A local import for `linting._served`'s reason and not as a style: `serving` reaches `cli`,
2321
+ which reaches the verbs, which reach this module — so the name at module scope would close
2322
+ a cycle. The measurement itself is `serving.surface`, which is the same function
2323
+ `cost --session` prints and the gate holds (RK1096), because an estimate quoting a
2324
+ second arithmetic is the disagreement that whole task removed.
2325
+
2326
+ Zero where it cannot be composed, which is not an adoption fact: a config too broken to
2327
+ describe a tool is one `adopt` is already reporting on, and a report that raised there
2328
+ would take away the read that explains why.
2329
+ """
2330
+ from roadkeep.serving import surface # noqa: PLC0415 - RK260, the cycle above
2331
+
2332
+ try:
2333
+ return surface(config).characters
2334
+ except (ValueError, KeyError, TypeError):
2335
+ return 0
2336
+
2337
+
2338
+ def _grouped(reasons: Iterable[str]) -> tuple[tuple[str, int], ...]:
2339
+ counts: dict[str, int] = {}
2340
+ for reason in reasons:
2341
+ counts[reason] = counts.get(reason, 0) + 1
2342
+ return _ranked(counts)
2343
+
2344
+
2345
+ def _ranked(counts: Mapping[str, int]) -> tuple[tuple[str, int], ...]:
2346
+ """Worst first, ties by name — a report read top-down has to start with the work."""
2347
+ return tuple(sorted(counts.items(), key=lambda pair: (-pair[1], pair[0])))