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)
488def fetch_base(root: Path) -> None:
489 """Fetch origin's heads and the state store in one round trip; print its lines.
491 What a start does before it cuts a branch: the base is origin's
492 and the store's row series are what the branch's first gate reads,
493 the shape a sync's own fetch has.
495 Raises:
496 Failed: when origin could not be fetched, in git's words.
497 """
498 from livery.git import fetch_store
499 from livery.workshop._series import mirrored_series
500 from livery.workshop._sync import store_lines
502 fetched = fetch_store(
503 state_store(root), series=mirrored_series(root), branches=True
504 )
505 if fetched.why:
506 fail(f"origin could not be fetched: {fetched.why}")
507 for line in store_lines(fetched):
508 print(line)
511def start_here(
512 root: Path,
513 repo: Repository,
514 branch: str,
515 *,
516 base: str = "main",
517 parent: str = "",
518 started: str = "",
519) -> None:
520 """Start *branch* in this checkout from ``origin/<base>``, or re-enter it.
522 The in-place half of ``start``, which the balancer's submit calls
523 too ([livery.workshop._balance.submit][]). A local *branch* that is
524 not finished work is switched to as it stands; one whose pull
525 request merged goes, and the start begins fresh. ``origin/<base>``
526 is read as the last fetch left it, so `fetch_base` comes first.
527 The working tree is the caller's to check: a dirty one carries
528 its changes onto the branch. *parent* records the branch ``fm
529 submit`` targets until it merges; *started* is how the branch is
530 announced, its name when empty.
531 """
532 if _kept(repo, root, branch):
533 git.switch(root, branch)
534 print(f" already started: back on {branch}")
535 return
536 git.run(root, "checkout", "-b", branch, f"origin/{base}")
537 print(f" on {started or branch}")
538 _record_parent(root, branch, parent)
541def _started_at(root: Path, branch: str, path: Path) -> Path | None:
542 """Where *branch*'s started work is: its worktree, another tree, or this checkout.
544 None when no tree holds the branch. The branch alone is not started
545 work: a merged one outlives the worktree its merge removed.
546 """
547 from livery.workshop._submit import worktree_for
549 if path.is_dir():
550 return path
551 if tree := worktree_for(root, branch):
552 return Path(tree)
553 if git.current_branch(root) == branch:553 ↛ 554line 553 didn't jump to line 554 because the condition on line 553 was never true
554 return root
555 return None
558def _kept(repo: Repository, root: Path, branch: str) -> bool:
559 """Whether *branch* exists and stays to be re-entered; the line says why.
561 A branch whose pull request merged and took its tip is finished
562 work: the janitor's rule ([livery.workshop._sweep.sweep_branch][])
563 drops it here, and the start begins fresh from the base. Any other
564 branch keeps its commits.
565 """
566 if not git.local_branch_exists(root, branch):
567 return False
568 from livery.workshop._sweep import sweep_branch
570 went, line = sweep_branch(
571 root,
572 branch,
573 current=git.current_branch(root),
574 dry_run=False,
575 repo=repo,
576 )
577 print(f" {line}")
578 return not went
581def _record_parent(root: Path, branch: str, parent: str) -> None:
582 """Record *parent* as the base ``fm submit`` targets for *branch*; none, nothing.
584 The parent's pushed tip is recorded beside it: *branch* starts
585 there, so the commits after it are the branch's own, which is what
586 ``fm sync`` moves when the parent moves or merges.
587 """
588 if not parent:
589 return
590 _stack.record_stack(root, branch, parent, git.sha_of(root, f"origin/{parent}"))
591 print(f" parent: {parent} (`{footman.prog()} submit` targets it until it merges)")
594def _issue_for(repo: Repository, ref: str, *, type: str, body: str) -> Issue:
595 """The issue *ref* names, or the one a quoted title files."""
596 number, title = parse_ref(ref)
597 if number:
598 found = repo.issue.get(number)
599 if found is None:
600 fail(f"issue #{number} does not exist in this repository")
601 return found
602 try:
603 work = repo.issue.create(title, body=body, labels=(f"kind/{type or 'feat'}",))
604 except ForgeError:
605 work = repo.issue.create(title, body=body)
606 print(" Note: the kind label was refused; filed without it")
607 print(f" filed #{work.number}: {work.title}")
608 return work
611def _assign(root: Path, repo: Repository, work: Issue) -> None:
612 """Put the caller on the issue; at the limit or a refusal, warn and go on."""
613 me = _me(repo)
614 limit = assignee_limit(root)
615 if me not in work.assignees and len(work.assignees) >= limit:
616 listed = ", ".join(work.assignees)
617 print(
618 f" Warning: #{work.number} is assigned to {listed} and the"
619 f" workspace's assignee limit is {limit}, so you will not be"
620 " listed as working on it until something lands. Coordinate"
621 " with them; `[issues] assignees` in workshop.toml raises the"
622 " limit if this issue takes more people."
623 )
624 return
625 try:
626 if me and me not in work.assignees:
627 repo.issue.assign(work.number, me)
628 except ForgeError as error:
629 print(
630 f" Note: could not assign the issue ({error}); others"
631 " will not see you working on it, so communicate."
632 )
635def _me(repo: Repository) -> str:
636 try:
637 from livery.workshop._extensions import workspace_root
638 from livery.workshop._forge_lane import this_forge
640 root = workspace_root()
641 return this_forge(root).whoami() if root is not None else ""
642 except Exception:
643 return ""
646def _launch_agent(
647 name: str, path: Path, briefing: str, branch: str, prompt: str
648) -> None:
649 """Hand the work to the agent in its worktree; a terminal handoff.
651 The briefing is minimal on purpose: the worktree carries the
652 project's own instructions, and repeating them here would drift.
653 Nothing after the exec runs.
654 """
655 briefing = f"{briefing}\n\nYou are on branch {branch}."
656 if prompt:656 ↛ 657line 656 didn't jump to line 657 because the condition on line 656 was never true
657 briefing += f"\n\n{prompt}"
658 executable = "claude" if name in ("", "claude") else name
659 os.chdir(path)
660 try:
661 os.execvp(executable, [executable, briefing])
662 except OSError:
663 fail(f"agent '{executable}' is not installed on this machine")
666def _open_work(path: Path, how: str) -> None:
667 from livery.workshop._env_tasks import START_PATH_VARIABLE
669 target = os.environ.get(START_PATH_VARIABLE, "")
670 if target and not how:
671 # The shell function around `start` names a file: the caller's
672 # own shell enters the worktree, so no child shell is opened.
673 Path(target).write_text(str(path), "utf-8")
674 print(f" the worktree is at {path}; this shell enters it")
675 return
676 mode = how or ("shell" if footman.attended() else "none")
677 if mode == "code":
678 try:
679 tools.code.opts(nofail=True, recorded=False)(str(path))
680 except (OSError, tools.ToolError):
681 # Opening an editor is a convenience, never the work: a
682 # machine without `code` gets the path instead.
683 print(f" `code` is not on PATH; the worktree is at {path}")
684 elif mode == "shell":684 ↛ 685line 684 didn't jump to line 685 because the condition on line 684 was never true
685 from livery.workshop._shell import launch_shell
687 os.chdir(path)
688 launch_shell("")
689 elif mode == "none":689 ↛ 692line 689 didn't jump to line 692 because the condition on line 689 was always true
690 print(f" the worktree is at {path}")
691 else:
692 fail(f"unknown open mode {how!r}: shell, code, or none")
695@issue.task(name="stop")
696def issue_stop(
697 ref: Annotated[Arg[str], ask(), suggest(_open_numbers, strict=False)] = "",
698 discard: Annotated[bool, doc("destroy work that exists nowhere else")] = False,
699) -> None:
700 """Stop working on an issue: unassign, clean up the local state.
702 The remote branch is never touched; while the issue is open it
703 stays the pool's copy. Work that exists nowhere else is never
704 destroyed without ``--discard``, and the refusal names what it
705 found: a delta the remote is missing, a remote gone while the
706 issue is open (exceptional), or an issue already closed.
707 """
708 root = _workspace()
709 repo = _repo(root)
710 number = 0
711 if ref:
712 number, _title = parse_ref(ref)
713 if not number:713 ↛ 714line 713 didn't jump to line 714 because the condition on line 713 was never true
714 fail("issue.stop takes a number; a title names nothing to stop")
715 else:
716 match = _BRANCH_RE.match(git.current_branch(root))
717 if match is None:
718 fail(
719 "not on an issue branch: name the issue"
720 f" (`{footman.prog()} issue.stop 123`) or run it from the branch."
721 )
722 number = int(match.group(1))
723 branch = _find_branch(root, number)
724 if not branch:724 ↛ 725line 724 didn't jump to line 725 because the condition on line 724 was never true
725 fail(f"no branch for issue #{number} exists locally or on the remote")
727 work = repo.issue.get(number)
728 state = work.state if work is not None else "unknown"
729 remote_exists = branch in git.remote_branches(root, "")
730 merged_head = ""
731 try:
732 landed = merged_pull_request(repo, root, branch)
733 merged_head = landed.head_sha if landed is not None else ""
734 except ForgeError:
735 merged_head = ""
736 only_local = (
737 only_local_work(root, branch, merged_head=merged_head)
738 if git.local_branch_exists(root, branch)
739 else ""
740 )
741 if only_local and not discard:
742 if state == "closed":
743 fail(
744 f"issue #{number} is already closed, but this branch holds"
745 f" {only_local} that exists nowhere else. Push it somewhere"
746 " it matters, or pass --discard to destroy it."
747 )
748 if not remote_exists:
749 fail(
750 f"the remote branch for issue #{number} is gone while the"
751 f" issue is still open, and this branch holds {only_local}."
752 " That is not a state stop creates; someone removed the"
753 " branch. Push the branch back, or pass --discard to"
754 " destroy the local work."
755 )
756 fail(
757 f"this branch holds {only_local} that the remote branch does"
758 " not. Push first (`git push`), or pass --discard to destroy"
759 " the delta; the remote branch stays as the pool's copy."
760 )
762 if work is not None and state == "open":762 ↛ 769line 762 didn't jump to line 769 because the condition on line 762 was always true
763 try:
764 repo.issue.unassign(number)
765 print(f" unassigned you from #{number}")
766 except ForgeError as error:
767 print(f" Note: could not unassign ({error}); continuing")
769 removed = _remove_local(root, branch)
770 what = " and ".join(removed) if removed else "nothing local to remove"
771 print(f" stopped #{number}: {what}; the remote branch stays")
774def _remove_local(root: Path, branch: str) -> list[str]:
775 """Remove the branch's worktree and local branch; what was removed."""
776 removed: list[str] = []
777 tree = worktree_for(root, branch)
778 if tree:
779 git.run(root, "worktree", "remove", "--force", tree)
780 print(f" removed worktree {tree}")
781 removed.append("the worktree")
782 elif git.current_branch(root) == branch:
783 git.switch(root, "main")
784 if git.local_branch_exists(root, branch):
785 git.delete_branch(root, branch)
786 removed.append("the local branch")
787 return removed
790def _held_by_pull_request(repo: Repository, root: Path, branch: str) -> str:
791 """Why a close keeps *branch* and its worktree; ``""`` when nothing keeps them.
793 An open pull request from *branch* holds them: the forge closes a
794 pull request unmerged once its head branch is deleted. A forge that
795 cannot answer holds them as well, since an unanswered question is
796 never read as "no pull request".
797 """
798 what = f"{branch} and its worktree" if worktree_for(root, branch) else branch
799 try:
800 pull = repo.pr.find_by_head(branch)
801 except ForgeError as error:
802 return (
803 f"kept {what}: the forge could not say whether a PR is open"
804 f" from it ({error}); ask again when it answers"
805 )
806 if pull is None or pull.state != "open":
807 return ""
808 return f"kept {what}: PR #{pull.number} is open from it; merge or close it first"
811def _close_with_record(
812 repo: Repository, number: int, reason: str, message: str, where: str
813) -> None:
814 """Comment why the issue ended and where its branch went, then close it."""
815 note = f"closed: {reason}"
816 if message:
817 note += f"\n\n{message}"
818 if where:
819 note += f"\n\n{where}"
820 repo.issue.comment(number, note)
821 repo.issue.close(number)
822 print(f" closed #{number}: {reason}")
825@issue.task(name="close", interactive=True)
826def issue_close(
827 ref: Annotated[Arg[str], ask(), suggest(_open_numbers, strict=False)] = "",
828 reason: Annotated[str, doc("why: done, wontfix, duplicate, stale, ...")] = "",
829 message: Annotated[str, doc("free-text detail for the close comment")] = "",
830 keep_branch: Annotated[bool, doc("retain the local and remote branch")] = False,
831 discard: Annotated[bool, doc("destroy work that exists nowhere else")] = False,
832) -> None:
833 """Close the issue itself, and remove the branch it was worked on.
835 An open pull request from the issue's branch keeps the branch and
836 its worktree: deleting the head branch makes the forge close the
837 pull request unmerged, and the branch may carry work for another
838 issue. The close then ends the issue alone and names the pull
839 request, to be merged or closed first. A forge that cannot say
840 whether such a pull request is open keeps them too, and the line
841 names the forge's error. A pull request that already merged means
842 the work landed, the supplied reason no longer applies, and the
843 close becomes cleanup: "issue already resolved". Otherwise the
844 worktree, the local branch, and the remote branch are removed by
845 default, with the removed head sha recorded in the close comment;
846 ``--keep-branch`` retains them.
847 """
848 if not ref:848 ↛ 849line 848 didn't jump to line 849 because the condition on line 848 was never true
849 fail(
850 "name the issue to close:"
851 f" `{footman.prog()} issue.close 123 --reason=wontfix`"
852 )
853 if not reason:853 ↛ 854line 853 didn't jump to line 854 because the condition on line 853 was never true
854 fail(
855 "closing needs a --reason (done, wontfix, duplicate, stale,"
856 " ...): the pool reads why the work ended."
857 )
858 root = _workspace()
859 repo = _repo(root)
860 number, _title = parse_ref(ref)
861 if not number:861 ↛ 862line 861 didn't jump to line 862 because the condition on line 861 was never true
862 fail("issue.close takes a number; a title names nothing to close")
863 work = repo.issue.get(number)
864 if work is None:864 ↛ 865line 864 didn't jump to line 865 because the condition on line 864 was never true
865 fail(f"issue #{number} does not exist in this repository")
867 git.fetch(root)
868 branch = _find_branch(root, number)
869 tip = git.any_head(root, branch) if branch else ""
871 held = _held_by_pull_request(repo, root, branch) if branch else ""
872 if held:
873 print(f" {held}")
874 _close_with_record(repo, number, reason, message, held)
875 return
877 # The destruction rule runs before anything is removed: a refusal
878 # that checks afterwards would be checking a branch that is
879 # already gone. The merged pull request is read first: its head
880 # decides what the merge took.
881 try:
882 landed = merged_pull_request(repo, root, branch) if branch else None
883 except ForgeError as error:
884 fail(
885 f"the forge could not say whether {branch}'s pull request merged"
886 f" ({error}); nothing was removed and #{number} stays open."
887 " Run the close again when the forge answers."
888 )
889 merged = landed is not None
890 only_local = (
891 only_local_work(root, branch, merged_head=landed.head_sha if landed else "")
892 if branch and git.local_branch_exists(root, branch)
893 else ""
894 )
896 if merged:
897 if reason:897 ↛ 899line 897 didn't jump to line 899 because the condition on line 897 was always true
898 print(" Note: the PR merged, so the supplied reason does not apply")
899 if git.local_branch_exists(root, branch):899 ↛ 907line 899 didn't jump to line 907 because the condition on line 899 was always true
900 if only_local and not discard:
901 print(
902 f" kept {branch}: it holds {only_local}; pass --discard"
903 " to remove it"
904 )
905 else:
906 _remove_local(root, branch)
907 if work.state == "open":907 ↛ 910line 907 didn't jump to line 910 because the condition on line 907 was always true
908 repo.issue.comment(number, "closed: resolved by the merged PR")
909 repo.issue.close(number)
910 print(" issue already resolved, nothing left to do")
911 return
913 if only_local and not discard and not keep_branch:
914 fail(
915 f"the branch for #{number} holds {only_local} that exists"
916 " nowhere else, and close removes branches by default. Pass"
917 " --keep-branch to retain them, or --discard to destroy the"
918 " work with the issue."
919 )
921 removed_sha = ""
922 if branch and not keep_branch:
923 # The tip was read before the branch is deleted: the close
924 # comment records where the work got to.
925 removed_sha = tip
926 _remove_local(root, branch)
927 if branch in git.remote_branches(root, ""):927 ↛ 931line 927 didn't jump to line 931 because the condition on line 927 was always true
928 git.run(root, "push", "origin", "--delete", branch)
929 print(f" removed the remote branch {branch}")
931 where = f"removed branch {branch} at {removed_sha}" if removed_sha else ""
932 _close_with_record(repo, number, reason, message, where)
935@issue.task(name="reopen")
936def issue_reopen(
937 ref: Annotated[Arg[str], ask()] = "",
938) -> None:
939 """Reopen a closed issue and put yourself on it, as start does.
941 For an issue a merge closed before its work was done (a branch
942 that carried a plan or a pinning test under the issue's number).
943 Reopening an open issue is a no-op, and the assignment follows
944 start's rules: the workspace's limit and a refused write warn
945 and go on.
946 """
947 if not ref:
948 fail(f"name the issue to reopen: `{footman.prog()} issue.reopen 123`")
949 root = _workspace()
950 repo = _repo(root)
951 number, _title = parse_ref(ref)
952 if not number:952 ↛ 953line 952 didn't jump to line 953 because the condition on line 952 was never true
953 fail("issue.reopen takes a number; a title names nothing to reopen")
954 work = repo.issue.get(number)
955 if work is None:
956 fail(f"issue #{number} does not exist in this repository")
957 if work.state == "open":
958 print(f" #{number} is already open")
959 else:
960 repo.issue.reopen(number)
961 print(f" reopened #{number}: {work.title}")
962 _assign(root, repo, work)