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/exporting.py ADDED
@@ -0,0 +1,808 @@
1
+ """A projection of the backlog, never a second author (RK39).
2
+
3
+ A README section and a site page repeat what the backlog says and drift the moment it
4
+ changes, because nothing re-derives them. This repository's own README claimed **8 of 36
5
+ tasks shipped** and listed `add`, `ship`, `pick` and `show` as "not yet built" while all
6
+ four were in the ledger — written by the same session that shipped them.
7
+
8
+ So the restatement is derived. Two properties make it a projection rather than a generator:
9
+
10
+ * **Idempotent.** The same `docs/` yields the same bytes, so a refresh with nothing to say
11
+ produces no diff — which is what makes the diff readable when there *is* something to
12
+ say. That is also why nothing here is stamped with a time: a generated-at field would
13
+ turn every refresh into a change, and dates are a non-goal besides.
14
+ * **It writes no new sentence.** Every character of content it emits already passed `add`
15
+ — task lines are rendered verbatim, block titles come from the headings — so L4 holds and
16
+ `lint` still proves the artefact. Column labels and totals are format, not prose.
17
+
18
+ That is also the boundary: a summary of a block, a release note, any text not already in a
19
+ validated line, is out of scope here and belongs to the author who calls `add`.
20
+
21
+ The README block is replaced **between two markers the author put there**. A missing marker
22
+ is refused with the two lines to paste, on the same reasoning as an undeclared block (RK37):
23
+ a write that invents its own container puts text where nothing looks for it.
24
+
25
+ A projection nothing writes is a chore with an exit code, so :func:`refreshes` is what every
26
+ governed write carries: the block is derived from the documents the transaction already
27
+ holds, inside the same `write_all` (RK188, RK187). `export` stays the command, for the tree
28
+ somebody hand-edited and for the first block a project ever renders.
29
+
30
+ Idempotence is what the gate over the block is made of (RK104), so it is a property to hold
31
+ rather than a claim to make, and two things here hold it. :func:`project` takes the governed
32
+ files as **documents** where it is asked to, which is how the same block can be derived at a
33
+ revision instead of from this working tree; and the next-ready line is picked *claim-blind*,
34
+ because a claim is dated in a temp file outside the repository and expires on a clock — so a
35
+ projection that read one would change bytes with no commit to explain it, and a gate over
36
+ those bytes would be red for a reason nobody could look up.
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import functools
42
+ import json
43
+ from collections.abc import Mapping, Sequence
44
+ from dataclasses import dataclass
45
+ from html import escape
46
+ from pathlib import Path
47
+
48
+ from roadkeep.backlog import Backlog
49
+ from roadkeep.config import Config
50
+ from roadkeep.counting import Census
51
+ from roadkeep.kernel.document import Document, Entry, StaleFile, Write
52
+ from roadkeep.picking import pick
53
+
54
+ #: The container, as a comment so it renders as nothing in either file it lives in — the
55
+ #: same two lines in Markdown and in HTML, which is why one `splice` serves both.
56
+ BEGIN = "<!-- roadkeep:begin -->"
57
+ END = "<!-- roadkeep:end -->"
58
+
59
+ @dataclass(frozen=True, slots=True)
60
+ class Kind:
61
+ """Where one flag writes when it names no path, and the shape the block takes there.
62
+
63
+ A record since RK1110, where the pair stopped being two literals. The first two targets
64
+ are files this tool does not own and names outright; the contents is *inside* a governed
65
+ file, whose path is the project's own `[files]` declaration (L6) — so a target is either a
66
+ name or a role, and which of the two decides where it lands.
67
+ """
68
+
69
+ shape: str
70
+ #: The literal path, relative to the root, for a target outside the governed set.
71
+ name: str = ""
72
+ #: The governed role whose own file carries the block, for one inside it.
73
+ role: str = ""
74
+
75
+
76
+ #: One statement of the pair, because the gate over the block (RK104) has to read exactly
77
+ #: what the write produces: a second spelling of `README.md` in the linter would be a gate
78
+ #: over a path nothing writes, which passes for the same reason the drift got in.
79
+ DEFAULTS: Mapping[str, Kind] = {
80
+ "readme": Kind(shape="markdown", name="README.md"),
81
+ "site": Kind(shape="html", name="docs/index.html"),
82
+ # Improvements and not every prose role (RK1110): it is the file both live corpora keep a
83
+ # contents in, and one flag per role is a decision to make when a project wants the second.
84
+ "contents": Kind(shape="contents", role="improvements"),
85
+ }
86
+
87
+ #: The governed files a projection is derived from — the three whose unit is a task line.
88
+ #: The prose files hold no count and no next-ready line, so only the contents reads one.
89
+ COUNTED_ROLES = ("roadmap", "changelog", "deferred")
90
+
91
+ #: The prose role the contents is derived from, which is a *reading* of that file's headings
92
+ #: and never a count of its lines (RK1110).
93
+ LISTED_ROLE = "improvements"
94
+
95
+
96
+ def _note(command: str) -> str:
97
+ return f"<!-- generated by `roadkeep export {command}`; edit the governed files instead -->"
98
+
99
+
100
+ class NoMarkers(ValueError):
101
+ """The file has nowhere to put the projection, and a write may not invent one."""
102
+
103
+ def __init__(self, where: str, missing: str) -> None:
104
+ super().__init__(
105
+ f"{where} has no {missing} marker: paste these two lines where the "
106
+ f"projection belongs, then re-run —\n{BEGIN}\n{END}"
107
+ )
108
+
109
+
110
+ class NoTarget(ValueError):
111
+ """The file a named projection would be written into is not there at all (RK1039).
112
+
113
+ One state earlier than :class:`NoMarkers`, and until this it was the one state this verb
114
+ answered with an errno: `export --readme` on a project that has no README yet printed
115
+ `[Errno 2] No such file or directory` and the **absolute** path, where every other message
116
+ here prints the path relative to the root and names the command that closes it.
117
+
118
+ The sentence was already written for the file next door — a README that exists and carries
119
+ no markers is told to paste two lines — so this is that answer one step earlier, the file
120
+ being what the caller creates rather than a flag they pass. A bare `--readme` reaches it
121
+ too: the flag's `const` is the default path, so naming nothing still names a target, which
122
+ is why the "not there is not a target" rule below could never cover this door.
123
+ """
124
+
125
+ def __init__(self, where: str) -> None:
126
+ super().__init__(
127
+ f"{where} is not there: a projection is written between two markers, so create "
128
+ f"the file with these two lines where it belongs, then re-run —\n{BEGIN}\n{END}"
129
+ )
130
+
131
+
132
+ @dataclass(frozen=True, slots=True)
133
+ class Row:
134
+ """One block, counted in both files."""
135
+
136
+ label: str
137
+ title: str
138
+ open: int
139
+ shipped: int
140
+ retired: int
141
+
142
+
143
+ @dataclass(frozen=True, slots=True)
144
+ class Listed:
145
+ """One heading a contents lists, as the file already writes it (RK1110).
146
+
147
+ Every field is read off the heading: the text a reader clicks, the fragment it lands on,
148
+ and the depth that decides its indent. Nothing composed — which is what makes the contents
149
+ a projection and not a second author (L4).
150
+ """
151
+
152
+ #: The heading's own text, less the `#`s: `§RK9 A design`, `VIII. The gateway`.
153
+ heading: str
154
+ #: The fragment the link points at, by the rule :func:`slug` states.
155
+ slug: str
156
+ level: int
157
+
158
+
159
+ #: The character categories a heading fragment drops, beyond the two it keeps (RK1110).
160
+ #: `Sm` is `+` and `↔`; `Sk` is the backtick a heading quotes a type name in. Both had to be
161
+ #: measured rather than assumed: with punctuation alone the rule reproduced 44 of 49 link
162
+ #: targets across Shio, Turing and claude-tray, and with these two it reproduces 47 — the
163
+ #: other two being links those files have already gone stale against, which is this task.
164
+ _DROPPED_CATEGORIES = frozenset({"Sm", "Sk"})
165
+
166
+
167
+ def slug(heading: str) -> str:
168
+ """The fragment a Markdown renderer gives this heading, by the rule the corpora show.
169
+
170
+ Lowercased, punctuation and the two symbol classes above removed, spaces to hyphens —
171
+ with `-` and `_` kept, both being characters an author writes *into* a fragment. An emoji
172
+ survives (`✅` is `So`), which is not a detail: Shio's contents links a heading carrying
173
+ one, and a rule that stripped it would break fifteen live anchors at once.
174
+
175
+ Held against the three corpora by `tests/test_exporting.py` rather than argued here: the
176
+ renderer's algorithm is somebody else's, so the only honest check is whether this
177
+ reproduces the fragments those files already link to.
178
+ """
179
+ import unicodedata # noqa: PLC0415 - one call, on a path that runs per heading
180
+
181
+ kept = "".join(
182
+ character
183
+ for character in heading.lower()
184
+ if character in "-_"
185
+ or not (
186
+ unicodedata.category(character).startswith("P")
187
+ or unicodedata.category(character) in _DROPPED_CATEGORIES
188
+ )
189
+ )
190
+ return kept.replace(" ", "-")
191
+
192
+
193
+ @dataclass(frozen=True, slots=True)
194
+ class Projection:
195
+ """The backlog as another file would restate it, in two shapes."""
196
+
197
+ rows: tuple[Row, ...]
198
+ open_entries: tuple[Entry, ...]
199
+ ledger_entries: tuple[Entry, ...]
200
+ next_ready: Entry | None
201
+ files: dict[str, str]
202
+ prefix: str
203
+ #: True when any line was retired: a column of zeroes is noise, not information.
204
+ show_retired: bool
205
+ #: The prose file's own headings, for the contents block (RK1110). Empty where the project
206
+ #: declares no such file or the caller gave a tree that did not carry it — and then the
207
+ #: target is not written, exactly as an absent README is not one.
208
+ listed: tuple[Listed, ...] = ()
209
+
210
+ @property
211
+ def totals(self) -> Row:
212
+ return Row(
213
+ label="",
214
+ title="Total",
215
+ open=sum(row.open for row in self.rows),
216
+ shipped=sum(row.shipped for row in self.rows),
217
+ retired=sum(row.retired for row in self.rows),
218
+ )
219
+
220
+ # -- the two shapes ----------------------------------------------------
221
+
222
+ @property
223
+ def progress(self) -> int:
224
+ """Shipped as a whole percentage of everything counted, floored.
225
+
226
+ Floored and not rounded, for the same reason the README carries no estimate: a bar
227
+ that reads 100% with one line still open is the only wrong number a meter can show.
228
+ """
229
+ totals = self.totals
230
+ counted = totals.open + totals.shipped + totals.retired
231
+ return 0 if not counted else min(100, totals.shipped * 100 // counted)
232
+
233
+ def body(self, shape: str, *, omit: str = "") -> str:
234
+ """The block one target takes, addressed by the shape :data:`DEFAULTS` names it by.
235
+
236
+ One door, because the write and the gate over it (RK104) have to render the same
237
+ bytes: a caller that chose between the two methods itself would be a second place
238
+ the pairing lives, and the linter is exactly the caller that must not get it wrong.
239
+
240
+ ``omit`` is the heading the block is written *under* (RK1110), which only the contents
241
+ has any use for: a list that links the section it is inside is a row nobody follows.
242
+ Passed in rather than derived here, because where the markers sit is a fact about the
243
+ file and both callers already hold that file's text — :func:`enclosing` reads it.
244
+ """
245
+ if shape == "html":
246
+ return self.html()
247
+ if shape == "markdown":
248
+ return self.markdown()
249
+ if shape == "contents":
250
+ return self.contents(omit=omit)
251
+ raise KeyError(f"no such projection shape: {shape!r}")
252
+
253
+ def contents(self, *, omit: str = "") -> str:
254
+ """The prose file's families, as the list that file already keeps by hand.
255
+
256
+ **One level, and it is the corpus that says so.** Listing every heading was the first
257
+ answer and it was wrong twice over: 55 rows against the 17 Shio keeps, and a reader
258
+ handed every `###` design in a 900-line file has an index the size of the thing it
259
+ indexes. Both live corpora list the families alone — Shio's 15 links and claude-tray's
260
+ 18 are all top-level — and a subsection is reached from the family it belongs to.
261
+
262
+ So the depth is the shallowest heading *below the title*, whatever that file writes it
263
+ as: `##` in both corpora, and derived rather than assumed because the level a project
264
+ organises by is the project's (L6, without a key to declare it).
265
+
266
+ Three headings are left out. The `#` names the file, and a contents linking the document
267
+ it is inside is a row nobody follows; ``omit`` is the heading this block is written
268
+ under, the same reason one step in; and anything deeper than the families belongs to
269
+ one of them. What is *not* excluded is an unanchored heading (RK1107): the question a
270
+ reader asks of a contents is what is in here, and a `## Table of contents` is as much
271
+ in here as a numbered family.
272
+ """
273
+ below = [one for one in self.listed if one.level > 1]
274
+ lines = [_note("--contents"), ""]
275
+ if not below:
276
+ return "\n".join(lines)
277
+ family = min(one.level for one in below)
278
+ for one in below:
279
+ if one.level == family and one.heading != omit:
280
+ lines.append(f"- [{one.heading}](#{one.slug})")
281
+ return "\n".join(lines)
282
+
283
+ def markdown(self) -> str:
284
+ """The README block's body. Deterministic, and every line derived."""
285
+ head = ["Block", "Open", "Shipped"] + (["Retired"] if self.show_retired else [])
286
+ lines = [_note("--readme"), "", _row(head), _row(["---"] * len(head))]
287
+ for row in self.rows:
288
+ lines.append(_row(self._cells(row)))
289
+ totals = self.totals
290
+ lines.append(_row([f"**{totals.title}**", *self._cells(totals)[1:]]))
291
+ if self.next_ready is not None:
292
+ lines += ["", "**Next ready:**", "", self.next_ready.raw]
293
+ return "\n".join(lines)
294
+
295
+ def _cells(self, row: Row) -> list[str]:
296
+ cells = [row.title, str(row.open), str(row.shipped)]
297
+ return cells + ([str(row.retired)] if self.show_retired else [])
298
+
299
+ def html(self) -> str:
300
+ """The landing page's status block — the half of RK39 the JSON payload did not reach.
301
+
302
+ A page is not a README with tags: it carries a meter and a per-block strip rather
303
+ than a table, so this is a second *shape* and not a second *source*. Everything is
304
+ still `escape`d and still verbatim, because a symptom holding an ``&`` would
305
+ otherwise be a projection that emits broken markup from a line that validated.
306
+ """
307
+ totals = self.totals
308
+ counted = totals.open + totals.shipped + totals.retired
309
+ out = [
310
+ _note("--site"),
311
+ '<div class="status-bar reveal">',
312
+ f' <span class="lbl"><b>{totals.shipped}</b> of <b>{counted}</b> '
313
+ f"tasks shipped</span>",
314
+ f' <div class="meter"><i style="width:{self.progress}%"></i></div>',
315
+ "</div>",
316
+ '<div class="blocks reveal">',
317
+ ]
318
+ for row in self.rows:
319
+ state = "done" if not row.open else "open"
320
+ # The count leads and the title follows: a block heading here is a whole
321
+ # sentence with a parenthetical, and a card that puts it beside the number
322
+ # squeezes both. The strip is read for the numbers.
323
+ out += [
324
+ f' <div class="blk {state}">',
325
+ f' <span class="b-n">{row.shipped} shipped · {row.open} open</span>',
326
+ f' <span class="b-t">{escape(row.title)}</span>',
327
+ " </div>",
328
+ ]
329
+ out.append("</div>")
330
+ if self.next_ready is not None:
331
+ task = self.next_ready.task
332
+ out += [
333
+ '<p class="next reveal">',
334
+ f' <span class="k">Next ready</span> <code>{escape(task.id)}</code> '
335
+ f"— {escape(task.symptom)}",
336
+ "</p>",
337
+ ]
338
+ return "\n".join(out)
339
+
340
+ def payload(self) -> dict[str, object]:
341
+ """The site build's shape. No timestamp, for the reason in the module docstring."""
342
+ return {
343
+ "prefix": self.prefix,
344
+ "files": self.files,
345
+ "blocks": [
346
+ {
347
+ "label": row.label,
348
+ "title": row.title,
349
+ "open": row.open,
350
+ "shipped": row.shipped,
351
+ "retired": row.retired,
352
+ }
353
+ for row in self.rows
354
+ ],
355
+ "totals": {
356
+ "open": self.totals.open,
357
+ "shipped": self.totals.shipped,
358
+ "retired": self.totals.retired,
359
+ },
360
+ "open": [_task_json(entry) for entry in self.open_entries],
361
+ "ledger": [_task_json(entry) for entry in self.ledger_entries],
362
+ "next": None if self.next_ready is None else self.next_ready.task.id,
363
+ }
364
+
365
+ def json(self) -> str:
366
+ return json.dumps(self.payload(), indent=2)
367
+
368
+
369
+ def project(
370
+ config: Config, documents: Mapping[str, Document] | None = None
371
+ ) -> Projection:
372
+ """Read the governed files and derive both shapes. Pure: nothing is written.
373
+
374
+ ``documents`` is the governed files as some *other* tree holds them, keyed by role — the
375
+ seam `lint --baseline` needs (RK104), since a block derived from this working tree and
376
+ compared against a README at a revision would report every ship since as a defect that
377
+ revision already had. Given, it is authoritative: a role it omits is a file that tree did
378
+ not carry, never one to fall back to disk for.
379
+ """
380
+ held = _from_disk(config) if documents is None else documents
381
+ roadmap_document = held.get("roadmap")
382
+ if roadmap_document is None:
383
+ raise KeyError("there is no roadmap to project: nothing states what is open")
384
+ ledger_document = held.get("changelog")
385
+ roadmap = Census.of(config, "roadmap", roadmap_document)
386
+ ledger = (
387
+ None
388
+ if ledger_document is None
389
+ else Census.of(config, "changelog", ledger_document)
390
+ )
391
+
392
+ shipped_marker = config.schema.shipped_marker
393
+ retired_marker = config.schema.retired_marker
394
+ titles = _titles(config, held)
395
+ labels = list(dict.fromkeys([*roadmap.blocks, *(ledger.blocks if ledger else ())]))
396
+ rows = tuple(
397
+ Row(
398
+ label=label,
399
+ title=titles.get(label, f"Block {label}"),
400
+ # A label the ledger declares and the roadmap does not is a block whose work
401
+ # is all shipped: zero open, not a refusal. `select` is right to refuse an
402
+ # undeclared block when a caller *asked* for one (RK28); here the label came
403
+ # from the files themselves, so the question is answered rather than rejected.
404
+ open=len(roadmap.select(block=label).counted) if label in roadmap.blocks else 0,
405
+ shipped=_count(ledger, label, shipped_marker),
406
+ retired=_count(ledger, label, retired_marker),
407
+ )
408
+ for label in labels
409
+ )
410
+ choice = pick(
411
+ config,
412
+ backlog=Backlog.during(
413
+ config,
414
+ roadmap=roadmap_document,
415
+ ledger=ledger_document,
416
+ store=held.get("deferred"),
417
+ ),
418
+ claims=False,
419
+ )
420
+ return Projection(
421
+ rows=rows,
422
+ open_entries=roadmap.counted,
423
+ ledger_entries=ledger.counted if ledger else (),
424
+ next_ready=choice.entry,
425
+ files={
426
+ role: config.relative(config.path(role))
427
+ for role in ("roadmap", "changelog", "improvements", "strategy")
428
+ if config.has(role)
429
+ },
430
+ prefix=config.schema.prefix,
431
+ show_retired=any(
432
+ e.task.status == retired_marker for e in (ledger.counted if ledger else ())
433
+ ),
434
+ listed=_listed(held.get(LISTED_ROLE)),
435
+ )
436
+
437
+
438
+ def _listed(document: Document | None) -> tuple[Listed, ...]:
439
+ """Every heading of the prose file, in file order, as the contents lists them (RK1110).
440
+
441
+ Off `Document.headings` and not off :func:`~roadkeep.sections.anchored`, which is the
442
+ decision worth stating: `anchored` drops a heading that declares no address, and those are
443
+ exactly the rows RK1107 made addressable and a reader still wants listed. A contents is
444
+ about what the file contains, not about what carries a pointer.
445
+ """
446
+ if document is None:
447
+ return ()
448
+ return tuple(
449
+ Listed(heading=text, slug=slug(text), level=heading.level)
450
+ for heading in document.headings
451
+ if (text := heading.text.strip())
452
+ )
453
+
454
+
455
+ def refreshes(config: Config, held: Sequence[Document]) -> tuple[Write, ...]:
456
+ """The projection writes a transaction owes for the files it is about to replace (RK188).
457
+
458
+ Called with the *edited* documents, before any of them lands, so the block is derived
459
+ from the state the transaction is creating and not from the one on disk — which is what
460
+ makes this a refresh rather than a second pass. Roles the transaction does not hold are
461
+ read from disk, because a projection counts three files and a `ship` writes at most two
462
+ of them.
463
+
464
+ Returns nothing where nothing changed, so an idempotent write stays idempotent: a
465
+ `section amend` moves no count and no next-ready line, and the README's mtime should
466
+ say so. The staleness question is asked here rather than in the caller for the reason
467
+ :data:`DEFAULTS` exists — the gate reads exactly what the write produces, and a second
468
+ place deciding "is it current" is a second answer to have wrong.
469
+ """
470
+ documents = dict(_from_disk(config))
471
+ for document in held:
472
+ role = _role_of(config, document.path)
473
+ if role is not None:
474
+ documents[role] = document
475
+ if "roadmap" not in documents:
476
+ return ()
477
+ projection = project(config, documents)
478
+ writes: list[Write] = []
479
+ for flag in DEFAULTS:
480
+ write, _ = splice_into(config, projection, flag)
481
+ if write is not None:
482
+ writes.append(write)
483
+ return tuple(writes)
484
+
485
+
486
+ def _role_of(config: Config, path: Path | None) -> str | None:
487
+ """Which projected role a file about to be written is, or None for one nothing projects.
488
+
489
+ The prose role joined the three counted ones with RK1110: a `section drop` edits the file
490
+ the contents lists, so a transaction holding it has to hand *that* version over — refreshing
491
+ from disk would derive the contents from the headings the drop is in the middle of removing.
492
+ """
493
+ if path is None:
494
+ return None
495
+ for role in (*COUNTED_ROLES, LISTED_ROLE):
496
+ if config.has(role) and config.path(role) == path:
497
+ return role
498
+ return None
499
+
500
+
501
+ def target_of(config: Config, flag: str) -> Path | None:
502
+ """The file this flag writes when it names no path, or None where the project has none.
503
+
504
+ One resolver for the write and for the gate (RK1110), which is :data:`DEFAULTS`' own reason
505
+ for existing: a target is a literal name or a governed role, and a second place deciding
506
+ which would be a gate reading a path nothing writes.
507
+ """
508
+ kind = DEFAULTS[flag]
509
+ if kind.role:
510
+ return config.path(kind.role) if config.has(kind.role) else None
511
+ return config.root / kind.name
512
+
513
+
514
+ def splice_into(
515
+ config: Config, projection: Projection, flag: str, name: str | None = None
516
+ ) -> tuple[Write | None, str]:
517
+ """Plan one target's marked block: the write to make, and which of two things happened.
518
+
519
+ One planner for the command and for the refresh a governed write carries (RK188), so
520
+ `export --readme` and a `ship` put the same bytes in the same place. ``name`` is the
521
+ path the flag was given on the command line; without one the target is where
522
+ :data:`DEFAULTS` says that flag writes, and a file that is not there is not a target —
523
+ an adopting project has a README long before it has a block in one.
524
+ """
525
+ resolved = config.root / name if name is not None else target_of(config, flag)
526
+ if resolved is None:
527
+ # A role this project does not declare (RK1110): the same answer an absent file gets,
528
+ # because a project with no rationale file has no contents to be stale.
529
+ return None, f"no {DEFAULTS[flag].role} file is declared"
530
+ target = resolved
531
+ where = config.relative(target)
532
+ if not target.is_file():
533
+ # Silent where nothing named it — a `ship` refreshes whatever a project happens to
534
+ # keep, and an adopting one has a README long before it has a block in it. Refused
535
+ # where the flag did (RK1039), including the bare `--readme` whose `const` names the
536
+ # default: a caller who asked for a projection is owed a sentence, not an errno.
537
+ if name is None:
538
+ return None, f"{where} is not there"
539
+ raise NoTarget(where)
540
+ with target.open("r", encoding="utf-8", newline="") as handle:
541
+ before = handle.read()
542
+ if name is None and BEGIN not in before:
543
+ # The markers are the declaration (RK37), the same reading the gate makes: a file
544
+ # carrying none is not a target, so a refresh never opens a container an author
545
+ # did not ask for. Named on the command line, the missing marker is still refused.
546
+ return None, f"{where} carries no projection"
547
+ after = splice(
548
+ before, projection.body(DEFAULTS[flag].shape, omit=enclosing(before)), where
549
+ )
550
+ if after == before:
551
+ # The point of idempotence, said out loud: nothing changed, so nothing is written
552
+ # and the file's mtime does not move either.
553
+ return None, f"{where} is already current"
554
+ return (
555
+ Write(target, after, functools.partial(_assert_unmoved, target, before)),
556
+ f"{where} refreshed between the roadkeep markers",
557
+ )
558
+
559
+
560
+ def _assert_unmoved(target: Path, before: str) -> None:
561
+ """The question `Document.save` asks (RK116), on the one file with no document (RK132).
562
+
563
+ Every governed write goes through `save` and is refused if the target stopped being the
564
+ file that was read. This one splices text into a README, which this tool does not own
565
+ and would be claiming a format it does not have by parsing — so the check is the same
566
+ question asked by hand: the bytes that were read, compared before the rename. A README
567
+ is the file most likely to be open in an editor while a command runs, which is exactly
568
+ the writer a lock does not order, and `--site` is the same splice on a second file.
569
+ """
570
+ if not target.is_file():
571
+ raise StaleFile(target, missing=True)
572
+ with target.open("r", encoding="utf-8", newline="") as handle:
573
+ if handle.read() != before:
574
+ raise StaleFile(target)
575
+
576
+
577
+ def splice(text: str, body: str, where: str) -> str:
578
+ """Replace what is between the markers, and nothing else.
579
+
580
+ Everything outside them is kept byte for byte, including the file's line endings: the
581
+ author owns that text and a projection that reformatted it would be an editor.
582
+ """
583
+ newline = "\r\n" if "\r\n" in text else "\n"
584
+ lines = text.split(newline)
585
+ begin = _index(lines, BEGIN, where, "begin")
586
+ end = _index(lines, END, where, "end")
587
+ if end < begin:
588
+ raise NoMarkers(where, "correctly ordered begin/end")
589
+ replaced = [*lines[: begin + 1], *body.split("\n"), *lines[end:]]
590
+ return newline.join(replaced)
591
+
592
+
593
+ def enclosing(text: str) -> str:
594
+ """The heading the roadkeep block is written under, less its `#`s (RK1110).
595
+
596
+ One reader for the write and for the gate, because both hold the target's text and the
597
+ contents needs to know which of the headings it lists is the one it is inside. Empty where
598
+ the block is above every heading or there is no marker at all — a projection at the top of
599
+ a file lists nothing twice, so there is nothing to leave out.
600
+ """
601
+ found = ""
602
+ for line in text.split("\n"):
603
+ if line.startswith("#"):
604
+ found = line.lstrip("#").strip()
605
+ elif line.strip() == BEGIN:
606
+ return found
607
+ return ""
608
+
609
+
610
+ def _index(lines: list[str], marker: str, where: str, name: str) -> int:
611
+ for number, line in enumerate(lines):
612
+ if line.strip() == marker:
613
+ return number
614
+ raise NoMarkers(where, name)
615
+
616
+
617
+ def _from_disk(config: Config) -> dict[str, Document]:
618
+ """The projected roles this project declares and has, each under its own schema.
619
+
620
+ Four since RK1110: the three counted, plus the prose file the contents lists. Read here
621
+ rather than in the renderer for the reason every other role is — `project` takes documents
622
+ so a baseline can hand it a revision's, and a role that fell back to disk on its own would
623
+ be the one input a `--baseline` run could not replace.
624
+ """
625
+ return {
626
+ role: config.document(role)
627
+ for role in (*COUNTED_ROLES, LISTED_ROLE)
628
+ if config.has(role) and config.path(role).is_file()
629
+ }
630
+
631
+
632
+ def _titles(config: Config, held: Mapping[str, Document]) -> dict[str, str]:
633
+ """Block titles from the headings that declare them, roadmap first, verbatim."""
634
+ out: dict[str, str] = {}
635
+ for role in ("changelog", "roadmap"): # the roadmap is read last, so its wording wins
636
+ document = held.get(role)
637
+ if document is None:
638
+ continue
639
+ for heading in document.headings:
640
+ if heading.label:
641
+ out[heading.label] = heading.text.removeprefix(
642
+ f"{config.schema.heading_word} "
643
+ )
644
+ return out
645
+
646
+
647
+ def _count(ledger: Census | None, label: str, marker: str) -> int:
648
+ if ledger is None:
649
+ return 0
650
+ return sum(
651
+ 1
652
+ for entry in ledger.counted
653
+ if entry.task.block == label and entry.task.status == marker
654
+ )
655
+
656
+
657
+ def _row(cells: list[str]) -> str:
658
+ return "| " + " | ".join(_cell(text) for text in cells) + " |"
659
+
660
+
661
+ def _cell(text: str) -> str:
662
+ """One cell, escaped as :func:`html.escape` escapes the other shape's (RK487).
663
+
664
+ A block title is the heading's own words, and a bar in one is the separator this row is
665
+ built from — so the cell splits, every count after it shifts a column, and the totals row
666
+ below stays right, which is a projection contradicting itself about work nobody changed.
667
+
668
+ Here rather than in :meth:`Projection._cells` for the reason :data:`DEFAULTS` is one
669
+ mapping: the linter re-derives this block and compares bytes (RK104), so a second place
670
+ deciding what a cell looks like is a second answer to have wrong. Head, separator, data
671
+ and totals all arrive through this door.
672
+
673
+ The backslash goes first, because `\\|` is what GFM reads as a literal bar — escaping the
674
+ bar alone would turn a title that already carried a backslash into one whose escape the
675
+ author never wrote.
676
+ """
677
+ return text.replace("\\", "\\\\").replace("|", "\\|")
678
+
679
+
680
+ def _task_json(entry: Entry) -> dict[str, object]:
681
+ task = entry.task
682
+ return {
683
+ "id": task.id,
684
+ "status": task.status,
685
+ "block": task.block,
686
+ "symptom": task.symptom,
687
+ "why": task.why,
688
+ "deps": [dep.render() for dep in task.deps],
689
+ "ref": task.ref,
690
+ "line": entry.lineno,
691
+ }
692
+
693
+
694
+ # -- one task, as a document (RK1362) -----------------------------------------
695
+
696
+
697
+ @dataclass(frozen=True, slots=True)
698
+ class Spec:
699
+ """One task as a **document**, for a reader who is not this session.
700
+
701
+ `brief` already composes this — the symptom, the non-goals that bind it, the `## Done
702
+ when` list and the design section — and it is bounded to a tool result on purpose, at
703
+ `[reads] brief`. That bound is the whole reason this exists separately: a reviewer on a
704
+ pull request, a second agent on a branch and a CI job asserting the criteria each need
705
+ the same four stores joined, and none of them can run the read.
706
+
707
+ So the ceiling is a file's rather than a result's: every list is whole, every lead is
708
+ uncut, and the design section is printed entire. Nothing here is composed (L4) — each
709
+ character passed a write that validated it — and nothing is stamped, so a re-run with
710
+ nothing to say makes no diff, which is `--readme`'s own argument one subject over.
711
+ """
712
+
713
+ task_id: str
714
+ block: str
715
+ block_named: str
716
+ status: str
717
+ readiness: str
718
+ where: str
719
+ symptom: str
720
+ why: str
721
+ #: `(id, status, detail)` per dep, in the order the line declares them.
722
+ deps: tuple[tuple[str, str, str], ...]
723
+ #: The task's own `## Done when — <id>` list, whole.
724
+ done_when: tuple[str, ...]
725
+ #: The block's, whole, and addressed by the block rather than by the line (RK1268).
726
+ block_done_when: tuple[str, ...]
727
+ #: Every non-goal, uncut: the scope a reviewer judges the work against.
728
+ non_goals: tuple[str, ...]
729
+ #: The design section's heading and body, entire, or the reason there is none.
730
+ heading: str = ""
731
+ body: str = ""
732
+ absence: str = ""
733
+ paths: tuple[str, ...] = ()
734
+
735
+ def markdown(self) -> str:
736
+ """The document, in the order a reader executes it.
737
+
738
+ The claim first and the design last, which is `brief`'s own order and for its reason:
739
+ what the work is measured against arrives before the first edit rather than at the
740
+ `ship`. A heading per store, so a reviewer can tell which file a sentence came out of.
741
+ """
742
+ rows = [
743
+ f"# {self.task_id} — {self.symptom}",
744
+ "",
745
+ _note("--spec"),
746
+ "",
747
+ f"**{self.block_named}** · **{self.status}** {self.readiness} · "
748
+ f"`{self.where}`",
749
+ "",
750
+ "## Why",
751
+ "",
752
+ self.why,
753
+ ]
754
+ if self.deps:
755
+ rows += ["", "## Depends on", ""]
756
+ rows += [f"- **{one}** — {status}, {detail}" for one, status, detail in self.deps]
757
+ if self.done_when:
758
+ rows += ["", f"## Done when — {self.task_id}", ""]
759
+ rows += [f"- {lead}" for lead in self.done_when]
760
+ if self.block_done_when:
761
+ rows += ["", f"## Done when — {self.block_named}", ""]
762
+ rows += [f"- {lead}" for lead in self.block_done_when]
763
+ if self.non_goals:
764
+ rows += ["", "## Non-goals", ""]
765
+ rows += [f"- {lead}" for lead in self.non_goals]
766
+ if self.paths:
767
+ rows += ["", "## Paths named", ""]
768
+ rows += [f"- `{one}`" for one in self.paths]
769
+ rows += ["", "## Design", ""]
770
+ rows += [self.heading, "", self.body] if self.heading else [self.absence]
771
+ return "\n".join(rows).rstrip() + "\n"
772
+
773
+
774
+ def spec(config: Config, task_id: str) -> Spec:
775
+ """Join the four stores for one task, with nothing elided (RK1362).
776
+
777
+ Composed off :func:`~roadkeep.briefing.brief` and never beside it, which is the rule
778
+ `--contents` keeps one file over: a spec derived twice is a spec that drifts from the
779
+ stores it claims to project. What differs is only the *bound* — the two lists are read
780
+ unbounded here, from the same two modules `brief` reads them bounded from.
781
+ """
782
+ from roadkeep import criteria, scoping # noqa: PLC0415 - RK260
783
+ from roadkeep.briefing import brief # noqa: PLC0415 - RK260
784
+ from roadkeep.sections import heading_of # noqa: PLC0415 - RK260
785
+
786
+ found = brief(config, task_id)
787
+ view, task = found.view, found.view.task
788
+ roadmap = config.document("roadmap")
789
+ return Spec(
790
+ task_id=task.id,
791
+ block=task.block,
792
+ block_named=config.schema.block_named(task.block),
793
+ status=task.status,
794
+ readiness=str(found.readiness),
795
+ where=f"{view.file}:{view.entry.lineno}",
796
+ symptom=task.symptom,
797
+ why=task.why,
798
+ deps=tuple(
799
+ (one.dep.id, str(one.status), one.detail) for one in found.deps
800
+ ),
801
+ done_when=criteria.leads(roadmap, task.id),
802
+ block_done_when=criteria.leads(roadmap, task.block),
803
+ non_goals=scoping.leads(roadmap),
804
+ heading="" if view.section is None else heading_of(config.schema, view.section),
805
+ body="" if view.section is None else view.section.body,
806
+ absence=view.section_absence,
807
+ paths=tuple(one.path for one in view.paths),
808
+ )