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/showing.py ADDED
@@ -0,0 +1,613 @@
1
+ """One task, from wherever its parts live (RK12).
2
+
3
+ A task is a line in one file, a rationale section in another, and sometimes a path on
4
+ disk. Nothing joins them, so reading one task means loading two whole files to reach
5
+ forty lines — the cost §RK29 measured at some 5k tokens to learn one line. `show` does
6
+ the join, and the join is the whole feature: no new field, no new file, nothing stored.
7
+
8
+ Three things it derives rather than trusts:
9
+
10
+ * **Where the id is.** The roadmap and the ledger are asked in that order, because
11
+ "RK6 shipped" is an answer and "no such task" is a different one (RK28's `NotOpen`
12
+ makes the same distinction one file up).
13
+ * **Whether the pointer resolves.** A `→ §RK12` whose section does not exist reads as a
14
+ design that does. Here it is reported as an absence *with the reason* — deleted on
15
+ ship, never written, or no prose file declared at all — because those are three
16
+ different states and only one of them is a defect (`lint` gates it: RK15).
17
+ * **The paths its text names.** Kept only when the file is really there, or when the
18
+ token is slash-shaped and therefore an explicit claim about the repository. That rule
19
+ is what separates `docs/specs/show.md` (missing, worth saying) from `Config.load`
20
+ (a dotted name in prose, and not this tool's business to report as a broken file).
21
+ Slash-shaped is not sufficient on its own: a glob, an elision, a placeholder or an npm
22
+ scope names a *class* of file rather than one, so it is dropped before disk is asked
23
+ (RK46) — asking would only ever answer "missing", and eight such answers on Shio were
24
+ eight false ones.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import os
30
+ import re
31
+ from collections.abc import Callable
32
+ from dataclasses import dataclass
33
+ from pathlib import Path
34
+
35
+ from roadkeep.config import DESIGN_ROLES, PROSE_ROLES, Config
36
+ from roadkeep.kernel.document import Document, Entry
37
+ from roadkeep.history import indexed
38
+ from roadkeep.provenance import invocation
39
+ from roadkeep.kernel.schema import Task
40
+ from roadkeep.sections import Section, addressable, declaring, find, heading_of
41
+
42
+ #: A path as prose spells one: inside backticks, or as a Markdown link target. Both are
43
+ #: deliberate acts of quoting, unlike a bare word that happens to contain a dot.
44
+ _QUOTED = re.compile(r"`([^`\s]+)`|\]\(([^)\s]+)\)")
45
+ _SCHEME = re.compile(r"^[a-z][a-z0-9+.-]*:")
46
+ #: A quoted token that stands for a *class* of file, not a file: a glob, an elision, a
47
+ #: placeholder, an npm scope. Each is slash-shaped, so each would otherwise read as a
48
+ #: claim the repository fails — `blueprints/*/files/package.json`, `monaco-editor/esm/vs/…`,
49
+ #: `template/widget/<name>.html`, `@graphiql/react`, four of the eight RK46 measured.
50
+ _UNRESOLVABLE = re.compile(r"[*…<]|^@")
51
+ #: A line anchor, which addresses a place *inside* a file and is not part of its name
52
+ #: (RK173): `scripts/prerender.mjs#L35`, `#L12-L20`. Two of Turing's eight `path.missing`
53
+ #: findings were this and nothing else — a token quoted the way GitHub spells a citation.
54
+ _LINE_ANCHOR = re.compile(r"#L\d+(?:-L?\d+)?$")
55
+ #: A token made of nothing but separators and dots names no artefact — a lone `\` quoted
56
+ #: as a character, `./`, `..`. Two of Turing's ledger entries quote one, and on Windows a
57
+ #: bare backslash *resolves*, to the drive root, so it read as a path the repository has
58
+ #: until RK218 stopped asking the disk about a revision. Refused rather than resolved,
59
+ #: because what it resolves to depends on the platform running the gate.
60
+ _SEPARATORS_ONLY = re.compile(r"^[\\/.]+$")
61
+
62
+
63
+ class NoSuchTask(KeyError):
64
+ """An id that is in neither governed file. Not a lint error — a wrong question."""
65
+
66
+ #: What an id in neither file means when it is nothing else. Replaced rather than
67
+ #: appended to where the argument turns out to address a live section (RK1025): "never
68
+ #: written or was retired" and "it is the section over there" are two different answers,
69
+ #: and printing both makes the refusal argue with itself.
70
+ ABSENT = "an id in neither file was never written or was retired (RK32)"
71
+
72
+ def __init__(self, task_id: str, where: tuple[str, ...], instead: str = "") -> None:
73
+ self.task_id = task_id
74
+ #: The verb one word away, where the argument turned out to address a section
75
+ #: (RK1025). Empty on the ordinary case, which is an id nothing carries.
76
+ self.instead = instead
77
+ super().__init__(
78
+ f"no task {task_id} in {' or '.join(where)}: {instead or self.ABSENT}"
79
+ )
80
+
81
+
82
+ @dataclass(frozen=True, slots=True)
83
+ class Referenced:
84
+ """A path the task's text names, and whether the repository has it."""
85
+
86
+ path: str
87
+ exists: bool
88
+
89
+
90
+ @dataclass(frozen=True, slots=True)
91
+ class View:
92
+ """Everything one task is, gathered from the files that hold a piece of it."""
93
+
94
+ entry: Entry
95
+ role: str
96
+ file: str
97
+ shipped: bool
98
+ section: Section | None
99
+ section_file: str | None
100
+ #: Which prose role declared it, so a reader can reach that file's own `section = <n>`
101
+ #: (RK287). The file alone cannot: `[limits.<role>]` is keyed by the role, and a printer
102
+ #: that re-derived it from the path would be the second answer to a settled question.
103
+ section_role: str | None
104
+ #: Why there is no section, when there is none. Empty when there is one.
105
+ section_absence: str
106
+ paths: tuple[Referenced, ...]
107
+ #: Every source line this entry owns, verbatim and with its endings (RK194). One on any
108
+ #: line a governed roadmap holds — the format has no multi-line task line — and more only
109
+ #: on a ledger written before this tool, where a bullet wraps. The span has been a fact
110
+ #: since RK157 and every *writer* uses it; this is the reader that prints it, so what
111
+ #: `record amend --lines` replaces is a command's answer rather than a file to open.
112
+ lines: tuple[str, ...] = ()
113
+
114
+ @property
115
+ def task(self) -> Task:
116
+ return self.entry.task
117
+
118
+ @property
119
+ def wrapped(self) -> bool:
120
+ """Whether the sentence runs past the line the parse read it from."""
121
+ return self.entry.wrapped
122
+
123
+ def stated(self, config: Config, *, body: bool = True) -> str:
124
+ """One task as a reader is told it, heading and prose included (RK9).
125
+
126
+ Beside :meth:`payload` since RK1170: these two were a printer in the handler and a builder
127
+ in `rendering.py`, so one answer was spelled in two files and neither held both. `config`
128
+ is passed and not stored — the limit beside a section's count is the *role's*, and which
129
+ file declared it is a fact about the project rather than about this view (RK287).
130
+ """
131
+ state = "shipped" if self.shipped else "open"
132
+ task, section = self.task, self.section
133
+ rows = [
134
+ f"{task.id} Block {task.block} {task.status} {state} "
135
+ f"{self.file}:{self.entry.lineno}",
136
+ f" symptom {task.symptom}",
137
+ f" why {task.why}",
138
+ ]
139
+ if self.wrapped:
140
+ # The rest of the sentence, verbatim (RK194): the fields above hold only as much of it
141
+ # as fits on the first line, and this is exactly what `record amend --lines` says it
142
+ # replaces — so the caller confirms the count here instead of opening the file.
143
+ rows.append(
144
+ f" wrapped {len(self.lines)} lines, {self.entry.lineno}-{self.entry.stop}"
145
+ )
146
+ rows += [
147
+ f" {offset:<9}{raw.rstrip()}"
148
+ for offset, raw in enumerate(self.lines, start=self.entry.lineno)
149
+ ]
150
+ if task.deps:
151
+ rows.append(f" deps {', '.join(dep.render() for dep in task.deps)}")
152
+ # And what the line is waiting **for**, which is not a dep (RK1311): a `(requires: …)`
153
+ # group says what has to be present for the work to be finishable, and this read — the
154
+ # one that joins a task out of every file holding a piece of it — printed the marker,
155
+ # the deps, the section and the budget, and nothing about it. Below the deps because
156
+ # that is the order the line spells them in, and silent where there are none, as the
157
+ # deps row is: a group nobody wrote is not an absence to report.
158
+ if task.requires:
159
+ rows.append(f" requires {', '.join(task.requires)}")
160
+ if section is not None:
161
+ # The role that declared it, so the limit printed beside the count is the one this
162
+ # file is held to (RK287) — `[limits.<role>]` is per prose file, exactly as it is for
163
+ # the changelog. A section exists only where a role declared it.
164
+ limit = config.schema_for(str(self.section_role)).section_max
165
+ rows.append(
166
+ f" section {self.section_file}:{section.first} "
167
+ f"§{section.anchor}, {section.counted(limit)}"
168
+ )
169
+ else:
170
+ # The absence carries its reason: deleted on ship, never written, or no prose file at
171
+ # all are three states, and only one of them is a defect (RK15).
172
+ rows.append(f" section none — {self.section_absence}")
173
+ rows += [
174
+ f" path {one.path}{'' if one.exists else ' (missing)'}" for one in self.paths
175
+ ]
176
+ if section is not None and body:
177
+ rows += ["", heading_of(config.schema, section), "", section.body]
178
+ return "\n".join(rows)
179
+
180
+ def payload(self, *, body: bool = True) -> dict[str, object]:
181
+ """The same answer as data, with the prose only where it was asked for (RK9).
182
+
183
+ Beside :meth:`stated` since RK1170, and the two differ on purpose: the printed register
184
+ is what a reader scans, and this carries the span a correction replaces and the absence
185
+ reason a client cannot infer.
186
+ """
187
+ task, section = self.task, self.section
188
+ body = None if not body or section is None else section.body
189
+ return {
190
+ "id": task.id,
191
+ "status": task.status,
192
+ "block": task.block,
193
+ "shipped": self.shipped,
194
+ "file": self.file,
195
+ "line": self.entry.lineno,
196
+ "rendered": self.entry.raw,
197
+ # The whole entry, and the span a correction replaces (RK194). Always present, so a
198
+ # caller reads the count rather than inferring one from a key that came and went.
199
+ "lines": [raw.rstrip("\r\n") for raw in self.lines],
200
+ "wrapped": self.wrapped,
201
+ "symptom": task.symptom,
202
+ "why": task.why,
203
+ "deps": [dep.render() for dep in task.deps],
204
+ # What has to be present for this to be finishable (RK1311), which is not a dep and
205
+ # is what `pick --have` filters on. `[]` and never omitted, for `deps`' reason: a
206
+ # key that appears only when it is set is one a reader learns to stop looking for.
207
+ "requires": list(task.requires),
208
+ "ref": task.ref,
209
+ "section": None
210
+ if section is None
211
+ else {**section.payload(self.section_file or ""), "body": body},
212
+ "section_absence": self.section_absence,
213
+ "paths": [{"path": p.path, "exists": p.exists} for p in self.paths],
214
+ }
215
+
216
+
217
+ def show(config: Config, task_id: str) -> View:
218
+ """Join the line, its section and the paths it names. Reads; never writes."""
219
+ entry, role, document = _locate(config, task_id)
220
+ section, section_file, section_role, absence = _rationale(
221
+ config, entry, shipped=role == "changelog"
222
+ )
223
+ owned = document.lines[entry.index : entry.stop]
224
+ # The whole entry, and not `entry.raw`: on a wrapped bullet the tail is the rest of the
225
+ # sentence, so a path quoted there is one this task names (RK194).
226
+ text = "".join(owned) + ("\n" + section.body if section is not None else "")
227
+ return View(
228
+ entry=entry,
229
+ role=role,
230
+ lines=owned,
231
+ file=config.relative(config.path(role)),
232
+ shipped=role == "changelog",
233
+ section=section,
234
+ section_file=section_file,
235
+ section_role=section_role,
236
+ section_absence=absence,
237
+ # Both bases, for the reason RK51 gives: the line and its section are read from a
238
+ # file, and a link relative to that file names an artefact the repository has.
239
+ paths=paths_in(
240
+ text,
241
+ config.root,
242
+ near=config.path(role).parent,
243
+ known=lambda: known_directories(config),
244
+ ),
245
+ )
246
+
247
+
248
+ def _locate(config: Config, task_id: str) -> tuple[Entry, str, Document]:
249
+ asked: list[str] = []
250
+ for role in ("roadmap", "changelog"):
251
+ if not config.has(role) or not config.path(role).is_file():
252
+ continue
253
+ asked.append(config.relative(config.path(role)))
254
+ document = config.document(role)
255
+ found = document.by_id().get(task_id)
256
+ if found is not None:
257
+ # The document too, and not the entry alone: the lines an entry owns are the
258
+ # file's, and loading it a second time to reach them is a second parse (RK194).
259
+ return found, role, document
260
+ raise NoSuchTask(task_id, tuple(asked), _instead(config, task_id))
261
+
262
+
263
+ def _instead(config: Config, given: str) -> str:
264
+ """The verb one word away, where the argument addresses a section (RK1025).
265
+
266
+ `show XX` used to answer *"no task XX … never written or was retired"*, which is
267
+ accurate and answers a question nobody asked: `XX` is the shape this tool prints in
268
+ every `→ §XX.1` it writes, and `section show XX` is the verb for it. The refusal said
269
+ what the argument was **not**, in a vocabulary the caller was not using, and the next
270
+ move it left them was a grep of the file the guard exists to keep them out of.
271
+
272
+ Two answers and they are not the same claim. A prose file that **declares** the address
273
+ is a fact — the section is there, and this is a redirect. An address the outline merely
274
+ *could* number is a reading of the argument's shape, which is worth saying because a
275
+ caller who typed one is holding a pointer, and is not worth stating as if a section
276
+ existed. A `§` the caller typed is the third: nobody writes a sigil at a task id.
277
+
278
+ **Named and never dispatched.** `show` joins a line, its section and its paths; `section
279
+ show` prints one section and its word count. A verb that quietly answered the other
280
+ question would be the second answer to one argument, which is what this repository
281
+ refuses everywhere else — and the caller who wanted the join would get the section and
282
+ no way to see that they had.
283
+ """
284
+ paused = _paused(config, given)
285
+ if paused:
286
+ return paused
287
+ anchor = given.lstrip("§")
288
+ if not anchor:
289
+ return ""
290
+ verb = f"`{invocation()} section show {anchor}`"
291
+ where = declaring(config, anchor)
292
+ if where:
293
+ files = " and ".join(config.relative(config.path(role)) for role in where)
294
+ return f"§{anchor} is a section in {files}, which {verb} prints"
295
+ if given.startswith("§") or addressable(config.schema, anchor):
296
+ return (
297
+ f"{NoSuchTask.ABSENT}, and §{anchor} is a section address rather than an id "
298
+ f"— {verb} reads one"
299
+ )
300
+ return _where_it_went(config, anchor)
301
+
302
+
303
+ def _paused(config: Config, task_id: str) -> str:
304
+ """The store's answer, where the two carriers this read opens have none (RK1341).
305
+
306
+ `defer` moves a line out of the backlog on purpose, so every task-addressed read declining
307
+ it is right: `pick` skips it, `list` omits it, and that is the whole point of the verb.
308
+ What none of them said is *where it went* — `show` answered `an id in neither file was
309
+ never written or was retired`, and both of those are false about a line sitting in
310
+ `DEFERRED.md` with a reason beside it.
311
+
312
+ First of the three answers here and not last, because it is the strongest: a declared
313
+ carrier holding the id is a fact, where an addressable anchor is a reading of the
314
+ argument's shape and history is evidence the id once existed. It is also the cheapest —
315
+ one parse against `_where_it_went`'s `git log` — and it is asked only after the parse has
316
+ failed, which is the rule that keeps this whole path free.
317
+
318
+ Silent where no `deferred` role is declared, that project having no such state to be in.
319
+ """
320
+ if not config.has("deferred") or not config.path("deferred").is_file():
321
+ return ""
322
+ entry = config.document("deferred").by_id().get(task_id)
323
+ if entry is None:
324
+ return ""
325
+ where = config.relative(config.path("deferred"))
326
+ # Both doors, in the order the reader needs them: what it says, then how to undo it. The
327
+ # read comes first because a paused line is usually being *checked*, not resumed.
328
+ return (
329
+ f"{task_id} is paused in {where}:{entry.lineno} — "
330
+ f"`{invocation()} list --role deferred` prints it with the reason it was set aside, "
331
+ f"and `{invocation()} resume {task_id}` returns it to its block"
332
+ )
333
+
334
+
335
+ def _where_it_went(config: Config, task_id: str) -> str:
336
+ """History's answer, where the parse has none (RK1048).
337
+
338
+ `Document.by_id()` keys an entry by the id it **leads with**, so an entry delivering two
339
+ things is visible under one of them. Measured in Shio: `docs/CHANGELOG.md:150` opens
340
+ `- **SH154** …` and its sentence also ships `**SH169**`, so `show SH169` answered *never
341
+ written or was retired* about a task that is in the file — while `gaps` resolved it to
342
+ `c843f449 feat(agent): verify and digest see a page's section references (SH154, SH169)`.
343
+ Two readers of one file, disagreeing.
344
+
345
+ Asked **only after the parse has failed**, so the answer path costs nothing and a common
346
+ typo costs one `git log` on a refusal that was already being composed. And it says only
347
+ what it found: a commit is evidence the id was written, never a claim about which entry
348
+ holds it — that is `gaps`', and naming it is what this sentence is for.
349
+
350
+ Silent where git cannot answer. A shallow clone, a tarball, an unindexed tree: the
351
+ absence is the refusal's own, and inventing a whereabouts from a failed search would be
352
+ the worse half of the defect this closes.
353
+ """
354
+ # Deferred: `history` shells out, and the overwhelming majority of `show` calls resolve.
355
+ from roadkeep.history import HistoryUnavailable, origin_of # noqa: PLC0415 - RK1002
356
+
357
+ try:
358
+ found = origin_of(config, task_id)
359
+ except (HistoryUnavailable, OSError):
360
+ return ""
361
+ commit = found.shipped_in or found.proposed_in
362
+ if commit is None:
363
+ return ""
364
+ return (
365
+ f"{NoSuchTask.ABSENT} — but {commit.short} wrote it "
366
+ f"({commit.subject}), so it is in a line this parse reads under another id: "
367
+ f"`{invocation()} gaps` resolves which"
368
+ )
369
+
370
+
371
+ def _rationale(
372
+ config: Config, entry: Entry, shipped: bool
373
+ ) -> tuple[Section | None, str | None, str | None, str]:
374
+ """The section the pointer addresses, from **whichever** prose role declares it (RK186).
375
+
376
+ RK172 taught resolution that a pointer addresses every governed prose file, because
377
+ `[files]` declares strategy as a role and a line pointing at it is already in the model.
378
+ It taught the gate and not this reader — and this is the worse half to leave: `lint` is
379
+ the backstop and is read once, while `show` and `brief` are what *start* a task. An agent
380
+ told the pointer resolves to nothing writes the design a second time, under an anchor the
381
+ line does not name, which is the `section.unreachable` RK135 exists to report.
382
+
383
+ Two roles declaring one anchor is the ambiguity, not a first match: reading the first is
384
+ what billed T354's `§X.1` 365 words of somebody else's subtree without saying so, and
385
+ `ref.ambiguous` is the gate's own word for it.
386
+ """
387
+ anchor = _decided_anchor(config, entry) or entry.task.ref or entry.task.id
388
+ # Searched across every prose role and *placed* in the design's two (RK1361). The two
389
+ # questions parted when `decisions` became a prose file: an anchor is resolved wherever a
390
+ # heading may declare it, so a decision's own body is found by `show` — while "where the
391
+ # design would go" is still improvements or strategy, a decisions file being somewhere a
392
+ # task's rationale never goes and so not an absence a `declare` here would close.
393
+ roles = tuple(role for role in PROSE_ROLES if config.has(role))
394
+ designed = tuple(role for role in DESIGN_ROLES if config.has(role))
395
+ if not designed:
396
+ return None, None, None, f"this project declares no {' or '.join(DESIGN_ROLES)} file"
397
+ named = " or ".join(config.relative(config.path(role)) for role in roles)
398
+ # Where the design would go, for every answer that has no section: the first declared
399
+ # role, which is `improvements` wherever a project declares one.
400
+ where = config.relative(config.path(designed[0]))
401
+ on_disk = tuple(role for role in roles if config.path(role).is_file())
402
+ if not on_disk:
403
+ return None, where, None, f"{named} is not on disk yet"
404
+ found = [
405
+ (config.relative(config.path(role)), role, section)
406
+ for role in on_disk
407
+ if (section := find(config.document(role), anchor)) is not None
408
+ ]
409
+ if len(found) == 1:
410
+ return found[0][2], found[0][0], found[0][1], ""
411
+ if found:
412
+ both = " and ".join(file for file, _, _ in found)
413
+ return (
414
+ None,
415
+ None,
416
+ None,
417
+ f"§{anchor} is declared by {both}: one anchor names one section, and a "
418
+ f"pointer resolving to two resolves to neither",
419
+ )
420
+ if shipped:
421
+ # Not a defect: `ship` deletes the section, which is what keeps the prose file a
422
+ # design file rather than a second changelog (RK6).
423
+ return None, where, None, "deleted on ship, which is where the rationale ends"
424
+ return None, where, None, f"§{anchor} is not in {named}: the pointer resolves to nothing"
425
+
426
+
427
+ def _decided_anchor(config: Config, entry: Entry) -> str:
428
+ """Where this id's **decision** keeps its body, if a record here has one (RK1363).
429
+
430
+ A ship deletes the design and files the decision, so once a line is in the ledger the
431
+ prose that survives is the decision's — and under `ref_scheme = "id"` this read found it
432
+ already, the anchor being the id either way. Under an outline it did not: the address is
433
+ the `--decides-ref` the record carries, and nothing else in the project spells it.
434
+
435
+ Never a shadow of a live line's own design: a decision is filed at the moment a line
436
+ departs, so no id is both an open line and a record here. Empty where the project
437
+ declares no decisions file, which is most of them.
438
+ """
439
+ if not config.has("decisions") or not config.path("decisions").is_file():
440
+ return ""
441
+ recorded = config.document("decisions").by_id().get(entry.task.id)
442
+ return "" if recorded is None else (recorded.task.ref or "")
443
+
444
+
445
+ def paths_in(
446
+ text: str,
447
+ root: Path,
448
+ *,
449
+ near: Path | None = None,
450
+ known: Callable[[], frozenset[str] | None] | None = None,
451
+ has: Callable[[str], bool] | None = None,
452
+ ) -> tuple[Referenced, ...]:
453
+ """Quoted paths, deduplicated, in order of appearance.
454
+
455
+ Public because RK29 joins the same list onto a wider answer, and a second
456
+ implementation would disagree about what counts as a path.
457
+
458
+ `near` is the directory the text was read from, and a token resolves against it as
459
+ well as against `root` (RK51). Both conventions are live: this repository writes
460
+ root-relative tokens in its own lines, Shio writes the file-relative ones Markdown
461
+ itself reads — 886 of them — and the question being asked is whether the repository
462
+ has the artefact, not whether the link would render from where it is written.
463
+
464
+ `known` answers *which directories the repository knows about*, which is what decides
465
+ whether a token is a claim at all (RK217, and see :func:`_claims_a_file`). A **callable**
466
+ and not the set, because the set costs a git listing and is needed only for a token that
467
+ fails `exists` — which on a healthy repository is none of them (RK222): `show` went from
468
+ 1.1 ms to 36.6 ms here and 4.2 ms to 73.4 ms on Turing by computing it up front, on the
469
+ read that starts every task. Called at most once per run of this function, and never
470
+ where every path resolves. Omitted, or answering None, keeps the filesystem answer.
471
+
472
+ `has` answers *does the tree being judged hold this artefact*, and the disk is only its
473
+ default (RK225). A run naming a revision may not consult the disk (RK218) and used to
474
+ consult it anyway — 34070 `stat` calls at Turing's pin, every one discarded — and worse,
475
+ `exists` decides **candidacy** here, so the candidate set was still half decided by this
476
+ afternoon while the findings were about a commit.
477
+ """
478
+ out: dict[str, Referenced] = {}
479
+ directories: frozenset[str] | None = None
480
+ asked = False
481
+ for match in _QUOTED.finditer(text):
482
+ token = (match.group(1) or match.group(2)).rstrip(".,;:")
483
+ if not token or _SCHEME.match(token) or token.startswith("#"):
484
+ continue
485
+ # One spelling, whatever platform wrote the line (RK226). A backslash separates on
486
+ # Windows and is an ordinary filename character everywhere else, so `docs\specs\x.md`
487
+ # resolved for its author and was a single unheard-of name in CI — the gate answering
488
+ # by host, which is RK213's shape through a different door. Normalised *toward* the
489
+ # repository's own spelling, because git's listing is forward slashes on every
490
+ # platform; a real filename holding a backslash is the case this gets wrong, and it
491
+ # cannot exist on Windows at all and breaks every Windows checkout where it can.
492
+ token = _LINE_ANCHOR.sub("", token.replace("\\", "/"))
493
+ if token.startswith("/"):
494
+ # Not this repository: `/roadkeep:add` is a slash command, and an absolute
495
+ # path is wrong on every other machine (which `roadkeep.toml` also refuses).
496
+ # Both are slash-shaped, so without this they read as claims about a file
497
+ # that is missing — four of them on one line, in RK25's own text.
498
+ continue
499
+ if _UNRESOLVABLE.search(token) or _SEPARATORS_ONLY.match(token):
500
+ # Nothing on disk can settle it either way, so there is no question to ask.
501
+ continue
502
+ exists = has(token) if has is not None else on_disk(token, root, near)
503
+ # Either the repository really has it, or the token is a decidable claim that it
504
+ # should: a filename whose directory the repository knows (RK55, RK217). A slash
505
+ # alone is not — 60 of Shio's 61 findings were a MIME type, an i18n key or two
506
+ # method names sharing one.
507
+ if not exists and known is not None and not asked:
508
+ directories, asked = known(), True
509
+ if exists or _claims_a_file(token, root, near, directories):
510
+ out.setdefault(token, Referenced(path=token, exists=exists))
511
+ return tuple(out.values())
512
+
513
+
514
+ def _claims_a_file(
515
+ token: str, root: Path, near: Path | None, known: frozenset[str] | None
516
+ ) -> bool:
517
+ """Whether a token that does not resolve is nonetheless a claim about a file (RK55).
518
+
519
+ Both halves are needed. The extension is what tells `lib/shio.ts` from
520
+ `ShPostUnifiedWriteService.update/publish`; the directory is what tells a file this
521
+ repository lost from one that was never in it — the `app/api/…` of a template it
522
+ generates elsewhere. Together they took Shio's 61 findings to the one true row: a Java
523
+ class the ledger still names under the directory it was renamed inside.
524
+
525
+ ``known`` is the second half asked of the **repository** rather than of this disk
526
+ (RK217). The filesystem was a proxy, and it failed in the direction that costs most: a
527
+ ledger naming `lib/gone.py` reported when that one file went and reported *nothing*
528
+ when `lib/` went with it, which is the larger deletion. Given the directories the
529
+ repository tracks or has declared it never will, the answer stops depending on what
530
+ somebody last built or cleaned.
531
+
532
+ Measured before the change, over both pins: 7246 distinct tokens, and the two rules
533
+ disagree on **none** of them — so what RK55 closed stays closed and nothing new is
534
+ admitted. The difference only appears once the disk stops matching the repository,
535
+ which is exactly the state the gate has to survive. ``None`` keeps the filesystem
536
+ answer, for a caller with no repository to ask.
537
+ """
538
+ head, _, name = token.rpartition("/")
539
+ if not head or "." not in name:
540
+ return False
541
+ bases = (root,) if near is None else (near, root)
542
+ if known is None:
543
+ return any((base / head).is_dir() for base in bases)
544
+ return any(_within(base / head, root) in known for base in bases)
545
+
546
+
547
+ def known_directories(
548
+ config: Config, names: frozenset[str] | None = None
549
+ ) -> frozenset[str] | None:
550
+ """Every directory this repository knows about, tracked or declared untracked (RK217).
551
+
552
+ The set `_claims_a_file` asks instead of the disk: every prefix of every tracked path,
553
+ built once per command from one listing rather than a stat per token.
554
+
555
+ **Tracked only, and no ignored directory in it.** A `bin/Release/app.exe` under an
556
+ ignored `bin/` would be admitted here and then withheld by `declared_untracked` (RK213)
557
+ one step later, so adding it would be a `check-ignore` per head for an answer that does
558
+ not change. The two rules compose in that order on purpose: this one asks whether the
559
+ token is a claim about *this* repository, and that one asks whether the repository said
560
+ it would never hold the file.
561
+
562
+ ``names`` is the listing a caller already holds, so a run at a revision passes that
563
+ revision's and this does not ask twice. Absent, the **index** is read and not
564
+ :func:`tracked_now` (RK221): that one subtracts what git calls deleted, which is right
565
+ for "does the tree still have this artefact" and exactly wrong here — a ledger naming
566
+ `lib/gone.py` after the file went would stop being a claim instead of becoming a
567
+ finding, and `show` said the task named no path at all while `lint` reported it missing.
568
+
569
+ **None where git cannot answer**, and the caller falls back to the disk. An absent
570
+ answer is not a negative one (RK95, and RK28 one file up): a checkout with no history
571
+ tracks nothing and declares nothing, so reading its silence as "no directory here is
572
+ the repository's" would drop every path claim in the file rather than decide it.
573
+
574
+ The root is in the set, because a token written from a governed file's own directory
575
+ can name it — `../outside.txt` from `docs/` is a path at the top of the repository, and
576
+ the repository certainly knows that directory.
577
+ """
578
+ if names is None:
579
+ names = indexed(config)
580
+ if not names:
581
+ return None
582
+ return frozenset(
583
+ {"."}
584
+ | {
585
+ "/".join(segments[:cut])
586
+ for name in names
587
+ for segments in (name.split("/"),)
588
+ for cut in range(1, len(segments))
589
+ }
590
+ )
591
+
592
+
593
+ def _within(path: Path, root: Path) -> str | None:
594
+ """A path as the repository spells it, or None where it climbs out of the tree."""
595
+ try:
596
+ spelled = os.path.relpath(path.resolve(), root.resolve()).replace(os.sep, "/")
597
+ except ValueError: # a different mount, so not this repository's at all
598
+ return None
599
+ return None if spelled.startswith("..") else spelled
600
+
601
+
602
+ def on_disk(token: str, root: Path, near: Path | None) -> bool:
603
+ """Whether *this working tree* has the artefact, under either convention (RK51).
604
+
605
+ Public because it is the default answer to "does the tree being judged hold this" and
606
+ a caller judging a **revision** supplies a different one (RK225). Named for what it
607
+ reads rather than for what it decides, so the two cannot be confused at a call site.
608
+ """
609
+ if Path(token).is_absolute():
610
+ # Refused in a config and meaningless in a line: it is a claim about one machine.
611
+ return False
612
+ bases = (root,) if near is None else (near, root)
613
+ return any((base / token).exists() for base in bases)