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/shipping.py ADDED
@@ -0,0 +1,3993 @@
1
+ """A line leaving the roadmap: three edits across three files, or none of them (RK6, RK32).
2
+
3
+ Shipping is the moment the format is most likely to break, because it is the only
4
+ operation that is not one edit. The line leaves the roadmap, the entry appears in the
5
+ ledger, and the rationale section is deleted — and whichever of the three is done by
6
+ hand last is the one that gets forgotten, which is how a backlog comes to have a task
7
+ that is shipped in one file and open in another.
8
+
9
+ So the three edits are one command, and the ordering is deliberate: **everything is
10
+ computed and validated in memory before any file is touched.** A refusal — no such open
11
+ task, already in the ledger, no block heading there to file it under, a file that
12
+ already drifted (L3) — costs nothing and leaves three untouched files. Writing is the
13
+ last thing that happens, and by then nothing is left that can fail except the disk.
14
+
15
+ Two decisions worth stating, because both are narrower than they could be:
16
+
17
+ * **The roadmap line is removed, not replaced by a stub.** A pointer left behind is a
18
+ second place a reader can ask about status, and the ledger is already greppable — the
19
+ answer to "did RK5 ship?" has to have exactly one home (RK7).
20
+ * **The `why` is the author's, and it is required** (RK142). The roadmap's sentence is a
21
+ problem and the ledger's is an outcome, so copying it across was writing the entry by
22
+ omission — a defect report filed under a heading meaning "done". It is refused at input
23
+ now, where every other field of every other write is already refused (L1); the tool still
24
+ never writes the sentence itself (L4), it only declines to inherit the wrong one.
25
+
26
+ The dep annotations of every line that named this task are re-derived in the same
27
+ transaction (RK8), because `(deps: RK5)` becomes a false statement at exactly the moment
28
+ this command runs and nothing else would ever revisit it.
29
+
30
+ **And the design it deletes can have been overtaken, which nothing recorded** (RK310). The
31
+ third of the three edits is a deletion, and it was silent about the one thing worth knowing:
32
+ a section is written when a task is filed and read when somebody claims it, and in between
33
+ the codebase moves. Measured in one block of eleven tasks, twice — a section proposing a
34
+ field the implementation found unnecessary, another dismissing a subsystem that had shipped
35
+ two blocks earlier. Both times the work got smaller once the design was checked against the
36
+ code, and both times `ship` then deleted the reasoning with no trace that it had been wrong.
37
+ `--superseded-design` is that trace, appended to the ledger's sentence because the entry is
38
+ already the one place the section's address and the outcome meet — and the value is the
39
+ *pattern*: a ledger where a third of the claimed designs turn out stale is a fact about how
40
+ far ahead this tool should let anybody design.
41
+
42
+ **And the half of it that was right goes somewhere, which nothing recorded either** (RK1267).
43
+ That flag types the deleted section as *stale*, and a section holds three contents with three
44
+ half-lives: the investigation, which dies with the ship; the criterion, which becomes a test;
45
+ and the decision, the constraint that stays true after the code moves. Deleting is right — a
46
+ rationale file reaching 539 KB one honest paragraph at a time is what this tool exists to
47
+ refuse — and untyped deletion is what is not: RK1265 records a definition of done written as a
48
+ section, deleted correctly, surviving nowhere, after which the block it governed was closed and
49
+ reopened six times. `--recorded-in <path>` is that trace, beside `--superseded-design` and
50
+ composed by the same writer, because the entry is where the address and the outcome already
51
+ meet. It is derived whole — the anchor is the pointer the line is losing and the destination is
52
+ a path — so it writes no prose (L4), and it is refused on a path this repository does not have,
53
+ as every other path a ledger sentence names already is (RK497). Never an archive: a flag that
54
+ copied the section into a second file is the 539 KB with better manners.
55
+
56
+ **Half of it is a state, and retiring the rest is not a verdict on the half** (RK121, RK129).
57
+ A ledger entry carrying a qualifier is the first half of *this* decision, so the departure
58
+ completes it in place — and only where the departure is a **ship**. Reaching the same code
59
+ with the retired marker replaced a `✅ **RK1 (local half)**` with a `🗑 **RK1**`, taking the
60
+ sentence about what actually landed out of the only file that held it: completing says the
61
+ rest landed too, retiring says it never will, and the second leaves the half that did ship as
62
+ history. That choice is refused back to the author rather than made silently.
63
+
64
+ **A line leaves by three doors and this module now records all three** (RK32). `ship` is
65
+ the first; :func:`retire` is the other two, superseded and abandoned, and it is the *same*
66
+ transaction with a different marker rather than a second one — because the failure being
67
+ fixed is that two of the three doors wrote nothing at all, not that they wrote it wrongly.
68
+ What survives a retirement is one line under the block it belonged to: the symptom moved
69
+ verbatim, and a `why` whose derived prefix names the replacement so the pointer is forward
70
+ and written at the moment of the decision. Never the design it replaced — an accreting
71
+ rationale file is the 539 KB this project exists to refuse.
72
+
73
+ **And the way out of the middle of one** (RK130). RK118 ordered a departure's three writes
74
+ so that every state a crash can leave is loud and lossless — the ledger first, so stopping
75
+ after it puts the id in two files and `lint` says so — and established no way out: `ship`
76
+ refused the id, :class:`Closure` wanted a marker the abandoned line does not carry, and
77
+ `record drop` wants a second entry. So the only exit was the edit the hook denies, on the
78
+ file this tool exists to own. :func:`_already_recorded` now reads the **ledger** side as well:
79
+ an entry for a line still open is a leftover unless the files say it is a live partial — a ⏳
80
+ line, or an entry naming a half. What that widening opened is refused rather than guessed: an
81
+ interrupted transaction wrote its entry from the line, so two that describe different work are
82
+ two tasks sharing an id, and `renumber` is their repair.
83
+
84
+ **A fourth door starts nowhere** (RK41). All three above begin from an open roadmap line,
85
+ so work that was finished before it was ever planned — a defect found on the way to
86
+ something else, fixed, real, shipped — has no route into the ledger except a fictitious
87
+ roadmap line shipped in the same breath. :func:`record` is that route made honest: it
88
+ writes the ledger entry and touches nothing else, which is why RK7 survives it untouched
89
+ — the line never exists open, so there is no second file to disagree with.
90
+
91
+ **And a door out of the ledger, for exactly one shape** (RK67). Every door above only ever
92
+ adds an entry, which is right for history and wrong for a duplicate: an id the ledger states
93
+ twice states one decision twice, `lint`'s `id.duplicate` reports it, and until now nothing but
94
+ the hand-edit the hook denies could act. :func:`drop` is the inverse of the door that wrote it
95
+ and refuses unless the id is there **twice** — removing the only record of a decision is
96
+ deleting history rather than de-duplicating it. The later entry goes: the first is where the
97
+ reader already found it — **and only when the two entries say the same thing** (RK127). Two
98
+ that do not are two deliveries under one id rather than one recorded twice, and the verb's
99
+ default picks exactly the wrong one of them: the entry that earned the id. So the guess is
100
+ refused and the reader chooses, either by naming the line that goes or by calling
101
+ :func:`readdress`, which gives the other delivery an address of its own. Prose that is wrong
102
+ is :func:`amend`'s, below, and an entry that should never have existed is a decision the
103
+ author states in the commit that removes it.
104
+
105
+ **And an update, because insert and delete are not one** (RK124). A `why` written under
106
+ pressure is the field most likely to be wrong, and the two doors above are not equivalent to
107
+ a correction: `drop` removes the entry and `add` appends a new one under its block, so fixing
108
+ a word **moves the line** — a ledger read in the order work landed stops being one, and a
109
+ reviewer diffing it sees a deletion and an insertion where a word changed. Worse on a shipped
110
+ entry, where `ship` wrote it from a roadmap line that no longer exists to re-derive it from.
111
+ :func:`amend` is that update, and it reaches exactly what the roadmap's own `amend` reaches:
112
+ the sentence, and never the claim. `symptom` is refused there and absent here for the same
113
+ reason, and the two fields this file adds are answered the same way — the **id** is
114
+ `renumber`'s, and the **block** is not a field at all, because filing an entry elsewhere is a
115
+ move and a flag that pretends nothing happened is the thing this verb exists to stop being.
116
+ The one addition is `part`: the qualifier of a partial (RK121) is a phrase that stops being
117
+ true, and correcting it is why that comment said `amend` all along.
118
+
119
+ **And the move that reasoning was right about, which no verb then made** (RK143). That
120
+ argument holds and what it left is a hole: `ship` derives the block from the roadmap line it
121
+ read, so a line filed under the wrong one ships to the wrong one — and from there `record add
122
+ --block` is refused for an id that exists, `drop` wants the id stated twice, `readdress`
123
+ changes the address and not the heading. So the only route left was the hand-edit the hook
124
+ denies. :func:`move` is the verb that *says* it is a move: the line is taken out and re-placed
125
+ under the named heading, **both** positions are reported because the entry does not keep its
126
+ number, and a heading the ledger does not declare is refused naming the ones it does — the
127
+ heading being `block add`'s to write (RK141). A move is what the diff shows either way, and a
128
+ command that names it is not the same as a flag that hides one inside a correction.
129
+ """
130
+
131
+ from __future__ import annotations
132
+
133
+ from collections.abc import Mapping, Sequence
134
+ from dataclasses import dataclass, replace
135
+ from pathlib import Path
136
+
137
+ from roadkeep import claiming, criteria, queueing
138
+ from roadkeep.authoring import (
139
+ Insertion,
140
+ place,
141
+ refuse_occupied,
142
+ refuse_reuse,
143
+ remove_entry,
144
+ )
145
+ from roadkeep.backlog import Backlog, NotOpen, Standing, Whereabouts
146
+ from roadkeep.config import DESIGN_ROLES, Config
147
+ from roadkeep.kernel.document import Document, Entry, Wrapped, counted, save_all
148
+ from roadkeep.ids import IdRef, next_id
149
+ from roadkeep.markers import refresh
150
+ from roadkeep.provenance import invocation
151
+ from roadkeep.remedying import Door
152
+ from roadkeep.renumbering import NotAnId, SameId, family_of
153
+ from roadkeep.kernel.schema import (
154
+ ELSEWHERE,
155
+ PARTIAL,
156
+ SchemaError,
157
+ Task,
158
+ Violation,
159
+ over_by,
160
+ width,
161
+ )
162
+ from roadkeep.sections import (
163
+ Section,
164
+ declaring,
165
+ find,
166
+ nested,
167
+ owners,
168
+ pointers,
169
+ )
170
+ from roadkeep.sections import drop as drop_section
171
+
172
+ __all__ = [
173
+ "AlreadyRecorded",
174
+ "AlreadyShipped",
175
+ "AlreadySuperseded",
176
+ "Ambiguous",
177
+ "Closure",
178
+ "Corrected",
179
+ "Departure",
180
+ "Divergent",
181
+ "Dropped",
182
+ "InheritedClaim",
183
+ "NoCompletion",
184
+ "NoDecision",
185
+ "NoDecisions",
186
+ "NoDesign",
187
+ "NoOutcome",
188
+ "NoQualifier",
189
+ "NoRestatement",
190
+ "NoSupersession",
191
+ "NoSuchEntry",
192
+ "NoSuchReplacement",
193
+ "NotDuplicated",
194
+ "NotOpen",
195
+ "NotDecided",
196
+ "NotRecorded",
197
+ "NotRedundant",
198
+ "Partial",
199
+ "PartRecorded",
200
+ "Readdressed",
201
+ "Record",
202
+ "Refiled",
203
+ "SecondPartial",
204
+ "Section",
205
+ "Superseded",
206
+ "Shipment",
207
+ "Unchosen",
208
+ "Wrapped",
209
+ "amend",
210
+ "drop",
211
+ "move",
212
+ "readdress",
213
+ "record",
214
+ "recording_cost",
215
+ "retire",
216
+ "retiring",
217
+ "ship",
218
+ "supersede",
219
+ ]
220
+
221
+
222
+ def _spelled(root: Path | None, written: Sequence[Path]) -> tuple[str, ...]:
223
+ """The paths a departure wrote, as the project spells them (RK309).
224
+
225
+ Relative, in the order they were written, because the caller feeds them to a `git add --`
226
+ from the repository root — and an absolute path is an answer about one machine, the rule
227
+ every message here already keeps. Spelled without a :class:`~roadkeep.config.Config`,
228
+ which a saved transaction no longer has: the root is what it carries for the claim, and a
229
+ path this cannot place against it is answered whole rather than dropped.
230
+ """
231
+ if root is None:
232
+ return ()
233
+ spelled: list[str] = []
234
+ for target in written:
235
+ try:
236
+ spelled.append(target.resolve().relative_to(root).as_posix())
237
+ except (OSError, ValueError): # another tree, or a path this filesystem will not place
238
+ spelled.append(target.as_posix())
239
+ return tuple(spelled)
240
+
241
+
242
+ class AlreadyRecorded(ValueError):
243
+ """A second ledger entry for one id is two records of one decision.
244
+
245
+ The message names which door the id already went through, because "already in the
246
+ changelog" sends a reader looking for a ✅ that may be a 🗑 (RK32).
247
+ """
248
+
249
+ def __init__(
250
+ self, task_id: str, where: str, lineno: int, marker: str, closable: bool = False
251
+ ) -> None:
252
+ self.task_id = task_id
253
+ self.lineno = lineno
254
+ self.marker = marker
255
+ #: Whether the closure path would take this line, which is the **only** state the
256
+ #: door below is true of (RK1045). RK1044 added the clause unconditionally and it
257
+ #: landed on the one caller it cannot help: a ⏳ line beside a full entry is refused
258
+ #: *by `ship` itself*, so the remedy named was the command that had just failed —
259
+ #: which costs a reader two more attempts before the sentence becomes the suspect.
260
+ #:
261
+ #: Nothing is invented where it is false. A live partial is deliberately outside the
262
+ #: closure path (widening it cost a task and a 224-word section), so what a caller
263
+ #: needs there is the qualifier corrected, not a fourth door composed here.
264
+ self.closable = closable
265
+ door = (
266
+ f" — `{invocation()} ship {task_id}` closes the open line against the entry "
267
+ f"that is already there, writing nothing to the ledger"
268
+ if closable
269
+ else ""
270
+ )
271
+ super().__init__(
272
+ f"{task_id} is already recorded as {marker} in {where}:{lineno}: a second "
273
+ f"entry would make the ledger disagree with itself about how it left{door}"
274
+ )
275
+
276
+
277
+ class SecondPartial(ValueError):
278
+ """A second `ship --part` against an id whose first half the ledger already holds (RK191).
279
+
280
+ :class:`AlreadyRecorded` was the answer here, and it is the right answer at the door it
281
+ was written for — an id the ledger already **closed**, where naming the entry in the way
282
+ is the whole of what a caller needs. It is not the answer here. A caller reaching this
283
+ one has work that came in more halves than one id can hold, and was told where the first
284
+ one is.
285
+
286
+ The answer exists and is not this tool's guess: Shio hit exactly this and settled it as
287
+ *a step delivered gets an id, not a share of one* (SH361), filing SH366 through SH371 as
288
+ the six steps of two tasks with each qualifier naming its parent in prose. That is also
289
+ what this refusal enforces — one partial per id, then the completion — so the check is
290
+ right and only its sentence was incomplete.
291
+
292
+ Which spelling the step takes is `roadkeep.toml`'s and not this module's (L6): where
293
+ `[ids] suffix` is declared the new line keeps the number and takes a letter, and where it
294
+ is not, it is an ordinary `add` whose `why` names the parent.
295
+ """
296
+
297
+ def __init__(
298
+ self, task_id: str, where: str, lineno: int, part: str, *, suffix: bool
299
+ ) -> None:
300
+ self.task_id = task_id
301
+ self.lineno = lineno
302
+ self.part = part
303
+ self.suffix = suffix
304
+ door = (
305
+ f"`{invocation()} add --id {task_id}b --block <x> --symptom \"…\" --why \"…\"`, this "
306
+ f"project declaring `[ids] suffix`"
307
+ if suffix
308
+ else f"`{invocation()} add --block <x> --symptom \"…\" --why \"…\"` with a `why` that "
309
+ f"names {task_id}, this project declaring no `[ids] suffix`"
310
+ )
311
+ super().__init__(
312
+ f"{task_id} already records a half in {where}:{lineno} ({part}): one id carries "
313
+ f"one partial and then the completion, so a second would be two answers about "
314
+ f"one piece of work — a step that was delivered gets an id of its own, and here "
315
+ f"that is {door}. `ship {task_id}` instead if what landed is the rest of it, and "
316
+ f"`record amend {task_id} --part \"…\"` if the qualifier stopped being true"
317
+ )
318
+
319
+
320
+ #: The names these had when shipping was the only door (RK6), kept because they read
321
+ #: better at a `ship` call site: an id can now be retired as well as shipped, and both are
322
+ #: the same refusal and the same transaction.
323
+ AlreadyShipped = AlreadyRecorded
324
+
325
+
326
+ class NoSuchPath(ValueError):
327
+ """Ledger prose naming a path this repository does not have (RK497).
328
+
329
+ The gate's `path.missing`, asked where the sentence is composed instead of after it lands
330
+ — which is L1, and the one ledger rule that was not held here. Measured at the cost the
331
+ law predicts: a `ship --why` citing a path from its own reproduction reported success,
332
+ the entry landed, the commit was made, and the finding came off an unrelated run
333
+ afterwards; repairing it took a second commit describing nothing shipped.
334
+
335
+ Refused rather than reported, and the split is the same one RK295 drew: a *scope* naming
336
+ an absent path is reported, because declaring one before the file exists is the ordinary
337
+ case, while a ledger entry is the opposite claim — the work is done, so the artefact is
338
+ there or the sentence is wrong.
339
+
340
+ Only the prose **this call** brought. What a ship inherits from the roadmap line it is
341
+ closing is somebody's earlier sentence, and `restate` is that door: refusing a ship over
342
+ it would price a correction as a shipment, and the gate still names it either way.
343
+
344
+ No fix is offered, because there is none to compute (L4): the token is either a typo, a
345
+ file that moved, or a name that should not have been in backticks — and which of the
346
+ three it is, is the thing only the author knows.
347
+ """
348
+
349
+ def __init__(self, named: str, missing: Sequence[str], file: str) -> None:
350
+ self.named = named
351
+ self.missing = tuple(missing)
352
+ spelled = ", ".join(self.missing)
353
+ super().__init__(
354
+ f"{named} names {spelled}, which {'are' if len(self.missing) > 1 else 'is'} not "
355
+ f"in the repository: {file} records work that is done, so a path it names has to "
356
+ f"resolve — the gate reports this as `path.missing` once the entry is written"
357
+ )
358
+
359
+
360
+ class NoRestatement(ValueError):
361
+ """A flag that writes the ledger's sentence, where the ledger is not written (RK62).
362
+
363
+ On the closing path the entry already exists and this command deliberately leaves it alone,
364
+ so the sentence has nothing to restate. Refused rather than dropped: a flag silently
365
+ ignored is a flag the caller believes took effect.
366
+
367
+ Three flags reach it, all of which land in that one sentence: `--why` is the sentence,
368
+ `--superseded-design` is the clause appended to it (RK310), and `--recorded-in` is the
369
+ second clause beside that one (RK1267).
370
+ """
371
+
372
+ def __init__(self, task_id: str, recorded: Entry, flag: str = "--why") -> None:
373
+ self.flag = flag
374
+ does = (
375
+ "restates the ledger's sentence"
376
+ if flag == "--why"
377
+ else "is written into the ledger's sentence"
378
+ )
379
+ super().__init__(
380
+ f"{task_id} is already recorded as {recorded.task.status} at line "
381
+ f"{recorded.lineno}, so this call only closes its roadmap line: {flag} {does}"
382
+ f", and the ledger is not written here"
383
+ )
384
+
385
+
386
+ class NoDesign(ValueError):
387
+ """A clause about the deleted design, on a line that pointed at none (RK310, RK1267).
388
+
389
+ Both clauses name the address of the rationale this shipment deletes, and a line with no
390
+ pointer has none: there is nothing that went stale and nothing being deleted, so an entry
391
+ saying either would send the next reader of the ledger looking through git for prose
392
+ nobody ever wrote.
393
+
394
+ The flag is a field because the two say different things about the same absence, and a
395
+ refusal naming the other one reads as a bug in the tool rather than as an answer.
396
+ """
397
+
398
+ #: What each flag's clause claims about the section, and where its value belongs instead.
399
+ _CLAIMS = {
400
+ "--superseded-design": (
401
+ "no design was superseded",
402
+ "the address of the rationale this shipment overtook",
403
+ "the outcome belongs in --why",
404
+ ),
405
+ "--recorded-in": (
406
+ "no design is being deleted",
407
+ "the address of the rationale whose durable half moved",
408
+ "there is nothing for the path to be the destination of",
409
+ ),
410
+ }
411
+
412
+ def __init__(self, task_id: str, flag: str = "--superseded-design") -> None:
413
+ self.task_id = task_id
414
+ self.flag = flag
415
+ absent, names, instead = self._CLAIMS[flag]
416
+ super().__init__(
417
+ f"{task_id} carries no pointer, so {absent}: {flag} names {names}, and this "
418
+ f"line never had one — {instead}"
419
+ )
420
+
421
+
422
+ class RemainderRefused(SchemaError):
423
+ """The open half's sentence, refused under the name the caller typed (RK1262).
424
+
425
+ `ship <id> --part … --why … --remainder …` validates the remainder as the reopened line's
426
+ `why`, because that is what it becomes — and the refusal then read `why: why is a sentence:
427
+ end it`. Both arguments on that command line are whys by the time the check runs, so the
428
+ message is **true and still does not say which string to fix**. Measured from a session that
429
+ had terminated its `--why` correctly, read the error as being about that argument, and got
430
+ to the right edit only by reasoning that nothing else could be wrong.
431
+
432
+ Everywhere else the field a refusal names is the flag that carried the value, which is why
433
+ this one reads as a contradiction rather than as a hint. So the violations about that field
434
+ are reported under `remainder`, and one sentence says where the rule came from — the code
435
+ stays `why.*`, being the rule that was broken and the token anything greppable keys on.
436
+
437
+ A :class:`SchemaError` subclass, so a caller catching that class keeps catching this: what
438
+ changed is what the refusal *says*, not which class of refusal it is.
439
+ """
440
+
441
+ #: The field the reopened line carries this value in, and the one being renamed.
442
+ BECOMES = "why"
443
+
444
+ def __init__(self, task_id: str, violations: tuple[Violation, ...]) -> None:
445
+ renamed = tuple(
446
+ replace(one, field="remainder") if one.field == self.BECOMES else one
447
+ for one in violations
448
+ )
449
+ super().__init__(renamed)
450
+ self.task_id = task_id
451
+ self.about = (
452
+ f"--remainder becomes {task_id}'s {self.BECOMES} when the partial lands, so it is "
453
+ f"held to that field's rules and named below as itself — the --why on this call is "
454
+ f"the ledger entry's own sentence and is not what this refuses"
455
+ )
456
+
457
+
458
+ def _elsewhere(task_id: str) -> str:
459
+ """Where a supersession note goes when the ledger sentence has no room for it (RK1330).
460
+
461
+ Both crowded refusals ended by naming what to shorten, and on the measured pair there is
462
+ nothing to shorten *to*: at the outcome's own declared aim of 28 words the note has -38
463
+ characters left even with the shortest path imaginable, so this is not a path-length
464
+ finding and no amount of cutting reaches a sentence that holds both. What the author is
465
+ really being told is that the note cannot be said here — and a refusal that names no
466
+ elsewhere reads as *do not say it*, which is how the trace gets dropped.
467
+
468
+ So the elsewhere is named, and it is the commit rather than a new field: `origin` already
469
+ answers which commit shipped a task and prints its subject, so a note put there is read
470
+ back by a verb, is not limited to what one line spares, and costs no format the parse, the
471
+ projections and the limits have to learn (which is the argument RK1261 made for keeping
472
+ the note out of a slot of its own, applied to where it lands instead).
473
+ """
474
+ # Worded to follow either branch of the room count, which is why it says nothing about how
475
+ # much is left: appended after "has 23 characters" it would contradict a sentence naming a
476
+ # number if it opened by claiming there was nowhere, and appended after "has none" it does
477
+ # not need to repeat it.
478
+ return (
479
+ f"what the design turned out to be wrong about is not lost by being said elsewhere: "
480
+ f"it goes in this ship's commit message, which `{invocation()} origin {task_id}` "
481
+ f"reads back"
482
+ )
483
+
484
+
485
+ class SupersessionCrowded(ValueError):
486
+ """A ledger sentence over its limit, reported as the field that has to survive (RK1261).
487
+
488
+ `--why` and `--superseded-design` render as one sentence and are refused as one field, so
489
+ the message named `why` and quoted a total neither argument was. Measured here: 183
490
+ characters of outcome beside 166 of supersession note answered `why: 385 characters, limit
491
+ is 200 … delete 185 characters — about 29 words`, which read literally asks for a
492
+ 15-character outcome. Read as advice it asks for the **wrong edit** — the obvious response
493
+ is to cut the outcome sentence, and that is the half the entry keeps once the design is
494
+ deleted. The note is the half that can go, and nothing in the message pointed there.
495
+
496
+ So the parts are named and the room is attributed to the one that has it. Raised only where
497
+ the composition is what overflowed: a `--why` over the allowance on its own is
498
+ `why.too-long` about the field it really is about, which is :meth:`Schema.why_budget`'s own
499
+ rule — an overrun in one field is never charged to another — applied one file over.
500
+ """
501
+
502
+ def __init__(
503
+ self,
504
+ task_id: str,
505
+ *,
506
+ authored: str,
507
+ note: str,
508
+ composed: str,
509
+ limit: int,
510
+ source: str = "",
511
+ ) -> None:
512
+ self.task_id = task_id
513
+ self.limit = limit
514
+ # Derived by subtraction rather than by re-composing the wrapper: `_parenthesised` is
515
+ # the only writer of that shape (L3's rule about one writer), and a second spelling of
516
+ # its brackets here would be the number that drifts when the clause is reworded.
517
+ structure = width(composed) - width(authored) - width(note)
518
+ room = limit - width(authored) - structure
519
+ #: What the author is being asked to do, which is the whole point of naming the parts.
520
+ # Named on both branches and not only where the room is nought (RK1330, found by
521
+ # shipping RK1330): a note that overflowed by 41 characters is not said in the 23 that
522
+ # are left, so "you have 23" is the same *do not say it* as "you have none" wearing a
523
+ # number. This class exists only because the note did not fit, and that is the whole
524
+ # condition for the elsewhere being worth naming.
525
+ edit = (
526
+ f"which has {room} characters beside this --why"
527
+ if room > 0
528
+ else "which has none beside this --why, so the outcome is what has to be shorter "
529
+ "first"
530
+ )
531
+ edit = f"{edit}. And {_elsewhere(task_id)}"
532
+ super().__init__(
533
+ f"{task_id}'s ledger sentence is "
534
+ f"{over_by(width(composed), limit, measured=composed, source=source)}, and two "
535
+ f"arguments compose it: --why took {width(authored)}, --superseded-design took "
536
+ f"{width(note)}, and parenthesising them into one sentence added {structure}. The "
537
+ f"outcome is what the entry keeps once the design is deleted, so it is the note "
538
+ f"that gives way, {edit}"
539
+ )
540
+
541
+
542
+ class RecordingCrowded(ValueError):
543
+ """A ledger sentence over its limit because the recording clause joined it (RK1267).
544
+
545
+ :class:`SupersessionCrowded`'s sibling with the giving-way half swapped, and that is the
546
+ whole difference: there the note is the author's and can be cut, and here the clause is an
547
+ address and a path — derived whole, so nothing in it is prose anybody can shorten. So the
548
+ outcome is what has to give, and the message says so rather than quoting a total neither
549
+ argument is and leaving the author to guess which end to cut.
550
+
551
+ Raised only where the composition is what overflowed, for the reason that one is: a `--why`
552
+ already over its allowance is `why.too-long` about the field it is really about.
553
+ """
554
+
555
+ def __init__(
556
+ self,
557
+ task_id: str,
558
+ *,
559
+ outcome: str,
560
+ clause: str,
561
+ composed: str,
562
+ limit: int,
563
+ source: str = "",
564
+ note: str | None = None,
565
+ authored: str | None = None,
566
+ ) -> None:
567
+ self.task_id = task_id
568
+ self.limit = limit
569
+ # `outcome` is what the recording clause was appended to, which is the `--why` only
570
+ # when no note was typed. With one it is the *composition*, and reporting its room as
571
+ # what "the outcome" has offered a figure 45 characters too generous on the measured
572
+ # case: a `--why` written to the number printed came back refused with the same number
573
+ # printed again, a fixed point no retry converges on (RK1331). So what the note and
574
+ # its brackets spend is taken off before the room is attributed to the field named.
575
+ spent = 0 if authored is None else width(outcome) - width(authored)
576
+ room = limit - (width(composed) - width(outcome)) - spent
577
+ # The pair reaches here and not :class:`SupersessionCrowded` whenever the supersession
578
+ # fitted and the recording is what tipped it (RK1330): the note is the half that can
579
+ # move, so where it moves to is said here too.
580
+ moves = f". And {_elsewhere(task_id)}" if note else ""
581
+ beside = (
582
+ f", and this --superseded-design a further {spent}" if note and spent else ""
583
+ )
584
+ super().__init__(
585
+ f"{task_id}'s ledger sentence is "
586
+ f"{over_by(width(composed), limit, measured=composed, source=source)}, and the "
587
+ f"recording clause is derived whole: {clause} spends "
588
+ f"{width(composed) - width(outcome)} of it, and none of that is prose to cut"
589
+ f"{beside}. So the outcome is what gives way, which has {max(room, 0)} characters "
590
+ f"here{moves}"
591
+ )
592
+
593
+
594
+ class NoDecisions(KeyError):
595
+ """`--decides` on a project that declares no decisions file (RK1269).
596
+
597
+ Refused and never scaffolded on the way past, which is `defer`'s rule about the deferred
598
+ store and its reason: a governed file invented at the moment one is needed is a format
599
+ decided by a verb, and the door that writes one is `declare`. So the refusal names it, and
600
+ the sentence the caller just composed is the one thing that has to be retyped — which is
601
+ why it is refused **before** the ledger is read and not after the entry lands.
602
+ """
603
+
604
+ def __init__(self, task_id: str, where: str, outlined: bool = False) -> None:
605
+ self.task_id = task_id
606
+ # The whole path and never a stair per call (RK1198, RK1205), which is what `outlined`
607
+ # buys (RK1363): on such a project the retry after `declare` is refused again, for a
608
+ # second fact — the body's address — and a caller told only the first half runs the
609
+ # same command twice to learn the second.
610
+ lands = (
611
+ "and then this call lands"
612
+ if not outlined
613
+ else (
614
+ f"and then this call lands with `--decides-ref <anchor>` beside it — this "
615
+ f"project numbers its own headings, so a decision addresses its body by an "
616
+ f"anchor nothing derives and `{invocation()} anchors --role decisions "
617
+ f"--next` names a free one"
618
+ )
619
+ )
620
+ super().__init__(
621
+ f"{where} declares no decisions file, so {task_id} has nowhere to record what "
622
+ f"outlives it: `{invocation()} declare decisions` opens the role and writes the "
623
+ f"file with this project's own block headings, {lands}"
624
+ )
625
+
626
+
627
+ class DecidesUnaddressed(ValueError):
628
+ """`--decides` under an outline, with nowhere for the record's body to go (RK1363).
629
+
630
+ `add --ref`'s own refusal one verb over, and filed for the reason that one was: a project
631
+ whose anchors are addresses derives none, so a record written without one is a record
632
+ whose body `section add` can never bind — it resolves an outline anchor's owner through
633
+ the pointer, and there is no verb that adds a pointer to a decision after the fact.
634
+
635
+ The whole path, because the address is a read this refusal can make for the caller and
636
+ the argument's place in the call is not obvious: `anchors --role decisions --next` is
637
+ where a free one comes from, and the retry is this same ship with one flag more.
638
+ """
639
+
640
+ def __init__(self, task_id: str, where: str) -> None:
641
+ self.task_id = task_id
642
+ super().__init__(
643
+ f'{where} numbers its own headings (ref_scheme = "outline"), so a decision '
644
+ f"addresses its body by an anchor nothing derives: `{invocation()} anchors "
645
+ f"--role decisions --next` names a free one, and `--decides-ref <anchor>` on "
646
+ f"this same call files the record pointing at it — then `{invocation()} section "
647
+ f"add <anchor> --role decisions --title …` writes what was weighed"
648
+ )
649
+
650
+
651
+ class DecidesDerived(ValueError):
652
+ """`--decides-ref` on a project whose anchors are ids (RK1363).
653
+
654
+ `add --ref`'s `ref.mismatch` one verb over: the anchor is the id, so a pointer chosen by
655
+ hand is a second answer to a settled question — and accepting it would let one project
656
+ address a decision's body two ways.
657
+ """
658
+
659
+ def __init__(self, task_id: str, anchor: str) -> None:
660
+ self.task_id = task_id
661
+ super().__init__(
662
+ f"the decision's body is addressed by its own id (§{task_id}), so --decides-ref "
663
+ f"{anchor!r} names a section chosen by hand: drop it, or set ref_scheme = "
664
+ f'"outline"'
665
+ )
666
+
667
+
668
+ class DecidesAlone(ValueError):
669
+ """`--decides-ref` with no `--decides` (RK1363).
670
+
671
+ Refused rather than ignored, which is `NoQualifier`'s rule and `--remainder`'s: a flag
672
+ accepted where it can take no effect is a flag the caller believes took one, and this one
673
+ would have addressed the body of a record the call is not writing.
674
+ """
675
+
676
+ def __init__(self, task_id: str) -> None:
677
+ self.task_id = task_id
678
+ super().__init__(
679
+ f"--decides-ref is where {task_id}'s decision keeps its body, and this call "
680
+ f"files no decision: pass --decides \"<the constraint>\" beside it, or drop it"
681
+ )
682
+
683
+
684
+ class InheritedClaim(SchemaError):
685
+ """A decision refused over the claim it inherited, and the two doors that are real (RK1281).
686
+
687
+ `ship --decides` composes the decision from the task's own claim and the author's sentence,
688
+ which is right: a decision is *about* the problem the line stated, and restating it would
689
+ be the second sentence RK142 refuses to inherit one file over. What it inherits with it is
690
+ the claim's **length**, measured against a limit the caller cannot reach — and the refusal
691
+ then offered the remedy every symptom overrun gets, which is to put the remainder in the
692
+ rationale section. That section is the one this ship is deleting.
693
+
694
+ So the refusal stands and its door changes. Two are real: `restate` rewrites the claim in
695
+ both files, and a wider `[limits.decisions] symptom` says the decisions file takes what the
696
+ roadmap already does. Neither is composed here — which of them is right depends on whether
697
+ the claim or the limit was wrong, and that is a judgement (L4).
698
+
699
+ A :class:`SchemaError` subclass, so a caller catching that class keeps catching this: what
700
+ changed is what the refusal *says*, and never which class of refusal it is.
701
+ """
702
+
703
+ def __init__(self, task_id: str, refused: SchemaError, where: str) -> None:
704
+ # The clause the schema appends is removed **by identity** (RK1285): `ELSEWHERE` is
705
+ # the one writer of it, so a rewording moves both ends at once — and here it is
706
+ # false, which is the case that made it a constant. `RemainderRefused`'s shape at the
707
+ # other end of the same message: there the field named was wrong, here the door is.
708
+ super().__init__(
709
+ tuple(
710
+ replace(one, message=one.message.removesuffix(ELSEWHERE))
711
+ if one.field == "symptom"
712
+ else one
713
+ for one in refused.violations
714
+ )
715
+ )
716
+ self.task_id = task_id
717
+ self.about = (
718
+ f"--decides writes no symptom: {task_id}'s claim is the roadmap line's, carried "
719
+ f"into {where} whole, so the remainder cannot go in the rationale section this "
720
+ f"ship is deleting. Either `restate {task_id} --symptom \"…\"`, which rewrites "
721
+ f"the claim in both files, or declare a wider limit — `{invocation()} govern "
722
+ f"limits.symptom <n> --role decisions` takes the reading first"
723
+ )
724
+
725
+
726
+ class NoDecision(ValueError):
727
+ """`--decides` on a `ship --part` (RK310's refusal, one file over — RK1269).
728
+
729
+ A partial keeps its section, so nothing has been deleted and there is no reading of the
730
+ design that survived it. The completion is the call that deletes, and it is the one that
731
+ knows which constraint outlived the code.
732
+ """
733
+
734
+ def __init__(self, task_id: str, part: str) -> None:
735
+ self.task_id = task_id
736
+ self.part = part
737
+ super().__init__(
738
+ f"a partial keeps {task_id}'s design, so nothing has outlived it yet: pass "
739
+ f"--decides on the `ship {task_id}` that completes ({part}), which is the call "
740
+ f"that deletes the section"
741
+ )
742
+
743
+
744
+ class NoSupersession(ValueError):
745
+ """A clause about a deleted design, on a `ship --part` (RK310, RK1267).
746
+
747
+ A partial keeps its section, because the design still has work left to describe (RK121).
748
+ So a premise that turned out stale is not yet settled: what the rest of the work reads
749
+ the design for may still be right, and the completion is the moment the whole of it is
750
+ known — and the same holds of where the durable half went, which is not decided while the
751
+ section is still being read. Refused rather than carried, there being no second entry for
752
+ the clause to be corrected onto.
753
+ """
754
+
755
+ def __init__(self, task_id: str, part: str, flag: str = "--superseded-design") -> None:
756
+ self.task_id = task_id
757
+ self.part = part
758
+ self.flag = flag
759
+ super().__init__(
760
+ f"a partial keeps {task_id}'s design, because the rest of the work still reads "
761
+ f"it: pass {flag} on the `ship {task_id}` that completes ({part}), "
762
+ f"which is the call that deletes the section"
763
+ )
764
+
765
+
766
+ class NoOutcome(ValueError):
767
+ """A ledger entry that would inherit the roadmap's problem statement (RK142).
768
+
769
+ A roadmap line states a problem; that is what it is for. A ledger entry states an
770
+ **outcome**: what now works. This transaction used to bridge the two by copying the
771
+ `why` across verbatim unless `--why` said otherwise, so the default was the wrong genre
772
+ — and the default is what an author who does not know about the flag gets. Measured in
773
+ Claude Code Tray: a shipped entry reading *"`UsageSample` and `PaceSnapshot` carry four
774
+ numbers and none is overage"*, a defect report filed under a heading meaning "done".
775
+
776
+ Refused at input, which is where every other field of every other write is already
777
+ refused (L1). It is the one field that was accepted silently when it was merely the
778
+ wrong sentence — and one argument at the moment the author still has the context beats
779
+ a correction made later by somebody who does not.
780
+ """
781
+
782
+ def __init__(self, task_id: str, why: str) -> None:
783
+ self.task_id = task_id
784
+ self.why = why
785
+ super().__init__(
786
+ f"{task_id} needs the outcome it shipped: the roadmap's sentence states the "
787
+ f"problem ({why[:60]}…) and the ledger's states what now works, so it is not "
788
+ f"inherited — pass --why \"…\" while you still have the context to write it"
789
+ )
790
+
791
+
792
+ class Divergent(ValueError):
793
+ """A roadmap line and a ledger entry for one id that describe different work (RK130).
794
+
795
+ The reading that opened when closing a still-open line became possible. A transaction
796
+ that stopped after its ledger write wrote that entry **from** this line, so the two state
797
+ the same symptom; two that do not are two tasks that were never one — the merge RK97 is
798
+ about, where one branch shipped under an id another branch had spent.
799
+
800
+ Closing that would delete a roadmap line and its rationale section on the strength of an
801
+ entry describing something else, which is a loss no crash caused. `renumber` is the
802
+ repair, and it is the one this refusal names.
803
+ """
804
+
805
+ def __init__(
806
+ self, task_id: str, roadmap: str, line: int, ledger: str, entry: int
807
+ ) -> None:
808
+ self.task_id = task_id
809
+ super().__init__(
810
+ f"{roadmap}:{line} and {ledger}:{entry} both carry {task_id} and describe "
811
+ f"different work: an interrupted transaction writes its entry from the line, so "
812
+ f"the two would match — these are two tasks sharing an id, and "
813
+ f"`{invocation()} renumber {task_id}` gives the open one an address of its own"
814
+ )
815
+
816
+
817
+ class PartRecorded(ValueError):
818
+ """A retirement against a task whose half the ledger already records (RK129).
819
+
820
+ RK121 gave the departure a completion path: an entry carrying a qualifier is not a second
821
+ record of one decision, it is the *first half* of this one, so it is replaced rather than
822
+ added to. That is right for `ship`, whose entry describes the whole of the work the
823
+ partial described part of.
824
+
825
+ `retire` reached the same code with a different marker, and there replacing is a
826
+ **deletion**: `✅ **RK1 (local half)**` became `🗑 **RK1** — abandoned: …`, and the
827
+ sentence describing what actually shipped left the only file whose job is to answer what
828
+ happened to this. The two are not one decision — completing says *the rest landed too*
829
+ and superseding that sentence is honest; retiring says *the rest never will*, which
830
+ leaves the half that did ship as history, the kind :func:`drop` refuses to remove even
831
+ when the id is stated twice.
832
+
833
+ So the choice is handed back rather than made silently, which is the whole defect: the
834
+ current behaviour made it, and made it in the direction that loses work.
835
+
836
+ **What it named was not a door** (RK1138). Observed on Shio's `SH698`: an intermittent red
837
+ was instrumented, the cure refuted, the remainder abandoned — and the hint sent the author
838
+ to `record amend --part`, which restates the entry and leaves this refusal exactly as it
839
+ was, because the entry still exists. Three shapes for a real door were measured and each is
840
+ blocked by a rule this project keeps: a **second entry** is the gate's own `id.duplicate`;
841
+ **appending a sentence** to the entry's `why` is `why.sentences`, the ledger holding one
842
+ sentence per outcome; and appending *inside* it would be this tool rewriting somebody's
843
+ prose (L4). The qualifier has room for neither the reason nor the fact.
844
+
845
+ So the exit is the completion, and the message now says so as the intended one. `ship <id>
846
+ --why "…"` replaces the qualified entry with **the author's own sentence** and drops the
847
+ qualifier — which is where "and the rest was abandoned" belongs, because ✅ marks the line
848
+ leaving by the delivering door and something here did deliver. 🗑 would say nothing ever
849
+ did, which is the other direction's lie and the one RK129 refuses.
850
+ """
851
+
852
+ def __init__(
853
+ self, task_id: str, where: str, lineno: int, part: str, marker: str
854
+ ) -> None:
855
+ self.task_id = task_id
856
+ self.lineno = lineno
857
+ self.part = part
858
+ super().__init__(
859
+ f"{where}:{lineno} already records {marker} {task_id} ({part}), and retiring "
860
+ f"{task_id} would replace that entry: the half that shipped would leave the only "
861
+ f"file that holds it. An entry holds one outcome per id, so an abandonment cannot "
862
+ f"be a second one — `{invocation()} ship {task_id} --why \"…\"` is the exit, and "
863
+ f"its sentence is where the rest being abandoned is recorded: the qualifier goes, "
864
+ f"and {marker} stays because this line left by the door something did deliver "
865
+ f"through"
866
+ )
867
+
868
+
869
+ class NotRedundant(ValueError):
870
+ """Two entries for one id that are not one entry twice (RK127).
871
+
872
+ `drop` reads "duplicate" as "the same work recorded again", which holds when it is a
873
+ slip. Shio's `SH347` is the other kind: one entry records an unplanned fix and ends by
874
+ naming what it left open, the other records exactly that, shipped later — two true
875
+ entries, two deliveries, one id, because the first was written by hand before there was
876
+ a verb to give unplanned work an id of its own. Dropping either destroys a delivery, and
877
+ the one the verb picked is the entry that actually earned the id.
878
+
879
+ So the guess is refused rather than defaulted. What the tool can read is whether the two
880
+ entries state the same thing; what it cannot read is whether two that differ are one
881
+ correction or two deliveries, and both doors out of that are the caller's: `--line` says
882
+ which entry goes, and `record renumber` says this one is different work.
883
+ """
884
+
885
+ def __init__(self, task_id: str, where: str, linenos: tuple[int, ...]) -> None:
886
+ self.task_id = task_id
887
+ self.linenos = linenos
888
+ lines = ", ".join(str(n) for n in linenos)
889
+ super().__init__(
890
+ f"{where} states {task_id} at {lines}, and those entries do not say the same "
891
+ f"thing: two entries for one id can be one slip or two deliveries, and only a "
892
+ f"reader knows which — `record drop {task_id} --line <n>` removes the one you "
893
+ f"name, `record renumber {task_id} --line <n>` gives the other its own address"
894
+ )
895
+
896
+
897
+ class Unchosen(ValueError):
898
+ """A re-addressing that did not say which of the entries moves (RK127).
899
+
900
+ There is no default to fall back on, and that absence is the point: the entry that
901
+ earned the id from a roadmap line is the one to leave alone, and nothing in the file
902
+ says which that is. So the candidates are named and the caller picks.
903
+ """
904
+
905
+ def __init__(self, task_id: str, where: str, linenos: tuple[int, ...]) -> None:
906
+ self.task_id = task_id
907
+ self.linenos = linenos
908
+ lines = ", ".join(str(n) for n in linenos)
909
+ super().__init__(
910
+ f"{where} states {task_id} at {lines} and which of them moves is yours to say: "
911
+ f"pass --line <n>, leaving the entry the rest of the repository already names"
912
+ )
913
+
914
+
915
+ class NoSuchEntry(KeyError):
916
+ """A line number that is not one of the entries for this id (RK127).
917
+
918
+ Named rather than ignored, because the caller is choosing between two lines they were
919
+ just shown: an off-by-one that silently fell back to "the later one" would be the same
920
+ guess this door exists to stop making.
921
+ """
922
+
923
+ def __init__(self, task_id: str, lineno: int, linenos: tuple[int, ...]) -> None:
924
+ self.task_id = task_id
925
+ self.lineno = lineno
926
+ lines = ", ".join(str(n) for n in linenos)
927
+ super().__init__(
928
+ f"line {lineno} is not an entry for {task_id} (it is at {lines})"
929
+ )
930
+
931
+
932
+ class NotDuplicated(ValueError):
933
+ """`drop` against an id the ledger does not state twice (RK67).
934
+
935
+ The narrow condition is this door's whole safety: de-duplicating is the one removal that
936
+ cannot lose a decision, because the decision stays on the line the reader already found.
937
+ So the message names the count it *did* find — "not a duplicate" reads as "no such entry"
938
+ when it is one entry, which is the case where the author has to hear the difference.
939
+ """
940
+
941
+ def __init__(self, task_id: str, where: str, linenos: tuple[int, ...]) -> None:
942
+ self.task_id = task_id
943
+ self.linenos = linenos
944
+ found = f"once, at line {linenos[0]}" if linenos else "nowhere"
945
+ super().__init__(
946
+ f"{task_id} is in {where} {found}: this removes the later of two entries for one "
947
+ f"id, and the only record of a decision is history rather than a duplicate"
948
+ )
949
+
950
+
951
+ class NotRecorded(KeyError):
952
+ """An id the ledger does not carry, at the one door that only reads the ledger (RK124).
953
+
954
+ Distinct from :class:`~roadkeep.backlog.NotOpen`, which is about the roadmap: a caller
955
+ correcting an entry is holding the ledger's own address, and being told "not open" would
956
+ send them to the file where it correctly is not.
957
+ """
958
+
959
+ def __init__(self, task_id: str, where: str, *, open_line: bool) -> None:
960
+ self.task_id = task_id
961
+ elsewhere = (
962
+ " — it is an open roadmap line, and `amend` is the verb for one"
963
+ if open_line
964
+ else ""
965
+ )
966
+ super().__init__(f"{task_id} is not in {where}{elsewhere}")
967
+
968
+
969
+ class Ambiguous(ValueError):
970
+ """A write against a single entry, on an id the ledger states twice (RK124, RK143).
971
+
972
+ Refused rather than applied to one of them: which entry a `--why` — or a `--to-block` —
973
+ was written about is the one thing this transaction cannot read, and the two may be two
974
+ different pieces of work sharing an id (RK127). `record drop` is the door for a real
975
+ duplicate; a reader who has two decisions here needs to decide that first.
976
+
977
+ Shared by both doors that address one entry by its id alone, and the reason neither takes
978
+ a `--line` the way `drop` and `readdress` do: there the choice *is* the fix, and here two
979
+ entries under one id is a defect to resolve before either of them is rewritten.
980
+ """
981
+
982
+ def __init__(self, task_id: str, where: str, linenos: tuple[int, ...]) -> None:
983
+ self.task_id = task_id
984
+ self.linenos = linenos
985
+ lines = ", ".join(str(n) for n in linenos)
986
+ super().__init__(
987
+ f"{where} states {task_id} at {len(linenos)} lines ({lines}): which of them "
988
+ f"this call is about is not a fact any file holds — de-duplicate it first"
989
+ )
990
+
991
+
992
+ class NoQualifier(ValueError):
993
+ """`--part` against an entry that records a whole shipment (RK121, RK124).
994
+
995
+ The qualifier is written by `ship --part` and removed by the completion, so this door
996
+ only ever *corrects* the phrase. Adding one here would make an entry claim a partial
997
+ delivery while the roadmap line it was written from is gone or closed.
998
+ """
999
+
1000
+ def __init__(self, task_id: str, lineno: int) -> None:
1001
+ self.task_id = task_id
1002
+ super().__init__(
1003
+ f"{task_id} at line {lineno} carries no qualifier, so there is none to "
1004
+ f"correct: `ship --part` is what writes one, on a line that is still open"
1005
+ )
1006
+
1007
+
1008
+ class NoCompletion(ValueError):
1009
+ """`--lines` on a ship that replaces no entry (RK193).
1010
+
1011
+ The count is the caller saying they read the span a write deletes, so it is only ever
1012
+ about the partial entry a completion rewrites. On every other path `ship` *places* a new
1013
+ entry and deletes nothing, and a count accepted there is a flag the caller believes took
1014
+ effect — the reason `--why` is refused on the closure path rather than ignored.
1015
+
1016
+ **Two sentences, because the paths here are two states** (RK1128). Where the ledger holds
1017
+ nothing to replace, naming that is the answer. Where the call still passes `--part` it is
1018
+ not a completion *whatever the ledger holds*, and reporting the ledger as empty sent a
1019
+ caller to look for an entry that was there: measured in Turing, `ship T898 --part … --lines
1020
+ 1` answered "records no partial for T898" over a `**T898 (the lint half)**` on line 693, and
1021
+ dropping the flag produced the refusal that names the real rule. So the narrower sentence is
1022
+ said at the narrower door, which is the shape every refusal here already takes.
1023
+ """
1024
+
1025
+ def __init__(self, task_id: str, where: str, *, also_part: bool = False) -> None:
1026
+ self.task_id = task_id
1027
+ because = (
1028
+ f"this call passes --part, so it is not one: a half is **placed** and nothing is "
1029
+ f"deleted whatever {where} holds — `ship {task_id}` with no --part is the "
1030
+ f"completion a count belongs to"
1031
+ if also_part
1032
+ else f"this call replaces none: {where} records no partial for {task_id}, so the "
1033
+ f"entry is placed and nothing is deleted"
1034
+ )
1035
+ super().__init__(f"--lines says how many lines a completion replaces, and {because}")
1036
+
1037
+
1038
+ class NoSpan(ValueError):
1039
+ """`--lines` on the `--supersedes` pointer, which no longer replaces a span (RK1053).
1040
+
1041
+ :class:`NoCompletion`'s shape one write over, and refused for its reason rather than
1042
+ ignored: a count accepted where nothing is deleted is a flag the caller believes took
1043
+ effect. What changed is the write beneath it. The forward pointer is appended to the
1044
+ `why`, which is the text of the entry's **first** line, so re-rendering that line
1045
+ reproduces every field the task holds — and the span the count used to authorise was
1046
+ prose the parse never held, deleted by a call that asked to add a pointer.
1047
+
1048
+ So the flag is not merely unnecessary here, it is a claim about a deletion that cannot
1049
+ happen, and the refusal says so rather than leaving a caller to assume it mattered.
1050
+ """
1051
+
1052
+ def __init__(self, task_id: str, where: str) -> None:
1053
+ self.task_id = task_id
1054
+ super().__init__(
1055
+ f"--lines says how many lines a write replaces, and the forward pointer onto "
1056
+ f"{task_id} replaces none: it is appended to the sentence on that entry's "
1057
+ f"first line at {where}, and the lines under it are left where they are"
1058
+ )
1059
+
1060
+
1061
+ class AlsoPaused(ValueError):
1062
+ """A departure for an id the deferred store still carries (RK1081).
1063
+
1064
+ Neither door removes the other file's line, so `ship` and `retire` both *succeeded* here
1065
+ and left the work recorded as shipped — or retired — and still set aside, with the gate
1066
+ calling that tree clean. Two files answering differently about one id is what
1067
+ :class:`AlreadyRecorded` refuses one pair over, and the store was the pair RK96 added and
1068
+ nothing widened for.
1069
+
1070
+ Refused rather than made to remove the store entry, which is the same choice `ship`
1071
+ makes about a second ledger entry: a departure writes the files its own transaction is
1072
+ about, and reconciling a contradiction is a decision with its own verb. `resume` is that
1073
+ verb since RK1081 — the roadmap already says the work is open, so the store's copy is
1074
+ the stale half — and this refusal names it.
1075
+ """
1076
+
1077
+ def __init__(self, task_id: str, where: str, lineno: int) -> None:
1078
+ self.task_id = task_id
1079
+ self.lineno = lineno
1080
+ super().__init__(
1081
+ f"{task_id} is also set aside in {where}:{lineno}: leaving it now would record "
1082
+ f"the work as gone while the store still says it is paused — "
1083
+ f"`{invocation()} resume {task_id}` removes the store's copy first, placing no "
1084
+ f"line, because the roadmap already carries one"
1085
+ )
1086
+
1087
+
1088
+ class NoSuchReplacement(KeyError):
1089
+ """A forward pointer to an id no file holds, or to the retiring line itself (RK32).
1090
+
1091
+ Refused, because a pointer to nothing is the exact defect this records against: the
1092
+ reader of the gap would be sent somewhere else that does not explain it either.
1093
+
1094
+ *No file* is three of them (RK244). An id that was set aside is findable — the store is
1095
+ a file and `resume` brings the line back — so reading only the roadmap and the ledger
1096
+ refused the supersession most worth recording, and did it by saying "in neither file"
1097
+ about a line that was in one.
1098
+ """
1099
+
1100
+ def __init__(self, replacement: str, task_id: str, *, itself: bool = False) -> None:
1101
+ if itself:
1102
+ where = f"{replacement} is {task_id}, and a line cannot replace itself"
1103
+ else:
1104
+ where = (
1105
+ f"{replacement} is in none of the three files this reads — not the "
1106
+ f"roadmap, not the ledger, not the deferred store"
1107
+ )
1108
+ super().__init__(
1109
+ f"{where}, so it cannot be what replaces {task_id}: retire it against an "
1110
+ f"id that exists, or as abandoned"
1111
+ )
1112
+
1113
+
1114
+ @dataclass(frozen=True, slots=True)
1115
+ class Departure:
1116
+ """Every edit one line's departure makes, as data, before or after it is written.
1117
+
1118
+ One shape for both doors (RK6, RK32): the marker is the only thing that differs, and a
1119
+ second dataclass would be a second place to add the next field to.
1120
+ """
1121
+
1122
+ task_id: str
1123
+ ledger: Insertion
1124
+ roadmap: Document
1125
+ removed_from: int
1126
+ #: The prose file this drop rewrote — **whichever role declared the anchor** (RK196), so
1127
+ #: it carries its own path and a caller naming the improvements file would be guessing.
1128
+ prose: Document | None = None
1129
+ dropped: Section | None = None
1130
+ #: Why nothing was dropped, when nothing was: a task can ship without a rationale
1131
+ #: section, and silence about that would read as a section that was deleted.
1132
+ kept: str | None = None
1133
+ #: The anchors that went with it, nested under the one named (RK78). Reported because a
1134
+ #: drop is a subtree, and a transaction that says "one section" about five is one whose
1135
+ #: size the author only learns from the diff.
1136
+ nested: tuple[str, ...] = ()
1137
+ #: Sections whose prose cited what this drop deleted (RK206). Named and never refused:
1138
+ #: the ship is right and the citing prose is the author's next edit, in this commit.
1139
+ cited: tuple[str, ...] = ()
1140
+ #: The parent anchor this drop left with no subsections (RK400), or None. The one thing
1141
+ #: a ship leaves standing that nothing named: an introduction to children that have all
1142
+ #: shipped, in the present tense, and the first thing anyone reads about that family.
1143
+ emptied: str | None = None
1144
+ #: Open lines whose `(deps: …)` this write made true again (RK8).
1145
+ refreshed: tuple[str, ...] = ()
1146
+ #: The marker the ledger line carries: ✅ shipped, 🗑 retired.
1147
+ marker: str = ""
1148
+ #: What the deleted design turned out to have been wrong about (RK310), as the author
1149
+ #: wrote it — the clause this transaction appended to the ledger's sentence. `None` on
1150
+ #: every ordinary shipment, which is the ordinary case: the design held.
1151
+ superseded: str | None = None
1152
+ #: Where the deleted design's durable half now lives (RK1267), as the path the caller
1153
+ #: named. Beside the field above and not inside it: one says the reasoning was wrong and
1154
+ #: the other says where the part that was right went, and a shipment may report both.
1155
+ recorded_in: str | None = None
1156
+ #: The line this departure filed into the decisions role (RK1269), or `None`. An
1157
+ #: :class:`Insertion` and not the sentence, because it is a **write** and the answer owes a
1158
+ #: file and a line for it exactly as it does for the ledger's.
1159
+ decided: Insertion | None = None
1160
+ #: The priority entry this departure took out with the line (RK327), or `None` where the
1161
+ #: queue never named it. Removed inside the same rewrite rather than reported, because it
1162
+ #: is derived dead by the departure — unlike :attr:`dependents` and :attr:`cited`, which
1163
+ #: are somebody else's lines and somebody else's prose.
1164
+ dequeued: str | None = None
1165
+ #: The leads of this task's own criteria list, which left with the line (RK1268). Empty on
1166
+ #: every departure of a task nobody wrote one for, which is the ordinary case.
1167
+ unmet: tuple[str, ...] = ()
1168
+ #: Open lines that still name this id. Reported and not refused: a supersession is
1169
+ #: legitimate and those lines are the author's next edit, which `lint` (RK14) gates.
1170
+ dependents: tuple[str, ...] = ()
1171
+ #: The role whose file holds `--superseded-by`'s target — `roadmap`, `changelog` or
1172
+ #: `deferred` (RK244). In the answer and never in the ledger line: a paused replacement
1173
+ #: is a supersession waiting on a `resume`, which the retired line's id alone cannot
1174
+ #: say, and a prefix saying it would go stale the moment the pause ends.
1175
+ replacement_in: str | None = None
1176
+ #: **The id that role is about** (RK1170). Set with the field above and for its reason: the
1177
+ #: two are halves of one fact, and the record held only the second — so both registers read
1178
+ #: the id back off argv, which is a verb answering about a call rather than a transaction.
1179
+ replacement: str | None = None
1180
+ #: The checkout, so the claim on a line that left for good is released (RK162) — the one
1181
+ #: thing this transaction touches that is not a governed file.
1182
+ root: Path | None = None
1183
+ #: What the working tree holds, split by whose claim names it (RK294) — read **before**
1184
+ #: :meth:`save` releases this line's claim, and `None` where no live claim declared a
1185
+ #: path. Reported and never refused: a loose path is a legitimate state, and a departure
1186
+ #: that failed over one would be an obstacle at the moment the author cannot route around
1187
+ #: it — the direction :func:`_drop_section` already chooses.
1188
+ scope: claiming.Scope | None = None
1189
+
1190
+ def save(self) -> tuple[str, ...]:
1191
+ """Write the files, and answer which ones (RK309). Nothing here can fail on the
1192
+ format — that was decided.
1193
+
1194
+ What can still fail is the disk: all three files are rendered to their scratch
1195
+ names, then asked whether they are still the files that were read, and only then
1196
+ renamed into place (RK116, RK131), each write landing whole (RK118). Three renames
1197
+ are still three moments, so **the order is the rest of the answer** — it decides
1198
+ which halfway states a crash can leave:
1199
+
1200
+ * **Ledger first**, because it is the only one of the three that records that this
1201
+ shipped. Stopping here leaves the id in two files, which `lint` reports as
1202
+ `id.two-files`. Reversed, stopping after the roadmap would remove the line while
1203
+ nothing recorded where it went — the task simply gone, and no gate able to say so,
1204
+ because a roadmap with one fewer line is a roadmap.
1205
+ * **Roadmap second.** Stopping here leaves a rationale section nothing points at,
1206
+ which `lint` reports as an orphan (RK15) and `section drop` removes.
1207
+ * **The rationale file last**, because its write is the only *deletion*. Earlier, it
1208
+ would take the design out while the line still named it: a pointer to nothing, and
1209
+ prose recoverable only from git.
1210
+
1211
+ So the bar every reachable middle state clears is the same one: **loud and
1212
+ lossless** — every file still holds what it held, and the gate names the state.
1213
+ Nothing here claims the three writes are one; what is claimed is that stopping
1214
+ between them costs a command and never a design.
1215
+
1216
+ **What it answers is which paths it wrote** (RK309), the projections RK188 refreshed
1217
+ included, because that is the half of a commit's contents no author should have to
1218
+ declare: a scope is what the holder *said* (RK280) and this is what the tool *did*.
1219
+ Read off :func:`~roadkeep.kernel.document.save_all`'s own return and never rebuilt from the
1220
+ config — a second list of the files a transaction touches is one that can be wrong.
1221
+ """
1222
+ # The decisions line goes **second**, between the two records and before the deletion
1223
+ # (RK1269): it is the only trace of what the section held that outlives the code, so a
1224
+ # crash after the roadmap or the prose write would take it with the design it survived.
1225
+ written = save_all(
1226
+ self.ledger.document,
1227
+ None if self.decided is None else self.decided.document,
1228
+ self.roadmap,
1229
+ self.prose,
1230
+ )
1231
+ if self.root is not None:
1232
+ # Last, and never a condition of the writes: a terminal marker is not the
1233
+ # in-progress one, so the rule every marker write obeys says *release* (RK162).
1234
+ # The entry is inert either way — an id is never reused — but a row that can never
1235
+ # mean anything is noise in the listing `claims` exists to be read (RK161).
1236
+ claiming.follow(self.root, self.task_id, self.marker, self.roadmap.entries)
1237
+ return _spelled(self.root, written)
1238
+
1239
+ @property
1240
+ def block(self) -> str:
1241
+ return self.ledger.entry.task.block
1242
+
1243
+ def event(self, config: Config) -> dict[str, object]:
1244
+ """What the departure did to the block it left (RK38), off the roadmap it wrote."""
1245
+ from roadkeep.rendering import _event # noqa: PLC0415 - RK260
1246
+
1247
+ return _event(self.task_id, self.block, self.roadmap, config)
1248
+
1249
+ def stated(self, config: Config, wrote: Sequence[str]) -> str:
1250
+ """Three edits across three files, as a reader is told them (RK6, RK32).
1251
+
1252
+ Beside :meth:`payload` since RK1170. `wrote` is the caller's, because :meth:`save` is
1253
+ the door's step and a record naming paths it has not written would be answering about
1254
+ a transaction that may not have landed.
1255
+ """
1256
+ from roadkeep.rendering import ( # noqa: PLC0415 - RK260
1257
+ _cited_rows,
1258
+ _decided_body_rows,
1259
+ _dequeued_rows,
1260
+ _unmet_rows,
1261
+ _emptied_rows,
1262
+ _event_rows,
1263
+ _prose_file,
1264
+ _scope_rows,
1265
+ )
1266
+
1267
+ roadmap = config.relative(config.path("roadmap"))
1268
+ ledger = config.relative(config.path("changelog"))
1269
+ rows = [
1270
+ f"{self.task_id} → {ledger}:{self.ledger.lineno} under Block {self.block}",
1271
+ f" removed {roadmap}:{self.removed_from}",
1272
+ ]
1273
+ if self.dropped is not None:
1274
+ rows.append(f" dropped {self.dropped} from {_prose_file(config, self.prose)}")
1275
+ if self.nested:
1276
+ rows.append(f" nested {', '.join(f'§{a}' for a in self.nested)} went with it")
1277
+ rows += _cited_rows(self.cited)
1278
+ rows += _emptied_rows(self.emptied)
1279
+ else:
1280
+ rows.append(f" kept nothing dropped: {self.kept}")
1281
+ # Beside the drop rather than inside it (RK310): the deletion is what makes the clause
1282
+ # the only surviving trace, and it is reported even where the section stayed — a design
1283
+ # another open line still points at can be just as overtaken as one that went.
1284
+ if self.superseded is not None:
1285
+ rows.append(f" overtook the design it read: {self.superseded}")
1286
+ # Under it and in the same place for the same reason (RK1267): the deletion is what
1287
+ # makes the address the only surviving trace, and this is where it went.
1288
+ if self.recorded_in is not None:
1289
+ rows.append(f" recorded the part that outlives it: {self.recorded_in}")
1290
+ # The fourth file, reported as a write and not as a note (RK1269): it has a line
1291
+ # number, so a reviewer reads the diff against it the way they read the ledger's.
1292
+ if self.decided is not None:
1293
+ rows.append(
1294
+ f" decided {config.relative(config.path('decisions'))}:"
1295
+ f"{self.decided.lineno} {self.decided.rendered}"
1296
+ )
1297
+ rows += _decided_body_rows(self.task_id, self.decided.entry.task.ref or "")
1298
+ if self.refreshed:
1299
+ rows.append(f" derived {', '.join(self.refreshed)} (dep annotations re-derived)")
1300
+ rows += _dequeued_rows(self.dequeued)
1301
+ rows += _unmet_rows(self.unmet)
1302
+ # Last before the event line, because it is about the commit this ship precedes rather
1303
+ # than about the three edits above it (RK294).
1304
+ rows += _scope_rows(self.scope, wrote)
1305
+ rows += _event_rows(self.event(config), " ", standing=True)
1306
+ return "\n".join(rows)
1307
+
1308
+ def payload(self, config: Config, wrote: Sequence[str]) -> dict[str, object]:
1309
+ """The same answer as data, with every file the three edits reached."""
1310
+ from roadkeep.rendering import _prose_file, _scope_json # noqa: PLC0415 - RK260
1311
+
1312
+ return {
1313
+ "id": self.task_id,
1314
+ "changelog": {
1315
+ "file": config.relative(config.path("changelog")),
1316
+ "line": self.ledger.lineno,
1317
+ "rendered": self.ledger.rendered,
1318
+ },
1319
+ "roadmap": {
1320
+ "file": config.relative(config.path("roadmap")),
1321
+ "removed": self.removed_from,
1322
+ },
1323
+ "improvements": {
1324
+ # The file the drop actually rewrote, which is whichever prose role declared
1325
+ # the anchor (RK196) — not always the improvements file.
1326
+ "file": _prose_file(config, self.prose),
1327
+ "dropped": None
1328
+ if self.dropped is None
1329
+ else {
1330
+ "anchor": self.dropped.anchor,
1331
+ "title": self.dropped.title,
1332
+ "first": self.dropped.first,
1333
+ "last": self.dropped.last,
1334
+ },
1335
+ "nested": list(self.nested),
1336
+ "cited": list(self.cited),
1337
+ "emptied": self.emptied,
1338
+ "kept": self.kept,
1339
+ # What the deleted design was overtaken by (RK310), beside the anchor it was
1340
+ # written under: the two are one fact, and a caller reading them off the
1341
+ # rendered sentence would be parsing prose.
1342
+ "superseded": self.superseded,
1343
+ # And where the half of it that was right went (RK1267), read off the same
1344
+ # anchor: the pair is what types the deletion, so one without the other is
1345
+ # half an answer to the question this write exists to record.
1346
+ "recorded_in": self.recorded_in,
1347
+ },
1348
+ "refreshed": list(self.refreshed),
1349
+ # What left the order with the line (RK327), named because a plan that silently
1350
+ # got shorter is a change with no sentence about it.
1351
+ "dequeued": self.dequeued,
1352
+ # And the task's own criteria that went with it (RK1268), for the same reason.
1353
+ "unmet": list(self.unmet),
1354
+ # The fourth file (RK1269), shaped as the ledger's own block above: a write with a
1355
+ # file and a line, never the sentence alone.
1356
+ "decisions": None
1357
+ if self.decided is None
1358
+ else {
1359
+ "file": config.relative(config.path("decisions")),
1360
+ "line": self.decided.lineno,
1361
+ "rendered": self.decided.rendered,
1362
+ # The command the text offers, in the payload that has to carry it
1363
+ # (RK1307, RK1361): the line is half a decision and the other half is a
1364
+ # `section add` an MCP caller can only make if it is told the argv.
1365
+ "weighed": [
1366
+ "section",
1367
+ "add",
1368
+ self.decided.entry.task.ref or self.task_id,
1369
+ "--role",
1370
+ "decisions",
1371
+ "--title",
1372
+ ],
1373
+ },
1374
+ "scope": _scope_json(self.scope, wrote),
1375
+ "event": self.event(config),
1376
+ }
1377
+
1378
+ def retired(self, config: Config, wrote: Sequence[str]) -> str:
1379
+ """The **other** door's reading of this record (RK32), as a reader is told it.
1380
+
1381
+ One shape for both doors and two registers each, which is four methods and not a flag:
1382
+ a retirement's subject is where the replacement was found and who still names the line,
1383
+ and a shipment's is the design that was deleted. A branch inside one method would be
1384
+ those two answers sharing a name because they share a dataclass.
1385
+ """
1386
+ from roadkeep.rendering import ( # noqa: PLC0415 - RK260
1387
+ _event_rows,
1388
+ _prose_file,
1389
+ _scope_rows,
1390
+ )
1391
+
1392
+ roadmap = config.relative(config.path("roadmap"))
1393
+ ledger = config.relative(config.path("changelog"))
1394
+ rows = [
1395
+ f"{self.task_id} {self.marker} {ledger}:{self.ledger.lineno} "
1396
+ f"under Block {self.block}",
1397
+ f" removed {roadmap}:{self.removed_from}",
1398
+ ]
1399
+ if self.replacement_in is not None:
1400
+ # Where the replacement was found, because the three files are three different
1401
+ # promises (RK244): shipped is a supersession already delivered, open is one being
1402
+ # worked, and paused is one waiting on a `resume` nobody is holding.
1403
+ rows.append(
1404
+ f" found {self.replacement} in "
1405
+ f"{config.relative(config.path(self.replacement_in))}"
1406
+ )
1407
+ if self.dropped is not None:
1408
+ rows.append(f" dropped {self.dropped} from {_prose_file(config, self.prose)}")
1409
+ if self.dependents:
1410
+ # Reported, not refused: a supersession is legitimate and these lines are the
1411
+ # author's next edit. `deps` now resolves them as unresolvable, not as satisfied.
1412
+ rows.append(f" still {', '.join(self.dependents)} name {self.task_id}")
1413
+ # A retirement is committed exactly as a ship is, and it releases the same claim (RK294).
1414
+ rows += _scope_rows(self.scope, wrote)
1415
+ rows += _event_rows(self.event(config), " ", standing=True)
1416
+ return "\n".join(rows)
1417
+
1418
+ def retirement(self, config: Config, wrote: Sequence[str]) -> dict[str, object]:
1419
+ """The retirement as data, with both halves of where the replacement is (RK244)."""
1420
+ from roadkeep.rendering import _scope_json # noqa: PLC0415 - RK260
1421
+
1422
+ return {
1423
+ "id": self.task_id,
1424
+ "marker": self.marker,
1425
+ "superseded_by": self.replacement,
1426
+ "replacement_in": self.replacement_in,
1427
+ "changelog": {
1428
+ "file": config.relative(config.path("changelog")),
1429
+ "line": self.ledger.lineno,
1430
+ "rendered": self.ledger.rendered,
1431
+ },
1432
+ "roadmap": {
1433
+ "file": config.relative(config.path("roadmap")),
1434
+ "removed": self.removed_from,
1435
+ },
1436
+ "dropped": None if self.dropped is None else self.dropped.anchor,
1437
+ "dependents": list(self.dependents),
1438
+ "refreshed": list(self.refreshed),
1439
+ "scope": _scope_json(self.scope, wrote),
1440
+ "event": self.event(config),
1441
+ }
1442
+
1443
+
1444
+ Shipment = Departure
1445
+
1446
+
1447
+ @dataclass(frozen=True, slots=True)
1448
+ class Partial:
1449
+ """Half a departure: the ledger records what landed, the roadmap keeps the line (RK121).
1450
+
1451
+ The third state the model did not have. Open in the roadmap and recorded in the ledger
1452
+ were the only two, so work delivered in halves was neither — and every project using
1453
+ this invented the same escape, a parenthetical on the ledger id that the grammar could
1454
+ not read. This is that escape given a verb, which is the half that can be *maintained*:
1455
+ only a command knows when the qualifier stops being true, and :func:`ship` completing
1456
+ the line is what removes it.
1457
+
1458
+ Not a :class:`Departure` with a flag: a departure's subject is a line that left, and
1459
+ this one's is a line that stayed. Nothing is removed and nothing is deleted — in
1460
+ particular the rationale section stays, because the design still has work left to
1461
+ describe.
1462
+ """
1463
+
1464
+ task_id: str
1465
+ ledger: Insertion
1466
+ #: The roadmap as this write leaves it: the same line, marked ⏳ where the project
1467
+ #: declares that marker, and every dependent's annotation re-derived from it (RK8).
1468
+ roadmap: Document
1469
+ part: str
1470
+ #: What the caller said is **left**, where they said it (RK1233). Written into the open
1471
+ #: line's own `why`, so the remainder is a field rather than a subtraction the next reader
1472
+ #: makes across two files. `None` is every call before this argument and every one that
1473
+ #: declines it — the line keeps the sentence it had, which is what it always did.
1474
+ remainder: str | None = None
1475
+ #: What the roadmap line's marker became — ⏳, or the one it already carried at a
1476
+ #: project that declares no such marker. Reported because the two differ and a caller
1477
+ #: reading "partial" would otherwise not know which of them happened.
1478
+ status: str = ""
1479
+ refreshed: tuple[str, ...] = ()
1480
+ #: The marker the ledger entry carries: ✅, on the part that shipped.
1481
+ marker: str = ""
1482
+
1483
+ def save(self) -> tuple[Path, ...]:
1484
+ # The ledger first, as everywhere else (RK118): the record of what landed is the
1485
+ # thing that cannot be reconstructed, and a marker not yet ⏳ is a state a second
1486
+ # run of the same command corrects.
1487
+ return save_all(self.ledger.document, self.roadmap)
1488
+
1489
+ @property
1490
+ def block(self) -> str:
1491
+ return self.ledger.entry.task.block
1492
+
1493
+ @property
1494
+ def lineno(self) -> int:
1495
+ """Where the line this did **not** remove still stands."""
1496
+ return self.roadmap.by_id()[self.task_id].lineno
1497
+
1498
+ def event(self, config: Config) -> dict[str, object]:
1499
+ from roadkeep.rendering import _event # noqa: PLC0415 - RK260
1500
+
1501
+ return _event(self.task_id, self.block, self.roadmap, config)
1502
+
1503
+ def stated(self, config: Config) -> str:
1504
+ """Half of a task recorded, with its roadmap line still open (RK121).
1505
+
1506
+ Beside :meth:`payload` since RK1170. Nothing was removed and nothing was dropped, so a
1507
+ departure's report would be three lines of None: what happened is an entry and a marker.
1508
+
1509
+ **And the door the open half leaves** (RK1302). This is the one ship that deliberately
1510
+ leaves work open, and the state it leaves is the one `pick` trusts most — so the line
1511
+ comes back on the very next call, ahead of everything, and did until two unrelated tasks
1512
+ shipped. Measured on quickshell: QS3 landed a corpus and a harness, its remainder waited
1513
+ on a parser and a renderer that were not written, and the answer stopped exactly where
1514
+ the caller needed the next sentence. The remedy is one command, `amend <id> --dep …`,
1515
+ and nothing said so — so a caller who does not know it re-picks the same line while the
1516
+ file goes on saying in progress.
1517
+
1518
+ Named the way `finish` below is named, and not taken in this transaction: `--part --dep`
1519
+ would amend the group here, on the argument that the moment a remainder is described is
1520
+ the moment its blockers are known. That is a real shape and RK1302 left it open rather
1521
+ than guessing at it — what the measurement showed missing was the sentence, not the
1522
+ keystroke. It is a **row and not a payload key** for the reason `finish` is: the doors
1523
+ this answer carries are all on stdout — a gap RK1307 has since closed, and
1524
+ :meth:`doors` is where both now come from.
1525
+ """
1526
+ from roadkeep.rendering import _event_rows # noqa: PLC0415 - RK260
1527
+
1528
+ roadmap = config.relative(config.path("roadmap"))
1529
+ ledger = config.relative(config.path("changelog"))
1530
+ rows = [
1531
+ f"{self.task_id} ({self.part}) → {ledger}:{self.ledger.lineno} "
1532
+ f"under Block {self.block}",
1533
+ f" open {roadmap}:{self.lineno} {self.status} — the rest of it is still a task",
1534
+ *(
1535
+ # The other half, where the caller named it (RK1233): the line now *states*
1536
+ # what is left, so the next reader is handed it rather than subtracting.
1537
+ [f" left {self.remainder}"] if self.remainder else []
1538
+ ),
1539
+ # Before `finish`, because it is what to do **now** and that one is what to do at
1540
+ # the end: the line is open, so it is picked again before either happens.
1541
+ f" waits this line is offered again until it says what it is waiting on — "
1542
+ f"`{invocation()} {' '.join(self.doors()[0].argv)}` names it, where the rest of "
1543
+ f"the work waits on something still open",
1544
+ f" finish {invocation()} {' '.join(self.doors()[1].argv)}"
1545
+ f" (drops the qualifier)",
1546
+ ]
1547
+ if self.refreshed:
1548
+ rows.append(f" derived {', '.join(self.refreshed)} (dep annotations re-derived)")
1549
+ rows += _event_rows(self.event(config), " ", standing=True)
1550
+ return "\n".join(rows)
1551
+
1552
+ def doors(self) -> tuple[Door, ...]:
1553
+ """The two commands this half-written state makes available (RK1302, RK1307).
1554
+
1555
+ In the order a caller reaches them: what to do **now** with the work that is left, and
1556
+ what closes the line at the end. One reader for both registers, because a printer that
1557
+ composed its own argv beside a payload that composed another is two answers about the
1558
+ same next step — which is the shape RK1307 is a class of.
1559
+ """
1560
+ return (
1561
+ Door(
1562
+ ("amend", self.task_id, "--dep", "<id>"),
1563
+ "the remainder waits on something still open, and this names it",
1564
+ ),
1565
+ Door(("ship", self.task_id), "the rest of it landed, and this drops the qualifier"),
1566
+ )
1567
+
1568
+ def payload(self, config: Config) -> dict[str, object]:
1569
+ """The same answer as data, saying the line is still open (RK121).
1570
+
1571
+ And the two doors the rows carry (RK1307): this is the one write that deliberately
1572
+ leaves work open, so the commands that resolve that state are the answer — and the
1573
+ caller reaching it through the served payload is the one that had neither.
1574
+ """
1575
+ from roadkeep.rendering import _served # noqa: PLC0415 - RK260
1576
+
1577
+ return {
1578
+ "id": self.task_id,
1579
+ "part": self.part,
1580
+ "doors": [one.payload(_served(config)) for one in self.doors()],
1581
+ # What is left, where the caller said it (RK1233). Null and not omitted: a
1582
+ # consumer reading a missing key cannot tell "not stated" from "older server".
1583
+ "remainder": self.remainder,
1584
+ "changelog": {
1585
+ "file": config.relative(config.path("changelog")),
1586
+ "line": self.ledger.lineno,
1587
+ "rendered": self.ledger.rendered,
1588
+ },
1589
+ "roadmap": {
1590
+ "file": config.relative(config.path("roadmap")),
1591
+ "line": self.lineno,
1592
+ "status": self.status,
1593
+ "open": True,
1594
+ },
1595
+ "refreshed": list(self.refreshed),
1596
+ "event": self.event(config),
1597
+ }
1598
+
1599
+
1600
+ @dataclass(frozen=True, slots=True)
1601
+ class Closure:
1602
+ """The rest of a transaction that never completed (RK62).
1603
+
1604
+ A roadmap line whose id the ledger *already* records has nowhere to go: `ship` cannot write
1605
+ a second entry, `retire` would claim a departure that did not happen, and the hook denies
1606
+ the hand-edit. So closing the line is its own outcome — the same edits a departure makes
1607
+ minus the one that is already done, and the ledger is opened only to be read.
1608
+
1609
+ Not a :class:`Departure` with a None: the field that would be None is the entry, which is
1610
+ the whole subject of that shape. Here the entry is the *evidence*, and it is somebody
1611
+ else's write.
1612
+ """
1613
+
1614
+ task_id: str
1615
+ #: The file this write leaves behind: without the line, dependents re-annotated. Named
1616
+ #: for what it *is* rather than for the role it happens to be (RK1088), because the role
1617
+ #: is the field below and a pair that can disagree is a pair that will: `Resumption` had
1618
+ #: exactly this shape until RK1086, where a document called `roadmap` was the answer for
1619
+ #: an act that touched the store.
1620
+ remaining: Document
1621
+ removed_from: int
1622
+ #: The ledger entry that already existed, and its marker — ✅ or 🗑, because a reader has
1623
+ #: to know which door this id went through before its line was left behind.
1624
+ recorded: Entry
1625
+ #: **Which file the line came out of** (RK1086). `roadmap` on every closure this verb
1626
+ #: makes today, and named rather than assumed because the assumption is what blocks the
1627
+ #: next one: RK1084 found an id the ledger records and the *store* still carries, which
1628
+ #: is the same act — remove the leftover, write nothing — against a different pair, and
1629
+ #: a result that can only say `removed_from` has nowhere to put the answer.
1630
+ removed_in: str = "roadmap"
1631
+ #: The prose file this drop rewrote, as :class:`Departure` carries it (RK196).
1632
+ prose: Document | None = None
1633
+ dropped: Section | None = None
1634
+ kept: str | None = None
1635
+ #: The anchors nested under the one dropped, as :class:`Departure` reports them (RK78).
1636
+ nested: tuple[str, ...] = ()
1637
+ #: Sections left citing what the drop deleted, as :class:`Departure` reports them (RK206).
1638
+ cited: tuple[str, ...] = ()
1639
+ #: The parent this drop left with no subsections, as :class:`Departure` reports it (RK400).
1640
+ emptied: str | None = None
1641
+ refreshed: tuple[str, ...] = ()
1642
+ dependents: tuple[str, ...] = ()
1643
+ #: The priority entry this closure took out (RK327). Here for the reason every other
1644
+ #: field of the departure is: the line leaves, so the order naming it could only fire on
1645
+ #: nothing — and a door that is `ship` minus the ledger edit is still a departure.
1646
+ dequeued: str | None = None
1647
+ #: The task's own criteria, which left with the line (RK1268) — :class:`Departure`'s field
1648
+ #: and its argument: this door is the rest of a transaction, so it owes the same edits.
1649
+ unmet: tuple[str, ...] = ()
1650
+ #: The line filed into the decisions role (RK1269). Reached on this door and not by the
1651
+ #: two clauses beside it: those restate a ledger sentence this path does not write, and a
1652
+ #: decision is a line in a file of its own, filed where the section is deleted.
1653
+ decided: Insertion | None = None
1654
+ #: The tree split by whose claim names it (RK294), as :class:`Departure` carries it. Read
1655
+ #: here too because the moment is the same one — this door is `ship` on a line whose entry
1656
+ #: is already on disk, and the commit it precedes stages exactly the same files.
1657
+ scope: claiming.Scope | None = None
1658
+ #: The checkout, so this door releases the claim its sibling releases (RK306).
1659
+ root: Path | None = None
1660
+
1661
+ @property
1662
+ def marker(self) -> str:
1663
+ return self.recorded.task.status
1664
+
1665
+ def save(self) -> tuple[str, ...]:
1666
+ """Write the roadmap and the prose file, and answer which. The ledger is never opened
1667
+ for writing, so it is not in the answer either (RK309).
1668
+
1669
+ And reconcile the claim, which this was the one departure not to do (RK306). RK162
1670
+ made every marker write a release and :meth:`Departure.save` obeys it; this shape is
1671
+ the same departure minus the ledger edit, and skipped it — so the interrupted
1672
+ transaction RK130 opened this door for closed its line and left the dated row and the
1673
+ scope it carried behind, for `claims` to list against an id no file holds and for a
1674
+ `--prune` the author was never told they needed.
1675
+
1676
+ The marker passed is the **ledger's**, which is what this door has: the line is gone,
1677
+ so there is no roadmap marker to write, and the entry's ✅ or 🗑 is the terminal one
1678
+ the rule reads as a release either way. Last and never a condition of the writes, for
1679
+ the reason its sibling states.
1680
+ """
1681
+ # The decision first, for the reason its sibling states (RK1269): it is the only
1682
+ # trace of what the section held, and the prose write is the deletion.
1683
+ written = save_all(
1684
+ None if self.decided is None else self.decided.document,
1685
+ self.remaining,
1686
+ self.prose,
1687
+ )
1688
+ if self.root is not None:
1689
+ claiming.follow(self.root, self.task_id, self.marker, self.remaining.entries)
1690
+ return _spelled(self.root, written)
1691
+
1692
+ def event(self, config: Config) -> dict[str, object]:
1693
+ from roadkeep.rendering import _event # noqa: PLC0415 - RK260
1694
+
1695
+ return _event(self.task_id, self.recorded.task.block, self.remaining, config)
1696
+
1697
+ def stated(self, config: Config, wrote: Sequence[str]) -> str:
1698
+ """A roadmap line closed against an entry the ledger already had (RK62).
1699
+
1700
+ Beside :meth:`payload` since RK1170, and the file the line came out of is read off this
1701
+ record rather than assumed to be the roadmap (RK1088).
1702
+ """
1703
+ from roadkeep.rendering import ( # noqa: PLC0415 - RK260
1704
+ _cited_rows,
1705
+ _decided_body_rows,
1706
+ _dequeued_rows,
1707
+ _unmet_rows,
1708
+ _emptied_rows,
1709
+ _event_rows,
1710
+ _prose_file,
1711
+ _scope_rows,
1712
+ )
1713
+
1714
+ ledger = config.relative(config.path("changelog"))
1715
+ rows = [
1716
+ f"{self.task_id} closed "
1717
+ f"{config.relative(config.path(self.removed_in))}:{self.removed_from} removed, "
1718
+ f"already {self.marker} in {ledger}:{self.recorded.lineno}",
1719
+ " ledger untouched: the entry was already there",
1720
+ ]
1721
+ if self.dropped is not None:
1722
+ rows.append(f" dropped {self.dropped} from {_prose_file(config, self.prose)}")
1723
+ if self.nested:
1724
+ rows.append(f" nested {', '.join(f'§{a}' for a in self.nested)} went with it")
1725
+ rows += _cited_rows(self.cited)
1726
+ rows += _emptied_rows(self.emptied)
1727
+ if self.refreshed:
1728
+ rows.append(f" derived {', '.join(self.refreshed)} (dep annotations re-derived)")
1729
+ rows += _dequeued_rows(self.dequeued)
1730
+ rows += _unmet_rows(self.unmet)
1731
+ if self.decided is not None:
1732
+ rows.append(
1733
+ f" decided {config.relative(config.path('decisions'))}:"
1734
+ f"{self.decided.lineno} {self.decided.rendered}"
1735
+ )
1736
+ rows += _decided_body_rows(self.task_id, self.decided.entry.task.ref or "")
1737
+ rows += _scope_rows(self.scope, wrote)
1738
+ rows += _event_rows(self.event(config), " ")
1739
+ return "\n".join(rows)
1740
+
1741
+ def payload(self, config: Config, wrote: Sequence[str]) -> dict[str, object]:
1742
+ """The same answer as data, naming the file the line came out of (RK1088)."""
1743
+ from roadkeep.rendering import _prose_file, _scope_json # noqa: PLC0415 - RK260
1744
+
1745
+ return {
1746
+ "id": self.task_id,
1747
+ # The file the line actually came out of (RK1088), read off the closure rather than
1748
+ # assumed to be the roadmap: the act is the same against a different pair, and a
1749
+ # payload that named one file by having only one to name is one a second act would
1750
+ # quietly make wrong.
1751
+ "closed": {
1752
+ "file": config.relative(config.path(self.removed_in)),
1753
+ "role": self.removed_in,
1754
+ "removed": self.removed_from,
1755
+ },
1756
+ "recorded": {
1757
+ "file": config.relative(config.path("changelog")),
1758
+ "line": self.recorded.lineno,
1759
+ "marker": self.marker,
1760
+ "written": False,
1761
+ },
1762
+ "improvements": {
1763
+ "file": _prose_file(config, self.prose),
1764
+ "dropped": None
1765
+ if self.dropped is None
1766
+ else {"anchor": self.dropped.anchor, "title": self.dropped.title},
1767
+ "nested": list(self.nested),
1768
+ "cited": list(self.cited),
1769
+ "emptied": self.emptied,
1770
+ "kept": self.kept,
1771
+ },
1772
+ "refreshed": list(self.refreshed),
1773
+ "dequeued": self.dequeued,
1774
+ # And the task's own criteria that went with it (RK1268), for the same reason.
1775
+ "unmet": list(self.unmet),
1776
+ # The fourth file this door may write (RK1269), shaped as `recorded` above is.
1777
+ "decisions": None
1778
+ if self.decided is None
1779
+ else {
1780
+ "file": config.relative(config.path("decisions")),
1781
+ "line": self.decided.lineno,
1782
+ "rendered": self.decided.rendered,
1783
+ # The command the text offers, in the payload that has to carry it
1784
+ # (RK1307, RK1361): the line is half a decision and the other half is a
1785
+ # `section add` an MCP caller can only make if it is told the argv.
1786
+ "weighed": [
1787
+ "section",
1788
+ "add",
1789
+ self.decided.entry.task.ref or self.task_id,
1790
+ "--role",
1791
+ "decisions",
1792
+ "--title",
1793
+ ],
1794
+ },
1795
+ "scope": _scope_json(self.scope, wrote),
1796
+ "event": self.event(config),
1797
+ }
1798
+
1799
+
1800
+ @dataclass(frozen=True, slots=True)
1801
+ class Record:
1802
+ """A ledger entry that had no roadmap line to leave (RK41).
1803
+
1804
+ Not a :class:`Departure`: there is no line removed, no section dropped and no
1805
+ `removed_from` to report, and a shared shape would carry three fields that are
1806
+ permanently None plus the invitation to make them meaningful later.
1807
+ """
1808
+
1809
+ task_id: str
1810
+ ledger: Insertion
1811
+ #: The roadmap as this write leaves it — the same document unless an annotation
1812
+ #: elsewhere became derivable (RK8), which is what :attr:`refreshed` names.
1813
+ roadmap: Document
1814
+ refreshed: tuple[str, ...] = ()
1815
+ #: The marker the entry carries: ✅, the only one a record can mean.
1816
+ marker: str = ""
1817
+ #: The earlier entry this one supersedes, as it now reads with the forward pointer on it
1818
+ #: (RK395). None on every `record add` that supersedes nothing, which is most of them.
1819
+ superseded: Entry | None = None
1820
+ #: Where a sentence already named this id, on the `--id` that was allowed because no
1821
+ #: line held it (RK1051). Reported and never swallowed: writing the entry a citation
1822
+ #: promised is the repair, and writing one it did not promise is the author's to see.
1823
+ mentioned: IdRef | None = None
1824
+
1825
+ def save(self) -> tuple[Path, ...]:
1826
+ """Write the ledger, and the roadmap only if a line in it actually changed."""
1827
+ # The roadmap is passed only where a line in it changed, so it is not rewritten to
1828
+ # the same bytes: an untouched file with a moved mtime reads as an edit to every
1829
+ # hook watching it, and "touched nothing else" has to be true on disk.
1830
+ return save_all(self.ledger.document, self.roadmap if self.refreshed else None)
1831
+
1832
+ @property
1833
+ def block(self) -> str:
1834
+ """As the file reads it back, and not as it was typed."""
1835
+ return self.ledger.entry.task.block
1836
+
1837
+ def event(self, config: Config) -> dict[str, object]:
1838
+ """The **roadmap's** block state, as it is for every other mutator: a hook asking "is
1839
+ Block B finished" is asking about open work, and a record adds none."""
1840
+ from roadkeep.rendering import _event # noqa: PLC0415 - RK260
1841
+
1842
+ return _event(self.task_id, self.block, self.roadmap, config)
1843
+
1844
+ def stated(self, config: Config, wrote: Sequence[Path]) -> str:
1845
+ """A ledger entry that had no roadmap line to leave (RK41).
1846
+
1847
+ Beside :meth:`payload` since RK1170.
1848
+ """
1849
+ from roadkeep.rendering import _event_rows, _staging_rows # noqa: PLC0415 - RK260
1850
+
1851
+ ledger = config.relative(config.path("changelog"))
1852
+ rows = [
1853
+ f"{self.task_id} {self.marker} {ledger}:{self.ledger.lineno} "
1854
+ f"under Block {self.block}",
1855
+ # Said out loud, because the absence is the whole point: a reader of this output
1856
+ # has to be able to tell "there was no line" from "the roadmap edit was forgotten".
1857
+ # About the write and not about the work (RK1050, RK1051): this door is also how a
1858
+ # task that *was* planned gets the entry it is missing, and `planned never` was a
1859
+ # claim about the wrong thing on exactly the write that repairs one.
1860
+ " roadmap no line to remove: this door writes the entry and nothing else",
1861
+ ]
1862
+ if self.mentioned is not None:
1863
+ # The citation the occupancy check used to refuse over (RK1051). Printed rather
1864
+ # than refused *and* rather than swallowed: an entry that keeps a sentence's promise
1865
+ # and one that collides with it are the same write, and only the author can tell
1866
+ # them apart — so the address is given and the judgement is left where it belongs.
1867
+ rows.append(
1868
+ f" cited {config.relative(self.mentioned.path)}:{self.mentioned.lineno} "
1869
+ f"already names {self.task_id}: no line held it, so this entry is what it "
1870
+ f"now points at"
1871
+ )
1872
+ if self.superseded is not None:
1873
+ # The edit the caller did not spell, printed where every other derived write is:
1874
+ # the forward pointer is this command's fact, and a reviewer reads the diff by it.
1875
+ rows.append(
1876
+ f" pointed {ledger}:{self.superseded.lineno} "
1877
+ f"{self.superseded.task.id} now names {self.task_id} as what replaced it"
1878
+ )
1879
+ if self.refreshed:
1880
+ rows.append(f" derived {', '.join(self.refreshed)} (dep annotations re-derived)")
1881
+ rows += _staging_rows(config.relative(one) for one in wrote)
1882
+ rows += _event_rows(self.event(config), " ")
1883
+ return "\n".join(rows)
1884
+
1885
+ def payload(self, config: Config, wrote: Sequence[Path]) -> dict[str, object]:
1886
+ """The same answer as data, with the entry this one supersedes (RK395)."""
1887
+ from roadkeep.rendering import _wrote_json # noqa: PLC0415 - RK260
1888
+
1889
+ return {
1890
+ "id": self.task_id,
1891
+ "marker": self.marker,
1892
+ "changelog": {
1893
+ "file": config.relative(config.path("changelog")),
1894
+ "line": self.ledger.lineno,
1895
+ "rendered": self.ledger.rendered,
1896
+ },
1897
+ "roadmap": {"touched": bool(self.refreshed)},
1898
+ "refreshed": list(self.refreshed),
1899
+ # The other half of the transaction (RK395): null on every record that supersedes
1900
+ # nothing, and the earlier entry as it now reads otherwise.
1901
+ "superseded": None
1902
+ if self.superseded is None
1903
+ else {
1904
+ "id": self.superseded.task.id,
1905
+ "line": self.superseded.lineno,
1906
+ "rendered": self.superseded.raw,
1907
+ },
1908
+ # The sentence that already named this id, where `--id` was allowed because no
1909
+ # line held it (RK1051): null on every other record.
1910
+ "mentioned": None
1911
+ if self.mentioned is None
1912
+ else {
1913
+ "file": config.relative(self.mentioned.path),
1914
+ "line": self.mentioned.lineno,
1915
+ },
1916
+ "event": self.event(config),
1917
+ **_wrote_json(config, wrote),
1918
+ }
1919
+
1920
+
1921
+ @dataclass(frozen=True, slots=True)
1922
+ class Dropped:
1923
+ """One of two ledger entries for a single id, removed (RK67).
1924
+
1925
+ No roadmap field, and that is the shape of the guarantee rather than an omission: an id
1926
+ the ledger still records once is an id every annotation elsewhere is still true about, so
1927
+ there is nothing to re-derive (RK8) and no second file to open. :class:`Record` had to say
1928
+ "touched nothing else" in a docstring; here there is nothing that could.
1929
+ """
1930
+
1931
+ task_id: str
1932
+ #: The ledger as this write leaves it: one entry for the id, and no doubled blank.
1933
+ ledger: Document
1934
+ removed_from: int
1935
+ #: The line the decision keeps, and the marker it carries there — printed, because a
1936
+ #: duplicate whose two entries disagree about the door is a fact the author has to see.
1937
+ kept: int
1938
+ kept_marker: str
1939
+ #: The block the ledger still files this decision under — the kept entry's, since that is
1940
+ #: the one that is left to answer for it.
1941
+ block: str = ""
1942
+ #: The marker the removed entry carried, which is normally the same one.
1943
+ marker: str = ""
1944
+
1945
+ def save(self) -> tuple[Path, ...]:
1946
+ """Write the ledger, and answer it (RK1130). Nothing else was opened, so nothing
1947
+ else can be touched — and the answer is what a `git add --` takes."""
1948
+ return self.ledger.save()
1949
+
1950
+ def event(self, config: Config) -> dict[str, object]:
1951
+ """The roadmap is read, never written (RK67): the event's block state is the
1952
+ *roadmap's* for every mutator, and a duplicate removed leaves open work as it was."""
1953
+ from roadkeep.rendering import _event # noqa: PLC0415 - RK260
1954
+
1955
+ return _event(self.task_id, self.block, config.document("roadmap"), config)
1956
+
1957
+ def stated(self, config: Config, wrote: Sequence[Path]) -> str:
1958
+ """Which of two entries went, and which line the decision keeps (RK67).
1959
+
1960
+ Beside :meth:`payload` since RK1170.
1961
+ """
1962
+ from roadkeep.rendering import _event_rows, _staging_rows # noqa: PLC0415 - RK260
1963
+
1964
+ ledger = config.relative(config.path("changelog"))
1965
+ rows = [
1966
+ f"{self.task_id} {self.marker} {ledger}:{self.removed_from} removed, "
1967
+ f"duplicate of {ledger}:{self.kept}",
1968
+ f" kept {self.kept_marker} line {self.kept}: where the decision was found",
1969
+ ]
1970
+ if self.kept_marker != self.marker:
1971
+ # Two entries that disagree about the door are not one decision written twice, and
1972
+ # the later one is gone: which marker the ledger now states has to be said aloud.
1973
+ rows.append(
1974
+ f" differed the entry removed said {self.marker}, so the ledger now states "
1975
+ f"{self.kept_marker}"
1976
+ )
1977
+ rows.append(" roadmap untouched: an id the ledger still records changes no annotation")
1978
+ rows += _event_rows(self.event(config), " ")
1979
+ rows += _staging_rows(config.relative(one) for one in wrote)
1980
+ return "\n".join(rows)
1981
+
1982
+ def payload(self, config: Config, wrote: Sequence[Path]) -> dict[str, object]:
1983
+ """The same answer as data, with both entries' markers (RK67)."""
1984
+ from roadkeep.rendering import _wrote_json # noqa: PLC0415 - RK260
1985
+
1986
+ return {
1987
+ "id": self.task_id,
1988
+ "changelog": {
1989
+ "file": config.relative(config.path("changelog")),
1990
+ "removed": self.removed_from,
1991
+ "marker": self.marker,
1992
+ },
1993
+ "kept": {"line": self.kept, "marker": self.kept_marker},
1994
+ "roadmap": {"touched": False},
1995
+ **_wrote_json(config, wrote),
1996
+ "event": self.event(config),
1997
+ }
1998
+
1999
+
2000
+ @dataclass(frozen=True, slots=True)
2001
+ class Corrected:
2002
+ """One ledger entry rewritten where it stands (RK124).
2003
+
2004
+ No `removed_from` and no insertion, which is the whole shape of the claim: the line
2005
+ keeps its number, so the ledger still reads in the order work landed and the diff shows
2006
+ a word. Nothing else is opened either — a `why` is prose, and no annotation anywhere is
2007
+ derived from it.
2008
+ """
2009
+
2010
+ task_id: str
2011
+ #: The ledger as this write leaves it: one line rewritten, everything else verbatim.
2012
+ ledger: Document
2013
+ entry: Entry
2014
+ #: Which fields moved — empty when the entry already read that way, so a caller can
2015
+ #: tell "corrected" from "already correct" without diffing the file.
2016
+ changed: tuple[str, ...] = ()
2017
+ #: How many continuation lines the write put back under the bullet (RK1049). Reported
2018
+ #: rather than inferred from the entry, because a caller reading `rendered` sees the
2019
+ #: first line only: a correction that kept four paragraphs and one that deleted them
2020
+ #: print identically, and this is the difference.
2021
+ below: int = 0
2022
+
2023
+ @property
2024
+ def rendered(self) -> str:
2025
+ return self.entry.raw
2026
+
2027
+ @property
2028
+ def lineno(self) -> int:
2029
+ return self.entry.lineno
2030
+
2031
+ def save(self) -> tuple[Path, ...]:
2032
+ """Write the ledger, and answer it (RK1130). Nothing else was opened, so nothing
2033
+ else can be touched — and the answer is what a `git add --` takes."""
2034
+ return self.ledger.save()
2035
+
2036
+ def stated(self, config: Config, wrote: Sequence[Path], undone_by: str | None) -> str:
2037
+ """What the correction moved, and whether it was written about work that held (RK124).
2038
+
2039
+ Beside :meth:`payload` since RK1170. `undone_by` is a parameter for `wrote`'s reason and
2040
+ one more (RK1052): it is read off the ledger *before* the write, because correcting the
2041
+ sentence is what can remove the mark it is read from — so the record cannot hold it.
2042
+ """
2043
+ from roadkeep.rendering import _staging_rows # noqa: PLC0415 - RK260
2044
+
2045
+ where = config.relative(config.path("changelog"))
2046
+ # `below` as well as `changed` (RK1049): a correction that moved no field and rewrote
2047
+ # four paragraphs under the bullet is a write, and calling it unchanged here would be
2048
+ # the collapse that task closed, reported as a no-op.
2049
+ if not self.changed and not self.below:
2050
+ return f"{self.task_id} unchanged: the entry already reads that way"
2051
+ rows = [
2052
+ f"{self.task_id} amended {where}:{self.lineno} "
2053
+ f"({', '.join(self.changed) or 'tail'})",
2054
+ f" {self.rendered}",
2055
+ ]
2056
+ if undone_by is not None:
2057
+ # The moment the clause matters most (RK1052): the author is composing an outcome
2058
+ # for work a later entry says did not hold, and `delivered` would have told them.
2059
+ # The two surfaces RK1042 joined are one fact again, said in the same words.
2060
+ rows.append(
2061
+ f" undone by {undone_by}: the decision this entry records was reverted, "
2062
+ f"so the outcome being corrected is one that did not hold"
2063
+ )
2064
+ if self.below:
2065
+ # Said out loud for the reason the absence is (RK1049): the line printed above is
2066
+ # the whole of what this command can render, and a reader who cannot see that four
2067
+ # paragraphs are still under it has to diff the file to learn whether they survived.
2068
+ rows.append(
2069
+ f" kept {self.below} continuation line(s) under the bullet, "
2070
+ f"verbatim: no field holds them"
2071
+ )
2072
+ rows += _staging_rows(config.relative(one) for one in wrote)
2073
+ return "\n".join(rows)
2074
+
2075
+ def payload(
2076
+ self, config: Config, wrote: Sequence[Path], undone_by: str | None
2077
+ ) -> dict[str, object]:
2078
+ """The same answer as data, with the tail this write put back (RK1049)."""
2079
+ from roadkeep.rendering import _wrote_json # noqa: PLC0415 - RK260
2080
+
2081
+ return {
2082
+ "id": self.task_id,
2083
+ "file": config.relative(config.path("changelog")),
2084
+ # The line it was already on, because not moving it is the claim.
2085
+ "line": self.lineno,
2086
+ **_wrote_json(config, wrote),
2087
+ "rendered": self.rendered,
2088
+ "changed": list(self.changed),
2089
+ # The lines under the bullet this write put back (RK1049): `rendered` is the first
2090
+ # line, so a reader diffing the JSON cannot otherwise tell a kept tail from a
2091
+ # collapsed one.
2092
+ "below": self.below,
2093
+ # The id that reverted this one, or null (RK1042, RK1052): read off the ledger as
2094
+ # it stood, since correcting the sentence is what can remove the mark it is read
2095
+ # from.
2096
+ "undone_by": undone_by,
2097
+ }
2098
+
2099
+
2100
+ def amend(
2101
+ config: Config,
2102
+ task_id: str,
2103
+ *,
2104
+ why: str | None = None,
2105
+ part: str | None = None,
2106
+ lines: int | None = None,
2107
+ ) -> Corrected:
2108
+ """Correct one ledger entry's sentence, or a partial's qualifier, in place (RK124).
2109
+
2110
+ Validated before the write exactly as `record add` validates its fields (L1), against
2111
+ the ledger's own schema — so an over-length `why` is refused with the number, and the
2112
+ line that reaches disk is one this tool can read back (L3).
2113
+
2114
+ Refused on an id the ledger states twice: which of two entries a correction was written
2115
+ about is not a fact any file holds, and `record drop` is the door for a duplicate.
2116
+
2117
+ And refused on an entry that **wraps** unless `lines` says how many it replaces (RK179):
2118
+ the correction is written over the whole span, so on a hand-written ledger it deletes
2119
+ text the parse never held — and a write that silently removes prose is the one thing
2120
+ this door was narrow enough to be incapable of.
2121
+
2122
+ Once `lines` above one says the caller read that span, a `why` carrying newlines writes
2123
+ it back (RK1049). The refusal that stood there is right about a task line and wrong about
2124
+ a ledger entry — the parser accepts a five-line entry and this was the verb offering to
2125
+ correct one it could only collapse, so the only lossless spelling was joining four
2126
+ paragraphs with `<br>` into a 2,400-character line. The first line is the `why` the
2127
+ schema checks, exactly as before; the rest is the tail, written verbatim because no
2128
+ field holds it. `lines` is what makes this legible rather than a mode: it is already the
2129
+ caller saying they read the span, and a multi-line `why` without it is still a shell
2130
+ that expanded something.
2131
+ """
2132
+ _refuse_absent(config, **{"--why": why, "--part": part})
2133
+ ledger = config.document("changelog")
2134
+ where = config.relative(config.path("changelog"))
2135
+ twins = tuple(entry for entry in ledger.entries if entry.task.id == task_id)
2136
+ if not twins:
2137
+ raise NotRecorded(
2138
+ task_id, where, open_line=task_id in config.document("roadmap").by_id()
2139
+ )
2140
+ if len(twins) > 1:
2141
+ raise Ambiguous(task_id, where, tuple(entry.lineno for entry in twins))
2142
+
2143
+ entry = twins[0]
2144
+ if part is not None and entry.task.part is None:
2145
+ # Unless the roadmap still carries it as a **live partial**, which is the one state
2146
+ # this refusal's own sentence names and never asked about (RK1046). A ⏳ line beside
2147
+ # an unqualified entry is the two files contradicting each other — the line says a
2148
+ # half landed, the entry says the whole did — and every verb refused it: `ship` and
2149
+ # `retire` both raise `AlreadyRecorded`, the gate is deliberately silent (RK121), and
2150
+ # this door sent the caller to `ship --part`, which sent them back here. A cycle, and
2151
+ # each refusal correct about its own invariant.
2152
+ #
2153
+ # The docstring above is why this is the door that gives: adding a qualifier is wrong
2154
+ # where the line "is gone or closed", and here it is neither. So the write is exactly
2155
+ # the correction that makes the two files agree, after which the completion path a
2156
+ # partial already has — `ship <id>` with no `--part` — closes it.
2157
+ open_line = config.document("roadmap").by_id().get(task_id)
2158
+ if open_line is None or open_line.task.status != PARTIAL:
2159
+ raise NoQualifier(task_id, entry.lineno)
2160
+
2161
+ sentence, below = _unwrapped(why, lines)
2162
+ wanted = replace(
2163
+ entry.task,
2164
+ why=entry.task.why if sentence is None else sentence,
2165
+ part=entry.task.part if part is None else part,
2166
+ )
2167
+ changed = tuple(
2168
+ name
2169
+ for name, before, after in (
2170
+ ("why", entry.task.why, wanted.why),
2171
+ ("part", entry.task.part, wanted.part),
2172
+ )
2173
+ if before != after
2174
+ )
2175
+ # The tail is not a field, so it is not in `changed` and cannot be compared to one: a
2176
+ # `why` whose first line already reads that way still rewrites the paragraphs under it,
2177
+ # and reporting "unchanged" there would be the collapse this task closed, silently.
2178
+ if not changed and not below:
2179
+ return Corrected(task_id=task_id, ledger=ledger, entry=entry)
2180
+
2181
+ # Asked after `changed`, so an amend that alters nothing never demands a count for a
2182
+ # write it is not going to make.
2183
+ counted(task_id, where, entry, lines, verb="correcting it", keeps_tail=True)
2184
+
2185
+ document = ledger.rewrite_entry(entry, ledger.schema.check(wanted), below)
2186
+ return Corrected(
2187
+ task_id=task_id,
2188
+ ledger=document,
2189
+ entry=document.by_id()[task_id],
2190
+ changed=changed,
2191
+ below=len(below),
2192
+ )
2193
+
2194
+
2195
+ def _unwrapped(why: str | None, lines: int | None) -> tuple[str | None, tuple[str, ...]]:
2196
+ """Split a `why` the caller wrote as a span into its first line and its tail (RK1049).
2197
+
2198
+ Only where `lines` above one says the caller read a wrapped entry, which is the whole
2199
+ door: everywhere else a newline in a one-line field is a shell that expanded something,
2200
+ and passing it through would turn `why.newline` — the refusal that names the cause and
2201
+ the remedy — into an entry silently grown by four lines.
2202
+
2203
+ `splitlines` and not `split("\\n")`, because the terminator here is the pipe's: a stdin
2204
+ stream written on Windows arrives CRLF, and a tail split on the newline alone carries a
2205
+ stray carriage return into a file whose endings :meth:`Document.rewrite_entry` supplies.
2206
+ """
2207
+ if why is None or lines is None or lines < 2 or not why.splitlines()[1:]:
2208
+ return why, ()
2209
+ first, *tail = why.splitlines()
2210
+ return first, tuple(tail)
2211
+
2212
+
2213
+ @dataclass(frozen=True, slots=True)
2214
+ class Refiled:
2215
+ """One ledger entry taken out from under one heading and re-placed under another (RK143).
2216
+
2217
+ The shape is the difference from :class:`Corrected`, and it is the whole argument for
2218
+ this being a verb rather than a flag on that one: **two positions**, because the line
2219
+ does not keep its number and a report that named one would be the pretence `amend`
2220
+ refused to make. The ledger and nothing else is opened, for the reason :class:`Dropped`
2221
+ is — a block says where an entry is filed and not what it records, so no annotation, dep
2222
+ or pointer anywhere is derived from it.
2223
+ """
2224
+
2225
+ task_id: str
2226
+ #: The ledger as this write leaves it: the line gone from one block and re-placed under
2227
+ #: the other, and the blank a block emptied by the removal no longer needs.
2228
+ ledger: Document
2229
+ entry: Entry
2230
+ from_block: str
2231
+ to_block: str
2232
+ #: The line it was filed on, which is the half a caller cannot read off the file after.
2233
+ from_line: int
2234
+
2235
+ @property
2236
+ def moved(self) -> bool:
2237
+ """False where the entry was already filed there, and then nothing was written."""
2238
+ return self.from_block != self.to_block
2239
+
2240
+ @property
2241
+ def rendered(self) -> str:
2242
+ return self.entry.raw
2243
+
2244
+ @property
2245
+ def lineno(self) -> int:
2246
+ return self.entry.lineno
2247
+
2248
+ def save(self) -> tuple[Path, ...]:
2249
+ """Write the ledger, and answer it (RK1130). Nothing else was opened, so nothing
2250
+ else can be touched — and the answer is what a `git add --` takes."""
2251
+ return self.ledger.save()
2252
+
2253
+ def event(self, config: Config) -> dict[str, object]:
2254
+ """The roadmap is read and never written (RK67's rule, for the same reason): a block is
2255
+ where an entry is filed, so re-filing one leaves every open line exactly as it was."""
2256
+ from roadkeep.rendering import _event # noqa: PLC0415 - RK260
2257
+
2258
+ return _event(self.task_id, self.to_block, config.document("roadmap"), config)
2259
+
2260
+ def stated(self, config: Config, wrote: Sequence[Path]) -> str:
2261
+ """Both positions, because the line does not keep its number (RK143).
2262
+
2263
+ Beside :meth:`payload` since RK1170.
2264
+ """
2265
+ from roadkeep.rendering import _event_rows, _staging_rows # noqa: PLC0415 - RK260
2266
+
2267
+ where = config.relative(config.path("changelog"))
2268
+ if not self.moved:
2269
+ return (
2270
+ f"{self.task_id} unchanged: the ledger already files it under "
2271
+ f"Block {self.to_block}"
2272
+ )
2273
+ rows = [
2274
+ f"{self.task_id} moved Block {self.from_block} → Block {self.to_block} "
2275
+ f"{where}:{self.from_line} → :{self.lineno}",
2276
+ f" {self.rendered}",
2277
+ " roadmap untouched: a block is where an entry is filed, not what it records",
2278
+ ]
2279
+ rows += _event_rows(self.event(config), " ")
2280
+ rows += _staging_rows(config.relative(one) for one in wrote)
2281
+ return "\n".join(rows)
2282
+
2283
+ def payload(self, config: Config, wrote: Sequence[Path]) -> dict[str, object]:
2284
+ """The same answer as data, naming both positions (RK143)."""
2285
+ from roadkeep.rendering import _wrote_json # noqa: PLC0415 - RK260
2286
+
2287
+ return {
2288
+ "id": self.task_id,
2289
+ "file": config.relative(config.path("changelog")),
2290
+ # Both, because the entry does not keep its number and a payload naming one
2291
+ # position would be the pretence this verb exists not to make.
2292
+ "from": {"block": self.from_block, "line": self.from_line},
2293
+ "to": {"block": self.to_block, "line": self.lineno},
2294
+ **_wrote_json(config, wrote),
2295
+ "moved": self.moved,
2296
+ "rendered": self.rendered,
2297
+ "roadmap": {"touched": False},
2298
+ "event": self.event(config),
2299
+ }
2300
+
2301
+
2302
+ def move(config: Config, task_id: str, *, to_block: str) -> Refiled:
2303
+ """Re-file one ledger entry under another block heading (RK143).
2304
+
2305
+ The door :func:`amend` was right to leave shut and nothing else opened. `ship` files an
2306
+ entry under the block its roadmap line sat in, so a line filed wrongly ships wrongly —
2307
+ and every other verb here declines the repair for a reason of its own: `record add`
2308
+ refuses an id that exists, `drop` wants the id stated twice, :func:`readdress` changes
2309
+ the address and not the heading. What was left was the hand-edit the guard denies.
2310
+
2311
+ Nothing is written until everything validates, as everywhere on the write path (L1): the
2312
+ line is removed and re-placed in memory, so a heading the ledger does not declare raises
2313
+ :class:`~roadkeep.authoring.UnknownBlock` — naming the labels it *does* — over a file
2314
+ still holding every byte it held. Re-placed and not spliced, so the entry lands after the
2315
+ destination's last one exactly as any other write to that block would leave it.
2316
+
2317
+ Refused on an id the ledger states twice, for the reason :func:`amend` is: which of two
2318
+ entries a move was meant for is not a fact any file holds.
2319
+ """
2320
+ ledger = config.document("changelog")
2321
+ where = config.relative(config.path("changelog"))
2322
+ twins = tuple(entry for entry in ledger.entries if entry.task.id == task_id)
2323
+ if not twins:
2324
+ raise NotRecorded(
2325
+ task_id, where, open_line=task_id in config.document("roadmap").by_id()
2326
+ )
2327
+ if len(twins) > 1:
2328
+ raise Ambiguous(task_id, where, tuple(entry.lineno for entry in twins))
2329
+
2330
+ entry = twins[0]
2331
+ if entry.task.block == to_block:
2332
+ # Already there. Reported rather than refused, and the file is not rewritten to the
2333
+ # same bytes: an unchanged file with a moved mtime reads as an edit to every hook
2334
+ # watching it, which is the rule `amend`'s no-op path holds too.
2335
+ return Refiled(
2336
+ task_id=task_id,
2337
+ ledger=ledger,
2338
+ entry=entry,
2339
+ from_block=entry.task.block,
2340
+ to_block=to_block,
2341
+ from_line=entry.lineno,
2342
+ )
2343
+ # The whole entry moves, continuation lines included (RK157): the schema renders one line
2344
+ # and a wrapped entry's remaining lines are prose no task holds, so a move that re-rendered
2345
+ # alone would take the paragraph out of the file in the name of re-filing it.
2346
+ carrying = tuple(
2347
+ line.rstrip("\r\n") for line in ledger.lines[entry.lineno : entry.stop]
2348
+ )
2349
+ insertion = place(
2350
+ remove_entry(ledger, entry),
2351
+ replace(entry.task, block=to_block),
2352
+ carrying=carrying,
2353
+ role="changelog",
2354
+ config=config,
2355
+ )
2356
+ return Refiled(
2357
+ task_id=task_id,
2358
+ ledger=insertion.document,
2359
+ entry=insertion.entry,
2360
+ from_block=entry.task.block,
2361
+ to_block=to_block,
2362
+ from_line=entry.lineno,
2363
+ )
2364
+
2365
+
2366
+ @dataclass(frozen=True, slots=True)
2367
+ class Readdressed:
2368
+ """One of two entries for an id, given an address of its own (RK127).
2369
+
2370
+ The ledger and nothing else, and the entry does not move: it keeps its line, so the file
2371
+ still reads in the order work landed and the diff is the number. Nothing elsewhere is
2372
+ re-derived either — every `(deps: <id> ✅)` in the backlog was written about the entry
2373
+ that keeps the id, which is the one this leaves alone.
2374
+ """
2375
+
2376
+ task_id: str
2377
+ to: str
2378
+ ledger: Document
2379
+ entry: Entry
2380
+ #: The line that keeps the original id — the delivery the rest of the repository names.
2381
+ kept: int
2382
+ kept_marker: str = ""
2383
+
2384
+ @property
2385
+ def rendered(self) -> str:
2386
+ return self.entry.raw
2387
+
2388
+ @property
2389
+ def lineno(self) -> int:
2390
+ return self.entry.lineno
2391
+
2392
+ def save(self) -> tuple[Path, ...]:
2393
+ """Write the ledger, and answer it (RK1130). Nothing else was opened, so nothing
2394
+ else can be touched — and the answer is what a `git add --` takes."""
2395
+ return self.ledger.save()
2396
+
2397
+ def stated(self, config: Config, wrote: Sequence[Path]) -> str:
2398
+ """The new address, and the line that keeps the old one (RK127).
2399
+
2400
+ Beside :meth:`payload` since RK1170.
2401
+ """
2402
+ from roadkeep.rendering import _staging_rows # noqa: PLC0415 - RK260
2403
+
2404
+ ledger = config.relative(config.path("changelog"))
2405
+ rows = [
2406
+ f"{self.task_id} → {self.to} {ledger}:{self.lineno}",
2407
+ f" {self.rendered}",
2408
+ f" kept {self.kept_marker} line {self.kept} still carries {self.task_id}: "
2409
+ f"every annotation elsewhere was written about that delivery",
2410
+ ]
2411
+ rows += _staging_rows(config.relative(one) for one in wrote)
2412
+ return "\n".join(rows)
2413
+
2414
+ def payload(self, config: Config, wrote: Sequence[Path]) -> dict[str, object]:
2415
+ """The same answer as data, with the delivery the id stayed on (RK127)."""
2416
+ from roadkeep.rendering import _wrote_json # noqa: PLC0415 - RK260
2417
+
2418
+ return {
2419
+ "id": self.task_id,
2420
+ **_wrote_json(config, wrote),
2421
+ "to": self.to,
2422
+ "file": config.relative(config.path("changelog")),
2423
+ # The entry does not move: it keeps its line, so the ledger still reads in the
2424
+ # order work landed and the diff is the number.
2425
+ "line": self.lineno,
2426
+ "rendered": self.rendered,
2427
+ "kept": {"line": self.kept, "marker": self.kept_marker},
2428
+ "roadmap": {"touched": False},
2429
+ }
2430
+
2431
+
2432
+ def drop(config: Config, task_id: str, *, lineno: int | None = None) -> Dropped:
2433
+ """Remove one of two ledger entries for an id, and never guess which (RK67, RK127).
2434
+
2435
+ Refused unless the id is recorded **twice**, so the operation is de-duplication and can
2436
+ never be a deletion of history: what stays is the first entry, where a reader who already
2437
+ found this decision found it. With three, the last goes and a second call is the next one —
2438
+ convergent by construction, rather than one command that decides how many to remove.
2439
+
2440
+ And refused again unless the entries **say the same thing**. "Duplicate" reads as "the
2441
+ same work recorded again", which is a slip; two entries that state different outcomes are
2442
+ two deliveries that were never one, and dropping either destroys one of them (RK127). The
2443
+ reader who has both in front of them says which with `lineno`, and the entry they name is
2444
+ the one that goes — including the first, which the default never picks.
2445
+
2446
+ The whole write is the ledger, which is what makes this narrow enough to exist at all: no
2447
+ dep annotation changes when an id the file still records goes from two entries to one.
2448
+ """
2449
+ ledger = config.document("changelog")
2450
+ where = config.relative(config.path("changelog"))
2451
+ twins = tuple(entry for entry in ledger.entries if entry.task.id == task_id)
2452
+ if len(twins) < 2:
2453
+ raise NotDuplicated(task_id, where, tuple(entry.lineno for entry in twins))
2454
+
2455
+ linenos = tuple(entry.lineno for entry in twins)
2456
+ if lineno is None:
2457
+ if not _one_entry_twice(ledger, twins):
2458
+ raise NotRedundant(task_id, where, linenos)
2459
+ going = twins[-1]
2460
+ else:
2461
+ found = next((entry for entry in twins if entry.lineno == lineno), None)
2462
+ if found is None:
2463
+ raise NoSuchEntry(task_id, lineno, linenos)
2464
+ going = found
2465
+
2466
+ kept = next(entry for entry in twins if entry.lineno != going.lineno)
2467
+ return Dropped(
2468
+ task_id=task_id,
2469
+ ledger=remove_entry(ledger, going),
2470
+ removed_from=going.lineno,
2471
+ kept=kept.lineno,
2472
+ kept_marker=kept.task.status,
2473
+ block=kept.task.block,
2474
+ marker=going.task.status,
2475
+ )
2476
+
2477
+
2478
+ def readdress(
2479
+ config: Config, task_id: str, *, lineno: int | None = None, to: str | None = None
2480
+ ) -> Readdressed:
2481
+ """Give one of two entries for an id an address of its own (RK127).
2482
+
2483
+ The counterpart of `renumber` (RK97) for the file that verb deliberately never opens —
2484
+ and the reason the two are not one door is the reason it does not: renumbering a *record*
2485
+ is how a `git log -S` starts returning two unrelated designs. That argument holds for an
2486
+ id one entry carries. It inverts for an id two carry, because the collision is already
2487
+ what makes the history unreadable, and until one of them has its own number there is no
2488
+ query that separates them.
2489
+
2490
+ So it is refused on anything but a collision, and which of the entries moves is the
2491
+ caller's: the one that earned the id from a roadmap line is normally the one to leave
2492
+ alone, and nothing in the file says which that is.
2493
+ """
2494
+ ledger = config.document("changelog")
2495
+ where = config.relative(config.path("changelog"))
2496
+ twins = tuple(entry for entry in ledger.entries if entry.task.id == task_id)
2497
+ if len(twins) < 2:
2498
+ raise NotDuplicated(task_id, where, tuple(entry.lineno for entry in twins))
2499
+
2500
+ linenos = tuple(entry.lineno for entry in twins)
2501
+ if lineno is None:
2502
+ raise Unchosen(task_id, where, linenos)
2503
+ going = next((entry for entry in twins if entry.lineno == lineno), None)
2504
+ if going is None:
2505
+ raise NoSuchEntry(task_id, lineno, linenos)
2506
+
2507
+ if to is None:
2508
+ to = next_id(config, family_of(config, task_id))
2509
+ if to == task_id:
2510
+ raise SameId(task_id)
2511
+ if not config.schema.id_pattern().match(to):
2512
+ raise NotAnId(to, config.schema.id_pattern().pattern)
2513
+ # `--to`, this verb's own spelling for the number (RK1212).
2514
+ refuse_reuse(config, to, flag="--to")
2515
+
2516
+ document = ledger.replace_task(going, ledger.schema.check(replace(going.task, id=to)))
2517
+ kept = next(entry for entry in twins if entry.lineno != going.lineno)
2518
+ return Readdressed(
2519
+ task_id=task_id,
2520
+ to=to,
2521
+ ledger=document,
2522
+ entry=document.by_id()[to],
2523
+ kept=kept.lineno,
2524
+ kept_marker=kept.task.status,
2525
+ )
2526
+
2527
+
2528
+ def _one_entry_twice(document: Document, twins: tuple[Entry, ...]) -> bool:
2529
+ """Do these entries state the same thing, id and position aside?
2530
+
2531
+ What the tool can read, and the whole of it: a slip records the same work again, so the
2532
+ marker, the symptom, the sentence, any qualifier and every line the bullet wraps onto
2533
+ all match. Anything else is a difference somebody wrote on purpose, and reading prose to
2534
+ decide whether it was a correction or a second delivery is the judgement L4 keeps out of
2535
+ this tool.
2536
+
2537
+ The wrapped lines are compared and not the fields alone (RK179): on a hand-written
2538
+ ledger a `why` is only as much of the sentence as fits on line one, so two entries whose
2539
+ every parsed field matches can still diverge two lines down — and this door answering
2540
+ "the same" there is `drop` removing a delivery it was built to be incapable of removing.
2541
+
2542
+ The **block** is deliberately not compared. It says where the entry was filed and not
2543
+ what it records, and the same entry appearing under two headings is exactly the slip
2544
+ this door was written for.
2545
+ """
2546
+ stated = {
2547
+ (t.task.status, t.task.symptom, t.task.why, t.task.part, _wrapped_onto(document, t))
2548
+ for t in twins
2549
+ }
2550
+ return len(stated) == 1
2551
+
2552
+
2553
+ def _wrapped_onto(document: Document, entry: Entry) -> tuple[str, ...]:
2554
+ """The lines an entry owns below its first, verbatim — empty for every governed one."""
2555
+ return tuple(
2556
+ line.rstrip("\r\n") for line in document.lines[entry.index + 1 : entry.stop]
2557
+ )
2558
+
2559
+
2560
+ def _refuse_absent(config: Config, **prose: str | None) -> None:
2561
+ """Refuse ledger prose that names a path this repository lacks (RK497, L1).
2562
+
2563
+ Called with the arguments **this** verb was given, keyed by the flag that carries each,
2564
+ so the refusal names the one the caller has to correct rather than the sentence it landed
2565
+ in. Every one of them is asked, and the refusal names every token, for the reason a
2566
+ schema refusal states every violation at once: one problem per run turns a single fix
2567
+ into a conversation.
2568
+
2569
+ Cheap on the sentences anybody means to write: :func:`~roadkeep.linting.unresolved` asks
2570
+ the filesystem per token and asks git only for one that fails (RK222).
2571
+ """
2572
+ # Deferred, and it is the gate: `linting` reads the files this module writes, so the
2573
+ # top-level edge would run the wrong way (RK260).
2574
+ from roadkeep.linting import unresolved # noqa: PLC0415 - RK497
2575
+
2576
+ file = config.relative(config.path("changelog"))
2577
+ for named, text in prose.items():
2578
+ if not text:
2579
+ continue
2580
+ missing = unresolved(config, text)
2581
+ if missing:
2582
+ raise NoSuchPath(named, missing, file)
2583
+
2584
+
2585
+ def ship(
2586
+ config: Config,
2587
+ task_id: str,
2588
+ *,
2589
+ why: str | None = None,
2590
+ part: str | None = None,
2591
+ remainder: str | None = None,
2592
+ lines: int | None = None,
2593
+ superseded: str | None = None,
2594
+ recorded_in: str | None = None,
2595
+ decides: str | None = None,
2596
+ decides_ref: str | None = None,
2597
+ ) -> Departure | Closure | Partial:
2598
+ """Move one task from the backlog to the ledger. Validates all three edits first.
2599
+
2600
+ Or, when the ledger already records the id, close the roadmap line alone (RK62): that is
2601
+ not a second entry, it is the rest of a transaction that never completed — which is the
2602
+ shape adoption produces, because a project that moved a task to its changelog by hand and
2603
+ left a pointer behind was following its own convention.
2604
+
2605
+ `why` is refused on that path rather than ignored: it restates the *ledger's* sentence, and
2606
+ the ledger is not written here. A flag silently dropped is a flag the caller believes took
2607
+ effect.
2608
+
2609
+ `part` is the third answer (RK121): **this much of it landed**. The entry is written with
2610
+ the qualifier and the roadmap line stays, because the work is not finished. A later
2611
+ `ship` with no `part` *completes* it — replacing the entry rather than adding a second —
2612
+ which is the whole reason this is a verb and not a spelling convention: only a command
2613
+ knows when "local half" stopped being true.
2614
+
2615
+ That completion is a **span** rewrite where the ledger arrived wrapped (RK193), and
2616
+ `lines` is the caller saying how many it replaces — the count `record amend` already
2617
+ takes, at the one other door reaching the same write. It is a flag on this verb rather
2618
+ than a detour through that one because the caller asked to finish work; it is refused on
2619
+ every path that replaces no entry, and its absence over a wrapped partial is refused too.
2620
+
2621
+ `superseded` is the fourth, and the only one about the file this command **deletes**
2622
+ (RK310). A design is written when a task is filed and read when somebody claims it, and
2623
+ in between the codebase moves — measured in one block of eleven tasks, twice, where the
2624
+ section argued at length from a fact that had stopped being true and the implementation
2625
+ was smaller and better once it was checked against the code. Both times `ship` then
2626
+ deleted the section with no trace that its reasoning had been overtaken, so the only
2627
+ reader who could ever find out was the one who had already done the work. The clause is
2628
+ appended to the ledger's sentence, which is the one place the section's address and the
2629
+ outcome already meet: derived up to the address, prose from there on (L4), and refused at
2630
+ the two doors where it would be untrue — a line that pointed at no design, and a partial,
2631
+ whose section stays because the rest of the work still reads it.
2632
+
2633
+ `recorded_in` is the fifth, and the other half of that one (RK1267). A section holds the
2634
+ investigation, the criterion and the decision, and the flag above types the deletion only
2635
+ as *stale*: nothing said where the part that outlives the code went, so a definition of
2636
+ done written as a design is deleted correctly and survives nowhere. The clause is composed
2637
+ by the same writer, into the same sentence, after the supersession where both were passed —
2638
+ and it is derived whole, the anchor being the pointer the line is losing and the value a
2639
+ path, so this writes no prose (L4). Refused at the same two doors, and at a third of its
2640
+ own: a path this repository does not have, which is `path.missing` asked before the entry
2641
+ lands rather than by the gate afterwards (RK497).
2642
+
2643
+ `decides` is the sixth, and the only one that writes a **fourth file** (RK1269). The other
2644
+ two type the deleted section — stale, or moved — and this one takes the third of its three
2645
+ contents out whole: the decision, the constraint that has to stay true after the code
2646
+ moves. It lands as one line in the decisions role, under the same block and the same
2647
+ limits, with the task's own symptom as the claim and this sentence as the reason — which
2648
+ is a record this format already writes, an ADR being the pair it has had all along. Never
2649
+ the section copied over, which is the accreting rationale file this tool exists to refuse;
2650
+ refused where the project declares no such role, naming `declare decisions`, and on a
2651
+ partial, whose section stays and so has outlived nothing yet.
2652
+ """
2653
+ _refuse_absent(
2654
+ config,
2655
+ **{
2656
+ "--why": why,
2657
+ "--part": part,
2658
+ "--decides": decides,
2659
+ "--superseded-design": superseded,
2660
+ # Backticked so the one definition of missing can see it (RK497, RK1267): the
2661
+ # reader takes paths out of *prose*, and this argument is a bare token until the
2662
+ # clause is composed — which happens after every refusal this call can raise.
2663
+ "--recorded-in": None if recorded_in is None else f"`{recorded_in}`",
2664
+ },
2665
+ )
2666
+ if part is not None:
2667
+ if lines is not None:
2668
+ # Before the ledger is read at all (RK1128): what refuses here is the flag pair and
2669
+ # not the file, so a message about what the ledger holds would be an answer to a
2670
+ # question this path never asks.
2671
+ raise NoCompletion(
2672
+ task_id, config.relative(config.path("changelog")), also_part=True
2673
+ )
2674
+ if superseded is not None:
2675
+ raise NoSupersession(task_id, part)
2676
+ if recorded_in is not None:
2677
+ raise NoSupersession(task_id, part, "--recorded-in")
2678
+ if decides is not None:
2679
+ raise NoDecision(task_id, part)
2680
+ if decides_ref is not None:
2681
+ # The flag that addresses a decision's body, on the call that files none
2682
+ # (RK1363): the refusal above already covers `--decides`, and this one is the
2683
+ # same sentence about the argument that rides with it.
2684
+ raise DecidesAlone(task_id)
2685
+ return _partial(config, task_id, part, why, remainder)
2686
+ recorded = _already_recorded(config, task_id)
2687
+ if recorded is None:
2688
+ return _depart(
2689
+ config,
2690
+ task_id,
2691
+ config.schema.shipped_marker,
2692
+ why,
2693
+ lines,
2694
+ superseded=superseded,
2695
+ recorded_in=recorded_in,
2696
+ decides=decides,
2697
+ decides_ref=decides_ref,
2698
+ )
2699
+ if why is not None:
2700
+ raise NoRestatement(task_id, recorded)
2701
+ if superseded is not None:
2702
+ raise NoRestatement(task_id, recorded, "--superseded-design")
2703
+ if recorded_in is not None:
2704
+ raise NoRestatement(task_id, recorded, "--recorded-in")
2705
+ if lines is not None:
2706
+ raise NoCompletion(task_id, config.relative(config.path("changelog")))
2707
+ # And this one is **not** refused here (RK1269): the two flags above land in a ledger
2708
+ # sentence this path does not write, and a decision lands in a file of its own — which
2709
+ # this path does write, because it is the closure that deletes the section.
2710
+ return _close(config, task_id, recorded, decides=decides, decides_ref=decides_ref)
2711
+
2712
+
2713
+ def retire(
2714
+ config: Config,
2715
+ task_id: str,
2716
+ *,
2717
+ reason: str,
2718
+ superseded_by: str | None = None,
2719
+ ) -> Departure:
2720
+ """Record a line leaving without shipping: superseded by a named id, or abandoned.
2721
+
2722
+ The `why` is a derived prefix plus the author's own sentence — the same split as every
2723
+ other field the tool fills in (RK8): "superseded by RK41" is a fact this command holds
2724
+ and the reason is prose it will not write (L4).
2725
+ """
2726
+ _refuse_absent(config, **{"--reason": reason})
2727
+ holder: str | None = None
2728
+ if superseded_by is not None:
2729
+ if superseded_by == task_id:
2730
+ raise NoSuchReplacement(superseded_by, task_id, itself=True)
2731
+ holder = _holding(Backlog.load(config), superseded_by)
2732
+ if holder is None:
2733
+ raise NoSuchReplacement(superseded_by, task_id)
2734
+ why = retiring(reason, superseded_by)
2735
+ return _depart(
2736
+ config,
2737
+ task_id,
2738
+ config.schema.retired_marker,
2739
+ why,
2740
+ replacement_in=holder,
2741
+ replacement=superseded_by,
2742
+ )
2743
+
2744
+
2745
+ def _holding(backlog: Backlog, task_id: str) -> str | None:
2746
+ """The role whose file holds this id, or `None` when none of the three does (RK244).
2747
+
2748
+ :class:`~roadkeep.backlog.Backlog` and not three `config.document` calls, because that
2749
+ is the reader that already knows how many files an id can live in — the set built by
2750
+ hand here counted two, and RK96 had made it three.
2751
+ """
2752
+ for role, document in (
2753
+ ("roadmap", backlog.roadmap),
2754
+ ("changelog", backlog.ledger),
2755
+ ("deferred", backlog.store),
2756
+ ):
2757
+ if document is not None and task_id in document.by_id():
2758
+ return role
2759
+ return None
2760
+
2761
+
2762
+ #: How an entry names the one that replaced it (RK395). Parenthesised into the ledger's own
2763
+ #: sentence by :func:`_parenthesised`, for `--superseded-design`'s reason (RK310): the line has
2764
+ #: one prose slot, and the clause is a fact this command holds rather than prose it writes
2765
+ #: (L4, RK8). The wording is `retire`'s, the shape being that verb with the target file changed.
2766
+ _SUPERSEDED = "superseded by {replacement}"
2767
+
2768
+
2769
+ class NotDecided(KeyError):
2770
+ """An id the decisions file does not carry, at the door that only reads it (RK1274).
2771
+
2772
+ :class:`NotRecorded` one file over, and separate for its reason: a caller superseding a
2773
+ decision holds *that* file's address, and being told the ledger does not have it would
2774
+ send them to the file where it correctly is not. Which of the two ids is missing is named,
2775
+ because this call takes two and a message that said neither would be read twice.
2776
+ """
2777
+
2778
+ def __init__(self, task_id: str, where: str, flag: str) -> None:
2779
+ self.task_id = task_id
2780
+ self.flag = flag
2781
+ super().__init__(
2782
+ f"{where} records no decision {task_id}, which is what {flag} names: a decision "
2783
+ f"is written by `ship --decides` at the moment a design is deleted, so the one "
2784
+ f"replacing this must already be filed before it can replace anything"
2785
+ )
2786
+
2787
+
2788
+ class AlreadySuperseded(ValueError):
2789
+ """A decision this file already marks as replaced (RK1274).
2790
+
2791
+ Refused rather than pointed a second time, which is the role's whole rule read forwards:
2792
+ nothing here is ever deleted, so an entry carrying two forward pointers is a chain a
2793
+ reader has to date to walk — and the file records no dates (a non-goal). One decision is
2794
+ superseded once; what replaces its replacement supersedes *that*.
2795
+ """
2796
+
2797
+ def __init__(self, task_id: str, where: str, lineno: int, marker: str) -> None:
2798
+ self.task_id = task_id
2799
+ self.lineno = lineno
2800
+ super().__init__(
2801
+ f"{where}:{lineno} already marks {task_id} {marker}: a decision is superseded "
2802
+ f"once and the entry that replaced it is named in its own sentence — what "
2803
+ f"replaces the replacement supersedes that one, which is the chain read forwards"
2804
+ )
2805
+
2806
+
2807
+ @dataclass(frozen=True, slots=True)
2808
+ class Superseded:
2809
+ """One decision marked replaced, and the entry that replaced it."""
2810
+
2811
+ task_id: str
2812
+ replacement: str
2813
+ document: Document
2814
+ lineno: int
2815
+ #: The sentence as it now reads, which is the whole of what the write changed.
2816
+ rendered: str = ""
2817
+
2818
+ def save(self) -> tuple[Path, ...]:
2819
+ return self.document.save()
2820
+
2821
+ def stated(self, config: Config, wrote: Sequence[Path]) -> str:
2822
+ from roadkeep.rendering import _staging_rows # noqa: PLC0415 - RK260
2823
+
2824
+ where = config.relative(config.path("decisions"))
2825
+ rows = [
2826
+ f"{where}:{self.lineno} {self.task_id} superseded by {self.replacement}",
2827
+ f" {self.rendered}",
2828
+ # The rule, said at the one door that could be mistaken for a deletion: both
2829
+ # lines stay and the marker is what says which is live.
2830
+ f" kept {self.replacement} stands and {self.task_id} is history — nothing "
2831
+ f"in this file is ever deleted",
2832
+ ]
2833
+ rows += _staging_rows(config.relative(one) for one in wrote)
2834
+ return "\n".join(rows)
2835
+
2836
+ def payload(self, config: Config, wrote: Sequence[Path]) -> dict[str, object]:
2837
+ from roadkeep.rendering import _wrote_json # noqa: PLC0415 - RK260
2838
+
2839
+ return {
2840
+ "id": self.task_id,
2841
+ "superseded_by": self.replacement,
2842
+ "file": config.relative(config.path("decisions")),
2843
+ "line": self.lineno,
2844
+ "rendered": self.rendered,
2845
+ **_wrote_json(config, wrote),
2846
+ }
2847
+
2848
+
2849
+ def supersede(config: Config, task_id: str, *, by: str) -> Superseded:
2850
+ """Mark one decision replaced by another, in the file that holds both (RK1274).
2851
+
2852
+ The role's **one** departure, and what separates it from the ledger. A roadmap line leaves
2853
+ by three doors; a decision leaves by being replaced, so nothing here is deleted and the
2854
+ file grows only by decisions somebody actually made.
2855
+
2856
+ `retire` is the wrong verb and its shape is the right one: that one starts from an open
2857
+ roadmap line, and a decision has none — the line it came from was in the ledger before
2858
+ the decision was written. So this starts from the decisions file itself and makes the two
2859
+ edits `record add --supersedes` makes one file over: the forward pointer onto the entry
2860
+ that is now stale, and its marker, in one write. Two records of one reversal that do not
2861
+ name each other is the state RK395 closed for the ledger, and this is that closure here.
2862
+
2863
+ Derived end to end (RK8, L4): the clause names the replacing entry and the marker is the
2864
+ role's own retired one, so there is no sentence for a caller to spell two ways — and no
2865
+ reason field, because *why* one decision replaced another is the argument in the entry
2866
+ that replaced it, already written and one line away.
2867
+ """
2868
+ if not config.has("decisions"):
2869
+ raise NoDecisions(task_id, config.relative(config.source or config.root))
2870
+ where = config.relative(config.path("decisions"))
2871
+ document = config.document("decisions")
2872
+ if task_id == by:
2873
+ # Its own refusal and not `retire`'s, which names that verb and the abandoned door:
2874
+ # neither exists here, and a message about them would send the caller to the backlog.
2875
+ raise ValueError(
2876
+ f"{task_id} cannot supersede itself: what replaces a decision is a *second* "
2877
+ f"decision, filed by the `ship --decides` of the work that changed it — and this "
2878
+ f"call is the one that then says which of the two is live"
2879
+ )
2880
+ standing = _only(document, task_id, where, "the id")
2881
+ replacement = _only(document, by, where, "--by")
2882
+ schema = config.schema_for("decisions")
2883
+ if standing.task.status != schema.shipped_marker:
2884
+ raise AlreadySuperseded(task_id, where, standing.lineno, standing.task.status)
2885
+ wanted = replace(
2886
+ standing.task,
2887
+ status=schema.retired_marker,
2888
+ why=_parenthesised(standing.task.why, _SUPERSEDED.format(replacement=by)),
2889
+ )
2890
+ # `replace_task` and not a span rewrite, for `_supersede`'s reason (RK1053): the clause
2891
+ # lands in the `why`, which is the first line's text, so re-rendering that line reproduces
2892
+ # every field this entry holds and anything beneath it is not this write's to touch.
2893
+ updated = document.replace_task(standing, document.schema.check(wanted))
2894
+ return Superseded(
2895
+ task_id=task_id,
2896
+ replacement=replacement.task.id,
2897
+ document=updated,
2898
+ lineno=standing.lineno,
2899
+ rendered=updated.by_id()[task_id].raw.rstrip("\r\n"),
2900
+ )
2901
+
2902
+
2903
+ def _only(document: Document, task_id: str, where: str, flag: str) -> Entry:
2904
+ """The one entry an id names in the decisions file, refused where there are none or two.
2905
+
2906
+ `_supersede`'s two refusals, kept here rather than shared with it: that one reads the
2907
+ ledger and names `record` in what it says, and a caller holding a decision's address
2908
+ would be sent to the wrong file by a message that was right about the other one.
2909
+ """
2910
+ twins = tuple(entry for entry in document.entries if entry.task.id == task_id)
2911
+ if not twins:
2912
+ raise NotDecided(task_id, where, flag)
2913
+ if len(twins) > 1:
2914
+ raise Ambiguous(task_id, where, tuple(entry.lineno for entry in twins))
2915
+ return twins[0]
2916
+
2917
+
2918
+ def record(
2919
+ config: Config,
2920
+ *,
2921
+ block: str,
2922
+ symptom: str,
2923
+ why: str,
2924
+ task_id: str | None = None,
2925
+ supersedes: str | None = None,
2926
+ lines: int | None = None,
2927
+ ) -> Record:
2928
+ """Write one ledger entry directly, for shipped work no open line can carry (RK41).
2929
+
2930
+ The job, stated as the job rather than as the case that produced it (RK1050): every
2931
+ other door into the ledger begins from a roadmap line, so this is the one for work that
2932
+ has none. Never planned is the first instance and not the definition — a task that was
2933
+ planned, shipped, and recorded inside a *second* task's sentence is invisible to every
2934
+ reader that keys on an id and needs its own entry, and so does a revert
2935
+ (``supersedes``). A description naming only the first case reads as a refusal for the
2936
+ others, and the search moves on to verbs that really do refuse.
2937
+
2938
+ The fields are refused at input exactly as `add` refuses them (L1), against
2939
+ :meth:`~roadkeep.kernel.schema.Schema.as_ledger` rather than the roadmap's schema — so the
2940
+ marker is ✅, the block heading must already be declared in the ledger, and a dep or a
2941
+ pointer is not accepted rather than dropped: there is no open line for a dep to be a
2942
+ planning fact about, and no rationale section for a pointer to resolve to.
2943
+
2944
+ The id is derived like any other (RK4) and refused if anything anywhere already
2945
+ mentions it, so recording cannot quietly claim an id the roadmap is holding. The
2946
+ `symptom` rule is the one that must not soften: what did not work, stated so it could
2947
+ have been falsified — never the name of the patch that closed it (L4 leaves that to
2948
+ the caller, here as everywhere).
2949
+
2950
+ ``supersedes`` is the **revert**, and it is one transaction rather than two (RK395).
2951
+ Measured on Turing: T922 and T924 shipped and were reverted an hour later, and recording
2952
+ that took three attempts at the wrong verb. `retire` starts from a roadmap line `ship`
2953
+ had already removed; `record drop` refuses anything but a duplicate, rightly, because
2954
+ removing the only record of a decision is deleting history. What was left was this
2955
+ command — which wrote the revert as an entry the earlier one knew nothing about, so a
2956
+ reader who found T922 read an entry saying it shipped with no pointer to the one saying
2957
+ it did not hold. Both entries stay, because both happened; what is added is the forward
2958
+ pointer `retire --superseded-by` already writes one file over, appended to the earlier
2959
+ sentence in **this** write rather than in a second one a crash can lose.
2960
+ """
2961
+ mention: IdRef | None = None
2962
+ if task_id is None:
2963
+ task_id = next_id(config)
2964
+ else:
2965
+ # `refuse_occupied` and not `refuse_reuse` (RK1051): the other doors move a task
2966
+ # *onto* a number and this one gives a number the entry it lacks, so a sentence
2967
+ # citing the id is the state being repaired rather than the collision being avoided.
2968
+ mention = refuse_occupied(config, task_id)
2969
+
2970
+ _refuse_absent(config, **{"--symptom": symptom, "--why": why})
2971
+ ledger = config.document("changelog")
2972
+ marker = config.schema.shipped_marker
2973
+ if supersedes is not None:
2974
+ ledger = _supersede(config, ledger, supersedes, task_id, lines)
2975
+ insertion = place(
2976
+ ledger,
2977
+ Task(id=task_id, status=marker, block=block, symptom=symptom, why=why),
2978
+ role="changelog",
2979
+ config=config,
2980
+ )
2981
+ # Resolved against the state this write creates, for the same reason `_depart` does it
2982
+ # (RK8): an id is normally too new for any line to name, but a range dep can already
2983
+ # span it, and an annotation left un-derived by one door is one nothing revisits.
2984
+ derived = refresh(
2985
+ Backlog.during(
2986
+ config, roadmap=config.document("roadmap"), ledger=insertion.document
2987
+ )
2988
+ )
2989
+ return Record(
2990
+ task_id=task_id,
2991
+ ledger=insertion,
2992
+ roadmap=derived.document,
2993
+ refreshed=derived.changed,
2994
+ marker=marker,
2995
+ # Read back off the document the insertion left, because the entry above it moved if
2996
+ # the new line landed first — a report naming the line it was read at would name
2997
+ # whatever came up into its place (the care RK357 takes about the same address).
2998
+ superseded=(
2999
+ None if supersedes is None else insertion.document.by_id()[supersedes]
3000
+ ),
3001
+ mentioned=mention,
3002
+ )
3003
+
3004
+
3005
+ def _supersede(
3006
+ config: Config,
3007
+ ledger: Document,
3008
+ task_id: str,
3009
+ replacement: str,
3010
+ lines: int | None,
3011
+ ) -> Document:
3012
+ """Append the forward pointer to the entry this write replaces (RK395).
3013
+
3014
+ The rewrite `record amend` makes, with the sentence derived rather than passed: what a
3015
+ reverted entry is missing is not a better `why`, it is the address of the entry that says
3016
+ it did not hold — and an author asked to compose that clause is an author who can spell it
3017
+ two ways (RK8's split, and `retire --superseded-by`'s exactly).
3018
+
3019
+ Its refusals are that verb's, for the same reasons: an id the ledger does not carry has no
3020
+ sentence to append to, and an id it carries **twice** leaves which entry unanswerable by
3021
+ any file. Nothing is written by this function; the caller places the new entry into what it
3022
+ returns, so the two edits reach disk together or neither does.
3023
+
3024
+ A **wrapped** entry costs nothing here, and used to cost a `--lines` (RK179, RK1053). The
3025
+ clause is appended to the `why`, which is the text of the first line, so that line alone
3026
+ reproduces every field this task holds — and rewriting the span was authorising a deletion
3027
+ the write does not need, in a call that asked to change no word of somebody's paragraph.
3028
+ The count is therefore refused rather than accepted-and-ignored: see :class:`NoSpan`.
3029
+ """
3030
+ # No self-pointer check: the replacement is derived, or `refuse_reuse` refused an id any
3031
+ # file already mentions, so an entry naming itself is a state neither door can reach.
3032
+ where = config.relative(config.path("changelog"))
3033
+ twins = tuple(entry for entry in ledger.entries if entry.task.id == task_id)
3034
+ if not twins:
3035
+ raise NotRecorded(
3036
+ task_id, where, open_line=task_id in config.document("roadmap").by_id()
3037
+ )
3038
+ if len(twins) > 1:
3039
+ raise Ambiguous(task_id, where, tuple(entry.lineno for entry in twins))
3040
+
3041
+ entry = twins[0]
3042
+ if lines is not None:
3043
+ raise NoSpan(task_id, where)
3044
+ wanted = replace(
3045
+ entry.task,
3046
+ why=_parenthesised(entry.task.why, _SUPERSEDED.format(replacement=replacement)),
3047
+ )
3048
+ # `replace_task` and not `rewrite_entry` (RK1053): the clause is appended to the `why`,
3049
+ # which is the text of the **first** line, so re-rendering that line alone reproduces
3050
+ # every field this task holds and the continuation beneath it is not this write's to
3051
+ # touch. Rewriting the span was the wider call — a caller who asked to add a pointer,
3052
+ # losing an entry's paragraphs, on the file whose purpose is that history survives.
3053
+ return ledger.replace_task(entry, ledger.schema.check(wanted))
3054
+
3055
+
3056
+ def _partial(
3057
+ config: Config, task_id: str, part: str, why: str | None, remainder: str | None = None
3058
+ ) -> Partial:
3059
+ """Record the half that landed and leave the line open (RK121)."""
3060
+ roadmap = config.document("roadmap")
3061
+ ledger = config.document("changelog")
3062
+
3063
+ entry = roadmap.by_id().get(task_id)
3064
+ if entry is None:
3065
+ raise NotOpen(
3066
+ task_id,
3067
+ config.relative(config.path("roadmap")),
3068
+ Whereabouts.of(config, task_id),
3069
+ )
3070
+ recorded = ledger.by_id().get(task_id)
3071
+ if recorded is not None:
3072
+ # A second partial would state the id twice in the ledger, which `lint` reports as
3073
+ # `id.duplicate` and which is the shape RK127 is about. One partial per task and
3074
+ # then a completion: `amend` is where a qualifier that has changed is corrected.
3075
+ #
3076
+ # Two refusals and not one (RK191): an id whose recorded entry carries a qualifier is
3077
+ # work that came in more halves than the model allows, and the answer there is the id
3078
+ # the next step is filed under — which the shared message, written for an id the
3079
+ # ledger *closed*, has nowhere to put.
3080
+ where = config.relative(config.path("changelog"))
3081
+ if recorded.task.in_halves:
3082
+ raise SecondPartial(
3083
+ task_id,
3084
+ where,
3085
+ recorded.lineno,
3086
+ recorded.task.part,
3087
+ suffix=config.schema.id_suffix,
3088
+ )
3089
+ # Closable exactly where `_already_recorded` would take the line (RK1045), which
3090
+ # since RK1075 is decided by the **entry's** qualifier and not by the roadmap's
3091
+ # marker: a ⏳ line beside an entry naming no half is the state that had no verb at
3092
+ # all, and the door that closes it is the one this refusal now names.
3093
+ raise AlreadyRecorded(
3094
+ task_id,
3095
+ where,
3096
+ recorded.lineno,
3097
+ recorded.task.status,
3098
+ closable=not recorded.task.in_halves,
3099
+ )
3100
+
3101
+ if why is None:
3102
+ # A partial states an outcome too — this much of it works — so the half that
3103
+ # landed is no more entitled to the problem statement than the whole (RK142).
3104
+ raise NoOutcome(task_id, entry.task.why)
3105
+ landed = replace(
3106
+ as_recorded(entry.task, config.schema.shipped_marker, why), part=part
3107
+ )
3108
+ insertion = place(ledger, landed, role="changelog", config=config)
3109
+ # ⏳ where the project declares it, and the line's own marker where it does not: the
3110
+ # marker set is the project's (L6), and a command that invented one would write a line
3111
+ # its own gate refuses. Either way the line stays open, which is the claim.
3112
+ status = PARTIAL if PARTIAL in config.schema.markers else entry.task.status
3113
+ # The **open half, as data** (RK1233). `--part` records what landed and RK1226 put that on
3114
+ # the brief; what stayed an inference is the remainder — a reader handed `landed the parser
3115
+ # half` beside a symptom describing the whole, working out the rest. `--remainder` is the
3116
+ # caller's sentence for what is left, written into the line's own `why` in this same
3117
+ # transaction, so the open line states it and `brief` prints both halves as fields.
3118
+ #
3119
+ # The **roadmap line** and never a second field on the entry, which is the decision RK1226
3120
+ # declined to take and RK1233 settles: a forward-looking clause in the ledger is history
3121
+ # stating work that has not happened, and nothing would update it when the rest ships. The
3122
+ # open line is maintained by definition — `amend` reaches it and the final `ship` removes it.
3123
+ #
3124
+ # The `why` and not the symptom, because the symptom is the falsifiable claim `amend`
3125
+ # refuses to touch (RK7): a task half-delivered is still that symptom's task, and narrowing
3126
+ # the claim itself is `restate`'s act and not a shipment's.
3127
+ #
3128
+ # Validated like any other `why` before it is rendered: `replace_task` re-renders from data
3129
+ # and checks nothing, so a remainder over its limit would land as a line the gate refuses.
3130
+ reopened = replace(entry.task, status=status)
3131
+ if remainder is not None:
3132
+ reopened = replace(reopened, why=remainder)
3133
+ violations = config.schema_for("roadmap").validate(reopened)
3134
+ if violations:
3135
+ # Under the flag that carried it, but only where the rule broken is one this
3136
+ # argument could have broken (RK1262): a line already carrying drift in some other
3137
+ # field is not the remainder's fault, and framing it as one would send the caller
3138
+ # to edit the string they had just written correctly — this task's own defect,
3139
+ # pointed the other way.
3140
+ if any(one.field == RemainderRefused.BECOMES for one in violations):
3141
+ raise RemainderRefused(task_id, tuple(violations))
3142
+ raise SchemaError(tuple(violations))
3143
+ remaining = roadmap.replace_task(entry, reopened)
3144
+ derived = refresh(
3145
+ Backlog.during(config, roadmap=remaining, ledger=insertion.document)
3146
+ )
3147
+ return Partial(
3148
+ task_id=task_id,
3149
+ ledger=insertion,
3150
+ roadmap=derived.document,
3151
+ part=part,
3152
+ remainder=remainder,
3153
+ status=status,
3154
+ refreshed=derived.changed,
3155
+ marker=config.schema.shipped_marker,
3156
+ )
3157
+
3158
+
3159
+ def _depart(
3160
+ config: Config,
3161
+ task_id: str,
3162
+ marker: str,
3163
+ why: str | None,
3164
+ lines: int | None = None,
3165
+ *,
3166
+ replacement_in: str | None = None,
3167
+ replacement: str | None = None,
3168
+ superseded: str | None = None,
3169
+ recorded_in: str | None = None,
3170
+ decides: str | None = None,
3171
+ decides_ref: str | None = None,
3172
+ ) -> Departure:
3173
+ """The one transaction both doors are: validate everything, then write nothing yet."""
3174
+ roadmap = config.document("roadmap")
3175
+ ledger = config.document("changelog")
3176
+
3177
+ entry = roadmap.by_id().get(task_id)
3178
+ if entry is None:
3179
+ raise NotOpen(
3180
+ task_id,
3181
+ config.relative(config.path("roadmap")),
3182
+ Whereabouts.of(config, task_id),
3183
+ )
3184
+ where = config.relative(config.path("changelog"))
3185
+ # Before the ledger is consulted (RK1081): a departure that lands while the store still
3186
+ # carries the id writes a contradiction rather than resolving one, and the file that can
3187
+ # hold a third line for it is the one RK96 added and no pairwise check reached.
3188
+ if config.has("deferred") and config.path("deferred").is_file():
3189
+ paused = config.document("deferred").by_id().get(task_id)
3190
+ if paused is not None:
3191
+ raise AlsoPaused(
3192
+ task_id, config.relative(config.path("deferred")), paused.lineno
3193
+ )
3194
+ duplicate = ledger.by_id().get(task_id)
3195
+ # A duplicate carrying a qualifier is not a second record of one decision — it is the
3196
+ # *first* half of this one (RK121), and a **ship** is the completion. So the entry is
3197
+ # replaced rather than added to, which is what keeps "local half" from outliving the
3198
+ # local half: five of the corpus's thirteen say something that stopped being true.
3199
+ #
3200
+ # Only a ship. `retire` reaches this same transaction with a different marker, and there
3201
+ # the replacement is a deletion of the record that a half landed (RK129) — the one
3202
+ # decision this module hands back rather than making.
3203
+ completing = (
3204
+ duplicate
3205
+ if duplicate is not None
3206
+ and duplicate.task.in_halves
3207
+ and marker == config.schema.shipped_marker
3208
+ else None
3209
+ )
3210
+ if duplicate is not None and completing is None:
3211
+ if duplicate.task.in_halves:
3212
+ raise PartRecorded(
3213
+ task_id, where, duplicate.lineno, duplicate.task.part, duplicate.task.status
3214
+ )
3215
+ raise AlreadyRecorded(
3216
+ task_id,
3217
+ where,
3218
+ duplicate.lineno,
3219
+ duplicate.task.status,
3220
+ # Reached only where the entry carries no qualifier — a duplicate that does is
3221
+ # `PartRecorded` above — so the closure path takes this line (RK1075).
3222
+ closable=not duplicate.task.in_halves,
3223
+ )
3224
+ if why is None:
3225
+ # `retire` always arrives with a derived sentence, so this is the ship path alone.
3226
+ raise NoOutcome(task_id, entry.task.why)
3227
+
3228
+ # Split before `--superseded-design` is appended and before anything else reads the
3229
+ # field (RK1053): the clause belongs at the end of the *sentence*, and appending it to
3230
+ # a `why` that carries the whole span would land it under the last paragraph. Guarded
3231
+ # by `completing`, so the count cannot open the span on a path that places a new line.
3232
+ why, below = _unwrapped(why, lines if completing is not None else None)
3233
+
3234
+ # The author's half, kept so a refusal about the composed sentence can name the parts
3235
+ # (RK1261): from here on `why` may be two arguments and a wrapper, and by the time a gate
3236
+ # reads it there is one field to blame.
3237
+ authored = why
3238
+ if superseded is not None:
3239
+ # Derived up to the address and prose from there on, the split every field this tool
3240
+ # fills in takes (RK8, RK310): the anchor is the pointer the line is losing, which is
3241
+ # the one fact about the deleted design that survives nowhere else, and what it turned
3242
+ # out to be wrong about is the author's. Into the `why` rather than into a slot of its
3243
+ # own, because the ledger's sentence is already where the outcome is read and a second
3244
+ # field is a second thing every projection, every limit and every parse has to learn.
3245
+ if entry.task.ref is None:
3246
+ raise NoDesign(task_id)
3247
+ why = _superseding(why, entry.task.ref, superseded, entry.task.id)
3248
+
3249
+ # After the supersession and never before it (RK1267): the two clauses read as a pair —
3250
+ # what the design was wrong about, then where the part that was right went — and the
3251
+ # order the ledger publishes them in is decided here rather than by which flag was typed
3252
+ # first. Derived whole, there being no prose in an address and a path (L4).
3253
+ overtaken = why
3254
+ if recorded_in is not None:
3255
+ if entry.task.ref is None:
3256
+ raise NoDesign(task_id, "--recorded-in")
3257
+ why = _recording(why, entry.task.ref, recorded_in, entry.task.id)
3258
+
3259
+ # The count is about the entry a completion rewrites, so it is refused wherever there is
3260
+ # no such entry rather than dropped (RK193): every other path places a new one.
3261
+ if completing is None and lines is not None:
3262
+ raise NoCompletion(task_id, where)
3263
+
3264
+ recorded = as_recorded(entry.task, marker, why)
3265
+ if superseded is not None or recorded_in is not None:
3266
+ # Before `place` validates, because from there on the two arguments are one field
3267
+ # (RK1261). The allowance is the ledger's own and not `why_max` — `why_budget` is what
3268
+ # refuses, so a message quoting anything else would name a number the write does not
3269
+ # use, which is the defect RK183 closed for the roadmap's line.
3270
+ grammar = config.schema_for("changelog")
3271
+ allowed = grammar.why_budget(recorded)
3272
+ # Each clause against the sentence it joined, in the order they were composed, so the
3273
+ # refusal names the one that pushed the total over and attributes the room to what can
3274
+ # actually give way (RK1267) — a single check over the pair would charge the overrun
3275
+ # to whichever class was written first.
3276
+ if superseded is not None and width(overtaken) > allowed >= width(authored):
3277
+ raise SupersessionCrowded(
3278
+ task_id,
3279
+ authored=authored,
3280
+ note=superseded,
3281
+ composed=overtaken,
3282
+ limit=allowed,
3283
+ source=grammar.source_of("why_max"),
3284
+ )
3285
+ if recorded_in is not None and width(why) > allowed >= width(overtaken):
3286
+ raise RecordingCrowded(
3287
+ task_id,
3288
+ outcome=overtaken,
3289
+ clause=f"`{recorded_in}` under §{entry.task.ref}",
3290
+ composed=why,
3291
+ limit=allowed,
3292
+ source=grammar.source_of("why_max"),
3293
+ note=superseded,
3294
+ authored=authored,
3295
+ )
3296
+ if completing is not None:
3297
+ # The same write `record amend` makes, so the same count (RK193). A completion drops
3298
+ # the qualifier *and states a different outcome*, and a wrapped entry's `why` is only
3299
+ # as much of the sentence as fits on line one — so rewriting that line alone leaves
3300
+ # the half's old tail under a sentence claiming the whole delivery, which is the
3301
+ # majority shape on the corpus (10 of Shio's 12 partials wrap). The count is a flag on
3302
+ # `ship` and not a detour through `record amend` because the caller asked to finish
3303
+ # work, not to fix a word; what it may never be is absent, `rewrite_entry` deleting
3304
+ # prose no field of this task holds.
3305
+ #
3306
+ # And the same tail, for the same reason (RK1053): the count says the caller read
3307
+ # the span, so `--why` may write it back rather than only collapse it. Otherwise
3308
+ # finishing the majority-shape partial is what deletes the paragraphs under it.
3309
+ counted(
3310
+ task_id, where, completing, lines, verb="completing it", keeps_tail=True
3311
+ )
3312
+ # Checked here, where `place` checks it on every other path (L1): this branch
3313
+ # rewrites an entry instead of placing one and was the one call that reached disk
3314
+ # unvalidated — a `why` carrying a newline landed as a two-line entry whose second
3315
+ # line no field held. Found writing the tail above, which is what made it matter:
3316
+ # the split is authorised by `--lines`, and without this the first line is not.
3317
+ replaced = ledger.rewrite_entry(completing, ledger.schema.check(recorded), below)
3318
+ insertion = Insertion(document=replaced, entry=replaced.by_id()[task_id])
3319
+ else:
3320
+ insertion = place(ledger, recorded, role="changelog", config=config)
3321
+ remaining = remove_entry(roadmap, entry)
3322
+ # One more change to a document already in hand (RK327): the queue names work, this line
3323
+ # is the work, and no state exists where the line has left and the order still names it.
3324
+ # Composed before the roadmap is touched, like everything else here: a decisions file that
3325
+ # refuses this line costs three untouched files rather than a departure half made.
3326
+ decided = _decided(config, entry.task, decides, decides_ref)
3327
+ remaining, dequeued = queueing.without(remaining, config, task_id)
3328
+ # And the task's own criteria list, in the same rewrite and for the same reason (RK1268):
3329
+ # the heading is addressed by an id this write is spending, so leaving it would file a
3330
+ # question about work the ledger already answers. A block's list is untouched — that one
3331
+ # outlives its lines, which is the whole difference between the two addresses.
3332
+ remaining, unmet = criteria.without(remaining, task_id)
3333
+ prose, dropped, kept, taken, cited, emptied = _drop_section(
3334
+ config, entry.task.ref, leaving=task_id
3335
+ )
3336
+ # Resolved against the state this write *creates* — the id is in the ledger and gone
3337
+ # from the roadmap — so a dependent's annotation is derived from what will be on
3338
+ # disk and not from what was (RK8).
3339
+ derived = refresh(
3340
+ Backlog.during(config, roadmap=remaining, ledger=insertion.document)
3341
+ )
3342
+
3343
+ return Departure(
3344
+ task_id=task_id,
3345
+ ledger=insertion,
3346
+ roadmap=derived.document,
3347
+ removed_from=entry.lineno,
3348
+ prose=prose,
3349
+ dropped=dropped,
3350
+ kept=kept,
3351
+ nested=taken,
3352
+ cited=cited,
3353
+ emptied=emptied,
3354
+ refreshed=derived.changed,
3355
+ marker=marker,
3356
+ superseded=superseded,
3357
+ recorded_in=recorded_in,
3358
+ decided=decided,
3359
+ dequeued=dequeued,
3360
+ unmet=unmet,
3361
+ dependents=tuple(
3362
+ e.task.id for e in derived.document.entries if task_id in e.task.dep_ids
3363
+ ),
3364
+ replacement_in=replacement_in,
3365
+ replacement=replacement,
3366
+ root=config.root,
3367
+ # Read off the roadmap as it *was*, and before `save` releases the claim (RK294): the
3368
+ # line still carries 🛠 here, and a claim is only ever read against that marker.
3369
+ scope=claiming.departing(config, task_id, roadmap.entries),
3370
+ )
3371
+
3372
+
3373
+ def _decided(
3374
+ config: Config, task: Task, decides: str | None, decides_ref: str | None = None
3375
+ ) -> Insertion | None:
3376
+ """The one line a departure files into the decisions role, or `None` (RK1269).
3377
+
3378
+ An ADR read as this format is an id, a marker, one falsifiable claim and a reason, so the
3379
+ record is composed the way the ledger's is: the task's own symptom is the claim — a
3380
+ decision is *about* the problem the line stated, and restating it here would be the second
3381
+ sentence RK142 refuses to inherit for the other file — and the author's `--decides` is the
3382
+ reason. Under the role's own grammar, so the marker is the project's ✅ and the deps are
3383
+ refused rather than dropped.
3384
+
3385
+ ``decides_ref`` is where that record's **body** goes, and it exists because RK1361's body
3386
+ was reachable on one kind of project only (RK1363). Under `ref_scheme = "id"` the anchor
3387
+ *is* the id and there is nothing to name; under an outline it is an address the file
3388
+ numbers for itself, so nothing derives it and a `--decides` without it files a record
3389
+ whose body no later call can bind — `section add <anchor> --role decisions` looks its
3390
+ owner up by pointer there, and finds none. So it is **required** under an outline, which
3391
+ is `add --ref`'s own rule one verb over and refused by the same code.
3392
+
3393
+ Validated here and written by nobody yet, which is what makes the fourth edit part of the
3394
+ same all-or-none: a `--decides` over its limit costs a refusal and leaves four files
3395
+ exactly as they were.
3396
+ """
3397
+ if decides is None:
3398
+ if decides_ref is not None:
3399
+ raise DecidesAlone(task.id)
3400
+ return None
3401
+ if not config.has("decisions"):
3402
+ raise NoDecisions(
3403
+ task.id,
3404
+ config.relative(config.source or config.root),
3405
+ config.schema.ref_scheme == "outline",
3406
+ )
3407
+ outlined = config.schema_for("decisions").ref_scheme == "outline"
3408
+ if decides_ref is not None and not outlined:
3409
+ raise DecidesDerived(task.id, decides_ref)
3410
+ if decides_ref is None and outlined:
3411
+ raise DecidesUnaddressed(task.id, config.relative(config.path("decisions")))
3412
+ try:
3413
+ return place(
3414
+ config.document("decisions"),
3415
+ as_recorded(
3416
+ task,
3417
+ config.schema_for("decisions").shipped_marker,
3418
+ decides,
3419
+ ref=decides_ref,
3420
+ ),
3421
+ role="decisions",
3422
+ config=config,
3423
+ )
3424
+ except SchemaError as error:
3425
+ # The claim is inherited and the remedy is not the one every symptom overrun gets
3426
+ # (RK1281): that message sends the author to the rationale section, which *this ship
3427
+ # is deleting*, and `--decides` writes no symptom for them to shorten. Re-raised
3428
+ # rather than widened, because the refusal is right and only its door was wrong.
3429
+ if any(one.field == "symptom" for one in error.violations):
3430
+ raise InheritedClaim(task.id, error, config.relative(config.path("decisions")))
3431
+ raise
3432
+
3433
+
3434
+ def _address(anchor: str, task_id: str | None) -> str:
3435
+ """The anchor, spelled only where it is not the id the entry already opens with (RK1332).
3436
+
3437
+ Both clauses wrote `design §<anchor>` into a line whose first bold run is the id, and on
3438
+ this repository's own ledger that was 48 entries out of 48: under `ref_scheme = "id"` the
3439
+ two strings are one, so 8 of those characters were the tool addressing a line by a name it
3440
+ had just written. They are spent in the sentence RK1330 measured as oversubscribed — the
3441
+ ship that closed it had 23 characters left over, and this is a third of them.
3442
+
3443
+ Conditional and not removed, which is the whole of the care here: under an outline the
3444
+ anchor is `I.2` and addresses a section the line names nowhere else, so dropping it there
3445
+ would cost the reader the one fact the deletion leaves no other copy of. The condition is
3446
+ the two strings being equal, which needs no scheme lookup to decide — the caller passing
3447
+ an id it already holds is enough, and a caller that passes none keeps the old spelling.
3448
+
3449
+ Returns the address with its trailing space, so a clause that omits it does not have to
3450
+ know it is omitting one.
3451
+ """
3452
+ return "" if task_id is not None and anchor == task_id else f"§{anchor} "
3453
+
3454
+
3455
+ def _superseding(
3456
+ why: str, anchor: str, superseded: str, task_id: str | None = None
3457
+ ) -> str:
3458
+ """The outcome with the overtaken design named inside it, as one sentence (RK310).
3459
+
3460
+ The note is the author's verbatim. A full stop *inside* it is still two sentences and is
3461
+ still refused, which is right — the second sentence belongs in the design file the same
3462
+ way it does anywhere else, and there is no case for saying it in the one clause whose
3463
+ subject is a design that no longer exists.
3464
+ """
3465
+ return _parenthesised(why, f"design {_address(anchor, task_id)}superseded: {superseded}")
3466
+
3467
+
3468
+ def _recording(
3469
+ why: str, anchor: str, path: str, task_id: str | None = None
3470
+ ) -> str:
3471
+ """The outcome with the deleted design's new address named inside it (RK1267).
3472
+
3473
+ Derived end to end, which is what separates it from :func:`_superseding`: the anchor is the
3474
+ pointer the line is losing and the path is a file this repository has, so there is no half
3475
+ of this clause the author writes and none of it is prose (L4). Backticked because that is
3476
+ how every other path in a ledger sentence is spelled, and how the gate recognises one.
3477
+ """
3478
+ return _parenthesised(why, f"design {_address(anchor, task_id)}recorded in `{path}`")
3479
+
3480
+
3481
+ def retiring(reason: str, superseded_by: str | None) -> str:
3482
+ """The ledger's sentence for a line that left without shipping (RK1305).
3483
+
3484
+ A derived prefix and the author's own sentence, which is the split every field the tool
3485
+ fills in already makes (RK8): *superseded by RK41* is a fact this command holds, and the
3486
+ reason is prose it will not write (L4).
3487
+
3488
+ Its own function so that :func:`~roadkeep.budgeting.budget` can price the sentence before
3489
+ it exists. That prefix is **structure spent inside a prose field** — mandatory, derived,
3490
+ and counted against the same 200 the reason is refused by — so a caller drafting against
3491
+ the published limit is drafting against a number the write does not use. Measured while
3492
+ retiring a task in an adopting project: the reason was refused three times running, at
3493
+ 250, 212 and 205, and each rewrite cut a clause out of the one field whose job is to carry
3494
+ evidence. One writer, so the price and the write cannot come apart.
3495
+ """
3496
+ if superseded_by is not None:
3497
+ return f"superseded by {superseded_by}: {reason}"
3498
+ return f"abandoned: {reason}"
3499
+
3500
+
3501
+ def supersession_cost(anchor: str, task_id: str | None = None) -> int:
3502
+ """What `--superseded-design` costs the ledger's sentence before its note (RK1261).
3503
+
3504
+ The other half of that task, and the one that arrives in time to be useful: `brief` quotes
3505
+ a shipping allowance without knowing a supersession will be appended to it, and a task
3506
+ about to lose its design is exactly when that allowance is read — so the number was wrong
3507
+ precisely when it was asked for. Unlike a `--part` qualifier, this one is **knowable**: the
3508
+ anchor is the pointer the line already carries, so only the note's own length is the
3509
+ caller's.
3510
+
3511
+ Measured by composing with an empty note rather than by counting brackets, so it cannot
3512
+ drift when the clause is reworded — :func:`_superseding` stays the only writer of it.
3513
+ """
3514
+ stem = "x."
3515
+ return width(_superseding(stem, anchor, "", task_id)) - width(stem)
3516
+
3517
+
3518
+ def recording_cost(anchor: str, task_id: str | None = None) -> int:
3519
+ """What `--recorded-in` costs that same sentence before the path (RK1275).
3520
+
3521
+ :func:`supersession_cost`'s twin, and filed for the reason that one was: two flags landed
3522
+ in the ledger's sentence after the allowance learned to name one of them, so the figure a
3523
+ brief quotes was wrong by a clause whose size this tool knows. The **wrapper** is knowable
3524
+ for the same reason — the anchor is the pointer the line already carries — and the path is
3525
+ the caller's, which is the shape a `--part` qualifier is already described in.
3526
+
3527
+ Measured through :func:`_recording` and never by counting brackets, so a reworded clause
3528
+ moves this number rather than leaving it behind.
3529
+ """
3530
+ stem = "x."
3531
+ return width(_recording(stem, anchor, "", task_id)) - width(stem)
3532
+
3533
+
3534
+ def _parenthesised(why: str, clause: str) -> str:
3535
+ """A `why` carrying a derived clause **inside its terminator** (RK310, RK395).
3536
+
3537
+ That placement is the whole of what this function is for: a `why` is one sentence and has
3538
+ to end like one, so a clause bolted on behind the full stop is two — refused by
3539
+ `why.sentences` and `why.no-terminator` at the door, which is the right refusal about the
3540
+ wrong thing. The author's own punctuation is what closes the composed sentence, so a `why`
3541
+ that never ended like one is still refused, and the terminator is moved rather than
3542
+ chosen: this writes no prose (L4), it parenthesises.
3543
+
3544
+ One writer for both clauses the ledger derives — the design a ship overtook, and the entry
3545
+ a revert replaced — because two call sites composing the same shape is how one of them
3546
+ comes to be refused by the gate the other passes.
3547
+ """
3548
+ stem = why.rstrip()
3549
+ terminator = ""
3550
+ if stem and stem[-1] in ".!?":
3551
+ stem, terminator = stem[:-1].rstrip(), stem[-1]
3552
+ return f"{stem} ({clause}){terminator}"
3553
+
3554
+
3555
+ def _others_pointing(config: Config, anchor: str, leaving: str) -> tuple[str, ...]:
3556
+ """Open lines other than this one whose pointer names the same anchor (RK64)."""
3557
+ return tuple(
3558
+ entry.task.id
3559
+ for entry in config.document("roadmap").entries
3560
+ if entry.task.ref == anchor and entry.task.id != leaving
3561
+ )
3562
+
3563
+
3564
+ def _already_recorded(config: Config, task_id: str) -> Entry | None:
3565
+ """The ledger entry this roadmap line was left behind by, or None if it is not one.
3566
+
3567
+ A ledger entry and a roadmap line for one id is *several* different situations, and only
3568
+ some of them are a leftover. Two answers, read off two different sides:
3569
+
3570
+ * **The roadmap's** (RK62). A line carrying a marker the roadmap may not carry — ✅ or 🗑
3571
+ — was already treated as gone, which is the shape adoption produces: a project that
3572
+ moved a task to its changelog by hand and left a pointer behind.
3573
+ * **The ledger's** (RK130). RK118 ordered a departure's writes so the ledger goes first,
3574
+ which makes stopping between them *loud and lossless* — `id.two-files` names it — and
3575
+ left no way out: `ship` refused the id, this function's roadmap-side condition did not
3576
+ match a line still marked 📋, and `record drop` wants a second entry. So an entry for a
3577
+ line that is still open is a leftover **unless the entry names a half**, which is the
3578
+ distinction RK121 made representable.
3579
+
3580
+ **The marker alone is not that distinction** (RK1075). This read a ⏳ line as a live
3581
+ partial whatever the ledger said, and the state where the two disagree — a partial
3582
+ marker beside an entry carrying *no* qualifier — is then a line no verb closes: `ship`
3583
+ and `retire` refuse through this function, `defer` refuses because a pause is between
3584
+ open and terminal, and the gate is silent by design (RK121). Shio filed three capture
3585
+ reports on it and closed it with the editor. RK1046 had already made the same reading
3586
+ one door over — a ⏳ line beside an unqualified entry is the two files contradicting
3587
+ each other, the line saying a half landed and the entry saying the whole did — and the
3588
+ entry is the record of what shipped. So the qualifier is what refuses here, and the
3589
+ marker is what it used to be mistaken for.
3590
+
3591
+ RK1046's exit stays and stops being the only one. It is the right door where the entry
3592
+ *should* carry a qualifier and does not; this is the door where the ledger is already
3593
+ right and the line is what is stale, and asking an author to write `--part "…"` to open
3594
+ it was asking them to claim a half nothing delivered.
3595
+
3596
+ And a refusal, because widening it opened one more reading. An interrupted transaction
3597
+ wrote its entry **from this line**, so the two state the same symptom; two that do not are
3598
+ two tasks sharing an id (RK97), and closing one of them would delete work no crash
3599
+ touched. Compared only where the ledger carries a symptom at all: a file with no such
3600
+ slot holds no fact to tell them apart, and the marker and the qualifier are then the whole
3601
+ of what the files say.
3602
+ """
3603
+ if not config.has("changelog") or not config.path("changelog").is_file():
3604
+ return None
3605
+ open_line = config.document("roadmap").by_id().get(task_id)
3606
+ if open_line is None:
3607
+ return None
3608
+ ledger = config.document("changelog")
3609
+ recorded = ledger.by_id().get(task_id)
3610
+ if recorded is None:
3611
+ return None
3612
+
3613
+ schema = config.schema
3614
+ if open_line.task.status in (schema.shipped_marker, schema.retired_marker):
3615
+ return recorded
3616
+ # The qualifier and not the marker (RK1075): an entry naming a half is a live partial and
3617
+ # closing it would drop the half that has not landed, where a ⏳ line beside an entry that
3618
+ # names none is the two files disagreeing about one delivery — and the ledger is the file
3619
+ # that records what shipped. Through `Task.in_halves`, which the gate reads too (RK1080).
3620
+ if recorded.task.in_halves:
3621
+ return None
3622
+ if (
3623
+ ledger.schema.symptom_field
3624
+ and open_line.task.symptom != recorded.task.symptom
3625
+ ):
3626
+ raise Divergent(
3627
+ task_id,
3628
+ config.relative(config.path("roadmap")),
3629
+ open_line.lineno,
3630
+ config.relative(config.path("changelog")),
3631
+ recorded.lineno,
3632
+ )
3633
+ return recorded
3634
+
3635
+
3636
+ def _close(
3637
+ config: Config,
3638
+ task_id: str,
3639
+ recorded: Entry,
3640
+ decides: str | None = None,
3641
+ decides_ref: str | None = None,
3642
+ ) -> Closure:
3643
+ """Everything a departure does except the entry, which is already on disk (RK62).
3644
+
3645
+ `decides` reaches here and the other two clauses do not (RK1269), and the split is what
3646
+ each is about: those land in the ledger's sentence, which this path deliberately leaves
3647
+ alone, and this one is a line in a file of its own — filed at the moment the section is
3648
+ deleted, which is an edit this door does make.
3649
+ """
3650
+ roadmap = config.document("roadmap")
3651
+ entry = roadmap.by_id()[task_id]
3652
+ decided = _decided(config, entry.task, decides, decides_ref)
3653
+ remaining = remove_entry(roadmap, entry)
3654
+ remaining, dequeued = queueing.without(remaining, config, task_id)
3655
+ # The rest of the transaction that stopped halfway (RK62, RK1268): the entry is on disk,
3656
+ # so what is left is every edit the roadmap side owes — the list among them.
3657
+ remaining, unmet = criteria.without(remaining, task_id)
3658
+ prose, dropped, kept, taken, cited, emptied = _drop_section(
3659
+ config, entry.task.ref, leaving=task_id
3660
+ )
3661
+ derived = refresh(
3662
+ Backlog.during(config, roadmap=remaining, ledger=config.document("changelog"))
3663
+ )
3664
+ return Closure(
3665
+ task_id=task_id,
3666
+ remaining=derived.document,
3667
+ removed_from=entry.lineno,
3668
+ recorded=recorded,
3669
+ prose=prose,
3670
+ dropped=dropped,
3671
+ kept=kept,
3672
+ nested=taken,
3673
+ cited=cited,
3674
+ emptied=emptied,
3675
+ refreshed=derived.changed,
3676
+ dependents=tuple(
3677
+ e.task.id for e in derived.document.entries if task_id in e.task.dep_ids
3678
+ ),
3679
+ dequeued=dequeued,
3680
+ unmet=unmet,
3681
+ decided=decided,
3682
+ scope=claiming.departing(config, task_id, roadmap.entries),
3683
+ root=config.root,
3684
+ )
3685
+
3686
+
3687
+ def as_recorded(task: Task, marker: str, why: str | None, ref: str | None = None) -> Task:
3688
+ """The same task as the ledger states it: one marker, no deps, no pointer.
3689
+
3690
+ The pointer is dropped because the section it names is deleted in the same command,
3691
+ and the deps because a dependency is a planning fact that a departed line has none
3692
+ left to state — both of which the ledger schema (`as_ledger`) already refuses.
3693
+
3694
+ **Public since RK1199**, and that is the whole of that defect. `brief` priced the ledger
3695
+ line by handing :func:`~roadkeep.budgeting.budget_of` the *roadmap's* task under the
3696
+ ledger's schema — and `Schema.render` appends `→ §<anchor>` whenever the task carries one,
3697
+ the pointer being split off before the grammar's own slot loop runs. So the structure it
3698
+ measured was ten characters wider than the line this function hands `ship`: `→ §RK1199` is
3699
+ exactly those ten, and the figure that existed to be composed against had ten it could not
3700
+ spend. `ref_required` is not the gate to close it with — that flag says a pointer is not
3701
+ *demanded*, and a schema that refused to render one a line carries would stop the file
3702
+ round-tripping (L3). The gate is this function, asked by both.
3703
+
3704
+ ``ref`` is the one caller that carries one *forward* (RK1363): a decision filed on an
3705
+ outline project addresses its body by an anchor nothing derives, so the record has to
3706
+ name it and the default stays `None` for the ledger, whose section is being deleted. The
3707
+ argument is the caller's declaration and not a fall-through from the task — inheriting
3708
+ the roadmap line's pointer here would file a decision addressing the design just deleted.
3709
+ """
3710
+ return replace(
3711
+ task,
3712
+ status=marker,
3713
+ deps=(),
3714
+ # And the requirements, for the deps' own reason one group over (RK1297): a
3715
+ # requirement says what has to be present for work to be finishable, and a line that
3716
+ # left has nothing to finish — the DualSense was on the desk or the work did not
3717
+ # ship. Cleared here rather than refused by the ledger's schema, because the slot is
3718
+ # written off the field and a ledger entry carrying one would render it.
3719
+ requires=(),
3720
+ ref=ref,
3721
+ why=why if why is not None else task.why,
3722
+ # And at column zero (RK49): the nesting said which roadmap line this one belonged
3723
+ # under, and that line is not in the ledger — an indented entry would be nested
3724
+ # beneath whatever entry happened to precede it.
3725
+ indent="",
3726
+ )
3727
+
3728
+
3729
+ def _drop_section(
3730
+ config: Config, anchor: str | None, *, leaving: str = ""
3731
+ ) -> tuple[
3732
+ Document | None,
3733
+ Section | None,
3734
+ str | None,
3735
+ tuple[str, ...],
3736
+ tuple[str, ...],
3737
+ str | None,
3738
+ ]:
3739
+ """Delete the rationale section the departing line pointed at, if it is only that line's.
3740
+
3741
+ Absence is reported, never refused: a task can ship without a section, and a command
3742
+ that fails over it would be an obstacle at the one moment the author is finishing.
3743
+
3744
+ So is a section with **more than one owner** (RK64). Under `ref_scheme = "id"` the anchor
3745
+ is the id and nothing else can name it; under an outline, four of Shio's lines point at one
3746
+ epic design, and deleting it when the first of them ships left three live pointers resolving
3747
+ to nothing. The section stays and the reason is reported in the same field.
3748
+
3749
+ A section **nesting** one of those is the same fact one level down, and it is a refusal
3750
+ rather than a report (RK78): keeping the section is a legitimate outcome of shipping,
3751
+ while a subtree that cannot be deleted whole is a transaction the author has to resolve —
3752
+ so :class:`~roadkeep.sections.SectionOccupied` propagates, and by the ordering this module
3753
+ already guarantees, no file has been touched when it does. What the drop *did* take is
3754
+ returned with it, because a deletion that reports one section and removes five is how the
3755
+ same defect stayed invisible for 160 lines.
3756
+
3757
+ **Which file, is asked and not assumed** (RK196). RK172 taught the gate that a pointer
3758
+ addresses every governed prose role and RK186 taught the reader; this is the third and the
3759
+ one that *writes*. Reading `improvements` alone meant a project declaring `strategy` was
3760
+ told "this project declares no improvements file" while the section the departing line
3761
+ pointed at stayed — a prose file becoming a second changelog, which is what RK6 exists to
3762
+ stop. So the anchor is resolved across the declared roles, exactly as :func:`show` resolves
3763
+ it, and the drop is made against the file that declares it.
3764
+
3765
+ Two roles declaring one anchor is **reported and not resolved**, for the reason absence is:
3766
+ which of the two a line meant is what `ref.ambiguous` asks the author, and a ship that
3767
+ deleted one of them would be answering that question by picking. The section stays, the
3768
+ ship is right, and the gate still says so.
3769
+
3770
+ And a departure deletes only the section it **owns** (RK236), which is `lint`'s own reading
3771
+ of ownership and not a second one: under `ref_scheme = "id"` the anchor is the id, so a
3772
+ line's own design is always owned and always deleted; under an outline the anchor is an
3773
+ address in a file the project already keeps, and a section whose heading names no task is
3774
+ prose belonging to none — the gate says so by never reporting it orphaned. Turing's Block O
3775
+ lines pointed at `STRATEGY.md` §X.3 and §X.4, subsections of a standing GEO memo whose
3776
+ siblings survived only because no line happened to name them; retiring the last owner of
3777
+ each deleted 39 lines of positioning, and restoring it took the hand edit the guard denies.
3778
+ RK64 could not see it (four of five lines were live until the fifth) and neither could
3779
+ RK196 (§X.1 survived by the accident of also being an improvements heading).
3780
+
3781
+ Kept and never refused, the direction the costs choose: prose left behind is one
3782
+ `section drop` away and a `lint` that reports nothing, while prose deleted is somebody's
3783
+ memo and a `git show`. No heuristic about what the prose *says* — only who it names, which
3784
+ is the claim RK61 already reads.
3785
+ """
3786
+ if anchor is None:
3787
+ return None, None, "the line carried no pointer", (), (), None
3788
+ # The design's two and never every prose role (RK1361), which is the one place that
3789
+ # distinction is load-bearing rather than cosmetic: this function *deletes*, and a
3790
+ # decisions file joining the search would let the ship that files a decision delete the
3791
+ # body of an earlier one that happened to share the anchor. A decision's body is never
3792
+ # deleted — the one departure is `supersede`, and it keeps both entries and both bodies.
3793
+ roles = tuple(role for role in DESIGN_ROLES if config.has(role))
3794
+ if not roles:
3795
+ return (
3796
+ None,
3797
+ None,
3798
+ f"this project declares no {' or '.join(DESIGN_ROLES)} file",
3799
+ (),
3800
+ (),
3801
+ None,
3802
+ )
3803
+ others = _others_pointing(config, anchor, leaving)
3804
+ if others:
3805
+ return (
3806
+ None,
3807
+ None,
3808
+ f"§{anchor} is also pointed at by {', '.join(others)}",
3809
+ (),
3810
+ (),
3811
+ None,
3812
+ )
3813
+
3814
+ named = " or ".join(config.relative(config.path(role)) for role in roles)
3815
+ # One resolver, called and not repeated (RK229): three verbs ask which file declares an
3816
+ # anchor, and the copy that answered it here is the copy `defer` did not have.
3817
+ holders = declaring(config, anchor)
3818
+ if len(holders) > 1:
3819
+ both = " and ".join(config.relative(config.path(role)) for role in holders)
3820
+ return (
3821
+ None,
3822
+ None,
3823
+ f"§{anchor} is declared by {both}: one anchor names one section, and a ship "
3824
+ f"that deleted one of two would be choosing which the line meant",
3825
+ (),
3826
+ (),
3827
+ None,
3828
+ )
3829
+ if not holders:
3830
+ return None, None, f"no §{anchor} section in {named}", (), (), None
3831
+
3832
+ role = holders[0]
3833
+ # The grammar of a section lives in one place (RK9), so shipping calls it rather than
3834
+ # keeping a second opinion about where a section ends.
3835
+ prose = config.document(role)
3836
+ held = find(prose, anchor)
3837
+ if held is not None:
3838
+ claim = owners(held, config.schema.id_pattern())
3839
+ if leaving and leaving not in claim:
3840
+ return None, None, _unowned(anchor, claim), (), (), None
3841
+ deleted = drop_section(
3842
+ prose,
3843
+ anchor,
3844
+ claimed=pointers(config, leaving=leaving),
3845
+ where=config.relative(config.path(role)),
3846
+ )
3847
+ # `cited` and `nested` are both `drop`'s own answers (RK209, RK1170): the deletion knows
3848
+ # what it breaks and what it took, and a second reading of the same file here would be two
3849
+ # more things to keep true.
3850
+ return (
3851
+ deleted.document,
3852
+ deleted.section,
3853
+ None,
3854
+ deleted.nested,
3855
+ deleted.cited,
3856
+ _emptied(config, deleted.document, anchor),
3857
+ )
3858
+
3859
+
3860
+ def _emptied(config: Config, document: Document, anchor: str) -> str | None:
3861
+ """The parent this drop left with no subsections under it (RK400).
3862
+
3863
+ A `ship` deletes the task's own `§<id>` and names any section whose prose cited it. Under
3864
+ an outline it leaves one thing standing that nothing named: the **parent** the deleted
3865
+ children hung under. That paragraph was written as an introduction to them — it states
3866
+ the problem they solve, in the present tense — so shipping the last of `§X.1`–`§X.4`
3867
+ leaves `§X` telling a reader the work is open, and it is the first thing anyone reads
3868
+ about that family.
3869
+
3870
+ Named and never rewritten. What the introduction should say instead is a `section amend`
3871
+ and a judgement (L4); noticing is not, and the tool is the only party that can.
3872
+
3873
+ Silent under `ref_scheme = "id"`, where an anchor has no parent — and silent for a parent
3874
+ that still holds children, which is the ordinary case and not worth a line.
3875
+ """
3876
+ parent, dot, _ = anchor.rpartition(".")
3877
+ if not dot or config.schema.ref_scheme != "outline":
3878
+ return None
3879
+ if find(document, parent) is None or nested(document, parent):
3880
+ return None
3881
+ return parent
3882
+
3883
+
3884
+ def _unowned(anchor: str, claim: tuple[str, ...]) -> str:
3885
+ """Why a section this line pointed at stayed (RK236), in the field a departure reports.
3886
+
3887
+ Names who it belongs to where the heading says, because that is the author's next question
3888
+ and the answer is what makes the outcome checkable — and says "no task" where it names
3889
+ none, which is the standing-memo case and the one this was filed from.
3890
+ """
3891
+ if claim:
3892
+ return f"§{anchor} belongs to {', '.join(claim)}, so it is not this line's to delete"
3893
+ return (
3894
+ f"§{anchor} names no task in its heading, so it is prose belonging to none — the "
3895
+ f"reading `lint` makes when it declines to report it orphaned"
3896
+ )
3897
+
3898
+
3899
+ @dataclass(frozen=True, slots=True)
3900
+ class Delivered:
3901
+ """Every claim one block has already made good on, as one result (RK385, RK1170).
3902
+
3903
+ The read that decides whether an `add` is a duplicate, so its two registers had better say
3904
+ the same thing: they were a printer and a payload builder in the same handler, agreeing by
3905
+ hand over a header, a state row, a bound and a per-entry mark.
3906
+
3907
+ **Symptoms and not outcomes.** A shipped line states two things, and a duplicate collides
3908
+ with the problem it claimed rather than with the fix it delivered — an outcome is written in
3909
+ the vocabulary of the fix and never matches. So the rows carry the symptom.
3910
+
3911
+ Unbounded unless a question narrows it. `--near` is not a truncation of this listing (RK442):
3912
+ it is the same read asked a narrower question, so what bounds it is the caller's sentence and
3913
+ not a number this verb chose — which is why the header says how many of how many, and why the
3914
+ order is published with no score under it (RK441).
3915
+ """
3916
+
3917
+ #: The ledger, as the project spells it, and the label this was asked about.
3918
+ where: str
3919
+ standing: Standing
3920
+ entries: tuple[Entry, ...]
3921
+ #: What the block holds, beside what this call chose to show (RK442): a consumer handed five
3922
+ #: rows and no total reads a five-entry block.
3923
+ recorded: int
3924
+ #: The sentence `--near` narrowed by, or empty where the whole block is the answer.
3925
+ near: str
3926
+ #: Which of these the ledger later undid, by the entry that undid it (RK1042).
3927
+ reversed_by: Mapping[str, str]
3928
+
3929
+ def __str__(self) -> str:
3930
+ rows: list[str] = []
3931
+ if not self.entries:
3932
+ # Said, never an empty stdout: "this block has delivered nothing" and "this command
3933
+ # found nothing to read" look the same to a caller, and only one of them is an answer.
3934
+ rows.append(f"{self.where} {self.standing.named} has delivered nothing yet")
3935
+ elif self.near:
3936
+ # The count of what is *shown* against the count of what is there (RK442). This verb
3937
+ # was deliberately unbounded, because the entry that got elided is exactly the one
3938
+ # nobody read — so a bounded answer has to say it is bounded, in the header, or it
3939
+ # inherits the guarantee it just gave up.
3940
+ rows.append(
3941
+ f"{self.where} {self.standing.named}, {len(self.entries)} nearest of "
3942
+ f"{self.recorded} delivered"
3943
+ )
3944
+ else:
3945
+ rows.append(f"{self.where} {self.standing.named}, {self.recorded} delivered")
3946
+ rows.append(f" block {self.standing.sentence}")
3947
+ if self.near:
3948
+ # Said once, above the rows: the ordering is the whole answer and there is no
3949
+ # threshold under it, which is the sentence that keeps a reader from taking #1 as a
3950
+ # verdict (RK441). The rest of the block is one command away and named here.
3951
+ rows.append(
3952
+ f" near ranked by word overlap, nearest first — an order and not a "
3953
+ f"verdict; `{invocation()} delivered {self.standing.label}` is all "
3954
+ f"{self.recorded}"
3955
+ )
3956
+ for entry in self.entries:
3957
+ # Marked and never dropped (RK1042). This verb's own rule about retired lines: a
3958
+ # claim that did not hold is still a claim somebody made and argued about, so the
3959
+ # marker says which and nothing is conflated. A superseded entry carries no marker
3960
+ # of its own — the ledger spells it in the sentence — so the mark is written here.
3961
+ undone = self.reversed_by.get(entry.task.id)
3962
+ said = f" (undone by {undone})" if undone else ""
3963
+ rows.append(f" {entry.task.status} {entry.task.id:<8} {entry.task.symptom}{said}")
3964
+ return "\n".join(rows)
3965
+
3966
+ def payload(self) -> dict[str, object]:
3967
+ return {
3968
+ "file": self.where,
3969
+ "block": self.standing.label,
3970
+ # Beside the list and not instead of it (RK429): an empty `delivered` is the answer
3971
+ # to what was asked, and this is what the label it was asked about turned out to be.
3972
+ "standing": self.standing.payload(),
3973
+ "recorded": self.recorded,
3974
+ "near": self.near or None,
3975
+ "delivered": [
3976
+ {
3977
+ "id": entry.task.id,
3978
+ "marker": entry.task.status,
3979
+ "symptom": entry.task.symptom,
3980
+ "line": entry.lineno,
3981
+ # Null and not omitted (RK1042): a consumer reading a missing key cannot
3982
+ # tell "this held" from "this server is older", and the whole use of this
3983
+ # payload is deciding a duplicate.
3984
+ "undone_by": self.reversed_by.get(entry.task.id),
3985
+ # The order and never a score (RK441): the absolute figure separates
3986
+ # nothing, so a payload carrying it is one turn from the threshold that
3987
+ # measurement rules out. Absent without `--near`, where the order is the
3988
+ # ledger's and not an answer.
3989
+ **({"rank": at} if self.near else {}),
3990
+ }
3991
+ for at, entry in enumerate(self.entries, start=1)
3992
+ ],
3993
+ }