Coverage for packages/workshop/src/livery/workshop/_workflow_tasks.py: 89%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop, packages/extensions/ty, packages/extensions/ruff, packages/extensions/python, packages/extensions/pytest, packages/extensions/pyrefly, packages/extensions/nanobind, packages/extensions/mypy, packages/extensions/mkdocstrings, packages/extensions/lfs, packages/extensions/docs, packages/extensions/cpp, packages/extensions/coverage, packages/extensions/conan, packages/extensions/cmake, packages/extensions/claude, packages/extensions/clang-tidy, packages/extensions/clang-format, packages/extensions/changelog, packages/extensions/basedpyright ran.

1"""The ``workflow`` group: the reserved-branch lifecycles' surface.
2
3``workflow.abort`` stops a reserved workflow, policy layered over the
4same teardown mechanism ``fm abandon`` uses. The hidden
5``workflow.configure`` asserts repository settings from the workspace
6contract, run at birth, as release aftercare, and after an abort.
7The lifecycle drivers (``workflow.release``, ``workflow.update``)
8arrive with their own modules; this one owns what every kind shares.
9"""
10
11from __future__ import annotations(empty)
12
13from pathlib import Path(empty)
14from typing import Annotated(empty)
15
16import livery.footman as footman(empty)
17from livery import git(empty)
18from livery.footman import doc, fail, group, suggest(empty)
19from livery.forge import Forge, Label, RepoConfig, Repository(empty)
20from livery.workshop._contract import load_contract(empty)
21from livery.workshop._extensions import workspace_root(empty)
22from livery.workshop._workflow_state import ((empty)
23 TEARDOWN_SAFE,
24 WorkflowState,
25 WorkflowStatus,
26 workflow_states,
27)
28
29workflow = group("workflow", help="The reserved-branch lifecycles")(empty)
30
31
32def _root() -> Path:(empty)
33 root = workspace_root()
34 if root is None:34 ↛ 35line 34 didn't jump to line 35 because the condition on line 34 was never true
35 fail("no workspace: no workshop.toml above the working directory")
36 return root
37
38
39def _resolved() -> tuple[Repository, Path]:(empty)
40 from livery.workshop._forge_lane import this_repository
41
42 root = _root()
43 return this_repository(root), root
44
45
46def render_workflows(states: tuple[WorkflowStatus, ...]) -> None:(empty)
47 """Print one line per workflow: name, state, author, the way forward."""
48 if not states:
49 print(" no reserved workflows in flight")
50 return
51 for wf in states:
52 author = f" ({wf.author})" if wf.author else ""
53 extra = f" - {wf.detail}" if wf.detail else ""
54 tagged = (
55 f" [tagged: {', '.join(wf.tagged)}]"
56 if wf.tagged and wf.state is not WorkflowState.SUCCEEDED
57 else ""
58 )
59 print(f" {wf.name}: {wf.state.value}{author}{extra}{tagged}")
60
61
62def abort_policy((empty)
63 repo: Repository,
64 root: Path,
65 states: tuple[WorkflowStatus, ...],
66 name: str,
67 *,
68 force: bool,
69 base: str = "main",
70 interactive: bool = False,
71) -> None:
72 """The abort's state gates, then the shared teardown.
73
74 Bare with one workflow targets it; several ask interactively or
75 refuse by name, silence never picks a teardown target. UNKNOWN
76 refuses without force, never tear down on a blip; a live state
77 refuses without force; a bare ``--force`` with several in flight
78 refuses, force one by name.
79 """
80 if not states:
81 print(" no reserved workflows to abort")
82 return
83 target: WorkflowStatus | None = None
84 if name:
85 target = next((wf for wf in states if wf.name == name), None)
86 if target is None:
87 known = ", ".join(wf.name for wf in states)
88 fail(f"no workflow named {name!r}; in flight: {known}")
89 elif len(states) == 1:
90 target = states[0]
91 elif interactive:
92 options: list[tuple[str, WorkflowStatus | None]] = [
93 (f"{wf.name} ({wf.author or 'unknown author'}, {wf.state.value})", wf)
94 for wf in states
95 ]
96 options.append(("nothing - leave them all running", None))
97 picked = footman.select("abort which?", options)
98 # The select's typing admits a bare-label pick; every option
99 # here carries a value, so a str can only mean no target.
100 target = picked if not isinstance(picked, str) else None
101 if target is None:
102 raise SystemExit(" nothing aborted")
103 else:
104 listed = "\n".join(
105 f" {footman.prog()} workflow.abort {wf.name}"
106 + (f" ({wf.author}, {wf.state.value})" if wf.author else "")
107 for wf in states
108 )
109 fail(
110 "several workflows are in flight, and silence must not pick a"
111 f" teardown target. Abort one by name:\n{listed}"
112 )
113 assert target is not None
114 if force and not name and len(states) > 1:114 ↛ 115line 114 didn't jump to line 115 because the condition on line 114 was never true
115 fail(
116 "--force with several workflows in flight needs a name: a bare"
117 " force must not sweep what someone else is running"
118 )
119 if target.state is WorkflowState.UNKNOWN and not force:
120 fail(
121 f"{target.name}'s state could not be read, and a blip must never"
122 " look like permission to tear down. Retry when the forge"
123 f" answers, or `{footman.prog()} workflow.abort {target.name}"
124 " --force` if you"
125 " know it is dead."
126 )
127 if target.state not in TEARDOWN_SAFE and not force:
128 who = target.author or "someone"
129 fail(
130 f"{target.name} is {target.state.value} ({who}); aborting it"
131 " loses in-flight work. Wait for it, coordinate with its"
132 f" author, or `{footman.prog()} workflow.abort {target.name}"
133 " --force` to tear"
134 " it down deliberately."
135 )
136 from livery.workshop._submit import teardown_branch
137
138 head_sha = ""
139 try:
140 head_sha = git.any_head(root, target.branch)
141 except Exception:
142 head_sha = ""
143 teardown_branch(repo, root, target.branch, base)
144 _reconcile_configuration(root, head_sha)
145
146
147def _active_names() -> tuple[str, ...]:(empty)
148 """The in-flight workflow names, for completion; empty off a workspace."""
149 try:
150 repo, root = _resolved()
151 return tuple(wf.name for wf in workflow_states(repo, root))
152 except Exception:
153 return ()
154
155
156@workflow.task(name="abort", interactive=True)(empty)
157def workflow_abort((empty)
158 name: Annotated[
159 str,
160 suggest(_active_names, strict=False),
161 doc("the workflow to stop; bare targets the only one in flight"),
162 ] = "",
163 force: Annotated[bool, doc("tear down a live or unreadable workflow")] = False,
164) -> None:
165 """Stop a reserved workflow: disarm, close its PR, tear its branch down.
166
167 Bare targets the only workflow in flight; with several, an
168 interactive run lists them and asks, a non-interactive run
169 refuses naming each. A live or unreadable workflow refuses
170 without ``--force``, and a bare ``--force`` never sweeps several.
171 Ends by re-asserting the repository configuration, so an aborted
172 workflow that had moved settings forward cannot leave protection
173 demanding contexts that never report again.
174 """
175 repo, root = _resolved()
176 states = workflow_states(repo, root)
177 abort_policy(
178 repo,
179 root,
180 states,
181 name,
182 force=force,
183 interactive=footman.attended(),
184 )
185
186
187def required_context_string(forge_kind: str, context: str) -> str:(empty)
188 """The status context string protection must require, per forge.
189
190 The name in the contract is the gate job's; forges report it
191 differently. GitHub reports the job name itself. Gitea reports
192 Actions statuses as ``<workflow name> / <job> (<event>)``, so a
193 bare job name never matches and the required check can never
194 pass; the workflow's emitted name is ``ci``, and the merge-
195 deciding event is the pull request's. GitLab has no required
196 contexts (the capability probe drops the half), so its spelling
197 never reaches a forge.
198 """
199 if forge_kind == "gitea":
200 return f"ci / {context} (pull_request)"
201 return context
202
203
204def contract_config(root: Path) -> RepoConfig:(empty)
205 """The repository settings the workspace contract states.
206
207 The approvals half derives from the owner declarations
208 (livery.workshop._governance): the highest declared count, with
209 codeowner review required whenever anyone is declared. A forge
210 without the min_approvals capability gets the config without
211 that half rather than a refusal: governance degrades to the
212 codeowners file alone, which is what the forge can honour.
213 """
214 from livery.workshop._governance import governance_config
215 from livery.workshop._points import EVERY_RUNNER_LABEL
216
217 contract = load_contract(root / "workshop.toml")
218 ci = contract.get("ci") or {}
219 context = str(ci.get("required-context") or "gate")
220 forge_kind = str((contract.get("forge") or {}).get("kind", ""))
221 approvals = governance_config(root)
222 return RepoConfig(
223 squash_only=True,
224 delete_branch_on_merge=True,
225 allow_auto_merge=True,
226 required_contexts=(required_context_string(forge_kind, context),),
227 # The release train's receipts: once cut, no ordinary push
228 # may delete or move them. A forge's glob stops at a slash, so
229 # a package in a group directory needs the second pattern.
230 protected_tag_patterns=("packages/*/v*", "packages/*/*/v*"),
231 # The same truth spelled for a forge that cannot name
232 # contexts: the server refuses merges while the head is not
233 # green, the UI's merge button included.
234 require_pipeline_success=True,
235 min_approvals=approvals.min_approvals,
236 require_codeowner_review=approvals.require_codeowner_review,
237 # The label `submit --every-runner` sets, so a forge that
238 # refuses a label it does not carry has it before any submit.
239 labels=(
240 Label(
241 name=EVERY_RUNNER_LABEL,
242 color="1d76db",
243 description="the gate runs every runner for this pull request",
244 ),
245 ),
246 )
247
248
249#: The paths whose change means the repository's settings may have
250#: moved: the contracts and the owners file, on every forge's spelling.
251GOVERNED_PATHS = ((empty)
252 "workshop.toml",
253 "CODEOWNERS",
254 ".gitea/CODEOWNERS",
255 ".github/CODEOWNERS",
256)
257
258
259def contract_changed(root: Path) -> tuple[str, ...]:(empty)
260 """The governed paths HEAD's own commit changed; empty is none.
261
262 The merge point's commit is one squash on main, so its file list
263 is the merge's whole diff. A shallow checkout of depth one reads
264 a squash as a root commit and lists every file, so the shell
265 fetches two.
266 """
267 changed = git.files_in_commit(root, "HEAD")
268 return tuple(
269 path
270 for path in changed
271 if path in GOVERNED_PATHS
272 or (path.startswith("packages/") and path.endswith("/workshop.toml"))
273 )
274
275
276@workflow.task(name="configure", hidden=True)(empty)
277def workflow_configure((empty)
278 if_changed: Annotated[
279 bool, doc("only when HEAD changed a contract or the owners file")
280 ] = False,
281) -> None:
282 """Assert the contract's repository settings; idempotent drift repair.
283
284 Run at repository birth, as release aftercare, after an abort,
285 and at the merge point, where ``--if-changed`` makes it classify
286 its own commit and exit fast when no contract path changed.
287 Resolves the admin ladder (``FORGE_ADMIN_TOKEN``, host-qualified
288 first, the everyday token as the fallback); a refused write
289 teaches the grant and the variable. Declared owners the forge
290 does not know refuse before anything is applied: a review chain
291 pointing at nobody is worse than unapplied settings.
292 """
293 root = _root()
294 if if_changed:
295 changed = contract_changed(root)
296 if not changed:296 ↛ 299line 296 didn't jump to line 299 because the condition on line 296 was always true
297 print(" no contract or owners path changed in HEAD; nothing to reconcile")
298 return
299 print(f" governed paths changed: {', '.join(changed)}")
300 assert_configuration(root)
301
302
303def assert_configuration(root: Path) -> None:(empty)
304 """The configure flow, root-taking so birth can call it too."""
305 from livery.forge import ForgeError, Unsupported
306 from livery.workshop._forge_lane import admin_forge, admin_repository
307 from livery.workshop._governance import unknown_owners
308
309 repo, admin_var = admin_repository(root)
310 forge, _ = admin_forge(root)
311 contract = load_contract(root / "workshop.toml")
312 owner = str((contract.get("forge") or {}).get("owner", ""))
313 missing = unknown_owners(root, forge, owner)
314 if missing:
315 listed = "\n".join(f" {entry}" for entry in missing)
316 fail(
317 "the owner declarations name people or teams this forge does"
318 f" not know:\n{listed}\n Fix the declarations (or the org"
319 " membership) and re-run."
320 )
321 from dataclasses import replace
322
323 config = contract_config(root)
324 if config.min_approvals is not None and not forge.supports("min_approvals"):
325 # The forge cannot enforce the count (GitLab's paid tiers);
326 # the codeowners file still documents it, so the rest of the
327 # contract applies rather than nothing.
328 print(
329 " note: this instance cannot enforce approval counts"
330 " (capability: min_approvals); the codeowners file still"
331 " names the reviewers"
332 )
333 config = replace(config, min_approvals=None, require_codeowner_review=None)
334 if config.required_contexts is not None and not forge.supports("required_contexts"):
335 # GitLab: protection cannot name check contexts, and the
336 # pipeline-success block carries the same truth there, the
337 # UI's merge button included.
338 print(
339 " note: this forge cannot name required check contexts"
340 " (capability: required_contexts); the pipeline-success"
341 " block enforces green-before-merge instead, the forge"
342 " UI included"
343 )
344 config = replace(config, required_contexts=None)
345 try:
346 repo.configure(config)
347 except Unsupported as error:
348 # A decline the probes above did not predict: name it
349 # verbatim, never half-teach a token that would not help.
350 fail(
351 f"the forge declined part of the configuration:\n{error}\n"
352 f" `{footman.prog()} doctor` says what this forge grants."
353 )
354 except ForgeError as error:
355 used = admin_var or "the everyday token"
356 fail(
357 f"the forge refused the configuration using {used}:\n{error}\n"
358 " An administrator's token applies it: set FORGE_ADMIN_TOKEN"
359 " (host-qualified FORGE_ADMIN_TOKEN__<HOST> where one machine"
360 f" serves several forges) and re-run"
361 f" `{footman.prog()} workflow.configure`."
362 )
363 from livery.workshop._points import job_seams
364
365 if "pages" in job_seams(root).values() and forge.supports("pages_config"):365 ↛ 366line 365 didn't jump to line 366 because the condition on line 365 was never true
366 repo.ensure_pages(build_type="workflow")
367 print(" pages hosting asserted (workflow build type)")
368 for line in reconcile_schedules(repo, forge):
369 print(line)
370 print(" repository configuration asserted from the contract")
371
372
373#: How the reconcile names the schedules it owns; any other schedule
374#: on the repository is a person's and is never touched.
375SCHEDULE_PREFIX = "workshop: "(empty)
376
377
378def reconcile_schedules(repo: Repository, forge: Forge) -> list[str]:(empty)
379 """Make the forge's clock match the points that run on it; what was done.
380
381 A forge whose clock is in the workflow file (GitHub, Gitea) has
382 nothing to reconcile and says so. On a forge with pipeline
383 schedules (GitLab) every declared point whose events include
384 ``schedule`` gets one schedule on ``main``, named
385 ``workshop: <point>``, at the point's cron, starting its pipeline
386 with ``FORGE_WORKFLOW`` set to the point's workflow file so the
387 document routes it; a schedule the reconcile named for a point
388 no longer declared is deleted.
389 """
390 from livery.workshop._points import DECLARED
391
392 if not forge.supports("pipeline_schedules"):
393 return [" schedules: the clock is in the workflow file; nothing to reconcile"]
394 wanted = {
395 f"{SCHEDULE_PREFIX}{point.name}": point
396 for point in DECLARED
397 if "schedule" in point.events
398 }
399 lines: list[str] = []
400 for description, point in wanted.items():
401 schedule = repo.schedule.ensure(
402 description,
403 ref="main",
404 cron=point.cron,
405 variables={"FORGE_WORKFLOW": point.workflow},
406 )
407 lines.append(
408 f" schedule {description!r}: {schedule.cron} on {schedule.ref},"
409 f" FORGE_WORKFLOW={point.workflow}"
410 )
411 for schedule in repo.schedule.list():
412 if (
413 schedule.description.startswith(SCHEDULE_PREFIX)
414 and schedule.description not in wanted
415 ):
416 repo.schedule.delete(schedule.description)
417 lines.append(f" schedule {schedule.description!r}: deleted, no such point")
418 return lines
419
420
421def _spawn_configure() -> footman.Result:(empty)
422 """Run the configure verb in a fresh process; the reconcile's seam.
423
424 Fresh, because the abort may sit inside a workflow whose update
425 rewrote this very toolchain.
426 """
427 import sys
428
429 return footman.run(
430 [sys.executable, "-m", "livery.footman", "workflow.configure"],
431 nofail=True,
432 recorded=False,
433 cwd=_root(),
434 )
435
436
437def _reconcile_configuration(root: Path, head_sha: str) -> None:(empty)
438 """Re-assert configuration after an abort; silent when provably unneeded.
439
440 The ladder: an offline diff of the governance paths from the
441 aborted PR's head sha (which persists after the branch deletion)
442 skips everything untouched with certainty; touched paths run the
443 configure in a fresh process (the abort may sit inside a
444 workflow whose update rewrote this toolchain). A failed
445 configure prints its reason verbatim under a conditional note,
446 never an asserted problem: the abort already succeeded, and the
447 repair verb is the same either way.
448 """
449 from livery.workshop._governance import governance_paths
450
451 if head_sha:451 ↛ 471line 451 didn't jump to line 471 because the condition on line 451 was always true
452 try:
453 # The branch side of the diff: an aborted branch that
454 # touched governance may have applied protection before
455 # its merge (the rename heal), and the abort leaves main
456 # demanding the old contract.
457 changed = git.run(
458 root,
459 "diff",
460 "--name-only",
461 f"origin/main...{head_sha}",
462 "--",
463 "workshop.toml",
464 "packages/*/workshop.toml",
465 *[p for p in governance_paths(_root()) if "*" not in p],
466 ).strip()
467 except Exception:
468 changed = "unknown"
469 if not changed:
470 return # nothing config-implying moved: provably unneeded
471 result = _spawn_configure()
472 if result.code != 0:472 ↛ exitline 472 didn't return from function '_reconcile_configuration' because the condition on line 472 was always true
473 detail = result.stderr.strip() or result.stdout.strip() or "(no output)"
474 indented = "\n".join(f" {line}" for line in detail.splitlines())
475 print(
476 " note: the configuration could not be re-asserted from here;"
477 f" if governance settings changed, `{footman.prog()} workflow.configure`"
478 " repairs them (an administrator's token may be needed):\n"
479 f"{indented}"
480 )