Coverage for packages/workshop/src/livery/workshop/_provenance.py: 84%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_without_docs.py, packages/workshop/tests/test_workshop_walk.py, packages/workshop/tests/test_workshop_vocabulary.py, packages/workshop/tests/test_workshop_update.py, packages/workshop/tests/test_workshop_templates.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_submit.py, packages/workshop/tests/test_workshop_steps.py, packages/workshop/tests/test_workshop_shipped_files.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_security.py, packages/workshop/tests/test_workshop_schema.py, packages/workshop/tests/test_workshop_render.py, packages/workshop/tests/test_workshop_release_render.py, packages/workshop/tests/test_workshop_regions.py, packages/workshop/tests/test_workshop_queries.py, packages/workshop/tests/test_workshop_quality.py, packages/workshop/tests/test_workshop_pythons.py, packages/workshop/tests/test_workshop_provenance.py, packages/workshop/tests/test_workshop_proved_parts.py, packages/workshop/tests/test_workshop_proved_decide.py, packages/workshop/tests/test_workshop_proved.py, packages/workshop/tests/test_workshop_prose.py, packages/workshop/tests/test_workshop_proof_pins.py, packages/workshop/tests/test_workshop_points_contributed.py, packages/workshop/tests/test_workshop_points.py, packages/workshop/tests/test_workshop_phase_verbs.py, packages/workshop/tests/test_workshop_package_templates.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_inputs_pins.py, packages/workshop/tests/test_workshop_influence.py, packages/workshop/tests/test_workshop_governance.py, packages/workshop/tests/test_workshop_env.py, packages/workshop/tests/test_workshop_entry.py, packages/workshop/tests/test_workshop_dispatch.py, packages/workshop/tests/test_workshop_currency.py, packages/workshop/tests/test_workshop_conformance.py, packages/workshop/tests/test_workshop_categories.py, packages/workshop/tests/test_workshop_c7_shards.py, packages/extensions/ruff/tests/test_ruff.py, packages/extensions/python/tests/test_runner_terminal.py, packages/extensions/python/tests/test_private_reaches.py, packages/extensions/python/tests/test_extensions_python.py, packages/extensions/python/tests/test_declared_imports.py, packages/extensions/pytest/tests/test_pytest.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings.py, packages/extensions/lfs/tests/test_lfs.py, packages/extensions/docs/tests/test_task_links.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.py, packages/extensions/cpp/tests/test_extensions_cpp.py, packages/extensions/coverage/tests/test_extensions_coverage.py, packages/extensions/coverage/tests/test_coverage_proved_parts.py, packages/extensions/conan/tests/test_extensions_conan.py, packages/extensions/cmake/tests/test_cmake.py ran.

