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/rendering.py ADDED
@@ -0,0 +1,1601 @@
1
+ """Every command's answer, once it is a string or a payload (RK493).
2
+
3
+ Split out of :mod:`roadkeep.cli`, which had grown to 8,489 lines holding the parser, the
4
+ 82 handlers and this — so an edit to one verb's printed sentence was made in the file the
5
+ whole surface is in, and that file's growth rule appends to it every task.
6
+
7
+ The printers went first because theirs is the cut with no import cycle: not one of them
8
+ calls a handler or the parser, so the dependency runs one way and `cli` imports what it
9
+ prints with. That is also the half a verb's edit reads least — a handler decides what is
10
+ computed, and the sentence stating it is read once.
11
+
12
+ Two kinds live here and they answer the same question in the two registers RK4 declared:
13
+ `_print_*` writes the plain stdout a shell composes with, and `*_json` builds the payload
14
+ `--json` carries. Neither reads a file or takes a lock: what arrives is already the result
15
+ of a transaction, and what leaves is text. Refusals are a code and left where they were.
16
+
17
+ A third kind arrived with RK494 and belongs by the same rule: the line-makers two verb
18
+ families both spell — a section's word count, a governed file's name, the wiring report
19
+ `install` and `merge --check` each print. They are not `_print_*` only because they return
20
+ their sentence instead of writing it; the alternative was a shared module holding text.
21
+
22
+ The consequence to expect (RK79): :mod:`roadkeep.provenance` reads module names off a
23
+ traceback, so a refusal decided inside a printer now names this file. That is the truth
24
+ about which code answered, which is the whole point of that read.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ from collections.abc import Iterable, Sequence
31
+
32
+ from roadkeep import claiming, criteria
33
+ from roadkeep.adopting import Estimate
34
+ from roadkeep.authoring import StatusChange
35
+ from roadkeep.backlog import Backlog, Stage
36
+ from roadkeep.briefing import NothingToBrief
37
+ from roadkeep.budgeting import Load
38
+ from roadkeep.claiming import Followed, Held
39
+ from roadkeep.config import Config, PROSE_ROLES
40
+ from roadkeep.deferring import Carried
41
+ from roadkeep.kernel.document import Document, Entry, Reject
42
+ from roadkeep.graph import Leverage
43
+ from roadkeep.history import Commit, Origin
44
+ from roadkeep.ids import Promise
45
+ from roadkeep.merging import (
46
+ ABSENT,
47
+ Attributes,
48
+ CURRENT,
49
+ DRIVER,
50
+ DRIVER_KEY,
51
+ Driver,
52
+ MOVED,
53
+ Registration,
54
+ UNKNOWN,
55
+ UNRUNNABLE,
56
+ Wiring,
57
+ )
58
+ from roadkeep.picking import Choice, Claim
59
+ from roadkeep.provenance import invocation, served_by
60
+ from roadkeep.remedying import Door
61
+ from roadkeep.kernel.schema import UTF16_UNITS, width as measured_width
62
+ from roadkeep.verbs.refusing import EXIT_GATE, EXIT_OK
63
+
64
+
65
+ #: What every character figure this tool publishes is counted in (RK430). Declared in the
66
+ #: payload rather than assumed, because the defect was two counters both being right: a
67
+ #: consumer's gate reading UTF-16 and a `len` reading code points differ by one on the
68
+ #: status marker this tool writes, and neither number carried the unit that settles it.
69
+ #: The same string `[limits]`' own vocabulary spells it with (RK437), so the unit a payload
70
+ #: declares and the unit a report names are one fact and cannot drift into two spellings.
71
+ CHARACTER_UNIT = UTF16_UNITS
72
+
73
+
74
+ def _promise_json(promise: Promise | None) -> dict[str, object] | None:
75
+ """The id a sentence named and the derivation stepped over (RK431), or nothing."""
76
+ if promise is None:
77
+ return None
78
+ return {
79
+ "id": promise.id,
80
+ "where": promise.where,
81
+ "derived": promise.derived,
82
+ "sentence": promise.sentence,
83
+ }
84
+
85
+
86
+ def _followed_rows(change: StatusChange, config: Config) -> list[str]:
87
+ """What the marker did to the claim on its line (RK158), and never silently.
88
+
89
+ A marker change is not obviously an assertion of ownership to whoever typed it, so the
90
+ door says which of the two it just made — the same reason `pick` names the claim it took
91
+ rather than only moving it.
92
+
93
+ Rows and no longer a printer (RK1170), like every other phrasing two registers share: the
94
+ verb composes its whole answer where the record is, and one seam writes it.
95
+ """
96
+ if change.claim is Followed.CLAIMED:
97
+ return [f" claimed held for {config.held}m unless a marker moves it sooner"]
98
+ if change.claim is Followed.RELEASED:
99
+ # `dropped` and not `released`: every label in this output is padded to one width, and
100
+ # the eight-letter word is the one that would not fit it.
101
+ return [" dropped the claim on this line is released"]
102
+ return []
103
+
104
+
105
+ def _event(task_id: str, block: str, roadmap: Document, config: Config) -> dict[str, object]:
106
+ """What changed, where, and what became of that place (RK38).
107
+
108
+ Three facts and no more. "This block is done" stays a *derived* fact about the files
109
+ every mutator just wrote, so it cannot go stale the way a queued message can, and the
110
+ tool never learns what happens next.
111
+
112
+ The third of them is :class:`~roadkeep.backlog.Stage` and no longer a boolean (RK438).
113
+ It was `not roadmap.holds(block)`, printed as `empty` — the roadmap holds no line under
114
+ the label, which is the single moment a heading becomes droppable and is why RK408 hung
115
+ the offer on it. RK429 then gave that word a second meaning, a block nothing has *ever*
116
+ filed under as opposed to one that is `finished`, and the two disagreed out loud:
117
+ shipping the last line of Block C here printed `Block C empty` beside an offer to
118
+ withdraw the heading while `pick --block C` answered `Block C is finished: the ledger
119
+ records 12 filed under it`. Both were right about their own question and one word was
120
+ carrying them.
121
+
122
+ So the event asks for the state the tool already computes, through the reader every
123
+ query uses — `Backlog.during`, so the roadmap is the one this transaction just wrote and
124
+ the ledger and the store are read (RK92). What the offer below hangs on is now *which*
125
+ state, which is the thing it always needed: a paused block has nothing open and is not
126
+ droppable, and under the old boolean it was told to run a command that refuses.
127
+ """
128
+ standing = Backlog.during(config, roadmap=roadmap).standing(block)
129
+ # And **what is left**, in the shape `list` answers with (RK1164). The standing was read
130
+ # here and reduced to one word, so a caller driving a block one task at a time followed
131
+ # every ship with a `list` asking what this call already knew — measured at six ships and
132
+ # six calls over one block. `stage` stays beside it: it is what the offer below branches
133
+ # on and what every consumer written before this reads.
134
+ return {
135
+ "id": task_id,
136
+ "block": block,
137
+ "stage": str(standing.stage),
138
+ "standing": None if standing is None else standing.payload(),
139
+ # And **what decided whether the word is true** (RK1300). RK1265 put the definition of
140
+ # done where a ship cannot delete it and said when to read it — before the block's last
141
+ # open line ships — but nobody knows a line is the last one until this call answers, so
142
+ # the reading always happened after, and only where a project's own skill file
143
+ # remembered to say so. Measured on winwright: two blocks emptied in one sitting, both
144
+ # events said `finished` with the standing and the count, and both readings then cost a
145
+ # `criterion list` that this transaction had already read the file for.
146
+ #
147
+ # Only on `finished`, which is the one stage the question is owed at: `empty` is a
148
+ # heading opened before its lines and has nothing to have satisfied, `paused` is not
149
+ # done, and a standing category (RK1180) is caught up rather than finished — so a list
150
+ # printed there would be asked forever and answered never. Nothing is enforced and
151
+ # nothing could be: whether the work satisfies a criterion is a judgement (L4).
152
+ "criteria": [
153
+ {"lead": one.lead, "why": one.why}
154
+ for one in (
155
+ criteria.read(roadmap, block) if standing.stage is Stage.FINISHED else ()
156
+ )
157
+ ],
158
+ # And the answer where there is no definition (RK1358). A block that finished with
159
+ # none read exactly like one that met its criteria — *nothing open, and the ledger
160
+ # records N filed under it*, the same two facts, with the list simply absent — and
161
+ # that is the reading a session takes on the turn it stops working. Measured on this
162
+ # repository: three of eight blocks declare any, and Block B closed on emptiness a
163
+ # dozen times over one session.
164
+ #
165
+ # Decided by the **file and not the config**, which is where the first attempt at this
166
+ # was wrong: `init` writes `[criteria]` into every project it scaffolds, so the table
167
+ # is a default and not an opt-in, and a predicate reading it would have printed this
168
+ # on every block of every scaffold. What says a project uses the feature is a block
169
+ # that has criteria — so one that has none, beside siblings that do, is an omission,
170
+ # and a project with none anywhere is one this has nothing to tell. Only on
171
+ # `finished`, for the reason the list above is.
172
+ "unchecked": bool(
173
+ standing.stage is Stage.FINISHED
174
+ and not criteria.read(roadmap, block)
175
+ and criteria.read(roadmap)
176
+ ),
177
+ # And the one command this state makes available (RK408, RK1319), which RK38 excluded
178
+ # and which stopped being excludable. That decision was right when it was made: the
179
+ # event carried three facts and no suggestion, on the argument that a consumer deriving
180
+ # the next command **from the stage** would be handed it twice, and `_DROPPABLE` was a
181
+ # map of two stages a caller could reproduce.
182
+ #
183
+ # RK1121 ended it. `[headings] permanent` made the offer depend on a second fact, and
184
+ # RK1319's own falsification then decided which half was missing: the key is reachable
185
+ # — `config --json` publishes it, declared and with its value — and the *map* is
186
+ # published nowhere, so a consumer had to hardcode which stages allow the offer. That
187
+ # ruled out the other shape this task weighed, publishing `permanent` beside the stage,
188
+ # which would have been a second copy of a read that already answers.
189
+ #
190
+ # `doors` and always a list (RK1324), empty where no offer applies: one name and
191
+ # one shape wherever a payload publishes a runnable command, so a consumer reads
192
+ # them with one loop instead of four names.
193
+ "doors": [
194
+ one.payload(_served(config))
195
+ for one in (_drop_door(config, block, standing.stage),)
196
+ if one is not None
197
+ ],
198
+ }
199
+
200
+
201
+ def _drop_door(config: Config, block: str, stage: Stage) -> Door | None:
202
+ """The heading this state makes droppable, or `None` (RK408).
203
+
204
+ One reader for both registers since RK1319, which is where RK38's exclusion was argued out
205
+ rather than swept up: RK1307 left this one alone on purpose, because a decision argued and
206
+ held by a test is not an omission, and reopening it inside a task about a different class
207
+ would have been a change nobody could find later.
208
+
209
+ What changed is the premise. RK38 excluded the suggestion because a consumer could derive
210
+ it *from the stage*, and RK1121's `[headings] permanent` made the offer depend on a second
211
+ fact. Which one was missing is what that line's falsification settled: the key is reachable
212
+ — `config --json` publishes it — and this map is published nowhere.
213
+ """
214
+ because = None if config.permanent_headings else _DROPPABLE.get(stage)
215
+ if because is None:
216
+ return None
217
+ return Door(("block", "drop", block), because)
218
+
219
+
220
+ #: The two stages a heading is droppable in, and the clause that says which one it is
221
+ #: (RK438). `finished` and `empty` are the states where `block drop` can work: nothing open,
222
+ #: and nothing paused holding the label. `live` needs no offer and `paused` must not have
223
+ #: one — the store files lines under that heading, so the command refuses, and naming an
224
+ #: edit that cannot work is worse than naming no edit at all (RK16). The word beside the
225
+ #: event is what tells a paused caller why the offer is absent.
226
+ #: No row for :attr:`Stage.CURRENT` (RK1180), which is the whole of that task's first half: a
227
+ #: standing category is caught up and not finished, so there is no heading to offer to withdraw —
228
+ #: measured as three declare-empty-drop cycles in one session, each drop followed within the hour
229
+ #: by a finding that re-declared the block.
230
+ _DROPPABLE = {
231
+ Stage.FINISHED: "its last open line just left",
232
+ Stage.EMPTY: "no file files a task line under it",
233
+ }
234
+
235
+
236
+ def _event_rows(
237
+ event: dict[str, object], indent: str, *, standing: bool = False
238
+ ) -> list[str]:
239
+ """The event, and where the stage allows it the one command that state makes available.
240
+
241
+ A heading becomes droppable the moment its block stops holding work, and a project whose
242
+ roadmap reads as a list of what is left has every reason to withdraw it. Until RK408 the
243
+ answer computed that state and stopped one word short of the verb — so the caller was
244
+ told a block is finished and left to remember `block drop` from somewhere other than the
245
+ sentence telling them it applies.
246
+
247
+ The same commitment `add` already makes: an `add` without `--section` answers with the
248
+ `section add` that closes the pointer it just created, rather than leaving the gate to
249
+ report the dangling reference a turn later. This is that situation one verb earlier.
250
+
251
+ A **suggestion and never an action**. Whether an emptied block is dropped or kept for
252
+ work still to be filed under it is the project's call, `block drop` refuses anyway where
253
+ the subtree is not blank in every file, and a ship that withdrew a heading nobody asked
254
+ it to would be the tool deciding the shape of the plan.
255
+
256
+ And since RK1121 the project may answer that call **once** rather than in every run's
257
+ reading: `[headings] permanent` says the headings outlive the work filed under them, and
258
+ the offer is then absent instead of hedged. The `stage` word stays either way — the state
259
+ is a fact and only the suggestion was a question the file could answer.
260
+
261
+ **This printer decides none of it** (RK1319). The offer is composed where the event is, so
262
+ a `config` no longer reaches here: it was a required keyword precisely so a printer could
263
+ not fall back to offering, and the way to make that impossible is to leave the printer
264
+ nothing to fall back *to*. What it renders now is the door the payload carries or no row.
265
+
266
+ ``indent`` is **required** for that same reason (RK1372). It defaulted to `""` and one
267
+ caller of ten took the default: `add`, whose own rows then sat at column 0 while the
268
+ `stage` row beside them sat at 2 — one answer at two columns, in the verb this tool prints
269
+ most. A default nobody wants is a column a caller is opted into by not thinking about it.
270
+ """
271
+ stage = event["stage"]
272
+ rows = [f"{indent}event {event['id']} Block {event['block']} {stage}"]
273
+ # What is left, on the line under it — for the two verbs a caller **drives a block** with
274
+ # (RK1164). `ship` and `retire` are where the follow-up `list` was measured, and where the
275
+ # live count is the question being asked: *is this block finished, and is there another*.
276
+ # Every other write says the stage and no more, which is RK1143's rule about a line that is
277
+ # never the next step; the payload carries the counts for all of them, a key costing a
278
+ # client nothing to skip where a line costs every reader the same attention.
279
+ #
280
+ # `_print_standing` stays silent on a live block for its own reason: there an empty listing
281
+ # was the filter's doing, and here the count is the answer.
282
+ left = event.get("standing") if standing else None
283
+ if isinstance(left, dict) and left.get("sentence"):
284
+ rows.append(f"{indent} {left['sentence']}")
285
+ # And what decides whether `finished` is true (RK1300), on the two verbs a caller drives a
286
+ # block with and for the reason the count above is there: the word arrives here, so the
287
+ # list it is a claim about has to arrive here too or it is read somewhere else or not at
288
+ # all. One row per criterion and the `why` with it — the lead alone is the address and not
289
+ # the test, and a reader deciding whether to open the next block is reading the test.
290
+ if standing:
291
+ rows += [
292
+ f"{indent} done when {one['lead']} — {one['why']}"
293
+ for one in event.get("criteria", ()) # type: ignore[union-attr]
294
+ ]
295
+ # And the sentence where that list is empty (RK1358), with the verb that ends it: a
296
+ # finish saying only what is left says nothing about what was owed, and the two read
297
+ # alike. Named rather than counted — *no criteria* is the fact, and `criterion add`
298
+ # is what a reader does about it before the next block is opened.
299
+ if event.get("unchecked"):
300
+ rows.append(
301
+ f"{indent} done when nothing — this block declares no criteria, so "
302
+ f"it finished on being empty: `{invocation()} criterion add --block "
303
+ f"{event.get('block')} --lead … --why …` states what it was for"
304
+ )
305
+ # Read off the event and never recomputed (RK1319): the offer is one decision, and a
306
+ # printer deciding it again is a second answer about whether a heading may go.
307
+ for door in event.get("doors", ()): # type: ignore[union-attr]
308
+ rows.append(
309
+ f"{indent} {door['what']} — "
310
+ f"`{invocation()} {' '.join(door['argv'])}` withdraws the heading, "
311
+ f"where this project drops one"
312
+ )
313
+ return rows
314
+
315
+
316
+ def _decided_body_rows(task_id: str, anchor: str = "") -> list[str]:
317
+ """The `section add` that gives a decision the half its line cannot hold (RK1361).
318
+
319
+ The line records that a decision was made and what it constrains; what was *weighed* —
320
+ the alternatives rejected and the consequences accepted — is a paragraph, and until the
321
+ decisions role became a prose file it had no governed home at all. Named here for
322
+ `Insertion.follow_up`'s reason and with its restraint: the call and its address are
323
+ derived, and the words in it are the author's (L4).
324
+
325
+ Printed on every `--decides` and never conditional on the body being absent. A `ship` is
326
+ one transaction and the body is written after it, so there is no state this could read to
327
+ know one is coming — and a row that appeared only sometimes would teach the two-command
328
+ path as an exception rather than as the shape.
329
+
330
+ ``anchor`` is the record's own pointer where it carries one (RK1363), which is every
331
+ outline project: there the address is the caller's `--decides-ref` and never the id, so a
332
+ row composed from the id alone printed a command that project refuses `anchor.format`.
333
+ Defaulted to the id, which is what the anchor *is* under `ref_scheme = "id"`.
334
+ """
335
+ return [
336
+ f" weighed `{invocation()} section add {anchor or task_id} --role decisions "
337
+ f"--title …` (the line records the decision; what it was weighed against goes here)"
338
+ ]
339
+
340
+
341
+ def _dequeued_rows(token: str | None) -> list[str]:
342
+ """What a departure took out of the priority queue (RK327).
343
+
344
+ Said and never silent, because a departure that quietly shortened the plan would be an
345
+ ordering changed with no sentence about it — and the printed line is what a reviewer
346
+ reads the diff against (RK298).
347
+
348
+ Rows and no longer a printer (RK1170): three verbs share this sentence and each of them
349
+ is moving its whole answer onto its record, which a function that prints cannot join.
350
+ """
351
+ if token is None:
352
+ return []
353
+ return [f" dequeued {token} left the priority queue with the line"]
354
+
355
+
356
+ def _unmet_rows(leads: Sequence[str], went_with: str = "the line") -> list[str]:
357
+ """What a departure took out of a criteria list (RK1268, RK1316).
358
+
359
+ `_dequeued_rows`' sentence one list over and for its reason: the heading is addressed by an
360
+ address this write spends, so it goes inside the transaction — and a definition of done
361
+ that disappeared with no line about it is exactly the deletion RK1268 was filed against.
362
+
363
+ ``went_with`` is **what** was spent, because two writes now spend an address: a departure
364
+ spends the line and `block drop` spends the label (RK1316). One sentence with the noun
365
+ passed in, and not two spellings of it: the fact is the same and only the address differs.
366
+ """
367
+ if not leads:
368
+ return []
369
+ return [f" finished {lead} — its criterion left with {went_with}" for lead in leads]
370
+
371
+
372
+ def _carried_json(config: Config, carried: Carried | None) -> dict[str, str | None] | None:
373
+ """The same answer as fields, so a caller reads the file rather than parsing a sentence."""
374
+ if carried is None:
375
+ return None
376
+ return {
377
+ "anchor": carried.anchor,
378
+ "role": carried.role,
379
+ "file": None if carried.role is None else config.relative(config.path(carried.role)),
380
+ "absence": carried.absence or None,
381
+ }
382
+
383
+
384
+ def _emptied_rows(parent: str | None) -> list[str]:
385
+ """The parent this drop left introducing children that have all shipped (RK400).
386
+
387
+ Beside the citation line and for the same reason: this is the only moment it can be
388
+ said. `ship` deletes the task's own section and names what cited it; under an outline it
389
+ leaves the **parent** standing, and that paragraph was written as an introduction to the
390
+ children — it states the problem they solve, in the present tense, and it is the first
391
+ thing anyone reads about that family.
392
+
393
+ Noticing is the tool's; what the introduction should say instead is a `section amend` and
394
+ a judgement (L4). So the sentence names the anchor and the door, and writes nothing.
395
+
396
+ Rows and no longer a printer (RK1170): the verbs that say this are moving their whole
397
+ answer onto their records, which a function that prints cannot be part of.
398
+ """
399
+ if parent is None:
400
+ return []
401
+ return [
402
+ f" emptied §{parent} now has no subsections — its prose introduces work that has "
403
+ f"shipped; `section amend {parent} --body -` is the edit, in this commit"
404
+ ]
405
+
406
+
407
+ def _premise_rows(edits: Sequence[str], design: str) -> list[str]:
408
+ """The two other places the claim a restatement replaced is also written (RK1196).
409
+
410
+ Beside the citation line and the emptied one, and for their reason: this is the only
411
+ moment it can be said. `restate` is the one verb here that *knows* a claim was wrong, and
412
+ the `why` beneath that claim and the section arguing from it are written from the same
413
+ premise — so from the next command on they read as prose somebody meant, and only the
414
+ author who just corrected the symptom is holding the fact that they do not.
415
+
416
+ A report and never a refusal, which is the difference between this and a rule. Whether the
417
+ `why` still holds is a judgement about meaning and this tool has none (L4), so it names the
418
+ doors with the id already in them and leaves the reading where it belongs.
419
+ """
420
+ if not edits:
421
+ return []
422
+ also = f"the `why` and §{design} were" if design else "the `why` was"
423
+ return [
424
+ f" premise {also} written from the claim this replaced — whether they still hold "
425
+ f"is a reading",
426
+ f" next {', '.join(f'`{one}`' for one in edits)} "
427
+ f"{'is the edit' if len(edits) == 1 else 'are the edits'}, in this commit",
428
+ ]
429
+
430
+
431
+ def _cited_rows(cited: Sequence[str]) -> list[str]:
432
+ """Who is left pointing at prose this command deleted (RK206).
433
+
434
+ Said here and gated nowhere, because this is the only moment it can be said: `ship`
435
+ creates the dangling citation, `as_ledger` keeps no pointer, and from the next command
436
+ on a reference to a section that shipped reads exactly like a typo. The ship is right —
437
+ what the author owes is one edit in the same commit, and this is the sentence that asks
438
+ for it.
439
+
440
+ Rows and no longer a printer (RK1170), for the reason its neighbour above is.
441
+ """
442
+ if not cited:
443
+ return []
444
+ return [
445
+ f" cited {', '.join(f'§{a}' for a in cited)} "
446
+ f"{'cites' if len(cited) == 1 else 'cite'} it in prose — now resolving to nothing"
447
+ ]
448
+
449
+
450
+ def _scope_rows(scope: claiming.Scope | None, wrote: Sequence[str] = ()) -> list[str]:
451
+ """What the tree holds that this commit's claim does not name (RK280, RK294).
452
+
453
+ Silent on a `None`, which is a project no claim spoke for — there the whole answer would
454
+ be `git status` under a heading claiming to have read something.
455
+
456
+ `wrote` is what the transaction **itself** just wrote, projections included (RK309), and
457
+ it joins the staging line without joining the scope: the scope is what the holder said,
458
+ verbatim, and these are not a declaration to be corrected but a record to be used. Six
459
+ scopes across one block named the roadmap, the ledger, the rationale file and the README
460
+ by hand, four of ten paths on the longest, and none of the four was a judgement anyone
461
+ made. They leave `loose` for the same reason — a path this command wrote is not a change
462
+ no claim accounts for, and saying both in one answer is the tool contradicting itself.
463
+
464
+ **And the scope itself, at a departure** (RK298). `claim <id>` may leave it out, the
465
+ caller having just declared it; a ship may not, because the ship is what *releases* it —
466
+ after it, `claim <id> --porcelain` refuses with "no live claim" and the `status <id> 🛠` it
467
+ names is refused too, the ledger now holding the id. So the one moment a commit needs the
468
+ answer is the one moment the verb for it stops answering, and this is the output the
469
+ committer is already reading. Spelled as the command rather than as a list, the shape
470
+ every other unreachable next step in this tool takes (RK257): what the author does with
471
+ these paths is stage them.
472
+
473
+ Rows and no longer a printer (RK1170): a departure composes its whole answer where the
474
+ record is, and the longest list in it cannot be the one part that writes itself.
475
+ """
476
+ if scope is None:
477
+ # The staging line is still owed (RK1130). What needs a claim is the *subtraction* —
478
+ # which paths are somebody else's — and a project that declared none was getting no
479
+ # `git add --` line at all from the two verbs that had one, on the write with the most
480
+ # files in it. So the silence stays where it belongs: on the three lists below.
481
+ return _staging_rows(dict.fromkeys(wrote))
482
+ rows = _staging_rows(dict.fromkeys((*scope.mine, *wrote)))
483
+ rows += [f" theirs {one} ({who} is holding it)" for one, who in scope.theirs]
484
+ # Beside the staging and not instead of it (RK1120): the file is staged either way — this
485
+ # transaction wrote it — and what the author needs is the ids inside it that this commit is
486
+ # not about, which is the hunk to leave out rather than a path to drop.
487
+ rows += [
488
+ f" shared {one} ({', '.join(others)} moved in it too, and staging it takes that)"
489
+ for one, others in scope.shared
490
+ ]
491
+ # No filter here since RK1117: `loose` already excludes what this id explains, and the
492
+ # subtraction moved to `split` because the two callers meant different things by the list
493
+ # this used to read — a departure's `wrote` is what the transaction wrote, and a governed
494
+ # file it wrote *and* somebody else had changed vanished from both reports.
495
+ # And whether the index already carries it (RK1197): a `git commit` takes a staged path
496
+ # whether or not the author reads a diff, and the diff they are reading is the other side.
497
+ rows += [
498
+ f" loose {one} "
499
+ f"({'staged already, and ' if one in set(scope.staged) else ''}no claim names it)"
500
+ for one in scope.loose
501
+ ]
502
+ # The declared paths that would stage nothing (RK295). Named here rather than folded into
503
+ # `mine`, which this list deliberately does not repeat: at a departure the work is done, so
504
+ # a scope naming a file the tree does not have is a typo and not a file yet to be written.
505
+ rows += [f" typo? {one} (declared, and stages nothing)" for one in scope.idle]
506
+ return rows
507
+
508
+
509
+ def _wrote_json(config: Config, paths: Iterable[Path]) -> dict[str, object]:
510
+ """The `wrote` key, spelled once for every write that answers one (RK1129, RK1130).
511
+
512
+ A fragment merged into each payload rather than a field on each record, because what a
513
+ client does with it is the same `git add` whichever verb answered — and a key spelled per
514
+ verb is a key that comes to differ per verb. Relative, like every path in every payload
515
+ here: an absolute one is a fact about the machine that ran the command.
516
+ """
517
+ return {"wrote": [config.relative(one) for one in paths]}
518
+
519
+
520
+ def _print(rows: Iterable[str]) -> bool:
521
+ """Write what a row producer returned, and say whether there was anything (RK1170).
522
+
523
+ The seam while the verbs move onto their records: a register composes rows where the answer is
524
+ and this writes them, so a caller that used to read *did it print* still can — `pick` closes
525
+ with an event line only where a claim was actually taken.
526
+
527
+ One definition and not one per verb file, which is the rule this whole task is about: three of
528
+ them existed within an hour of the first, and a fourth file using the name without one is how
529
+ 106 tests found out.
530
+ """
531
+ for row in rows:
532
+ print(row)
533
+ return bool(rows)
534
+
535
+
536
+ def _staging_rows(paths: Iterable[str]) -> list[str]:
537
+ """The `git add --` line, spelled in one place (RK298, RK1129).
538
+
539
+ Every write says it — a departure, which releases the scope nothing can read back afterwards,
540
+ an `add` refreshing a projection the commit was leaving behind, and twenty-six others — so the
541
+ quoting and the label are here rather than at each of them. Nothing for an empty list: a
542
+ command that wrote no file has no staging to advise, and a bare `git add --` is a line
543
+ somebody would paste.
544
+
545
+ Rows and no longer a print since RK1170: a write verb moving onto its record composes what it
546
+ returns, and a helper that printed could only be reached from a handler.
547
+ """
548
+ staging = tuple(paths)
549
+ if not staging:
550
+ return []
551
+ return [f" stage git add -- {' '.join(_shell(one) for one in staging)}"]
552
+
553
+
554
+ def _shell(path: str) -> str:
555
+ """One path as a shell would take it: quoted only where a space would split it (RK298).
556
+
557
+ Double quotes, the spelling :func:`~roadkeep.provenance._spelled` already uses for a
558
+ command a reader copies — a path is declared verbatim (RK280) and may hold a blank, and a
559
+ `git add --` line that split one in two would stage two files that do not exist.
560
+ """
561
+ return f'"{path}"' if " " in path else path
562
+
563
+
564
+ def _scope_json(
565
+ scope: claiming.Scope | None, wrote: Sequence[str] = ()
566
+ ) -> dict[str, object] | None:
567
+ """The same lists as fields, so a caller stages them rather than parsing a sentence.
568
+
569
+ `mine` stays the declaration and `wrote` is its own key (RK309): a client that merged them
570
+ would be reading a scope this tool did not receive, and the two answer different questions.
571
+ """
572
+ if scope is None:
573
+ return None
574
+ return {
575
+ "mine": list(scope.mine),
576
+ "wrote": list(wrote),
577
+ "theirs": [{"path": one, "claimed_by": who} for one, who in scope.theirs],
578
+ # Already subtracted (RK1117), so the payload and the printed report cannot disagree
579
+ # about which paths belong to nobody.
580
+ "unclaimed": list(scope.loose),
581
+ # Which of them the index already carries (RK1197). A subset and its own key, because
582
+ # a client acting on `unclaimed` decides, and one acting on this has already been
583
+ # committed to by a `git add` nobody in this session typed.
584
+ "unclaimed_staged": list(scope.staged),
585
+ "staging_nothing": list(scope.idle),
586
+ # RK1120: per governed file, the other ids whose line moved in it. Its own key beside
587
+ # `unclaimed`, because the two are different answers — a path nobody claims, and a path
588
+ # this commit does claim that is carrying somebody else's line.
589
+ "shared": [{"path": one, "ids": list(ids)} for one, ids in scope.shared],
590
+ }
591
+
592
+
593
+ def _tree(root: str) -> str:
594
+ """Which tree the report is about (RK299) — unconditionally, and in the shape `--version`
595
+ already uses for which *engine* answered (RK79).
596
+
597
+ Every path above is relative to this and nothing above says what it is relative to, so a
598
+ run in the wrong directory produces a report that is right about a repository nobody asked
599
+ about. Observed: 34 findings and a clean summary line for another project entirely, where
600
+ the only clue was one filename the misread project does not have.
601
+
602
+ Never conditional on it differing from the working directory. That is a second rule to
603
+ remember, and it makes the attribution appear exactly when a reader has already stopped
604
+ expecting it — the same argument as naming the files on a clean run.
605
+ """
606
+ return f" (in {root})"
607
+
608
+
609
+ def _served(config: Config) -> str:
610
+ """The prefix this session's tools arrive under, or `""` where it has none (RK449).
611
+
612
+ One reader for the four payloads that publish a remedy, because it is one question about
613
+ one project and four calls to `serving` would be four places to forget it — and since
614
+ RK488 it is `provenance.served_by`'s answer rather than a fourth spelling of it, the guard
615
+ and the attestation having each written the same `or ""` for themselves.
616
+ """
617
+ return served_by(config.root)
618
+
619
+
620
+ def _row_json(entry: Entry) -> dict[str, object]:
621
+ task = entry.task
622
+ return {
623
+ "id": task.id,
624
+ "status": task.status,
625
+ "block": task.block,
626
+ "symptom": task.symptom,
627
+ "why": task.why,
628
+ "deps": [dep.render() for dep in task.deps],
629
+ "ref": task.ref,
630
+ "line": entry.lineno,
631
+ "length": measured_width(entry.raw),
632
+ }
633
+
634
+
635
+ def _miss_json(miss: Reject) -> dict[str, object]:
636
+ return {
637
+ "line": miss.lineno,
638
+ "block": miss.block,
639
+ "reason": miss.reason,
640
+ "raw": miss.raw,
641
+ }
642
+
643
+
644
+ def _nothing_json(nothing: NothingToBrief, args: argparse.Namespace) -> dict[str, object]:
645
+ """The finished-block answer, in the shape it was asked for (RK409).
646
+
647
+ `reason` is the sentence `pick` composed, carried verbatim rather than re-derived: the
648
+ two answers about why nothing is ready would otherwise be two, and this is the one place
649
+ a caller reads it without a task beside it.
650
+
651
+ `held` is the field the prose already carried (RK154). "Every ready task is claimed by a
652
+ worker who has not finished it" is the one absence a caller cannot act on without the
653
+ ids — its own claim being the one it would otherwise ask about again next turn — so a
654
+ payload that dropped them would make the machine-readable form the poorer answer.
655
+ """
656
+ return {
657
+ "brief": None,
658
+ "empty": True,
659
+ "block": args.block,
660
+ "designed": args.designed,
661
+ "reason": nothing.reason,
662
+ # The boolean could not carry the third state and still cannot (RK429): `empty` is
663
+ # true for a finished block, a heading opened before its lines and a backlog whose
664
+ # every line is blocked. It stays, because a caller reading it is reading the
665
+ # question it asked; this says which of them answered.
666
+ "standing": None if nothing.standing is None else nothing.standing.payload(),
667
+ "held": [{"id": one.id, "since": one.since} for one in nothing.held],
668
+ # `held`'s argument one axis over (RK1297): the absence a caller can act on least by
669
+ # itself is the one whose remedy is another person, so the ids and the requirements
670
+ # are exactly what an empty answer has to carry out of the call.
671
+ "lacking": [
672
+ {"id": one.id, "missing": list(one.missing)} for one in nothing.lacking
673
+ ],
674
+ }
675
+
676
+
677
+ def _load_json(load: Load) -> dict[str, object]:
678
+ return {
679
+ "path": load.path,
680
+ "present": load.present,
681
+ "over": load.over,
682
+ "units": [
683
+ {"unit": c.unit, "limit": c.limit, "taken": c.taken, "left": c.left, "over": c.over}
684
+ for c in load.costs
685
+ ],
686
+ # Every section and not the largest few (RK1092), for `by_tool`'s reason: a caller
687
+ # reading this to decide what to cut is reading a payload, and the terminal is
688
+ # reading a report. Empty where the file is not on disk.
689
+ # In the order the report shows them (RK1252) — ranked by the limit about to refuse,
690
+ # so a consumer acting on the first row acts on the same section a reader would.
691
+ "parts": [
692
+ {
693
+ "heading": part.heading,
694
+ "lines": part.lines,
695
+ "bytes": part.bytes,
696
+ # The reading, per section (RK1253) — beside the two declared units and never
697
+ # the key this list is ordered by, which is the ceiling's.
698
+ "characters": part.characters,
699
+ }
700
+ for part in load.ranked
701
+ ],
702
+ # What this checkout pays over the counted number (RK1105), so a caller comparing two
703
+ # machines has the difference as a field instead of inferring it from a mismatch.
704
+ "translated": load.translated,
705
+ # The same text in the unit a model is charged in (RK1250), and `null` where it does
706
+ # not decode. Outside `units` deliberately: everything in that list is a declared
707
+ # limit and this is a reading, so a caller iterating limits must not meet it.
708
+ "characters": load.characters,
709
+ }
710
+
711
+
712
+ def _pick_json(
713
+ config: Config,
714
+ choice: Choice,
715
+ claim: Claim | None,
716
+ event: dict[str, object] | None,
717
+ ) -> dict[str, object]:
718
+ """The answer as one object, beside `_brief_json` and for the same reason it exists."""
719
+ entry = choice.entry
720
+ return {
721
+ "pick": None
722
+ if entry is None
723
+ else {
724
+ "id": entry.task.id,
725
+ "block": entry.task.block,
726
+ "status": entry.task.status,
727
+ "file": config.relative(config.path("roadmap")),
728
+ "line": entry.lineno,
729
+ "symptom": entry.task.symptom,
730
+ "ref": entry.task.ref,
731
+ },
732
+ "tier": None if choice.tier is None else str(choice.tier),
733
+ "reason": choice.reason,
734
+ "scope": choice.block,
735
+ # Beside `scope` and never instead of it (RK429): the label is what was asked and
736
+ # this is what became of it, so a loop scoped to a block reads one word rather than
737
+ # matching the sentence `reason` states it in.
738
+ "standing": None if choice.standing is None else choice.standing.payload(),
739
+ "alternatives": list(choice.alternatives),
740
+ "ready": choice.ready,
741
+ "blocked": choice.blocked,
742
+ "outside": choice.outside,
743
+ "paused": choice.paused,
744
+ "needs_design": choice.needs_design,
745
+ "undesigned": choice.undesigned,
746
+ # `claimed` on a stalled line and `held` beside it are two facts with two names
747
+ # (RK152): one is a line somebody is on that nothing could offer, the other is a
748
+ # candidate the ranking stepped around.
749
+ "stalled": [
750
+ {"id": s.id, "blockers": list(s.blockers), "claimed": _held_json(s.claimed)}
751
+ for s in choice.stalled
752
+ ],
753
+ "held": [{"id": h.id, "age": round(h.age), "since": h.since} for h in choice.held],
754
+ "claimed": None
755
+ if claim is None
756
+ else {
757
+ "taken": claim.taken,
758
+ "from": None if claim.change is None else claim.change.before,
759
+ "to": None if claim.change is None else claim.change.after,
760
+ },
761
+ "event": event,
762
+ }
763
+
764
+
765
+ def _held_json(held: Held | None) -> dict[str, object] | None:
766
+ """One claim as an age and a duration, or nothing where the line is not held."""
767
+ if held is None:
768
+ return None
769
+ return {"age": round(held.age), "since": held.since}
770
+
771
+
772
+ def _claim_event(claim: Claim | None, config: Config) -> dict[str, object] | None:
773
+ """RK38's event line for a claim, or nothing where no line was taken."""
774
+ if claim is None or claim.change is None:
775
+ return None
776
+ entry = claim.change.entry
777
+ return _event(entry.task.id, entry.task.block, claim.change.document, config)
778
+
779
+
780
+ # -- the sentences `pick` and `brief` share, as rows (RK1170) ------------------
781
+ #
782
+ # Rows and no longer prints. Both verbs are moving onto their records, and a register composes
783
+ # what it returns — a helper that printed could only be called from a handler, which is what kept
784
+ # two verbs' answers in the file that neither of their records is in. Every sentence below is the
785
+ # one that was printed, and every guard is where it was: what changed is who does the writing.
786
+
787
+
788
+ def _claim_rows(claim: Claim | None, config: Config) -> list[str]:
789
+ """What a claim moved, on the two commands that can take one (RK119, RK149).
790
+
791
+ One sentence and one place, because two commands printing the same fact in two wordings
792
+ is two answers to "what did I just take". Empty where nothing was taken, which is what tells
793
+ `pick` there is no event line to close with. The window comes from the config and is not
794
+ a constant here (RK151): a project that declared its own would otherwise be told the
795
+ default's number by the command that just applied its own.
796
+ """
797
+ if claim is None or claim.change is None:
798
+ return []
799
+ return [
800
+ f" claimed {claim.change.before} → {claim.change.after}, held for "
801
+ f"{config.held}m unless a marker moves it sooner"
802
+ ]
803
+
804
+
805
+ def _held_rows(choice: Choice) -> list[str]:
806
+ """Which ready lines a live claim kept out of the answer (RK119).
807
+
808
+ Named and not counted, for the reason a claim carries no owner: the caller cannot be
809
+ told whose it is, so the id is the only thing it can recognise its own by — and a line
810
+ silently absent is one the caller asks about again on the next turn.
811
+ """
812
+ return [
813
+ f" held {held.id} was claimed {held.since} ago and is not offered"
814
+ for held in choice.held
815
+ ]
816
+
817
+
818
+ def _undesigned_rows(choice: Choice) -> list[str]:
819
+ """What `--designed` set aside, and never silently (RK83).
820
+
821
+ Said rather than folded into `backlog`, whose three numbers are facts about the
822
+ file: this one is a fact about the question, and a filter that hides its own effect is
823
+ how "this block is finished" gets read off an answer that never looked at half of it.
824
+ """
825
+ if not choice.undesigned:
826
+ return []
827
+ return [f" skipped {choice.undesigned} ready and still needing designing"]
828
+
829
+
830
+ def _lacking_rows(choice: Choice) -> list[str]:
831
+ """The ready lines this caller has no way to finish, one row each (RK1297).
832
+
833
+ A row per line and not a count, unlike `--designed`'s above, and the difference is who
834
+ the row is for: an undesigned line comes back to this caller the moment it writes the
835
+ design, and one of these comes back to *somebody else* — so the id is what gets handed
836
+ over and the requirement is what it is handed over for.
837
+
838
+ `absent` and not `waiting`, because nothing here is pending: the line is ready, the
839
+ backlog is right, and what is missing is in the room rather than in the files. Nor
840
+ `needs`, which is the row an `add` prints for the section it left owing (RK1297).
841
+ """
842
+ return [
843
+ f" absent {one.id} is ready and requires {', '.join(one.missing)}, "
844
+ f"which this caller did not declare"
845
+ for one in choice.lacking
846
+ ]
847
+
848
+
849
+ def _waiting_rows(choice: Choice) -> list[str]:
850
+ """What the declared priority is waiting on, where nothing ready answers it (RK1304).
851
+
852
+ The `reason` above already says the queue names nothing ready, and that sentence is true
853
+ and stops one step short: it does not say which task would change it. This is that step,
854
+ beside the pick rather than instead of it — the pick may still be the right call when the
855
+ blocker is expensive, and the case worth having is the other one.
856
+
857
+ The **ids** and not a command, unlike every other door this file prints: releasing a token
858
+ may take several of them and `ship` takes one, so an argv would be a fiction wherever the
859
+ row is most needed. A token blocked on work outside the backlog has no id to name at all
860
+ and says so — nothing this tool could offer would release it.
861
+ """
862
+ rows: list[str] = []
863
+ for one in choice.waiting:
864
+ lines = f"{one.lines} line{'' if one.lines == 1 else 's'}, blocked"
865
+ if not one.releases:
866
+ rows.append(f" waiting {one.token} — {lines} on work this backlog does not name")
867
+ continue
868
+ more = f" (of {one.of})" if one.of > len(one.releases) else ""
869
+ released = "it" if one.lines == 1 else "them"
870
+ rows.append(
871
+ f" waiting {one.token} — {lines}; "
872
+ f"{', '.join(one.releases)}{more} would release {released}"
873
+ )
874
+ return rows
875
+
876
+
877
+ def _stalled_rows(choice: Choice) -> list[str]:
878
+ """A started task that cannot be continued is the one thing a pick must not hide.
879
+
880
+ And whether somebody is holding it (RK152), because "started and stuck" invites
881
+ unblocking the line while "claimed and waiting" invites leaving it alone — two answers
882
+ one sentence used to serve.
883
+ """
884
+ rows: list[str] = []
885
+ for stalled in choice.stalled:
886
+ whose = (
887
+ "" if stalled.claimed is None else f" and claimed {stalled.claimed.since} ago"
888
+ )
889
+ rows.append(
890
+ f" stalled {stalled.id} is in progress{whose}, waiting on "
891
+ f"{', '.join(stalled.blockers) or 'nothing this backlog names'}"
892
+ )
893
+ return rows
894
+
895
+
896
+ def _leverage_rows(leverage: Leverage) -> list[str]:
897
+ """The reverse direction, which is the half of prioritisation a tool may supply.
898
+
899
+ Bounded by :data:`~roadkeep.briefing.UNBLOCKS`, which is this printer's own number lifted
900
+ to where the payload could read it (RK1301): the row had a cap and the payload had none,
901
+ so one register showed four ids and the other spelled seventy-nine of them.
902
+ """
903
+ from roadkeep.briefing import UNBLOCKS # noqa: PLC0415 - RK260
904
+
905
+ shown = ", ".join(leverage.transitive[:UNBLOCKS])
906
+ tail = " …" if leverage.count > UNBLOCKS else ""
907
+ detail = f": {shown}{tail}" if shown else ""
908
+ return [f" unblocks {leverage.count} of {leverage.of} open{detail}"]
909
+
910
+
911
+ def _commits_json(origin: Origin) -> dict[str, object]:
912
+ def one(commit: Commit | None) -> dict[str, object] | None:
913
+ if commit is None:
914
+ return None
915
+ return {
916
+ "sha": commit.sha,
917
+ "short": commit.short,
918
+ "date": commit.date,
919
+ "author": commit.author,
920
+ "subject": commit.subject,
921
+ "reasoning": commit.reasoning,
922
+ }
923
+
924
+ return {
925
+ "proposed_in": one(origin.proposed_in),
926
+ "shipped_in": one(origin.shipped_in),
927
+ }
928
+
929
+
930
+ #: What each `[ids]` key reads as off the ids themselves, and the condition under which
931
+ #: declaring it is right — the second half being the whole discipline of this line: the
932
+ #: report says what the ids spell and leaves the judgement where it belongs (RK110, L4).
933
+ _ID_SPELLS = {
934
+ "pad": ("carry a leading zero", "if that width is this backlog's spelling"),
935
+ "suffix": ("end in a lowercase letter", "if a split here keeps its number"),
936
+ }
937
+
938
+
939
+ #: What choosing each unread reading means, in the words the row's own clause already uses.
940
+ #: Keyed by the flag, because the flag is what the door carries and what a reader reruns.
941
+ _READING_WHAT = {
942
+ "--prefix": "measure this file again with that family read as a track of the backlog",
943
+ "--ref-scheme": "measure this file again with its sections addressed the way it addresses them",
944
+ }
945
+
946
+
947
+ def _readings(estimate: Estimate) -> tuple[tuple[str, str, int, Door], ...]:
948
+ """The readings this file carries that the declared one leaves unread, each with its door.
949
+
950
+ One writer for both answers (RK1147). The printed report has named the flag since RK285 and
951
+ the payload published `{"scheme": "outline", "count": 20}` beside `line.non-canonical: 20`,
952
+ leaving the door to be inferred from two counts — by an agent, which is the author this tool
953
+ is built for. Both guards live here now, spelled once: a family the chosen ones already
954
+ cover is not unread, and a scheme is reported only where the declared one left an address
955
+ unread (RK288/RK305, :func:`_misread`).
956
+
957
+ The door reruns **this** estimate, so it carries the flags that decided what was measured:
958
+ `--sections` reads a rationale file and `--ledger` applies the changelog limits (RK76). A
959
+ door dropping either would name a command whose answer is about a reading nobody asked for,
960
+ which is worse than the count it was added to explain.
961
+ """
962
+ role: tuple[str, ...] = ()
963
+ if estimate.unit == "section":
964
+ role = ("--sections",)
965
+ elif estimate.ledger:
966
+ role = ("--ledger",)
967
+
968
+ def door(flag: str, value: str) -> Door:
969
+ return Door(
970
+ argv=("adopt", estimate.path.as_posix(), *role, flag, value),
971
+ what=_READING_WHAT[flag],
972
+ )
973
+
974
+ rows = [
975
+ ("--prefix", prefix, count, door("--prefix", prefix))
976
+ for prefix, count in estimate.prefixes
977
+ if prefix not in estimate.families
978
+ ]
979
+ if _misread(estimate):
980
+ rows += [
981
+ ("--ref-scheme", scheme, count, door("--ref-scheme", scheme))
982
+ for scheme, count in estimate.schemes
983
+ if scheme != estimate.ref_scheme
984
+ ]
985
+ return tuple(rows)
986
+
987
+
988
+ def _reading_door(estimate: Estimate, flag: str, value: str) -> dict[str, object]:
989
+ """One row's door as a payload key, or nothing at all.
990
+
991
+ Absent and not ``"door": null``, for the reason a remedy is (see :func:`_remedy_json`): a
992
+ consumer reading the key at all is one that acts on it, and a null is a row it has to
993
+ test before it can use. No ``served`` is threaded here because `adopt` is deliberately
994
+ unserved — it runs once, before the project exists (RK57) — so there is no tool call to
995
+ publish beside the argv.
996
+ """
997
+ # `doors` and always a list (RK1324): one name and one shape wherever a payload publishes
998
+ # a runnable command, so a consumer reads them with one loop rather than five names.
999
+ found = [d for f, v, _, d in _readings(estimate) if (f, v) == (flag, value)]
1000
+ return {"doors": [found[0].payload()]} if found else {}
1001
+
1002
+
1003
+ def _print_estimate(estimate: Estimate) -> None:
1004
+ where = estimate.path.as_posix()
1005
+ # Which of the three (RK485): a prefix nothing declared and nothing produced is the
1006
+ # schema's default, and calling that a reading is the estimate claiming a measurement.
1007
+ source = ""
1008
+ if estimate.inferred:
1009
+ source = " (inferred from the ids)"
1010
+ elif estimate.defaulted:
1011
+ source = " (the default — no id here was read, so the counts below assume it)"
1012
+ # No prefix on a rationale file: a section is addressed by its §, not by a family, so
1013
+ # naming one would be a claim the run never made (RK99).
1014
+ under = f"prefix {'/'.join(estimate.families)}{source}, " if estimate.families else ""
1015
+ # Which grammar read the file, said always (RK1346). The two readings printed the same
1016
+ # header, so `0 conform, 361 would change` and `361 conform, 0 would change` on one file
1017
+ # were tellable apart only by remembering which command had been typed — and the reader
1018
+ # this output is for has typed neither before.
1019
+ # Three roles and not two (RK1347): `unit` is what tells a rationale file apart, a
1020
+ # sections run counting sections where the other two count lines, and naming it *a
1021
+ # backlog* was a claim about the grammar that answered which was wrong on one run in
1022
+ # three — worse than the silence the header kept before RK1346.
1023
+ if estimate.unit == "section":
1024
+ role = "prose"
1025
+ else:
1026
+ role = "a ledger" if estimate.ledger else "a backlog"
1027
+ print(f"{where} {under}refs by {estimate.ref_scheme}, read as {role}")
1028
+ print(
1029
+ f" read {estimate.parsed} {estimate.unit}(s), {estimate.conforming} conform, "
1030
+ f"{estimate.changing} would change"
1031
+ )
1032
+ if estimate.lines and not estimate.recognised:
1033
+ # First of the three, because it is the one that says the headline above means nothing
1034
+ # about a backlog (RK376). A measurement and never a verdict on the file: what was read
1035
+ # against what is there, leaving "you named the wrong file" to the reader (L4).
1036
+ # Worded off `unit`, for the reason the `loose` line below is: the shapes a run reads
1037
+ # are entries and bullets on a backlog and headings on a rationale file (RK387), and
1038
+ # one sentence naming both would name neither run's.
1039
+ shapes = (
1040
+ "no entry, reject, table row, bullet or block heading"
1041
+ if estimate.unit == "line"
1042
+ else "no anchored section, and no heading carrying prose"
1043
+ )
1044
+ print(
1045
+ f" unread nothing in {estimate.lines} line(s) was read in any shape — {shapes}"
1046
+ )
1047
+ if estimate.tabular:
1048
+ # Directly under the headline, because it is the headline it explains: a table-shaped
1049
+ # backlog reads as 0 lines, which is what an empty file reads as (RK98).
1050
+ print(f" table {estimate.tabular} line(s) in a table this format does not read")
1051
+ if estimate.listed:
1052
+ # Beside it, and for the same reason (RK279, RK281) — this is the shape the headline
1053
+ # is most often explaining. Worded off `unit`, because the field holds one idea, "in
1054
+ # a shape this format has no reader for", and that is a bullet in a backlog and a
1055
+ # heading in a rationale file: one sentence for both would name neither.
1056
+ said = (
1057
+ f"{estimate.listed} plain bullet(s) under a block"
1058
+ if estimate.unit == "line"
1059
+ else f"{estimate.listed} heading(s) with prose and no anchor"
1060
+ )
1061
+ print(f" loose {said}, in no shape read here")
1062
+ if estimate.blocks:
1063
+ print(f" blocks {', '.join(estimate.blocks)}")
1064
+ # Both guards moved into `_readings` (RK1147), which is now the one place that decides
1065
+ # what is unread here — the payload publishes the same rows with the door beside them, and
1066
+ # two loops asking the same question in two functions is the drift that put a flag on one
1067
+ # surface and a bare count on the other. Only the *sentences* stay here.
1068
+ for flag, value, count, _ in _readings(estimate):
1069
+ # `prefix` takes a list now (RK74), so this names the flag instead of the limitation:
1070
+ # whether the spelling is a second track or a paste from another backlog is the
1071
+ # reader's call.
1072
+ if flag == "--prefix":
1073
+ print(
1074
+ f" also {count} id(s) spell {value}, unread here: "
1075
+ f"--prefix {value} if it is a track of this backlog"
1076
+ )
1077
+ continue
1078
+ scheme = value
1079
+ # The same sentence one field over (RK285). Shio read `0 conform, 65 would change`
1080
+ # under the default and `63 conform, 2 would change` under `--ref-scheme outline`,
1081
+ # with `ref.mismatch` on every line as the only signal — while the prefix half of the
1082
+ # same misreading already named its flag. The trailing clause keeps the judgement with
1083
+ # the reader for the reason that one does: whether a live outline is what this backlog
1084
+ # numbers by is a decision about the project, not a fact about the file.
1085
+ # Worded off `unit` for the reason the loose line is (RK288): on a backlog the
1086
+ # evidence is the pointers, on a rationale file it is the headings' own anchors,
1087
+ # and one sentence for both would name neither.
1088
+ spells = "pointer(s) spell" if estimate.unit == "line" else "heading(s) anchored"
1089
+ print(
1090
+ f" also {count} {spells} {scheme}, unread here: "
1091
+ f"--ref-scheme {scheme} if that is how this project addresses its sections"
1092
+ )
1093
+ # The one finding a per-file estimate could not reach (RK347), and a line here rather than
1094
+ # a refusal for the reason every other one is: `adopt` writes nothing and exits 0 (RK18),
1095
+ # and what an adopter is buying is the number *before* the commitment.
1096
+ for roles, taken in _by_files(estimate.ambiguous):
1097
+ # Grouped by the files that collide and not one line per address, because the repair is
1098
+ # one line of configuration for all of them — printed per address it would state the
1099
+ # same declaration four times, which is the shape that reads as four problems. The
1100
+ # addresses stay named: a count alone sends somebody to diff two outlines by hand.
1101
+ print(
1102
+ f" refs {len(taken)} address(es) declared by both {' and '.join(roles)} "
1103
+ f"({', '.join(taken)}), refused here: {_AMBIGUOUS_FIX[estimate.ref_scheme]}"
1104
+ )
1105
+ for declaration, count in estimate.ledger_shape:
1106
+ # Beside the `[ids]` line and in its shape (RK286): a count, and the keys that close
1107
+ # it. The reason on each refused line names the slots; this is what declaring them
1108
+ # recovers, which is the number an adopter is deciding on and which used to cost a
1109
+ # scratch `roadkeep.toml` to reach.
1110
+ print(
1111
+ f" ledger {count} line(s) parse as entries, refused here: "
1112
+ f"[ledger] {declaration}"
1113
+ )
1114
+ for shape in estimate.id_shape:
1115
+ # Beside the prefix line and in its shape (RK110): a count, and the key that closes
1116
+ # it. The trailing clause is the whole discipline — what the ids spell, never that
1117
+ # the project should therefore declare it.
1118
+ spells, when = _ID_SPELLS[shape.key]
1119
+ print(
1120
+ f" ids {shape.count} id(s) {spells}, refused here: "
1121
+ f"[ids] {shape.declaration} {when}"
1122
+ )
1123
+ if estimate.measures and not estimate.parsed:
1124
+ # A measurement of nothing, said once instead of three times as a zero (RK1345).
1125
+ # Printing `longest 0 of 120, 0 over` per field is defensible and reads as *your
1126
+ # fields fit*: `0 over` is vacuously true over an empty population and sits in the
1127
+ # same column as a real count — an ungoverned changelog measured 717 lines, 398
1128
+ # recognised, none parsed, and said it three times. The verb already tells the two
1129
+ # apart elsewhere, `govern` answering `reading none — <why>` rather than `0`.
1130
+ print(
1131
+ f" fields none — nothing parsed as an entry, so "
1132
+ f"{', '.join(one.field for one in estimate.measures)} went unread"
1133
+ )
1134
+ for measure in estimate.measures if estimate.parsed else ():
1135
+ # Printed even at zero over: the number an adopting project is here for is the
1136
+ # *longest*, which is what a limit gets set from, and a measure that appears only
1137
+ # once it is exceeded is one nobody can declare a limit from (RK99).
1138
+ print(
1139
+ f" {measure.field:<8} longest {measure.longest} of {measure.limit} "
1140
+ f"{measure.unit}"
1141
+ + (f", {measure.over} over" if measure.refuses else ", which nothing refuses")
1142
+ )
1143
+ if estimate.non_goals is not None:
1144
+ _print_scoped(estimate.non_goals)
1145
+ # The terms of the measurement rather than its result (RK291), the shape `[non_goals] not
1146
+ # governed` and `install`'s "no .github/workflows/" already use. Printed always, because a
1147
+ # limit stated only where it happened to bite is one the reader cannot rely on: RK290 made
1148
+ # the estimate and the gate agree on everything one file decides, so this names the rest.
1149
+ print(f" scope {_estimate_scope(estimate)}")
1150
+ if estimate.gains:
1151
+ # A category and not three more measurements (RK1089). Every row above answers what
1152
+ # this *file* would cost; these answer what the *project* is missing, and the first
1153
+ # of them (RK1087) printed among the numbers read as one more of them. The heading is
1154
+ # what keeps the next member from landing somewhere else again.
1155
+ print(
1156
+ f" gains {len(estimate.gains)} the format would add and this project "
1157
+ f"has not declared:"
1158
+ )
1159
+ # To the widest and never to a constant (RK1344), which is `remedying.offered`'s rule
1160
+ # and its reason: nine was a guess about the longest label, and it stopped being true
1161
+ # the day one reached it. Two did — `decisions` and `non-goals` are exactly nine — so
1162
+ # the pad added nothing and the row printed `decisionsno decisions file`, on the two
1163
+ # gains an adopter meets most, in the one output whose reader has never seen this
1164
+ # tool. The separator is explicit for the same reason the sibling rows spell theirs:
1165
+ # a width that has to also supply the gap is a width that stops doing so at the top.
1166
+ wide = max(len(gain.name) for gain in estimate.gains)
1167
+ for gain in estimate.gains:
1168
+ print(f" {gain.name:<{wide}} {gain.because}")
1169
+ if estimate.surface:
1170
+ # The other side of the transaction, and the only row here that is not about the file
1171
+ # (RK1100). An estimate that named four doors this format opens and no cost is one that
1172
+ # asks for a decision while holding half the terms — and this half is knowable in
1173
+ # advance, being a fact about the package: RK1097 measured three projects serving the
1174
+ # same 52 tools within 1.4% of each other.
1175
+ #
1176
+ # Stated at the cadence it is paid at and never summed with anything (RK1095): once at
1177
+ # connect, against a resident file paid every turn. And no verdict on it — whether the
1178
+ # doors above are worth this is the adopter's arithmetic, not the tool's (L4).
1179
+ print(
1180
+ f" serves {estimate.surface} characters once at connect, if this project "
1181
+ f"serves the tools: `[tools]` is where a ceiling on that is declared"
1182
+ )
1183
+ for marker, count in estimate.undeclared:
1184
+ print(f" marker {marker} on {count} line(s), declared by nothing in [markers]")
1185
+ for code, count in estimate.codes:
1186
+ print(f" {code:<8} {count}")
1187
+ for reason, count in estimate.rejects:
1188
+ print(f" unparsed {count}: {reason}")
1189
+ if estimate.non_canonical:
1190
+ # Qualified where the reading itself is in doubt (RK285). This states a refusal
1191
+ # absolutely, and on Shio it rested on a prefix and a scheme the report had just
1192
+ # named as probably wrong — the one claim in this output an adopter cannot discount,
1193
+ # and it was the one that was wrong. The number stays; what is added is which reading
1194
+ # produced it, so a reader can tell "your file is broken" from "read it another way".
1195
+ # The third reader of one list (RK1147). Behind the same predicate as the `also` lines
1196
+ # above (RK305) and not behind a second spelling of it: an alternative reading offered
1197
+ # here on a file the declared scheme read whole is the same wrong advice, and two
1198
+ # conditions for one sentence is where the two drift apart — which is what the payload
1199
+ # did, publishing the count these words qualify with no flag beside it.
1200
+ under = [f"{flag} {value}" for flag, value, _, _ in _readings(estimate)]
1201
+ because = f" — measured under this reading; {', '.join(under)} changes it" if under else ""
1202
+ print(
1203
+ f" {estimate.non_canonical} line(s) do not round-trip: the tool would "
1204
+ f"refuse to write this file until they are rewritten by hand{because}"
1205
+ )
1206
+
1207
+
1208
+ #: What closes a doubled address, per scheme (RK347). Under an outline it is a line of
1209
+ #: configuration and never a renumbering of somebody's document: `[refs]` reads each file's
1210
+ #: outline as its own, so the two `I`s stop being one address. Under `id` there is nothing to
1211
+ #: namespace — the anchor is the task's own id, unique across the project by construction — so
1212
+ #: two headings answering to one is a heading somebody has to delete.
1213
+ _AMBIGUOUS_FIX = {
1214
+ "outline": '[refs] <role> = "<prefix>" puts each file\'s outline in its own namespace',
1215
+ "id": "an id addresses one section, so one of the two headings is the one to delete",
1216
+ }
1217
+
1218
+
1219
+ #: The findings that mean "the declared scheme could not read this address" (RK305). Under
1220
+ #: `id` a pointer the author chose is `ref.mismatch`; under an outline one shaped like an id
1221
+ #: is `ref.format`. Both are the signal RK285 said arrived with no sentence naming the flag.
1222
+ _MISREAD_CODES = ("ref.mismatch", "ref.format")
1223
+
1224
+
1225
+ def _by_files(ambiguous) -> list[tuple[tuple[str, ...], list[str]]]:
1226
+ """The doubled addresses gathered under the files that declare them, in first-seen order."""
1227
+ grouped: dict[tuple[str, ...], list[str]] = {}
1228
+ for anchor, roles in ambiguous:
1229
+ grouped.setdefault(roles, []).append(anchor)
1230
+ return list(grouped.items())
1231
+
1232
+
1233
+ def _misread(estimate) -> bool:
1234
+ """Whether the declared scheme left any address in this file unread (RK305).
1235
+
1236
+ RK288 asked a **majority**: print `--ref-scheme <other>` only where the other scheme
1237
+ accounts for more of the file than the declared one. That is a proxy for *this file is
1238
+ really addressed the other way*, and it holds on a file nothing writes to. It does not
1239
+ hold here. This repository's rationale file carries a permanent preamble anchored `§0.1`
1240
+ and one `§RK<n>` section per **open** design, and a ship deletes the second kind — so the
1241
+ ratio falls with every task delivered and, at the moment the open designs stop
1242
+ outnumbering the preamble, a fully conforming file is told to be read the other way.
1243
+ Measured while shipping Block B: five and five, one ship from the alarm.
1244
+
1245
+ What the count cannot see is that the two kinds of heading are not competing readings of
1246
+ one file — one is prose the project keeps and the other is a queue. So the question asked
1247
+ here is the one RK288 was written about: did the declared scheme leave something *unread*?
1248
+ A file whose scheme parses every address it was asked about has no minority reading to
1249
+ report, whatever the ratio; Shio's `0.1` headings and its hand-chosen pointers are unread
1250
+ under `id`, and still say so.
1251
+
1252
+ Two shapes because the evidence is: a rationale file's unread headings are the ones
1253
+ :attr:`~roadkeep.adopting.Estimate.listed` already counts, and a backlog's are the
1254
+ pointers the gate refuses.
1255
+ """
1256
+ if estimate.unit == "section":
1257
+ return estimate.listed > 0
1258
+ return any(code in _MISREAD_CODES for code, _ in estimate.codes)
1259
+
1260
+
1261
+ def _estimate_scope(estimate) -> str:
1262
+ """What this estimate could not decide, said in names the reader can act on (RK291/292).
1263
+
1264
+ Three sentences, because the fact has three shapes and one wording made two of them wrong.
1265
+ Where the target is declared, the siblings are what handing over would complete, so they are
1266
+ named. Where it is declared and alone, there is nothing to hand over and the limit is still
1267
+ real. Where it is **not** declared — the case `adopt` exists for — this project's `[files]`
1268
+ belong to somebody else: naming them said Turing's `docs/IMPROVEMENTS.md` was measured while
1269
+ this repository's went unread, which reads as not having read what was read.
1270
+ """
1271
+ across = "deps and pointers resolve across files"
1272
+ if not estimate.declared:
1273
+ return (
1274
+ f"one file read, declared by no project here: {across}, so neither was checked — "
1275
+ f"`lint` is the answer inside the project that owns them"
1276
+ )
1277
+ named = ", ".join(estimate.unopened) if estimate.unopened else "no other governed file"
1278
+ return (
1279
+ f"{named} not read: {across}, so neither was checked here — `lint` is the answer "
1280
+ f"once they are declared"
1281
+ )
1282
+
1283
+
1284
+ def _print_scoped(scoped) -> None:
1285
+ """The roadmap's other bullet, under the two limits it would be held to (RK139).
1286
+
1287
+ Printed even at zero, and even where `[non_goals]` is undeclared, for the reason every
1288
+ measure is: what an adopter is asking is what the rule would cost, and a section that
1289
+ appeared only once it was already expensive is one nobody can decide from. Whether the
1290
+ project opted in is said in the same line, because it is what decides whether these
1291
+ bullets are in the headline count or beside it.
1292
+ """
1293
+ governed = "governed" if scoped.governed else "not governed, so measured at the defaults"
1294
+ print(
1295
+ f" non-goals {scoped.parsed} bullet(s), {scoped.unparsed} unread, "
1296
+ f"{scoped.over} over — [non_goals] {governed}"
1297
+ )
1298
+ if scoped.measures and not scoped.parsed:
1299
+ # The same empty population as the fields above (RK1345), and the same answer. The
1300
+ # header already says `0 bullet(s)`, which is what makes the two rows beneath it worth
1301
+ # narrowing rather than dropping: a reader who has just been told the count is nought
1302
+ # is the one most likely to read `0 over` as a verdict on their prose.
1303
+ print(
1304
+ f" fields none — no bullet parsed, so "
1305
+ f"{', '.join(one.field for one in scoped.measures)} went unread"
1306
+ )
1307
+ return
1308
+ for measure in scoped.measures:
1309
+ print(
1310
+ f" {measure.field:<8} longest {measure.longest} of {measure.limit} "
1311
+ f"{measure.unit}, {measure.over} over"
1312
+ )
1313
+
1314
+
1315
+ def _estimate_json(estimate: Estimate) -> dict[str, object]:
1316
+ return {
1317
+ "file": estimate.path.as_posix(),
1318
+ "prefix": estimate.prefix,
1319
+ "families": list(estimate.families),
1320
+ "inferred": estimate.inferred,
1321
+ # The third state, published rather than left to be read off a false `false` (RK485):
1322
+ # a consumer that saw `inferred: false` on a defaulted prefix read it as *declared*,
1323
+ # which is the same two-words-for-three the printed line had.
1324
+ "defaulted": estimate.defaulted,
1325
+ # Empty where the project has them all, and empty where no project declared the
1326
+ # target at all (RK1089) — a consumer telling those apart reads `declared`.
1327
+ "gains": [
1328
+ {"name": gain.name, "because": gain.because} for gain in estimate.gains
1329
+ ],
1330
+ # Beside the gains and not among the counts, because it is the one figure here that is
1331
+ # not about the file (RK1100). Its own object, so the cadence travels with the number:
1332
+ # a client adding this to a per-turn cost is the arithmetic RK1095 refused to print.
1333
+ "serves": {"characters": estimate.surface, "cadence": "once, at connect"},
1334
+ "unit": estimate.unit,
1335
+ # Which role decided the numbers (RK1147): `unit` says lines for a backlog and for a
1336
+ # ledger alike, and a ledger is measured under `[limits.changelog]` (RK76) — so a
1337
+ # consumer rerunning this estimate needs the flag rather than a guess, and every door
1338
+ # below carries it for the same reason.
1339
+ "ledger": estimate.ledger,
1340
+ "ref_scheme": estimate.ref_scheme,
1341
+ "parsed": estimate.parsed,
1342
+ "conforming": estimate.conforming,
1343
+ "changing": estimate.changing,
1344
+ "blocks": list(estimate.blocks),
1345
+ # The door beside the count, on exactly the rows the printed report names a flag for
1346
+ # (RK1147) — absent on the rest, because a family the chosen ones already cover is not
1347
+ # an unread reading and a door there would be a command with nothing to change.
1348
+ "prefixes": [
1349
+ {"prefix": p, "count": n, **_reading_door(estimate, "--prefix", p)}
1350
+ for p, n in estimate.prefixes
1351
+ ],
1352
+ "measures": [
1353
+ {
1354
+ "field": m.field,
1355
+ "limit": m.limit,
1356
+ # `null` where nothing parsed, so a consumer reads an absent measurement as
1357
+ # one rather than as a fitting zero (RK1345). The limit stays, being a fact
1358
+ # about the schema and the thing an adopter came to see; `longest` and `over`
1359
+ # are the two that would be claims about a population that is empty.
1360
+ "longest": m.longest if estimate.parsed else None,
1361
+ # `null` where nothing refuses the limit (RK1348), as it already is where
1362
+ # nothing was parsed: both are counts a consumer must not read as work.
1363
+ "over": m.over if estimate.parsed and m.refuses else None,
1364
+ "refuses": m.refuses,
1365
+ # RK437: which counter the two figures beside it are in. `[limits]` is one
1366
+ # table in three units, and a payload that named none left a caller to assume
1367
+ # the wrong one on exactly the row where assuming is wrong.
1368
+ "unit": m.unit,
1369
+ }
1370
+ for m in estimate.measures
1371
+ ],
1372
+ "undeclared": [{"marker": m, "count": n} for m, n in estimate.undeclared],
1373
+ "id_shape": [
1374
+ {"key": s.key, "value": s.value, "count": s.count, "declaration": s.declaration}
1375
+ for s in estimate.id_shape
1376
+ ],
1377
+ "codes": [{"code": c, "count": n} for c, n in estimate.codes],
1378
+ "non_goals": None
1379
+ if estimate.non_goals is None
1380
+ else {
1381
+ "parsed": estimate.non_goals.parsed,
1382
+ "unparsed": estimate.non_goals.unparsed,
1383
+ "over": estimate.non_goals.over,
1384
+ "governed": estimate.non_goals.governed,
1385
+ "changing": estimate.non_goals.changing,
1386
+ "measures": [
1387
+ {
1388
+ "field": m.field,
1389
+ "limit": m.limit,
1390
+ # Absent where no bullet parsed, as the fields above are (RK1345).
1391
+ "longest": m.longest if estimate.non_goals.parsed else None,
1392
+ "over": m.over if estimate.non_goals.parsed and m.refuses else None,
1393
+ "refuses": m.refuses,
1394
+ "unit": m.unit,
1395
+ }
1396
+ for m in estimate.non_goals.measures
1397
+ ],
1398
+ },
1399
+ "rejects": [{"reason": r, "count": n} for r, n in estimate.rejects],
1400
+ "non_canonical": estimate.non_canonical,
1401
+ "schemes": [
1402
+ {"scheme": s, "count": n, **_reading_door(estimate, "--ref-scheme", s)}
1403
+ for s, n in estimate.schemes
1404
+ ],
1405
+ # Each file under the key that says what its name **is** (RK371): a role `[files]`
1406
+ # answers, or a path it does not. The printed line can leave this to the sentence
1407
+ # around it; a payload read so that an answer costs no file read (L5) cannot, and a
1408
+ # `roles` list holding filenames sent an agent to look up something that was never
1409
+ # there. Never resolved into roles to make one key true — a file this project does not
1410
+ # govern has none, and inventing one is what RK292 keeps out of the report.
1411
+ "ambiguous": [
1412
+ {
1413
+ "anchor": anchor,
1414
+ "declared_by": [
1415
+ {"path": name} if name in estimate.by_path else {"role": name}
1416
+ for name in names
1417
+ ],
1418
+ }
1419
+ for anchor, names in estimate.ambiguous
1420
+ ],
1421
+ # Beside them and not merely inside them: how the run named each file is the same
1422
+ # answer when nothing collided at all, and it is not a claim about who owns one.
1423
+ "by_path": list(estimate.by_path),
1424
+ "ledger_shape": [{"declaration": d, "count": n} for d, n in estimate.ledger_shape],
1425
+ "unopened": list(estimate.unopened),
1426
+ "declared": estimate.declared,
1427
+ "tabular": estimate.tabular,
1428
+ "listed": estimate.listed,
1429
+ # RK376: the pair that tells an empty roadmap apart from a file nothing was read in.
1430
+ "lines": estimate.lines,
1431
+ "recognised": estimate.recognised,
1432
+ }
1433
+
1434
+
1435
+ def _other_copy(command: str) -> str:
1436
+ """The copy this process runs, where the driver command does not already name it (RK1386).
1437
+
1438
+ A comparison of paths and never a second reading: :func:`~roadkeep.provenance.engine` has
1439
+ already answered which tree is writing, and what makes this a finding is that the command
1440
+ `persisted` resolved points somewhere else — a console script installed months ago on a
1441
+ machine whose checkout is a thousand commits newer, which is the state RK1385 made visible.
1442
+
1443
+ `""` on every machine with one copy, which is every adopter: there the driver and the pen
1444
+ are the same install, and a line offering an alternative that is the same path is noise on
1445
+ the answer a project reads once.
1446
+ """
1447
+ from roadkeep.provenance import engine # noqa: PLC0415 - RK260
1448
+
1449
+ home = engine().home.parent.parent
1450
+ if not command or command.startswith(home.as_posix()):
1451
+ return ""
1452
+ return (
1453
+ f"to wire the checkout writing here instead, set that key to a command running "
1454
+ f"{home.as_posix()} — git executes it outside a shell, so it takes an absolute path"
1455
+ )
1456
+
1457
+
1458
+ def registration_report(registration: Registration, where: str, label: int) -> list[str]:
1459
+ """Everything one registration has to say, rendered once for both its surfaces (RK276).
1460
+
1461
+ `merge --register` and `install --register-merge` are the same write — RK148 said so, and
1462
+ the install branch carried a comment claiming the two printed the same lines. RK274 then
1463
+ added a third line and it reached one of them, so the comment asserting the invariant
1464
+ became the record of it breaking. Two renderings of one dataclass drift the moment the
1465
+ dataclass grows a field, and the only fix that holds is that there is one rendering.
1466
+
1467
+ `label` is the column the install report pads its own verbs to and the merge report does
1468
+ not — the difference that pushed the two apart, reduced to the one parameter it is.
1469
+
1470
+ What it says about the config half is `Wiring`'s (RK278): the `then` line is advice, and
1471
+ advice to wire a driver no governed file routes to is what `--check` had already stopped
1472
+ giving. The state line is printed either way, because narrowing a demand is not licence to
1473
+ stop reporting.
1474
+ """
1475
+ prefix = f" {'registered':<{label}} " if label else ""
1476
+ lines = [f"{prefix}{where} + {line}" for line in registration.added]
1477
+ lines += [f"{prefix}{where} {line} (already there)" for line in registration.present]
1478
+ # RK274: named where the writes are named, because "what this command did" has to include
1479
+ # the file it deliberately did not touch — a skip nobody is told about is indistinguishable
1480
+ # from a skip nobody intended.
1481
+ lines += [
1482
+ f"{prefix}{where} {path} → {value} (another driver, left alone)"
1483
+ for path, value in registration.left_alone
1484
+ ]
1485
+ pad = label or 8
1486
+ if registration.wiring is None or registration.wiring.demands_driver:
1487
+ # Printed and not run: a driver command names a path into this checkout, and setting
1488
+ # somebody's git config is a write outside the files this tool was given (L2).
1489
+ lines.append(f" {'then':<{pad}} {registration.command}")
1490
+ # What the stored value cannot promise, said where it is stored (RK255): git executes
1491
+ # it long after this process, and a driver that stopped resolving is silent till a merge.
1492
+ lines.append(f" {'re-run':<{pad}} after {registration.invalidated_by}")
1493
+ # **And the other copy, where this machine has one** (RK1386). The command above is
1494
+ # `persisted`'s, which is right about what git needs — an absolute executable, because
1495
+ # git runs the driver outside a shell (RK255) — and silent about *which* one. On a
1496
+ # machine that both installs this tool and develops it those are two, and the one the
1497
+ # line names is whichever installed the console script.
1498
+ #
1499
+ # Named and never chosen. Setting somebody's git config is a write outside the files
1500
+ # this tool was given (L2), which is why the line above is printed rather than run, and
1501
+ # the same rule forbids picking the copy for them: what a reader gets is that there are
1502
+ # two, so the choice is made knowing it is one.
1503
+ if (other := _other_copy(registration.command)) :
1504
+ lines.append(f" {'or':<{pad}} {other}")
1505
+ if registration.wiring is not None:
1506
+ # Read after the attribute lines were written (RK266). This is the line that carries a
1507
+ # re-run: three attributes "already there" is the answer where the config is the half
1508
+ # that moved, and without this the output that says nothing changed would be all of it.
1509
+ lines.append(f" {'config':<{pad}} {_wiring_line(registration.wiring)}")
1510
+ return lines
1511
+
1512
+
1513
+ def _wiring_line(wired: Wiring) -> str:
1514
+ """The config half's state, with the qualifier only both halves together can add (RK278).
1515
+
1516
+ One function, so the check and the verb cannot say it two ways — which is what happened the
1517
+ commit RK277 shipped, where `--check` knew nothing routed here and `--register` did not.
1518
+ """
1519
+ tail = "" if wired.attributes.routes_here else " — and no governed file routes here"
1520
+ return f"{_driver_line(wired.driver)}{tail}"
1521
+
1522
+
1523
+ #: What each state of the stored driver says, and what a `--check` exits with (RK266). Only two
1524
+ #: are failures: git has no driver it can run. `MOVED` is a driver that works and is not what
1525
+ #: this machine would write, and exiting 1 on it would make the check unusable on any repository
1526
+ #: two people registered from — which is every repository the driver is for.
1527
+ _DRIVER_STATES = {
1528
+ ABSENT: (EXIT_GATE, "not set, so a conflict falls back to git's own markers"),
1529
+ # Not "the command above": `--check` prints no command, and a state line that only reads
1530
+ # right under the other surface is one of the two that must stand on its own.
1531
+ CURRENT: (EXIT_OK, "set to the command this machine would write"),
1532
+ MOVED: (EXIT_OK, "set to a command that runs, and is not this machine's"),
1533
+ UNRUNNABLE: (EXIT_GATE, "set to a command this machine no longer has"),
1534
+ UNKNOWN: (EXIT_OK, "could not be read: no git, or no repository here"),
1535
+ }
1536
+
1537
+
1538
+ def _driver_line(driver: Driver) -> str:
1539
+ """One line for the state, quoting the stored value only where it is the evidence."""
1540
+ _, said = _DRIVER_STATES[driver.state]
1541
+ line = f"{DRIVER_KEY} {said}"
1542
+ if driver.state in (MOVED, UNRUNNABLE):
1543
+ return f"{line}: {driver.stored}"
1544
+ return line
1545
+
1546
+
1547
+ def _attributes_line(attributes: Attributes) -> str:
1548
+ """What git sends to the driver, counted — and named where some of it is not.
1549
+
1550
+ "git sends" and no longer "`.gitattributes` sends" (RK273): the answer is `check-attr`'s,
1551
+ so it holds for a rule set in a subdirectory or in `.git/info/attributes`, and naming one
1552
+ file as the authority would be naming the one this tool happens to write.
1553
+ """
1554
+ if attributes.state == UNKNOWN:
1555
+ return "could not be read: no git, or no repository here"
1556
+ counted = f"{len(attributes.sent)} of {len(attributes.resolved)} governed files"
1557
+ line = f"git sends {counted} to the {DRIVER} driver"
1558
+ if attributes.state != CURRENT:
1559
+ line = f"git sends {counted}: {', '.join(attributes.unsent)} would merge textually"
1560
+ if attributes.claimed:
1561
+ # Said in every state, including the passing one (RK274): a claimed file is settled, so
1562
+ # it does not hold the answer open — but dropping it from the line would leave a count
1563
+ # short of its total with nothing explaining the gap, which reads as the failure it
1564
+ # is not. Said, never corrected: it is somebody's decision and this tool can see it.
1565
+ named = ", ".join(f"{path} → {value}" for path, value in attributes.claimed)
1566
+ return f"{line} ({named}, left alone)"
1567
+ return line
1568
+
1569
+
1570
+ def _prose_file(config: Config, prose: Document | None) -> str:
1571
+ """The prose file a drop actually rewrote, as the project spells it (RK196).
1572
+
1573
+ Read off the document rather than off `config.path("improvements")`, because which role
1574
+ declared the anchor is what the drop resolved and a caller restating it would be
1575
+ guessing — the guess that reported "no §X.1 section in IMPROVEMENTS.md" about a section
1576
+ sitting in `STRATEGY.md`. Nothing dropped means no document, and then the answer is the
1577
+ first declared prose role, which is where a design would have been.
1578
+ """
1579
+ if prose is not None and prose.path is not None:
1580
+ return config.relative(prose.path)
1581
+ declared = tuple(role for role in PROSE_ROLES if config.has(role))
1582
+ return config.relative(config.path(declared[0])) if declared else ""
1583
+
1584
+
1585
+ def _dated_json(commit: Commit) -> dict[str, str]:
1586
+ """A commit as an **address**: where to look, and when it landed (RK1163).
1587
+
1588
+ Four fields and not five. The message body belongs to an answer *about* that commit, and this
1589
+ rides inside a `brief` — a bounded answer whose whole argument is that it costs less than
1590
+ reading the file (RK29), where one long commit message would be a paragraph nobody asked for.
1591
+
1592
+ A name of its own since RK1170 found the duplicate: this was written as a second
1593
+ `_commit_json`, which shadowed the nullable one above and made `origin '§<anchor>' --json`
1594
+ raise on the half of its answer that is `None` by construction.
1595
+ """
1596
+ return {
1597
+ "sha": commit.sha,
1598
+ "short": commit.short,
1599
+ "date": commit.date,
1600
+ "subject": commit.subject,
1601
+ }