1"""The ``issue`` family: the shared work pool and its lifecycle.
3``issue.create``, ``issue.list``, and ``issue.search`` are the pool's
4reads and the one write that files work. The top-level ``start``
5lives here too, since most work starts from an issue: it picks an
6issue up (assign within the workspace's limit, branch from a fetched
7base, open the work in a linked worktree by default), files one from
8a quoted title, or starts a plain branch that belongs to no issue.
9``issue.stop`` is start's inverse for an issue: unassign, clean up
10the local state, and leave the remote branch as the pool's copy.
11``issue.close`` closes the issue itself, removes the branch it was
12worked on unless an open pull request comes from that branch, and
13records where the work got to.
15One destruction rule holds everywhere: work that exists nowhere else
16is never destroyed without ``--discard``, and the refusal's prose
17names the situation it found.
18"""
20from __future__ import annotations
22import os
23import re
24from pathlib import Path
25from typing import Annotated
27import livery.footman as footman
28import livery.toolroom.tools as tools
29from livery import git
30from livery.footman import Arg, ask, doc, fail, group, suggest
31from livery.forge import ForgeError, Issue, Repository
32from livery.workshop import _stack
33from livery.workshop._ci_context import state_store
34from livery.workshop._contract import load_contract
35from livery.workshop._submit import (
36 merged_pull_request,
37 only_local_work,
38 parse_number,
39 worktree_for,
40)
42_KINDS = ("feat", "fix", "chore", "docs", "refactor")
43_SLUG_CAP = 40
44_BRANCH_RE = re.compile(r"^(?:feat|fix|chore|docs|refactor)/(\d+)-")
46issue = group("issue", help="Issues: the shared work pool")
49def _workspace() -> Path:
50 from livery.workshop._extensions import workspace_root
52 root = workspace_root()
53 if root is None:53 ↛ 54line 53 didn't jump to line 54 because the condition on line 53 was never true
54 fail("no workspace: no workshop.toml above the working directory")
55 return root
58def _repo(root: Path) -> Repository:
59 from livery.workshop._forge_lane import this_repository
61 return this_repository(root)
64def assignee_limit(root: Path) -> int:
65 """The workspace's assignee limit; policy, not a forge fact.
67 ``[issues] assignees`` in the root ``workshop.toml``, default 1 so
68 a free GitLab needs nothing. Enforced by the workshop on every
69 forge, including ones whose native limit is higher; whether the
70 forge itself can honour it is ``configure``'s check.
71 """
72 contract = root / "workshop.toml"
73 if not contract.is_file():
74 return 1
75 data = load_contract(contract)
76 return int(data.get("issues", {}).get("assignees", 1))
79def parse_ref(token: str) -> tuple[int, str]:
80 """*token* as ``(number, "")`` or ``(0, title)``.
82 A token [livery.workshop._submit.parse_number][] reads as a
83 number, ``#`` or not, is one; anything else is a title to file
84 first. The ``#`` matters here: read as a title, ``#123`` would
85 file a junk issue named with the hash.
86 """
87 number = parse_number(token)
88 if number is None:
89 return 0, token
90 return number, ""
93def _slug(title: str) -> str:
94 kebab = re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-")
95 return kebab[:_SLUG_CAP].rstrip("-") or "work"
98def branch_name(kind: str, number: int, title: str) -> str:
99 """``<kind>/<number>-<slug>``: the number carries identity."""
100 return f"{kind}/{number}-{_slug(title)}"
103def worktree_home(root: Path) -> Path:
104 """Where this repository's issue worktrees live under the runner's home.
106 The folder is named after the repository's main checkout, which git
107 reports from any of its worktrees, so work started inside a
108 worktree lands beside the rest. A directory that is no checkout is
109 named by itself.
110 """
111 name = root.name
112 if (root / ".git").exists():
113 name = git.main_checkout(root).name
114 return footman.data_dir() / "worktrees" / name
117def worktree_path(root: Path, number: int, title: str) -> Path:
118 """Where the issue's worktree lives: under the runner's home.
120 Outside every repository, so repo tooling never walks into a
121 worktree, and under a per-user home so a worktree's venv
122 hardlinks from the same filesystem's cache. The home is the
123 runner's own data directory, asked of footman: a footman plugin
124 owns no home of its own.
125 """
126 return worktree_home(root) / f"{number}-{_slug(title)}"
129def _open_numbers() -> list[str]:
130 """Completion: the open issue numbers; never raises.
132 Offline, token-less, or outside a repo must cost the
133 suggestions, never the command.
134 """
135 try:
136 root = _workspace()
137 return [str(row.number) for row in _repo(root).issue.list(state="open")]
138 except Exception:
139 return []
142def _issue_kind(labels: tuple[str, ...], override: str) -> str:
143 if override:143 ↛ 144line 143 didn't jump to line 144 because the condition on line 143 was never true
144 return override
145 for label in labels:145 ↛ 146line 145 didn't jump to line 146 because the loop on line 145 never started
146 _, _, kind = label.partition("kind/")
147 if kind in _KINDS:
148 return kind
149 return "feat"
152def _find_branch(root: Path, number: int, *, ask_origin: bool = True) -> str:
153 """The issue's branch, from the local listing, then origin's.
155 With *ask_origin* false, origin's branches are the remote-tracking
156 refs the last fetch left: no network and no wait, for a caller that
157 only names the branch.
158 """
159 needle = f"/{number}-"
160 for name in git.local_branches(root, ""):
161 if _BRANCH_RE.match(name) and needle in name:
162 return name
163 remote = (
164 git.remote_branches(root, "") if ask_origin else git.tracking_branches(root, "")
165 )
166 for name in remote:166 ↛ 169line 166 didn't jump to line 169 because the loop on line 166 didn't complete
167 if _BRANCH_RE.match(name) and needle in name:167 ↛ 166line 167 didn't jump to line 166 because the condition on line 167 was always true
168 return name
169 return ""
172@issue.default
173def issue_default() -> None:
174 """List the open issues (the bare ``fm issue``)."""
175 issue_list()
178@issue.task(name="list")
179def issue_list() -> None:
180 """The open issues: number, title, who is on them."""
181 root = _workspace()
182 rows = _repo(root).issue.list(state="open")
183 if not rows:
184 print(" no open issues")
185 return
186 for row in rows:
187 holders = f" ({', '.join(row.assignees)})" if row.assignees else ""
188 print(f" #{row.number} {row.title}{holders}")
191@issue.task(name="show")
192def issue_show(
193 ref: Annotated[Arg[str], ask(), suggest(_open_numbers, strict=False)] = "",
194) -> None:
195 """One issue in full: title, state, who is on it, the body, and its thread.
197 The body is the work order and the thread its continuation, so
198 both print verbatim. The pull request on the issue's branch is
199 named when one is open, since that is where the work stands. The
200 branch is looked up among the local branches and the
201 remote-tracking refs, so the verb asks no remote of git; a lookup
202 git cannot answer is named in one line, and the body and the
203 thread still print.
204 """
205 root = _workspace()
206 number, _ = parse_ref(ref)
207 if not number:
208 fail(f"issue.show takes an issue number; {ref!r} is not one")
209 repo = _repo(root)
210 found = repo.issue.get(number)
211 if found is None:
212 fail(f"no issue #{number} on the forge")
213 holders = f" ({', '.join(found.assignees)})" if found.assignees else ""
214 labels = f" [{', '.join(found.labels)}]" if found.labels else ""
215 print(f" #{found.number} {found.title}{holders}{labels}")
216 print(f" {found.state} {found.url}".rstrip())
217 try:
218 branch = _find_branch(root, number, ask_origin=False)
219 except git.GitError as error:
220 print(f" the issue's branch could not be looked up: {error}")
221 branch = ""
222 pull = repo.pr.find_by_head(branch) if branch else None
223 if pull is not None and pull.state == "open":
224 print(f" open PR #{pull.number} on {branch}: {pull.title}")
225 if found.body.strip():225 ↛ 228line 225 didn't jump to line 228 because the condition on line 225 was always true
226 print()
227 print(found.body.rstrip("\n"))
228 for comment in repo.issue.comments(number):
229 when = f" {comment.created_at}" if comment.created_at else ""
230 print()
231 print(f" --- {comment.author}{when}")
232 print(comment.body.rstrip("\n"))
235@issue.task(name="search")
236def issue_search(text: Arg[str] = "") -> None:
237 """The open issues whose title or body contains *text*."""
238 if not text:
239 fail(f"name the text to search for: `{footman.prog()} issue.search watcher`")
240 root = _workspace()
241 for row in _repo(root).issue.search(text):
242 print(f" #{row.number} {row.title}")
245@issue.task(name="create")
246def issue_create(
247 title: Arg[str] = "",
248 type: Annotated[str, doc("kind label: feat, fix, chore, docs, refactor")] = "feat",
249 body: Annotated[str, doc("the issue body, readable by an outsider")] = "",
250) -> None:
251 """File a new issue; ``start`` with a title files and starts.
253 The kind label is best-effort: a forge or token that refuses
254 labels costs the label, never the issue. Every filed issue
255 should carry a body an outsider can read; correct one later
256 with ``issue.update``.
257 """
258 if not title:258 ↛ 259line 258 didn't jump to line 259 because the condition on line 258 was never true
259 fail(f'name the issue: `{footman.prog()} issue.create "fix the flaky watch"`')
260 root = _workspace()
261 repo = _repo(root)
262 if type not in _KINDS:262 ↛ 263line 262 didn't jump to line 263 because the condition on line 262 was never true
263 fail(f"unknown type {type!r}: one of {', '.join(_KINDS)}")
264 try:
265 created = repo.issue.create(title, body=body, labels=(f"kind/{type}",))
266 except ForgeError:
267 created = repo.issue.create(title, body=body)
268 print(" Note: the kind label was refused; the issue is filed without it")
269 print(f" filed #{created.number}: {created.title}")
270 if created.url:270 ↛ exitline 270 didn't return from function 'issue_create' because the condition on line 270 was always true
271 print(f" {created.url}")
274@issue.task(name="update")
275def issue_update(
276 number: Arg[int] = 0,
277 title: Annotated[str, doc("the corrected title (empty keeps it)")] = "",
278 body: Annotated[str, doc("the corrected body (empty keeps it)")] = "",
279) -> None:
280 """Rewrite an issue's title, body, or both.
282 Only the provided fields change; clearing a text to empty is not
283 part of the contract. The issue is read first, so a wrong number
284 refuses by name instead of writing nowhere.
285 """
286 if not number:286 ↛ 287line 286 didn't jump to line 287 because the condition on line 286 was never true
287 fail(f"name the issue: `{footman.prog()} issue.update 123 --body=...`")
288 if not title and not body:
289 fail("nothing to change: pass --title, --body, or both")
290 root = _workspace()
291 repo = _repo(root)
292 found = repo.issue.get(number)
293 if found is None:
294 fail(f"issue #{number} does not exist in this repository")
295 repo.issue.update(number, title=title, body=body)
296 changed = ", ".join(
297 name for name, value in (("title", title), ("body", body)) if value
298 )
299 print(f" #{number}: {changed} updated")
302@issue.task(name="comment")
303def issue_comment(
304 number: Arg[int] = 0,
305 body: Annotated[str, doc("what to add to the issue's thread")] = "",
306) -> None:
307 """Add to an issue's thread, leaving its body alone.
309 The body is the work order and the thread its continuation, so a
310 ruling, a measurement or a change of direction goes here rather
311 than into a rewrite of the body, which would replace the
312 specification a reader opens the issue for. The issue is read
313 first, so a wrong number refuses by name instead of writing
314 nowhere.
315 """
316 if not number:
317 fail(f"name the issue: `{footman.prog()} issue.comment 123 --body=...`")
318 if not body:
319 fail("nothing to say: pass --body with the text for the thread")
320 root = _workspace()
321 repo = _repo(root)
322 found = repo.issue.get(number)
323 if found is None:
324 fail(f"issue #{number} does not exist in this repository")
325 repo.issue.comment(number, body)
326 print(f" #{number}: added to the thread")
329_PLAIN_BRANCH_RE = re.compile(rf"^({'|'.join(_KINDS)})/([a-z0-9][a-z0-9-]*)$")
332def _provision(path: Path) -> None:
333 """Sync the worktree at *path*, so its first gate finds what it reads; idempotent.
335 A failure is said and not fatal: the worktree exists, and running
336 the start again, or a sync in it, repairs it.
337 """
338 provision = tools.uv.opts(cwd=path, nofail=True, recorded=False)(
339 "run", footman.prog(), "sync"
340 )
341 if provision.code != 0:
342 print(f" Note: `{footman.prog()} sync` in the worktree failed; run it there")
345@footman.task(interactive=True)
346def start(
347 ref: Annotated[Arg[str], ask(), suggest(_open_numbers, strict=False)] = "",
348 type: Annotated[str, doc("kind override: feat, fix, chore, docs, refactor")] = "",
349 from_: Annotated[
350 str,
351 doc("start on this pushed, unmerged branch instead of main; submit targets it"),
352 ] = "",
353 body: Annotated[str, doc("the issue body when the title form files one")] = "",
354 wip: Annotated[
355 bool, doc("park the dirty tree as a commit and reuse this checkout")
356 ] = False,
357 worktree: Annotated[bool, doc("open the work in a linked worktree")] = True,
358 agent: Annotated[
359 str, doc("hand the work to a coding agent (implies a worktree)")
360 ] = "",
361 prompt: Annotated[
362 str, doc("an initial prompt appended to the agent's briefing")
363 ] = "",
364 open: Annotated[str, doc("how to open a worktree: shell, code, or none")] = "",
365) -> None:
366 """Start work: an issue by number, a title that files one, or a plain branch.
368 REF is an issue number (a leading ``#`` is accepted), a quoted
369 title, which files the issue first, or ``<kind>/<slug>`` (``docs/
370 the-plan``) for a branch that belongs to no issue: a note, a small
371 fix. An issue is assigned, and assignment is documentation: at the
372 workspace's assignee limit, or when the forge refuses the write,
373 the start proceeds with a warning that others will not see you on
374 the issue. An issue's branch is ``<kind>/<number>-<slug>`` and
375 ``fm submit`` closes the issue on merge; a plain branch is named
376 as given and closes nothing. Every branch starts from a fetched
377 ``origin/main``, so a stale base is impossible; ``--from=<branch>``
378 starts on a pushed, unmerged parent instead and records the parent
379 with the commit the branch starts from. ``fm submit`` targets the
380 parent until it has merged, and ``fm sync`` and ``fm submit`` move
381 the branch's own commits when the parent moves or merges. A worktree under
382 the runner's home is the default, entered in a shell when a
383 person is at the terminal (``--open=code`` opens the editor
384 instead, ``--open=none`` prints the path); ``--no-worktree``
385 reuses this checkout, where a dirty tree refuses naming ``--wip``
386 (park the tree as a commit; squash-only merging evaporates it) as
387 the escape. ``--agent`` launches the named agent in the worktree
388 with a minimal briefing; the worktree's own instructions are the
389 real ones. Re-running on started work re-enters it, in whichever
390 tree holds the branch. A local branch no tree holds is re-entered
391 on its own tip, unless its pull request merged and took that tip:
392 the branch is finished work, so it goes and the start begins fresh.
393 """
394 if not ref:
395 fail(
396 f"name what to start: an issue number (`{footman.prog()} start 123`),"
397 f' a quoted title (`{footman.prog()} start "fix the flaky watch"`), or'
398 f" a branch (`{footman.prog()} start docs/the-plan`)"
399 )
400 root = _workspace()
401 repo = _repo(root)
402 if agent:402 ↛ 403line 402 didn't jump to line 403 because the condition on line 402 was never true
403 worktree = True
404 if type and type not in _KINDS:
405 fail(f"unknown type {type!r}: one of {', '.join(_KINDS)}")
406 plain = _PLAIN_BRANCH_RE.match(ref)
407 if plain is None and "/" in ref and " " not in ref:
408 fail(
409 f"{ref!r} is not a branch this verb starts: spell it"
410 f" `<kind>/<slug>` with a kind of {', '.join(_KINDS)} and a"
411 " lowercase slug (`docs/the-plan`)"
412 )
413 if plain is not None:
414 kind, slug = plain.group(1), plain.group(2)
415 branch = ref
416 path = worktree_home(root) / f"{kind}-{slug}"
417 briefing = f"Work on branch {branch}."
418 started = f"{branch} (no issue; submit closes nothing)"
419 else:
420 work = _issue_for(repo, ref, type=type, body=body)
421 _assign(root, repo, work)
422 kind = _issue_kind(work.labels, type)
423 branch = branch_name(kind, work.number, work.title)
424 path = worktree_path(root, work.number, work.title)
425 briefing = f"Work on issue #{work.number}: {work.title}\n\n{work.body}"
426 started = branch
427 fetch_base(root)
428 base = "main"
429 if from_:
430 if from_ == branch:430 ↛ 431line 430 didn't jump to line 431 because the condition on line 430 was never true
431 fail(f"--from={from_} names the branch being started")
432 if not git.remote_head(root, from_):
433 fail(
434 f"origin has no branch {from_!r} to start on: push the parent"
435 f" first (`{footman.prog()} submit` in its worktree), then"
436 " start on it"
437 )
438 base = from_
439 if worktree:
440 from livery.workshop._sweep import sweep_worktrees
442 for line in sweep_worktrees(worktree_home(root).parent, dry_run=False):442 ↛ 443line 442 didn't jump to line 443 because the loop on line 442 never started
443 print(f" {line}")
444 held = _started_at(root, branch, path)
445 if held is not None:
446 print(f" already started: {branch} at {held}")
447 if held == path:
448 # A start that failed after the worktree existed (a sync
449 # that met no network) left it unsynced; running the
450 # start again is the recovery, so it syncs again.
451 _provision(path)
452 if agent:452 ↛ 453line 452 didn't jump to line 453 because the condition on line 452 was never true
453 _launch_agent(agent, held, briefing, branch, prompt)
454 return
455 _open_work(held, open)
456 return
457 path.parent.mkdir(parents=True, exist_ok=True)
458 if _kept(repo, root, branch):
459 # The branch outlived its worktree and is not finished work:
460 # a worktree on its own tip re-enters it, its commits kept.
461 git.run(root, "worktree", "add", str(path), branch)
462 print(f" worktree {path} on {branch}, its own commits kept")
463 else:
464 git.run(root, "worktree", "add", str(path), "-b", branch, f"origin/{base}")
465 print(f" worktree {path} on {started}")
466 _record_parent(root, branch, from_)
467 _provision(path)
468 if agent:468 ↛ 469line 468 didn't jump to line 469 because the condition on line 468 was never true
469 _launch_agent(agent, path, briefing, branch, prompt)
470 return
471 _open_work(path, open)
472 return
473 if not git.is_clean(root):
474 if wip:
475 git.commit_all(root, f"chore(wip): parked by start ({branch})")
476 print(" parked the working tree (squash-only merging evaporates it)")
477 else:
478 fail(
479 "the working tree has uncommitted changes.\n"
480 f" Park them and reuse this checkout: {footman.prog()} start --wip"
481 f" --no-worktree {ref}\n"
482 " Or work in a linked worktree: "
483 f"{footman.prog()} start {ref}"
484 )
485 start_here(root, repo, branch, base=base, parent=from_, started=started)
488@footman.task(serial=True)
489def finish(
490 ref: Annotated[
491 Arg[str], doc("issue number, worktree name, or branch name to clean up")
492 ] = "",
493 all: Annotated[
494 bool, doc("clean up every merged worktree and branch in this repository")
495 ] = False,
496 dry_run: Annotated[
497 bool, doc("say what would be cleaned up, touch nothing")
498 ] = False,
499) -> None:
500 """Clean up finished work: remove a landed worktree or step off a merged branch.
502 The inverse of ``start`` for work whose pull request has already
503 merged. Without *REF* or ``--all``: inside a linked worktree,
504 removes it and its local branch; in the main checkout on a merged
505 branch, switches onto an up-to-date ``main`` and removes the
506 branch. With *REF* (an issue number, worktree name, or local branch
507 name), cleans up that one target. With ``--all``, cleans up every
508 merged worktree and local branch in this repository without
509 touching caches or the state store.
511 Work that is unmerged, dirty, or holds commits ahead of its merged
512 pull request is always kept and named.
513 """
514 from livery.workshop._sweep import finish_flow
516 finish_flow(_workspace(), ref, all_=all, dry_run=dry_run)
519def fetch_base(root: Path) -> None:
520 """Fetch origin's heads and the state store in one round trip; print its lines.
522 What a start does before it cuts a branch: the base is origin's
523 and the store's row series are what the branch's first gate reads,
524 the shape a sync's own fetch has.
526 Raises:
527 Failed: when origin could not be fetched, in git's words.
528 """
529 from livery.git import fetch_store
530 from livery.workshop._series import mirrored_prefixes, mirrored_series
531 from livery.workshop._sync import store_lines
533 fetched = fetch_store(
534 state_store(root),
535 series=mirrored_series(root),
536 prefixes=mirrored_prefixes(root),
537 branches=True,
538 )
539 if fetched.why:
540 fail(f"origin could not be fetched: {fetched.why}")
541 for line in store_lines(fetched):
542 print(line)
545def start_here(
546 root: Path,
547 repo: Repository,
548 branch: str,
549 *,
550 base: str = "main",
551 parent: str = "",
552 started: str = "",
553) -> None:
554 """Start *branch* in this checkout from ``origin/<base>``, or re-enter it.
556 The in-place half of ``start``, which the balancer's submit calls
557 too ([livery.workshop._balance.submit][]). A local *branch* that is
558 not finished work is switched to as it stands; one whose pull
559 request merged goes, and the start begins fresh. ``origin/<base>``
560 is read as the last fetch left it, so `fetch_base` comes first.
561 The working tree is the caller's to check: a dirty one carries
562 its changes onto the branch. *parent* records the branch ``fm
563 submit`` targets until it merges; *started* is how the branch is
564 announced, its name when empty.
565 """
566 if _kept(repo, root, branch):
567 git.switch(root, branch)
568 print(f" already started: back on {branch}")
569 return
570 git.run(root, "checkout", "-b", branch, f"origin/{base}")
571 print(f" on {started or branch}")
572 _record_parent(root, branch, parent)
575def _started_at(root: Path, branch: str, path: Path) -> Path | None:
576 """Where *branch*'s started work is: its worktree, another tree, or this checkout.
578 None when no tree holds the branch. The branch alone is not started
579 work: a merged one outlives the worktree its merge removed.
580 """
581 from livery.workshop._submit import worktree_for
583 if path.is_dir():
584 return path
585 if tree := worktree_for(root, branch):
586 return Path(tree)
587 if git.current_branch(root) == branch:587 ↛ 588line 587 didn't jump to line 588 because the condition on line 587 was never true
588 return root
589 return None
592def _kept(repo: Repository, root: Path, branch: str) -> bool:
593 """Whether *branch* exists and stays to be re-entered; the line says why.
595 A branch whose pull request merged and took its tip is finished
596 work: the janitor's rule ([livery.workshop._sweep.sweep_branch][])
597 drops it here, and the start begins fresh from the base. Any other
598 branch keeps its commits.
599 """
600 if not git.local_branch_exists(root, branch):
601 return False
602 from livery.workshop._sweep import sweep_branch
604 went, line = sweep_branch(
605 root,
606 branch,
607 current=git.current_branch(root),
608 dry_run=False,
609 repo=repo,
610 )
611 print(f" {line}")
612 return not went
615def _record_parent(root: Path, branch: str, parent: str) -> None:
616 """Record *parent* as the base ``fm submit`` targets for *branch*; none, nothing.
618 The parent's pushed tip is recorded beside it: *branch* starts
619 there, so the commits after it are the branch's own, which is what
620 ``fm sync`` moves when the parent moves or merges.
621 """
622 if not parent:
623 return
624 _stack.record_stack(root, branch, parent, git.sha_of(root, f"origin/{parent}"))
625 print(f" parent: {parent} (`{footman.prog()} submit` targets it until it merges)")
628def _issue_for(repo: Repository, ref: str, *, type: str, body: str) -> Issue:
629 """The issue *ref* names, or the one a quoted title files."""
630 number, title = parse_ref(ref)
631 if number:
632 found = repo.issue.get(number)
633 if found is None:
634 fail(f"issue #{number} does not exist in this repository")
635 return found
636 try:
637 work = repo.issue.create(title, body=body, labels=(f"kind/{type or 'feat'}",))
638 except ForgeError:
639 work = repo.issue.create(title, body=body)
640 print(" Note: the kind label was refused; filed without it")
641 print(f" filed #{work.number}: {work.title}")
642 return work
645def _assign(root: Path, repo: Repository, work: Issue) -> None:
646 """Put the caller on the issue; at the limit or a refusal, warn and go on."""
647 me = _me(repo)
648 limit = assignee_limit(root)
649 if me not in work.assignees and len(work.assignees) >= limit:
650 listed = ", ".join(work.assignees)
651 print(
652 f" Warning: #{work.number} is assigned to {listed} and the"
653 f" workspace's assignee limit is {limit}, so you will not be"
654 " listed as working on it until something lands. Coordinate"
655 " with them; `[issues] assignees` in workshop.toml raises the"
656 " limit if this issue takes more people."
657 )
658 return
659 try:
660 if me and me not in work.assignees:
661 repo.issue.assign(work.number, me)
662 except ForgeError as error:
663 print(
664 f" Note: could not assign the issue ({error}); others"
665 " will not see you working on it, so communicate."
666 )
669def _me(repo: Repository) -> str:
670 try:
671 from livery.workshop._extensions import workspace_root
672 from livery.workshop._forge_lane import this_forge
674 root = workspace_root()
675 return this_forge(root).whoami() if root is not None else ""
676 except Exception:
677 return ""
680def _launch_agent(
681 name: str, path: Path, briefing: str, branch: str, prompt: str
682) -> None:
683 """Hand the work to the agent in its worktree; a terminal handoff.
685 The briefing is minimal on purpose: the worktree carries the
686 project's own instructions, and repeating them here would drift.
687 Nothing after the exec runs.
688 """
689 briefing = f"{briefing}\n\nYou are on branch {branch}."
690 if prompt:690 ↛ 691line 690 didn't jump to line 691 because the condition on line 690 was never true
691 briefing += f"\n\n{prompt}"
692 executable = "claude" if name in ("", "claude") else name
693 os.chdir(path)
694 try:
695 os.execvp(executable, [executable, briefing])
696 except OSError:
697 fail(f"agent '{executable}' is not installed on this machine")
700def _open_work(path: Path, how: str) -> None:
701 from livery.workshop._env_tasks import START_PATH_VARIABLE
703 target = os.environ.get(START_PATH_VARIABLE, "")
704 if target and not how:
705 # The shell function around `start` names a file: the caller's
706 # own shell enters the worktree, so no child shell is opened.
707 Path(target).write_text(str(path), "utf-8")
708 print(f" the worktree is at {path}; this shell enters it")
709 return
710 mode = how or ("shell" if footman.attended() else "none")
711 if mode == "code":
712 try:
713 tools.code.opts(nofail=True, recorded=False)(str(path))
714 except (OSError, tools.ToolError):
715 # Opening an editor is a convenience, never the work: a
716 # machine without `code` gets the path instead.
717 print(f" `code` is not on PATH; the worktree is at {path}")
718 elif mode == "shell":718 ↛ 719line 718 didn't jump to line 719 because the condition on line 718 was never true
719 from livery.workshop._shell import launch_shell
721 os.chdir(path)
722 launch_shell("")
723 elif mode == "none":723 ↛ 726line 723 didn't jump to line 726 because the condition on line 723 was always true
724 print(f" the worktree is at {path}")
725 else:
726 fail(f"unknown open mode {how!r}: shell, code, or none")
729@issue.task(name="stop")
730def issue_stop(
731 ref: Annotated[Arg[str], ask(), suggest(_open_numbers, strict=False)] = "",
732 discard: Annotated[bool, doc("destroy work that exists nowhere else")] = False,
733) -> None:
734 """Stop working on an issue: unassign, clean up the local state.
736 The remote branch is never touched; while the issue is open it
737 stays the pool's copy. Work that exists nowhere else is never
738 destroyed without ``--discard``, and the refusal names what it
739 found: a delta the remote is missing, a remote gone while the
740 issue is open (exceptional), or an issue already closed.
741 """
742 root = _workspace()
743 repo = _repo(root)
744 number = 0
745 if ref:
746 number, _title = parse_ref(ref)
747 if not number:747 ↛ 748line 747 didn't jump to line 748 because the condition on line 747 was never true
748 fail("issue.stop takes a number; a title names nothing to stop")
749 else:
750 match = _BRANCH_RE.match(git.current_branch(root))
751 if match is None:
752 fail(
753 "not on an issue branch: name the issue"
754 f" (`{footman.prog()} issue.stop 123`) or run it from the branch."
755 )
756 number = int(match.group(1))
757 branch = _find_branch(root, number)
758 if not branch:758 ↛ 759line 758 didn't jump to line 759 because the condition on line 758 was never true
759 fail(f"no branch for issue #{number} exists locally or on the remote")
761 work = repo.issue.get(number)
762 state = work.state if work is not None else "unknown"
763 remote_exists = branch in git.remote_branches(root, "")
764 merged_head = ""
765 try:
766 landed = merged_pull_request(repo, root, branch)
767 merged_head = landed.head_sha if landed is not None else ""
768 except ForgeError:
769 merged_head = ""
770 only_local = (
771 only_local_work(root, branch, merged_head=merged_head)
772 if git.local_branch_exists(root, branch)
773 else ""
774 )
775 if only_local and not discard:
776 if state == "closed":
777 fail(
778 f"issue #{number} is already closed, but this branch holds"
779 f" {only_local} that exists nowhere else. Push it somewhere"
780 " it matters, or pass --discard to destroy it."
781 )
782 if not remote_exists:
783 fail(
784 f"the remote branch for issue #{number} is gone while the"
785 f" issue is still open, and this branch holds {only_local}."
786 " That is not a state stop creates; someone removed the"
787 " branch. Push the branch back, or pass --discard to"
788 " destroy the local work."
789 )
790 fail(
791 f"this branch holds {only_local} that the remote branch does"
792 " not. Push first (`git push`), or pass --discard to destroy"
793 " the delta; the remote branch stays as the pool's copy."
794 )
796 if work is not None and state == "open":796 ↛ 803line 796 didn't jump to line 803 because the condition on line 796 was always true
797 try:
798 repo.issue.unassign(number)
799 print(f" unassigned you from #{number}")
800 except ForgeError as error:
801 print(f" Note: could not unassign ({error}); continuing")
803 removed = _remove_local(root, branch)
804 what = " and ".join(removed) if removed else "nothing local to remove"
805 print(f" stopped #{number}: {what}; the remote branch stays")
808def _remove_local(root: Path, branch: str) -> list[str]:
809 """Remove the branch's worktree and local branch; what was removed."""
810 removed: list[str] = []
811 tree = worktree_for(root, branch)
812 if tree:
813 git.run(root, "worktree", "remove", "--force", tree)
814 print(f" removed worktree {tree}")
815 removed.append("the worktree")
816 elif git.current_branch(root) == branch:
817 git.switch(root, "main")
818 if git.local_branch_exists(root, branch):
819 git.delete_branch(root, branch)
820 removed.append("the local branch")
821 return removed
824def _held_by_pull_request(repo: Repository, root: Path, branch: str) -> str:
825 """Why a close keeps *branch* and its worktree; ``""`` when nothing keeps them.
827 An open pull request from *branch* holds them: the forge closes a
828 pull request unmerged once its head branch is deleted. A forge that
829 cannot answer holds them as well, since an unanswered question is
830 never read as "no pull request".
831 """
832 what = f"{branch} and its worktree" if worktree_for(root, branch) else branch
833 try:
834 pull = repo.pr.find_by_head(branch)
835 except ForgeError as error:
836 return (
837 f"kept {what}: the forge could not say whether a PR is open"
838 f" from it ({error}); ask again when it answers"
839 )
840 if pull is None or pull.state != "open":
841 return ""
842 return f"kept {what}: PR #{pull.number} is open from it; merge or close it first"
845def _close_with_record(
846 repo: Repository, number: int, reason: str, message: str, where: str
847) -> None:
848 """Comment why the issue ended and where its branch went, then close it."""
849 note = f"closed: {reason}"
850 if message:
851 note += f"\n\n{message}"
852 if where:
853 note += f"\n\n{where}"
854 repo.issue.comment(number, note)
855 repo.issue.close(number)
856 print(f" closed #{number}: {reason}")
859@issue.task(name="close", interactive=True)
860def issue_close(
861 ref: Annotated[Arg[str], ask(), suggest(_open_numbers, strict=False)] = "",
862 reason: Annotated[str, doc("why: done, wontfix, duplicate, stale, ...")] = "",
863 message: Annotated[str, doc("free-text detail for the close comment")] = "",
864 keep_branch: Annotated[bool, doc("retain the local and remote branch")] = False,
865 discard: Annotated[bool, doc("destroy work that exists nowhere else")] = False,
866) -> None:
867 """Close the issue itself, and remove the branch it was worked on.
869 An open pull request from the issue's branch keeps the branch and
870 its worktree: deleting the head branch makes the forge close the
871 pull request unmerged, and the branch may carry work for another
872 issue. The close then ends the issue alone and names the pull
873 request, to be merged or closed first. A forge that cannot say
874 whether such a pull request is open keeps them too, and the line
875 names the forge's error. A pull request that already merged means
876 the work landed, the supplied reason no longer applies, and the
877 close becomes cleanup: "issue already resolved". Otherwise the
878 worktree, the local branch, and the remote branch are removed by
879 default, with the removed head sha recorded in the close comment;
880 ``--keep-branch`` retains them.
881 """
882 if not ref:882 ↛ 883line 882 didn't jump to line 883 because the condition on line 882 was never true
883 fail(
884 "name the issue to close:"
885 f" `{footman.prog()} issue.close 123 --reason=wontfix`"
886 )
887 if not reason:887 ↛ 888line 887 didn't jump to line 888 because the condition on line 887 was never true
888 fail(
889 "closing needs a --reason (done, wontfix, duplicate, stale,"
890 " ...): the pool reads why the work ended."
891 )
892 root = _workspace()
893 repo = _repo(root)
894 number, _title = parse_ref(ref)
895 if not number:895 ↛ 896line 895 didn't jump to line 896 because the condition on line 895 was never true
896 fail("issue.close takes a number; a title names nothing to close")
897 work = repo.issue.get(number)
898 if work is None:898 ↛ 899line 898 didn't jump to line 899 because the condition on line 898 was never true
899 fail(f"issue #{number} does not exist in this repository")
901 git.fetch(root)
902 branch = _find_branch(root, number)
903 tip = git.any_head(root, branch) if branch else ""
905 held = _held_by_pull_request(repo, root, branch) if branch else ""
906 if held:
907 print(f" {held}")
908 _close_with_record(repo, number, reason, message, held)
909 return
911 # The destruction rule runs before anything is removed: a refusal
912 # that checks afterwards would be checking a branch that is
913 # already gone. The merged pull request is read first: its head
914 # decides what the merge took.
915 try:
916 landed = merged_pull_request(repo, root, branch) if branch else None
917 except ForgeError as error:
918 fail(
919 f"the forge could not say whether {branch}'s pull request merged"
920 f" ({error}); nothing was removed and #{number} stays open."
921 " Run the close again when the forge answers."
922 )
923 merged = landed is not None
924 only_local = (
925 only_local_work(root, branch, merged_head=landed.head_sha if landed else "")
926 if branch and git.local_branch_exists(root, branch)
927 else ""
928 )
930 if merged:
931 if reason:931 ↛ 933line 931 didn't jump to line 933 because the condition on line 931 was always true
932 print(" Note: the PR merged, so the supplied reason does not apply")
933 if git.local_branch_exists(root, branch):933 ↛ 941line 933 didn't jump to line 941 because the condition on line 933 was always true
934 if only_local and not discard:
935 print(
936 f" kept {branch}: it holds {only_local}; pass --discard"
937 " to remove it"
938 )
939 else:
940 _remove_local(root, branch)
941 if work.state == "open":941 ↛ 944line 941 didn't jump to line 944 because the condition on line 941 was always true
942 repo.issue.comment(number, "closed: resolved by the merged PR")
943 repo.issue.close(number)
944 print(" issue already resolved, nothing left to do")
945 return
947 if only_local and not discard and not keep_branch:
948 fail(
949 f"the branch for #{number} holds {only_local} that exists"
950 " nowhere else, and close removes branches by default. Pass"
951 " --keep-branch to retain them, or --discard to destroy the"
952 " work with the issue."
953 )
955 removed_sha = ""
956 if branch and not keep_branch:
957 # The tip was read before the branch is deleted: the close
958 # comment records where the work got to.
959 removed_sha = tip
960 _remove_local(root, branch)
961 if branch in git.remote_branches(root, ""):961 ↛ 965line 961 didn't jump to line 965 because the condition on line 961 was always true
962 git.run(root, "push", "origin", "--delete", branch)
963 print(f" removed the remote branch {branch}")
965 where = f"removed branch {branch} at {removed_sha}" if removed_sha else ""
966 _close_with_record(repo, number, reason, message, where)
969@issue.task(name="reopen")
970def issue_reopen(
971 ref: Annotated[Arg[str], ask()] = "",
972) -> None:
973 """Reopen a closed issue and put yourself on it, as start does.
975 For an issue a merge closed before its work was done (a branch
976 that carried a plan or a pinning test under the issue's number).
977 Reopening an open issue is a no-op, and the assignment follows
978 start's rules: the workspace's limit and a refused write warn
979 and go on.
980 """
981 if not ref:
982 fail(f"name the issue to reopen: `{footman.prog()} issue.reopen 123`")
983 root = _workspace()
984 repo = _repo(root)
985 number, _title = parse_ref(ref)
986 if not number:986 ↛ 987line 986 didn't jump to line 987 because the condition on line 986 was never true
987 fail("issue.reopen takes a number; a title names nothing to reopen")
988 work = repo.issue.get(number)
989 if work is None:
990 fail(f"issue #{number} does not exist in this repository")
991 if work.state == "open":
992 print(f" #{number} is already open")
993 else:
994 repo.issue.reopen(number)
995 print(f" reopened #{number}: {work.title}")
996 _assign(root, repo, work)