1"""Provenance: which channel owns a file, and where to edit it.
2
3One classifier answers for any path; everything else serialises its
4answer. ``fm explain <path>`` prints it. The fragment engine and the
5emitters open every file they write with a header, so the answer rides
6the file wherever comments are possible. Materialised copies are never injected:
7override detection depends on the copy staying byte-identical to
8its source, so those files, and comment-hostile ones, are explain's
9territory alone. Shipped extension content carries its header through
10the provenance lint, whose ``--fix`` writes the computed text.
11"""
12
13from __future__ import annotations
14
15import os
16from collections.abc import Container, Generator, Iterable
17from contextlib import contextmanager
18from contextvars import ContextVar
19from dataclasses import dataclass
20from pathlib import Path
21from typing import Annotated
22
23import livery.footman as footman
24from livery import git
25from livery.footman import Arg, ask, doc, fail, suggest, task
26from livery.workshop._categories import (
27 ChannelRule,
28 Provenance,
29 category_of,
30 channel_of,
31 register_channels,
32)
33from livery.workshop._extensions import SELF, workspace_root
34from livery.workshop._packages import Package
35
36#: Comment leaders by suffix, and by exact name for suffixless files.
37#: A type absent from both tables cannot carry a header and is
38#: explain's territory alone.
39_BY_SUFFIX = {
40 ".py": "#",
41 ".toml": "#",
42 ".yml": "#",
43 ".yaml": "#",
44 ".sh": "#",
45 ".cfg": "#",
46 ".ini": "#",
47 ".md": "html",
48}
49_BY_NAME = {".gitignore": "#", ".gitattributes": "#", "CODEOWNERS": "#"}
50
51
52def comment_style(path: Path) -> str:
53 """The comment leader for *path*: ``#``, ``//``, ``html``, or empty.
54
55 The editor's ``.vscode/settings.json`` is JSON with comments, the
56 one JSON the render owns; every other JSON carries no header.
57 """
58 if path.name == "settings.json" and path.parent.name == ".vscode":
59 return "//"
60 return _BY_NAME.get(path.name, _BY_SUFFIX.get(path.suffix, ""))
61
62
63#: Phrases that mark a header as machine-written, for refresh.
64_MARKERS = (
65 "the workshop from workshop.toml",
66 "Seeded from",
67 "extension content",
68)
69
70
71def format_header(lines: tuple[str, ...], style: str) -> str:
72 """The header *lines* as one comment block in *style*."""
73 if style == "html":
74 body = "".join(f" {line}\n" for line in lines[1:])
75 return f"<!-- {lines[0]}\n{body}-->\n"
76 return "".join(f"{style} {line}\n" for line in lines)
77
78
79def generated_header(style: str, lines: tuple[str, ...] = ()) -> str:
80 """The provenance header a generated file opens with, as a comment block.
81
82 *style* is the file's comment marker (``#`` or ``//``), or ``html``
83 for a ``<!-- -->`` block. *lines* say what writes the file and how
84 a reader changes it, for a file an extension writes outside the
85 engine; without them, the header says what every artifact the
86 engine emits says: the contract is the source, and an edit here is
87 drift.
88 """
89 if not lines:
90 prog = footman.prog()
91 lines = (
92 "Generated by the workshop from workshop.toml; the gate keeps",
93 "it matching. Edit the contract (or the emitters) and run",
94 f"`{prog} sync`; an edit here is drift.",
95 )
96 return format_header(lines, style)
97
98
99def content_header(extension: str, style: str) -> str:
100 """The header shipped extension content carries, lint-enforced."""
101 lines = (
102 f"Shipped as {extension} extension content, delivered to the workspace",
103 "by the sync verb. Edit this copy in the extension and release it;",
104 "an edited delivered copy is a local override, kept and named.",
105 )
106 return format_header(lines, style)
107
108
109def _insertion_point(text: str, path: Path) -> int:
110 """Where a header lands: after a shebang or markdown frontmatter."""
111 if text.startswith("#!"):
112 return text.find("\n") + 1
113 if path.suffix == ".md" and text.startswith("---\n"):
114 end = text.find("\n---\n", 4)
115 if end != -1:115 ↛ 117line 115 didn't jump to line 117 because the condition on line 115 was always true
116 return end + len("\n---\n")
117 return 0
118
119
120def inject(path: Path, header: str) -> None:
121 """Open *path* with *header*, replacing a stale machine header."""
122 text = path.read_text(encoding="utf-8")
123 text = strip_header(text, path, size=len(header.splitlines()))
124 at = _insertion_point(text, path)
125 path.write_text(text[:at] + header + text[at:], encoding="utf-8", newline="\n")
126
127
128def has_header(path: Path, header: str) -> bool:
129 """Whether *path* already opens with *header* (shebang-tolerant)."""
130 text = path.read_text(encoding="utf-8")
131 at = _insertion_point(text, path)
132 return text[at:].startswith(header)
133
134
135def strip_header(text: str, path: Path, *, size: int = 3) -> str:
136 """*text* with a machine-written header removed, everything after it kept.
137
138 An HTML header is its ``<!-- -->`` block. A line-comment header is
139 its first *size* lines, the length every machine header is written
140 at, when the first carries a marker: the comment lines below it are
141 the file's own and stay, and so does a blank line after either.
142 """
143 at = _insertion_point(text, path)
144 head, tail = text[:at], text[at:]
145 style = comment_style(path)
146 if style == "html":
147 if tail.startswith("<!--") and "-->" in tail:
148 block, _, rest = tail.partition("-->\n")
149 if any(marker in block for marker in _MARKERS):149 ↛ 151line 149 didn't jump to line 151 because the condition on line 149 was always true
150 return head + rest
151 return text
152 lines = tail.splitlines(keepends=True)
153 first = lines[:size]
154 leader = style or "#"
155 if (
156 len(first) == size
157 and all(line.startswith(leader) for line in first)
158 and any(marker in first[0] for marker in _MARKERS)
159 ):
160 return head + "".join(lines[size:])
161 return text
162
163
164def _materialised(root: Path, relative: Path) -> Provenance | None:
165 """The answer for a path under ``.workshop/``, this checkout's state, or None."""
166 del root
167 prog = footman.prog()
168 parts = relative.parts
169 if parts[0] == ".workshop":
170 if parts[1:2] == ("graphs",):
171 return None
172 if parts[1:2] == ("fragments",):
173 return Provenance(
174 "extension fragment",
175 f"a mounted extension's content/fragments/{relative.name}, or a"
176 " render from its registries",
177 f"edit the extension's copy; an edit here is a local override"
178 f" `{prog} sync` keeps and names",
179 )
180 # Everything else under .workshop is this checkout's own: the
181 # tool receipts, the stub receipt, the linked binaries. None of
182 # them has an edit path, and
183 # calling them extension fragments was a lie the directory's older
184 # shape made easy to tell.
185 return Provenance(
186 "checkout state",
187 f"written by `{prog} sync` for this checkout alone",
188 "nothing to edit here; delete it and the next sync writes it again",
189 )
190 return None
191
192
193@dataclass(frozen=True)
194class _WorkspaceScan:
195 """Precomputed workspace provenance lookups shared across a batch of paths."""
196
197 root: Path
198 comp_frags: tuple[tuple[str, str, bool], ...]
199 receipts: frozenset[str]
200 target_owners: dict[str, tuple[str, ...]]
201 pkg_rendered: frozenset[str]
202 group_cache: dict[str, bool]
203
204
205_SCAN_CACHE: ContextVar[_WorkspaceScan | None] = ContextVar(
206 "_provenance_scan_cache", default=None
207)
208
209
210def _scan_workspace(root: Path) -> _WorkspaceScan:
211 """Compute the workspace-wide lookups `classify` reads, once for a batch."""
212 from livery.workshop._extensions import declaration
213 from livery.workshop._fragment_engine import local_receipts
214 from livery.workshop._fragments import package_files
215 from livery.workshop._shipped_files import delivery_order, shipped
216
217 has_contract = (root / "workshop.toml").is_file()
218 order = delivery_order(root) if has_contract else ()
219 comp_frags = tuple(
220 (extension, fragment.target, fragment.local)
221 for extension in order
222 if extension != SELF and (decl := declaration(extension)) is not None
223 for fragment in decl.fragments
224 )
225 fragments, _ = shipped(root) if has_contract else ((), ())
226 by_target: dict[str, list[str]] = {}
227 for fragment in fragments:
228 by_target.setdefault(fragment.target, []).append(fragment.owner)
229 target_owners = {
230 target: tuple(dict.fromkeys(owners)) for target, owners in by_target.items()
231 }
232 return _WorkspaceScan(
233 root=root,
234 comp_frags=comp_frags,
235 receipts=frozenset(local_receipts(root)),
236 target_owners=target_owners,
237 pkg_rendered=frozenset(package_files()),
238 group_cache={},
239 )
240
241
242def _cached_member_depth(
243 root: Path, relative: Path, scan: _WorkspaceScan | None
244) -> int:
245 """`member_depth` using *scan*'s per-group cache when inside a batch."""
246 from livery.workshop._packages import PACKAGES_DIR, is_group, member_depth
247
248 if scan is None or scan.root != root:
249 return member_depth(root, relative)
250 parts = relative.parts
251 if len(parts) <= 2 or parts[0] != PACKAGES_DIR:
252 return 0
253 first = parts[1]
254 grouped = scan.group_cache.get(first)
255 if grouped is None:
256 group = root / PACKAGES_DIR / first
257 grouped = group.is_dir() and is_group(group)
258 scan.group_cache[first] = grouped
259 if grouped:
260 return 3 if len(parts) > 3 else 0
261 return 2
262
263
264@contextmanager
265def _workspace_scan_cache(root: Path) -> Generator[_WorkspaceScan]:
266 """Reuse one workspace scan across every `classify` call in this block."""
267 current = _SCAN_CACHE.get()
268 if current is not None and current.root == root:268 ↛ 269line 268 didn't jump to line 269 because the condition on line 268 was never true
269 yield current
270 return
271 scan = _scan_workspace(root)
272 token = _SCAN_CACHE.set(scan)
273 try:
274 yield scan
275 finally:
276 _SCAN_CACHE.reset(token)
277
278
279def _computed(root: Path, relative: Path) -> Provenance | None:
280 """The answer for a file a listed extension's code writes, or None.
281
282 A path under a directory such a render writes, which the render did
283 not write, is the repository's own: the agent's own skill beside the
284 delivered ones, say.
285 """
286 prog = footman.prog()
287 path = relative.as_posix()
288 scan = _SCAN_CACHE.get()
289 if scan is not None and scan.root == root:
290 entries = scan.comp_frags
291 cached_receipts: frozenset[str] | None = scan.receipts
292 else:
293 from livery.workshop._extensions import declaration
294 from livery.workshop._shipped_files import delivery_order
295
296 entries = tuple(
297 (extension, fragment.target, fragment.local)
298 for extension in delivery_order(root)
299 if extension != SELF and (decl := declaration(extension)) is not None
300 for fragment in decl.fragments
301 )
302 cached_receipts = None
303 for extension, target, is_local in entries:
304 if path != target and not (target.endswith("/") and path.startswith(target)):
305 continue
306 where = f"`{prog} sync`, from {extension}'s [fragments] render for {target}"
307 if not is_local:307 ↛ 316line 307 didn't jump to line 316 because the condition on line 307 was always true
308 return Provenance(
309 "computed",
310 where,
311 f"change what it is computed from and run `{prog} sync`;"
312 " an edit here is drift",
313 )
314 # A linked directory's files are the link's: the receipt
315 # names the link, the nearest written ancestor.
316 if cached_receipts is None:
317 from livery.workshop._fragment_engine import local_receipts
318
319 receipts: Container[str] = local_receipts(root)
320 else:
321 receipts = cached_receipts
322 ancestors = [path, *(parent.as_posix() for parent in relative.parents)]
323 if any(candidate in receipts for candidate in ancestors):
324 return Provenance(
325 "materialised",
326 where,
327 "edit what it is computed from; an edit here is a local"
328 f" override `{prog} sync` keeps and names",
329 )
330 return Provenance(
331 "yours",
332 "this repository",
333 "edit directly; it commits like any repo file",
334 )
335 return None
336
337
338def emitted_paths(root: Path) -> frozenset[str]:
339 """The paths the workshop emitters write for *root*, the owners file included.
340
341 One emission is a full render of every workflow, the site
342 configuration, and the entry script; a caller classifying many
343 paths computes this once and hands it to
344 [livery.workshop._provenance.classify][].
345 """
346 from livery.workshop._ci_generate import generate
347 from livery.workshop._governance import codeowners_file
348
349 generated = set(generate(root))
350 owners = codeowners_file(root)
351 if owners is not None:
352 generated.add(owners.path)
353 return frozenset(generated)
354
355
356def classify(
357 root: Path, relative: Path, *, emitted: frozenset[str] | None = None
358) -> Provenance:
359 """The provenance of *relative* inside *root*; "yours" when no channel claims it.
360
361 *relative* is taken lexically, never resolved: a materialised
362 link classifies as the delivered entry it is, not as the wheel
363 path it points into. *emitted* is the emitters' path set from
364 [livery.workshop._provenance.emitted_paths][]; a caller with many
365 paths passes one set rather than paying an emission per path.
366 The answer comes from the channel registry, the builtin ladder
367 below and whatever an extension registered beside it, highest rank
368 first.
369 """
370 found = channel_of(root, relative, emitted=emitted)
371 if found is not None:
372 return found.provenance
373 return Provenance("yours", "this repository", "edit directly")
374
375
376def _rule_materialised(
377 root: Path, relative: Path, emitted: frozenset[str] | None
378) -> Provenance | None:
379 del emitted
380 return _materialised(root, relative)
381
382
383def _rule_computed(
384 root: Path, relative: Path, emitted: frozenset[str] | None
385) -> Provenance | None:
386 del emitted
387 return _computed(root, relative)
388
389
390def _rule_generated(
391 root: Path, relative: Path, emitted: frozenset[str] | None
392) -> Provenance | None:
393 prog = footman.prog()
394 generated = emitted_paths(root) if emitted is None else emitted
395 if relative.as_posix() not in generated:
396 return None
397 return Provenance(
398 "generated",
399 "the workshop emitters, from workshop.toml",
400 f"edit workshop.toml (or the emitters) and run `{prog} sync`",
401 )
402
403
404def classify_many(
405 root: Path,
406 paths: Iterable[Path],
407 *,
408 emitted: frozenset[str] | None = None,
409) -> dict[Path, Provenance]:
410 """Classify every path in *paths*, scanning workspace provenance data once.
411
412 Equivalent to calling `classify` for each path through the full channel
413 ladder, without re-reading extension declarations, shipped fragments, or
414 local receipts on every iteration.
415 """
416 items = tuple(paths)
417 if not items:417 ↛ 418line 417 didn't jump to line 418 because the condition on line 417 was never true
418 return {}
419 resolved_emitted = emitted_paths(root) if emitted is None else emitted
420 with _workspace_scan_cache(root):
421 return {path: classify(root, path, emitted=resolved_emitted) for path in items}
422
423
424def _rule_composed(
425 root: Path, relative: Path, emitted: frozenset[str] | None
426) -> Provenance | None:
427 del emitted
428 from livery.workshop._fragment_engine import PACKAGE_PREFIX
429
430 scan = _SCAN_CACHE.get()
431 depth = _cached_member_depth(root, relative, scan)
432 posix = relative.as_posix()
433 inner = PACKAGE_PREFIX + Path(*relative.parts[depth:]).as_posix() if depth else ""
434 if scan is not None and scan.root == root:
435 owners_list: list[str] = list(scan.target_owners.get(posix, ()))
436 if inner and inner != posix:
437 owners_list.extend(scan.target_owners.get(inner, ()))
438 owners = tuple(dict.fromkeys(owners_list))
439 else:
440 from livery.workshop._shipped_files import shipped
441
442 fragments, _order = shipped(root)
443 owners = tuple(
444 dict.fromkeys(
445 fragment.owner
446 for fragment in fragments
447 if fragment.target in (posix, inner)
448 )
449 )
450 if not owners:
451 return None
452 prog = footman.prog()
453 return Provenance(
454 "composed",
455 f"the fragment engine, from {', '.join(owners)}",
456 f"edit inside its regions, or the extension's lines, and run `{prog} sync`",
457 )
458
459
460def _rule_seed(
461 root: Path, relative: Path, emitted: frozenset[str] | None
462) -> Provenance | None:
463 del emitted
464 del root
465 from livery.workshop._seeds import PROJECT_SEEDS
466
467 if relative.as_posix() not in PROJECT_SEEDS:
468 return None
469 return Provenance(
470 "seed",
471 "written at birth from the extensions' seeds",
472 "yours: edit directly; nothing rewrites it",
473 )
474
475
476def _rule_receipts(
477 root: Path, relative: Path, emitted: frozenset[str] | None
478) -> Provenance | None:
479 del root, emitted
480 if relative.as_posix() != ".workshop-rendered":
481 return None
482 prog = footman.prog()
483 return Provenance(
484 "receipts",
485 "what the fragment engine last wrote into the workspace's files",
486 f"never by hand; `{prog} sync` keeps it",
487 )
488
489
490def _rule_contract(
491 root: Path, relative: Path, emitted: frozenset[str] | None
492) -> Provenance | None:
493 del root, emitted
494 if relative.name != "workshop.toml":
495 return None
496 return Provenance(
497 "contract",
498 "the workspace contract, config-as-code",
499 "edit directly and merge; governance applies itself on main",
500 )
501
502
503def _rule_environment(
504 root: Path, relative: Path, emitted: frozenset[str] | None
505) -> Provenance | None:
506 del root, emitted
507 if relative.as_posix() != ".repo.env":507 ↛ 509line 507 didn't jump to line 509 because the condition on line 507 was always true
508 return None
509 prog = footman.prog()
510 return Provenance(
511 "environment",
512 "the committed rung of the env cascade",
513 f"`{prog} env.set KEY --scope=repo`, or edit directly",
514 )
515
516
517def _rule_toolchain(
518 root: Path, relative: Path, emitted: frozenset[str] | None
519) -> Provenance | None:
520 del root, emitted
521 posix = relative.as_posix()
522 if posix == "uv.lock":
523 return Provenance(
524 "toolchain",
525 "uv's lockfile",
526 "`uv lock` (or the update wave); never by hand",
527 )
528 if posix == "toolroom.lock" or posix.startswith(".workshop/graphs/"):
529 prog = footman.prog()
530 what = (
531 "toolroom's lockfile"
532 if posix == "toolroom.lock"
533 else "resolved tool dependency graph"
534 )
535 return Provenance(
536 "toolchain",
537 what,
538 f"`{prog} toolroom.lock` (or `toolroom.refresh`); never by hand",
539 )
540 return None
541
542
543def _rule_member(
544 root: Path, relative: Path, emitted: frozenset[str] | None
545) -> Provenance | None:
546 """A package's own files: its changelog config, its receipts, its content."""
547 del emitted
548 scan = _SCAN_CACHE.get()
549 depth = _cached_member_depth(root, relative, scan)
550 if not depth:
551 return None
552 prog = footman.prog()
553 member = Path(*relative.parts[:depth])
554 rest = Path(*relative.parts[depth:]).as_posix()
555 if rest == ".workshop-rendered":
556 return Provenance(
557 "receipts",
558 "what the render wrote into this package for the steps' files",
559 f"never by hand; `{prog} sync` keeps it",
560 )
561 if scan is not None and scan.root == root:
562 rendered: Container[str] = scan.pkg_rendered
563 else:
564 from livery.workshop._fragments import package_files
565
566 rendered = package_files()
567 if rest in rendered:567 ↛ 568line 567 didn't jump to line 568 because the condition on line 567 was never true
568 return Provenance(
569 "rendered",
570 "a step record's fragment for this package's kind",
571 f"edit the record's fragment and run `{prog} sync`; a"
572 " deeper file with InheritParentConfig carries this package's own lines",
573 )
574 if "/content/" in rest:
575 return Provenance(
576 "extension-content",
577 f"{member.as_posix()}: what this extension ships; the"
578 " provenance lint keeps its header",
579 f"edit directly here; `{prog} sync` delivers it",
580 )
581 return Provenance(
582 "yours",
583 f"{member.as_posix()}: the package's own file since its birth",
584 "edit directly",
585 )
586
587
588# The builtin ladder as ranked rules: an extension registers its own beside
589# them, at the rank that says where it stands.
590register_channels(
591 [
592 ChannelRule("materialised", _rule_materialised, 100, "livery.workshop"),
593 ChannelRule("computed", _rule_computed, 95, "livery.workshop"),
594 ChannelRule("generated", _rule_generated, 90, "livery.workshop"),
595 ChannelRule("composed", _rule_composed, 85, "livery.workshop"),
596 ChannelRule("seed", _rule_seed, 70, "livery.workshop"),
597 ChannelRule("receipts", _rule_receipts, 60, "livery.workshop"),
598 ChannelRule("contract", _rule_contract, 50, "livery.workshop"),
599 ChannelRule("environment", _rule_environment, 40, "livery.workshop"),
600 ChannelRule("toolchain", _rule_toolchain, 30, "livery.workshop"),
601 ChannelRule("member", _rule_member, 20, "livery.workshop"),
602 ]
603)
604
605
606def _tracked_paths() -> list[str]:
607 """Git-tracked paths, the completion surface for explain."""
608 root = workspace_root()
609 if root is None:
610 return []
611 try:
612 return git.ls_files(root)
613 except git.GitError:
614 return []
615
616
617@task
618def explain(
619 path: Annotated[
620 Arg[str],
621 ask(),
622 suggest(_tracked_paths, strict=False),
623 doc("the file to explain, relative to the workspace root, or a step's name"),
624 ] = "",
625) -> None:
626 """Name a file's owning channel, its source and its edit path; or what a step runs.
627
628 Every answer for a file has the same three lines; a file no channel
629 claims is yours, which is the honest default, not an error. A
630 step's name, ``typecheck.mypy``, prints the command the step runs
631 and what the engine appends to it.
632 """
633 if not path:
634 fail(f"name a file: `{footman.prog()} explain pyproject.toml`")
635 root = workspace_root()
636 if root is None:
637 fail("no workspace: no workshop.toml above the working directory")
638 from livery.workshop._steps import steps_by_name
639
640 record = steps_by_name().get(path)
641 if record is not None:
642 from livery.workshop._words import explained
643
644 for line in explained(record):
645 print(line)
646 return
647 raw = Path(path)
648 if raw.is_absolute():
649 try:
650 raw = raw.relative_to(root)
651 except ValueError:
652 fail(f"{path} is outside this workspace")
653 relative = Path(os.path.normpath(str(raw)))
654 if not relative.parts or relative.parts[0] == "..":
655 fail(f"{path} is outside this workspace")
656 for line in describe(root, relative):
657 print(line)
658
659
660def classify_channels(root: Path, paths: tuple[str, ...]) -> dict[str, str]:
661 """Classify the channel of every path in *paths*, caching shared scans once.
662
663 Equivalent to calling `classify` for each path, without repeating the
664 workspace's emitted, shipped-fragment, computed-fragment and rendered
665 lookups per path. Any extension-registered channel rule beyond the base
666 ladder is still consulted through `channel_of`.
667 """
668 from livery.workshop._categories import channel_rules
669 from livery.workshop._extensions import declaration
670 from livery.workshop._fragment_engine import PACKAGE_PREFIX, local_receipts
671 from livery.workshop._fragments import package_files as rendered_package_files
672 from livery.workshop._packages import member_depth
673 from livery.workshop._seeds import PROJECT_SEEDS
674 from livery.workshop._shipped_files import delivery_order, shipped
675
676 if not paths:676 ↛ 677line 676 didn't jump to line 677 because the condition on line 676 was never true
677 return {}
678 has_contract = (root / "workshop.toml").is_file()
679 emitted = emitted_paths(root) if has_contract else frozenset()
680 if any(rule.extension != "livery.workshop" for rule in channel_rules()):680 ↛ 681line 680 didn't jump to line 681 because the condition on line 680 was never true
681 with _workspace_scan_cache(root):
682 return {
683 path: classify(root, Path(path), emitted=emitted).channel
684 for path in paths
685 }
686 fragments, _ = shipped(root) if has_contract else ((), ())
687 frag_targets = frozenset(fragment.target for fragment in fragments)
688 order = delivery_order(root) if has_contract else ()
689 comp_frags = tuple(
690 fragment
691 for extension in order
692 if extension != SELF and (decl := declaration(extension)) is not None
693 for fragment in decl.fragments
694 )
695 receipts = local_receipts(root)
696 pkg_rendered = rendered_package_files()
697 result: dict[str, str] = {}
698 for path in paths:
699 relative = Path(path)
700 parts = relative.parts
701 if parts and parts[0] == ".workshop":
702 if parts[1:2] == ("graphs",):
703 result[path] = "toolchain"
704 continue
705 result[path] = (
706 "extension fragment"
707 if parts[1:2] == ("fragments",)
708 else "checkout state"
709 )
710 continue
711 matched_computed: str | None = None
712 for fragment in comp_frags:
713 target = fragment.target
714 if path == target or (target.endswith("/") and path.startswith(target)):714 ↛ 715line 714 didn't jump to line 715 because the condition on line 714 was never true
715 if not fragment.local:
716 matched_computed = "computed"
717 else:
718 ancestors = [
719 path,
720 *(parent.as_posix() for parent in relative.parents),
721 ]
722 matched_computed = (
723 "materialised"
724 if any(candidate in receipts for candidate in ancestors)
725 else "yours"
726 )
727 break
728 if matched_computed is not None:728 ↛ 729line 728 didn't jump to line 729 because the condition on line 728 was never true
729 result[path] = matched_computed
730 continue
731 if path in emitted:
732 result[path] = "generated"
733 continue
734 depth = member_depth(root, relative)
735 inner = PACKAGE_PREFIX + Path(*parts[depth:]).as_posix() if depth else ""
736 if path in frag_targets or (inner and inner in frag_targets):
737 result[path] = "composed"
738 continue
739 if path in PROJECT_SEEDS:
740 result[path] = "seed"
741 continue
742 if path == ".workshop-rendered":
743 result[path] = "receipts"
744 continue
745 if relative.name == "workshop.toml":
746 result[path] = "contract"
747 continue
748 if path == ".repo.env":748 ↛ 749line 748 didn't jump to line 749 because the condition on line 748 was never true
749 result[path] = "environment"
750 continue
751 if path in ("uv.lock", "toolroom.lock"):
752 result[path] = "toolchain"
753 continue
754 if depth:
755 rest = Path(*parts[depth:]).as_posix()
756 if rest == ".workshop-rendered":756 ↛ 757line 756 didn't jump to line 757 because the condition on line 756 was never true
757 result[path] = "receipts"
758 elif rest in pkg_rendered:758 ↛ 759line 758 didn't jump to line 759 because the condition on line 758 was never true
759 result[path] = "rendered"
760 elif "/content/" in rest:
761 result[path] = "extension-content"
762 else:
763 result[path] = "yours"
764 continue
765 result[path] = "yours"
766 return result
767
768
769def describe(root: Path, relative: Path) -> list[str]:
770 """The lines ``fm explain`` prints for *relative*: category, channel, sets, readers.
771
772 A file is claimed by each step that reads it and each CI job whose
773 declared inputs read it, the job as ``<point>/<job>``. A contract
774 also names the schema it is judged by, with the owners whose keys
775 the schema holds.
776 """
777 from livery.workshop._influence import sets_of
778 from livery.workshop._packages import discover_packages
779 from livery.workshop._points import jobs_reading
780
781 packages = discover_packages(root) if (root / "packages").is_dir() else ()
782 posix = relative.as_posix()
783 unit, inside = unit_of(root, packages, posix)
784 lines = [f" {posix}"]
785 if unit is not None:785 ↛ 788line 785 didn't jump to line 788 because the condition on line 785 was always true
786 category = category_of(unit, inside)
787 lines.append(f" category: {category.name} ({category.supplier})")
788 found = channel_of(root, relative)
789 answer = found.provenance if found is not None else classify(root, relative)
790 supplier = found.supplier if found is not None else "livery.workshop"
791 lines.append(f" channel: {answer.channel} ({supplier})")
792 named = sorted(sets_of(root, posix, packages=packages))
793 if named:
794 lines.append(f" sets: {', '.join(named)}")
795 lines.append(f" source: {answer.source}")
796 lines.append(f" edit: {answer.edit}")
797 from livery.workshop._steps import claimants, readers_of
798
799 claims = list(claimants(unit, inside)) if unit is not None else []
800 for step_name in readers_of(root, posix):
801 if step_name not in claims:801 ↛ 800line 801 didn't jump to line 800 because the condition on line 801 was always true
802 claims.append(step_name)
803 claims.sort()
804 claims.extend(jobs_reading(root, posix))
805 if claims:
806 lines.append(f" claimed by: {', '.join(claims)}")
807 from livery.workshop._schema import judged_by
808
809 schema = judged_by(root, relative)
810 if schema:
811 lines.append(f" {schema}")
812 lines.extend(f" {line}" for line in owned_lines(root, relative))
813 return lines
814
815
816def unit_of(
817 root: Path, packages: tuple[Package, ...], path: str
818) -> tuple[Package | None, str]:
819 """The package *path* belongs to and the path inside it, or the root's unit.
820
821 A path under no package is the workspace unit's, relative to the
822 root; None when the root has no unit to speak of.
823 """
824 from livery.workshop._packages import workspace_suite
825
826 for package in packages:
827 if path.startswith(package.path + "/"):
828 return package, path[len(package.path) + 1 :]
829 return workspace_suite(root) or _root_unit(root), path
830
831
832def _root_unit(root: Path) -> Package:
833 """The workspace unit for a root without its own tests directory."""
834 return Package(directory=root, path=".", name="workspace", depends=())
835
836
837def owned_lines(root: Path, relative: Path) -> list[str]:
838 """What a managed file carries that the repository owns, one line each.
839
840 A marked region is named with the lines its markers enclose. A file
841 without one says nothing.
842 """
843 from livery.workshop import _regions
844
845 path = root / relative
846 if not path.is_file():
847 return []
848 text = path.read_text(encoding="utf-8", errors="replace")
849 return [
850 f"region {region.name}: lines {region.first} to {region.last}, yours to"
851 " edit inside the markers; the render keeps it"
852 for region in _regions.regions_in(text)
853 ]
854
855
856def _content_trees(root: Path) -> list[tuple[str, Path]]:
857 """Each workspace package's shipped content tree, with its extension name."""
858 from livery.workshop._packages import package_directories
859
860 trees = []
861 for directory in package_directories(root):
862 src = directory / "src"
863 if not src.is_dir():863 ↛ 864line 863 didn't jump to line 864 because the condition on line 863 was never true
864 continue
865 for content in sorted(src.rglob("content")):
866 if not content.is_dir():866 ↛ 867line 866 didn't jump to line 867 because the condition on line 866 was never true
867 continue
868 if {"templates", "content"} & set(content.relative_to(src).parts[:-1]):868 ↛ 869line 868 didn't jump to line 869 because the condition on line 868 was never true
869 continue # a seed's own content tree, written at a birth
870 extension = ".".join(content.parent.relative_to(src).parts)
871 trees.append((extension, content))
872 return trees
873
874
875def content_lint(
876 root: Path, *, fix: bool = False, files: frozenset[str] | None = None
877) -> list[str]:
878 """Extension content files missing their computed header; ``fix`` writes it.
879
880 *files* keeps the lint to those root-relative files; None lints
881 every content file.
882
883 Only the workspace's own packages are linted: an installed
884 extension's content is its home repository's to keep. Files without
885 a comment syntax are exempt, and so are the fragment engine's
886 templates under `content/root/` and `content/package/`, and under
887 `content/for/<target>/root/` and `content/for/<target>/package/`,
888 whose composed files carry headers of their own, and the seeds under
889 `content/seeds/` and the templates' files under `content/templates/`,
890 which become the workspace's own files.
891 """
892 from livery.workshop._seeds import SEEDS, TEMPLATES
893 from livery.workshop._shipped_files import (
894 FOR_CONTENT,
895 PACKAGE_CONTENT,
896 ROOT_CONTENT,
897 )
898
899 problems = []
900 for extension, content in _content_trees(root):
901 for path in sorted(content.rglob("*")):
902 if not path.is_file() or "__pycache__" in path.parts:
903 continue
904 if files is not None and path.relative_to(root).as_posix() not in files:904 ↛ 905line 904 didn't jump to line 905 because the condition on line 904 was never true
905 continue
906 # A template the fragment engine composes into a workspace file
907 # carries that file's own header; this one would land in it.
908 parts = path.relative_to(content).parts
909 if parts[0] in (ROOT_CONTENT, PACKAGE_CONTENT, SEEDS, TEMPLATES):
910 continue
911 if (
912 parts[0] == FOR_CONTENT
913 and len(parts) > 3
914 and parts[2] in (ROOT_CONTENT, PACKAGE_CONTENT)
915 ):
916 continue
917 style = comment_style(path)
918 if not style:
919 continue
920 header = content_header(extension, style)
921 if has_header(path, header):
922 continue
923 if fix:
924 inject(path, header)
925 problems.append(f"{path.relative_to(root).as_posix()}: header written")
926 else:
927 problems.append(
928 f"{path.relative_to(root).as_posix()}: missing its header"
929 )
930 return problems
931
932
933@task(name="provenance")
934def provenance_check(
935 fix: Annotated[bool, doc("write the computed headers in place")] = False,
936) -> None:
937 """Check shipped extension content opens with its provenance header.
938
939 Part of the gate. Nobody composes a header by hand: ``--fix``
940 writes the computed text, and the render and emitters inject
941 theirs into everything they write.
942 """
943 check_content(fix=fix)
944
945
946def check_content(*, fix: bool = False, files: frozenset[str] | None = None) -> None:
947 """The provenance check over the content files in scope; refuses a missing header.
948
949 The engine behind `fm provenance` and the gate's ``provenance.check``: *files*
950 keeps it to those root-relative files, None to every content file.
951 """
952 root = workspace_root()
953 if root is None:953 ↛ 954line 953 didn't jump to line 954 because the condition on line 953 was never true
954 fail("no workspace: no workshop.toml above the working directory")
955 findings = content_lint(root, fix=fix, files=files)
956 for line in findings:
957 print(f" {line}")
958 if findings and not fix:
959 fail(
960 "extension content is missing provenance headers: run"
961 f" `{footman.prog()} check --fix` to write them"
962 )