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/queueing.py ADDED
@@ -0,0 +1,752 @@
1
+ """The queue that outranks the id order, in the file the plan lives in (RK325).
2
+
3
+ `priority` is the one tier of `pick` a project **declares** rather than derives (RK11), and
4
+ until now it lived in `roadkeep.toml` — where :func:`~roadkeep.guarding.governed` is explicit
5
+ that nothing governs it: the config is "the per-project declaration, which a human edits by
6
+ hand on purpose". That is right about the prefix, the paths and the limits. None of them
7
+ stops being true by itself.
8
+
9
+ The queue is the exception, because **every token in it names work, and work leaves**. An id
10
+ that shipped is an entry the tool wrote the ledger for and then left standing in a file it
11
+ does not open; a block that emptied is a tier that fires on nothing. Every other list this
12
+ format holds — task lines, ledger entries, non-goals — has an insert and a drop, and the one
13
+ that outranks the id order had neither, so its only repair was the editor the guard denies.
14
+
15
+ So it moves to where the plan is, and RK70 is the **pattern** rather than a precedent: a list
16
+ that is not task lines, one renderer, refused at insertion, addressed by a verb. `picking`'s
17
+ standing objection to a `## Priority` section is about *interpreting prose* — Shio's queue is
18
+ a paragraph explaining why reachability comes first — and it does not apply to a section this
19
+ tool renders.
20
+
21
+ Four decisions, each narrower than it could be:
22
+
23
+ * **No opt-in table.** Non-goals needed one (RK66): both corpora wrote theirs as prose years
24
+ before the schema existed, so a default would report fifteen findings on adoption. Nobody
25
+ has a rendered queue section, so there is nothing to grandfather — **the heading declares
26
+ the list**, exactly as a block heading declares a block (RK37), and a project with no such
27
+ heading has no section and keeps whatever `roadkeep.toml` says.
28
+ * **No reason field.** An entry is a token: an id, or `Block X`. Why something jumps the
29
+ queue is the commit that moved it, exactly as `restate` takes none — and a reason in the
30
+ file is a sentence that goes stale one tier below the one nothing was keeping true.
31
+ * **No derived annotation.** `- RK14` and not `- RK14 📋 (a symptom)`: the id is the address
32
+ and the roadmap is one file away, so an annotation here is a second thing every write has
33
+ to keep in step for a reader who is already looking at the line above it.
34
+ * **The section wins where both exist.** `priority` in the config stays *read*, because Shio
35
+ and Turing may have declared one and a move that silently emptied their queue would be this
36
+ tool changing what `pick` answers without being asked. Which one applied is reported
37
+ (:attr:`Queue.declared_in`), because a queue that quietly came from the other file is the
38
+ failure this module is about.
39
+
40
+ What the move buys is more than a door, and the three tasks it unblocks are the argument:
41
+ `ship` already rewrites the roadmap inside its atomic transaction, so an entry a departure
42
+ kills cannot survive it (RK327); the gate reads a file it already reads (RK326); `--fix`
43
+ repairs one it already repairs (RK328). A separate store makes each of those a fourth writer.
44
+ """
45
+
46
+ from __future__ import annotations
47
+
48
+ import re
49
+ from collections.abc import Sequence
50
+ from dataclasses import dataclass
51
+ from pathlib import Path
52
+
53
+ from roadkeep.config import Config
54
+ from roadkeep.kernel.document import Document, blank
55
+ from roadkeep.kernel.schema import Dep, DepKind
56
+
57
+ __all__ = [
58
+ "HEADING",
59
+ "DuplicateEntry",
60
+ "Dropped",
61
+ "Entry",
62
+ "NoQueue",
63
+ "NoSuchEntry",
64
+ "NotAnEntry",
65
+ "Queue",
66
+ "Written",
67
+ "add",
68
+ "declared",
69
+ "drop",
70
+ "entries",
71
+ "read",
72
+ "render",
73
+ "tokens",
74
+ "typed",
75
+ "without",
76
+ ]
77
+
78
+ #: Any heading whose text starts like this holds the queue. A prefix match for
79
+ #: :data:`~roadkeep.scoping.HEADING`'s reason: "## Priority", "## Priority queue" and
80
+ #: "## Priority (what jumps the id order)" are one list, and which words a project put
81
+ #: after the first is not a fact this tool needs.
82
+ HEADING = re.compile(r"^priority\b", re.IGNORECASE)
83
+
84
+ #: What a migration *writes*, which the pattern above deliberately cannot say (RK427): the
85
+ #: match is a prefix so a project may title its own section, and one that has none yet gets
86
+ #: the plainest spelling rather than a guess at which words it would have chosen.
87
+ SECTION = "## Priority"
88
+
89
+ #: `- <token>`, at column zero and nothing else on the line. Deliberately the whole bullet:
90
+ #: an entry is an address, so a trailing note would be prose the renderer cannot reproduce
91
+ #: and the round trip is what refuses it (L3).
92
+ _BULLET = re.compile(r"^- (?P<token>\S+(?: \S+)?)\s*$")
93
+ #: A bullet that is one, without the shape this governs — reported, never guessed at.
94
+ _ANY_BULLET = re.compile(r"^[-*+] (?P<rest>.*)$")
95
+
96
+
97
+ class NoQueue(KeyError):
98
+ """No heading holds a queue to write to. A heading is the only thing that declares one.
99
+
100
+ ``in_config`` is the case that had no door at all (RK427). RK325 moved the queue out of
101
+ `roadkeep.toml` and into the roadmap, and `lint` still reads the old declaration — which
102
+ is right, a project that has not migrated still has a real order. But it reported
103
+ `priority.shipped` naming **roadkeep.toml**, and the verb whose whole job is that repair
104
+ refused with "no priority heading in docs/ROADMAP.md", having never looked at the file
105
+ the finding named. A finding in one file and its door on another is a defect with no
106
+ exit but the hand edit this tool exists to replace, so the refusal names the migration.
107
+ """
108
+
109
+ def __init__(self, where: str, tokens: tuple[str, ...] = ()) -> None:
110
+ self.tokens = tokens
111
+ if tokens:
112
+ listed = ", ".join(tokens)
113
+ super().__init__(
114
+ f"this project's queue is still `priority` in roadkeep.toml ({listed}), "
115
+ f"which no verb writes: `priority migrate` moves it into {where} as the "
116
+ f"section RK325 introduced, and then every queue verb reaches it"
117
+ )
118
+ return
119
+ super().__init__(
120
+ f"no priority heading in {where}, so there is no order to take a token out of: "
121
+ f"`priority add <token>` opens the section and writes the first entry (RK1014)"
122
+ )
123
+
124
+
125
+ class NotAnEntry(ValueError):
126
+ """A token that is neither an id of this project nor `Block X` (RK325).
127
+
128
+ The same refusal `[priority]` in the config already makes, from the same typing code, and
129
+ for the reason that one gives: an entry `pick` cannot resolve is a queue the author
130
+ believes is in force and is not.
131
+ """
132
+
133
+ def __init__(self, token: str, where: str) -> None:
134
+ self.token = token
135
+ super().__init__(
136
+ f"{token!r} is neither an id of this project nor 'Block X', so nothing in "
137
+ f"{where} can ever be first because of it: a queue is an order over the work "
138
+ f"this backlog holds"
139
+ )
140
+
141
+
142
+ class DuplicateEntry(ValueError):
143
+ """A token the queue already carries. One address, one place in the order."""
144
+
145
+ def __init__(self, token: str, where: str, lineno: int) -> None:
146
+ self.token = token
147
+ self.lineno = lineno
148
+ super().__init__(
149
+ f"{where}:{lineno} already queues {token}: an entry is an address, so a second "
150
+ f"one is two answers about where the same work sits in the order"
151
+ )
152
+
153
+
154
+ class NoSuchEntry(KeyError):
155
+ """A token the queue does not carry, at the door that removes one."""
156
+
157
+ def __init__(self, token: str, where: str, held: tuple[str, ...]) -> None:
158
+ self.token = token
159
+ known = ", ".join(held) or "nothing"
160
+ super().__init__(f"{where} does not queue {token}: the queue holds {known}")
161
+
162
+
163
+ @dataclass(frozen=True, slots=True)
164
+ class Entry:
165
+ """One bullet under the priority heading, as data and as the file spells it."""
166
+
167
+ token: str
168
+ #: 1-based. An entry is one line — the renderer writes no wrap, having nothing to wrap.
169
+ lineno: int
170
+ raw: str = ""
171
+
172
+
173
+ @dataclass(frozen=True, slots=True)
174
+ class Queue:
175
+ """The order `pick` applies, and which file declared it (RK325).
176
+
177
+ Both, because the answer is only checkable with the source: a queue that quietly came
178
+ from `roadkeep.toml` after the author wrote a section is the failure this module exists
179
+ to make visible, and `pick` prints the tier either way.
180
+ """
181
+
182
+ tokens: tuple[str, ...] = ()
183
+ #: `"roadmap"` where a heading declares the section, `"config"` where `priority` did,
184
+ #: and `""` where neither — which is not the same as an empty section (RK326's
185
+ #: distinction, made here because the reader is the one place that can see both).
186
+ declared_in: str = ""
187
+ #: The bullets under the heading whose shape the format does not hold, with their line.
188
+ #: Counted apart and never silently dropped, for :func:`~roadkeep.scoping.rejects`'
189
+ #: reason: being unreadable is not being absent, and a count that omitted these would
190
+ #: read as a complete one.
191
+ rejects: tuple[tuple[int, str], ...] = ()
192
+
193
+ def __bool__(self) -> bool:
194
+ return bool(self.tokens)
195
+
196
+ def stated(self, config: Config) -> str:
197
+ """The order, and which file declared it (RK325).
198
+
199
+ Beside :meth:`payload` since RK1170. Both, always: a project that wrote a section and
200
+ is still being ordered by its config is the state this move exists to make visible, and
201
+ it is invisible from the tokens alone.
202
+ """
203
+ where = config.relative(config.path("roadmap"))
204
+ source = config.relative(config.source or config.root)
205
+ if not self.declared_in:
206
+ return (
207
+ f"{where}: no priority queue — add a `## Priority` heading, or declare "
208
+ f"`priority` in {source}; the id order stands either way"
209
+ )
210
+ named = where if self.declared_in == "roadmap" else source
211
+ empty = " empty: the tier is declared and off" if not self.tokens else ""
212
+ rows = [f"{named} {len(self.tokens)} entr(ies){empty}"]
213
+ rows += [
214
+ f" {place:<8} {token}" for place, token in enumerate(self.tokens, 1)
215
+ ]
216
+ rows += [f" unread {where}:{lineno} {raw}" for lineno, raw in self.rejects]
217
+ return chr(10).join(rows)
218
+
219
+ def payload(self, config: Config) -> dict[str, object]:
220
+ where = config.relative(config.path("roadmap"))
221
+ return {
222
+ "declared_in": self.declared_in or None,
223
+ "file": where
224
+ if self.declared_in == "roadmap"
225
+ else config.relative(config.source or config.root),
226
+ "priority": list(self.tokens),
227
+ # Bullets under the heading the format could not read — counted apart for
228
+ # `non-goal`'s reason: unreadable is not absent.
229
+ "unread": [{"line": lineno, "raw": raw} for lineno, raw in self.rejects],
230
+ }
231
+
232
+
233
+ @dataclass(frozen=True, slots=True)
234
+ class Written:
235
+ """An entry inserted, and the document it went into. Save writes the roadmap."""
236
+
237
+ document: Document
238
+ entry: Entry
239
+ #: Where in the order it landed, 1-based — the field a caller cannot read off the line
240
+ #: number, and the whole point of a list whose order is its content.
241
+ position: int = 1
242
+ #: How long the queue is now, so "3rd of 5" is one answer rather than two calls.
243
+ length: int = 1
244
+ #: Whether this write also opened the section (RK1014). Reported, because a caller who
245
+ #: asked to queue one token has just had a heading written into a governed file, and a
246
+ #: write nobody sees is the thing the event line exists to stop (RK38).
247
+ opened: bool = False
248
+
249
+ @property
250
+ def lineno(self) -> int:
251
+ return self.entry.lineno
252
+
253
+ def save(self) -> tuple[Path, ...]:
254
+ return self.document.save()
255
+
256
+ def stated(self, config: Config, wrote: Sequence[Path]) -> str:
257
+ """Where in the order it landed, and whether the section is new (RK325, RK1014).
258
+
259
+ Beside :meth:`payload` since RK1170. **No event line** (RK38): the payload a hook reads
260
+ is an id and its block's open state, and an entry states neither — the token names work
261
+ whose line is somewhere else.
262
+ """
263
+ from roadkeep.rendering import _staging_rows # noqa: PLC0415 - RK260
264
+
265
+ where = config.relative(config.path("roadmap"))
266
+ rows = [f"{where}:{self.lineno} queued {self.entry.token}"]
267
+ if self.opened:
268
+ # Said, because the caller asked for an entry and got a heading too (RK1014) — the
269
+ # same reason every write here prints what it changed rather than only that it did.
270
+ rows.append(
271
+ " opened the priority section, above the blocks — the queue is declared now"
272
+ )
273
+ rows.append(f" order {self.position} of {self.length}")
274
+ rows += _staging_rows(config.relative(one) for one in wrote)
275
+ return "\n".join(rows)
276
+
277
+ def payload(self, config: Config, wrote: Sequence[Path]) -> dict[str, object]:
278
+ from roadkeep.rendering import _wrote_json # noqa: PLC0415 - RK260
279
+
280
+ return {
281
+ "token": self.entry.token,
282
+ "file": config.relative(config.path("roadmap")),
283
+ "line": self.lineno,
284
+ # The two a caller cannot read off a line number, and the whole content of a list
285
+ # whose order is what it says (RK325).
286
+ "position": self.position,
287
+ "length": self.length,
288
+ "rendered": self.entry.raw,
289
+ # Whether this call also opened the section (RK1014): a caller who asked to queue
290
+ # a token has had a heading written into a governed file.
291
+ "opened": self.opened,
292
+ **_wrote_json(config, wrote),
293
+ }
294
+
295
+
296
+ @dataclass(frozen=True, slots=True)
297
+ class Dropped:
298
+ """An entry removed. Save writes the roadmap and nothing else."""
299
+
300
+ document: Document
301
+ entry: Entry
302
+ length: int = 0
303
+
304
+ @property
305
+ def lineno(self) -> int:
306
+ return self.entry.lineno
307
+
308
+ def save(self) -> tuple[Path, ...]:
309
+ return self.document.save()
310
+
311
+ def stated(self, config: Config, wrote: Sequence[Path]) -> str:
312
+ """What left the order, and how much of it is left."""
313
+ from roadkeep.rendering import _staging_rows # noqa: PLC0415 - RK260
314
+
315
+ where = config.relative(config.path("roadmap"))
316
+ rows = [
317
+ f"{where}:{self.lineno} dropped {self.entry.token}",
318
+ f" order {self.length} left",
319
+ ]
320
+ rows += _staging_rows(config.relative(one) for one in wrote)
321
+ return "\n".join(rows)
322
+
323
+ def payload(self, config: Config, wrote: Sequence[Path]) -> dict[str, object]:
324
+ from roadkeep.rendering import _wrote_json # noqa: PLC0415 - RK260
325
+
326
+ return {
327
+ "token": self.entry.token,
328
+ "file": config.relative(config.path("roadmap")),
329
+ "removed": self.lineno,
330
+ "length": self.length,
331
+ "rendered": self.entry.raw,
332
+ **_wrote_json(config, wrote),
333
+ }
334
+
335
+
336
+ def typed(config: Config, token: str) -> bool:
337
+ """Is this a token a queue may carry — an id of this project, or `Block X`?
338
+
339
+ Typed by the code that types a **dep**, so `Block X` cannot come to mean two things
340
+ (RK11's rule, and the one `_check_priority` in `config` already applies). One function,
341
+ called by both the writer and the reader, because a token the write path accepted and the
342
+ gate then failed on is the split L1 exists to prevent.
343
+ """
344
+ schema = config.schema
345
+ kind = schema.classify_dep(Dep(token))
346
+ if kind is DepKind.TASK:
347
+ return bool(schema.id_pattern().match(token))
348
+ return schema.block_of_dep(Dep(token)) is not None
349
+
350
+
351
+ def render(token: str) -> str:
352
+ """The bullet as this format writes it. The only writer of it.
353
+
354
+ One line and one token, so there is nothing to fill and nothing to wrap — the shape a
355
+ `prose` width would be about does not exist here.
356
+ """
357
+ return f"- {token.strip()}"
358
+
359
+
360
+ def read(document: Document, config: Config) -> Queue:
361
+ """Every entry under the priority heading, in file order, with what could not be read.
362
+
363
+ File order **is** the order: an entry's place in the list is its whole content, so
364
+ nothing here sorts and nothing derives a rank. A bullet the shape does not hold is
365
+ carried as a reject rather than dropped, which is what lets the gate report it against a
366
+ line number and what keeps this count honest.
367
+ """
368
+ start = _heading_index(document)
369
+ if start is None:
370
+ return Queue()
371
+ entries: list[Entry] = []
372
+ rejects: list[tuple[int, str]] = []
373
+ for offset, raw in enumerate(document.lines[start + 1 :], start=start + 2):
374
+ body = raw.rstrip("\r\n")
375
+ if body.startswith("#"):
376
+ break # the next heading ends the section, whatever its level
377
+ if not _ANY_BULLET.match(body):
378
+ continue
379
+ match = _BULLET.match(body)
380
+ if match is None or not typed(config, match.group("token")):
381
+ rejects.append((offset, body))
382
+ continue
383
+ entries.append(Entry(token=match.group("token"), lineno=offset, raw=body))
384
+ return Queue(
385
+ tokens=tuple(one.token for one in entries),
386
+ declared_in="roadmap",
387
+ rejects=tuple(rejects),
388
+ )
389
+
390
+
391
+ def declared(config: Config) -> Queue:
392
+ """The queue `pick` applies: the roadmap's section, or `roadkeep.toml`'s `priority`.
393
+
394
+ **The section wins where both exist**, and the loser is not merged in: two orders
395
+ concatenated is a third order nobody wrote. Which file answered is on the result, because
396
+ a project that wrote a section and is still being ordered by its config has a fact to
397
+ learn and no other way to learn it.
398
+
399
+ A heading with no bullets under it is a queue that is **empty**, not one that is absent —
400
+ so it wins over the config too. Declaring the list and then removing every entry is how a
401
+ project turns the tier off, and falling back there would make the last `priority drop`
402
+ silently restore an order the author had just finished dismantling.
403
+ """
404
+ if config.has("roadmap") and config.path("roadmap").is_file():
405
+ found = read(config.document("roadmap"), config)
406
+ if found.declared_in:
407
+ return found
408
+ if config.priority:
409
+ return Queue(tokens=config.priority, declared_in="config")
410
+ return Queue()
411
+
412
+
413
+ def tokens(config: Config) -> tuple[str, ...]:
414
+ """Just the order, for the caller that has no use for where it came from."""
415
+ return declared(config).tokens
416
+
417
+
418
+ def add(
419
+ config: Config, token: str, *, after: str | None = None, first: bool = False
420
+ ) -> Written:
421
+ """Insert one token into the queue. Validated first, and nothing written on a refusal.
422
+
423
+ Appended by default, because a queue grows at the end and the alternative — everything
424
+ new is most urgent — is the order nobody meant. `first` and `after` are the two places
425
+ that are not the end, and they are the reason this is an insert rather than an append:
426
+ moving work up the order is the whole act the config file made unavailable.
427
+ """
428
+ where = config.relative(config.path("roadmap"))
429
+ document = config.document("roadmap")
430
+ heading = _heading_index(document)
431
+ opened = False
432
+ if heading is None:
433
+ # A queue still in the config is `migrate`'s (RK427): moving it is one act, and
434
+ # opening a second section beside it would be two orders in two files.
435
+ if _in_config(config):
436
+ raise NoQueue(where, _in_config(config))
437
+ # And a project with neither gets the heading written here (RK1014), the way
438
+ # `block add` opens a block heading — the two doors used to name each other and
439
+ # neither wrote it, leaving the hand edit this tool exists to replace.
440
+ document, heading = open_queue(document)
441
+ opened = True
442
+ entry = token.strip()
443
+ if not typed(config, entry):
444
+ raise NotAnEntry(entry, where)
445
+
446
+ held = read(document, config)
447
+ twin = entries(document, config)
448
+ existing = next((one for one in twin if one.token == entry), None)
449
+ if existing is not None:
450
+ raise DuplicateEntry(entry, where, existing.lineno)
451
+ if after is not None:
452
+ target = next((one for one in twin if one.token == after.strip()), None)
453
+ if target is None:
454
+ raise NoSuchEntry(after.strip(), where, held.tokens)
455
+
456
+ at, separate, position = _placement(document, heading, twin, after=after, first=first)
457
+ updated = document
458
+ if separate:
459
+ # The line above is the heading or its prose, and a bullet glued to either reads as
460
+ # part of it — so the blank that separates them is part of this insertion.
461
+ updated = updated.insert_line(at, "")
462
+ at += 1
463
+ updated = updated.insert_line(at, render(entry))
464
+ return Written(
465
+ document=updated,
466
+ entry=Entry(token=entry, lineno=at + 1, raw=render(entry)),
467
+ position=position,
468
+ length=len(twin) + 1,
469
+ opened=opened,
470
+ )
471
+
472
+
473
+ def drop(config: Config, token: str) -> Dropped:
474
+ """Remove the entry a token addresses. The other half of the door.
475
+
476
+ No correction verb between them, and that is the shape of the claim: an entry carries a
477
+ token and nothing else, so there is no field an amend could reach — a token that changed
478
+ is a different entry, and where it sits in the order is a drop and an insert.
479
+ """
480
+ where = config.relative(config.path("roadmap"))
481
+ document = config.document("roadmap")
482
+ if _heading_index(document) is None:
483
+ raise NoQueue(where, _in_config(config))
484
+
485
+ held = entries(document, config)
486
+ going = next((one for one in held if one.token == token.strip()), None)
487
+ if going is None:
488
+ raise NoSuchEntry(
489
+ token.strip(), where, tuple(one.token for one in held)
490
+ )
491
+ return Dropped(
492
+ document=_remove_line(document, going.lineno),
493
+ entry=going,
494
+ length=len(held) - 1,
495
+ )
496
+
497
+
498
+ def without(document: Document, config: Config, token: str) -> tuple[Document, str | None]:
499
+ """The same roadmap with one entry gone, and the token if there was one (RK327).
500
+
501
+ A :class:`~roadkeep.kernel.document.Document` in, a document out, because every caller is a
502
+ **departure**: `ship`, `retire` and `defer` all rewrite the roadmap inside one atomic
503
+ transaction, and dropping the entry is one more change to a file already in hand. Going
504
+ through :func:`drop` would be a second read of the same file and a second write of it —
505
+ and then a state where the line has left and the queue still names it, which is precisely
506
+ what this closes.
507
+
508
+ Silent where nothing is queued, and that is not a fallback: most departures are of work
509
+ nobody put in the order, and a refusal there would make the queue an obstacle at the one
510
+ moment the author is finishing.
511
+
512
+ What separates this from `dependents` and `cited`, which the same transaction reports and
513
+ never touches: those are other lines and other prose, and editing them would be composing
514
+ somebody's sentence. **A queue entry is derived dead by the departure itself** — the id it
515
+ names has left the roadmap, so the tier could only ever fire on nothing.
516
+ """
517
+ going = next((one for one in entries(document, config) if one.token == token), None)
518
+ if going is None:
519
+ return document, None
520
+ return _remove_line(document, going.lineno), going.token
521
+
522
+
523
+ def entries(document: Document, config: Config) -> tuple[Entry, ...]:
524
+ """The readable bullets alone, with their lines — what the writers address against.
525
+
526
+ Public because the gate reports against a *line* (RK326): :func:`read` answers what the
527
+ order is, and a finding needs where the entry that is dead was written.
528
+ """
529
+ start = _heading_index(document)
530
+ if start is None:
531
+ return ()
532
+ out: list[Entry] = []
533
+ for offset, raw in enumerate(document.lines[start + 1 :], start=start + 2):
534
+ body = raw.rstrip("\r\n")
535
+ if body.startswith("#"):
536
+ break
537
+ match = _BULLET.match(body)
538
+ if match is not None and typed(config, match.group("token")):
539
+ out.append(Entry(token=match.group("token"), lineno=offset, raw=body))
540
+ return tuple(out)
541
+
542
+
543
+ def _remove_line(document: Document, lineno: int) -> Document:
544
+ """Take the bullet out, and the blank line the removal doubled.
545
+
546
+ A queue of one sits between blanks, so removing it leaves a paragraph break the file never
547
+ had — both spellings round-trip, which is exactly why nothing downstream would catch it
548
+ (the care :func:`~roadkeep.scoping._remove_span` takes, one list over).
549
+ """
550
+ start = lineno - 1
551
+ updated = document.remove_line(start)
552
+ lines = updated.lines
553
+ if start > 0 and start < len(lines) and blank(lines[start - 1]) and blank(lines[start]):
554
+ return updated.remove_line(start)
555
+ if start >= len(lines) and start > 0 and blank(lines[start - 1]):
556
+ return updated.remove_line(start - 1)
557
+ return updated
558
+
559
+
560
+ def _in_config(config: Config) -> tuple[str, ...]:
561
+ """The tokens `roadkeep.toml` still declares, where the roadmap declares no section."""
562
+ return tuple(config.priority)
563
+
564
+
565
+ @dataclass(frozen=True, slots=True)
566
+ class Migrated:
567
+ """A config-declared queue written into the roadmap as the section (RK427)."""
568
+
569
+ document: Document
570
+ tokens: tuple[str, ...]
571
+ #: The heading's line, 1-based, so the answer names where the section landed.
572
+ lineno: int
573
+
574
+ def save(self) -> tuple[Path, ...]:
575
+ return self.document.save()
576
+
577
+ def configured(self, config: Config) -> str:
578
+ """The file the queue was declared in, as this project spells it."""
579
+ return config.relative(config.source) if config.source else "roadkeep.toml"
580
+
581
+ def stated(self, config: Config, wrote: Sequence[Path]) -> str:
582
+ """The section, and what `lint` will now say about the line left behind (RK427).
583
+
584
+ Beside :meth:`payload` since RK1170. The last row is the half a caller would otherwise
585
+ learn from a red run: the section wins from here, so the `priority` line left in
586
+ `roadkeep.toml` becomes `priority.config` — a finding whose remedy is a one-line edit
587
+ the guard does not deny, that file being one this tool does not govern and never writes.
588
+ """
589
+ from roadkeep.rendering import _staging_rows # noqa: PLC0415 - RK260
590
+
591
+ where = config.relative(config.path("roadmap"))
592
+ rows = [
593
+ f"{where}:{self.lineno} priority section written",
594
+ *(
595
+ f" {position:<8} {token}"
596
+ for position, token in enumerate(self.tokens, start=1)
597
+ ),
598
+ f" left `priority` is still in {self.configured(config)} and is now read by "
599
+ f"nothing — take the line out; `lint` reports it as `priority.config` until you do",
600
+ ]
601
+ rows += _staging_rows(config.relative(one) for one in wrote)
602
+ return "\n".join(rows)
603
+
604
+ def payload(self, config: Config, wrote: Sequence[Path]) -> dict[str, object]:
605
+ from roadkeep.rendering import _wrote_json # noqa: PLC0415 - RK260
606
+
607
+ return {
608
+ "file": config.relative(config.path("roadmap")),
609
+ "line": self.lineno,
610
+ "tokens": list(self.tokens),
611
+ "configured": self.configured(config),
612
+ **_wrote_json(config, wrote),
613
+ }
614
+
615
+
616
+ def migrate(config: Config) -> Migrated:
617
+ """Write `roadkeep.toml`'s `priority` into the roadmap as the section RK325 introduced.
618
+
619
+ The one door between the two declarations, and it exists because the gate reads the old
620
+ one and every write verb reads the new one — so without it a project that never migrated
621
+ was reported a defect no command could reach.
622
+
623
+ **The config line is not deleted**, and that is deliberate rather than a shortcut. Nothing
624
+ in this package writes `roadkeep.toml`: it carries an author's comments and a TOML rewrite
625
+ that preserves them is a parser this tool would have to grow and a dependency it refuses
626
+ to take. What happens instead is already designed — the section wins over the config
627
+ (:func:`declared`), so the order is live the moment this returns, and `lint` reports
628
+ `priority.config` about the line left behind, whose own remedy is the one-line edit the
629
+ guard does not deny because `roadkeep.toml` is not a governed file.
630
+
631
+ Refused where the roadmap already declares a section: two orders concatenated is a third
632
+ order nobody wrote, which is the same reason :func:`declared` does not merge them.
633
+ """
634
+ where = config.relative(config.path("roadmap"))
635
+ document = config.document("roadmap")
636
+ if _heading_index(document) is not None:
637
+ raise AlreadyDeclared(where)
638
+ tokens = _in_config(config)
639
+ if not tokens:
640
+ raise NothingToMigrate(where)
641
+ for token in tokens:
642
+ if not typed(config, token):
643
+ raise NotAnEntry(token, _configured(config))
644
+
645
+ updated, at = open_queue(document)
646
+ for offset, token in enumerate([render(one) for one in tokens] + [""]):
647
+ updated = updated.insert_line(at + 2 + offset, token)
648
+ return Migrated(document=updated, tokens=tokens, lineno=at + 1)
649
+
650
+
651
+ class AlreadyDeclared(KeyError):
652
+ """The roadmap already holds the section, so there is nothing for a migration to open."""
653
+
654
+ def __init__(self, where: str) -> None:
655
+ super().__init__(
656
+ f"{where} already declares a priority section, so the queue is already the one "
657
+ f"every verb writes — take `priority` out of roadkeep.toml, which `lint` reports "
658
+ f"as `priority.config` until you do"
659
+ )
660
+
661
+
662
+ class NothingToMigrate(KeyError):
663
+ """Neither file declares a queue: there is no order to move."""
664
+
665
+ def __init__(self, where: str) -> None:
666
+ super().__init__(
667
+ f"roadkeep.toml declares no `priority`, so nothing is waiting to move into "
668
+ f"{where}: `priority add <token>` writes the first entry of a new one"
669
+ )
670
+
671
+
672
+ def _configured(config: Config) -> str:
673
+ return config.relative(config.source) if config.source else "roadkeep.toml"
674
+
675
+
676
+ def _first_block_index(document: Document) -> int:
677
+ """Where the section goes: above the first block heading, which is where it is read.
678
+
679
+ The same placement rule `priority add` already assumes and the gate already checks — the
680
+ order is about the work below it, and a queue underneath the blocks is one a reader meets
681
+ after the list it was meant to reorder.
682
+ """
683
+ for at, line in enumerate(document.lines):
684
+ if line.lstrip().startswith("## "):
685
+ return at
686
+ return len(document.lines)
687
+
688
+
689
+ def open_queue(document: Document) -> tuple[Document, int]:
690
+ """Write the heading that declares the queue, above the blocks (RK1014).
691
+
692
+ The one writer of :data:`SECTION`, called by `add` when a project has no queue at all and
693
+ by `migrate` when it has one in the config. Before the first block, which is where the
694
+ refusal used to tell a caller to put it by hand — the order is what a reader takes for the
695
+ shape of the plan, and a queue underneath the blocks reads as a seventh block.
696
+
697
+ A heading and the blank under it, and nothing else: what goes in the section is the
698
+ caller's, and a section opened with an entry nobody asked for would be this tool writing
699
+ an order (L4).
700
+ """
701
+ at = _first_block_index(document)
702
+ return document.insert_line(at, SECTION).insert_line(at + 1, ""), at
703
+
704
+
705
+ def opened(document: Document) -> bool:
706
+ """Whether this roadmap declares a queue at all — the heading, not what is under it.
707
+
708
+ A different question from :func:`entries`, and the one an estimate asks (RK1090): a
709
+ project with a `## Priority` section and nothing in it right now has the door and is
710
+ using it, where one with no section picks by the lowest ready id. Counting entries
711
+ answers the first as if it were the second, which is this repository on any day its
712
+ queue is empty.
713
+ """
714
+ return _heading_index(document) is not None
715
+
716
+
717
+ def _heading_index(document: Document) -> int | None:
718
+ """The 0-based index of the priority heading line, or None when there is no section."""
719
+ heading = next((h for h in document.headings if HEADING.match(h.text)), None)
720
+ return None if heading is None else heading.lineno - 1
721
+
722
+
723
+ def _placement(
724
+ document: Document,
725
+ heading: int,
726
+ existing: tuple[Entry, ...],
727
+ *,
728
+ after: str | None,
729
+ first: bool,
730
+ ) -> tuple[int, bool, int]:
731
+ """Where the bullet goes, whether a blank precedes it, and its 1-based place in the order.
732
+
733
+ After the section's *prose* when the list is empty, never straight under the heading, for
734
+ :func:`~roadkeep.scoping._placement`'s reason: a section that opens with a sentence about
735
+ what the queue is for would have that sentence read as a footnote to the first entry.
736
+ """
737
+ if not existing:
738
+ end = len(document.lines)
739
+ for offset, raw in enumerate(document.lines[heading + 1 :], start=heading + 1):
740
+ if raw.lstrip().startswith("#"):
741
+ end = offset
742
+ break
743
+ while end > heading + 1 and blank(document.lines[end - 1]):
744
+ end -= 1
745
+ return end, True, 1
746
+ if first:
747
+ return existing[0].lineno - 1, False, 1
748
+ if after is not None:
749
+ target = next(one for one in existing if one.token == after.strip())
750
+ place = existing.index(target)
751
+ return target.lineno, False, place + 2
752
+ return existing[-1].lineno, False, len(existing) + 1