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/authoring.py ADDED
@@ -0,0 +1,2117 @@
1
+ """Writing the line, so the limit is met before the sentence exists (RK5).
2
+
3
+ This is the module the whole tool is for. Everything before it proves the format can
4
+ be read; `add` is where the format starts being *enforced at the moment of writing*
5
+ (L1), and the difference is not convenience:
6
+
7
+ * A linter reports after the prose exists. The tokens are already spent, and the
8
+ author is being asked to delete work they just justified — which is why the ninety-two
9
+ over-length lines that motivated this tool were written by authors who knew the rule.
10
+ * `add` refuses an over-length ``why`` **before** a second sentence is composed to fill
11
+ it, and the refusal names the limit, the actual length, and the file the remainder
12
+ belongs in. *The saving is the analysis, not the characters:* the author stops asking
13
+ "is this too long, what would I cut?" and starts calling a command.
14
+
15
+ Three decisions that are the point of the module rather than details of it:
16
+
17
+ * **Nothing is written unless everything validates.** :func:`place` renders, inserts and
18
+ re-reads in memory, and the file is touched only after the result round-trips (L3). A
19
+ partial write to a governed file is the failure mode the tool exists to remove.
20
+ * **The pointer is derived, never asked for.** Under ``ref_scheme = "id"`` the anchor is
21
+ the task's own id (RK27), so `add` supplies it; passing a different one is refused
22
+ rather than honoured, because a pointer an author can choose is a pointer an author
23
+ can get wrong.
24
+ * **The block must already be declared.** A heading is the only thing that declares a
25
+ block (RK37), so `add` files a task under one and never creates one — a heading
26
+ invented by a write puts the task where nothing looks for it.
27
+
28
+ * **A success that fails the gate is not a success.** Under ``ref_scheme = "id"`` the
29
+ pointer above is derived on every line and `lint` requires it resolve, so `add` alone
30
+ left a tree the gate refused and said nothing about it (RK93). `--section` writes the
31
+ rationale in the *same* transaction — both files validated, then both saved — and
32
+ without it :attr:`Insertion.needs` names the anchor that resolves to nothing. The
33
+ obligation is stated by the command that created it, never discovered from the backstop.
34
+
35
+ What it deliberately does not do: write prose (L4 — it has no opinion on the sentence,
36
+ only its length and count, and `--section` carries the author's paragraph to
37
+ :mod:`roadkeep.sections` without composing a word of it), derive the dep markers (RK8
38
+ does that on every write, and until then a marker is passed through exactly as typed), or
39
+ fix a file that has drifted.
40
+
41
+ :func:`set_status` (RK7) lives here for the same reason `add` does — it is a write to the
42
+ roadmap — and adds exactly one rule: the marker has one home, so a sibling file carrying
43
+ one for the same id is refused instead of reconciled.
44
+ """
45
+
46
+ from __future__ import annotations
47
+
48
+ from collections.abc import Callable, Sequence
49
+ from dataclasses import dataclass, replace
50
+ from pathlib import Path
51
+
52
+ from roadkeep import claiming, sections
53
+ from roadkeep.backlog import Backlog, DepStatus, NotOpen, Whereabouts
54
+ from roadkeep.claiming import Followed
55
+ from roadkeep.config import DESIGN_ROLES, PROSE_ROLES, ROLES, Config
56
+ from roadkeep.kernel.document import (
57
+ Document,
58
+ Entry,
59
+ Heading,
60
+ RepeatedHeading,
61
+ UnknownBlock,
62
+ counted,
63
+ save_all,
64
+ blank,
65
+ read_deps,
66
+ read_requires,
67
+ )
68
+ from roadkeep.ids import CARRIERS, IdRef, Promise, carried, derivation, scan
69
+ from roadkeep.markers import derive, refresh
70
+ from roadkeep.ranking import VOLUNTEERED, nearest
71
+ from roadkeep.kernel.schema import SchemaError, Task, width as measured_width
72
+ from roadkeep.sections import Section
73
+
74
+ #: The rationale a line arrives with: the heading, and prose that is either the string itself
75
+ #: or a **reader** for it (RK381). A reader is called once, at the last moment it can be — see
76
+ #: :func:`_with_section` — so a caller whose paragraph comes off a pipe does not spend it on a
77
+ #: call the line's own fields were going to refuse.
78
+ Rationale = tuple[str, "str | Callable[[], str]"]
79
+
80
+
81
+ class IdInUse(ValueError):
82
+ """An id is the one decision that cannot be taken back once it is committed.
83
+
84
+ ``flag`` is which argument this caller's number arrived on (RK1212). Written for `add
85
+ --id`, where every word of it is right, and shared by RK4 with every door that moves a
86
+ task onto a number — so `renumber --to TT1` answered *omit `--id` and it is derived* at a
87
+ verb that declares no `--id`, and said so itself one call later. The advice underneath is
88
+ correct at all of them, which is what makes the wrong spelling worse than no remedy: it
89
+ reads as typeable, and costs a call to find out it is not.
90
+
91
+ An argument and not a lookup here, the shape :class:`~roadkeep.kernel.document.UnknownBlock`
92
+ already has for `--organise`: the raiser is the one thing that knows which door it is.
93
+ """
94
+
95
+ def __init__(self, task_id: str, where: str, lineno: int, *, flag: str = "--id") -> None:
96
+ self.task_id = task_id
97
+ self.where = where
98
+ self.lineno = lineno
99
+ self.flag = flag
100
+ super().__init__(
101
+ f"{task_id} already occurs at {where}:{lineno}: an id is never reused, "
102
+ f"not even one that was retired — omit {flag} and it is derived"
103
+ )
104
+
105
+
106
+ class StatusElsewhere(ValueError):
107
+ """A marker in a second file is a status two files can come to disagree about."""
108
+
109
+ def __init__(
110
+ self, task_id: str, role: str, where: str, lineno: int, marker: str
111
+ ) -> None:
112
+ self.task_id = task_id
113
+ self.role = role
114
+ super().__init__(
115
+ f"{task_id} already carries {marker} in the {role} at {where}:{lineno}: "
116
+ f"status lives in exactly one file, because two files that both express it "
117
+ f"will eventually express different ones and nothing says which is right"
118
+ )
119
+
120
+
121
+ class DuplicateId(ValueError):
122
+ """Two lines for one id are two statuses for one task, in one file."""
123
+
124
+ def __init__(self, task_id: str, where: str, linenos: Sequence[int]) -> None:
125
+ self.task_id = task_id
126
+ self.linenos = tuple(linenos)
127
+ lines = ", ".join(str(number) for number in self.linenos)
128
+ super().__init__(
129
+ f"{task_id} appears at {where}:{lines}: one line per task, and two lines "
130
+ f"carry two statuses — `lint` reports this, and it is fixed by hand"
131
+ )
132
+
133
+
134
+ class NoSuchDep(ValueError):
135
+ """A dep naming an id neither governed file carries (RK500).
136
+
137
+ The gate's `deps.unknown`, asked where the token is typed. Measured by RK498's register
138
+ as one of the five findings a write accepted, and the one that costs more than it reads:
139
+ the write already treats the token as an id, so the next derived number steps **over** it
140
+ (RK431) — an unresolvable dep is therefore not ignored, it spends an address.
141
+
142
+ Decidable from what the verb is already holding. `Backlog` is loaded to place the line
143
+ and to derive the annotation, and it is the same reader the gate asks; nothing here needs
144
+ git, a second file or a listing.
145
+
146
+ Only `UNKNOWN`, which is the resolver's own answer and not a guess about the token: work
147
+ outside this backlog and a paused dep both resolve to something else, and refusing either
148
+ would refuse a line that states a fact honestly (RK92).
149
+ """
150
+
151
+ def __init__(self, task_id: str, deps: Sequence[str], where: str) -> None:
152
+ self.task_id = task_id
153
+ self.deps = tuple(deps)
154
+ named = ", ".join(self.deps)
155
+ super().__init__(
156
+ f"{task_id} would wait on {named}, which {'are' if len(self.deps) > 1 else 'is'} "
157
+ f"in neither {where} nor the changelog: nothing can say whether it is done — "
158
+ f"state the dep it meant, or `gaps` reads where the id went"
159
+ )
160
+
161
+
162
+ class CyclicDep(ValueError):
163
+ """A dep that would leave the line waiting on itself (RK500).
164
+
165
+ The gate's `deps.cycle`, asked before the line exists. Two shapes reach it and the
166
+ refusal is one: a dep whose own blockers walk back to this task, and a `Block X` dep
167
+ naming the block the line is being **filed into** — the block cannot empty until this
168
+ line ships, so the line waits on itself.
169
+
170
+ The second needs saying explicitly, because it is the one the graph cannot see: the line
171
+ is not in the backlog yet, so expanding `Block X` yields the members it has *now* and
172
+ this task is not among them. It becomes a member the moment the write lands, which is
173
+ what makes the answer decidable and not a prediction.
174
+ """
175
+
176
+ def __init__(self, task_id: str, dep: str, *, joins: bool = False) -> None:
177
+ self.task_id = task_id
178
+ self.dep = dep
179
+ super().__init__(
180
+ f"{task_id} would wait on {dep}, "
181
+ + (
182
+ f"which is the block this line is filed under: the block cannot empty "
183
+ f"until this line ships, so no amount of shipping anything else makes it "
184
+ f"ready"
185
+ if joins
186
+ else f"whose own blockers walk back to {task_id}, so nothing in the group "
187
+ f"can be started"
188
+ )
189
+ )
190
+
191
+
192
+ class DerivedPointer(ValueError):
193
+ """Under the id scheme there is no anchor to choose (RK27)."""
194
+
195
+ def __init__(self, task_id: str, given: str) -> None:
196
+ super().__init__(
197
+ f"the pointer is derived from the id (§{task_id}), so --ref {given!r} "
198
+ f"names a section chosen by hand: drop it, or set ref_scheme = \"outline\""
199
+ )
200
+
201
+
202
+ class NoAnchor(ValueError):
203
+ """A rationale asked for on a line that carries no pointer to reach it by (RK93)."""
204
+
205
+ def __init__(self, task_id: str) -> None:
206
+ self.task_id = task_id
207
+ super().__init__(
208
+ f"{task_id} carries no pointer, so a section written now is one nothing "
209
+ f"names: pass --ref to give the line an anchor, or write the prose after"
210
+ )
211
+
212
+
213
+ class NoProseFile(ValueError):
214
+ """A rationale asked for by a project that declares nowhere to put one (RK93).
215
+
216
+ Every prose role and not one of them (RK230): naming `improvements` was the refusal a
217
+ project declaring `strategy` alone got for a section its own file would have held, and
218
+ "declare it under [files]" then asked for the second prose file it had no use for.
219
+
220
+ The two a **design** may live in, which stopped being every prose role at RK1361: a
221
+ decision's body is prose in a governed file and is not somewhere a task's design could
222
+ go, so naming it here would offer a `declare` that does not close this refusal.
223
+ """
224
+
225
+ def __init__(self, task_id: str, role: str = "") -> None:
226
+ self.task_id = task_id
227
+ named = repr(role) if role else " or ".join(repr(r) for r in DESIGN_ROLES)
228
+ super().__init__(
229
+ f"this project declares no {named} file, so {task_id} has nowhere to "
230
+ f"carry a section: declare one under [files], or drop --section"
231
+ )
232
+
233
+
234
+ @dataclass(frozen=True, slots=True)
235
+ class Insertion:
236
+ """The line that was written, and the document that now holds it.
237
+
238
+ Plus, for the door that takes prose (RK93), the rationale written in the same
239
+ transaction — or, when it did not, the anchor the line points at that nothing
240
+ answers yet, which is what makes the follow-up the write's own report instead of
241
+ the gate's.
242
+ """
243
+
244
+ document: Document
245
+ entry: Entry
246
+ #: The prose file as this write leaves it, and the section it gained. Both None
247
+ #: unless `--section` was passed: `place` inserts one line into one file.
248
+ prose: Document | None = None
249
+ section: Section | None = None
250
+ #: The anchor this line points at that no declared prose file answers. Set only
251
+ #: when no section was written, because then there is nothing left to report.
252
+ needs: str | None = None
253
+ #: Which role that follow-up would write into (RK197). A project declaring several has
254
+ #: more than one place a section could go, so the command offered names the one it means
255
+ #: — otherwise the author is handed `section add`'s default and a file that refuses it.
256
+ needs_role: str | None = None
257
+ #: The family that follow-up's anchor extends, where that role declares none yet (RK1205).
258
+ #: One address up and the same verb, because `section add I.1` on a file with no §I is
259
+ #: `UnknownParent` — so without this the command handed over is one that cannot run, which
260
+ #: is RK197's own claim about a *file* nobody created, made one level down.
261
+ opens: str | None = None
262
+ #: The family this write **declared**, where the design it wrote is a block's first
263
+ #: (RK1258). Distinct from :attr:`opens`, which is a call still owed: this one already ran,
264
+ #: inside the same transaction, and what it left is a heading with no prose under it. Said
265
+ #: out loud because the write touched a second address the caller did not name, and because
266
+ #: the words it took are the block's — which is the one thing an author may want to correct.
267
+ opened: str | None = None
268
+ #: The id a sentence promised that deriving this one stepped over (RK431). Set only
269
+ #: where the id was *derived* — a caller that named its own spent nothing — and only
270
+ #: where the number below it is a mention no line ever took.
271
+ promise: Promise | None = None
272
+ #: The outline section this line's pointer just bound itself into (RK452), where the
273
+ #: design was written before the line. Distinct from :attr:`section`, which is a section
274
+ #: this write *created*: nothing was gained here, an existing heading stopped belonging
275
+ #: to nobody, and a caller reporting one as the other would say a paragraph was written
276
+ #: that was not. Always None under `ref_scheme = "id"`, where the anchor is the id.
277
+ bound: Section | None = None
278
+ #: Every path :meth:`save` wrote, projections included (RK1129) — set by :func:`add` off
279
+ #: the save's own return, and empty on an insertion nothing has written yet. This is the
280
+ #: list a `git add --` takes, which is the one thing the report could not say.
281
+ wrote: tuple[Path, ...] = ()
282
+ #: The delivered entries of this block that share a word with the symptom just filed,
283
+ #: nearest first (RK1370). `delivered --near` is the read the skill puts before every
284
+ #: proposal and it has to be *remembered*: this session filed a task whose remedy the code
285
+ #: already had, and the ranking that would have named it was one call away inside this same
286
+ #: transaction. Volunteered here because this is the moment nothing is spent but an id —
287
+ #: `restate` and `retire` are one call away, and the design is not written yet.
288
+ #:
289
+ #: An order and never a verdict (RK441), and the same rows `delivered --near` prints:
290
+ #: filtering the far ones out would be that impossible gate rebuilt as a silence, which
291
+ #: :data:`~roadkeep.ranking.VOLUNTEERED` carries the measurement for.
292
+ near: tuple[Entry, ...] = ()
293
+ #: What that block holds, beside what the rows above show (RK1374). `Delivered.recorded`'s
294
+ #: twin, and there for that field's reason: the listing is bounded at
295
+ #: :data:`~roadkeep.ranking.VOLUNTEERED`, and a bounded answer that does not say so inherits
296
+ #: the guarantee the unbounded one gave — a reader handed three rows reads a three-entry
297
+ #: block. Zero where nothing was ranked, which is the same answer as the empty tuple above.
298
+ near_recorded: int = 0
299
+
300
+ @property
301
+ def rendered(self) -> str:
302
+ return self.entry.raw
303
+
304
+ @property
305
+ def lineno(self) -> int:
306
+ return self.entry.lineno
307
+
308
+ def save(self) -> tuple[Path, ...]:
309
+ """Write the files, and answer which paths that touched.
310
+
311
+ The return is :func:`~roadkeep.kernel.document.save_all`'s own, projections included
312
+ (RK1129): a write that refreshes a derived block owes the caller the fact, because the
313
+ caller is composing a commit and the block is what a clean checkout calls stale. It was
314
+ discarded here, so the report had nothing to name.
315
+ """
316
+ return save_all(self.document, self.prose)
317
+
318
+ def follow_up(self) -> str | None:
319
+ """The `section add` that closes a pointer this write just created (RK93, RK197).
320
+
321
+ `--role` only where it is not the default, which keeps the sentence every project sees
322
+ the one it already saw — and makes the exception the case that needs it: a project whose
323
+ only prose file is the strategy one would otherwise be handed `section add`'s default and
324
+ a role it does not declare, which is a follow-up that cannot run.
325
+
326
+ On the record since RK1170, with the two registers that print it: the anchor and the
327
+ role are both fields here, and a helper in the door was the *third* place that pair had
328
+ to be read together.
329
+ """
330
+ if self.needs is None:
331
+ return None
332
+ return f"section add {self.needs} --title …{self._named()}"
333
+
334
+ def _named(self) -> str:
335
+ return "" if self.needs_role in (None, "improvements") else f" --role {self.needs_role}"
336
+
337
+ def follow_ups(self) -> tuple[str, ...]:
338
+ """Every call between this write and a pointer that resolves, in order (RK1205).
339
+
340
+ One normally, and that one is :meth:`follow_up`. Two where the anchor extends a family
341
+ no prose file declares yet: `section add` refuses that child with `UnknownParent`, so
342
+ the single command this used to hand over was one the author would run and be refused
343
+ by — worse than silence, because a printed call is read as a call that works.
344
+
345
+ The parent's own title is not composed here and never could be (L4): what is derived
346
+ is that a call is needed and what its address is, which is everything except the words.
347
+ """
348
+ if self.needs is None:
349
+ return ()
350
+ opening = (
351
+ () if self.opens is None
352
+ else (f"section add {self.opens} --title …{self._named()}",)
353
+ )
354
+ return (*opening, f"section add {self.needs} --title …{self._named()}")
355
+
356
+ def event(self, config: Config) -> dict[str, object]:
357
+ """What this write did to the block it landed in (RK38), off the file it wrote."""
358
+ from roadkeep.rendering import _event # noqa: PLC0415 - RK260
359
+
360
+ return _event(self.entry.task.id, self.entry.task.block, self.document, config)
361
+
362
+ def added(self, config: Config, capture: str | None, stamped: bool) -> str:
363
+ """`add`'s own answer, as a reader is told it (RK93, RK431, RK452).
364
+
365
+ **Named for the verb and not `stated`** (RK1170), which is the same choice
366
+ :class:`~roadkeep.shipping.Departure` makes for its second door: this record is
367
+ *embedded* by three other transactions — a pause's store line, a departure's ledger
368
+ line, a record's — and a method called `stated` on it would answer about an `add` from
369
+ inside each of them. There is no default door here to take the plain name.
370
+
371
+ `capture` and `stamped` are parameters for the reason `wrote` is elsewhere: the stamp
372
+ happens after the save and outside this transaction (RK1141), so they are facts about
373
+ the call and a record holding them would be claiming a write it did not make.
374
+ """
375
+ from roadkeep.rendering import ( # noqa: PLC0415 - RK260
376
+ _event_rows,
377
+ _prose_file,
378
+ _staging_rows,
379
+ )
380
+ from roadkeep.provenance import invocation # noqa: PLC0415 - RK260
381
+
382
+ # The file the write actually chose (RK230), read off the document `_with_section` left
383
+ # rather than composed from the improvements default: a report that names the role and a
384
+ # write that derives it are two answers, and one of them is wrong on every project that
385
+ # declares `strategy` alone.
386
+ prose = _prose_file(config, self.prose)
387
+ rows = [self.rendered]
388
+ if self.opened is not None:
389
+ # Above the design and not below it, because that is the order the file now reads
390
+ # in — and with the correction named, the title being the block's rather than one
391
+ # this write composed (RK1258).
392
+ rows.append(
393
+ f" opened §{self.opened} → {prose}, titled from Block "
394
+ f"{self.entry.task.block} (`section amend {self.opened} --title` renames it)"
395
+ )
396
+ if self.section is not None:
397
+ rows.append(
398
+ f" design §{self.section.anchor} → {prose}:{self.section.first} "
399
+ f"{self.section.words} words"
400
+ )
401
+ elif self.needs is not None:
402
+ # Backticked and carrying the invocation, like every other route this tool composes
403
+ # (RK476): the bare argv is the *field*, and a line printed for a reader is the form
404
+ # `serving._rerouted` already spells as a tool where there is no shell.
405
+ # Every call and not the last one (RK1205): where the anchor extends a family this
406
+ # file has not opened, the closing command refuses until the opening one has run,
407
+ # and naming one of the two is the staircase RK1198 took out of the door above.
408
+ rows += [
409
+ f" needs `{invocation()} {one}` "
410
+ f"(the pointer above resolves to nothing until then)"
411
+ if one == self.follow_ups()[-1]
412
+ else f" needs `{invocation()} {one}` "
413
+ f"(§{self.needs} extends it, and no prose file declares it yet)"
414
+ for one in self.follow_ups()
415
+ ]
416
+ # And the call that would not have needed any of them (RK1218). `add --section`
417
+ # has written both halves in one transaction since RK93, and this row — printed on
418
+ # every `add` that omits it — named only the *follow-up*, so what the tool taught,
419
+ # once per task, was the two-command path. Measured across fourteen sessions
420
+ # driving another project's backlog: every task filed in two commands, with the
421
+ # roadmap between them in the state this project's own gate calls `ref.unresolved`.
422
+ #
423
+ # Under the row rather than instead of it: this call is already made and its
424
+ # pointer already dangles, so the follow-up is what closes *this* one and this is
425
+ # what closes the next. A line that replaced the remedy with advice would be the
426
+ # tool answering a question the caller has not asked yet.
427
+ # A **flag** and never a composed command, which is the one care this row needs.
428
+ # `add` has already run here, so an argv printed with the invocation on it would
429
+ # read as a call to make — and making it files a second task. RK1209's sweep finds
430
+ # a command by exactly that prefix, so the shape is also what keeps this row out
431
+ # of it: what is offered is the argument to add next time, not a call to run now.
432
+ rows.append(
433
+ ' or pass `--section "<its title>"` to `add` next time: both halves in '
434
+ "one transaction, under the same limits"
435
+ )
436
+ # And **what that body may weigh**, at the moment the caller is about to write it
437
+ # (RK1309). The row above names the command and the limit it enforces reached the
438
+ # author only as a refusal: measured in pportal, 2026-08-22, a body written to a
439
+ # file and passed with `--section-body-file` came back 266 words against 250 — a
440
+ # good refusal, arriving after the paragraph, with the retry paying for every word
441
+ # of it again. The figure is a fact about the role and needs no id, so this is the
442
+ # one place it costs nothing to state: the id was just minted and the prose has
443
+ # not been composed, which is the whole of L1 said about one field.
444
+ rows.append(f" weighs {_body_aim(config, self.needs, self.prose)}")
445
+ elif self.bound is not None:
446
+ # Said, because the write touched a second file the caller did not name (RK452) —
447
+ # and because the heading now carries an id, which is the fact `ship` and the gate
448
+ # both read as "this design belongs to that task".
449
+ rows.append(
450
+ f" bound §{self.bound.anchor} → {prose}:{self.bound.first} "
451
+ f"the design was written first, so this line's id is now in its heading"
452
+ )
453
+ if self.promise is not None:
454
+ # Beside the line and not instead of it: the `add` succeeded, and what this reports
455
+ # is a sentence somewhere else that has just stopped being true (RK431).
456
+ rows.append(f" promise {self.promise.sentence}")
457
+ if self.near:
458
+ # The read the skill puts before a proposal, handed back at the one moment nothing
459
+ # is spent but an id (RK1370). Labelled once and the rows under it, which is how
460
+ # every wrapped answer here is read — and the sentence says what the order is not,
461
+ # because a reader taking #1 for a verdict is RK441's own finding.
462
+ # The count of what is shown against the count of what is there, and the command
463
+ # that shows the rest (RK442, RK1374) — in `delivered --near`'s own two phrases,
464
+ # because this is that read volunteered and a second wording for one fact is what
465
+ # RK1375 is about. The block's own listing and never a `--near` rendered with the
466
+ # symptom in it, which is the second grammar RK313 declined.
467
+ rows.append(
468
+ f" near {len(self.near)} nearest of {self.near_recorded} delivered under "
469
+ f"this block — an order and not a verdict; `{invocation()} delivered "
470
+ f"{self.entry.task.block}` is all {self.near_recorded}"
471
+ )
472
+ rows += [
473
+ f" {one.task.status} {one.task.id:<8} {one.task.symptom}"
474
+ for one in self.near
475
+ ]
476
+ if capture:
477
+ # Said either way: a stamp that did not land is the row `stats` will still count,
478
+ # and silence about it is how a second step comes to be forgotten (RK86).
479
+ rows.append(
480
+ f" capture {capture} now names {self.entry.task.id}"
481
+ if stamped
482
+ else f" capture {capture} could not be stamped: the line is filed, the "
483
+ f"link is not"
484
+ )
485
+ # The projection this write refreshed is in here (RK1129): the roadmap and the rationale
486
+ # are files the caller named, and the README is one they did not — so a commit took the
487
+ # two and left the third, green against the tree and `export.stale` in a clean checkout.
488
+ rows += _staging_rows(config.relative(one) for one in self.wrote)
489
+ rows += _event_rows(self.event(config), " ")
490
+ return "\n".join(rows)
491
+
492
+ def addition(
493
+ self, config: Config, capture: str | None, stamped: bool
494
+ ) -> dict[str, object]:
495
+ """The same answer as data, with both derived addresses (RK249)."""
496
+ from roadkeep.rendering import ( # noqa: PLC0415 - RK260
497
+ _promise_json,
498
+ _prose_file,
499
+ )
500
+
501
+ prose = _prose_file(config, self.prose)
502
+ return {
503
+ "id": self.entry.task.id,
504
+ # The other derived address (RK249). Reported for the reason `id` is: under
505
+ # `ref_scheme = "outline"` the write derives it, and the only other readings were
506
+ # the tail of `rendered` and the anchor inside the `needs` sentence — which is null
507
+ # exactly when `--section` wrote the rationale here, the composition RK93 recommends.
508
+ "ref": self.entry.task.ref,
509
+ "file": config.relative(config.path("roadmap")),
510
+ "line": self.lineno,
511
+ "rendered": self.rendered,
512
+ "length": measured_width(self.rendered),
513
+ "section": None if self.section is None else self.section.payload(prose),
514
+ # The family this write declared on the way in (RK1258): null on every add that
515
+ # extended one already there, so a client tells a heading it now owns from one it
516
+ # merely wrote under. An address and not a section — what is there is a heading.
517
+ "opened": self.opened,
518
+ # Not a section this write *created* (RK452): an existing outline heading stopped
519
+ # belonging to nobody, and a caller reading one key for both would report a
520
+ # paragraph that was never written.
521
+ "bound": None if self.bound is None else self.bound.payload(prose),
522
+ # The follow-up as data: null when the pointer already resolves, so a caller acts
523
+ # on a field instead of matching a sentence (RK93). The **first** call and not the
524
+ # closing one (RK1205) — which is the same value on every project not meeting that
525
+ # defect, and a call that runs on the one that is: this key has always meant *what
526
+ # to do next*, and where a family is missing the closing command is not it.
527
+ "needs": None if self.needs is None else self.follow_ups()[0],
528
+ # And the whole sequence, because the first alone is the staircase again: empty
529
+ # where the pointer resolves, one call normally, two where a family has to be
530
+ # opened before the design can extend it.
531
+ "needs_path": list(self.follow_ups()),
532
+ # And what the body that follow-up writes may weigh (RK1309), beside the call that
533
+ # writes it: the limit reached the author only as a refusal, and this is the one
534
+ # moment it costs nothing to state — the id is minted and the prose is not composed.
535
+ # `null` where the pointer already resolves, there being no body still to write.
536
+ "weighs": None
537
+ if self.needs is None
538
+ else _body_weight(config, self.needs, self.prose),
539
+ # Null on almost every add, and the whole point when it is not (RK431): the id
540
+ # below the one just written was a sentence, not a line.
541
+ "promise": _promise_json(self.promise),
542
+ # The delivered entries this symptom shares a word with (RK1370), as the rows show
543
+ # them. `[]` and never omitted, for `undone_by`'s reason one file over: a consumer
544
+ # reading a missing key cannot tell "nothing is near" from "this build is older",
545
+ # and deciding a duplicate is the whole use of it. No score, the ordering being the
546
+ # answer and a figure beside it one turn from the threshold RK441 rules out.
547
+ "near": [
548
+ {
549
+ "id": one.task.id,
550
+ "marker": one.task.status,
551
+ "symptom": one.task.symptom,
552
+ "line": one.lineno,
553
+ "rank": at,
554
+ }
555
+ for at, one in enumerate(self.near, start=1)
556
+ ],
557
+ # What the block holds against what the list shows (RK1374), which is the key
558
+ # `delivered` calls `recorded`: a consumer handed three rows and no total reads a
559
+ # three-entry block, and the whole use of this list is deciding a duplicate.
560
+ "near_recorded": self.near_recorded,
561
+ # Every path this write touched, projections included (RK1129) — the same key a
562
+ # departure's scope carries, so a client staging one stages the other.
563
+ "wrote": [config.relative(one) for one in self.wrote],
564
+ # Which capture this line files, where one was named (RK1141) — null where none
565
+ # was, and false where the stamp could not be written, so a client tells "not
566
+ # asked" from "asked and did not land".
567
+ "capture": None if not capture else {"path": capture, "stamped": stamped},
568
+ "event": self.event(config),
569
+ }
570
+
571
+
572
+ def compose(
573
+ config: Config,
574
+ *,
575
+ task_id: str,
576
+ block: str,
577
+ symptom: str,
578
+ why: str,
579
+ status: str | None = None,
580
+ deps: Sequence[str] = (),
581
+ requires: Sequence[str] = (),
582
+ ref: str | None = None,
583
+ ) -> Task:
584
+ """The fields, as a :class:`Task`. Fills in what is derivable; validates nothing.
585
+
586
+ Validation stays in :func:`place` so that every violation is reported at once — a
587
+ constructor that raises can only ever name the first thing wrong with a line.
588
+ """
589
+ schema = config.schema
590
+ if schema.ref_scheme == "id":
591
+ if ref is not None and ref != task_id:
592
+ raise DerivedPointer(task_id, ref)
593
+ ref = task_id
594
+ return Task(
595
+ id=task_id,
596
+ # The default is the first marker this project declares, not a hardcoded 📋:
597
+ # the marker set is configuration (L6), so the default has to come from it.
598
+ status=status or schema.markers[0],
599
+ block=block,
600
+ symptom=symptom,
601
+ why=why,
602
+ deps=read_deps(", ".join(deps), schema) if deps else (),
603
+ # Through the file's own reader for `deps`' reason (RK1297): what an author types
604
+ # and what the parser reads back out of the line are split by one function, so a
605
+ # group the writer and the reader disagree about is not a state this can reach.
606
+ requires=read_requires(", ".join(requires)) if requires else (),
607
+ ref=ref,
608
+ )
609
+
610
+
611
+ def place(
612
+ document: Document,
613
+ task: Task,
614
+ *,
615
+ carrying: Sequence[str] = (),
616
+ where: str = "",
617
+ config: Config | None = None,
618
+ role: str = "",
619
+ ) -> Insertion:
620
+ """Validate, render, insert — in memory, and refuse before any of it.
621
+
622
+ Raises :class:`~roadkeep.kernel.schema.SchemaError` with every violation,
623
+ :class:`UnknownBlock` when no heading declares the block,
624
+ :class:`~roadkeep.kernel.document.RepeatedHeading` when two do (RK391), and
625
+ :class:`~roadkeep.kernel.document.RoundTripError` when either the file already carries a
626
+ line the schema would rewrite or the new line does not read back as it was written.
627
+
628
+ ``carrying`` is the lines an entry owns **beyond** the one the schema renders (RK157),
629
+ and only a *move* passes it: re-placing a wrapped ledger entry under another heading has
630
+ to carry its continuation with it, since the schema renders one line and the rest is
631
+ prose no task holds. A newly composed line carries nothing, which is every other caller.
632
+
633
+ ``role`` is **which governed file this is**, and it is the one argument to reach for
634
+ (RK412). The refusal needs that file twice over — as a path, so it can be named, and as
635
+ a role, so it can name `block add --organise <role>` where the file declares no heading
636
+ at all (RK405) — and until this those were two arguments, the second spelled out at five
637
+ call sites and derivable from the first at none of them. Nothing held them level: a door
638
+ passing the path and forgetting the role printed the bare `block add`, which on the file
639
+ the sentence is about is one more refusal, and no test and no gate can see the difference
640
+ because it is a sentence. `defer` was in exactly that state. One argument, derived
641
+ together, and the one that can be forgotten stops existing.
642
+
643
+ ``where`` is the same file as a path, for the caller that has no role to give: `merge`
644
+ re-places entries into a document it composed itself, and a role would be a claim about a
645
+ file on disk it is not writing. Rendered by the caller in the way `sections` already
646
+ renders its own (RK181, RK257), because this function takes a :class:`Document` and
647
+ `config.relative` is out of its reach. Passing both is refused, being two answers to one
648
+ question — and `role` without a :class:`~roadkeep.config.Config` is refused for the same
649
+ reason it is not a guess: there is nothing to resolve it against.
650
+
651
+ ``config`` is what turns the refusal `ref.missing` into an address (RK349). RK312 wired
652
+ that enrichment around `add`'s own call and left `defer` and `resume` — which reach this
653
+ same `check` through their own doors — printing the bare rule, and an asymmetry is worse
654
+ than the original gap: a caller who has met the good refusal once reads the bare one as
655
+ *there is no answer here*. So it is made here, at the seam every line write passes,
656
+ rather than at four call sites that would drift apart again. Omitted, the refusal is the
657
+ schema's own, which is what a caller with no project to read anchors out of gets.
658
+ """
659
+ if role:
660
+ if where:
661
+ raise ValueError(
662
+ "place takes the role or the path it resolves to, not both: they are two "
663
+ "answers to one question and the role is the one that derives the other"
664
+ )
665
+ if config is None:
666
+ raise ValueError(f"place(role={role!r}) needs a config to resolve it against")
667
+ where = config.relative(config.path(role))
668
+ # Computed before `check` and raised after it (RK1256), which is the seam this closes.
669
+ # `UnknownBlock` and `SchemaError` are two whole halves — each names every problem of its
670
+ # own class — and a call wrong in both was refused twice, learning one class per round
671
+ # trip. The block is answerable here regardless of the prose: it is a heading in a
672
+ # document already read, so nothing about it waits on the fields being legal.
673
+ declared = document.declaring(task.block)
674
+ unopened = (
675
+ UnknownBlock(
676
+ task.block,
677
+ sorted({h.label for h in document.headings if h.label}),
678
+ where,
679
+ word=document.schema.heading_word,
680
+ # Which file the remedy has to start organising, where it declares no block at
681
+ # all (RK405) — the same fact `where` is, which is why it is derived and not
682
+ # asked for (RK412). Empty only for the caller that gave a path alone.
683
+ organise=role,
684
+ )
685
+ if not declared
686
+ else None
687
+ )
688
+ try:
689
+ document.schema.check(task)
690
+ except SchemaError as error:
691
+ # Around `check` rather than before it, so a line that is missing a pointer *and*
692
+ # over on its `why` still hears both (RK312): the schema reports every violation at
693
+ # once, and an early refusal here would trade that for the one sentence it improves.
694
+ refusal = (
695
+ error
696
+ if config is None
697
+ else sections.naming_the_anchor(config, task.block, error)
698
+ )
699
+ if unopened is not None:
700
+ # The other half, carried rather than merged: `UnknownBlock` renders a remedy
701
+ # a bare violation line would lose, and folding it into `violations` would make
702
+ # a rule of this schema out of a fact about a heading.
703
+ refusal.beside = str(unopened)
704
+ raise refusal from None
705
+ if unopened is not None:
706
+ raise unopened
707
+ if len(declared) > 1:
708
+ # The ambiguity is not resolved by position (RK391) — see `RepeatedHeading`. Here
709
+ # rather than at `add`, because this is the seam every line write passes and `ship`,
710
+ # `record add` and `move` reach a repeated heading through their own doors.
711
+ raise RepeatedHeading(
712
+ task.block,
713
+ [h.lineno for h in declared],
714
+ where,
715
+ word=document.schema.heading_word,
716
+ )
717
+ heading = declared[0]
718
+
719
+ rendered = document.schema.render(task)
720
+ index, payload = _placement(document, heading, rendered, tuple(carrying))
721
+ updated = document
722
+ for offset, raw in enumerate(payload):
723
+ updated = updated.insert_line(index + offset, raw)
724
+ # The new line is canonical by construction — and the guard is the point: a line
725
+ # this tool wrote and cannot read back is exactly what must never reach the disk.
726
+ updated.ensure_writable()
727
+
728
+ lineno = index + payload.index(rendered) + 1
729
+ entry = next(e for e in updated.entries if e.lineno == lineno)
730
+ return Insertion(document=updated, entry=entry)
731
+
732
+
733
+ def remove_entry(document: Document, entry: Entry) -> Document:
734
+ """Take the entry out, and the blank line the removal doubled. The inverse of `place`.
735
+
736
+ A task line sits between blanks when it is the last one in its block, so removing it
737
+ leaves a paragraph break the file never had. Both spellings round-trip, which is
738
+ exactly why nothing downstream would catch it.
739
+
740
+ The **whole** entry, which is the same fact `place` needed (RK157): a wrapped ledger
741
+ entry's continuation lines are the removal's to take, and leaving them behind would file
742
+ somebody's paragraph under whatever bullet the deletion left above them. Takes the entry
743
+ rather than its index for exactly that reason — an index is the half of the answer that
744
+ was wrong.
745
+
746
+ Here rather than in one caller because a line now leaves the roadmap by four doors —
747
+ three of them departures (RK6, RK32) and one of them reversible (RK91) — and a second
748
+ copy of this rule is a second opinion about the shape of the file it leaves behind.
749
+ """
750
+ index = entry.index
751
+ updated = document.remove_lines(index, entry.stop)
752
+ lines = updated.lines
753
+ if index > 0 and index < len(lines) and blank(lines[index - 1]) and blank(lines[index]):
754
+ return updated.remove_line(index)
755
+ if index >= len(lines) and index > 0 and blank(lines[index - 1]):
756
+ # The block was last in the file: its trailing blank has nothing left to separate.
757
+ return updated.remove_line(index - 1)
758
+ return updated
759
+
760
+
761
+ def refuse_deps(config: Config, backlog: Backlog, task: Task) -> None:
762
+ """Refuse the two deps a write can decide about the backlog in front of it (RK500).
763
+
764
+ L1 for the dep field: the gate reports `deps.unknown` and `deps.cycle` about a line that
765
+ is already in the file, and both are answerable from the :class:`~roadkeep.backlog.Backlog`
766
+ this verb loaded to place the line and derive its annotation.
767
+
768
+ **What stays the gate's, and why the boundary is not arbitrary.** `deps.retired` and
769
+ `deps.stale` become true when a *later* write moves the line the dep names — the write
770
+ that stated it was correct when it ran, so there was nothing to refuse. These two are
771
+ false the moment they are written.
772
+
773
+ The cycle walk uses :func:`~roadkeep.graph._hops` on the task **as it would be**, which
774
+ is why it is that function and not :meth:`Graph.of`: the line may not be in the backlog
775
+ yet, and asking the graph about an id it has never seen answers about nothing.
776
+ """
777
+ # Deferred: `graph` reads a backlog and this module writes one, so the edge runs one way
778
+ # at import and the other at call time (RK260).
779
+ from roadkeep.graph import Graph, _hops # noqa: PLC0415 - RK500
780
+
781
+ where = config.relative(config.path("roadmap"))
782
+ unknown = [
783
+ resolution.dep.id
784
+ for resolution in backlog.resolve(task)
785
+ # A line naming **itself** is the schema's `deps.self`, decided from the field alone
786
+ # and with a message of its own. Answering it here first would report a dep in
787
+ # neither file, which is true and is the less useful of the two things to say.
788
+ if resolution.status is DepStatus.UNKNOWN and resolution.dep.id != task.id
789
+ ]
790
+ if unknown:
791
+ raise NoSuchDep(task.id, unknown, where)
792
+ schema = backlog.config.schema
793
+ for dep in task.deps:
794
+ # The block this line is filed under, which the expansion below cannot know about.
795
+ if schema.classify_dep(dep).collective and dep.id == f"Block {task.block}":
796
+ raise CyclicDep(task.id, dep.id, joins=True)
797
+ graph = Graph.of(backlog)
798
+ for hop in _hops(backlog, task):
799
+ if not hop.walkable:
800
+ continue
801
+ if hop.target == task.id or task.id in graph.reach(hop.target):
802
+ raise CyclicDep(task.id, hop.via)
803
+
804
+
805
+ def add(
806
+ config: Config,
807
+ *,
808
+ block: str,
809
+ symptom: str,
810
+ why: str,
811
+ status: str | None = None,
812
+ deps: Sequence[str] = (),
813
+ requires: Sequence[str] = (),
814
+ ref: str | None = None,
815
+ task_id: str | None = None,
816
+ family: str | None = None,
817
+ section: Rationale | None = None,
818
+ ) -> Insertion:
819
+ """Insert one task into the roadmap and save it. The whole write path.
820
+
821
+ The id is derived unless one is given, and a given id that occurs anywhere is
822
+ refused (:class:`IdInUse`) — including in prose, because a number a document
823
+ already mentions is a number two designs would share in the history.
824
+
825
+ ``family`` picks which track the derived id counts in (RK74) and defaults to the first
826
+ the project declares, which is the only answer for the projects that declare one. It
827
+ is never inferred from the block: a track is not a block, and a tool that mapped one
828
+ to the other would be holding an opinion about someone else's backlog.
829
+
830
+ ``requires`` is what has to be *present* for the work to be finishable (RK1297) — never
831
+ derived and never inferred, because nothing in either file can see the room the caller
832
+ is in. Every token is refused here unless `[requirements] declared` names it (L1), so a
833
+ requirement `pick` could never match is not a line this door writes.
834
+
835
+ The dep annotations are derived here too (RK8), so `--dep RK1` renders `RK1 ✅` when
836
+ RK1 has shipped and the author never types a marker. Only this line is derived: no
837
+ existing line can name an id that did not exist a moment ago.
838
+
839
+ **Both headings, not one** (RK380): the roadmap's is `place`'s refusal, and
840
+ :func:`declaring` asks the same question of the ledger — the one the first `ship` in this
841
+ block would otherwise ask at the end of the task instead of the start.
842
+
843
+ ``section`` is the rationale as ``(title, body)``, and the reason this door takes
844
+ prose at all (RK93). Under ``ref_scheme = "id"`` every line renders a pointer `lint`
845
+ requires to resolve, so an `add` on its own could not leave a gate-clean tree and the
846
+ author learned the follow-up from the backstop — the inversion L1 exists to prevent.
847
+ Given, both files are validated and then both are written, so the line and the design
848
+ it points at arrive together or neither does. Omitted, nothing is invented (L4):
849
+ :attr:`Insertion.needs` carries the anchor that resolves to nothing, so the command
850
+ that created the obligation is the one that states it.
851
+
852
+ Its body may be a **reader** rather than a string, and the ordering below is the whole
853
+ reason (RK381). Every refusal the *line* can raise — a spent id, a `why` three words
854
+ over, an undeclared block, a rendered line past its limit — happens above
855
+ :func:`_with_section`, and the docstring at the top of this module says why that is
856
+ right. What it stopped short of is that a caller reading the paragraph off a pipe has
857
+ already spent it by the time the refusal arrives, and a pipe does not rewind: measured
858
+ against Turing, a `--why` 15 characters over cost a 184-word body a second time, to
859
+ correct three words in a different argument. So the prose is not fetched until the line
860
+ it belongs to has passed.
861
+ """
862
+ promise: Promise | None = None
863
+ if task_id is None:
864
+ # Read before the write and not after it: this `add` is about to put the derived id
865
+ # into a file the scan reads, and from that moment the corpus no longer says which
866
+ # of the two numbers was a line and which was a sentence (RK431).
867
+ derived = derivation(config, family)
868
+ task_id, promise = derived.id, derived.promise
869
+ else:
870
+ refuse_reuse(config, task_id)
871
+ task = compose(
872
+ config,
873
+ task_id=task_id,
874
+ block=block,
875
+ symptom=symptom,
876
+ why=why,
877
+ status=status,
878
+ deps=deps,
879
+ requires=requires,
880
+ ref=ref,
881
+ )
882
+ # The pointer, against the same history `section add` reads (RK1177). One command earlier
883
+ # than it used to be: `add --ref XIV.29` was accepted and `section add XIV.29` then refused
884
+ # it, so the repair was an `amend --ref` against a line that should never have been written
885
+ # — and the `ref.unresolved` state in between is indistinguishable from the honest one every
886
+ # two-command task passes through, so a reader cannot tell *not written yet* from *can never
887
+ # be written*. The check already existed and already knew the answer; what it lacked was
888
+ # being asked here, which costs one lookup.
889
+ _refuse_retired(config, task)
890
+ # Both fields' breaches in one refusal, where the body is already in hand (RK426). A
891
+ # call whose `why` is fifteen characters over and whose body is fifty words over used to
892
+ # cost two full resubmissions, the second for a limit the first refusal had already
893
+ # measured — and re-passing the prose is exactly what `--section-body-file` exists to
894
+ # avoid, so the tool had conceded the cost and then charged it for a field it never read.
895
+ #
896
+ # **Only where the body is a string.** RK381's ordering is not relaxed: a body arriving
897
+ # off a *pipe* is spent by reading it, and a pipe does not rewind, so for that one shape
898
+ # the line still has to pass before the paragraph is fetched. A `str` costs nothing to
899
+ # look at twice, which is the whole distinction and the reason it is drawn on the type.
900
+ _refuse_together(config, task, section)
901
+ backlog = Backlog.load(config)
902
+ # Before `place`, which is where the line stops being a proposal: a dep nothing carries
903
+ # and one that closes a loop are both facts about this backlog, and both are false now
904
+ # rather than later (RK500).
905
+ refuse_deps(config, backlog, task)
906
+ insertion = replace(
907
+ place(
908
+ config.document("roadmap"),
909
+ derive(backlog, task),
910
+ role="roadmap",
911
+ config=config,
912
+ ),
913
+ promise=promise,
914
+ )
915
+ # After the roadmap's own refusal and before the prose is read (RK380, RK381): a label
916
+ # neither file declares is one mistake, and hearing it named against the file the line
917
+ # was going into is the half that tells a typo from a block only half opened.
918
+ declaring(config, block)
919
+ if section is not None:
920
+ insertion = _with_section(config, insertion, *section)
921
+ elif insertion.entry.task.ref and (
922
+ role := _unresolved(config, insertion.entry.task.ref)
923
+ ):
924
+ insertion = replace(
925
+ insertion,
926
+ needs=insertion.entry.task.ref,
927
+ needs_role=role,
928
+ opens=_unopened(config, role, insertion.entry.task.ref),
929
+ )
930
+ else:
931
+ insertion = _binding(config, insertion)
932
+ # The paths ride back on the record (RK1129), because the caller composing a commit is the
933
+ # one who needs them and `save` is the only reader that knows what a projection refreshed.
934
+ # And the neighbours beside them (RK1370), read after the write rather than before it: this
935
+ # is a *report* and not a gate — nothing here refuses a duplicate and nothing could (RK441)
936
+ # — so it costs the same ranking whichever side of `save` it runs, and running it here keeps
937
+ # every refusal above untouched by a read that cannot refuse anything.
938
+ shown, recorded = _near(config, insertion)
939
+ return replace(
940
+ insertion, wrote=insertion.save(), near=shown, near_recorded=recorded
941
+ )
942
+
943
+
944
+ def _near(config: Config, insertion: Insertion) -> tuple[tuple[Entry, ...], int]:
945
+ """This block's nearest delivered entries, and how many it holds (RK1370, RK1374).
946
+
947
+ The block's own ledger and never the whole of it, which is `delivered`'s rule: a duplicate
948
+ collides with a claim filed under the same heading, and ranking across blocks would offer a
949
+ caller entries from a part of the plan they did not propose into.
950
+
951
+ **Symptoms and not outcomes**, for that verb's reason: a shipped line states a problem and
952
+ a fix, and a proposal collides with the problem — an outcome is written in the vocabulary of
953
+ the solution and never matches.
954
+
955
+ Empty where the project has no ledger to read and where the block has delivered nothing,
956
+ which are the two states with nothing to rank — and never empty because the nearest looked
957
+ far, that being the judgement :data:`~roadkeep.ranking.VOLUNTEERED` records the measurement
958
+ against.
959
+
960
+ **Declared is not on disk**, which is `declaring`'s own distinction one function up: a
961
+ project may name a changelog it has not created, and the first `add` is exactly when it has
962
+ not. A read that is a *report* may not be the thing that refuses such a write, so the
963
+ absence answers here rather than raising.
964
+
965
+ `is_file` and not `exists` (RK1373), which is the idiom `backlog.py` and this module's two
966
+ other readers already use: a role whose declared path names a **directory** passes `exists`
967
+ and then fails inside `Document.load`, on an error no refusal here owns — and this read runs
968
+ *after* `save`, so that error would fail a call whose files are already written. Every other
969
+ reader treats such a path as the absent file it effectively is.
970
+ """
971
+ if not config.has("changelog") or not config.path("changelog").is_file():
972
+ return (), 0
973
+ task = insertion.entry.task
974
+ entries = config.document("changelog").block(task.block)
975
+ if not entries:
976
+ return (), 0
977
+ # The block's own count beside the shown one (RK1374), off the same read: a second lookup
978
+ # for it is the two figures coming to disagree about which block was ranked.
979
+ return (
980
+ tuple(
981
+ entries[index]
982
+ for index in nearest(
983
+ task.symptom, [one.task.symptom for one in entries], VOLUNTEERED
984
+ )
985
+ ),
986
+ len(entries),
987
+ )
988
+
989
+
990
+ def _unopened(config: Config, role: str, anchor: str) -> str | None:
991
+ """The family this anchor extends that the prose file has not opened yet (RK1205).
992
+
993
+ ``None`` wherever the follow-up runs as it stands: an anchor whose parent is declared, a
994
+ top-level one under an outline — which :func:`~roadkeep.sections.place_for` places after
995
+ the last top level (RK166) — and the id scheme, where an anchor carries no place at all
996
+ and a `§RK9` extending nothing is a section for a task rather than a child of anything.
997
+
998
+ Asked here rather than left to `section add`, because this is the moment the command is
999
+ *composed*: the refusal one door over is correct and arrives one call too late, after the
1000
+ author has spent a retry on a call that was never available (RK1149).
1001
+
1002
+ The address alone, and never a title. What a family is called is editorial and L4's to
1003
+ leave alone — the same reason `block add` takes the title `add` will not compose.
1004
+ """
1005
+ document = config.document(role)
1006
+ if sections._top_level(document, anchor) or document.schema.ref_scheme == "id":
1007
+ return None
1008
+ if sections._extends(document, anchor) is not None:
1009
+ return None
1010
+ # The address one segment up, which is what `section add` will look for and not find. A
1011
+ # one-segment anchor under the id scheme left above; here it means the file is an outline
1012
+ # and the anchor is a child, so there is always a segment to drop.
1013
+ parent = anchor.rsplit(".", 1)[0]
1014
+ return None if parent == anchor else parent
1015
+
1016
+
1017
+ def _binding(config: Config, insertion: Insertion) -> Insertion:
1018
+ """Bind this line's id into the outline heading it just started naming (RK452).
1019
+
1020
+ Under an outline the id in the heading is the binding (RK262), and two writes made it:
1021
+ `section add` renders it when a live line already points at the anchor, and
1022
+ `add --section` because it holds the line. Neither runs when the **design is written
1023
+ first**. `section add I.1 --title "…"` on an anchor nothing points at yet composes a
1024
+ heading naming no task, and the `add --ref I.1` that follows creates the pointer and
1025
+ never returns to the heading — so which of two writes came first decided whether the
1026
+ section ever belonged to anybody.
1027
+
1028
+ The second order costs permanently and quietly: `ship` reports the section *kept*, as
1029
+ prose belonging to none, `lint` exits 0 on exactly that reading, and the rationale for
1030
+ shipped work stays in the prose file, which is what RK6 exists to stop. The recovery was
1031
+ a `section amend --title "<title> (<id>)"` derived from a field called `kept`, a round
1032
+ after the evidence had scrolled away.
1033
+
1034
+ So the pointer write does from the other end what `section add` does, in the same
1035
+ transaction. Not a heuristic about the prose (RK236): the anchor is claimed by exactly
1036
+ the line that would have bound it had it been written first, and the rendering is
1037
+ :func:`~roadkeep.sections.amend`'s, so one function still writes a heading.
1038
+
1039
+ Three states it leaves alone, and each is somebody else's answer. A heading that already
1040
+ names a task is :func:`~roadkeep.sections.owners`' `yes` and never overwritten. **Two
1041
+ live claimants is RK64's ambiguity and stays the author's**, as it does at `section add`
1042
+ — a binding chosen here would be this tool deciding whose design it is. And under
1043
+ `ref_scheme = "id"` there is no heading to bind, the anchor being the id already.
1044
+ """
1045
+ task = insertion.entry.task
1046
+ if config.schema.ref_scheme != "outline" or not task.ref:
1047
+ return insertion
1048
+ role = prose_role(config, on_disk=True)
1049
+ if role is None:
1050
+ return insertion
1051
+ document = config.document(role)
1052
+ section = sections.find(document, task.ref)
1053
+ if section is None or sections.owners(section, config.schema.id_pattern()):
1054
+ return insertion
1055
+ # Every *other* live line naming this anchor. One is RK64's ambiguity — the design the
1056
+ # author has to place — and the line just written is not one of them, its own claim being
1057
+ # the thing being rendered.
1058
+ claimants = [
1059
+ entry.task.id
1060
+ for entry in insertion.document.entries
1061
+ if entry.task.ref == task.ref and entry.task.id != task.id
1062
+ ]
1063
+ if claimants:
1064
+ return insertion
1065
+ # `bind` and not `section amend --title`: nobody asked for a title here, and a retitle
1066
+ # restyles the heading on purpose (RK388) — so routing through it would take the `§` an
1067
+ # author wrote as the silent price of a binding.
1068
+ prose = sections.bind(config.document(role), section, task.id)
1069
+ bound = sections.find(prose, task.ref)
1070
+ return replace(insertion, prose=prose, bound=bound)
1071
+
1072
+
1073
+ @dataclass(frozen=True, slots=True)
1074
+ class Rereadable:
1075
+ """A body that can be fetched more than once, so it may be validated early (RK426).
1076
+
1077
+ RK381 made the body a *reader* because a paragraph off a pipe is spent by reading it and
1078
+ a pipe does not rewind — so a `why` fifteen characters over cost a 184-word body a second
1079
+ time. That argument holds for one of the three sources and not the other two: a literal
1080
+ string and a path both cost nothing to look at twice.
1081
+
1082
+ Collapsing all three into a bare lambda lost that, and with it the only distinction that
1083
+ decides whether both fields can be refused in one call. So the two cheap sources arrive
1084
+ wrapped and the pipe stays a plain callable — the type is the answer, rather than a flag
1085
+ the caller has to remember to pass and `add` has to trust.
1086
+ """
1087
+
1088
+ read: Callable[[], str]
1089
+
1090
+ def __call__(self) -> str:
1091
+ return self.read()
1092
+
1093
+
1094
+ def _refuse_together(
1095
+ config: Config, task: Task, section: Rationale | None
1096
+ ) -> None:
1097
+ """Raise once for every field breached across the line and its section (RK426).
1098
+
1099
+ Silent unless *both* halves are checkable now: a body that is a reader is RK381's case
1100
+ and stays deferred, and a task with no anchor or a project with no prose file are
1101
+ refusals :func:`_with_section` makes for reasons of their own. What this adds is the one
1102
+ thing neither pass could see — the other pass's findings — so it reports and never
1103
+ decides, and every rule below it still runs exactly as it did.
1104
+ """
1105
+ if section is None:
1106
+ return
1107
+ title, body = section
1108
+ if isinstance(body, Rereadable):
1109
+ # Cheap to fetch twice, which is the whole condition: a path re-read costs a file
1110
+ # read and a literal costs nothing, while a pipe is spent by looking at it.
1111
+ body = body()
1112
+ if not isinstance(body, str) or not task.ref:
1113
+ return
1114
+ role = prose_role(config)
1115
+ if role is None:
1116
+ return
1117
+ found = tuple(config.schema_for("roadmap").validate(task)) + sections.violations(
1118
+ config.schema_for(role),
1119
+ task.ref,
1120
+ title,
1121
+ body,
1122
+ task,
1123
+ known=sections.known(config, task.ref, task),
1124
+ )
1125
+ if found:
1126
+ raise SchemaError(found)
1127
+
1128
+
1129
+ def _with_section(
1130
+ config: Config, insertion: Insertion, title: str, body: str | Callable[[], str]
1131
+ ) -> Insertion:
1132
+ """Validate the rationale against the line that is not on disk yet (RK93).
1133
+
1134
+ Every refusal the prose file has — the word budget, an undeclared block, an anchor
1135
+ already taken — arrives here, *before* the roadmap is written: a transaction that
1136
+ wrote the line and then refused the section would leave exactly the dangling pointer
1137
+ this closes, and one the author did not choose.
1138
+
1139
+ A reader is called at the **last** moment it can be (RK381), which is below the two
1140
+ refusals this function makes itself: a line with no anchor and a project with no prose
1141
+ file are both facts known before a paragraph is needed, and reading one to discard it is
1142
+ the cost this door exists to stop paying. What is left above the read is
1143
+ :func:`sections.add`'s own anchor and title checking, which cannot be split from the
1144
+ body's without giving up reporting every violation at once — and that residue is what a
1145
+ body named by *path* answers instead, the retry re-reading the file.
1146
+ """
1147
+ task = insertion.entry.task
1148
+ if not task.ref:
1149
+ raise NoAnchor(task.id)
1150
+ role = prose_role(config)
1151
+ if role is None:
1152
+ raise NoProseFile(task.id)
1153
+ opens = _opens_the_family(config, role, task)
1154
+ placed = sections.add(
1155
+ config,
1156
+ role,
1157
+ task.ref,
1158
+ title,
1159
+ body() if callable(body) else body,
1160
+ task=task,
1161
+ opens=opens,
1162
+ )
1163
+ return replace(
1164
+ insertion,
1165
+ prose=placed.document,
1166
+ section=placed.section,
1167
+ opened=None if opens is None else opens[0],
1168
+ )
1169
+
1170
+
1171
+ def _opens_the_family(config: Config, role: str, task: Task) -> tuple[str, str] | None:
1172
+ """The family a block's first `add --section` declares in the same write (RK1258).
1173
+
1174
+ ``(anchor, title)``, or None wherever the call already runs as it stands — which is every
1175
+ `add` on a project under the id scheme, and every one into a block whose prose has started.
1176
+
1177
+ Four conditions, and each of them is what keeps this from guessing. The anchor's
1178
+ **immediate parent** has to be the one thing missing (:func:`_unopened`), and it has to be
1179
+ a *top level*: a hole two generations deep is RK1208's refusal and stays one, because the
1180
+ address in between names a subtree whose title nobody has written. The block has to have
1181
+ **no family at all** — this is a block's first task by definition, and a block that already
1182
+ numbers its prose somewhere is a caller who typed the wrong numeral, which is a typo and
1183
+ not an opening. And the block's heading has to give a title, since that title is what the
1184
+ family takes.
1185
+
1186
+ The title is the block's own and never composed (L4): a family under an outline is the
1187
+ block's prose, so the words are already written down one file over. Wrong words are
1188
+ `section amend <family> --title`, which is a door that exists — where composing them here
1189
+ would be the tool holding an opinion no verb could correct it out of.
1190
+ """
1191
+ from roadkeep.blocking import _title # noqa: PLC0415 - RK260
1192
+ from roadkeep.history import families_of_block # noqa: PLC0415 - RK260
1193
+
1194
+ if not task.ref or (family := _unopened(config, role, task.ref)) is None:
1195
+ return None
1196
+ if "." in family or families_of_block(config, task.block):
1197
+ return None
1198
+ heading = config.document("roadmap").heading(task.block)
1199
+ if heading is None or not (title := _title(heading)):
1200
+ return None
1201
+ return family, title
1202
+
1203
+
1204
+ def prose_role(config: Config, *, on_disk: bool = False) -> str | None:
1205
+ """Which prose role a section written now goes into, or None where none is declared (RK230).
1206
+
1207
+ Improvements wherever it is declared — `section add`'s own default and where `--section`
1208
+ has always written — and otherwise the **first declared role**, which is the only answer
1209
+ for a project that declares one. That is the whole fix: naming the role outright refused
1210
+ `add --section` to exactly the projects RK172, RK186, RK196 and RK197 each taught one more
1211
+ reader about, and left them the two commands and the dangling pointer RK93 closed.
1212
+
1213
+ **Derived, and never a flag on `add`.** The role is already said in `section add --role`,
1214
+ and a second place to say it is a second thing that can disagree; a project declaring both
1215
+ roles has a real choice, and taking that two-command route deliberately is how an author
1216
+ makes it — which is not the same as being handed it by a refusal.
1217
+
1218
+ `on_disk` narrows it to roles whose file exists, which is what a *follow-up* needs (RK197):
1219
+ a command naming a file nobody created cannot run. A write does not ask, because
1220
+ `section add` writes into a declared file whether or not this run is the one creating it.
1221
+ """
1222
+ # The design's two and not every prose role (RK1361): this answers where a task's
1223
+ # rationale goes when nothing named one, and `decisions` is never that answer.
1224
+ roles = tuple(
1225
+ role
1226
+ for role in DESIGN_ROLES
1227
+ if config.has(role) and (not on_disk or config.path(role).is_file())
1228
+ )
1229
+ if not roles:
1230
+ return None
1231
+ return "improvements" if "improvements" in roles else roles[0]
1232
+
1233
+
1234
+ def _unresolved(config: Config, ref: str) -> str | None:
1235
+ """The role a follow-up would write this pointer's section into, or None if one answers.
1236
+
1237
+ RK15's finding, asked early — and asked of **every declared prose role** (RK197). Reading
1238
+ the improvements file alone told a project that declares `strategy` its pointer resolved
1239
+ to nothing, for an anchor `docs/STRATEGY.md` holds and `lint` resolves: the follow-up
1240
+ named a `section add` that would write a second copy, and the second copy is
1241
+ `ref.ambiguous` — one anchor in two roles, resolving to neither. That is worse than the
1242
+ read half it mirrors (RK186), because what it spends is prose the project already has and
1243
+ the tool cannot write it (L4), so the cost lands on the author.
1244
+
1245
+ None when the project declares no prose file or has not created one yet: the pointer is
1246
+ then unresolvable for a reason no `section add` fixes, and a follow-up naming a command
1247
+ that cannot run is worse than the silence this replaces.
1248
+
1249
+ The **role** and not just the fact, because a project declaring several has more than one
1250
+ place a section could go and the follow-up has to name the one it means — the same
1251
+ derivation the write itself now makes (RK230), so the command offered writes where
1252
+ `--section` would have.
1253
+ """
1254
+ role = prose_role(config, on_disk=True)
1255
+ if role is None or sections.declaring(config, ref):
1256
+ return None
1257
+ return role
1258
+
1259
+
1260
+ @dataclass(frozen=True, slots=True)
1261
+ class StatusChange:
1262
+ """The line as it now reads, and the marker it carried before (RK7)."""
1263
+
1264
+ document: Document
1265
+ entry: Entry
1266
+ before: str
1267
+ #: Other lines whose dep annotation this write made true again (RK8).
1268
+ refreshed: tuple[str, ...] = ()
1269
+ #: What this write did to the claim on the line (RK158). Reported, because a marker change
1270
+ #: is not obviously an assertion of ownership to whoever typed it — and a claim taken or
1271
+ #: dropped without being said is the silence RK119 argued against for the answer itself.
1272
+ claim: Followed = Followed.NEITHER
1273
+ #: Every path this write took, projections included (RK1130) — the list a `git add --`
1274
+ #: takes, so the report a caller composes a commit from can name the file it refreshed.
1275
+ wrote: tuple[Path, ...] = ()
1276
+
1277
+ @property
1278
+ def after(self) -> str:
1279
+ return self.entry.task.status
1280
+
1281
+ @property
1282
+ def changed(self) -> bool:
1283
+ return self.before != self.after
1284
+
1285
+ @property
1286
+ def rendered(self) -> str:
1287
+ return self.entry.raw
1288
+
1289
+ @property
1290
+ def lineno(self) -> int:
1291
+ return self.entry.lineno
1292
+
1293
+ def event(self, config: Config) -> dict[str, object]:
1294
+ """What this write did to the block it landed in (RK38), off the document it wrote."""
1295
+ from roadkeep.rendering import _event # noqa: PLC0415 - RK260
1296
+
1297
+ return _event(self.entry.task.id, self.entry.task.block, self.document, config)
1298
+
1299
+ def stated(self, config: Config) -> str:
1300
+ """What the marker did, as a reader is told it (RK7, RK158).
1301
+
1302
+ Beside :meth:`payload` since RK1170. The no-op reading is here too, and that is the
1303
+ point of moving it: a line that already carried the marker still followed its claim and
1304
+ still has a standing to report, which is one answer with a branch in it and not two.
1305
+ """
1306
+ from roadkeep.rendering import ( # noqa: PLC0415 - RK260
1307
+ _event_rows,
1308
+ _followed_rows,
1309
+ _staging_rows,
1310
+ )
1311
+
1312
+ where = f"{config.relative(config.path('roadmap'))}:{self.lineno}"
1313
+ if not self.changed:
1314
+ rows = [f"{self.entry.task.id} is already {self.after} {where}"]
1315
+ return "\n".join(
1316
+ rows + _followed_rows(self, config)
1317
+ + _event_rows(self.event(config), " ")
1318
+ )
1319
+ rows = [f"{self.entry.task.id} {self.before} → {self.after} {where}"]
1320
+ if self.refreshed:
1321
+ rows.append(f" derived {', '.join(self.refreshed)} (dep annotations re-derived)")
1322
+ rows += _followed_rows(self, config)
1323
+ rows += _staging_rows(config.relative(one) for one in self.wrote)
1324
+ rows += _event_rows(self.event(config), " ")
1325
+ return "\n".join(rows)
1326
+
1327
+ def payload(self, config: Config) -> dict[str, object]:
1328
+ """The same answer as data, with the claim this marker took or dropped (RK158)."""
1329
+ from roadkeep.rendering import _wrote_json # noqa: PLC0415 - RK260
1330
+
1331
+ return {
1332
+ "id": self.entry.task.id,
1333
+ "from": self.before,
1334
+ "to": self.after,
1335
+ "changed": self.changed,
1336
+ "file": config.relative(config.path("roadmap")),
1337
+ "line": self.lineno,
1338
+ "rendered": self.rendered,
1339
+ "refreshed": list(self.refreshed),
1340
+ "claim": str(self.claim) or None,
1341
+ **_wrote_json(config, self.wrote),
1342
+ "event": self.event(config),
1343
+ }
1344
+
1345
+
1346
+ def set_status(config: Config, task_id: str, marker: str) -> StatusChange:
1347
+ """Write one task's marker in the roadmap, and refuse if a sibling carries one.
1348
+
1349
+ A marker is maturity, and maturity has one home. Two files that both express it will
1350
+ eventually express different values, and at that point there is no rule that says
1351
+ which one is the status — so the second one is refused rather than reconciled
1352
+ (:class:`StatusElsewhere`), and so is a second line for the same id in this file
1353
+ (:class:`DuplicateId`).
1354
+
1355
+ ✅ is refused here by the schema itself, not by a special case: shipped work is the
1356
+ ledger's to state, and `ship` (RK6) is the only thing that puts it there.
1357
+
1358
+ A marker this task's dependents cached is stale the moment it changes, so the write
1359
+ re-derives every annotation in the file (RK8) and names the lines it corrected.
1360
+
1361
+ The claim follows the marker (RK158): 🛠 dates one and any other marker drops one, which is
1362
+ the rule the *read* already assumed and this door was the one exception to. It happens on
1363
+ the no-op path too — re-asserting the marker a line already carries is a re-assertion of
1364
+ the claim, the same way re-taking an expired one is a new claim — while the file itself is
1365
+ still left untouched, an unchanged file with a moved mtime reading as an edit.
1366
+
1367
+ Which makes this the door that refuses a **taken** line (RK160), because it is the door
1368
+ every claim is written by: writing 🛠 over a live claim used to re-date it in the holder's
1369
+ name and say nothing. A release is never refused — that is any other marker.
1370
+ """
1371
+ backlog = Backlog.load(config)
1372
+ roadmap = backlog.roadmap
1373
+ entry = roadmap.by_id().get(task_id)
1374
+ if entry is None:
1375
+ raise NotOpen(
1376
+ task_id,
1377
+ config.relative(config.path("roadmap")),
1378
+ Whereabouts.of(config, task_id),
1379
+ )
1380
+ twins = tuple(e.lineno for e in roadmap.entries if e.task.id == task_id)
1381
+ if len(twins) > 1:
1382
+ raise DuplicateId(task_id, config.relative(config.path("roadmap")), twins)
1383
+ _refuse_sibling_status(config, task_id)
1384
+ # Before the write, beside every other refusal this door already makes (RK160): the
1385
+ # in-progress marker is an assertion that somebody is on the line, and one live claim is
1386
+ # all it takes for that to be somebody else's.
1387
+ claiming.refuse_taken(config, task_id, marker, roadmap.entries)
1388
+
1389
+ # The **file's** schema and not the project's (RK401): `config.schema` is the default
1390
+ # grammar with no `[rules.<role>]` or `[limits.<role>]` applied, so on a project that
1391
+ # configured this file away from the default the gate called a line legal and this door
1392
+ # refused to correct it — leaving the hand edit the guard denies as the only way out.
1393
+ # `roadmap.schema` is what `Config.document` already resolved, which is the seam
1394
+ # `renumber` reaches through and the one `adopt` settled this argument on (RK76).
1395
+ updated = sections.checked(
1396
+ config, replace(entry.task, status=marker), schema=roadmap.schema
1397
+ )
1398
+ if updated.status == entry.task.status:
1399
+ # Nothing to write: rewriting the same bytes would make a no-op look like an
1400
+ # edit to every tool that watches the file.
1401
+ return StatusChange(
1402
+ document=roadmap,
1403
+ entry=entry,
1404
+ before=entry.task.status,
1405
+ claim=claiming.follow(config.root, task_id, marker, roadmap.entries),
1406
+ )
1407
+ derived = refresh(replace(backlog, roadmap=roadmap.replace_task(entry, updated)))
1408
+ wrote = derived.document.save()
1409
+ return StatusChange(
1410
+ wrote=wrote,
1411
+ document=derived.document,
1412
+ entry=next(e for e in derived.document.entries if e.lineno == entry.lineno),
1413
+ before=entry.task.status,
1414
+ refreshed=tuple(name for name in derived.changed if name != task_id),
1415
+ # After the save, and never a condition of it: the registry is transient state whose
1416
+ # worst failure is a claim lost, which is the behaviour before claims existed.
1417
+ claim=claiming.follow(config.root, task_id, marker, derived.document.entries),
1418
+ )
1419
+
1420
+
1421
+ @dataclass(frozen=True, slots=True)
1422
+ class Amendment:
1423
+ """One line as it now reads, and as it read before (RK65).
1424
+
1425
+ Not a :class:`StatusChange` with more fields: the marker has its own door because status is
1426
+ maturity, and this one exists for the fields a project *adopting* the tool has to correct —
1427
+ which is a different question with a different refusal.
1428
+ """
1429
+
1430
+ document: Document
1431
+ entry: Entry
1432
+ before: Task
1433
+ #: Other lines whose dep annotation this write made true again (RK8).
1434
+ refreshed: tuple[str, ...] = ()
1435
+ #: Every path this write took, projections included (RK1130) — the list a `git add --`
1436
+ #: takes, so the report a caller composes a commit from can name the file it refreshed.
1437
+ wrote: tuple[Path, ...] = ()
1438
+
1439
+ @property
1440
+ def changed(self) -> tuple[str, ...]:
1441
+ """Which fields actually differ, in field order — empty when nothing was written.
1442
+
1443
+ **`requires` is one of them** (RK1311), and its absence here was the worse half of that
1444
+ defect: `amend <id> --requires console --why "<the sentence it already had>"` wrote the
1445
+ requirement onto the line and answered *unchanged: every field already reads that way*.
1446
+ Both cannot be true, and the one printed is the one that stops a caller retrying — it
1447
+ was visible at all only because the roadmap line was read straight afterwards.
1448
+
1449
+ The field is what this walks and not a list somebody keeps in step: `amend` grew a
1450
+ fourth argument (RK1297) and this tuple was written when there were three.
1451
+ """
1452
+ return tuple(
1453
+ name
1454
+ for name in ("why", "deps", "requires", "ref")
1455
+ if getattr(self.before, name) != getattr(self.entry.task, name)
1456
+ )
1457
+
1458
+ @property
1459
+ def was(self) -> dict[str, str | tuple[str, ...]]:
1460
+ """What each changed field said before, keyed by field name (RK1133).
1461
+
1462
+ The reading this record held and did not answer. `status` reports `from` beside `to`
1463
+ and `restate` reports `was` beside `now`; an amend reported *which* fields moved and
1464
+ never their old values, so a client rendering one could show the new line and not the
1465
+ sentence it replaced — on `why`, the field this verb exists to correct.
1466
+
1467
+ Only the fields in :attr:`changed`, because a field that did not move has no *before*
1468
+ to report: sending its current value under this name would let a reader show a diff
1469
+ where there is none. Deps are rendered as the line spells them, which is the one
1470
+ spelling every other payload here uses — a `Dep` is a record, and handing one to a
1471
+ client outside this process is the thing :data:`UNSENT` refuses for a document.
1472
+ """
1473
+ return {
1474
+ name: tuple(dep.render() for dep in self.before.deps)
1475
+ if name == "deps"
1476
+ else getattr(self.before, name)
1477
+ for name in self.changed
1478
+ }
1479
+
1480
+ @property
1481
+ def rendered(self) -> str:
1482
+ return self.entry.raw
1483
+
1484
+ def stated(self, config: Config) -> str:
1485
+ """What this correction did, as a reader is told it (RK65).
1486
+
1487
+ Beside :meth:`payload` since RK1170, for the reason :class:`Restatement`'s pair is: both
1488
+ registers were in the handler, and a write verb's answer is what the transaction
1489
+ produced rather than something the door composes about it.
1490
+ """
1491
+ from roadkeep.rendering import _staging_rows # noqa: PLC0415 - RK260
1492
+
1493
+ where = config.relative(config.path("roadmap"))
1494
+ if not self.changed:
1495
+ return f"{self.entry.task.id} unchanged: every field already reads that way"
1496
+ rows = [
1497
+ f"{self.entry.task.id} amended {where}:{self.entry.lineno}"
1498
+ f" ({', '.join(self.changed)})",
1499
+ f" {self.rendered}",
1500
+ ]
1501
+ if self.refreshed:
1502
+ rows.append(f" derived {', '.join(self.refreshed)} (dep annotations re-derived)")
1503
+ rows += _staging_rows(config.relative(one) for one in self.wrote)
1504
+ return "\n".join(rows)
1505
+
1506
+ def payload(self, config: Config) -> dict[str, object]:
1507
+ """The same answer as data, carrying what each changed field said before (RK1133)."""
1508
+ from roadkeep.rendering import _wrote_json # noqa: PLC0415 - RK260
1509
+
1510
+ return {
1511
+ "id": self.entry.task.id,
1512
+ "file": config.relative(config.path("roadmap")),
1513
+ "line": self.entry.lineno,
1514
+ "changed": list(self.changed),
1515
+ "rendered": self.rendered,
1516
+ # What each changed field said before (RK1133), beside which ones moved: `status`
1517
+ # answers `from`/`to` and `restate` answers `was`/`now`, and this was the one write
1518
+ # whose client could show the new line and nothing else.
1519
+ "was": {
1520
+ name: list(value) if isinstance(value, tuple) else value
1521
+ for name, value in self.was.items()
1522
+ },
1523
+ "refreshed": list(self.refreshed),
1524
+ **_wrote_json(config, self.wrote),
1525
+ }
1526
+
1527
+
1528
+ def amend(
1529
+ config: Config,
1530
+ task_id: str,
1531
+ *,
1532
+ why: str | None = None,
1533
+ deps: Sequence[str] | None = None,
1534
+ requires: Sequence[str] | None = None,
1535
+ ref: str | None = None,
1536
+ lines: int | None = None,
1537
+ ) -> Amendment:
1538
+ """Correct one open line's `why`, `deps`, `requires` or `ref`. At input, or nothing (RK65).
1539
+
1540
+ The three fields a project that adopted the tool has to be able to fix: a pointer it never
1541
+ had, a dep naming an id that is in neither file, and the compression of a `why` that was a
1542
+ paragraph before the limit existed. `retire` plus `add` would lose the id, and the id is
1543
+ what the history is keyed on.
1544
+
1545
+ `symptom` is deliberately absent: it is the falsifiable claim the line *is*, so a different
1546
+ one is a different task — and the corpus says it is not the problem (0 of Shio's 78 over the
1547
+ limit, against 70 of its whys). `status` is absent because :func:`set_status` is its door.
1548
+
1549
+ Nothing is written when nothing differs: rewriting the same bytes makes a no-op look like an
1550
+ edit to every hook watching the file.
1551
+
1552
+ And refused on a **wrapped** line unless `lines` says how many it replaces (RK195). The
1553
+ ledger's rule (RK179) one file over, for the reason that made it worth counting rather
1554
+ than assuming: this is the door a project *adopting* the tool reaches for, and an adopted
1555
+ roadmap is the only place a wrapped line can come from — `add` refuses to write one, so
1556
+ every governed roadmap reads as zero and the population is the backlogs nobody has
1557
+ imported yet.
1558
+ """
1559
+ backlog = Backlog.load(config)
1560
+ roadmap = backlog.roadmap
1561
+ entry = roadmap.by_id().get(task_id)
1562
+ if entry is None:
1563
+ raise NotOpen(
1564
+ task_id,
1565
+ config.relative(config.path("roadmap")),
1566
+ Whereabouts.of(config, task_id),
1567
+ )
1568
+ twins = tuple(e.lineno for e in roadmap.entries if e.task.id == task_id)
1569
+ if len(twins) > 1:
1570
+ raise DuplicateId(task_id, config.relative(config.path("roadmap")), twins)
1571
+
1572
+ wanted = replace(
1573
+ entry.task,
1574
+ why=entry.task.why if why is None else why,
1575
+ deps=entry.task.deps
1576
+ if deps is None
1577
+ else read_deps(", ".join(deps), roadmap.schema),
1578
+ # The whole group or nothing, exactly as `--dep` replaces its own (RK1297): a
1579
+ # requirement that no longer holds is removed by restating the ones that do, and a
1580
+ # flag that only ever added would leave a line nothing could ever offer again.
1581
+ requires=entry.task.requires
1582
+ if requires is None
1583
+ else read_requires(", ".join(requires)),
1584
+ ref=entry.task.ref if ref is None else ref,
1585
+ )
1586
+ if deps is not None:
1587
+ refuse_deps(config, backlog, wanted)
1588
+ # Derived on write like every other annotation (RK8): the author names the dep and the
1589
+ # tool states whether it shipped.
1590
+ updated = sections.checked(config, derive(backlog, wanted), schema=roadmap.schema)
1591
+ if updated == entry.task:
1592
+ return Amendment(document=roadmap, entry=entry, before=entry.task)
1593
+ # Asked after the no-op check, so an amend that alters nothing never demands a count for
1594
+ # a write it is not going to make. No `keeps_tail` here or at `restate` (RK1057): on the
1595
+ # roadmap the count authorises a deletion and only that, no multi-line task line being a
1596
+ # non-goal — so a wrapped line is a hand-written note the format is asserting over, and
1597
+ # offering to write it back would be offering the shape this file does not have.
1598
+ counted(
1599
+ task_id,
1600
+ config.relative(config.path("roadmap")),
1601
+ entry,
1602
+ lines,
1603
+ verb="correcting it",
1604
+ )
1605
+ derived = refresh(replace(backlog, roadmap=roadmap.rewrite_entry(entry, updated)))
1606
+ wrote = derived.document.save()
1607
+ return Amendment(
1608
+ wrote=wrote,
1609
+ document=derived.document,
1610
+ entry=next(e for e in derived.document.entries if e.lineno == entry.lineno),
1611
+ before=entry.task,
1612
+ refreshed=tuple(name for name in derived.changed if name != task_id),
1613
+ )
1614
+
1615
+
1616
+ @dataclass(frozen=True, slots=True)
1617
+ class Restatement:
1618
+ """One line's falsifiable claim, corrected under the id that keeps it (RK178).
1619
+
1620
+ Not an :class:`Amendment` with a fourth field, and the separation is the whole answer:
1621
+ `amend` reaches the fields a description gets *wrong about work that did not change*, and
1622
+ it excludes this one because a different symptom is normally a different task (RK65). That
1623
+ reason is sound and its outcome was not — a premise that turns out false leaves the file
1624
+ this tool exists to keep true asserting something false, in the field a reader sees first.
1625
+
1626
+ So the correction is a verb rather than a flag, and this shape is what makes it *recorded*
1627
+ instead of hidden: the act has a name in the history, and the answer prints both readings,
1628
+ so a reviewer sees a restatement where a `--symptom` inside `amend` would have shown a
1629
+ word changing. What it deliberately does **not** carry is a reason — there is no field in
1630
+ the format for one, and an argument the tool cannot store is an argument it must not
1631
+ pretend to take (L4). The commit that removes the false claim is where it belongs.
1632
+ """
1633
+
1634
+ document: Document
1635
+ entry: Entry
1636
+ before: Task
1637
+ #: Other lines whose dep annotation this write made true again (RK8). Normally empty: a
1638
+ #: symptom is nobody's dependency, and this is here because the write path derives it.
1639
+ refreshed: tuple[str, ...] = ()
1640
+ #: Whether the caller declared this a slip of the pen rather than a false premise (RK414).
1641
+ #: Declared and **never inferred**: which of the two a rewording is cannot be read off two
1642
+ #: strings, and a tool that guessed would be filing the caller's intent under its own.
1643
+ typo: bool = False
1644
+ #: Every path this write took, projections included (RK1130) — the list a `git add --`
1645
+ #: takes, so the report a caller composes a commit from can name the file it refreshed.
1646
+ wrote: tuple[Path, ...] = ()
1647
+ #: The anchor of the design that argues from the claim this call replaced (RK1196), where
1648
+ #: the pointer resolves to exactly one live section. Empty where it resolves to none or to
1649
+ #: two, which are a `lint` finding and not this verb's to settle — `deferring._carried`
1650
+ #: spells the same three outcomes at the door that keeps a section rather than naming it.
1651
+ design: str = ""
1652
+ #: Which prose role holds that anchor, so the follow-up names `--role` where the project's
1653
+ #: design does not live in the default file (RK196).
1654
+ design_role: str = ""
1655
+
1656
+ @property
1657
+ def changed(self) -> bool:
1658
+ return self.before.symptom != self.entry.task.symptom
1659
+
1660
+ @property
1661
+ def follow_up(self) -> tuple[str, ...]:
1662
+ """The edits the two other statements of the replaced claim need (RK1196).
1663
+
1664
+ Composed once and read by both registers, which is what keeps the printed row and the
1665
+ payload from being two spellings of one answer (RK1170). Empty on a `--typo`, which is
1666
+ the caller declaring the claim was the one intended: a slip of the pen leaves the `why`
1667
+ and the design arguing the premise they were written for, so asking for two edits there
1668
+ would be the record describing a decision nobody took (RK414). Empty too where nothing
1669
+ changed, the file already stating this symptom.
1670
+ """
1671
+ if self.typo or not self.changed:
1672
+ return ()
1673
+ edits = [f"amend {self.entry.task.id} --why -"]
1674
+ if self.design:
1675
+ named = "" if self.design_role == "improvements" else f" --role {self.design_role}"
1676
+ edits.append(f"section amend {self.design}{named} --body -")
1677
+ return tuple(edits)
1678
+
1679
+ @property
1680
+ def rendered(self) -> str:
1681
+ return self.entry.raw
1682
+
1683
+ @property
1684
+ def lineno(self) -> int:
1685
+ return self.entry.lineno
1686
+
1687
+ def stated(self, config: Config) -> str:
1688
+ """What this correction did, as a reader is told it (RK178, RK414).
1689
+
1690
+ Beside :meth:`payload` since RK1170. Both registers were in the handler, which is where a
1691
+ write verb's answer least belongs: the record is what the transaction produced, and the
1692
+ door only chose which reading to print.
1693
+ """
1694
+ from roadkeep.rendering import _premise_rows, _staging_rows # noqa: PLC0415 - RK260
1695
+
1696
+ where = config.relative(config.path("roadmap"))
1697
+ if not self.changed:
1698
+ return f"{self.entry.task.id} unchanged: the line already states that symptom"
1699
+ rows = [
1700
+ f"{self.entry.task.id} restated {where}:{self.lineno}",
1701
+ f" was {self.before.symptom}",
1702
+ f" now {self.entry.task.symptom}",
1703
+ f" {self.rendered}",
1704
+ # Said out loud, because keeping them is the whole argument for the verb: the work
1705
+ # never changed, so nothing the history is keyed on moves.
1706
+ " kept the id, the deps and the section: the work never changed",
1707
+ # Which of the two acts it was (RK414): the default sentence claims a premise turned
1708
+ # out false, and printing that over a misspelt word is the record describing a
1709
+ # decision nobody took.
1710
+ " spelling the claim is the one intended — a slip of the pen, not a false premise"
1711
+ if self.typo
1712
+ else " claim the premise this line asserted turned out to be false",
1713
+ ]
1714
+ # Said after the claim and before the staging line, which is the order the author acts
1715
+ # in: what this call did, then the two edits it did not (RK1196).
1716
+ rows += _premise_rows(self.follow_up, self.design)
1717
+ if self.refreshed:
1718
+ rows.append(f" derived {', '.join(self.refreshed)} (dep annotations re-derived)")
1719
+ rows += _staging_rows(config.relative(one) for one in self.wrote)
1720
+ return "\n".join(rows)
1721
+
1722
+ def payload(self, config: Config) -> dict[str, object]:
1723
+ """The same answer as data, with both readings of the claim (RK178)."""
1724
+ from roadkeep.rendering import _wrote_json # noqa: PLC0415 - RK260
1725
+
1726
+ return {
1727
+ "id": self.entry.task.id,
1728
+ "file": config.relative(config.path("roadmap")),
1729
+ "line": self.lineno,
1730
+ # Both readings, which is what makes this recorded rather than hidden: a reviewer
1731
+ # sees a claim replaced where a flag would show a word changing.
1732
+ "was": self.before.symptom,
1733
+ "now": self.entry.task.symptom,
1734
+ "changed": self.changed,
1735
+ # Which of the two acts this was (RK414), so a consumer counting how often a claim
1736
+ # actually moved is not counting spelling fixes with them.
1737
+ "typo": self.typo,
1738
+ # The two other places the replaced claim is written, as the doors that reach them
1739
+ # (RK1196) — empty on a typo and on a no-op, exactly as the printed rows are.
1740
+ "premise": {
1741
+ "design": self.design or None,
1742
+ "role": self.design_role or None,
1743
+ "next": list(self.follow_up),
1744
+ },
1745
+ "rendered": self.rendered,
1746
+ "refreshed": list(self.refreshed),
1747
+ **_wrote_json(config, self.wrote),
1748
+ }
1749
+
1750
+
1751
+ def restate(
1752
+ config: Config,
1753
+ task_id: str,
1754
+ symptom: str,
1755
+ *,
1756
+ lines: int | None = None,
1757
+ typo: bool = False,
1758
+ ) -> Restatement:
1759
+ """Correct one open line's symptom, keeping its id, its deps and its section (RK178).
1760
+
1761
+ ``typo`` splits the two acts this door had to carry as one (RK414). The verb is
1762
+ documented for the case it was written for — the premise itself turned out false — and a
1763
+ misspelt word is not that: the claim is the one intended, and repairing it through a
1764
+ door whose answer reads *the work never changed, the premise did* files a decision
1765
+ nobody took. So the caller says which, the answer says which, and `restate`'s every
1766
+ other occurrence still means what its documentation says, which is the only thing that
1767
+ makes it greppable.
1768
+
1769
+ Declared and never inferred, deliberately. Whether "the annotaton is stale" → "the
1770
+ annotation is stale" is a spelling fix and "the annotation is stale" → "the annotation
1771
+ is absent" is a new claim cannot be read off the two strings — the difference is what
1772
+ the author meant — so a tool that decided would be recording its guess as the record.
1773
+ Nothing is validated differently either: a typo's symptom faces the same schema, because
1774
+ a slip of the pen that lands over the limit is still over the limit.
1775
+
1776
+ The door RK65 was right to leave shut and the one nothing else opened. Measured in
1777
+ claude-tray: T210 was written from a list of response headers, executing it meant reading
1778
+ the files, and the premise was false — nothing there derived what the line asserted. The
1779
+ `why` was corrected, the marker dropped to an idea, the rationale rewritten to open by
1780
+ refuting itself, and the symptom could not be touched at all.
1781
+
1782
+ The designed exit was `retire` plus `add`, and it costs twice: it spends an id, deletes a
1783
+ section that was already right, and records a departure where none happened — and RK125
1784
+ shows a project that cannot retire at all. None of that is a price a *correction* should
1785
+ pay, because the work never changed. So the id stays, which is what the history is keyed
1786
+ on, and every other field with it.
1787
+
1788
+ Nothing is written when nothing differs, as at the door next to this one: rewriting the
1789
+ same bytes makes a no-op look like an edit to every hook watching the file.
1790
+
1791
+ A claim is deliberately not consulted. `status` refuses a held line because writing 🛠 is
1792
+ an *assertion of ownership* (RK160), and this write touches no marker: the person who
1793
+ discovers a premise is false is normally the one holding the line, and a rule that refused
1794
+ them would be a rule against the case this verb exists for.
1795
+ """
1796
+ backlog = Backlog.load(config)
1797
+ roadmap = backlog.roadmap
1798
+ entry = roadmap.by_id().get(task_id)
1799
+ if entry is None:
1800
+ raise NotOpen(
1801
+ task_id,
1802
+ config.relative(config.path("roadmap")),
1803
+ Whereabouts.of(config, task_id),
1804
+ )
1805
+ twins = tuple(e.lineno for e in roadmap.entries if e.task.id == task_id)
1806
+ if len(twins) > 1:
1807
+ raise DuplicateId(task_id, config.relative(config.path("roadmap")), twins)
1808
+
1809
+ updated = sections.checked(
1810
+ config,
1811
+ derive(backlog, replace(entry.task, symptom=symptom)),
1812
+ schema=roadmap.schema,
1813
+ )
1814
+ if updated == entry.task:
1815
+ return Restatement(document=roadmap, entry=entry, before=entry.task, typo=typo)
1816
+ # The same count as the door next to this one (RK195): a restatement rewrites the line's
1817
+ # prose, so on a wrapped line it strands the same tail.
1818
+ counted(
1819
+ task_id,
1820
+ config.relative(config.path("roadmap")),
1821
+ entry,
1822
+ lines,
1823
+ verb="restating it",
1824
+ )
1825
+ derived = refresh(replace(backlog, roadmap=roadmap.rewrite_entry(entry, updated)))
1826
+ wrote = derived.document.save()
1827
+ design, role = _arguing(config, updated)
1828
+ return Restatement(
1829
+ wrote=wrote,
1830
+ document=derived.document,
1831
+ entry=next(e for e in derived.document.entries if e.lineno == entry.lineno),
1832
+ before=entry.task,
1833
+ refreshed=tuple(name for name in derived.changed if name != task_id),
1834
+ typo=typo,
1835
+ design=design,
1836
+ design_role=role,
1837
+ )
1838
+
1839
+
1840
+ def _body_aim(config: Config, anchor: str, role: str) -> str:
1841
+ """What a body under this anchor may weigh, before one is written (RK1309).
1842
+
1843
+ `add`'s own help states the rule this closed: *a limit reported after the prose exists is
1844
+ a limit discovered too late to save the tokens it was meant to save*. The prose fields are
1845
+ exactly where it still landed — measured in pportal, 2026-08-22, at 266 words against 250,
1846
+ discovered by writing 266, with the retry carrying every word again.
1847
+
1848
+ Through :func:`~roadkeep.budgeting.body_budget`, which is the reader the `budget` verb and
1849
+ the gate both use, so the number here and the refusal one call later cannot disagree. Any
1850
+ failure to price is silence rather than a broken `add`: the write has landed, and a row
1851
+ about a limit is not worth a traceback on top of it.
1852
+ """
1853
+ from roadkeep.budgeting import body_budget # noqa: PLC0415 - RK260
1854
+
1855
+ try:
1856
+ return body_budget(config, anchor, role).stated()
1857
+ except (KeyError, OSError, ValueError):
1858
+ return ""
1859
+
1860
+
1861
+ def _body_weight(config: Config, anchor: str, role: str) -> dict[str, object] | None:
1862
+ """The same figure as data (RK1309), off the same reader as the row above it.
1863
+
1864
+ :meth:`~roadkeep.budgeting.Body.payload` and not a shape composed here: the caller reaching
1865
+ this through the served answer is the one the whole pre-write read is for, and a second
1866
+ spelling of a limit is the drift this package exists to stop.
1867
+ """
1868
+ from roadkeep.budgeting import body_budget # noqa: PLC0415 - RK260
1869
+
1870
+ try:
1871
+ return body_budget(config, anchor, role).payload()
1872
+ except (KeyError, OSError, ValueError):
1873
+ return None
1874
+
1875
+
1876
+ def _arguing(config: Config, task: Task) -> tuple[str, str]:
1877
+ """The one live section written from the claim this restatement replaced (RK1196).
1878
+
1879
+ Resolved here rather than at either printer, because it is a fact about the transaction
1880
+ and not about the register it is read in — the shape `wrote` and `refreshed` already have.
1881
+
1882
+ A pointer that resolves to nothing or to two files answers the empty pair, so the report
1883
+ names the `why` alone. Both are findings `lint` already holds and neither is this verb's
1884
+ to settle: a follow-up naming one of two ambiguous files would be a guess printed as an
1885
+ instruction, and `deferring._carried` declines the same guess at the door beside this one.
1886
+ """
1887
+ if not task.ref:
1888
+ return "", ""
1889
+ roles = sections.declaring(config, task.ref)
1890
+ return (task.ref, roles[0]) if len(roles) == 1 else ("", "")
1891
+
1892
+
1893
+ def _refuse_sibling_status(config: Config, task_id: str) -> None:
1894
+ """Any other governed file carrying a marker for this id is the disagreement.
1895
+
1896
+ Except the one shape the tool creates on purpose (RK121, RK1080, RK1114). `ship --part`
1897
+ writes an entry naming a half and *leaves the line open* at ⏳, so a ⏳ line beside a
1898
+ qualified ✅ is the two files agreeing rather than disagreeing — and refusing it closed the
1899
+ only door that starts work: measured on dockerdesk, `pick` named the line, `brief` called
1900
+ it ready, and `brief --claim` answered that status lives in exactly one file. It does; the
1901
+ roadmap holds it, and an id in the ledger is a finished task only when the line is gone.
1902
+
1903
+ :attr:`~roadkeep.kernel.schema.Task.in_halves` and never a second test of the qualifier,
1904
+ which is where RK1080 folded the two readings this rule has: the gate skips the same pair
1905
+ for the same reason (`linting._carried`), and a door disagreeing with it would refuse a
1906
+ state the gate calls clean.
1907
+ """
1908
+ for role in ROLES:
1909
+ if role == "roadmap" or not config.has(role) or not config.path(role).is_file():
1910
+ continue
1911
+ found = config.document(role).by_id().get(task_id)
1912
+ if found is not None and not found.task.in_halves:
1913
+ raise StatusElsewhere(
1914
+ task_id,
1915
+ role,
1916
+ config.relative(config.path(role)),
1917
+ found.lineno,
1918
+ found.task.status,
1919
+ )
1920
+
1921
+
1922
+ def refuse_reuse(config: Config, task_id: str, *, flag: str = "--id") -> None:
1923
+ """Refuse an id anything already mentions, anywhere (RK4).
1924
+
1925
+ Public because every door that **moves a task onto** a number needs the same refusal,
1926
+ and an id rule with a second implementation is an id rule two commands can disagree
1927
+ about: `add` (RK5), `renumber` and `record renumber` all call this one. A mention is
1928
+ refused as well as a line, and that is right here: landing a task on a number some
1929
+ sentence already names silently re-points the sentence at work it was not about.
1930
+
1931
+ ``flag`` is the one thing that is **not** shared (RK1212): the rule is one and the
1932
+ argument carrying the number is each verb's own, so the remedy is passed rather than
1933
+ assumed — `renumber` and `record renumber` take `--to`, and the sentence naming `--id` at
1934
+ them was a call the parser refuses, one step further down.
1935
+
1936
+ :func:`refuse_occupied` is the *other* rule, for the door that gives a number the line
1937
+ it is missing rather than taking one over (RK1051). Two functions and not a flag,
1938
+ because they enforce different things — this one that a number is unspoken for, that
1939
+ one that no line holds it.
1940
+ """
1941
+ clash = next((ref for ref in scan(config) if ref.id == task_id), None)
1942
+ if clash is not None:
1943
+ raise IdInUse(task_id, config.relative(clash.path), clash.lineno, flag=flag)
1944
+
1945
+
1946
+ def refuse_occupied(config: Config, task_id: str) -> IdRef | None:
1947
+ """Refuse an id a **line** holds, and hand back the mention it tolerates (RK1051).
1948
+
1949
+ Measured in Shio: one ledger entry recorded two shipped tasks, so the second had no
1950
+ entry of its own — invisible to `show`, to both counts, and reported by the gate as a
1951
+ broken promise. `record add --id` is the repair, and it refused, because that id
1952
+ occurred **eight** times: its own half, plus seven entries citing its rule. The guard
1953
+ was inverted for exactly this case — the better documented a decision is, the less
1954
+ repairable its record — and the rule was never at stake, since nothing is being
1955
+ *reused* by an id that has no line.
1956
+
1957
+ So the question asked here is :func:`~roadkeep.ids.carried`'s, which is the parse's and
1958
+ not the scan's: does some governed file hold this id as a task, an entry or a paused
1959
+ line, or has the project reserved it? Any of those is an allocation and is refused with
1960
+ the same :class:`IdInUse` as ever. A bare mention is **returned**, never swallowed: the
1961
+ caller reports it, because writing the line a sentence promised is the good case and
1962
+ writing one it did not is a fact the author has to see.
1963
+ """
1964
+ occurrences = [ref for ref in scan(config) if ref.id == task_id]
1965
+ if task_id not in carried(config):
1966
+ return occurrences[0] if occurrences else None
1967
+ # The address is the *line's* and not the first mention's: a refusal is read by
1968
+ # somebody about to click it, and sending them to a sentence citing the id when a
1969
+ # task line holds it names the wrong file for the wrong reason.
1970
+ holders = {
1971
+ config.path(role)
1972
+ for role in CARRIERS
1973
+ if config.has(role) and config.path(role).is_file()
1974
+ }
1975
+ clash = next(
1976
+ (ref for ref in occurrences if ref.path in holders),
1977
+ occurrences[0] if occurrences else None,
1978
+ )
1979
+ raise IdInUse(
1980
+ task_id,
1981
+ config.relative(clash.path) if clash else config.relative(config.source or config.root),
1982
+ clash.lineno if clash else 0,
1983
+ )
1984
+
1985
+
1986
+ def declaring(config: Config, block: str) -> None:
1987
+ """Refuse a block the **ledger** does not declare, at the door that opens it (RK380).
1988
+
1989
+ The roadmap's own heading is `place`'s refusal and this is the other half. Measured in
1990
+ Turing: Block BV carried eight open lines and no `## Block BV` in `CHANGELOG.md`, and the
1991
+ first `ship` in that block refused — correctly, and at the worst possible moment. A ship
1992
+ is the *end* of a task: the code is written, the tests pass, the commit is drafted, and
1993
+ the author is then told the backlog was mis-set-up before any of it started. The fact was
1994
+ available at the `add` that opened the block, where nothing is at stake and the retry
1995
+ costs one command.
1996
+
1997
+ So the condition is exactly `ship`'s — the ledger declares no heading for this label —
1998
+ asked one task earlier, and the refusal is :class:`~roadkeep.kernel.document.UnknownBlock`
1999
+ itself, spelling the same file and the same `block add` remedy. A second sentence for one
2000
+ condition is a second thing to keep true.
2001
+
2002
+ Not a write, which is the option this deliberately does not take (RK141): `block add`
2003
+ takes the **title** because naming a block is editorial, and `add` holds a label and no
2004
+ title. A heading composed here would be one nobody looks under, and L4 forbids the tool
2005
+ inventing the words for it.
2006
+
2007
+ Silent where the project declares no ledger and where its file is not on disk yet: a
2008
+ refusal about a file nothing reads is one the author cannot act on, and `ship` on such a
2009
+ project has nothing to refuse over either.
2010
+
2011
+ **A ledger organised by nothing is asked too** — and for a week it was not (RK403,
2012
+ RK411), which is the one fact this docstring exists to keep straight. Measured on a fresh
2013
+ project whose changelog was prose: this refused and named `block add`, which answered *A
2014
+ is already declared in docs/ROADMAP.md: nothing to open*, because a file declaring no
2015
+ block is not one that verb started organising. A refusal naming a remedy that refuses is
2016
+ worse than silence, so the check was narrowed to ledgers that declare a block. RK405 gave
2017
+ that verb `--organise <role>`, the remedy exists, and the narrowing's whole reason went
2018
+ with it — restored here, and it is the premise having moved rather than a decision
2019
+ reversed. The refusal names the argument, so the author is never sent to the refusing
2020
+ command: see :class:`~roadkeep.kernel.document.UnknownBlock`.
2021
+ """
2022
+ if not config.has("changelog") or not config.path("changelog").is_file():
2023
+ return
2024
+ ledger = config.document("changelog")
2025
+ if ledger.heading(block) is not None:
2026
+ return
2027
+ raise UnknownBlock(
2028
+ block,
2029
+ sorted({heading.label for heading in ledger.headings if heading.label}),
2030
+ config.relative(config.path("changelog")),
2031
+ word=ledger.schema.heading_word,
2032
+ # The one raiser whose two files differ (RK404): the labels are the ledger's and the
2033
+ # line is the roadmap's, and unsaid that reads as the label being wrong.
2034
+ into=config.relative(config.path("roadmap")),
2035
+ # And the argument that opens a first heading, where this file has none (RK411):
2036
+ # without it this door is the one that sends the author to a refusing command.
2037
+ organise="changelog",
2038
+ )
2039
+
2040
+
2041
+ def _placement(
2042
+ document: Document, heading: Heading, rendered: str, carrying: tuple[str, ...] = ()
2043
+ ) -> tuple[int, list[str]]:
2044
+ """Where the line goes, and the lines to insert there — blank ones included.
2045
+
2046
+ After the block's last task when it has one, which needs no blank-line reasoning at
2047
+ all. An empty block does: the heading may be followed by a blank line, by the next
2048
+ heading, or by nothing, and a task glued to either side of a heading reads as
2049
+ belonging to the wrong one.
2050
+
2051
+ An empty block also carries its own prose down with it (RK108) — the paragraph that
2052
+ says what the block is for stays above the first task, because the line after the
2053
+ heading's blank is where the introduction is and not where the backlog starts.
2054
+ """
2055
+ entries = document.block(heading.label)
2056
+ if entries:
2057
+ # The last entry's *end*, not the line after its first line (RK157): a ledger entry
2058
+ # written before this tool existed wraps, and the lines under it parse as nothing —
2059
+ # so inserting one line down put the new bullet inside the previous entry and left
2060
+ # its paragraph reading as the sentence somebody else shipped. Silent, because both
2061
+ # bullets round-trip and no rule says a continuation line belongs to the bullet above.
2062
+ return entries[-1].stop, [rendered, *carrying]
2063
+
2064
+ lines = document.lines
2065
+ index = _after_preamble(document, heading)
2066
+ before: list[str] = []
2067
+ if index < len(lines) and blank(lines[index]):
2068
+ index += 1
2069
+ else:
2070
+ before = [""]
2071
+ at_end = index >= len(lines)
2072
+ after = [] if at_end or blank(lines[index]) else [""]
2073
+ return index, [*before, rendered, *carrying, *after]
2074
+
2075
+
2076
+ def _after_preamble(document: Document, heading: Heading) -> int:
2077
+ """The line past the heading's own prose — 0-based, and the heading's own line when
2078
+ there is none, which is every block in this repository and was the whole rule (RK108).
2079
+
2080
+ *Own* is the boundary the document draws (RK115): any heading ends it, because prose
2081
+ under a nested heading belongs to that heading and a line placed after it would sit
2082
+ under the wrong one. Trailing blanks are not prose, so what comes back is the blank
2083
+ that separates the paragraph from the block — which the caller then reads exactly as it
2084
+ reads the blank after a bare heading.
2085
+ """
2086
+ start = heading.lineno # 0-based: the line after the heading
2087
+ end = document.prose_end(heading)
2088
+ index = start
2089
+ for offset in range(start, end):
2090
+ if not blank(document.lines[offset]):
2091
+ index = offset + 1
2092
+ return index
2093
+
2094
+
2095
+ def _refuse_retired(config: Config, task: Task) -> None:
2096
+ """Refuse a line whose pointer names an address a ship already took (RK1177).
2097
+
2098
+ The same rule and the same reader as `section add`'s own refusal, asked one command earlier.
2099
+ Nothing is duplicated: this calls what that verb calls, so the sentence a caller gets and the
2100
+ address it recommends are the one answer — and a project whose history cannot be read is
2101
+ silent here exactly as it is there, because what is lost is a refusal and never a file.
2102
+
2103
+ Silent under ``ref_scheme = "id"``, where the pointer is the id and reuse is `refuse_reuse`'s
2104
+ question one file over — a second opinion about a closed one would fire on every `add`.
2105
+
2106
+ Only a **retired** address: a pointer at a section that exists is how every task after the
2107
+ first cites its own design, and one at an address nobody ever used is the normal case this
2108
+ tool derives.
2109
+ """
2110
+ if task.ref is None or not task.ref:
2111
+ return
2112
+ from roadkeep.sections import PROSE_ROLES, _refuse_reuse # noqa: PLC0415 - RK260
2113
+
2114
+ for role in PROSE_ROLES:
2115
+ if config.has(role):
2116
+ _refuse_reuse(config, role, task.ref, config.relative(config.path(role)))
2117
+ return