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/budgeting.py ADDED
@@ -0,0 +1,2056 @@
1
+ """What a line has left for prose, asked before a word of it exists (RK190).
2
+
3
+ RK183 made the `why`'s limit the smaller of its own and what the line has left, and RK184
4
+ made the refusal state the surplus. Both act at the same moment: **after** a sentence has
5
+ been composed. The number they report is derived from the id, the marker, the deps and the
6
+ pointer — every one of which `add` knows before the prose exists — so nothing about it had
7
+ to wait for a draft.
8
+
9
+ That is the arrangement L1 exists to end, one layer in. A `maxLength` refuses before a
10
+ sentence is written to fill it; a derived budget delivered only as a refusal has the shape
11
+ of a linter again, and the author pays a retry to learn a number the tool could have handed
12
+ them. The saving is the analysis: "how long may this sentence be, under these deps" has an
13
+ answer, and asking it costs no context (L5).
14
+
15
+ Two moments and one door. Asked with no id, the budget is the line `add` is *about* to
16
+ write — the next id, this project's first marker, the deps the caller names. Asked with an
17
+ id, it is the line already on the desk, which an `amend` is about to rewrite; the symptom is
18
+ that line's own, so what comes back is the room the `why` really has.
19
+
20
+ Nothing here restates a limit. Every number is :meth:`Schema.prose_budget`,
21
+ :meth:`Schema.why_budget` or a field's own declared maximum, read off the schema — a
22
+ constant here would be one more thing to keep true, and the first slot to move would make
23
+ this the second opinion an author trusts.
24
+
25
+ **One transaction, one budget** (RK301). `add --section` writes a line *and* a body, the body
26
+ has its own limit, and it refuses the whole `add` — so a read that named only the line's two
27
+ fields was silent about half of what it was asked about. Thirteen refusals in one session,
28
+ each the entire paragraph re-sent to learn a config value; over MCP there is no pipe, so the
29
+ retry is the whole payload. The body rides here as a field and not as a second verb, and its
30
+ aim sits **under** its limit rather than on it: composing to exactly the declared number is
31
+ what four of those refusals were.
32
+
33
+ **The pointer is part of the structure, and under an outline it is the caller's** (RK265).
34
+ Under ``ref_scheme = "id"`` the anchor is derived, so a budget asked before the prose knows
35
+ it exactly. Under ``"outline"`` the anchor is *chosen*, and a budget that composed the line
36
+ without one measured a structure the `add` would not have — over-reporting the room by the
37
+ anchor's width, and refusing the sentence it had just approved. So ``ref`` is an argument
38
+ here for the same reason it is one on `add`, and where the caller names none the assumption
39
+ is the **widest anchor the roadmap already carries** rather than no anchor at all: a number
40
+ that cannot be exact is at least never optimistic, and :attr:`Budget.ref_assumed` says which
41
+ of the two the caller is reading.
42
+
43
+ **Three writes carry a prose limit, and this answers for all three** (RK283). The task line
44
+ was the only one served, and it is the smallest: `non-goal add --why` is capped by
45
+ `[non_goals]`, and a section body by `section = <n>` in words — the longest thing an author
46
+ writes, and the one whose refusal costs the most to obey. Measured filing four tasks after a
47
+ block emptied: two refusals on a non-goal `why` at 286 and 234 against 200, one on a section
48
+ body at 366 words against 300. Both limits are facts about the file and the role, known
49
+ before a word, so both are read here rather than met at the door. Not a `--dry-run` on the
50
+ write verbs, which would want the prose first — the whole point is to be answerable without it.
51
+
52
+ **And the draft is measured here too, which is the half RK190 left** (RK1190). Every number
53
+ above is knowable before the first word, and *none of them measures the words that then get
54
+ written* — so the only thing that ever compared a paragraph against its limit was the write
55
+ that refused it. Measured on one session driving another project: eight refusals on length,
56
+ several of them three and four retries for a single task, each costing the whole field again.
57
+ The refusals are good; none of them is reachable until something has been sent.
58
+
59
+ So every subject that has a limit takes the draft it is for — `--why` and `--symptom` on a
60
+ line, `--body` beside `--anchor` — and answers with the overrun rather than with the refusal.
61
+ It is **counted by the writer's own counter**: :func:`~roadkeep.kernel.schema.width` for a
62
+ field and the section reader's own words for a body, because a second counter that disagreed
63
+ with the door by one would be worse than no read at all. Nothing is composed and nothing is
64
+ validated — a draft twice its limit is a **number**, where an `add` carrying it is a refusal,
65
+ and that difference is the whole verb. Over MCP it is the same read: `isError` where the draft
66
+ is over, because a caller gating on the answer should not have to parse prose for the one bit
67
+ it asked for.
68
+
69
+ Stdin is accepted here and nowhere else in this shape (RK329's objection, and why it does not
70
+ apply): a pipe does not rewind, so the writing verbs read one late and refuse the paragraph
71
+ back to the caller — this writes nothing, so a refusal costs a re-send of something that was
72
+ never going to land.
73
+
74
+ **Validated in characters, published in words** (RK185). A model has no characters: the
75
+ tokenizer exposes tokens, so "200 characters" is a target reached by trial and every retry
76
+ is a re-guess. Words survive tokenization well enough to be aimed at, so every number above
77
+ is also stated as one — the aim, beside the gate. They are not in conflict, because the
78
+ character figure is what refuses and the word figure is what an author can act on before a
79
+ sentence exists; publishing only the first is the arrangement L1 exists to end. The
80
+ conversion itself lives in :mod:`roadkeep.kernel.schema` and is read from here (RK201), because
81
+ the refusal an author reaches *after* an overrun states its surplus in words off the same
82
+ constant — one arithmetic in two directions, and not two constants that can disagree.
83
+ """
84
+
85
+ from __future__ import annotations
86
+
87
+ from dataclasses import dataclass, replace
88
+ from typing import Sequence
89
+
90
+ from pathlib import Path
91
+
92
+ from roadkeep.authoring import compose, prose_role
93
+ from roadkeep.config import Budget as ConfigBudget
94
+ from roadkeep.config import Config, spent, translated
95
+ from roadkeep.ids import next_id
96
+ from roadkeep.kernel.schema import (
97
+ CHARS_PER_WORD,
98
+ UTF16_UNITS,
99
+ Schema,
100
+ Task,
101
+ body_aim,
102
+ width,
103
+ words,
104
+ )
105
+ from roadkeep.scoping import NoSuchNonGoal, NotGoverned, address, leads, read
106
+ #: `words` here is the char-to-word conversion this module publishes as an aim; the section
107
+ #: reader's `words` is what a body is actually charged. Two arithmetics, so the import that
108
+ #: would have shadowed one is aliased rather than the two being reconciled (RK1190).
109
+ from roadkeep.sections import binding, declaring, find, words as prose_words
110
+
111
+ #: Re-exported, not re-declared (RK201). The conversion moved down to `schema`, where the
112
+ #: refusal that states a surplus can reach it: the aim and the surplus are the same
113
+ #: arithmetic in opposite directions, and two constants would be two answers.
114
+ __all__ = [
115
+ "CHARS_PER_WORD",
116
+ "AmbiguousAnchor",
117
+ "Body",
118
+ "Budget",
119
+ "Cost",
120
+ "Load",
121
+ "Share",
122
+ "body_budget",
123
+ "budget",
124
+ "budget_of",
125
+ "file_budget",
126
+ "non_goal_budget",
127
+ "words",
128
+ ]
129
+
130
+
131
+ class AmbiguousAnchor(ValueError):
132
+ """Two prose files declare one anchor, so no file is the one being budgeted (RK303).
133
+
134
+ A `ValueError` and deliberately not the `KeyError` this module already raises: that one
135
+ means "no prose file to be a fact about" and is swallowed where a line's own budget is
136
+ being read, and swallowing this one would put the answer back to a number about a file
137
+ nobody named. `show` and `ship` state the same finding in their own words; this is the
138
+ third door reaching it, and `--role` is what resolves it, the caller naming which of the
139
+ two they mean being the only thing that can.
140
+ """
141
+
142
+ def __init__(self, anchor: str, files: Sequence[str]) -> None:
143
+ self.anchor, self.files = anchor, tuple(files)
144
+ super().__init__(
145
+ f"§{anchor} is declared by {' and '.join(self.files)}: one anchor names one "
146
+ f"section, and a budget for the first of two prices a section the pointer does "
147
+ f"not reach — `budget --anchor {anchor} --role <role>` is which of the two "
148
+ f"you mean"
149
+ )
150
+
151
+
152
+ @dataclass(frozen=True, slots=True)
153
+ class Share:
154
+ """One prose field: its own declared limit, what this line leaves it, and what it took."""
155
+
156
+ field: str
157
+ #: The field's own declared maximum — `[limits]`, and what the MCP schema publishes.
158
+ limit: int
159
+ #: What *this* line allows it, which is the smaller of the two and the one that binds.
160
+ allowed: int
161
+ taken: int
162
+ #: Where that maximum was declared, as `Schema.source_of` spells it (RK1067, RK1071).
163
+ #: The refusal carries this and the read did not, which is the wrong way round: this is
164
+ #: the earlier of the two moments, and the one the whole tool is built on — the number
165
+ #: arriving before the prose does. Carried on the share rather than composed by the
166
+ #: printer, because a per-role limit means the answer differs by which file is asked
167
+ #: about, and only the reader that resolved the schema knows which one that was.
168
+ source: str = ""
169
+ #: Whether :attr:`taken` is prose the caller handed over to be measured rather than prose
170
+ #: the file holds (RK1190). It changes no arithmetic — a draft is measured against the same
171
+ #: allowance the write enforces, which is the whole claim — and it changes every word of the
172
+ #: answer: "153 written" about a paragraph that exists nowhere is a report about the wrong
173
+ #: file, and the caller cannot tell the two apart from the number.
174
+ drafted: bool = False
175
+ #: How many sentences this field accepts, or 0 where nothing bounds it (RK1225). A
176
+ #: **rule** and not a width, and it belongs here for the reason every width does: it is
177
+ #: knowable before a word exists and it refuses after one has been composed.
178
+ sentences: int = 0
179
+ #: Whether the field must end in a stop — the second rule over the same prose, published
180
+ #: with it because `--why`'s own help says *one sentence, ending in a stop* while this
181
+ #: read said only 200 and the line maximum. Two descriptions of one field disagreeing
182
+ #: about what binds it is the state RK1225 is about.
183
+ terminated: bool = False
184
+ #: Whether the write this budget is about **replaces** this field rather than adding to it
185
+ #: (RK1366). Every write that reaches one does — `amend --why`, `restate --symptom`,
186
+ #: `non-goal amend --why`, and the two sentences RK1365 fixed a file over — so the room for
187
+ #: the next one is the whole allowance and never the allowance less prose it deletes.
188
+ #:
189
+ #: :attr:`taken` is untouched by it and stays what the file holds, which is what
190
+ #: :attr:`over` is measured on: an adopting corpus's standing drift is exactly the finding
191
+ #: that number exists for, and zeroing the field to fix the remainder would take it out.
192
+ #: False wherever the prose *is* carried forward — a retirement's derived prefix, which the
193
+ #: author's reason is appended to (RK1305) — and false against a draft, where `taken` is
194
+ #: the prospective prose and the remainder is the overrun the write will be refused by.
195
+ replaced: bool = False
196
+
197
+ @property
198
+ def bounded(self) -> str:
199
+ """The rules this field is held to beyond its width, as one clause or `""` (RK1225).
200
+
201
+ Composed here rather than at the printer for :attr:`aimed`'s reason: which rules a
202
+ field has is a fact about the share, and a second reader spelling them would be a
203
+ second answer about what `add` will refuse.
204
+ """
205
+ said = []
206
+ if self.sentences:
207
+ said.append(f"{self.sentences} sentence" + ("s" if self.sentences > 1 else ""))
208
+ if self.terminated:
209
+ said.append("ending in a stop")
210
+ return ", ".join(said)
211
+
212
+ @property
213
+ def left(self) -> int:
214
+ """The room the *next* write has, which is the whole allowance where it replaces.
215
+
216
+ RK1365 found this arithmetic wrong for the ledger's sentence and RK1366 for the line
217
+ above it: nothing extends a one-sentence field, so `allowed - taken` described a write
218
+ nobody makes. On one line here the two readings were 55 and 200, and the word aims
219
+ beside them 8 against 31 — a quarter of the real figure, which is worse than none,
220
+ because an author either composes to it or stops believing the row.
221
+ """
222
+ return self.allowed if self.replaced else max(0, self.allowed - self.taken)
223
+
224
+ @property
225
+ def over(self) -> int:
226
+ """What this field exceeds its allowance by — 0 where it fits (RK1190).
227
+
228
+ The number :attr:`left` cannot carry, because that one floors at zero: a symptom of 200
229
+ against 120 reported `200 written, 0 left`, and the deficit an author has to cut was the
230
+ subtraction between two figures on the same row. Not the refusal's arithmetic borrowed —
231
+ the refusal states this same surplus from the other side, off :attr:`allowed`, which is
232
+ the one number both moments are derived from.
233
+ """
234
+ return max(0, self.taken - self.allowed)
235
+
236
+ @property
237
+ def aim(self) -> int:
238
+ """What this field allows, in the unit an author can count (RK185).
239
+
240
+ Derived from :attr:`allowed` and not from :attr:`limit`, which is the whole reason
241
+ it waited on RK183: an aim computed from the published ceiling would inherit the
242
+ overrun and send the author at prose the line has no room for.
243
+ """
244
+ return words(self.allowed)
245
+
246
+ @property
247
+ def aimed(self) -> str:
248
+ """The word figure, about the room the author actually has (RK245).
249
+
250
+ Beside a partly written field the whole-field aim answers a question nobody asked, and
251
+ read next to a remainder in characters it invites the reading that thirty words are
252
+ available when three are. So the two are never printed together: what is stated is the
253
+ aim for what is left, and `--json` keeps both.
254
+
255
+ "More" only where there is prose to add to (RK1366): on a replaced field the whole
256
+ figure *is* the remainder, and `aim 26 more words` beside a sentence about to be
257
+ deleted reads as twenty-six on top of the twenty-one already there.
258
+ """
259
+ return (
260
+ f"aim {self.room} more words"
261
+ if self.taken and not self.replaced
262
+ else f"aim {self.aim} words"
263
+ )
264
+
265
+ def payload(self) -> dict[str, object]:
266
+ """One prose field in both units, shared with the non-goal's two (RK283).
267
+
268
+ The same shape and the same arithmetic at both doors: a second spelling of it here would
269
+ be a second answer, and the whole reason this verb exists is that there is only one.
270
+ """
271
+ return {
272
+ "field": self.field,
273
+ "limit": self.limit,
274
+ "allowed": self.allowed,
275
+ "aim": self.aim,
276
+ "taken": self.taken,
277
+ "left": self.left,
278
+ # What `left` floors away (RK1190). Published always and not only when non-zero, for
279
+ # the reason `stats` prints `uncounted` at zero: a field that appears only when it
280
+ # is set is a field a reader learns to stop looking for.
281
+ "over": self.over,
282
+ # Whether `taken` is the file's prose or the caller's draft (RK1190): the same
283
+ # number means two different things and only this says which.
284
+ "drafted": self.drafted,
285
+ # And whether the write replaces it (RK1366), which is what makes `left` the whole
286
+ # allowance rather than the difference. Published for `drafted`'s reason: a consumer
287
+ # given `127 taken, 160 left` against a 160 allowance cannot otherwise tell an
288
+ # arithmetic it should not reproduce from one it should.
289
+ "replaced": self.replaced,
290
+ # The rules that are not widths (RK1225). `0` is *unbounded* and not *one*, which
291
+ # is what a project switching `[rules.<role>] one_sentence` off gets.
292
+ "sentences": self.sentences,
293
+ "terminated": self.terminated,
294
+ # Beside `left` and not instead of it (RK245): the characters are still what
295
+ # refuses, and this is the same remainder in the unit an author can count.
296
+ "room": self.room,
297
+ # Declared, as the section budget declares `words` (RK430). A number published
298
+ # without its unit is what let a consumer counting UTF-16 and a tool counting code
299
+ # points both be right about one line and disagree by one.
300
+ "unit": UTF16_UNITS,
301
+ "bound_by_line": self.bound_by_line,
302
+ # Where `limit` was set (RK1071), so a surface serving this can answer *why is it
303
+ # 200* without a second call — the read that otherwise costs a turn. Beside the
304
+ # number rather than under the payload, because a per-role limit makes it a fact
305
+ # about this field and not about the answer.
306
+ "source": self.source.strip(" ()"),
307
+ }
308
+
309
+ @property
310
+ def room(self) -> int:
311
+ """What is *left*, in that same unit (RK245).
312
+
313
+ The figure an `amend` is actually bounded by, and the one number RK185 skipped:
314
+ beside a partly written field, :attr:`aim` describes the whole of it, so `18 left
315
+ aim 30 words` invites the reading that thirty words are available when about three
316
+ are. Floored by :func:`~roadkeep.kernel.schema.words`, which is the right rounding here for
317
+ RK201's reason read from the other side — a remainder is an allowance, and an
318
+ allowance that rounds up is the retry both figures exist to remove.
319
+
320
+ Off :attr:`left` and not off `allowed - taken`, so RK1366's correction reaches the
321
+ unit an author actually composes in: the characters are what refuses and this is the
322
+ figure a sentence is written towards, so a wrong remainder here is the expensive half.
323
+ """
324
+ return words(self.left)
325
+
326
+ @property
327
+ def bound_by_line(self) -> bool:
328
+ """Whether the line is what binds this field, rather than the field's own limit.
329
+
330
+ The one thing a published `maxLength` cannot say: an author writing to the two
331
+ numbers in the schema is refused by a third, measured on a string they never write.
332
+ """
333
+ return self.allowed < self.limit
334
+
335
+
336
+ @dataclass(frozen=True, slots=True)
337
+ class Budget:
338
+ """What one line — written or about to be — has for prose, and how it is divided."""
339
+
340
+ task: Task
341
+ #: Whether the line exists. False means the id is the next one and the fields are the
342
+ #: caller's, which is the pre-`add` question; True means an `amend`'s.
343
+ open_line: bool
344
+ line_max: int
345
+ #: What the line costs before a word of prose: the marker, the bold id, the `(deps: …)`
346
+ #: group, the em dashes and the pointer. Rendered, never added up a second time (L3).
347
+ structure: int
348
+ prose: int
349
+ shares: tuple[Share, ...]
350
+ #: The anchor the structure above was measured with, or None where the line carries no
351
+ #: pointer at all. Under the id scheme it is the id and nobody chose it.
352
+ ref: str | None = None
353
+ #: Whether that anchor is an assumption rather than the caller's (RK265). True means the
354
+ #: outline scheme is in force, no ``ref`` was named, and the width came off the file.
355
+ ref_assumed: bool = False
356
+ #: The **other half of the same transaction** (RK301). `add --section` writes a line and
357
+ #: a body, the body has its own limit, and it refused the whole `add` while this read
358
+ #: mentioned only the line. None where the project declares no prose file, which is the
359
+ #: only state in which that write does not exist.
360
+ section: Body | None = None
361
+ #: Why there is no section budget, where the absence is a **defect** (RK303): an anchor
362
+ #: two prose files declare has no one file to be priced against, and a silent None reads
363
+ #: as the project that declares no prose file at all. Empty in every other state,
364
+ #: including that one, for the reason `show` states its absences apart.
365
+ section_absence: str = ""
366
+ #: The flags whose value came from the caller rather than from the line (RK1221). Empty on
367
+ #: every call that named none, which is `brief`'s and every read of a line as it stands.
368
+ stated: tuple[str, ...] = ()
369
+ #: Prose **this tool writes into a field before the caller's** (RK1305), where a write does
370
+ #: that. One write does: a retirement's `why` is a derived prefix plus the author's own
371
+ #: sentence, and the prefix is counted against the same limit the reason is refused by. So
372
+ #: it is neither structure — it is inside a prose field — nor the caller's, and a reader
373
+ #: handed `21 written` on a field nobody has drafted has no way to tell which. Empty
374
+ #: everywhere else, which is every budget about a line and every one about a ship.
375
+ derived: str = ""
376
+
377
+ def share(self, field: str) -> Share:
378
+ return next(one for one in self.shares if one.field == field)
379
+
380
+ def __str__(self) -> str:
381
+ """What this line has for prose, one field per row — the register a reader scans.
382
+
383
+ Beside :meth:`payload` since RK1170, and for that task's reason: these two were a printer
384
+ inside the handler and a builder in `rendering.py`, so one answer was spelled in two files
385
+ and neither held both. What the payload publishes is now what this shows, by construction
386
+ rather than by a test.
387
+ """
388
+ # Three states and not two (RK1305): `open_line=False` meant *the line `add` would
389
+ # write next* while this record now also answers for a line a **departure** writes, and
390
+ # a retirement's figures under that sentence describe the wrong write entirely.
391
+ if self.open_line:
392
+ state = "open line"
393
+ elif self.derived:
394
+ state = "the ledger line retire writes"
395
+ else:
396
+ state = "the line add would write next"
397
+ deps = ", ".join(dep.render() for dep in self.task.deps) or "—"
398
+ rows = [
399
+ f"{self.task.id} {self.task.status} deps {deps} ({state})",
400
+ f" line {self.line_max}, of which {self.structure} is structure",
401
+ ]
402
+ if self.stated:
403
+ # Said, because the number now depends on it (RK1221): a caller who passed
404
+ # `--symptom` and reads an allowance has to be able to see that it was theirs, and
405
+ # one whose flag matched the file changed nothing and is not told they did.
406
+ rows.append(
407
+ f" yours {', '.join(self.stated)} — measured as the line an `amend` "
408
+ f"carrying them would write, not as the line on file"
409
+ )
410
+ # Only where the caller could have named the anchor and did not (RK265). Said beside the
411
+ # structure it moved, because a number resting on a guess and one resting on the id read
412
+ # identically otherwise — and the guess is the one an `add --ref` can still correct.
413
+ if self.ref_assumed:
414
+ assumed = (
415
+ f"§{self.ref} assumed, the widest this roadmap carries"
416
+ if self.ref
417
+ else "none on this roadmap, so the structure counts no pointer"
418
+ )
419
+ rows.append(f" pointer {assumed} — pass --ref for the anchor this line will use")
420
+ if self.derived:
421
+ # Before the field rows, because it is what those numbers are already carrying
422
+ # (RK1305): `21 written` on a field nobody has drafted reads as the caller's prose
423
+ # and is the tool's, and the remainder underneath is the one that binds either way.
424
+ rows.append(
425
+ f" derived `{self.derived}` — written into the why before a word of "
426
+ f"yours, and counted against the same limit"
427
+ )
428
+ rows.append(f" prose {self.prose}")
429
+ # One row and not a clause per field (RK1366), which is where `derived` puts the same
430
+ # kind of note: what a remainder below means depends on this, and a reader handed
431
+ # `127 written, 160 left` against a 160 allowance reads the two as adding up.
432
+ if any(share.replaced and share.taken for share in self.shares):
433
+ rows.append(
434
+ " replacing what is written below, so each remainder is the whole allowance "
435
+ "and not what is left beside it — no write extends one of these fields"
436
+ )
437
+ for share in self.shares:
438
+ # The field's own limit is what the schema publishes; what this line allows is what
439
+ # refuses. Both, and which one binds, because that difference is the whole finding.
440
+ bound = " ← the line binds, not the field" if share.bound_by_line else ""
441
+ # "drafted" and not "written" where the prose is the caller's (RK1190): the number
442
+ # is the same and the two sentences are about different files, one of which has
443
+ # nothing in it yet. And the surplus rather than a floored `0 left`, which is what
444
+ # made a field three words over read as one exactly full.
445
+ held = "drafted" if share.drafted else "written"
446
+ spent = f", {share.over} over" if share.over else f", {share.left} left"
447
+ taken = f", {share.taken} {held}{spent}" if share.taken else ""
448
+ # The aim, beside the gate (RK185): the characters are what refuses and the words
449
+ # are what a model can count towards, so both are stated and neither is converted.
450
+ # The rules beside the widths (RK1225): a `why` that fits every number here and
451
+ # arrives as two sentences is still refused, so a read that published only the
452
+ # figures cost the composition it exists to save.
453
+ held = f", {share.bounded}" if share.bounded else ""
454
+ rows.append(
455
+ f" {share.field:<11}{share.allowed} of {share.limit}{taken}{held}"
456
+ f" {share.aimed}{bound}"
457
+ )
458
+ rows += sourced(self.shares)
459
+ # The other half of the same transaction (RK301): `add --section` writes a body too, and
460
+ # the body's limit refused the whole `add` while this read named only the line's fields.
461
+ if self.section is not None:
462
+ rows.append(f" section {self.section.stated()}")
463
+ elif self.section_absence:
464
+ # An absence that is a defect is said, never left as a missing row (RK303): the
465
+ # line's own two figures are still right, and the half nobody can price is the half
466
+ # a caller would otherwise read as "this project keeps no rationale file".
467
+ rows.append(f" section none — {self.section_absence}")
468
+ return "\n".join(rows)
469
+
470
+ def payload(self) -> dict[str, object]:
471
+ return {
472
+ "id": self.task.id,
473
+ "status": self.task.status,
474
+ "deps": [dep.render() for dep in self.task.deps],
475
+ "open_line": self.open_line,
476
+ "line_max": self.line_max,
477
+ "structure": self.structure,
478
+ # The pointer the structure was measured with, and whether anybody chose it (RK265):
479
+ # a client comparing this budget against its own `add` needs to know the difference.
480
+ "ref": self.ref,
481
+ "ref_assumed": self.ref_assumed,
482
+ "prose": self.prose,
483
+ "fields": [share.payload() for share in self.shares],
484
+ # The write this line is half of (RK301). Null where no prose file is declared,
485
+ # which is the only project on which `add --section` does not exist.
486
+ "section": None if self.section is None else self.section.payload(),
487
+ # Why it is null, where that is a defect rather than a project shape (RK303). Empty
488
+ # otherwise, so a client can tell the two nulls apart without a second call.
489
+ "section_absence": self.section_absence,
490
+ # Which flags the caller's own values came from (RK1221), so a consumer comparing
491
+ # this against the file can tell an answer about the line from an answer about the
492
+ # line an `amend` would write.
493
+ "stated": list(self.stated),
494
+ # What the tool wrote into a prose field before the caller's own (RK1305). Empty
495
+ # and never omitted, for `section_absence`'s reason: a client can then tell a write
496
+ # that derives nothing from a build that did not know the field existed.
497
+ "derived": self.derived,
498
+ }
499
+
500
+ def delta(self, base: "Budget | None", against: str | None) -> dict[str, object]:
501
+ """This budget as what it **changes** about another, never as a second copy (RK1298).
502
+
503
+ A brief prices three writes off one line — the line an `amend` rewrites, the ledger
504
+ entry a `ship` composes, and the decision a `--decides` files — and published all three
505
+ as whole tables. They differ in a handful of values; everything else repeats, per prose
506
+ field and with the section sub-object byte-identical. That repetition is the largest
507
+ thing in the payload which is not information, and it grows with every field a project
508
+ declares a limit on — against a read whose whole claim is that it costs less than
509
+ opening the file (RK1286).
510
+
511
+ So the second and third tables are stated as their difference from the first: ``against``
512
+ names the budget this was measured from, and ``changed`` carries only what moved. The
513
+ figures stay reachable by overlay and none of them is published twice.
514
+
515
+ Diffed off :meth:`payload` rather than off the fields, which is what keeps the two from
516
+ drifting: a key added there is diffed here without this method learning its name. Fields
517
+ are keyed by name because a delta addresses rows rather than ordering them, and a field
518
+ that moved in nothing is absent — as is ``section``, whose whole point is that it is the
519
+ same object. ``against`` of None means there was no base, and then ``changed`` is the
520
+ whole table: one shape, whichever it is.
521
+ """
522
+ mine = self.payload()
523
+ theirs = base.payload() if base is not None else {}
524
+ changed = {
525
+ key: value
526
+ for key, value in mine.items()
527
+ if key not in ("fields", "section") and theirs.get(key) != value
528
+ }
529
+ was = {row["field"]: row for row in theirs.get("fields", ())} # type: ignore[union-attr]
530
+ fields = {}
531
+ for row in mine["fields"]: # type: ignore[union-attr]
532
+ before = was.get(row["field"], {})
533
+ moved = {k: v for k, v in row.items() if k != "field" and before.get(k) != v}
534
+ if moved:
535
+ fields[row["field"]] = moved
536
+ if fields:
537
+ changed["fields"] = fields
538
+ if mine["section"] != theirs.get("section"):
539
+ changed["section"] = mine["section"]
540
+ return {"against": against, "changed": changed}
541
+
542
+
543
+ def budget(
544
+ config: Config,
545
+ task_id: str | None = None,
546
+ *,
547
+ block: str = "",
548
+ deps: Sequence[str] = (),
549
+ status: str | None = None,
550
+ symptom: str = "",
551
+ family: str | None = None,
552
+ ref: str | None = None,
553
+ why: str | None = None,
554
+ body: str | None = None,
555
+ retire: str | None = None,
556
+ ) -> Budget:
557
+ """The prose budget of a line, named by id or described by the fields an `add` takes.
558
+
559
+ An id that is not in the roadmap is not an error here: it is the third question, "what
560
+ would a line with *this* id have", which is what a caller checking a split (`RK9b`) is
561
+ asking. Only an id that resolves changes the answer, and then it changes it entirely —
562
+ the symptom, marker and deps come off the file rather than off the arguments.
563
+
564
+ ``ref`` is the anchor the line would point at, and only the outline scheme has one to
565
+ name: under the id scheme it is derived, so a caller passing a different one is refused
566
+ by :func:`~roadkeep.authoring.compose` exactly as `add` refuses it. It rides here because
567
+ the pointer is structure and the structure is what the prose is left over from — passing
568
+ it late is how a budget approves a sentence the `add` then refuses (RK265). An id the
569
+ roadmap holds keeps its own anchor unless this names another, which is the `amend` that
570
+ moves the pointer and the prose in one call.
571
+
572
+ ``why`` is the draft of that field (RK1190), and it is the one argument here that is
573
+ **measured rather than composed**: `symptom` goes through
574
+ :func:`~roadkeep.authoring.compose` because it is structure to the `why` — what it takes is
575
+ what the other loses — while a `why` moves no other number, so putting it through the
576
+ composer would buy nothing and cost the refusal this read exists to replace. ``None`` means
577
+ no draft, which the empty string is not: `--why ""` asks what an empty field costs.
578
+
579
+ ``retire`` asks the **third** shape of the same question (RK1305): what a retirement's
580
+ reason has, which is the one write this read did not answer for. `""` is an abandonment and
581
+ an id is a supersession, because the two spend different amounts of the field before the
582
+ author starts — and `None` is a caller who did not ask. Measured in an adopting project at
583
+ three refusals in a row, 250 then 212 then 205 against 200, each rewrite cutting a clause
584
+ out of the one field whose job is to carry evidence.
585
+ """
586
+ task, open_line, assumed = _subject(
587
+ config,
588
+ task_id,
589
+ block=block,
590
+ deps=deps,
591
+ status=status,
592
+ symptom=symptom,
593
+ family=family,
594
+ ref=ref,
595
+ )
596
+ if retire is not None:
597
+ return _retirement(config, task, retire, why=why, body=body)
598
+ answer = budget_of(
599
+ config,
600
+ task,
601
+ open_line=open_line,
602
+ ref_assumed=assumed,
603
+ # The one caller that knows (RK1320): `--symptom` is prose this call was handed, and
604
+ # a line the roadmap holds carries prose nobody typed here. `or None` and not the
605
+ # string, because `--symptom ""` is not a draft — it is the absence of one, and the
606
+ # tri-state `why` has is bought by an argument this one does not take.
607
+ symptom=symptom or None,
608
+ why=why,
609
+ body=body,
610
+ )
611
+ # Named here and not inside `_subject`, which answers with a task: which flags the caller
612
+ # supplied is a fact about the *call*, and the record that publishes it is this one.
613
+ held = config.document("roadmap").by_id().get(task_id or "")
614
+ return (
615
+ answer
616
+ if held is None
617
+ else replace(
618
+ answer, stated=_stated(held.task, block, deps, status, symptom, ref)
619
+ )
620
+ )
621
+
622
+
623
+ def _retirement(
624
+ config: Config, task: Task, superseded_by: str, *, why: str | None, body: str | None
625
+ ) -> Budget:
626
+ """What a retirement's reason has, before it is written (RK1305).
627
+
628
+ Priced under the **changelog's** grammar for the reason `brief`'s shipping figure is
629
+ (RK1199): a retirement writes a ledger line, whose limit is `[limits.changelog]` and whose
630
+ structure carries no deps and no pointer. Through :func:`~roadkeep.shipping.as_recorded`,
631
+ so the figure and the write cannot come apart.
632
+
633
+ And the derived prefix goes **into the field** rather than beside it, which is the one
634
+ thing this shape has that the other two do not: `abandoned:` and `superseded by RK41:` are
635
+ written by `retire` before a word of the author's, and counted against the same limit the
636
+ reason is refused by. So it is measured as prose the line already carries — `taken`, with
637
+ `left` the remainder that binds — and named on :attr:`Budget.derived`, because a reader
638
+ handed a non-zero `written` on a field nobody has drafted cannot tell whose it is.
639
+ """
640
+ from roadkeep.shipping import as_recorded, retiring # noqa: PLC0415 - RK260
641
+
642
+ prefix = retiring("", superseded_by or None)
643
+ composed = f"{prefix}{why or ''}"
644
+ return replace(
645
+ budget_of(
646
+ config,
647
+ as_recorded(task, config.schema.retired_marker, composed),
648
+ open_line=False,
649
+ schema=config.schema_for("changelog"),
650
+ # Drafted only where the caller drafted: the prefix is measured either way and is
651
+ # the tool's, and `drafted` is the flag that says which of the two a number is.
652
+ why=composed if why is not None else None,
653
+ body=body,
654
+ ),
655
+ derived=prefix,
656
+ )
657
+
658
+
659
+ def budget_of(
660
+ config: Config,
661
+ task: Task,
662
+ *,
663
+ open_line: bool,
664
+ ref_assumed: bool = False,
665
+ schema: Schema | None = None,
666
+ symptom: str | None = None,
667
+ why: str | None = None,
668
+ body: str | None = None,
669
+ ) -> Budget:
670
+ """The same answer about a task the caller already holds — what `brief` hands over.
671
+
672
+ Separate from :func:`budget` because the caller that has the line does not want it
673
+ looked up again, and because a shipped one has no budget to state: the ledger is a
674
+ different grammar, and the line an `amend` would rewrite is the open one.
675
+
676
+ ``schema`` is which grammar the answer is about (RK1174). The roadmap's is the default and
677
+ was the only one, which made the number `brief` printed the wrong one for the write an
678
+ author was usually about to make: a `ship` writes a **ledger** line, whose allowance comes
679
+ from `[limits.changelog]` and from a structure with no deps and no pointer in it. Measured
680
+ on one task: 162 characters for the line that exists and 172 for the line it ships to.
681
+
682
+ ``why`` is a draft to measure and not a field to set (RK1190): it changes what the answer
683
+ *reports* about that share and nothing it is derived from, which is why it arrives here
684
+ rather than on the task. ``None`` leaves the reading every caller before it had — the line's
685
+ own prose, which is what `brief` wants and what an `amend` is about to replace.
686
+
687
+ ``symptom`` says the same thing about the other field, and it is **said rather than
688
+ derived** (RK1320). Unlike ``why`` it is not a value this measures: the symptom is
689
+ structure to the `why` — what it takes is what the other loses — so it has to be on the
690
+ task before the line is rendered, and :func:`_subject` puts it there. What arrives here is
691
+ only *whose it is*, which is the one fact no reading of the task can recover.
692
+ """
693
+ # The **roadmap's** schema and not the base one (RK1225). `[limits.roadmap]` and
694
+ # `[rules.roadmap]` are what that file is held to (RK50, RK52), and `config.schema` carries
695
+ # neither — so on a project declaring either, this answered with numbers and rules nobody
696
+ # is judged by. Found publishing the sentence rule: a roadmap that had switched it off was
697
+ # still told `1 sentence`, and the widths beside it were wrong in the same direction. The
698
+ # same defect RK1199 fixed one role over, and `schema_for` is the reader both now use.
699
+ schema = schema or config.schema_for("roadmap")
700
+ prose = schema.prose_budget(task)
701
+ # The structure is derived from the budget rather than measured again: `prose_budget` is
702
+ # the one place that renders the emptied line, and a second measurement is a second answer.
703
+ shares: list[Share] = []
704
+ if schema.symptom_field:
705
+ shares.append(
706
+ Share(
707
+ "symptom",
708
+ schema.symptom_max,
709
+ min(schema.symptom_max, prose),
710
+ width(task.symptom),
711
+ schema.source_of("symptom_max"),
712
+ # **Said and no longer derived** (RK1320). This read `not open_line and
713
+ # bool(task.symptom)`, on the reasoning that a symptom on a line the roadmap
714
+ # does not hold came from the caller — true of the pre-`add` read the flag was
715
+ # written for, and false of every shape added since. `brief`'s `shipping` and
716
+ # `deciding` price a task read off the *file* under the ledger's grammar, and
717
+ # RK1305's retirement does the same, so one call answered `drafted: false` and
718
+ # `drafted: true` about the same 93 characters off the same line.
719
+ #
720
+ # `open_line` was a proxy for *the caller composed this* and stopped being one
721
+ # the moment a second reason to pass False existed. The caller that composed
722
+ # the prose is the caller that knows, which is the argument `why` already takes.
723
+ drafted=symptom is not None,
724
+ # `restate --symptom` is the one write that reaches this field and it replaces
725
+ # it (RK1366) — and only on a line that exists: the pre-`add` read has nothing
726
+ # written, and the ledger's inherited claim is carried forward rather than
727
+ # rewritten, which is `open_line` saying both at once.
728
+ replaced=open_line and symptom is None,
729
+ )
730
+ )
731
+ shares.append(
732
+ Share(
733
+ "why",
734
+ schema.why_max,
735
+ schema.why_budget(task),
736
+ width(task.why if why is None else why),
737
+ schema.source_of("why_max"),
738
+ drafted=why is not None,
739
+ # The two rules this field has beyond its width (RK1225), read off the schema
740
+ # exactly as the numbers are: a `why` that fits every figure published here and is
741
+ # written as two sentences is still refused, which is this verb costing a
742
+ # composition it exists to save. Per role, because `[rules.<role>]` switches them.
743
+ sentences=1 if schema.one_sentence else 0,
744
+ terminated=schema.terminator,
745
+ # The same for `amend --why` (RK1366). False where the prose is carried forward
746
+ # instead: a retirement's derived prefix is written *into* this field and the
747
+ # author's reason is appended to it, so there the remainder is the difference and
748
+ # `_retirement` reaches this through `open_line=False`.
749
+ replaced=open_line and why is None,
750
+ )
751
+ )
752
+ section, absence = _section_of(
753
+ config, task.ref or task.id, assumed=ref_assumed, body=body
754
+ )
755
+ return Budget(
756
+ task=task,
757
+ open_line=open_line,
758
+ line_max=schema.line_max,
759
+ structure=schema.line_max - prose,
760
+ prose=prose,
761
+ shares=tuple(shares),
762
+ ref=task.ref,
763
+ ref_assumed=ref_assumed,
764
+ # The same anchor the line points at, which makes this one read for both halves of
765
+ # the transaction (RK301): before the `add` it is the body about to be written, and
766
+ # on an open line it is what a `section amend` has left.
767
+ section=section,
768
+ section_absence=absence,
769
+ )
770
+
771
+
772
+ def _section_of(
773
+ config: Config, anchor: str, *, assumed: bool = False, body: str | None = None
774
+ ) -> tuple[Body | None, str]:
775
+ """This anchor's body budget, or None and why there is none.
776
+
777
+ Swallowing the refusal :func:`body_budget` raises rather than propagating it, because
778
+ the caller asked about a *line*: a project that declares no rationale file has a legal
779
+ `add` with no `--section` in it, and turning that into an error would refuse the read
780
+ every other project uses. The same holds for an anchor two files declare (RK303) — the
781
+ line's own two fields are unaffected by it — but that one is a defect and the other is
782
+ not, so the reason rides back with the absence rather than the two reading identically.
783
+
784
+ ``assumed`` says the anchor was **not chosen by anybody** — RK265's stand-in, the widest
785
+ pointer the roadmap already carries, used so the *structure* of an unwritten line is
786
+ never under-measured. Its occupancy is another task's, and reporting it answered the
787
+ question backwards (RK1041): `296 written, 4 left` about a section this task will not
788
+ write into, where what it gets is a fresh anchor and the whole limit. Measured twice in
789
+ one session — once an under-written section, once three retries of `add` against a
790
+ number bearing no relation to the limit enforced.
791
+
792
+ So the guess is kept where it is honest and dropped where it is not: the line's own two
793
+ fields still take the wider structure, and the section reads as the one an `add --section`
794
+ would create. Naming a `--ref` makes the anchor the caller's and this branch is not taken,
795
+ which is the read a child address wants (RK1029).
796
+ """
797
+ try:
798
+ answer = body_budget(config, anchor, body=body)
799
+ except AmbiguousAnchor as error:
800
+ return None, str(error)
801
+ except KeyError:
802
+ return None, ""
803
+ if assumed:
804
+ answer = replace(answer, taken=0, subtree=0, written=False, under="", under_taken=0)
805
+ return answer, ""
806
+
807
+
808
+ def _stated(
809
+ task: Task,
810
+ block: str,
811
+ deps: Sequence[str],
812
+ status: str | None,
813
+ symptom: str,
814
+ ref: str | None,
815
+ ) -> tuple[str, ...]:
816
+ """Which of the caller's fields differ from the line's own, by flag name (RK1221).
817
+
818
+ The answer names them, which is the half of RK465 a silent override would still be missing:
819
+ a caller who passed `--symptom` and gets a number back has to be able to see that it was
820
+ *their* symptom that produced it, and a caller who passed one identical to the file's has
821
+ changed nothing and should not be told they did.
822
+ """
823
+ given = (
824
+ ("--block", block, task.block),
825
+ ("--symptom", symptom, task.symptom),
826
+ ("--marker", status, task.status),
827
+ ("--ref", ref, task.ref),
828
+ )
829
+ named = [flag for flag, stated, held in given if stated and stated != held]
830
+ if deps and tuple(deps) != tuple(dep.render() for dep in task.deps):
831
+ named.append("--dep")
832
+ return tuple(named)
833
+
834
+
835
+ def _subject(
836
+ config: Config,
837
+ task_id: str | None,
838
+ *,
839
+ block: str,
840
+ deps: Sequence[str],
841
+ status: str | None,
842
+ symptom: str,
843
+ family: str | None,
844
+ ref: str | None = None,
845
+ ) -> tuple[Task, bool, bool]:
846
+ """The line the budget is about, whether the roadmap holds it, and whether it guessed.
847
+
848
+ **Every field the caller states wins over the file's** (RK1221), which until then was true
849
+ of `--ref` alone. The other arm composes a line out of `--block`, `--dep`, `--marker` and
850
+ `--symptom`; this one read all four and discarded them, so `budget RK12 --symptom "<a
851
+ rewrite I am weighing>"` answered about the symptom already on the line and said so
852
+ nowhere. RK465 named that shape — a narrowing flag nobody reads is worse than a refused
853
+ one, because the caller reads a number believing it narrowed it — and RK1190 sharpened it,
854
+ `--symptom` now being a draft to *measure*, which is exactly what an author weighing an
855
+ `amend` passes.
856
+
857
+ Honoured rather than refused, and all four rather than one: the deps and the marker move
858
+ the allowance as the symptom does, so taking one and ignoring the others would make four
859
+ flags mean two things. What comes back is the line an `amend` carrying those arguments
860
+ would write, which is the question that was being asked.
861
+
862
+ Re-composed and never `replace`d, so the rule each field is subject to is applied by the
863
+ one function that owns it (RK265): a `--ref` under the id scheme is refused here exactly as
864
+ the `amend` will refuse it, and so is a block no heading declares.
865
+ """
866
+ if task_id is not None:
867
+ entry = config.document("roadmap").by_id().get(task_id)
868
+ if entry is not None:
869
+ task = entry.task
870
+ stated = _stated(task, block, deps, status, symptom, ref)
871
+ if not stated:
872
+ # Nothing of the caller's to apply, which is every call before RK1221 and the
873
+ # one `brief` makes: the entry's own task, untouched and uncomposed.
874
+ return task, True, False
875
+ return (
876
+ compose(
877
+ config,
878
+ task_id=task.id,
879
+ block=block or task.block,
880
+ symptom=symptom or task.symptom,
881
+ why=task.why,
882
+ status=status or task.status,
883
+ deps=tuple(deps) if deps else tuple(dep.render() for dep in task.deps),
884
+ ref=ref if ref is not None else task.ref,
885
+ ),
886
+ True,
887
+ False,
888
+ )
889
+ assumed = ref is None and config.schema.ref_scheme != "id"
890
+ return (
891
+ compose(
892
+ config,
893
+ task_id=task_id if task_id is not None else next_id(config, family),
894
+ block=block,
895
+ symptom=symptom,
896
+ why="",
897
+ status=status,
898
+ deps=deps,
899
+ ref=_widest_anchor(config) if assumed else ref,
900
+ ),
901
+ False,
902
+ assumed and ref is None,
903
+ )
904
+
905
+
906
+ @dataclass(frozen=True, slots=True)
907
+ class Body:
908
+ """A section body's budget, declared and counted in the unit it is declared in (RK283).
909
+
910
+ Not a :class:`Share`, and deliberately: that one converts characters into an aim, and
911
+ `section = <n>` is **already** in words — running it through the conversion would state
912
+ a second number for a limit the config spells outright, which is RK258's finding at the
913
+ other door. So this carries no `aim`: the limit is the aim.
914
+ """
915
+
916
+ anchor: str
917
+ role: str
918
+ limit: int
919
+ #: This section's **own** prose, which is the argument an `amend` is about to replace.
920
+ taken: int
921
+ #: The same count over the subtree (RK287). Equal to :attr:`taken` on a leaf, and larger
922
+ #: on a parent — reported beside it and never instead of it, because charging a container
923
+ #: for its children names a figure the author cannot act on by editing the paragraph.
924
+ subtree: int
925
+ #: Whether the anchor names a section that exists. False is the pre-`section add` read,
926
+ #: where the whole limit is free; True is the `amend`, which is where it matters — there
927
+ #: the author holds a body and the number nobody has stated is what it has to fit inside.
928
+ written: bool
929
+ #: The ancestor address whose budget binds this one, and what it already spends (RK1029).
930
+ #: `("", 0)` where none does — a top level, or a parent that is a container nothing points
931
+ #: at, which the gate charges its own prose and not its children's.
932
+ #:
933
+ #: A **row and not a substitution**: the field's own limit is still the first number,
934
+ #: because that is what the paragraph in front of the author has to fit, and this is the
935
+ #: second one that decides whether the `add` after it lands. Before RK1029 there was
936
+ #: nowhere to put it, so `budget --anchor IX.1` answered `30 words, aim 28` about a parent
937
+ #: with one word of room — the pre-`add` read, wrong in the generous direction, on the one
938
+ #: question this whole tool is built to answer before the prose exists.
939
+ under: str = ""
940
+ under_taken: int = 0
941
+ #: A body the caller handed over to be measured, in words (RK1190). ``None`` is every call
942
+ #: before this argument existed and means "no draft", which is not the same as an empty one.
943
+ #:
944
+ #: Its own field and never folded into :attr:`taken`, which is the difference from
945
+ #: :class:`Share`: there, `allowed` is derived from the line and a draft can simply stand in
946
+ #: for what is written. Here `allowed` is derived from :attr:`taken` — a replacement body is
947
+ #: charged what its subsections spend and credited what its own prose gives back — so a
948
+ #: draft written into that field would move the allowance it is being measured against.
949
+ draft: int | None = None
950
+
951
+ @property
952
+ def over(self) -> int:
953
+ """What the draft exceeds the replacement allowance by — 0 where it fits (RK1190).
954
+
955
+ Against :attr:`allowed`, which is exactly what a write here accepts: the declared limit,
956
+ less what this section's own subsections spend, less what a binding ancestor has taken
957
+ elsewhere. Not against :attr:`left`, which asks a different question — how much *more*
958
+ a written section could hold — and would price an amend as though it were an insert.
959
+ """
960
+ return 0 if self.draft is None else max(0, self.draft - self.allowed)
961
+
962
+ @property
963
+ def draft_left(self) -> int:
964
+ """What the allowance still has under the draft — 0 where the draft is over."""
965
+ return 0 if self.draft is None else max(0, self.allowed - self.draft)
966
+
967
+ @property
968
+ def under_left(self) -> int:
969
+ """What the binding ancestor leaves this body, which is what the next write accepts.
970
+
971
+ **Less what this section already contributes** (RK1035). The ancestor's total is
972
+ billed with everything under it, this section included, so quoting it raw answered a
973
+ written child with the room an *insert* would have — two figures and the subtraction
974
+ between them, which is the analysis this door exists to remove rather than move.
975
+
976
+ :attr:`taken` and not :attr:`subtree`: a write replaces this section's **own** prose
977
+ and leaves its subsections where they are, so what comes back is what a replacement
978
+ body may say and not what deleting the whole subtree would free. On an unwritten
979
+ anchor both are zero and the answer is what it always was.
980
+ """
981
+ return max(0, self.limit - (self.under_taken - self.taken))
982
+
983
+ @property
984
+ def allowed(self) -> int:
985
+ """The limit that actually binds this body — :attr:`Share.allowed` for a section.
986
+
987
+ Every other field in this module reports the smaller of its own declared maximum and
988
+ what the line leaves it, and until RK1036 this was the one that reported the larger.
989
+ Measured on a parent whose subtree sat exactly at its limit: `30 words, 10 written,
990
+ 20 left … aim 18 more words`, an eighteen-word body refused, and ten what landed —
991
+ both figures on the line and the subtraction between them the reader's.
992
+
993
+ Two claims on one budget and the tighter wins. **Its own subtree**: a write replaces
994
+ this section's prose and its subsections stay, so what they spend is gone before a
995
+ word is composed. **Its binding ancestor** (RK1029): a subsection is charged to the
996
+ address that owns it. On a leaf with no ancestor both are the declared limit, which
997
+ is every section in a flat file and why this was invisible for so long.
998
+
999
+ The declared limit stays :attr:`limit` and is still what a reader is shown first —
1000
+ RK1029's "a row and not a substitution" — and this is what the aim is derived from.
1001
+ """
1002
+ own = self.limit - (self.subtree - self.taken)
1003
+ ancestor = self.under_left if self.under else self.limit
1004
+ return max(0, min(self.limit, own, ancestor))
1005
+
1006
+ @property
1007
+ def left(self) -> int:
1008
+ return max(0, self.allowed - self.taken)
1009
+
1010
+ @property
1011
+ def aim(self) -> int:
1012
+ """What the body may be composed to, which is under what refuses (RK301)."""
1013
+ return body_aim(self.allowed)
1014
+
1015
+ @property
1016
+ def room(self) -> int:
1017
+ """The same headroom applied to what is *left*, which is an amend's figure (RK245)."""
1018
+ return body_aim(self.left)
1019
+
1020
+ @property
1021
+ def nests(self) -> bool:
1022
+ """Whether the section carries subsections, so the two counts are two numbers."""
1023
+ return self.subtree != self.taken
1024
+
1025
+ def stated(self, named: bool = True) -> str:
1026
+ """A section body's budget as one line, shared by both doors that print it (RK283/301).
1027
+
1028
+ Words throughout and no character figure beside them (RK258) — this limit is declared in
1029
+ words. The aim sits **under** the limit rather than on it (RK301): composing to exactly
1030
+ the declared number is what the thirteen measured refusals did.
1031
+ """
1032
+ spent = f", {self.taken} written, {self.left} left" if self.written else ""
1033
+ nested = f", {self.subtree} with subsections" if self.nests else ""
1034
+ aim = (
1035
+ f"aim {self.room} more words" if self.written else f"aim {self.aim} words"
1036
+ )
1037
+ where = f" ({self.role})" if named else ""
1038
+ # The row RK1029 added, and it is a row: the field's own limit stays the first number,
1039
+ # because that is what the paragraph has to fit — and this is the one that decides
1040
+ # whether the `add` after it lands.
1041
+ # The verb is the one that follows this read (RK1035): a written anchor's next write is
1042
+ # an `amend`, and naming an `add` there priced a section the caller is not about to
1043
+ # insert. The number changed with the sentence — `under_left` is now what a replacement
1044
+ # body may say, this section's own prose already discounted.
1045
+ door = "amend" if self.written else "add"
1046
+ binds = (
1047
+ f"\n under §{self.under} spends {self.under_taken} of {self.limit}"
1048
+ f", so {self.under_left} is what an `{door}` here accepts"
1049
+ if self.under
1050
+ else ""
1051
+ )
1052
+ # The draft last, because it is the only row that is a verdict (RK1190): everything
1053
+ # above is a fact about the file and this is what the paragraph in hand costs against it.
1054
+ return f"{self.limit} words{where}{spent}{nested} {aim}{binds}{self._drafted()}"
1055
+
1056
+ def _drafted(self) -> str:
1057
+ """The row the draft adds, or nothing where none was handed over (RK1190)."""
1058
+ if self.draft is None:
1059
+ return ""
1060
+ verdict = (
1061
+ f"{self.over} over — cut about {self.over} word(s)"
1062
+ if self.over
1063
+ else f"fits, {self.draft_left} word(s) spare"
1064
+ )
1065
+ return f"\n draft {self.draft} words against {self.allowed}: {verdict}"
1066
+
1067
+ def payload(self) -> dict[str, object]:
1068
+ """One shape at both doors (RK301): the standalone read and the field on a line's own."""
1069
+ return {
1070
+ "anchor": self.anchor,
1071
+ "role": self.role,
1072
+ "written": self.written,
1073
+ # `unit` because this is the one budget already declared in words, and a client
1074
+ # reading `limit` beside a task's characters would otherwise compare the two.
1075
+ "unit": "words",
1076
+ "limit": self.limit,
1077
+ # What actually binds, which is `Share.allowed`'s field one door over (RK1036): the
1078
+ # smaller of the declared limit, what this section's own subsections spend, and what
1079
+ # a binding ancestor leaves. Equal to `limit` on a leaf in a flat file.
1080
+ "allowed": self.allowed,
1081
+ # Under the limit, not on it (RK301): the aim is what a body may be composed to.
1082
+ "aim": self.aim,
1083
+ "taken": self.taken,
1084
+ "left": self.left,
1085
+ "room": self.room,
1086
+ # Both figures, as `section show` carries both (RK287): `taken` is the argument and
1087
+ # this is what a reader pays for the whole subtree.
1088
+ "subtree": self.subtree,
1089
+ # The ancestor that binds, where one does (RK1029). Null and not omitted: a client
1090
+ # reading a missing key cannot tell "no ancestor" from "this server is older".
1091
+ "under": self.under or None,
1092
+ "under_taken": self.under_taken,
1093
+ "under_left": self.under_left if self.under else None,
1094
+ # The body the caller handed over, measured against `allowed` (RK1190). Null and not
1095
+ # zero where none was: an empty draft is a body of no words, which is a different
1096
+ # answer from no draft at all.
1097
+ "draft": self.draft,
1098
+ "over": self.over,
1099
+ }
1100
+
1101
+
1102
+ def non_goal_budget(config: Config, lead: str | None = None) -> tuple[Share, ...]:
1103
+ """The two limits `non-goal add` enforces, before either field is composed (RK283).
1104
+
1105
+ Both are characters and both are the list's own (RK70), so a caller reading a task's
1106
+ `why_max` here would be told a number this door does not use. Refused where the project
1107
+ has not opted in, for the reason the write is: a budget for a list nobody governs is a
1108
+ limit invented, and it would read as one the file is already held to.
1109
+
1110
+ ``lead`` names a bullet that exists, which makes this the `add`'s answer or the rewrite's:
1111
+ what is taken comes off that bullet, and what is left is the whole allowance, because
1112
+ `non-goal amend --why` replaces that argument and a changed lead is a drop and an add
1113
+ (RK1366). Neither field takes room from the other — a non-goal is two fields on two lines
1114
+ with no shared line limit — so :attr:`Share.allowed` is each one's own throughout.
1115
+ """
1116
+ if config.non_goals is None:
1117
+ raise NotGoverned(config.relative(config.source or config.root))
1118
+ scope = config.non_goals
1119
+ taken = {"lead": 0, "why": 0}
1120
+ if lead is not None:
1121
+ document = config.document("roadmap")
1122
+ wanted = address(lead)
1123
+ found = next((goal for goal in read(document) if address(goal.lead) == wanted), None)
1124
+ if found is None:
1125
+ raise NoSuchNonGoal(
1126
+ lead, config.relative(config.path("roadmap")), leads(document)
1127
+ )
1128
+ taken = {
1129
+ "lead": width(found.lead.strip()),
1130
+ "why": width(" ".join(found.why.split())),
1131
+ }
1132
+ return tuple(
1133
+ Share(field, limit, limit, taken[field], replaced=lead is not None)
1134
+ for field, limit in (("lead", scope.lead), ("why", scope.why))
1135
+ )
1136
+
1137
+
1138
+ @dataclass(frozen=True, slots=True)
1139
+ class Cost:
1140
+ """One unit of an always-loaded file's budget: what it may cost, and what it costs.
1141
+
1142
+ Neither unit is converted into the other and neither carries an aim (RK345). Lines and
1143
+ bytes are what the loader pays and what `[budgets]` declares, so a word figure here
1144
+ would be this module inventing a third number for a limit the config spells outright —
1145
+ RK258's finding at the one budget whose units were never characters to begin with.
1146
+ """
1147
+
1148
+ unit: str
1149
+ limit: int
1150
+ taken: int
1151
+
1152
+ @property
1153
+ def left(self) -> int:
1154
+ return max(0, self.limit - self.taken)
1155
+
1156
+ @property
1157
+ def over(self) -> int:
1158
+ """What the gate would refuse, which is the same subtraction the other way (RK30)."""
1159
+ return max(0, self.taken - self.limit)
1160
+
1161
+
1162
+ @dataclass(frozen=True, slots=True)
1163
+ class Part:
1164
+ """One `##` section of an every-turn file, and what it costs (RK1092).
1165
+
1166
+ The read `cost --tools` makes about the served surface, made about the resident file:
1167
+ that one ranks tools so an author cutting the schema knows where the size went, and this
1168
+ one had only a total. `agents.md` reached 8,392 of 8,400 bytes and the next compression
1169
+ was a preference — RK203 says compress the prose rather than the Layout index, which was
1170
+ an argument made when the prose had slack and nothing re-measured since.
1171
+
1172
+ Sections and not paragraphs, because a `##` is what the file itself declares and a
1173
+ paragraph is where a reader happened to stop. What this deliberately does not answer is
1174
+ which of them a turn *uses*: that needs a model of the reading, which is L4's own line,
1175
+ and a number invented for it would be worse than the total it replaced.
1176
+ """
1177
+
1178
+ #: The heading, verbatim, or `""` for whatever stands above the first one.
1179
+ heading: str
1180
+ lines: int
1181
+ bytes: int
1182
+ #: The section in UTF-16 code units, or `None` where the file does not decode (RK1253).
1183
+ #: The reading :attr:`Load.characters` is, one level down — charged by nothing and
1184
+ #: **never ranked on**: the order is the ceiling's (RK1252), and a list sorted by a figure
1185
+ #: nothing refuses would answer a question the gate never asks while looking like the one
1186
+ #: that does. A column, so the author cutting to fit the served comparison has the weight
1187
+ #: of each section without the list changing what it is about.
1188
+ #:
1189
+ #: `None` for the whole file or for none of it, which :func:`_parts` enforces rather than
1190
+ #: discovers. One direction is free: a UTF-8 continuation byte is never a newline, so
1191
+ #: splitting on line boundaries cannot break a sequence, and a file that decodes has
1192
+ #: sections that all do. The other is not — one bad byte makes the *file* undecodable
1193
+ #: while its other sections read fine, and reporting those would be a breakdown that does
1194
+ #: not sum to the total above it. So the absence is the file's and never a section's.
1195
+ characters: int | None = None
1196
+
1197
+
1198
+ @dataclass(frozen=True, slots=True)
1199
+ class Load:
1200
+ """What one every-turn file costs against what it declared it may (RK345)."""
1201
+
1202
+ #: As the project spells it, which is how `[budgets]` addresses it and how `lint` names it.
1203
+ path: str
1204
+ costs: tuple[Cost, ...]
1205
+ #: Where the size is, by section, largest first (RK1092). Empty where the file is not on
1206
+ #: disk, which is the one state that has no content to attribute.
1207
+ parts: tuple[Part, ...] = ()
1208
+ #: False is the state `lint` reports as `budget.absent`: a budget with nothing under it.
1209
+ #: Said rather than answered as a free file, because the whole limit being available is
1210
+ #: the one reading that would make a missing file look like room.
1211
+ present: bool = True
1212
+ #: Bytes this checkout carries that the count above left out — one per `\r\n` (RK1105).
1213
+ #: Reported and never charged: the ceiling is the commit's, so the number that decides is
1214
+ #: normalised, and this is the honest remainder a loader on *this* machine really pays.
1215
+ #: 0 on an LF checkout, which is every question about the two being the same question.
1216
+ translated: int = 0
1217
+ #: The same text in UTF-16 code units, or `None` where there is no answer — the file is
1218
+ #: absent, or it is not UTF-8 (RK1245). Beside `bytes` and never instead of it: `bytes` is
1219
+ #: what `[budgets]` declares and `lint` refuses on, and this is what a *reader* pays,
1220
+ #: which is the comparison `cost --session` exists to make against the served schema.
1221
+ #:
1222
+ #: Charged by nothing. :func:`~roadkeep.config.spent` stays bytes-only for the reason its
1223
+ #: own docstring gives — an instruction file is not a format this tool decodes (L4) — so
1224
+ #: this is a second reading of the same normalised bytes and never a second budget.
1225
+ characters: int | None = None
1226
+
1227
+ @property
1228
+ def over(self) -> bool:
1229
+ return any(cost.over for cost in self.costs)
1230
+
1231
+ @property
1232
+ def bytes(self) -> int:
1233
+ """What a loader pays for this file, or 0 where no byte budget was declared.
1234
+
1235
+ A property and not a sum at the call site (RK1096): `cost --session` re-derived it
1236
+ by walking `costs` for the unit it wanted, which is this record's own arithmetic
1237
+ performed by a reader — the shape RK345 removed from the two that count the file.
1238
+ """
1239
+ return next((cost.taken for cost in self.costs if cost.unit == "bytes"), 0)
1240
+
1241
+ @property
1242
+ def tightest(self) -> Cost | None:
1243
+ """The declared unit that will refuse first, or `None` where none is declared.
1244
+
1245
+ The room in one clause (RK1248). `--file` prints a row per unit because it is *about*
1246
+ this file; `--session` prints a row per file because it is about the session, and a
1247
+ line carrying every unit's room would spend the comparison it exists for on a
1248
+ breakdown the other read already gives.
1249
+
1250
+ **Tightest and not first**, measured as the share taken rather than the count left: a
1251
+ file 21 lines and 1494 bytes from its ceilings is nearer the first of them, and the
1252
+ one that refuses is the one to name. Ties go to the earlier unit, which is `lines`,
1253
+ because a tie is two right answers and picking is not this property's decision.
1254
+ """
1255
+ return min(
1256
+ (cost for cost in self.costs if cost.limit),
1257
+ key=lambda cost: (-(cost.taken / cost.limit), self.costs.index(cost)),
1258
+ default=None,
1259
+ )
1260
+
1261
+ @property
1262
+ def ranked(self) -> tuple[Part, ...]:
1263
+ """The sections, largest first **in the unit that will refuse this file** (RK1252).
1264
+
1265
+ :func:`_parts` sorted by bytes always, and RK1248 made the cost of that visible: the
1266
+ limit about to refuse may be `lines`, and a breakdown ranked by bytes then names a
1267
+ section that is not the one to cut. `agents.md` at 104 of 125 lines and 6906 of 8400
1268
+ bytes is a line problem, and its longest section by bytes is a table.
1269
+
1270
+ Keyed on :attr:`tightest` and not on a preference, so the ranking and the room are one
1271
+ decision — which is what stops the report advising against the ceiling it just stated.
1272
+ Bytes where nothing is declared, which is the order this always had.
1273
+
1274
+ Ties by heading, as :func:`_parts` does, because a tie is two right answers and the
1275
+ stable one is the one a second run reproduces.
1276
+ """
1277
+ cost = self.tightest
1278
+ unit = "bytes" if cost is None else cost.unit
1279
+ return tuple(
1280
+ sorted(self.parts, key=lambda part: (-getattr(part, unit), part.heading))
1281
+ )
1282
+
1283
+ @property
1284
+ def room(self) -> str:
1285
+ """What the tightest declared limit has left, as the clause `--session` prints.
1286
+
1287
+ Here and not at the reader for :attr:`bytes`' reason (RK1096): the subtraction is
1288
+ :class:`Cost`'s and the choice of which cost is this record's, so a caller composing
1289
+ either would be performing this record's arithmetic.
1290
+ """
1291
+ cost = self.tightest
1292
+ if cost is None:
1293
+ return ""
1294
+ if cost.over:
1295
+ return f"over by {cost.over} {cost.unit} of {cost.limit}"
1296
+ return f"{cost.left} {cost.unit} left of {cost.limit}"
1297
+
1298
+
1299
+ def _resident(load: Load) -> str:
1300
+ """One every-turn file as a `--session` row: the figure, the path, and what they are.
1301
+
1302
+ **Three states and not a reason with a default** (RK1251). RK1245 gave :class:`Load` a
1303
+ `characters` field and printed *bytes, because this file is not UTF-8* wherever it was
1304
+ `None` — which is true of a file that does not decode and false of a file that is not
1305
+ there, and `None` is what both leave. So a project whose declared `agents.md` is missing
1306
+ was told this tool could not read it.
1307
+
1308
+ Both other surfaces already say it plainly: `budget --file` prints `not on disk — the
1309
+ entry holds nothing`, and `lint` reports `budget.absent`, a finding that exists precisely
1310
+ because a budget with nothing under it is the one reading that makes a missing file look
1311
+ like room. This row was the third statement of that state and the only wrong one.
1312
+
1313
+ So the absent row **states no room either**, which is the other half RK1251 named: `10
1314
+ lines left of 10` is arithmetically true and is the sentence `budget.absent` exists to
1315
+ contradict. :attr:`Load.present` carries the distinction and always did.
1316
+ """
1317
+ if not load.present:
1318
+ return f"{0:>6} {load.path} not on disk — the entry holds nothing"
1319
+ figure = load.bytes if load.characters is None else load.characters
1320
+ said = f"{figure:>6} {load.path}"
1321
+ if load.characters is None:
1322
+ said += " (bytes: this file is not UTF-8)"
1323
+ # The room the project's own `[budgets]` line declares (RK1248), in the unit it declared
1324
+ # it in — which is named, because the figure to its left is not in it.
1325
+ return f"{said} {load.room}" if load.room else said
1326
+
1327
+
1328
+ @dataclass(frozen=True, slots=True)
1329
+ class Session:
1330
+ """Both halves of what a session pays, against the cadence each is paid at (RK1095).
1331
+
1332
+ **Two figures and never a sum.** The schema is sent once at the handshake and a resident
1333
+ file is read on every turn, so adding them produces a number that is wrong for every
1334
+ session whose turn count is not one — which is all of them. What is honest is naming each
1335
+ against what it is paid for, and letting the reader multiply the half that repeats.
1336
+
1337
+ A record since RK1170, and the refusal above is why it is worth one: the two registers
1338
+ each had to decline to add the same pair, in two places, by not writing a line.
1339
+ """
1340
+
1341
+ #: The served schema, in characters — what the handshake costs, once.
1342
+ once: int
1343
+ #: How many tools that schema describes, which is what the figure is *of*.
1344
+ tools: int
1345
+ #: Every resident file, in the order `file_budget` answers. The records themselves since
1346
+ #: RK1248 and no longer a widening tuple of their fields: this read wanted a third of them
1347
+ #: and then a fourth, and a projection is what RK1244 had just finished removing one
1348
+ #: surface over — :class:`Load` already *is* what one every-turn file costs against what
1349
+ #: it declared, which is exactly what a row here is about.
1350
+ resident: tuple[Load, ...] = ()
1351
+ #: The `SessionStart` notice, in the same unit as :attr:`once` (RK1243). The third thing
1352
+ #: a session pays for, and the one nothing counted: it is resident for the whole session
1353
+ #: in every governed project, it has a ceiling, and until now the ceiling was a constant
1354
+ #: a test asserted a fixture against. Measured **without** the drift sentence (RK234),
1355
+ #: which is deliberately over that ceiling and goes away with one `install` — what is
1356
+ #: priced here is what every session gets.
1357
+ notice: int = 0
1358
+ #: What the notice may cost, so the room is stated beside the figure — RK345's pairing,
1359
+ #: and the reason this is a read rather than a second gate.
1360
+ notice_limit: int | None = None
1361
+ #: What the served surface may cost, for the row that had no such pairing (RK1333). The
1362
+ #: notice beside it derived `+15 of 320` while this one printed 64679 and stopped, though
1363
+ #: `[tools] session` declares the ceiling and `budget.session` is the single finding that
1364
+ #: refuses the total against it — so there was one number to name and the row named none.
1365
+ #: Measured at 21 characters of room, which is the next sentence added to any one of 66
1366
+ #: tool descriptions: the reader most likely to run this verb is the one it answered
1367
+ #: least. Same pairing as :attr:`notice_limit` and for the same reason it is a read.
1368
+ once_limit: int | None = None
1369
+ #: The part of :attr:`once` that names the checkout rather than the surface (RK1334) —
1370
+ #: counted in, because a session is sent it, and out of what the ceiling is measured on,
1371
+ #: because no author can edit it. Its own row so the subtraction is visible: a figure that
1372
+ #: silently differed from the one the gate used would be RK1333's defect rebuilt.
1373
+ provenance: int = 0
1374
+
1375
+ @property
1376
+ def turn(self) -> int:
1377
+ """What a turn costs **a reader**, in the unit the once-per-session figures are in.
1378
+
1379
+ Code units and not bytes (RK1245), which is the whole point of the read: this verb
1380
+ exists so an author can decide between cutting a tool description and cutting a
1381
+ paragraph, and until now it asked them to make that comparison across two units. On
1382
+ ASCII prose the two agree and the defect is invisible; on a paragraph carrying the
1383
+ status markers this tool writes, bytes are three times code units and the choice a
1384
+ reader makes from these numbers is the wrong one.
1385
+
1386
+ A file that does not decode falls back to its bytes, which is the closest true thing
1387
+ available and is named as such in the row beneath.
1388
+ """
1389
+ return sum(
1390
+ load.bytes if load.characters is None else load.characters
1391
+ for load in self.resident
1392
+ )
1393
+
1394
+ @property
1395
+ def declared(self) -> int:
1396
+ """The same files in the unit `[budgets]` declares, which is what `lint` refuses on.
1397
+
1398
+ Stated and never converted into the figure above: the gate reads bytes for the reason
1399
+ :func:`~roadkeep.config.spent` gives — a budget is what a *loader* pays and an
1400
+ instruction file is not a format this tool decodes (L4). Two honest readings of one
1401
+ set of files, so the report can be compared without the gate being moved.
1402
+ """
1403
+ return sum(load.bytes for load in self.resident)
1404
+
1405
+ @property
1406
+ def at_connect(self) -> int:
1407
+ """Everything paid once, which is the schema **and** the notice (RK1243).
1408
+
1409
+ Added, where :attr:`once` and :attr:`turn` are not: the rule this record keeps is
1410
+ that two *cadences* may not be summed, and these two share one. A reader deciding
1411
+ whether to cut a tool description or a sentence from the notice is deciding inside
1412
+ one budget, which is exactly the arithmetic RK1095 removed from the pair above.
1413
+ """
1414
+ return self.once + self.notice
1415
+
1416
+ @staticmethod
1417
+ def _room(taken: int, limit: int | None) -> str:
1418
+ """The room beside a figure, in the one spelling both once-rows use (RK1333).
1419
+
1420
+ Shared rather than repeated because the defect was the two rows disagreeing about
1421
+ whether a ceiling gets named at all: a second copy is what let one of them keep a
1422
+ pairing the other never grew. A limit nothing declares stays silent, which is the
1423
+ state a project with no `[tools]` table is in and is not a finding.
1424
+ """
1425
+ return "" if limit is None else f", {limit - taken:+} of {limit}"
1426
+
1427
+ def stated(self, unit: str) -> str:
1428
+ rows = [
1429
+ f"session {self.at_connect} {unit} once, {self.turn} on every turn — "
1430
+ f"two cadences, so they are not added",
1431
+ f" once {self.once:>6} {self.tools} tool(s) and the handshake, at "
1432
+ f"connect{self._room(self.once - self.provenance, self.once_limit)}",
1433
+ ]
1434
+ if self.provenance:
1435
+ # Named under the figure it is inside, so the room above reads as a subtraction
1436
+ # somebody can check rather than as a number that disagrees with the total.
1437
+ rows.append(
1438
+ f" once {self.provenance:>6} of that names the checkout — no ceiling "
1439
+ f"is about it"
1440
+ )
1441
+ if self.notice:
1442
+ rows.append(
1443
+ f" once {self.notice:>6} the session-start notice"
1444
+ f"{self._room(self.notice, self.notice_limit)}"
1445
+ )
1446
+ rows += [f" turn {_resident(load)}" for load in self.resident]
1447
+ if not self.resident:
1448
+ # The state `--file` raises on, said rather than left as an absent row: a project
1449
+ # with no `[budgets]` pays the schema and nothing else, which is a real answer.
1450
+ rows.append(" turn 0 this project declares no [budgets] file")
1451
+ elif self.declared != self.turn:
1452
+ # Named once and not per row (RK1245): the conversion is one fact about the set,
1453
+ # and repeating it beside each file would spend the report on the difference
1454
+ # rather than on the comparison the reader came for. Silent where they agree,
1455
+ # which is every ASCII project and is where there is nothing to say.
1456
+ #
1457
+ # And it stops at the conversion (RK1249). It used to say bytes is *what `lint`
1458
+ # refuses on*, which is a third statement of the gate that neither the gate nor
1459
+ # the rows above agree with: `[budgets]` declares two units, `lint` emits
1460
+ # `budget.lines` and `budget.bytes` each naming its own, and the row above this
1461
+ # one already says which of them will refuse *this* file. A summary taking the
1462
+ # last word reads as the general rule, so what it may claim is only what it knows.
1463
+ rows.append(
1464
+ f" bytes {self.declared:>6} the same files in the unit `[budgets]` counts"
1465
+ )
1466
+ return chr(10).join(rows)
1467
+
1468
+ def payload(self, unit: str) -> dict[str, object]:
1469
+ return {
1470
+ # Named by cadence rather than by subject, because that is the fact a caller is
1471
+ # deciding against — and a `total` key would be the sum this read refuses.
1472
+ "once": {
1473
+ # The cadence's whole figure, with its two parts named under it (RK1243):
1474
+ # a caller acting on this is choosing which of them to cut.
1475
+ "characters": self.at_connect,
1476
+ "unit": unit,
1477
+ "of": f"{self.tools} tool(s) and the handshake, and the session-start notice",
1478
+ "schema": self.once,
1479
+ # Beside the figure it bounds, as the notice's is (RK1333): a consumer
1480
+ # reading `schema` to decide whether a description may grow was getting the
1481
+ # only number here that carried nothing to measure it against.
1482
+ "schema_limit": self.once_limit,
1483
+ # What the limit is actually measured on, beside what it is (RK1334): a
1484
+ # consumer subtracting these itself would be deriving the gate's number,
1485
+ # which is the duplication RK1096 removed one surface over.
1486
+ "schema_provenance": self.provenance,
1487
+ "schema_held": self.once - self.provenance,
1488
+ "notice": self.notice,
1489
+ "notice_limit": self.notice_limit,
1490
+ },
1491
+ "each_turn": {
1492
+ # The reader's unit, so the two cadences are comparable (RK1245) — with the
1493
+ # gate's own figure beside it rather than converted away.
1494
+ "characters": self.turn,
1495
+ "unit": unit,
1496
+ "bytes": self.declared,
1497
+ "files": [
1498
+ {
1499
+ "path": load.path,
1500
+ "bytes": load.bytes,
1501
+ "characters": load.characters,
1502
+ # Which of the two absences a null `characters` is (RK1251): a file
1503
+ # that is not there and one this could not decode are different
1504
+ # states, and a caller reading only the null cannot tell them apart.
1505
+ "present": load.present,
1506
+ # The tightest declared limit and what it has left, so a caller acts
1507
+ # on the one that refuses rather than on the first declared (RK1248).
1508
+ "limit": None
1509
+ if load.tightest is None
1510
+ else {
1511
+ "unit": load.tightest.unit,
1512
+ "declared": load.tightest.limit,
1513
+ "left": load.tightest.left,
1514
+ "over": load.tightest.over,
1515
+ },
1516
+ }
1517
+ for load in self.resident
1518
+ ],
1519
+ },
1520
+ }
1521
+
1522
+
1523
+ def notice_budget(config: Config) -> tuple[int, int | None]:
1524
+ """What this project's `SessionStart` line costs, and what it may (RK1243).
1525
+
1526
+ The third thing a session pays for, and the one no command could ask about. `--tools`
1527
+ prices the schema and `--file` the resident files; the notice is resident too — one line
1528
+ handed to every session in every governed project — and its ceiling was a constant in
1529
+ `guarding.py` that a test asserted a fixture against. RK1242 raised that constant by 23%
1530
+ to fit a clause, which is a change to what every adopting session pays, made by editing a
1531
+ literal. RK30's own argument, one surface over: a limit nobody counts is a limit that
1532
+ moves.
1533
+
1534
+ Measured off :func:`~roadkeep.guarding.announce` and never re-composed, which is
1535
+ :func:`~roadkeep.serving.surface`'s rule: it is the line *this* project's sessions get,
1536
+ with this project's paths in it, so a sentence reworded in `guarding.py` moves the figure.
1537
+
1538
+ **Without the drift sentence** (RK234), which is deliberately over the ceiling and is not
1539
+ resident — it appears only while a vendored copy has drifted and goes away with one
1540
+ `install`. What is priced here is what every session pays.
1541
+
1542
+ In UTF-16 code units, the unit every other figure in this module is in (RK430) — and the
1543
+ unit the ceiling is now held in, so this read and that gate cannot disagree about a line
1544
+ carrying a character outside the BMP.
1545
+
1546
+ ``(0, None)`` where there is no notice: a project this cannot announce for pays nothing,
1547
+ which is a real answer rather than a missing row.
1548
+ """
1549
+ from roadkeep.guarding import _NOTICE_BUDGET, announce # noqa: PLC0415 - RK260
1550
+
1551
+ said = announce({"cwd": str(config.root)}, config.root)
1552
+ if said is None:
1553
+ return 0, None
1554
+ return width(str(replace(said, stale=()))), _NOTICE_BUDGET
1555
+
1556
+
1557
+ @dataclass(frozen=True, slots=True)
1558
+ class Briefed:
1559
+ """What one task's brief costs a tool result, in the unit a model is charged (RK1286)."""
1560
+
1561
+ id: str
1562
+ characters: int
1563
+
1564
+ def over(self, limit: int | None) -> bool:
1565
+ return limit is not None and self.characters > limit
1566
+
1567
+
1568
+ @dataclass(frozen=True, slots=True)
1569
+ class Unpriced:
1570
+ """One line whose brief would not compose, and what refused it (RK1288)."""
1571
+
1572
+ id: str
1573
+ #: The tool's own answer, verbatim: what each unmeasured line was refused for is a
1574
+ #: sentence some module already wrote, so naming it costs a row and not a decision.
1575
+ because: str
1576
+
1577
+
1578
+ @dataclass(frozen=True, slots=True)
1579
+ class Reads:
1580
+ """Every open line's brief, widest first, against what one may cost (RK1286).
1581
+
1582
+ The one read this project recommends over reading the file, and the one thing here with no
1583
+ figure. Every resident file has a budget and the served surface has two, on RK30's
1584
+ argument that a limit nobody counts is a limit that moves — and `brief` grew four
1585
+ arithmetic rows in one session with nothing counting any of them.
1586
+
1587
+ **Widest first and not the median.** A brief that fits on the average task and not on the
1588
+ hardest one is a brief a session replaces by re-reading the file exactly when the file is
1589
+ longest, which is the cost RK29 removed. So the bound is the widest, and the listing is
1590
+ ordered to put it where a reader looks.
1591
+ """
1592
+
1593
+ briefs: tuple[Briefed, ...] = ()
1594
+ #: The lines whose briefs would not compose (RK1288). Dropped by a bare `continue`
1595
+ #: before, which made the one number this read exists for wrong in the direction that
1596
+ #: matters: the widest is the bound, and a line that could not be composed is exactly the
1597
+ #: shape most likely to be it — so the ranking named the top of the rest and called it
1598
+ #: the answer. No silent caps, and the gate inherits that: `read.over` is derived from
1599
+ #: this ranking, so a project could be over its ceiling on a line nothing reported.
1600
+ unpriced: tuple[Unpriced, ...] = ()
1601
+ #: How many open lines this reading did **not** ask for (RK1287). Above zero only on the
1602
+ #: gate's bounded read, and never a silence: a listing that omits without saying so reads
1603
+ #: as one that covered everything, which is the law this project holds about every capped
1604
+ #: answer it gives.
1605
+ elided: int = 0
1606
+ #: How many open lines there are (RK1289). **Carried and never reconstructed**: the note
1607
+ #: added `elided` to what it priced and called that the backlog, which is the backlog only
1608
+ #: while every line it asked for answered — a line that refused leaves the ranking without
1609
+ #: ever being elided, so four wanted of ten with one refusing printed "3 of 9". Three
1610
+ #: numbers that add up beats two arranged so the sum is wrong, and this reading walked
1611
+ #: every open id to compute the bound in the first place.
1612
+ open_lines: int = 0
1613
+ #: `[reads] brief`, or `None` where the project declared none — opt-in, as every other
1614
+ #: table whose absence means *ungoverned* rather than *zero* is.
1615
+ limit: int | None = None
1616
+
1617
+ @property
1618
+ def widest(self) -> Briefed | None:
1619
+ return self.briefs[0] if self.briefs else None
1620
+
1621
+ @property
1622
+ def over(self) -> tuple[Briefed, ...]:
1623
+ return tuple(one for one in self.briefs if one.over(self.limit))
1624
+
1625
+
1626
+ def brief_budget(
1627
+ config: Config, task_id: str | None = None, *, offered: bool = False
1628
+ ) -> Reads:
1629
+ """What a brief costs, per open line or for the one named (RK1286).
1630
+
1631
+ Measured off :func:`~roadkeep.briefing.brief`'s own rendering and never re-composed, which
1632
+ is :func:`~roadkeep.serving.surface`'s rule one read over: a row added to that answer moves
1633
+ this figure, which is the whole reason the number is worth reading.
1634
+
1635
+ In UTF-16 code units, the unit every other figure in this module is in (RK430) and the one
1636
+ a model is charged — so the read and the gate that refuses cannot disagree about an answer
1637
+ carrying a marker outside the BMP.
1638
+
1639
+ Open lines only. A shipped id has no brief left to start work from, and a paused one is a
1640
+ line `pick` can never offer — pricing either would be measuring an answer nobody asks for.
1641
+
1642
+ ``offered`` is the **bounded** reading, and it is the gate's (RK1287). A brief costs tens
1643
+ of milliseconds, so pricing every open line put a project that declared a ceiling at O(open)
1644
+ of them on every commit — six seconds on a two-hundred-line backlog, and the first thing
1645
+ anybody does with a gate that costs six seconds is stop running it. What this prices instead
1646
+ is the briefs a session is **about to ask for**: `pick`'s own answer and the alternatives it
1647
+ already names, which is a bound this module does not invent and one that moves with that
1648
+ verb. What it leaves out is :attr:`Reads.elided` — never dropped in silence.
1649
+ """
1650
+ from roadkeep.briefing import NothingToBrief, brief # noqa: PLC0415 - RK260
1651
+ from roadkeep.picking import pick # noqa: PLC0415 - RK260
1652
+
1653
+ roadmap = config.document("roadmap")
1654
+ every = list(roadmap.by_id())
1655
+ if task_id is not None:
1656
+ # The named form keeps the rule the unnamed one states (RK1291): a shipped line has
1657
+ # no brief left to start work from and a paused one is a line `pick` can never offer,
1658
+ # so an id that is not open answers as the absence it is rather than with a figure
1659
+ # comparable to nothing — a shipped brief carries no allowances, no deps and no
1660
+ # design, because the ship deleted them. `Whereabouts` is the reader every other
1661
+ # refusal about a missing id already asks (RK1213, RK1276).
1662
+ if task_id not in roadmap.by_id():
1663
+ from roadkeep.backlog import Whereabouts # noqa: PLC0415 - RK260
1664
+
1665
+ return Reads(
1666
+ limit=config.brief_read,
1667
+ unpriced=(
1668
+ Unpriced(
1669
+ id=task_id,
1670
+ because=(
1671
+ f"not an open line — {Whereabouts.of(config, task_id).sentence}, "
1672
+ f"and a brief is what starts work on one"
1673
+ ),
1674
+ ),
1675
+ ),
1676
+ open_lines=len(every),
1677
+ )
1678
+ wanted, elided = [task_id], 0
1679
+ elif offered:
1680
+ chosen = pick(config)
1681
+ named = [one.task.id for one in (chosen.entry,) if one is not None]
1682
+ # And the lines a live claim kept out of that ranking: a held line is one somebody is
1683
+ # working on, which is the strongest evidence there is that its brief gets asked for.
1684
+ # Without them a session holding the only open line priced nothing and said `0 of 1`,
1685
+ # which reads as a check doing nothing rather than as one that had nothing to do.
1686
+ held = [one.id for one in chosen.held]
1687
+ wanted = list(dict.fromkeys([*named, *chosen.alternatives, *held]))
1688
+ elided = max(0, len(every) - len(wanted))
1689
+ else:
1690
+ wanted, elided = every, 0
1691
+ out: list[Briefed] = []
1692
+ refused: list[Unpriced] = []
1693
+ for one in wanted:
1694
+ try:
1695
+ out.append(Briefed(id=one, characters=width(brief(config, one).stated(config))))
1696
+ except (NothingToBrief, KeyError, OSError) as error:
1697
+ # Named and never dropped (RK1288). An id no line carries is still not this
1698
+ # read's to *refuse* — it is asked about the backlog, and a caller naming a
1699
+ # shipped task is answered by `show` — but a line the ranking could not measure
1700
+ # is the one most likely to have been the widest, so its absence is the answer.
1701
+ refused.append(Unpriced(id=one, because=str(error) or type(error).__name__))
1702
+ return Reads(
1703
+ briefs=tuple(sorted(out, key=lambda one: one.characters, reverse=True)),
1704
+ limit=config.brief_read,
1705
+ elided=elided,
1706
+ unpriced=tuple(refused),
1707
+ open_lines=len(every),
1708
+ )
1709
+
1710
+
1711
+ def file_budget(config: Config, path: str | None = None) -> tuple[Load, ...]:
1712
+ """What the always-loaded files have left, before an edit is composed (RK345).
1713
+
1714
+ The one limit this format holds that had no pre-write read. Every other budget here is
1715
+ answered from the id, the marker, the deps and the pointer; this one is answered from
1716
+ the file on disk and `roadkeep.toml`, and neither waited on the edit either — but the
1717
+ room was measured with two `wc` reads and a subtraction by hand, and the second spelling
1718
+ of a Layout entry was one line over. That is the analysis L1 exists to remove, one file
1719
+ over from the ones this tool governs.
1720
+
1721
+ A tuple whether one file is named or none, so the shape does not depend on the question:
1722
+ unnamed is every declared budget, and named is the one — matched on the path the project
1723
+ declared *or* on any spelling that resolves to the same file, because the caller has the
1724
+ file open and not `roadkeep.toml`. Not a second gate (RK50): `lint` refuses the file that
1725
+ went over, this reports what is left, and both count through
1726
+ :func:`~roadkeep.config.spent`.
1727
+ """
1728
+ if not config.budgets:
1729
+ raise KeyError(
1730
+ f"{config.relative(config.source or config.root)} declares no [budgets]: "
1731
+ f"a budget for a file nobody declared is a limit invented here"
1732
+ )
1733
+ declared = config.budgets
1734
+ if path is not None:
1735
+ wanted = Path(path)
1736
+ resolved = (config.root / wanted).resolve()
1737
+ declared = tuple(
1738
+ one
1739
+ for one in config.budgets
1740
+ if config.relative(one.path) == str(wanted).replace("\\", "/")
1741
+ or one.path.resolve() == resolved
1742
+ )
1743
+ if not declared:
1744
+ named = ", ".join(config.relative(one.path) for one in config.budgets)
1745
+ raise KeyError(f"no [budgets] entry for {path}: this project budgets {named}")
1746
+ return tuple(_load(config, one) for one in declared)
1747
+
1748
+
1749
+ def _load(config: Config, budget: ConfigBudget) -> Load:
1750
+ raw = budget.path.read_bytes() if budget.path.is_file() else None
1751
+ measured = spent(raw if raw is not None else b"")
1752
+ # Normalised before `_parts`, and not only in the total (RK1105): a breakdown counted off
1753
+ # the checkout sums past the number above it, and the reader comparing the two is deciding
1754
+ # what to cut. One convention, both figures.
1755
+ counted = b"" if raw is None else raw.replace(b"\r\n", b"\n")
1756
+ return Load(
1757
+ path=config.relative(budget.path),
1758
+ costs=tuple(
1759
+ Cost(unit, limit, measured[unit])
1760
+ for unit, limit in (("lines", budget.lines), ("bytes", budget.bytes))
1761
+ if limit is not None
1762
+ ),
1763
+ parts=_parts(counted) if raw is not None else (),
1764
+ present=raw is not None,
1765
+ translated=0 if raw is None else translated(raw),
1766
+ characters=None if raw is None else _characters(counted),
1767
+ )
1768
+
1769
+
1770
+ def _characters(counted: bytes) -> int | None:
1771
+ """The normalised bytes as UTF-16 code units, or `None` where they are not UTF-8 (RK1245).
1772
+
1773
+ `None` and never a guess: a file this cannot decode is one where the question *what does
1774
+ a reader pay for it* has no answer here, and its bytes alone are then the honest row.
1775
+ Nothing is refused either way — the gate reads bytes and is untouched.
1776
+
1777
+ The **normalised** bytes, which is the convention the total is counted on (RK1105): a
1778
+ figure counted off the checkout's own terminator would disagree with the number printed
1779
+ beside it on exactly the machines a budget is a fact about.
1780
+ """
1781
+ try:
1782
+ return width(counted.decode("utf-8"))
1783
+ except UnicodeDecodeError:
1784
+ return None
1785
+
1786
+
1787
+ def _parts(raw: bytes) -> tuple[Part, ...]:
1788
+ """The file's `##` sections, largest first (RK1092).
1789
+
1790
+ Bytes and never text, for the reason the budget itself is counted that way: an instruction
1791
+ file is not a format this tool decodes (L4). Handed the same normalised bytes the total is
1792
+ counted from (RK1105) — this sentence said the opposite while that was true of both, and a
1793
+ breakdown on the checkout's own terminator would sum past the number printed above it.
1794
+
1795
+ The order here is the *record's* since RK1252: this one produces both figures and
1796
+ :attr:`Load.ranked` sorts them by whichever limit is about to refuse. Sorted at all,
1797
+ still, because a caller reading `Load.parts` directly gets a stable order rather than
1798
+ the accident of the file's own layout.
1799
+
1800
+ Only `##`, because that is the level `agents.md` organises by — a `###` under one belongs
1801
+ to it, and splitting there would report a heading's own body as a sibling of its parent.
1802
+ """
1803
+ # The reading is the file's or nobody's (RK1253): one bad byte makes the whole undecodable
1804
+ # while its other sections read fine, and a column present on four rows of seven is a
1805
+ # breakdown that does not sum to the total it sits under.
1806
+ decodes = _characters(raw) is not None
1807
+ sections: list[tuple[str, list[bytes]]] = [("", [])]
1808
+ for line in raw.splitlines(keepends=True):
1809
+ if line.startswith(b"## "):
1810
+ sections.append((line.decode("utf-8", "replace").rstrip(), []))
1811
+ sections[-1][1].append(line)
1812
+ return tuple(
1813
+ sorted(
1814
+ (
1815
+ Part(
1816
+ heading=name,
1817
+ lines=len(body),
1818
+ bytes=sum(len(one) for one in body),
1819
+ characters=_characters(b"".join(body)) if decodes else None,
1820
+ )
1821
+ for name, body in sections
1822
+ if body
1823
+ ),
1824
+ key=lambda part: (-part.bytes, part.heading),
1825
+ )
1826
+ )
1827
+
1828
+
1829
+ def body_budget(
1830
+ config: Config, anchor: str, role: str | None = None, body: str | None = None
1831
+ ) -> Body:
1832
+ """What a section body may say, in words, before one is written (RK283).
1833
+
1834
+ The longest thing an author composes and the limit that cost the most to meet at the
1835
+ door: 366 words against 300, discovered by writing 366. Everything it needs is the role's
1836
+ `section = <n>` and, for an `amend`, what the section already spends — both facts about
1837
+ the file, neither of which waited on the paragraph.
1838
+
1839
+ The role is resolved the way every other reader resolves it (RK196) and never assumed to
1840
+ be `improvements`: the file that *holds* the anchor where one does, and otherwise the one
1841
+ a `section add` would write into — because an unwritten anchor is the pre-write question
1842
+ and the answer has to be about the file that write will land in. A named ``role`` wins.
1843
+
1844
+ An anchor **two files declare is refused** (RK303), which is what every other reader of
1845
+ the same question does: `show` answers that the pointer resolves to neither, `ship`
1846
+ leaves the section rather than choosing which of the two the line meant, and the gate
1847
+ reports `section.ambiguous` at both headings. Answering with the first was the one door
1848
+ that had not learned it, and it priced a limit for a section the author cannot address —
1849
+ the number right about a file that was picked rather than named. ``role`` is the way
1850
+ through, because naming which of the two is meant is the only thing that resolves it and
1851
+ no verb here may resolve it by picking (L4).
1852
+
1853
+ ``body`` is the draft this anchor is about to be given (RK1190), counted by the same reader
1854
+ the written prose is counted by rather than by a second one here: the gate, the write and
1855
+ this read all have to agree about what a word is, and the only way they can is by asking
1856
+ once. It is never composed and never validated — what comes back is
1857
+ :attr:`Body.over`, where an actual `section add` would come back a refusal.
1858
+ """
1859
+ named, where = role, config.relative(config.source or config.root)
1860
+ if role is None:
1861
+ # One resolver, called and not repeated (RK229) — the copy that lived here is the
1862
+ # copy that never learned what two declaring files mean.
1863
+ holders = declaring(config, anchor)
1864
+ if len(holders) > 1:
1865
+ raise AmbiguousAnchor(
1866
+ anchor, [config.relative(config.path(name)) for name in holders]
1867
+ )
1868
+ role = holders[0] if holders else prose_role(config)
1869
+ if role is None or not config.has(role):
1870
+ # Named or derived, and never the same sentence for both: a project that declares
1871
+ # `strategy` and was asked for it is a different mistake from one declaring neither.
1872
+ missing = f"declares no {named}" if named else "declares no prose file"
1873
+ raise KeyError(
1874
+ f"{where} {missing} to budget §{anchor} against: a section limit is a fact "
1875
+ f"about a role, and this one has no file to be a fact about"
1876
+ )
1877
+ section = find(config.document(role), anchor) if config.path(role).is_file() else None
1878
+ binds, spends = _binding(config, role, anchor)
1879
+ return Body(
1880
+ anchor=anchor,
1881
+ role=role,
1882
+ limit=config.schema_for(role).section_max,
1883
+ taken=0 if section is None else section.own_words,
1884
+ subtree=0 if section is None else section.words,
1885
+ written=section is not None,
1886
+ under=binds,
1887
+ under_taken=spends,
1888
+ # Counted by the reader that counts the written prose, never by a second one here.
1889
+ draft=None if body is None else prose_words(body),
1890
+ )
1891
+
1892
+
1893
+ def _binding(config: Config, role: str, anchor: str) -> tuple[str, int]:
1894
+ """The ancestor whose budget decides what a body here may say, and what it spends (RK1029).
1895
+
1896
+ Every ancestor and not the immediate one, because a parent with room under a grandparent
1897
+ with none is still a write the gate fails — and the *tightest* of them, since that is the
1898
+ one an `add` will actually be refused by. `("", 0)` where none binds.
1899
+
1900
+ What binds is :func:`~roadkeep.sections.binding`, which is the same reading `add` now
1901
+ refuses on and the same one the gate bills: a container nothing points at is measured on
1902
+ its own prose, so it never binds a child, and reporting it here would price a body
1903
+ against a heading nobody charges (RK215).
1904
+ """
1905
+ tightest, spent = "", 0
1906
+ parent = anchor.rsplit(".", 1)[0] if "." in anchor else ""
1907
+ while parent:
1908
+ answer = binding(config, role, parent)
1909
+ if answer is not None and answer[0] > spent:
1910
+ tightest, spent = parent, answer[0]
1911
+ parent = parent.rsplit(".", 1)[0] if "." in parent else ""
1912
+ return tightest, spent
1913
+
1914
+
1915
+ def _widest_anchor(config: Config) -> str | None:
1916
+ """The longest pointer the roadmap already carries, or None on a file carrying none.
1917
+
1918
+ The stand-in for an anchor the caller did not name (RK265). Widest and not narrowest,
1919
+ and not none: the whole defect is a budget that promised room the `add` then refused, so
1920
+ an assumption that can be wrong is made wrong in the direction that costs an author
1921
+ nothing — a sentence with characters to spare, rather than a second composition of it.
1922
+
1923
+ A roadmap holding no pointer at all is the one case with no evidence to reason from, and
1924
+ None is that stated rather than papered over: the caller is told the structure counts no
1925
+ pointer, which is the honest form of the number this task found being reported silently.
1926
+ """
1927
+ return max(
1928
+ (entry.task.ref for entry in config.document("roadmap").entries if entry.task.ref),
1929
+ key=len,
1930
+ default=None,
1931
+ )
1932
+
1933
+
1934
+ def sourced(shares: Sequence[Share]) -> list[str]:
1935
+ """Where the numbers above came from, as the one row that says it (RK1071).
1936
+
1937
+ One line and not a parenthesis after each figure: the read is a column of small numbers
1938
+ and an address on every row drowns it, where the fact is almost always the same for all
1939
+ of them. Split only where the project declared some and not others, which is exactly
1940
+ when *which of these did I choose* is a live question — and silent where it declared
1941
+ none, because `this tool's default` five times over is the noise this avoids.
1942
+ """
1943
+ chosen = [share for share in shares if not share.source.endswith("default)")]
1944
+ if not chosen:
1945
+ return []
1946
+ # Grouped by the table, because that is what a reader opens: one file and one heading,
1947
+ # then the line each field is on. Two roles can differ (RK50), so the grouping is real
1948
+ # rather than cosmetic — a `[limits.changelog]` share sorts under its own key.
1949
+ tables: dict[str, list[str]] = {}
1950
+ for share in chosen:
1951
+ address, _, table = share.source.strip(" ()").partition(" ")
1952
+ file, _, lineno = address.partition(":")
1953
+ tables.setdefault(f"{file} {table.rsplit('.', 1)[0]}", []).append(
1954
+ f"{share.field}:{lineno}" if lineno else share.field
1955
+ )
1956
+ said = "; ".join(f"{table} {', '.join(fields)}" for table, fields in tables.items())
1957
+ fell_back = [share.field for share in shares if share not in chosen]
1958
+ rest = f"; {', '.join(fell_back)} is this tool's default" if fell_back else ""
1959
+ return [f" declared {said}{rest}"]
1960
+
1961
+
1962
+ #: The percentile the conversion follows, which is the sentence above `CHARS_PER_WORD`: an
1963
+ #: author who lands on the word aim clears the character gate about nineteen times in twenty.
1964
+ #: Stated here because the reading and the constant have to follow one number, and a second
1965
+ #: spelling of it is what let the corpus grow past the figure with only a test to say so.
1966
+ CONVERSION_AT = 95
1967
+
1968
+
1969
+ @dataclass(frozen=True, slots=True)
1970
+ class Fixed:
1971
+ """One number this build fixes from a corpus, with the reading that fixes it (RK1381).
1972
+
1973
+ Here and not in `describing`, which is the module that prints it (RK1382): a record belongs
1974
+ with the reading that builds it, and declaring it beside the presenter made the two import
1975
+ each other inside functions — so neither import could sit at the top of its file and this
1976
+ module's own reading could not name its return type.
1977
+
1978
+ What it holds is the reading and never only the figure, which is the whole of RK1381: every
1979
+ other number decided by one has a verb that states it — `govern <key>` with no value,
1980
+ `cost`, `budget --file` — and this one had a comment in source and an assertion in a suite,
1981
+ so a corpus that grew past it spoke through a red test and the new figure took a throwaway
1982
+ script to get.
1983
+
1984
+ How it is *stated* stays the presenter's, which is the line this move does not cross: the
1985
+ two methods below are the same pair every record here carries (RK1170), one answer in two
1986
+ registers, and a `config` that composed its own row would be the second spelling of it.
1987
+ """
1988
+
1989
+ name: str
1990
+ at: float
1991
+ #: The corpus it was taken over, as a count of the things measured.
1992
+ sample: int
1993
+ #: The percentile the figure follows, and the figure it follows it at.
1994
+ percentile: int
1995
+ reading: float
1996
+ why: str
1997
+
1998
+ def stated(self) -> str:
1999
+ return (
2000
+ f" {self.name:<12} {self.at} p{self.percentile} {self.reading} over "
2001
+ f"{self.sample} — {self.why}"
2002
+ )
2003
+
2004
+ def payload(self) -> dict[str, object]:
2005
+ return {
2006
+ "name": self.name,
2007
+ "at": self.at,
2008
+ "sample": self.sample,
2009
+ "percentile": self.percentile,
2010
+ "reading": self.reading,
2011
+ "why": self.why,
2012
+ }
2013
+
2014
+
2015
+ def conversion(config: Config) -> Fixed:
2016
+ """The reading behind `CHARS_PER_WORD`, as a command rather than a script (RK1381).
2017
+
2018
+ Every other number decided by a reading has a verb that states it — `govern <key>` with no
2019
+ value, `cost`, `budget --file`, `weight`. This one had a comment in source and an assertion
2020
+ in a suite, so a corpus that grew past it spoke through a red test and getting the new
2021
+ figure meant writing the same throwaway measurement twice in one session.
2022
+
2023
+ The **same corpus the constant is fixed from**: this project's own written `symptom` and
2024
+ `why` fields, across the roadmap and the ledger, which is the prose the format is proven by
2025
+ (RK18). A field nobody wrote is left out rather than counted as zero characters per zero
2026
+ words, that being a division and not a reading.
2027
+
2028
+ A read and never a write. There is nothing to declare — the conversion is a property of the
2029
+ prose those lines are written in and not a project's to configure (L6) — so what comes back
2030
+ is the percentile, the sample it was taken over, and the figure this build carries.
2031
+ """
2032
+ ratios = sorted(
2033
+ len(text) / len(text.split())
2034
+ for role in ("roadmap", "changelog")
2035
+ if config.has(role) and config.path(role).is_file()
2036
+ for entry in config.document(role).entries
2037
+ for text in (entry.task.symptom or "", entry.task.why or "")
2038
+ if text.split()
2039
+ )
2040
+ if not ratios:
2041
+ raise ValueError(
2042
+ "this project has written no symptom or why to measure, so the conversion has no "
2043
+ "corpus here: the figure this build carries is the one it was fixed from elsewhere"
2044
+ )
2045
+ at = ratios[min(int(len(ratios) * CONVERSION_AT / 100), len(ratios) - 1)]
2046
+ return Fixed(
2047
+ name="chars/word",
2048
+ at=CHARS_PER_WORD,
2049
+ sample=len(ratios),
2050
+ percentile=CONVERSION_AT,
2051
+ reading=round(at, 2),
2052
+ why=(
2053
+ "the first round number above this corpus's percentile, so a word aim clears the "
2054
+ "character gate about nineteen times in twenty"
2055
+ ),
2056
+ )