Coverage for packages/workshop/src/livery/workshop/_prose.py: 96%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_prose.py, packages/workshop/tests/test_workshop_conformance.py, packages/extensions/pytest/tests/test_pytest.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings_refs.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings.py, packages/extensions/docs/tests/test_taskref.py, packages/extensions/docs/tests/test_task_links.py, packages/extensions/docs/tests/test_llms.py, packages/extensions/docs/tests/test_groups.py, packages/extensions/docs/tests/test_extensions_docs.py, packages/extensions/docs/tests/test_docs_verbs.py, packages/extensions/docs/tests/test_docs_site.py, packages/extensions/docs/tests/test_docs_phase.py, packages/extensions/docs/tests/test_docs_contract.py, packages/extensions/docs/tests/test_docs.py, packages/extensions/agents/tests/test_agents.py ran.

1"""Prose fragments: what the extensions say to the agent and to a reader, in sections.
2
3An extension's prose, its voice, its standards, its rules, is a set of
4fragments, and one set writes the agent's entry file and the site's
5development pages. A fragment is a markdown file in the extension's
6``content/fragments/`` named ``<section>.<topic>[.<audience>].md``, or
7one the base renders from its registries, a render that takes the
8audience. The base defines the sections and their order, and an
9extension adds fragments to them, never a section. The audience is
10``agent`` or ``human``, and a name without one serves both; a render
11answers each audience itself, and an empty answer leaves the fragment
12out for that reader. A topic is never named ``agent`` or ``human``: the
13last part of a name spells the audience.
14
15The agents extension delivers the agent's set as numbered rule files
16under each enabled agent's local rules directory: a shipped fragment
17byte for byte its source, a rendered one under a header naming its
18origin, each through the fragment engine so an edited copy is kept and
19named. The repository's own fragments live in ``fragments/`` at the
20root under the same names, are linked rather than copied, and sort
21last. Reach for
22[livery.workshop._prose.fragments][] for the set a reader gets and
23[livery.workshop._shipped_files][] for the delivery.
24"""
25
26from __future__ import annotations
27
28import json
29import shutil
30from collections.abc import Callable, Iterable
31from dataclasses import dataclass
32from pathlib import Path
33from typing import Any, cast
34
35import livery.footman as footman
36
37BASE_EXTENSION = "livery.workshop"
38AGENT = "agent"
39HUMAN = "human"
40AUDIENCES = (AGENT, HUMAN)
41
42#: The base's sections, in the order the entry file and the site read them.
43BASE_SECTIONS = (
44 "identity",
45 "voice",
46 "standards",
47 "rules",
48 "workflow",
49 "gate",
50 "verbs",
51 "compositions",
52 "tools",
53)
54
55#: The fragments directory: an extension's under its content, the repository's
56#: own at the root.
57OWN = "fragments"
58
59#: The extension name of the repository's own fragments.
60REPOSITORY = ""
61
62#: A render: the workspace root and the audience, ``agent``, ``human``
63#: or None for no particular reader, to the markdown; empty leaves the
64#: fragment out for that reader.
65Render = Callable[[Path, "str | None"], str]
66
67
68class ProseError(ValueError):
69 """A fragment name the guidance refuses; the message names the files."""
70
71
72@dataclass(frozen=True)
73class Prose:
74 """One prose fragment: a file an extension ships, or a render from the registries.
75
76 Attributes:
77 section: The section it belongs to, one of the base's.
78 topic: What it is about; with the section, its name.
79 audience: ``agent`` or ``human`` for a file that serves one
80 reader, empty for both; a rendered fragment is empty here
81 and answers per audience.
82 extension: The extension that ships or renders it; empty for the
83 repository's own.
84 source: The shipped file, or None for a rendered fragment.
85 render: The render, or None for a shipped fragment.
86 """
87
88 section: str
89 topic: str
90 audience: str = ""
91 extension: str = BASE_EXTENSION
92 source: Path | None = None
93 render: Render | None = None
94
95 @property
96 def name(self) -> str:
97 """The delivered file name, ``<section>.<topic>.md``."""
98 return f"{self.section}.{self.topic}.md"
99
100 @property
101 def origin(self) -> str:
102 """Where it comes from, for a refusal: the posix file, or the extension."""
103 if self.source is not None:103 ↛ 105line 103 didn't jump to line 105 because the condition on line 103 was always true
104 return f"{self.source.as_posix()} ({self.extension or 'this repository'})"
105 return f"the render of {self.extension}"
106
107 def text(self, root: Path, audience: str | None) -> str:
108 """The markdown for *audience*: the shipped text, or the render's answer."""
109 if self.render is not None:
110 return self.render(root, audience)
111 if self.source is not None:111 ↛ 113line 111 didn't jump to line 113 because the condition on line 111 was always true
112 return self.source.read_text(encoding="utf-8")
113 return ""
114
115
116def _check_section(where: str, section: str) -> None:
117 if section not in BASE_SECTIONS:
118 raise ProseError(
119 f"{where}: section {section!r} is not one of the sections; the"
120 f" sections are {', '.join(BASE_SECTIONS)}"
121 )
122
123
124def parse_name(filename: str, *, where: str = "") -> tuple[str, str, str]:
125 """Split a fragment file name into section, topic and audience.
126
127 ``rules.tests.agent.md`` is the rules section, the topic tests, for
128 the agent. A third part spells the audience, so a topic is never
129 named ``agent`` or ``human``. Refuses a name outside the convention
130 and an unknown section, naming *where*, the file by default.
131 """
132 where = where or filename
133 stem, dot, suffix = filename.rpartition(".")
134 parts = stem.split(".") if dot and suffix == "md" else []
135 audience = ""
136 if len(parts) > 2 and parts[-1] in AUDIENCES:
137 audience = parts.pop()
138 if len(parts) != 2 or not all(parts):
139 raise ProseError(
140 f"{where}: a fragment is named <section>.<topic>[.<audience>].md"
141 )
142 section, topic = parts
143 _check_section(where, section)
144 return section, topic, audience
145
146
147def shipped(extension: str, content: Path) -> list[Prose]:
148 """The fragments *extension* ships under ``content/fragments/``, in name order.
149
150 Every file there is a fragment, so a name outside the convention
151 refuses naming the file. The repository's own come from its root
152 with the empty extension name.
153 """
154 directory = content / OWN
155 if not directory.is_dir():
156 return []
157 found: list[Prose] = []
158 for path in sorted(directory.iterdir()):
159 if not path.is_file():159 ↛ 160line 159 didn't jump to line 160 because the condition on line 159 was never true
160 continue
161 section, topic, audience = parse_name(path.name, where=path.as_posix())
162 found.append(Prose(section, topic, audience, extension, source=path))
163 return found
164
165
166def repository_fragments(root: Path) -> list[Prose]:
167 """The repository's own fragments under ``fragments/`` at *root*, in name order."""
168 return shipped(REPOSITORY, root)
169
170
171def in_play(root: Path, order: Iterable[str] | None = None) -> list[Prose]:
172 """Every shipped fragment in play: each extension's set in *order*, then the own.
173
174 *order* is the mounted extensions' order, the workspace's stack when
175 absent. An extension that ships no content adds nothing.
176 """
177 from livery.workshop._extensions import extension_content, stack_names
178
179 listed: list[Prose] = []
180 for extension in stack_names(root) if order is None else order:
181 content = extension_content(extension)
182 if content is not None:
183 listed += shipped(extension, content)
184 return [*listed, *repository_fragments(root)]
185
186
187def guidance(root: Path, audience: str) -> list[Prose]:
188 """The guidance one reader gets in the workspace at *root*, in reading order.
189
190 *audience* is [livery.workshop.AGENT][] or [livery.workshop.HUMAN][].
191 The set is every fragment the mounted extensions ship, every
192 fragment the base renders, and the repository's own under
193 ``fragments/``: by section, then by extension in mount order, the
194 repository's own last, then by name. A fragment written for the
195 other reader is left out.
196
197 Raises:
198 ValueError: when two fragments in the set deliver under one name,
199 naming both.
200 """
201 return fragments(root, in_play(root), audience)
202
203
204def present_extensions(root: Path) -> frozenset[str]:
205 """The extensions the sets of the packages present in *root* hold."""
206 from livery.workshop._composition import extension_set
207 from livery.workshop._packages import discover_packages
208
209 return frozenset(
210 name for package in discover_packages(root) for name in extension_set(package)
211 )
212
213
214def fragments(
215 root: Path, shipped: Iterable[Prose], audience: str | None
216) -> list[Prose]:
217 """The fragments *audience* reads: by section, then extension, then name.
218
219 A shipped fragment for the other reader is left out; a rendered
220 fragment is always in and answers for itself when rendered. The
221 mounted extensions come in mount order, an extension outside the mount
222 after them, and the repository's own last. Two fragments of one
223 name in the set refuse naming both.
224 """
225 from livery.workshop._extensions import stack_names
226
227 chosen: list[Prose] = []
228 for prose in [*shipped, *_RENDERED.values()]:
229 if prose.audience and prose.audience != audience:
230 continue
231 chosen.append(prose)
232 mounted = list(stack_names(root))
233
234 def rank(prose: Prose) -> tuple[int, int, int, str, str]:
235 if prose.extension == REPOSITORY:
236 tier, index, name = 2, 0, ""
237 elif prose.extension in mounted:
238 tier, index, name = 0, mounted.index(prose.extension), ""
239 else:
240 tier, index, name = 1, 0, prose.extension
241 return (BASE_SECTIONS.index(prose.section), tier, index, name, prose.name)
242
243 chosen.sort(key=rank)
244 seen: dict[str, Prose] = {}
245 for prose in chosen:
246 other = seen.setdefault(prose.name, prose)
247 if other is not prose:
248 raise ProseError(
249 f"two fragments deliver as {prose.name}: {other.origin} and"
250 f" {prose.origin}; a topic is unique across everything delivered"
251 )
252 return chosen
253
254
255def render_gate(root: Path, audience: str | None) -> str:
256 """The gate's steps for the extensions the members hold.
257
258 A list for the agent, a table for a reader. A step of a phase the
259 gate does not run, one declared ``gated = false``, is left out.
260 """
261 from livery.workshop._steps import _gated, steps_by_name
262
263 present = present_extensions(root)
264 records = [
265 record
266 for record in steps_by_name().values()
267 if _gated(record)
268 and (not record.extensions or present & set(record.extensions))
269 ]
270 if not records:270 ↛ 271line 270 didn't jump to line 271 because the condition on line 270 was never true
271 return ""
272 held = ", ".join(sorted(present)) or "none"
273 prog = footman.prog()
274 lines = ["# The gate's steps", ""]
275 if audience == HUMAN:
276 lines += [
277 f"`{prog} check` runs every step below, each registered by an"
278 f" extension; the members hold the extensions {held}.",
279 "",
280 "| step | tools | packages | rewrites under `--fix` |",
281 "| --- | --- | --- | --- |",
282 ]
283 for record in records:
284 tools = ", ".join(record.tools) or "none"
285 scope = " or ".join(record.extensions) or "every"
286 fix = "yes" if record.fix is not None else "no"
287 lines.append(f"| {record.name} | {tools} | {scope} | {fix} |")
288 else:
289 lines += [
290 f"`{prog} check` runs these steps in parallel, the rewriters first"
291 f" and one at a time under `--fix`; the members hold the"
292 f" extensions {held}.",
293 "",
294 ]
295 for record in records:
296 # The name carries the tool; the store's tools are named
297 # only where they are more than it.
298 tools = (
299 f" ({', '.join(record.tools)})"
300 if record.tools and record.tools != (record.step,)
301 else ""
302 )
303 where = "the workspace"
304 if record.extensions:
305 where = f"{' or '.join(record.extensions)} packages"
306 fix = "; rewrites under --fix" if record.fix is not None else ""
307 lines.append(f"- {record.name}{tools}: judges {where}{fix}")
308 return "\n".join(lines) + "\n"
309
310
311#: The trees this process listed, by root and the stamps of the tasks
312#: file and the contract: a listing is a runner process, and a sync
313#: renders the verbs fragment for two readers on each of its passes.
314_TREES: dict[tuple[Any, ...], dict[str, Any] | None] = {}
315
316
317def _tree_key(root: Path) -> tuple[Any, ...]:
318 from livery.workshop._contract import _stamp
319
320 return (str(root), _stamp(root / "tasks.py"), _stamp(root / "workshop.toml"))
321
322
323def forget_trees() -> None:
324 """Drop every tree this process listed, so the next read lists again."""
325 _TREES.clear()
326
327
328def _own_root() -> Path | None:
329 """This process's own project root, the one tree it holds already."""
330 return footman.project_root()
331
332
333def composed_tree(root: Path) -> dict[str, Any] | None:
334 """The workspace's composed task tree, as ``--json --list`` reports it.
335
336 This process's own workspace answers from the tree it discovered
337 ([livery.footman.task_tree][]). Another root, a newborn a birth syncs
338 from its parent's task, is listed by running the runner there: its
339 tree lives in its own venv's entry points, which only a process in
340 that venv can list. None without a tasks file at the root, without
341 the runner on PATH, and when the listing fails: the fragment is then
342 left out rather than guessed. Listed once per process; a later read
343 answers from the first until the tasks file or the contract changes.
344 """
345 if not (root / "tasks.py").is_file():
346 return None
347 key = _tree_key(root)
348 if key in _TREES:
349 return _TREES[key]
350 own = _own_root()
351 if own is not None and own.resolve() == root.resolve():
352 tree = footman.task_tree()
353 _TREES[key] = tree
354 return tree
355 runner = shutil.which(footman.prog())
356 if runner is None:356 ↛ 357line 356 didn't jump to line 357 because the condition on line 356 was never true
357 return None
358 result = footman.run(
359 [runner, "--json", "--list"], cwd=root, nofail=True, recorded=False
360 )
361 if int(result) != 0:361 ↛ 362line 361 didn't jump to line 362 because the condition on line 361 was never true
362 return None
363 tree = cast("dict[str, Any]", json.loads(result.stdout)["tree"])
364 _TREES[key] = tree
365 return tree
366
367
368def render_verbs(root: Path, audience: str | None) -> str:
369 """The verbs by provider, then what each extension of the installed set provides.
370
371 The composed tree's verbs open it: the base's, those of each plugin
372 no extension of the set carries, and the repository's own last.
373 Then each extension of the installed set, in composition order, has
374 a block, read from its declaration: what it does, its verbs, its
375 templates, its contract keys and step options, the steps it
376 declares off, and the extensions it cooperates with. Without a
377 tree, as a workspace without a tasks file has, the blocks stand
378 alone; with neither a verb nor an extension, the fragment is left
379 out.
380 """
381 from livery.workshop._capabilities import blocks, render_block, verbs_by_provider
382 from livery.workshop._extensions import stack_names
383
384 tree = composed_tree(root)
385 found, by_extension = blocks(root, verbs_by_provider(tree) if tree else {})
386 if not found and not by_extension:
387 return ""
388 mounted = [
389 extension for extension in stack_names(root) if extension in by_extension
390 ]
391 others = sorted(
392 extension
393 for extension in by_extension
394 if extension not in mounted and extension != REPOSITORY
395 )
396 ordered = [*mounted, *others, *([REPOSITORY] if REPOSITORY in by_extension else [])]
397 prog = footman.prog()
398 lines = ["# The verbs by extension", ""]
399 if ordered:
400 if audience == HUMAN:
401 lines.append(
402 f"`{prog}` composes these verbs from the base, the plugins the"
403 " project mounts and the repository's own tasks file, and an"
404 f" extension's verbs are in its section below; `{prog} <verb>"
405 " --help` describes one."
406 )
407 else:
408 lines.append(
409 f"Every job goes through `{prog}`; these are its verbs, by what"
410 " provides them: the base, each plugin the project mounts, and"
411 " the repository's own tasks file. An extension's verbs are in"
412 " its block below. Verbs hidden from `--help`, which CI and other"
413 f" verbs call, are not listed; `{prog} --all --help` shows them:"
414 )
415 lines.append("")
416 for extension in ordered:
417 verbs = sorted(verb.address for verb in by_extension[extension])
418 lines.append(f"- {extension or 'this repository'}: {', '.join(verbs)}")
419 lines.append("")
420 if found:
421 lines += [
422 "Each extension the workspace installs, listed or required by one"
423 " listed, has a block below: what it does, its verbs, its templates,"
424 " the contract keys and step options it reads, and the installed"
425 " extensions it contributes to. A package turns any step off with"
426 " `enabled = false` in its `[phases.<phase>.<step>]` table.",
427 "",
428 ]
429 for block in found:
430 lines += render_block(block, audience)
431 return "\n".join(lines).rstrip("\n") + "\n"
432
433
434def render_compositions(root: Path, audience: str | None) -> str:
435 """The sets of extensions the present packages hold, each with its packages.
436
437 A set is named by the shortest list that composes it, the extensions
438 joined with ``+``, and is listed with every extension it holds and
439 the gate phases that judge a package holding it. A package holding
440 no extension is listed under ``none``.
441 """
442 from livery.workshop._composition import extension_set, implied
443 from livery.workshop._extensions import installed_declaration
444 from livery.workshop._packages import discover_packages
445 from livery.workshop._phases import declared_phases
446 from livery.workshop._steps import judges_extensions, steps_by_name
447
448 gated = {name for name, spec in declared_phases().items() if spec.gated}
449 members: dict[tuple[str, ...], list[str]] = {}
450 for package in discover_packages(root):
451 held = extension_set(package)
452 members.setdefault(held, []).append(package.path)
453 if not members:
454 return ""
455 lines = ["# The compositions present", ""]
456 if audience == HUMAN:
457 lines += [
458 "| composition | extensions | packages | gate phases |",
459 "| --- | --- | --- | --- |",
460 ]
461 else:
462 lines += [
463 "The sets of extensions the packages hold, each named by the shortest"
464 " list that composes it, with its packages and the gate phases that"
465 " judge them:",
466 "",
467 ]
468 named: dict[tuple[str, ...], str] = {}
469 for held in members:
470 required = implied(held, installed_declaration)
471 # The shortest list leaves out what another member requires; a
472 # cycle among the requires leaves nothing out of the whole set.
473 shortest = [name for name in held if name not in required] or held
474 named[held] = "+".join(shortest) or "none"
475 for held in sorted(members, key=named.__getitem__):
476 extensions = ", ".join(held) or "none"
477 paths = ", ".join(sorted(members[held]))
478 # A set's phases are those of the gate's steps that judge a
479 # package holding it; a step naming no extensions judges the
480 # workspace, never one set, and a step of a phase the gate never
481 # runs, the docs phase's, is no gate's.
482 phases = (
483 ", ".join(
484 sorted(
485 {
486 r.phase
487 for r in steps_by_name().values()
488 if r.phase in gated
489 and r.extensions
490 and judges_extensions(r, held)
491 }
492 )
493 )
494 or "none"
495 )
496 if audience == HUMAN:
497 lines.append(f"| {named[held]} | {extensions} | {paths} | {phases} |")
498 else:
499 lines.append(
500 f"- {named[held]} ({paths}): holds {extensions}; gate phases {phases}"
501 )
502 return "\n".join(lines) + "\n"
503
504
505def render_tools(root: Path, audience: str | None) -> str:
506 """The tools the lock pins, each with its version and the sites requiring it."""
507 from livery.workshop._tools import current_lock, requirements
508
509 lock = current_lock(root)
510 if lock is None or not lock.tools:
511 return ""
512 sites: dict[str, set[str]] = {}
513 for requirement in requirements(root):
514 sites.setdefault(requirement.name, set()).add(requirement.site)
515 prog = footman.prog()
516 hosts = ", ".join(lock.hosts)
517 lines = ["# The locked tools", ""]
518 if audience == HUMAN:
519 lines.append(
520 f"`toolroom.lock` pins these for {hosts}; `{prog} toolroom.sync` installs"
521 f" them into the tool store, and `{prog} sync` runs it."
522 )
523 else:
524 lines.append(
525 f"The tool store holds these versions, pinned by `toolroom.lock` for"
526 f" {hosts}; `{prog} sync` installs them, never a hand install"
527 f" (only `uv` may come from the host to bootstrap before `{prog}`"
528 f" exists; the entered environment uses the pinned version):"
529 )
530 lines.append("")
531 for name in sorted(lock.tools):
532 where = ", ".join(sorted(sites.get(name, ())))
533 scope = ", ".join(lock.tools[name].on)
534 lines.append(
535 f"- {name} {lock.tools[name].version}"
536 + (f": {where}" if where else "")
537 + (f" ({scope} only)" if scope else "")
538 )
539 return "\n".join(lines) + "\n"
540
541
542#: The base's rendered fragments by delivered name: what the registries
543#: say, never written by hand.
544_RENDERED: dict[str, Prose] = {
545 prose.name: prose
546 for prose in (
547 Prose("gate", "checks", render=render_gate),
548 Prose("verbs", "extensions", render=render_verbs),
549 Prose("compositions", "present", render=render_compositions),
550 Prose("tools", "locked", render=render_tools),
551 )
552}