Let a project's config name a working branch per epic that chunks branch off and merge into
CI / tests (pull_request) Successful in 5m4s
CI / tests (pull_request) Successful in 5m4s
This commit is contained in:
@@ -121,6 +121,8 @@ A project whose pull requests need a human's approval sets `wait-for-approval =
|
||||
|
||||
A project whose team merges its pull requests itself sets `merge = "human"`. `chunk-pr merge` then brings the branch level with origin's default branch, finishes the chunk's plan items, waits for the checks and marks the pull request ready, but leaves the merge to a person. A plan or changelog kept in the checkout is finished on the branch, so it lands with that merge; one kept in Jira, or in the config's folder, is finished at once; where you close the pull request unmerged, file the item again. A do-epic chunk parks until the pull request is merged, and its window's name says `awaits your merge`. The chunk resumes and brings the branch level again once the pull request conflicts with the default branch. It does so too once the branch is behind a default branch whose protection, on GitHub, requires an up-to-date branch. loop-claude doesn't start a chunk for an item that a ready pull request finishes. Once no item left in the release can start and one awaits a merge, loop-claude stops and names the pull requests to merge; run it again after you merge one. The first chunk after a merge runs `chunk-pr clean` in the worktree the merged pull request left, where nobody pushed to the pull request after the chunk did. Nobody works on a pull request that awaits your merge. To have a reviewer's comment answered, turn the pull request back into a draft: a chunk then takes its item up again. Left out, the setting is `"chunk"`: the chunk merges.
|
||||
|
||||
A project whose team wants an epic's work in one pull request sets `epic-branch`, a template with `{epic}` for the epic's key, such as `epic-branch = "{epic}"`. The plan must name a Jira epic. Each chunk then branches off the epic's working branch, here `ABC-123` for the epic ABC-123, and `chunk-pr` opens its pull request into that branch and merges it there without a person, also under `merge = "human"` and `wait-for-approval`: those two keep guarding the default branch. `chunk-preflight`, and do-epic as a chunk starts, make the branch on origin off the default branch, or merge the default branch into it with a merge commit. Where that merge conflicts, they stop, and a person merges it. That needs git 2.38 or later. Once the epic's last issue has landed, `chunk-pr open-epic <epic's key> <title>` brings the branch level once more and opens the pull request from it into the default branch, which a person merges. An auto-reviewer that reviews only pull requests into the default branch is asked by a comment: set `review-request-comment` to the comment's text, such as `"@reviewbot review"`. `chunk-pr ready` then posts it on a pull request into the working branch, and `chunk-pr push` pushes later commits and posts it again.
|
||||
|
||||
For a client's project, use one sandbox VM per client, so that one client's code, transcripts and credentials never share a machine with another's. What the client's repo should not hold lives in the config's folder, at paths written as `folder:<path>`, as `project-config --help` shows: the plan, the working rules in an `AGENTS.md` I write for the agents, the records, and the goals and audience, as `goals-and-audience = "folder:goals.md"`. Name that file `goals.md`, so the rules for goals and audience load when an agent writes it. A file outside the checkout has no commits in the checkout's history, so four things are not supported for it yet. `score-outcomes` and loop-claude's routing figures count a project's chunks only where `todo.md`, `docs/comprehension-history.md` and `docs/reading-cost.md` are at those paths in the checkout; otherwise each says so, and the loop goes on. For a plan or a comprehension history outside the checkout, `larv-review` says it cannot tell whether a scoring run is owed, and for such a history it cannot find a paired ruling's base. For a plan outside the checkout, chunk-preflight and loop-claude don't see a release whose last item has shipped, and say that its release review and its cut are yours to call. And rule-hook checks a plan outside the checkout on every call, not only when it changed.
|
||||
|
||||
A client that plans in Jira Cloud names an epic as its project's plan: `plan = "jira:https://acme.atlassian.net/browse/ABC-12"`, which is `jira:` and the epic's address as the browser shows it. The plan is then the epic's open child issues, in Jira's backlog order, which the team sets, apart from the rank `todo-item add` gives an issue it files. An issue in a done status is a finished item. Each part of an item comes from one part of its issue:
|
||||
@@ -158,6 +160,7 @@ The last line prints each setting's path once the config is complete.
|
||||
- `config.toml` fits do-epic to a team whose own automation moves issues, such as a CI job that moves an issue when its pull request merges. Two settings do:
|
||||
- `jira-unblocking-statuses` lists the statuses at which an issue's work has landed though Jira doesn't count it done yet, such as `["Release Ready"]`, in upper or lower case. An issue in one of them takes no chunk and no longer blocks the issues it blocks, and `--status` names the statuses beside each blocker. A status Jira counts as done always does both. The release reviews, which are the epic's last chunk, still wait until Jira counts every issue done: run `do-epic <EPIC-KEY>` then, to start them.
|
||||
- `jira-automation-moves-issues = true` keeps do-epic from moving the issue of a finished chunk in a repo: the automation moves it, and do-epic waits for that move before it starts what the issue blocks. An issue without a repo has no pull request, so do-epic still moves it, with `jira-finish-transition`. The setting needs `jira-unblocking-statuses`, which names the status the automation gives an issue whose pull request merged.
|
||||
- `config.toml` names the statuses do-epic itself gives an issue whose chunk merges into an epic's working branch, in a repo whose config sets `epic-branch`. A team's automation moves an issue only for a pull request into the default branch, so there do-epic makes both moves, whatever `jira-automation-moves-issues` says. `jira-pull-request-open-status`, such as `"Code Review"`, is the status of an issue whose chunk parks with its pull request open; a pull request that opens and merges within one run of the worker skips it. `jira-pull-request-merged-status`, such as `"Release Ready"`, is the status once the pull request has merged into the working branch. `jira-unblocking-statuses` must list it, and an issue that has it counts as done when the release reviews and the finishing chunk fall due, since both come before a person merges the working branch. Without it, a finished chunk's issue moves to done, and where `jira-automation-moves-issues` is set do-epic stops and asks you to move it.
|
||||
- `config.toml` also says how a starting chunk's issue shows on its team's board. A starting chunk always assigns its issue to the account do-epic works as, unless someone else holds it; that issue keeps its assignee, and moves and joins the sprint like any other. `jira-start-transition` names the workflow transition that then moves the issue, such as `"In Progress"`; an issue whose work has started already keeps its status. `jira-sprint-board` is the ID of the board whose active sprint the issue joins, such as `6`. Where a setting is left out, do-epic doesn't take its step.
|
||||
- `config.toml` may set `jira-finding-type`, the issue type do-epic files a finding as, and `jira-review-type`, the one it files a repo's release review as, such as `"Feature"` and `"Chore"`. Both are Task where left out. do-epic doesn't file anything where the Jira project lacks the type, and says which types it has.
|
||||
- `config.toml` may set `sub-task-summary`, which shapes the summary of each sub-task do-epic files for an issue that changes several repos, such as `sub-task-summary = "{label}: {Summary}"`. `{label}` is the team's label for the repo, else the repo's name, and `{Summary}` is the issue's summary with a capital first letter. It must hold `{Summary}`. Without it a summary is `[<repo>] <the issue's summary>`.
|
||||
@@ -196,7 +199,7 @@ It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that thro
|
||||
|
||||
Install puts only `loop-claude` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout. Those under `~/.claude` are the release's; test a change to one from `~/code/claude-config/bin`. The tools are listed in alphabetical order, and the packages under `bin/` follow under their own heading.
|
||||
|
||||
- `chunk-pr open|sync|ready|merge|clean` opens a chunk's pull request as a draft, brings its branch level with origin's default branch, marks it ready and merges it once its checks pass, with `gh` on a GitHub origin and `tea` elsewhere. The chunks of one project merge one at a time: in its turn, `merge` brings the branch level again, finishes the plan items its `--finish` flags name, and waits for the checks. Under `merge = "human"` it then marks the pull request ready and leaves the merge to a person. Once the pull request is merged, `clean` removes the chunk's worktree and branch and fast-forwards the main checkout. `chunk-pr --help` states the steps.
|
||||
- `chunk-pr open|sync|ready|push|merge|clean|open-epic` opens a chunk's pull request as a draft, brings its branch level with origin's default branch, marks it ready and merges it once its checks pass, with `gh` on a GitHub origin and `tea` elsewhere. Where the project's config sets `epic-branch`, the pull request goes into the epic's working branch instead, `push` pushes later commits and asks the auto-reviewer for a review, and `open-epic` opens the pull request from that branch into the default branch. The chunks of one project merge one at a time: in its turn, `merge` brings the branch level again, finishes the plan items its `--finish` flags name, and waits for the checks. Under `merge = "human"` it then marks the pull request ready and leaves the merge to a person. Once the pull request is merged, `clean` removes the chunk's worktree and branch and fast-forwards the main checkout. `chunk-pr --help` states the steps.
|
||||
- `chunk-preflight` finds the mechanical facts a chunk starts from, and with `--worktree` makes its worktree; `loop-claude` runs it with `--worktree` before it routes each chunk, and `chunk-preflight --help` lists the facts.
|
||||
- `command-patterns [<version>] [--calls <file>]` prints a table of the shell command patterns a release's archived chunks ran, such as `tea pr create`, for an audit of the release, and with `--calls <file>` saves each call as a JSON line; `command-patterns --help` states the columns and the line's keys.
|
||||
- `compress-archives` gzips each transcript in loop-claude's archive and each file in the review folders 30 days after it last changed, keeping all of them; Install's crontab line runs it daily.
|
||||
@@ -239,7 +242,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
|
||||
- `deploy_release` imports `release_plan`'s `release_standing`.
|
||||
- `do_epic/` holds `do-epic`, the tool that drives one Jira epic. `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `planning.py` settles, before the chunks start, where each open issue is worked, its scores and the order the issues start in, through `split.py`, `repo_pick.py`, `issue_scores.py` and `ranking.py`. `scheduler.py` says which issues run now: as many as the epic's cap and each repo's `parallel-chunks` allow, and none in a repo where loop-claude runs chunks. `gates.py` reads once whether a chunk's pull request waits on its checks, an approval or a new review, and `parked.py` keeps each chunk that does in a state file, so it takes no running slot while it waits and goes on waiting after a reboot. `chunk_prompt.py` words what a chunk's worker reads. Through `findings.py` that worker files a finding as an issue of the epic, with `--file`, and appends a decision to its description, with `--record-decision`. `finish.py` ends an epic that holds no open issue: its finishing chunk files a release review of each repo the epic changed, has the human confirm each goal, and with `--close-epic` posts the summary on the epic and closes it. `config.py` reads its machine-wide settings, importing `project_config`'s settings and `model_routing`'s ladder file, and `epic_record.py` reads and writes an epic's description by section, language line and cap line, through `record_store`'s `EpicDescription`. `repos.py` finds a repo's checkout and project config by its name, and clones a missing checkout from the host and owner of the epic's other repos, through `forge`'s `url_beside`. `repo_pick.py` asks claude, by `repo-rule.md`, where an epic item is worked, and records the answer as a label on the issue. `split.py` has claude predict from the code which repos an item changes, and files a sub-task per repo under it where there are several. `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`. `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, posts comments, moves a finished chunk's issue to done, and closes the epic. `e2e/` holds `do-epic-e2e`.
|
||||
- `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), finds a pull request, lists the ready ones and reads its checks, once or until they settle (`pulls.py`), and reads a pull request's review state (`reviews.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release`, `do_epic` and `larv_review`.
|
||||
- `git_cli/` runs git for every tool (`git_repo.py`), and reads the git calls in a shell command (`git_command.py`).
|
||||
- `git_cli/` runs git for every tool (`git_repo.py`), reads the git calls in a shell command (`git_command.py`), and keeps an epic's working branch level with the default branch (`epic_branch.py`).
|
||||
- `judge_replay` imports `agent_cycle`'s judge and verdicts, and `chunk_driver`'s premises, records and `ANSWER_DESTINATIONS`.
|
||||
- `loop_claude` runs `chunk-preflight` as a process of its own.
|
||||
- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, do-epic, both replay tools and `reviewer-merge-trials`' driver use it.- `loop_state/` holds where loop-claude and do-epic keep their files (`paths.py`), which `rung_replay` reads too.
|
||||
|
||||
+133
-15
@@ -3,12 +3,24 @@
|
||||
usage: chunk-pr open <title> [<body>]
|
||||
chunk-pr sync
|
||||
chunk-pr ready [<title>]
|
||||
chunk-pr push
|
||||
chunk-pr merge [--finish <ID> [--changelog <bullet> | --no-changelog]]...
|
||||
chunk-pr clean
|
||||
chunk-pr open-epic <epic's key> <title> [<body>]
|
||||
|
||||
Run it in the chunk's worktree, on the chunk's branch. ready and merge act on the branch's open
|
||||
pull request only while its head is the commit checked out, so push before you run them.
|
||||
|
||||
Where the project's config sets `epic-branch` (`project-config --help`), a chunk's pull request
|
||||
goes into its epic's working branch, which chunk-preflight or do-epic recorded for the chunk's
|
||||
branch when the chunk began. There, each step below reads "origin's default branch" as that
|
||||
branch, with these differences:
|
||||
- merge merges the pull request itself, whatever `merge` and `wait-for-approval` say: those
|
||||
govern the pull request into the default branch, which open-epic opens;
|
||||
- ready and push ask for a review, where the config sets `review-request-comment`, by making
|
||||
that comment on the pull request;
|
||||
- clean still fast-forwards the main checkout to origin's default branch.
|
||||
|
||||
open pushes the branch, setting its upstream, and opens a draft pull request into origin's
|
||||
default branch. <title> is one line, as ~/.claude/CLAUDE.md → "Git, commits, and PRs"
|
||||
says, and <body> is the pull request's summary. On a branch that fits the config's `branch`
|
||||
@@ -25,6 +37,9 @@ ready marks the pull request ready for review. On Gitea a draft is a pull req
|
||||
starts with `WIP: `, so there it drops that prefix. Given <title>, one line, which it holds
|
||||
to the template as open does, it sets that
|
||||
as the pull request's title first; where that fails, the pull request stays a draft.
|
||||
push pushes the branch, setting its upstream. Where its pull request is open and goes into an
|
||||
epic's working branch, it then asks for a review as ready does. Use it for each push
|
||||
after ready there, and wait for that review as for any other.
|
||||
merge merges the pull request in its turn: the chunks of one project on this machine take
|
||||
turns, one at a time. Run it in the background. In its turn it:
|
||||
1. fetches origin and merges its default branch into the branch, as sync does;
|
||||
@@ -78,6 +93,13 @@ clean acts once the forge reports the branch's pull request merged at the com
|
||||
doesn't touch anything. Where the main checkout has uncommitted or untracked files, another
|
||||
branch checked out, or commits origin's default branch lacks, it leaves that as it was,
|
||||
still removes the worktree and the branch, and fails saying why.
|
||||
open-epic runs in any checkout of the repository, once the epic's last chunk has merged. It
|
||||
fetches origin and brings the working branch of the epic named level with origin's
|
||||
default branch, by a merge commit pushed to origin, or makes the branch where origin has
|
||||
none. Then it opens the pull request from that branch into the default branch, ready and
|
||||
titled <title>, and leaves it to a person to merge. Where the two don't merge cleanly it
|
||||
opens nothing and says how a person merges them. Where the pull request is open
|
||||
already, it opens no second one. It fails where the config sets no `epic-branch`.
|
||||
|
||||
It prints what it did, exit 0, or why it failed, exit 1.
|
||||
"""
|
||||
@@ -94,6 +116,8 @@ import typing
|
||||
|
||||
from chunk_pr.approval import approval, approved, awaited, left_to_a_person, left_to_park, PARKS, unanswered
|
||||
from forge.pulls import checks_passed, merged_pull, open_pull, required_checks
|
||||
from git_cli.git_repo import CHUNK_BASE
|
||||
from git_cli import epic_branch
|
||||
from failure import Failure
|
||||
from forge.commands import Forge, forge_of, gitea, Run, runner
|
||||
from project_config.main import located
|
||||
@@ -113,7 +137,7 @@ QUEUE_POLL_SECONDS = 10
|
||||
RULING = "^Ruling: "
|
||||
# The project's config, loaded once per step, on the first call that needs it.
|
||||
Config = typing.Callable[[], ProjectConfig | Failure]
|
||||
USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr sync | chunk-pr ready [<title>] | chunk-pr merge [--finish <ID> [--changelog <bullet> | --no-changelog]]... | chunk-pr clean"
|
||||
USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr sync | chunk-pr ready [<title>] | chunk-pr push | chunk-pr merge [--finish <ID> [--changelog <bullet> | --no-changelog]]... | chunk-pr clean | chunk-pr open-epic <epic's key> <title> [<body>]"
|
||||
|
||||
# Each forge's merge methods in the order merge prefers them, as the repository setting that allows the method and the method's name in the forge's merge call. A merge commit and a fast-forward keep the branch's commits as they are; a rebase or a squash rewrites them.
|
||||
METHODS: dict[Forge, tuple[tuple[str, str], ...]] = {
|
||||
@@ -142,7 +166,11 @@ def step(argv: list[str], run: Run, config: Config, parks: bool = False) -> str
|
||||
case ["sync"]:
|
||||
return synced(run, config)
|
||||
case ["ready", *title] if len(title) <= 1 and not any(given.startswith("-") for given in title):
|
||||
return Failure("give a title of one line") if title and not one_line(title[0]) else (misfit(title[0], run, config) if title else None) or marked_ready(run, title[0] if title else None)
|
||||
return Failure("give a title of one line") if title and not one_line(title[0]) else (misfit(title[0], run, config) if title else None) or readied(run, title[0] if title else None, config)
|
||||
case ["push"]:
|
||||
return pushed(run, config)
|
||||
case ["open-epic", epic, title, *body] if len(body) <= 1 and not any(given.startswith("-") for given in (epic, title)):
|
||||
return Failure("give a title of one line") if not one_line(title) else epic_opened(epic, title, body[0] if body else "", run, config)
|
||||
case ["merge", *given]:
|
||||
finishes = finishes_of(given)
|
||||
return Failure(USAGE) if finishes is None else merged(run, config, time.sleep, finishes=finishes, parks=parks)
|
||||
@@ -192,6 +220,22 @@ def default_branch(run: Run) -> str | Failure:
|
||||
return default.strip().removeprefix("origin/")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Base:
|
||||
"""The branch a chunk's pull request merges into. to_epic says it is an epic's working branch, which the chunk merges into whatever the config says of the default branch: `merge = "human"` and `wait-for-approval` govern only the epic branch's own pull request (docs/decisions.md → `epic-branch: an epic's chunks branch off and merge into a working branch …`)."""
|
||||
branch: str
|
||||
to_epic: bool
|
||||
|
||||
|
||||
def base_of(branch: str, run: Run) -> Base | Failure:
|
||||
"""The Base of the pull request from branch: the epic's working branch the checkout records for it (`git_repo.record_chunk_base`), else origin's default branch."""
|
||||
recorded = run(["git", "config", "--get", f"branch.{branch}.{CHUNK_BASE}"])
|
||||
if not isinstance(recorded, Failure) and recorded.strip():
|
||||
return Base(recorded.strip(), True)
|
||||
default = default_branch(run)
|
||||
return default if isinstance(default, Failure) else Base(default, False)
|
||||
|
||||
|
||||
def pull(run: Run) -> tuple[Forge, str, str] | Failure:
|
||||
"""The forge, the number of the branch's open pull request at its head, and that head."""
|
||||
found = checkout(run)
|
||||
@@ -209,10 +253,10 @@ def opened(title: str, body: str, run: Run) -> str | Failure:
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
forge, branch, head = found
|
||||
base = default_branch(run)
|
||||
base = base_of(branch, run)
|
||||
if isinstance(base, Failure):
|
||||
return base
|
||||
if branch == base:
|
||||
if branch == base.branch:
|
||||
return Failure(f"{branch} is origin's default branch; open the pull request from the chunk's branch")
|
||||
pushed = run(["git", "push", "--quiet", "--set-upstream", "origin", branch])
|
||||
if isinstance(pushed, Failure):
|
||||
@@ -223,7 +267,7 @@ def opened(title: str, body: str, run: Run) -> str | Failure:
|
||||
if isinstance(number, Failure):
|
||||
return number
|
||||
command = ["gh", "pr", "create"] if forge == "gh" else ["tea", "pulls", "create"]
|
||||
created = run([*command, "--draft", "--head", branch, "--base", base, "--title", title, "--body" if forge == "gh" else "--description", body])
|
||||
created = run([*command, "--draft", "--head", branch, "--base", base.branch, "--title", title, "--body" if forge == "gh" else "--description", body])
|
||||
if isinstance(created, Failure):
|
||||
return created
|
||||
number = open_pull(forge, branch, head, run)
|
||||
@@ -237,15 +281,15 @@ def synced(run: Run, config: Config) -> str | Failure:
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
_, branch, _ = found
|
||||
base = default_branch(run)
|
||||
base = base_of(branch, run)
|
||||
if isinstance(base, Failure):
|
||||
return base
|
||||
if branch == base:
|
||||
if branch == base.branch:
|
||||
return Failure(f"{branch} is origin's default branch; sync the chunk's branch")
|
||||
level = levelled(run, branch, base)
|
||||
level = levelled(run, branch, base.branch)
|
||||
if isinstance(level, Failure):
|
||||
return level
|
||||
done = f"Merged origin/{base} into {branch}." if level else f"{branch} already holds origin/{base}."
|
||||
done = f"Merged origin/{base.branch} into {branch}." if level else f"{branch} already holds origin/{base.branch}."
|
||||
loaded = config()
|
||||
if isinstance(loaded, Failure):
|
||||
return Failure(f"{done.removesuffix('.')}, but the plan to check cannot be found: {loaded.reason}")
|
||||
@@ -278,6 +322,18 @@ def levelled(run: Run, branch: str, base: str, resolve: str = "resolve them and
|
||||
return True
|
||||
|
||||
|
||||
def readied(run: Run, title: str | None, config: Config) -> str | Failure:
|
||||
"""Mark the branch's pull request ready, then ask for a review of it as `review_asked` does."""
|
||||
found = pull(run)
|
||||
marked = found if isinstance(found, Failure) else marked_ready(run, title)
|
||||
if isinstance(found, Failure) or isinstance(marked, Failure):
|
||||
return marked
|
||||
asked = review_asked(found[0], found[1], run, config)
|
||||
if isinstance(asked, Failure):
|
||||
return Failure(f"marked pull request #{found[1]} ready, but could not ask for a review: {asked.reason}")
|
||||
return f"{marked[:-1]}, and asked for a review with “{asked}”." if asked else marked
|
||||
|
||||
|
||||
def marked_ready(run: Run, title: str | None) -> str | Failure:
|
||||
found = pull(run)
|
||||
if isinstance(found, Failure):
|
||||
@@ -295,6 +351,65 @@ def marked_ready(run: Run, title: str | None) -> str | Failure:
|
||||
return f"Marked pull request #{number} ready, titled “{title}”." if title is not None else f"Marked pull request #{number} ready."
|
||||
|
||||
|
||||
def pushed(run: Run, config: Config) -> str | Failure:
|
||||
"""Push the branch checked out, and ask for a review of its open pull request as `review_asked` does."""
|
||||
found = checkout(run)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
forge, branch, head = found
|
||||
sent = run(["git", "push", "--quiet", "--set-upstream", "origin", branch])
|
||||
number = sent if isinstance(sent, Failure) else open_pull(forge, branch, head, run)
|
||||
if isinstance(number, Failure):
|
||||
return number
|
||||
asked = review_asked(forge, number, run, config) if number is not None else None
|
||||
if isinstance(asked, Failure):
|
||||
return Failure(f"pushed {branch}, but could not ask for a review: {asked.reason}")
|
||||
return f"Pushed {branch}, and asked for a review of pull request #{number} with “{asked}”." if asked else f"Pushed {branch}."
|
||||
|
||||
|
||||
def review_asked(forge: Forge, number: str, run: Run, config: Config) -> str | None | Failure:
|
||||
"""Comment on the pull request numbered number with the config's `review-request-comment`, where the pull request goes into an epic's working branch: a forge's auto-reviewer may review only pull requests into the default branch unless asked. The comment made; None where the config names none or the pull request goes into the default branch."""
|
||||
branch = answers(run, ["symbolic-ref", "--short", "HEAD"])
|
||||
base = branch if isinstance(branch, Failure) else base_of(branch[0], run)
|
||||
if isinstance(base, Failure):
|
||||
return base
|
||||
if not base.to_epic:
|
||||
return None
|
||||
loaded = config()
|
||||
if isinstance(loaded, Failure) or loaded.review_request_comment is None:
|
||||
return loaded if isinstance(loaded, Failure) else None
|
||||
comment = loaded.review_request_comment
|
||||
made = run(["gh", "pr", "comment", number, "--body", comment] if forge == "gh" else ["tea", "comment", number, comment])
|
||||
return made if isinstance(made, Failure) else comment
|
||||
|
||||
|
||||
def epic_opened(epic: str, title: str, body: str, run: Run, config: Config) -> str | Failure:
|
||||
"""Bring the working branch of the epic with the key epic level with origin's default branch, then open its pull request into that branch, ready, for a person to merge."""
|
||||
loaded = config()
|
||||
if isinstance(loaded, Failure):
|
||||
return loaded
|
||||
if loaded.epic_branch is None:
|
||||
return Failure("the project's config sets no `epic-branch`, so the epic has no branch to open a pull request from (`project-config --help`)")
|
||||
branch = templates.epic_branch(loaded.epic_branch, epic)
|
||||
found = answers(run, ["remote", "get-url", "origin"])
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
default = default_branch(run)
|
||||
if isinstance(default, Failure):
|
||||
return default
|
||||
forge = forge_of(found[0])
|
||||
level = epic_branch.levelled(branch, f"origin/{default}", run=lambda *args, cwd=None, timeout=None, guarded=False, errors="strict": run(["git", *args]))
|
||||
head = level if isinstance(level, Failure) else answers(run, ["rev-parse", f"origin/{branch}"])
|
||||
number = head if isinstance(head, Failure) else open_pull(forge, branch, head[0], run)
|
||||
if isinstance(number, Failure):
|
||||
return number
|
||||
if number is not None:
|
||||
return f"{level} Pull request #{number} from {branch} is open already."
|
||||
command = ["gh", "pr", "create"] if forge == "gh" else ["tea", "pulls", "create"]
|
||||
created = run([*command, "--head", branch, "--base", default, "--title", title, "--body" if forge == "gh" else "--description", body])
|
||||
return created if isinstance(created, Failure) else f"{level} Opened the pull request from {branch} into {default}, which a person merges."
|
||||
|
||||
|
||||
def finishes_of(given: list[str]) -> list[list[str]] | None:
|
||||
"""`todo-item finish`'s arguments for each item that merge's flags name, in their order; None where the flags are malformed."""
|
||||
finishes, rest = [], given
|
||||
@@ -320,15 +435,18 @@ def merged(run: Run, config: Config, sleep: typing.Callable[[float], None], fini
|
||||
loaded = config()
|
||||
if isinstance(loaded, Failure):
|
||||
return loaded
|
||||
by_human = loaded.merge == "human"
|
||||
waits = awaited(forge, loaded.wait_for_approval, by_human)
|
||||
branch = answers(run, ["symbolic-ref", "--short", "HEAD"])
|
||||
base = branch if isinstance(branch, Failure) else base_of(branch[0], run)
|
||||
if isinstance(base, Failure):
|
||||
return base
|
||||
by_human = loaded.merge == "human" and not base.to_epic
|
||||
waits = awaited(forge, loaded.wait_for_approval and not base.to_epic, by_human)
|
||||
if isinstance(waits, Failure):
|
||||
return waits
|
||||
method = merge_method(forge, run)
|
||||
if isinstance(method, Failure):
|
||||
return method
|
||||
base = default_branch(run)
|
||||
required = base if isinstance(base, Failure) else required_checks(forge, base, run)
|
||||
required = required_checks(forge, base.branch, run)
|
||||
if isinstance(required, Failure):
|
||||
return required
|
||||
queue = answers(run, ["rev-parse", "--path-format=absolute", "--git-common-dir"])
|
||||
@@ -338,7 +456,7 @@ def merged(run: Run, config: Config, sleep: typing.Callable[[float], None], fini
|
||||
if isinstance(absent, Failure):
|
||||
return absent
|
||||
file = pathlib.Path(queue[0]) / QUEUE
|
||||
pull_request = Merging(forge, number, method, str(base), required, waits, by_human)
|
||||
pull_request = Merging(forge, number, method, base.branch, required, waits, by_human)
|
||||
while True:
|
||||
with turn(file, number, sleep) as untaken:
|
||||
taken = untaken or merge_turn(pull_request, finishes, loaded, run, sleep)
|
||||
@@ -356,7 +474,7 @@ def merged(run: Run, config: Config, sleep: typing.Callable[[float], None], fini
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Merging:
|
||||
"""A pull request that merge takes turns for: its forge and number, the merge method, the default branch it merges into with the checks that branch requires, whether it waits for an approval, and whether a person merges it."""
|
||||
"""A pull request that merge takes turns for: its forge and number, the merge method, the branch it merges into (`Base`) with the checks that branch requires, whether it waits for an approval, and whether a person merges it."""
|
||||
forge: Forge
|
||||
number: str
|
||||
method: str
|
||||
|
||||
@@ -55,6 +55,8 @@ class Checkout:
|
||||
self.open = open
|
||||
self.allowed = allowed
|
||||
self.statuses: list[str] = []
|
||||
# The epic's working branch the checkout records for the branch checked out; empty where it records none. Reading it is the one command the fake doesn't record.
|
||||
self.chunk_base = ""
|
||||
# What GitHub reports as the pull request's review decision on each read; the last one repeats.
|
||||
self.decisions = ["APPROVED"]
|
||||
# Set, what GitHub prints instead of a decision's JSON.
|
||||
@@ -82,9 +84,11 @@ class Checkout:
|
||||
return failed
|
||||
texts = {name: str(answer).strip() for name, answer in named.items()}
|
||||
paths = {name: pathlib.Path(texts[name]) for name in ("plan", "changelog", "comprehension-history") if texts.get(name, "").startswith("/")}
|
||||
return ProjectConfig("proj", pathlib.Path("/config"), pathlib.Path("/checkout"), paths, wait_for_approval=texts.get("wait-for-approval") == "true", merge=texts.get("merge", "chunk"), commit_title=texts.get("commit-title", "{summary}"), pull_request_title=texts.get("pull-request-title", "{summary}"), branch=texts.get("branch", "item-{id}"))
|
||||
return ProjectConfig("proj", pathlib.Path("/config"), pathlib.Path("/checkout"), paths, wait_for_approval=texts.get("wait-for-approval") == "true", merge=texts.get("merge", "chunk"), commit_title=texts.get("commit-title", "{summary}"), pull_request_title=texts.get("pull-request-title", "{summary}"), branch=texts.get("branch", "item-{id}"), epic_branch=texts.get("epic-branch"), review_request_comment=texts.get("review-request-comment"))
|
||||
|
||||
def __call__(self, command: list[str]) -> str | Failure:
|
||||
if command[:3] == ["git", "config", "--get"] and command[3].endswith(".chunk-base"):
|
||||
return self.chunk_base
|
||||
self.ran.append(command)
|
||||
if command[0] == ("tea" if self.github else "gh"):
|
||||
return Failure(f"{command[0]} on the wrong forge")
|
||||
@@ -1025,6 +1029,130 @@ class Clean(unittest.TestCase):
|
||||
self.assert_kept()
|
||||
|
||||
|
||||
class EpicBranch(unittest.TestCase):
|
||||
"""A chunk whose branch the checkout records as merging into the epic's working branch ABC-1, in a project whose config sets `epic-branch`."""
|
||||
|
||||
COMMENT_GH = ["gh", "pr", "comment", "12", "--body", "@reviewer review"]
|
||||
COMMENT_TEA = ["tea", "comment", "12", "@reviewer review"]
|
||||
|
||||
def checkout(self, origin: str = GITHUB, open: bool = True, comment: bool = True) -> Checkout:
|
||||
checkout = Checkout(origin, open=open)
|
||||
checkout.chunk_base = "ABC-1\n"
|
||||
checkout.answers[(PROJECT_CONFIG, "epic-branch")] = "{epic}\n"
|
||||
if comment:
|
||||
checkout.answers[(PROJECT_CONFIG, "review-request-comment")] = "@reviewer review\n"
|
||||
checkout.answers[("git", "rev-list", "--count", "HEAD..origin/ABC-1")] = "0\n"
|
||||
return checkout
|
||||
|
||||
def test_open_opens_the_draft_into_the_epic_branch(self):
|
||||
for origin, create in ((GITHUB, ["gh", "pr", "create", "--draft", "--head", "item-7", "--base", "ABC-1", "--title", "Do it", "--body", ""]), (GITEA, ["tea", "pulls", "create", "--draft", "--head", "item-7", "--base", "ABC-1", "--title", "Do it", "--description", ""])):
|
||||
with self.subTest(origin):
|
||||
checkout = self.checkout(origin, open=False)
|
||||
self.assertEqual(step(["open", "Do it"], checkout, checkout.config), "Opened draft pull request #12.")
|
||||
self.assertIn(create, checkout.ran)
|
||||
|
||||
def test_sync_merges_the_epic_branch_not_the_default_branch(self):
|
||||
checkout = self.checkout()
|
||||
checkout.answers[("git", "rev-list", "--count", "HEAD..origin/ABC-1")] = "2\n"
|
||||
self.assertIn("Merged origin/ABC-1 into item-7.", str(step(["sync"], checkout, checkout.config)))
|
||||
self.assertIn(["git", "merge", "--quiet", "--no-edit", "origin/ABC-1"], checkout.ran)
|
||||
self.assertNotIn(MERGE, checkout.ran)
|
||||
|
||||
def test_merge_merges_without_a_person_whatever_the_config_says_of_the_default_branch(self):
|
||||
checkout = self.checkout()
|
||||
checkout.answers[(PROJECT_CONFIG, "merge")] = "human\n"
|
||||
checkout.answers[tuple(WAITS)] = "true\n"
|
||||
checkout.decisions = ["REVIEW_REQUIRED"]
|
||||
self.assertEqual(step(["merge"], checkout, checkout.config, parks=True), "Merged pull request #12 (merge).")
|
||||
self.assertNotIn(GH_DECISION, checkout.ran)
|
||||
|
||||
def test_ready_asks_for_the_review_the_config_names(self):
|
||||
for origin, comment in ((GITHUB, self.COMMENT_GH), (GITEA, self.COMMENT_TEA)):
|
||||
with self.subTest(origin):
|
||||
checkout = self.checkout(origin)
|
||||
self.assertEqual(step(["ready"], checkout, checkout.config), "Marked pull request #12 ready, and asked for a review with “@reviewer review”.")
|
||||
self.assertEqual(checkout.acted()[-1], comment)
|
||||
|
||||
def test_ready_asks_for_no_review_where_the_config_names_none_or_the_pull_request_goes_into_the_default_branch(self):
|
||||
unnamed = self.checkout(comment=False)
|
||||
self.assertEqual(step(["ready"], unnamed, unnamed.config), "Marked pull request #12 ready.")
|
||||
into_default = self.checkout()
|
||||
into_default.chunk_base = ""
|
||||
self.assertEqual(step(["ready"], into_default, into_default.config), "Marked pull request #12 ready.")
|
||||
for checkout in (unnamed, into_default):
|
||||
self.assertNotIn(self.COMMENT_GH, checkout.ran)
|
||||
|
||||
def test_a_review_request_the_forge_refuses_fails_after_the_pull_request_is_ready(self):
|
||||
checkout = self.checkout()
|
||||
checkout.answers[tuple(self.COMMENT_GH)] = Failure("gh pr comment: denied")
|
||||
self.assertEqual(step(["ready"], checkout, checkout.config), Failure("marked pull request #12 ready, but could not ask for a review: gh pr comment: denied"))
|
||||
|
||||
def test_push_pushes_the_branch_and_asks_for_a_review_of_the_new_head(self):
|
||||
checkout = self.checkout()
|
||||
self.assertEqual(step(["push"], checkout, checkout.config), "Pushed item-7, and asked for a review of pull request #12 with “@reviewer review”.")
|
||||
self.assertEqual(checkout.acted(), [PUSH, self.COMMENT_GH])
|
||||
|
||||
def test_push_only_pushes_where_no_review_is_to_ask_for(self):
|
||||
unopened, unnamed, into_default = self.checkout(open=False), self.checkout(comment=False), self.checkout()
|
||||
into_default.chunk_base = ""
|
||||
for checkout in (unopened, unnamed, into_default):
|
||||
self.assertEqual(step(["push"], checkout, checkout.config), "Pushed item-7.")
|
||||
self.assertEqual(checkout.acted(), [PUSH])
|
||||
|
||||
def test_a_failed_push_asks_for_no_review(self):
|
||||
checkout = self.checkout()
|
||||
checkout.answers[tuple(PUSH)] = Failure("git push: rejected")
|
||||
self.assertEqual(step(["push"], checkout, checkout.config), Failure("git push: rejected"))
|
||||
self.assertNotIn(self.COMMENT_GH, checkout.ran)
|
||||
|
||||
def epic(self, origin: str = GITHUB) -> Checkout:
|
||||
"""A Checkout whose origin holds the epic branch ABC-1, level with main."""
|
||||
checkout = self.checkout(origin)
|
||||
checkout.answers[("git", "rev-list", "--count", "origin/ABC-1..origin/main")] = "0\n"
|
||||
checkout.answers[("git", "rev-parse", "origin/ABC-1")] = "abc123\n"
|
||||
return checkout
|
||||
|
||||
def test_open_epic_levels_the_epic_branch_and_opens_its_pull_request_into_the_default_branch_ready_for_a_person(self):
|
||||
for origin, create in ((GITHUB, ["gh", "pr", "create", "--head", "ABC-1", "--base", "main", "--title", "Ship the epic", "--body", "What it holds"]), (GITEA, ["tea", "pulls", "create", "--head", "ABC-1", "--base", "main", "--title", "Ship the epic", "--description", "What it holds"])):
|
||||
with self.subTest(origin):
|
||||
checkout = self.epic(origin)
|
||||
self.assertEqual(step(["open-epic", "ABC-1", "Ship the epic", "What it holds"], checkout, checkout.config), "origin/ABC-1 already holds origin/main. Opened the pull request from ABC-1 into main, which a person merges.")
|
||||
self.assertEqual(checkout.acted()[-1], create)
|
||||
self.assertIn(FETCH, checkout.ran)
|
||||
|
||||
def test_open_epic_merges_a_newer_default_branch_into_the_epic_branch_first(self):
|
||||
checkout = self.epic()
|
||||
checkout.answers[("git", "rev-list", "--count", "origin/ABC-1..origin/main")] = "3\n"
|
||||
checkout.answers[("git", "merge-tree", "--write-tree", "origin/ABC-1", "origin/main")] = "7ree\n"
|
||||
checkout.answers[("git", "commit-tree", "7ree", "-p", "origin/ABC-1", "-p", "origin/main", "-m", "Merge remote-tracking branch 'origin/main' into ABC-1")] = "c0mm17\n"
|
||||
self.assertIn("Merged origin/main into origin/ABC-1. Opened", str(step(["open-epic", "ABC-1", "Ship the epic"], checkout, checkout.config)))
|
||||
self.assertIn(["git", "push", "--quiet", "origin", "c0mm17:refs/heads/ABC-1"], checkout.ran)
|
||||
|
||||
def test_open_epic_leaves_a_conflict_with_the_default_branch_to_a_person_and_opens_nothing(self):
|
||||
checkout = self.epic()
|
||||
checkout.answers[("git", "rev-list", "--count", "origin/ABC-1..origin/main")] = "3\n"
|
||||
checkout.answers[("git", "merge-tree", "--write-tree", "origin/ABC-1", "origin/main")] = Failure("git merge-tree: CONFLICT")
|
||||
done = step(["open-epic", "ABC-1", "Ship the epic"], checkout, checkout.config)
|
||||
self.assertIsInstance(done, Failure)
|
||||
self.assertIn("a person merges it", done.reason)
|
||||
self.assertFalse(any(command[:3] == ["gh", "pr", "create"] for command in checkout.ran))
|
||||
|
||||
def test_open_epic_opens_no_second_pull_request(self):
|
||||
checkout = self.epic()
|
||||
checkout.answers[("gh", "pr", "list", "--head", "ABC-1", *GH_LIST[5:])] = "31\tabc123\tfalse\n"
|
||||
self.assertEqual(step(["open-epic", "ABC-1", "Ship the epic"], checkout, checkout.config), "origin/ABC-1 already holds origin/main. Pull request #31 from ABC-1 is open already.")
|
||||
self.assertFalse(any(command[:3] == ["gh", "pr", "create"] for command in checkout.ran))
|
||||
|
||||
def test_open_epic_refuses_where_the_config_names_no_epic_branch_or_the_title_is_not_one_line(self):
|
||||
unset = Checkout(GITHUB, open=False)
|
||||
self.assertEqual(step(["open-epic", "ABC-1", "Ship the epic"], unset, unset.config), Failure("the project's config sets no `epic-branch`, so the epic has no branch to open a pull request from (`project-config --help`)"))
|
||||
self.assertEqual(unset.ran, [])
|
||||
checkout = self.epic()
|
||||
self.assertEqual(step(["open-epic", "ABC-1", "Ship\nit"], checkout, checkout.config), Failure("give a title of one line"))
|
||||
self.assertEqual(step(["open-epic", "ABC-1"], checkout, checkout.config), Failure(USAGE))
|
||||
self.assertEqual(checkout.ran, [])
|
||||
|
||||
|
||||
class Launcher(unittest.TestCase):
|
||||
def test_help_exits_0_and_a_wrong_step_exits_1(self):
|
||||
self.assertEqual(subprocess.run([str(TOOL), "--help"], capture_output=True, env=isolated_env()).returncode, 0)
|
||||
|
||||
@@ -41,7 +41,11 @@ and prints that the release reviews and the cuts are the human's to call. It pri
|
||||
each / of the branch a dash, on the branch the config's `branch` template names, which is
|
||||
item-<ID> where the config names none. It continues a worktree already on that branch; else it adds one on the
|
||||
local branch, else on a new branch tracking origin's, else on a new branch off the default
|
||||
branch. Without --worktree, it prints that none was made;
|
||||
branch. Without --worktree, it prints that none was made. Where the config sets `epic-branch`
|
||||
(`project-config --help`), it first makes the working branch of the plan's epic on origin, off
|
||||
the default branch, or merges the default branch into it; a new branch is then made off that
|
||||
branch, and the checkout records that the chunk's pull request goes into it, for `chunk-pr`.
|
||||
Where the two don't merge cleanly, it makes no worktree and says how a person merges them;
|
||||
- each path the project's config sets, as `project-config` prints them in that worktree, or else
|
||||
in the checkout;
|
||||
- the language the config names for the project's prose, and its templates for commit titles,
|
||||
@@ -81,7 +85,8 @@ import subprocess
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from git_cli.git_repo import commit_exists, default_branch, file_at, git, top
|
||||
from git_cli.git_repo import commit_exists, default_branch, file_at, git, record_chunk_base, top
|
||||
from git_cli import epic_branch
|
||||
from failure import Failure
|
||||
from forge.commands import Forge, forge_of, Run, runner
|
||||
from chunk_preflight.gathered import Gathered, ItemFacts, LeftWorktree, NamedPath, Ran, Worktree
|
||||
@@ -91,7 +96,9 @@ from forge.pulls import merged_pull
|
||||
from plan.named_paths import named_paths
|
||||
from release_plan.next_chunk import NextChunk, NoItem, plan_name, planned
|
||||
from release_plan.release_standing import project_plan
|
||||
from project_config.settings import ProjectConfig
|
||||
from chunk_preflight.choices import pulls_command, worktree_add, worktree_on, worktrees
|
||||
from project_config import templates
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
# Each tool run in the item's worktree, {item} standing for the item's ID.
|
||||
@@ -152,20 +159,38 @@ def preflight(root: pathlib.Path, timeout: float, make: bool, item_id: int | Non
|
||||
forge_run = runner(str(root), timeout)
|
||||
held = project_plan(config, ref, str(root), forge_run=forge_run)
|
||||
plan = planned(held.plan, held.cut, ref, config.branch, outside, item_id)
|
||||
item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout, make)
|
||||
item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout, make, epic_branch_of(config))
|
||||
# A `checkout:` path lands in the worktree the chunk works in.
|
||||
made = located(str(item.worktree.path), pathlib.Path.home()) if isinstance(item, ItemFacts) and isinstance(item.worktree, Worktree) else config
|
||||
return render(Gathered(ref, note, held.cut, item, plan_name(ref, outside), (config if isinstance(made, Failure) else made).places, outside is not None, config.texts, merges_unread=held.merges_unread, left=left_worktrees(root, forge_run) if config.merge == "human" else ()))
|
||||
|
||||
|
||||
def item_facts(root: pathlib.Path, default: str, plan: NextChunk, timeout: float, make: bool) -> ItemFacts:
|
||||
worktree = item_worktree(root, plan.branch, default) if make else Failure(f"none made, since it ran without {WORKTREE}.")
|
||||
def epic_branch_of(config: ProjectConfig) -> str | None | Failure:
|
||||
"""The working branch of the plan's epic, as the config's `epic-branch` names it; None where the config sets none."""
|
||||
if config.epic_branch is None:
|
||||
return None
|
||||
if config.epic is None:
|
||||
return Failure("none made: the config sets `epic-branch`, but its `plan` names no Jira epic to name the branch by; chunk-preflight makes an epic's chunks only from a plan kept in Jira")
|
||||
return templates.epic_branch(config.epic_branch, config.epic.key)
|
||||
|
||||
|
||||
def item_facts(root: pathlib.Path, default: str, plan: NextChunk, timeout: float, make: bool, epic: str | None | Failure = None) -> ItemFacts:
|
||||
worktree = Failure(f"none made, since it ran without {WORKTREE}.") if not make else epic if isinstance(epic, Failure) else item_worktree(root, plan.branch, default, timeout, epic)
|
||||
path = worktree.path if isinstance(worktree, Worktree) else None
|
||||
return ItemFacts(plan, worktree, pull_listing(root, plan.branch, timeout), named_files(plan.text, path or root), tools_run(plan.first.id, path, timeout) if path else [])
|
||||
|
||||
|
||||
def item_worktree(root: pathlib.Path, branch: str, default: str) -> Worktree | Failure:
|
||||
"""The worktree on branch, made where none is; a Failure where git cannot make it, or its path holds something else."""
|
||||
def item_worktree(root: pathlib.Path, branch: str, default: str, timeout: float | None = None, epic: str | None = None) -> Worktree | Failure:
|
||||
"""The worktree on branch, made where none is; a Failure where git cannot make it, or its path holds something else.
|
||||
|
||||
epic names the working branch of the chunk's epic, where the project keeps one. The worktree then branches off that branch, which is first made on origin or brought level with default (`epic_branch.levelled`), and the checkout records that the chunk merges into it."""
|
||||
if epic is not None:
|
||||
level = epic_branch.levelled(epic, default, timeout=timeout)
|
||||
recorded = level if isinstance(level, Failure) else record_chunk_base(branch, epic)
|
||||
if isinstance(recorded, Failure):
|
||||
return Failure(f"none made: {recorded.reason}")
|
||||
made = item_worktree(root, branch, f"origin/{epic}")
|
||||
return made if isinstance(made, Failure) else Worktree(made.path, f"{made.how} {level} Its pull request goes into {epic}.")
|
||||
listing = git("worktree", "list", "--porcelain")
|
||||
if isinstance(listing, Failure):
|
||||
return listing
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import os
|
||||
import pathlib
|
||||
@@ -11,11 +12,13 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from project_config.templates import BRANCH
|
||||
from release_plan.next_chunk import CarriedOver, NoItem
|
||||
from project_config.settings import Epic, ProjectConfig
|
||||
from chunk_preflight.main import epic_branch_of, item_worktree, line_count, ran, seconds, TIMEOUT
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import Gathered, ItemFacts, LeftWorktree, NamedPath, Ran, Worktree
|
||||
from git_cli import git_repo
|
||||
from test_env import isolated_env
|
||||
from release_plan.release_standing import LastCut, UNSEEN_RELEASES
|
||||
from chunk_preflight.main import line_count, ran, seconds, TIMEOUT
|
||||
from release_plan.awaiting_merge import marked
|
||||
from release_plan import next_chunk
|
||||
from chunk_preflight.facts import open_pulls, render
|
||||
@@ -585,6 +588,51 @@ class Render(unittest.TestCase):
|
||||
self.assertIn("`larv-review places` could not finish: timed out", said)
|
||||
|
||||
|
||||
class EpicBranchWorktree(unittest.TestCase):
|
||||
"""A chunk's worktree in a project whose config names an epic's working branch, here ABC-1."""
|
||||
|
||||
def setUp(self):
|
||||
self.repo = Repo(self)
|
||||
self.enterContext(contextlib.chdir(self.repo.root))
|
||||
# item_worktree runs git in this process's environment, so the identity its merge commit needs is the checkout's own.
|
||||
for name, value in (("user.name", "t"), ("user.email", "t@example.com")):
|
||||
self.repo.git(self.repo.root, "config", name, value)
|
||||
|
||||
def test_the_first_chunk_makes_the_epic_branch_on_origin_and_branches_off_it_recording_where_it_merges(self):
|
||||
made = item_worktree(self.repo.root, "ABC-7", "origin/main", 30, "ABC-1")
|
||||
self.assertEqual(made, Worktree(self.repo.temp / "proj-ABC-7", "added on the new branch ABC-7, made off origin/ABC-1. Made origin/ABC-1 off origin/main. Its pull request goes into ABC-1."))
|
||||
self.assertEqual(self.repo.git(self.repo.origin, "rev-parse", "ABC-1"), self.repo.git(self.repo.root, "rev-parse", "origin/main"))
|
||||
self.assertEqual(git_repo.default_ref(str(made.path)), "origin/ABC-1")
|
||||
|
||||
def test_a_later_chunk_branches_off_what_the_epic_branch_holds(self):
|
||||
item_worktree(self.repo.root, "ABC-7", "origin/main", 30, "ABC-1")
|
||||
first = self.repo.temp / "proj-ABC-7"
|
||||
self.repo.write(first, "src/first.py", "FIRST = 1\n")
|
||||
self.repo.commit(first, "first")
|
||||
self.repo.git(first, "push", "--quiet", "origin", "ABC-7:ABC-1")
|
||||
made = item_worktree(self.repo.root, "ABC-8", "origin/main", 30, "ABC-1")
|
||||
self.assertIn("origin/ABC-1 already holds origin/main.", made.how)
|
||||
self.assertTrue((made.path / "src/first.py").exists())
|
||||
|
||||
def test_a_default_branch_that_conflicts_with_the_epic_branch_makes_no_worktree_and_leaves_it_to_a_person(self):
|
||||
item_worktree(self.repo.root, "ABC-7", "origin/main", 30, "ABC-1")
|
||||
first = self.repo.temp / "proj-ABC-7"
|
||||
self.repo.write(first, "src/app.py", "def run():\n\treturn 2\n\n")
|
||||
self.repo.commit(first, "first")
|
||||
self.repo.git(first, "push", "--quiet", "origin", "ABC-7:ABC-1")
|
||||
self.repo.push_from_elsewhere("src/app.py", "def run():\n\treturn 3\n\n")
|
||||
made = item_worktree(self.repo.root, "ABC-8", "origin/main", 30, "ABC-1")
|
||||
self.assertIsInstance(made, Failure)
|
||||
self.assertTrue(made.reason.startswith("none made: origin/main doesn't merge into origin/ABC-1 cleanly, so a person merges it"), made.reason)
|
||||
self.assertFalse((self.repo.temp / "proj-ABC-8").exists())
|
||||
|
||||
def test_names_the_epic_branch_by_the_plans_epic_and_none_where_the_config_sets_no_template(self):
|
||||
config = ProjectConfig("proj", pathlib.Path("/config"), pathlib.Path("/checkout"), {}, epic=Epic("https://acme.atlassian.net", "ABC-1"), epic_branch="epic/{epic}")
|
||||
self.assertEqual(epic_branch_of(config), "epic/ABC-1")
|
||||
self.assertIsNone(epic_branch_of(dataclasses.replace(config, epic_branch=None)))
|
||||
self.assertEqual(epic_branch_of(dataclasses.replace(config, epic=None)), Failure("none made: the config sets `epic-branch`, but its `plan` names no Jira epic to name the branch by; chunk-preflight makes an epic's chunks only from a plan kept in Jira"))
|
||||
|
||||
|
||||
class OpenPulls(unittest.TestCase):
|
||||
def test_lists_gh_rows_as_they_come_and_only_teas_rows_from_the_branch(self):
|
||||
self.assertEqual(open_pulls("12\thttps://github.com/o/r/pull/12\n14\thttps://github.com/o/r/pull/14\n", "gh", "item-3"), ["#12 https://github.com/o/r/pull/12", "#14 https://github.com/o/r/pull/14"])
|
||||
|
||||
@@ -180,6 +180,19 @@ class EpicStoreContract:
|
||||
self.assertEqual([store.finish_issue(key), store.finish_issue(closed)], [None, None])
|
||||
self.assertEqual({issue.key: issue.done for issue in self.issues(store)}, {key: True, other: False, closed: True})
|
||||
|
||||
def test_moves_a_child_issue_or_a_sub_task_to_the_status_named_and_leaves_one_already_there(self) -> None:
|
||||
store = self.new_store()
|
||||
child = self.filed(store, store.epic_key, "Count the runs.")
|
||||
task = self.filed(store, child, "Count them in the api.")
|
||||
self.assertEqual([store.move_issue(task, "Done"), store.move_issue(task, "done")], [None, None])
|
||||
self.assertEqual({issue.key: issue.status for issue in self.issues(store)}, {child: "To Do", task: "Done"})
|
||||
|
||||
def test_refuses_to_move_an_issue_outside_the_epic(self) -> None:
|
||||
store = self.new_store()
|
||||
self.filed(store, store.epic_key, "Count the runs.")
|
||||
self.assertIsInstance(store.move_issue("ZZZ-1", "Done"), Failure)
|
||||
self.assertEqual([issue.status for issue in self.issues(store)], ["To Do"])
|
||||
|
||||
def test_finishes_a_sub_task_of_a_child_issue_and_leaves_its_parent_open(self) -> None:
|
||||
store = self.new_store()
|
||||
child = self.filed(store, store.epic_key, "Count the runs.")
|
||||
|
||||
@@ -115,6 +115,17 @@ class MemoryEpic:
|
||||
self.change(key, assignee=self.account)
|
||||
return None if child.assignee in (None, self.account) else child.assignee
|
||||
|
||||
def move_issue(self, key: str, status: str) -> None | Failure:
|
||||
if self.fails:
|
||||
return Failure(self.fails)
|
||||
child = self.within(key)
|
||||
if child is None:
|
||||
return no_child(self.epic_key, key, "moved")
|
||||
if child.status.casefold() != status.casefold():
|
||||
self.change(key, status=status, done=status.casefold() == "done")
|
||||
self.writes.append(f"move {key} to {status}")
|
||||
return None
|
||||
|
||||
def finish_issue(self, key: str) -> None | Failure:
|
||||
if self.fails:
|
||||
return Failure(self.fails)
|
||||
|
||||
@@ -10,6 +10,7 @@ from project_config.settings import DEFAULT_ISSUE_TYPE, Epic, Finish, JIRA_FINDI
|
||||
from atlassian.jira import DONE, entry_of, finishing_transition, ISSUE_KEY, issue_type_refusal, issue_types_of, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, SHAPE, status_category, unshaped
|
||||
from do_epic.backend.protocol import EpicIssue, no_blocker, no_child, no_parent, no_scores, no_words, unfit, unfit_label
|
||||
from failure import Failure
|
||||
from do_epic.backend.jira_status import moved_to
|
||||
from plan.todo_table import MOVES
|
||||
from do_epic.repo_pick import REVIEW_LABEL
|
||||
from do_epic.backend.jira_start import Start, started
|
||||
@@ -207,6 +208,13 @@ class JiraEpic:
|
||||
# Jira keeps a sub-task in its parent's sprint, so the parent joins the sprint in its place.
|
||||
return started(self.epic.site, key, key if within[0] == self.epic_key else within[0], self.start, authorization, self.http)
|
||||
|
||||
def move_issue(self, key: str, status: str) -> None | Failure:
|
||||
authorization = basic_auth(self.env_file)
|
||||
if isinstance(authorization, Failure):
|
||||
return authorization
|
||||
within = self.within(key, authorization, "move", "moved")
|
||||
return within if isinstance(within, Failure) else moved_to(self.epic.site, key, status, authorization, self.http)
|
||||
|
||||
def finish_issue(self, key: str) -> None | Failure:
|
||||
authorization = basic_auth(self.env_file)
|
||||
if isinstance(authorization, Failure):
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Moves a Jira issue to a status by name, for a team whose own automation doesn't see the move's cause, such as a pull request into an epic's working branch."""
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from atlassian.client import Http
|
||||
from atlassian.jira import offers_of, unshaped
|
||||
|
||||
|
||||
def moved_to(site: str, key: str, status: str, authorization: str, http: Http) -> Failure | None:
|
||||
"""Moves the issue named key to the status named status, in upper or lower case, by the first transition its workflow offers to it. An issue already there stays as it is. Why Jira did not take the move; None where the issue has the status."""
|
||||
answered: typing.Any = http("GET", f"{site}/rest/api/3/issue/{key}?fields=status", authorization, None)
|
||||
if isinstance(answered, Failure):
|
||||
return Failure(f"cannot read {key} to move it: {answered.reason}")
|
||||
try:
|
||||
now = str(answered["fields"]["status"]["name"])
|
||||
except (KeyError, TypeError) as failure:
|
||||
return Failure(unshaped(key, failure))
|
||||
if now.casefold() == status.casefold():
|
||||
return None
|
||||
offered = http("GET", f"{site}/rest/api/3/issue/{key}/transitions", authorization, None)
|
||||
if isinstance(offered, Failure):
|
||||
return Failure(f"cannot read {key}'s transitions: {offered.reason}")
|
||||
offers = offers_of(offered, key)
|
||||
if isinstance(offers, Failure):
|
||||
return offers
|
||||
leading = [id_ for id_, _, to, _ in offers if to.casefold() == status.casefold()]
|
||||
if not leading:
|
||||
others = " and ".join(f"{name!r} to {to!r}" for _, name, to, _ in offers)
|
||||
return Failure(f"{key} has no transition to the status {status!r} from its status {now!r}, " + (f"only {others}" if offers else "nor any other the account may make"))
|
||||
moved = http("POST", f"{site}/rest/api/3/issue/{key}/transitions", authorization, {"transition": {"id": leading[0]}})
|
||||
return Failure(f"cannot move {key} to {status!r}: {moved.reason}") if isinstance(moved, Failure) else None
|
||||
@@ -70,6 +70,9 @@ class EpicStore(typing.Protocol):
|
||||
def start_issue(self, key: str) -> str | None | Failure:
|
||||
"""Shows the team that the epic's child issue named key, or a sub-task of one, is being worked. It assigns an issue nobody holds to the account the store works as. An issue someone else holds stays theirs, and the answer is their display name; otherwise the answer is None. Where the backend's settings say so, it also moves an issue whose work hasn't started, and adds every starting issue to a sprint, whoever holds it. An issue outside the epic is refused. A Failure names each step that could not be made, and anyone else who holds the issue; the steps the tracker took stay taken."""
|
||||
|
||||
def move_issue(self, key: str, status: str) -> None | Failure:
|
||||
"""Moves the epic's child issue named key, or a sub-task of one, to the status named status, in upper or lower case; one already there stays as it is. An issue outside the epic is refused. A Failure says why the move could not be made, such as a workflow that gives no way from the issue's status to that one."""
|
||||
|
||||
def finish_issue(self, key: str) -> None | Failure:
|
||||
"""Moves the epic's child issue named key, or a sub-task of one, to a done status, so that read answers it as done; one already done stays as it is. An issue outside the epic is refused. A Failure says why the move could not be made: the issue's workflow gives no way to a done status, gives several the backend cannot choose between, or refuses the move."""
|
||||
|
||||
|
||||
@@ -397,6 +397,37 @@ class Jira(Case):
|
||||
self.jira.answers[("GET", f"{ISSUES}/{child}?fields=parent,status")] = Failure("Jira answered 503")
|
||||
self.assertEqual(store.start_issue(task), Failure(f"cannot read {child} to start its sub-task: Jira answered 503"))
|
||||
|
||||
def test_moves_an_issue_by_the_transition_that_leads_to_the_status_named_in_any_case(self) -> None:
|
||||
store = self.new_store()
|
||||
key = store.file("ABC-12", "Count the runs.", "", ())
|
||||
review = {"name": "Code Review", "statusCategory": {"key": "indeterminate"}}
|
||||
self.jira.workflow = [{"id": "31", "name": "Mark as done", "to": DONE}, {"id": "51", "name": "Ask for review", "to": review}]
|
||||
self.assertIsNone(store.move_issue(key, "code review"))
|
||||
self.assertEqual((self.jira.transitioned, self.jira.issues[0]["fields"]["status"]), (["51"], review)) # type: ignore[index]
|
||||
self.assertIsNone(store.move_issue(key, "Code Review"))
|
||||
self.assertEqual(self.jira.transitioned, ["51"])
|
||||
|
||||
def test_a_move_the_workflow_does_not_offer_fails_naming_what_it_offers(self) -> None:
|
||||
store = self.new_store()
|
||||
key = store.file("ABC-12", "Count the runs.", "", ())
|
||||
self.assertEqual(store.move_issue(key, "Code Review"), Failure(f"{key} has no transition to the status 'Code Review' from its status 'To Do', only 'Mark as done' to 'Done'"))
|
||||
self.jira.workflow = []
|
||||
self.assertEqual(store.move_issue(key, "Code Review"), Failure(f"{key} has no transition to the status 'Code Review' from its status 'To Do', nor any other the account may make"))
|
||||
self.assertEqual(self.jira.transitioned, [])
|
||||
|
||||
def test_a_move_jira_cannot_read_or_refuses_fails_saying_which(self) -> None:
|
||||
store = self.new_store()
|
||||
key = store.file("ABC-12", "Count the runs.", "", ())
|
||||
transitions = f"{ISSUES}/{key}/transitions"
|
||||
for answers, reason in (
|
||||
({("GET", transitions): Failure("Jira answered 503")}, f"cannot read {key}'s transitions: Jira answered 503"),
|
||||
({("GET", transitions): {"transitions": [{"id": "21"}]}}, f"Jira answered {key}'s transitions in a shape other than the one it documents"),
|
||||
({("POST", transitions): Failure("Jira answered 400")}, f"cannot move {key} to 'Done': Jira answered 400"),
|
||||
):
|
||||
with self.subTest(reason=reason):
|
||||
self.jira.answers = answers
|
||||
self.assertEqual(store.move_issue(key, "Done"), Failure(reason))
|
||||
|
||||
def test_finishes_an_issue_by_the_transition_the_settings_name(self) -> None:
|
||||
store = self.new_store()
|
||||
key = store.file("ABC-12", "Count the runs.", "", ())
|
||||
|
||||
@@ -12,6 +12,7 @@ from project_config.settings import ProjectConfig
|
||||
from model_routing.ladder import ProjectRung
|
||||
from chunk_driver import prompts
|
||||
from model_routing.route import Route
|
||||
from project_config import templates
|
||||
from agent_cycle.worker_prompts import WorkerPrompts
|
||||
|
||||
# The entry point's name as the worker, the judge and the human read it.
|
||||
@@ -21,7 +22,7 @@ DRIVER = DO_EPIC
|
||||
def shipping(config: ProjectConfig) -> str:
|
||||
"""How a chunk in the repo that config names ships its change. An epic's issue isn't an item of the repo's plan, so `chunk-pr merge --finish`, which adds a finished item's changelog bullet, doesn't apply: the worker writes the bullet itself, where the repo publishes something others consume. (docs/decisions.md → `do-epic: drives one Jira epic …`, "Releases"). Where the repo's config leaves the merge to a person, the worker ends its run on `chunk-pr merge`'s word, since do-epic parks the chunk until that merge ("Long gates")."""
|
||||
opening = "The issue isn't an item of the repo's plan, so run `chunk-pr merge` without `--finish`."
|
||||
if config.merge == "human":
|
||||
if config.merge == "human" and config.epic_branch is None:
|
||||
opening += " The repo's team merges its pull requests itself, so `chunk-pr merge` leaves the pull request ready for a person to merge: end your run when it says so."
|
||||
if config.epic:
|
||||
return f"{opening} The repo's plan is a Jira epic, and the history of its issues serves as the changelog, so leave the changelog as it is."
|
||||
@@ -29,9 +30,18 @@ def shipping(config: ProjectConfig) -> str:
|
||||
return f"{opening} Where the repo publishes something others consume, add one bullet to `## Unreleased` in `{changelog}` that tells the repo's consumers what changed; otherwise leave the changelog as it is."
|
||||
|
||||
|
||||
def epic_branch_rule(config: ProjectConfig, epic: str) -> str:
|
||||
"""What a chunk is told where the repo's config sets `epic-branch`, empty where it doesn't: its base, that its merge needs no person, how a later push asks for a review, and which branch its sibling repos are tested at (docs/decisions.md → `epic-branch: an epic's chunks branch off and merge into a working branch …`)."""
|
||||
if config.epic_branch is None:
|
||||
return ""
|
||||
branch = templates.epic_branch(config.epic_branch, epic)
|
||||
pushed = " Push each later commit to the open pull request with `chunk-pr push`, which asks the repo's auto-reviewer for a review of the new head, and wait for that review." if config.review_request_comment else ""
|
||||
return f"The chunk's pull request goes into the epic's working branch `{branch}`, not into the default branch: {DRIVER} has made that branch level with the default branch and recorded it as the base of the chunk's branch, so make the chunk's worktree and branch off `origin/{branch}`. `chunk-pr merge` merges into `{branch}` without waiting for a person.{pushed} Test each sibling repo at its branch `{branch}` where it has one, else at its default branch, and name in the chunk's summary each sibling that ran at its default branch."
|
||||
|
||||
|
||||
def task(issue: EpicIssue, epic: str, team: LabelRepos, checkout: str | None, launcher: pathlib.Path, language: str, config: ProjectConfig | None) -> str:
|
||||
"""The task of the chunk that works issue, of the epic with the key epic: in checkout, or without a repo where it is None. team is the config's LABEL_REPOS table. launcher is the do-epic that runs the chunk, language the one the epic's Jira text is in, and config the project config of the repo's checkout, None without a repo."""
|
||||
shipped = shipping(config) if config else ""
|
||||
shipped = " ".join(filter(None, [shipping(config), epic_branch_rule(config, epic)])) if config else ""
|
||||
where = f"in the checkout {checkout}, on the branch {issue.key}" if checkout else "which changes no repo: work in the folder you start in"
|
||||
return f"Work the Jira issue {issue.key} of the epic {epic} as one chunk, {where}. {" ".join(filter(None, [findings.instructions(epic, launcher, language, team, issue), shipped]))} Its summary: {issue.summary}" + (f"\n\nIts description:\n\n{issue.detail}" if issue.detail else "")
|
||||
|
||||
|
||||
+20
-2
@@ -21,6 +21,7 @@ One pair per machine, the same for every epic (docs/decisions.md → `do-epic: d
|
||||
- `jira-sprint-board` is the ID of a Jira board, the number in the board's address, such as `6`. An issue whose chunk starts joins that board's active sprint; a sub-task's parent joins in its place. Without it do-epic doesn't add a starting issue to a sprint.
|
||||
- `jira-unblocking-statuses` lists the statuses at which an issue's work has landed though Jira doesn't count it done yet, such as `["Release Ready"]`, in upper or lower case. An issue in one of them takes no chunk and no longer blocks the issues it blocks. A status Jira counts as done always does both, listed or not.
|
||||
- `jira-automation-moves-issues = true` says the team's own automation moves an issue when its pull request merges. do-epic then moves only the issue of a chunk without a repo, which has no pull request, and waits for the automation to move each other. It needs `jira-unblocking-statuses`, which then names the status the automation gives an issue whose pull request merged. false where left out.
|
||||
- `jira-pull-request-open-status` and `jira-pull-request-merged-status` name the statuses do-epic itself gives an issue whose chunk merges into an epic's working branch, in a repo whose config sets `epic-branch` (`project-config --help`): the first once the chunk's pull request is open, such as `"Code Review"`, and the second once it has merged into that branch, such as `"Release Ready"`. A team's automation moves an issue only for a pull request into the default branch, so there do-epic makes both moves, whatever `jira-automation-moves-issues` says. `jira-unblocking-statuses` must list the second, and an issue that has it counts as done when the epic's release reviews and its finishing chunk fall due: both come before a person merges the working branch into the default branch. Without the first, do-epic doesn't move an issue as its pull request opens. Without the second, a finished chunk's issue moves to done, and where `jira-automation-moves-issues` is set do-epic stops and asks for the setting.
|
||||
- `jira-finding-type` names the Jira issue type do-epic files a finding as, and `jira-review-type` the one it files a repo's release review as, such as `"Feature"` and `"Chore"`, for a Jira project that has no Task type. Task where left out. do-epic doesn't file anything where the project lacks the type, and says which types it has.
|
||||
- `sub-task-summary` shapes the summary of each sub-task do-epic files for an issue that changes several repos, such as `"{label}: {Summary}"`. `{label}` is the team's label for the repo, else the repo's name, and `{Summary}` is the issue's summary with a capital first letter. It must hold `{Summary}`. Where left out, a summary is `[<repo>] <the issue's summary>`.
|
||||
- `[label-repos]` has one line for each label of the team's own that names a repo: the label, then that repo's name, such as `twu-4 = "tenant-web-ui-4"`. do-epic reads such a label as it reads its own `repo:<name>`. A team whose label is the repo's name maps the name to itself. Where several lines name one repo, do-epic writes the label of the first.
|
||||
@@ -51,9 +52,12 @@ LABEL_REPOS = "label-repos"
|
||||
# Three readers, seated as those who write and read this config, picked `jira-unblocking-statuses` from four candidates, 3-0, and `jira-automation-moves-issues` 2-1. `jira-unblock-statuses` reads as statuses do-epic moves an issue to, and `jira-finish-issues = false` as closing no epic either.
|
||||
UNBLOCKING_STATUSES = "jira-unblocking-statuses"
|
||||
AUTOMATION_MOVES = "jira-automation-moves-issues"
|
||||
# Three readers, seated as those who write and read this config, picked `jira-pull-request-open-status` from four candidates, 2-1, and the merged status's name was spelt to pair with it. Each names a status, not a transition as `jira-start-transition` does: do-epic takes whichever transition leads there.
|
||||
PULL_OPEN_STATUS = "jira-pull-request-open-status"
|
||||
PULL_MERGED_STATUS = "jira-pull-request-merged-status"
|
||||
SUB_TASK_SUMMARY = "sub-task-summary"
|
||||
ISSUE_TYPES = (JIRA_FINDING_TYPE, JIRA_REVIEW_TYPE)
|
||||
OPTIONAL = (CLONE_FOLDER, LANGUAGE, *JIRA_FINISH, START_TRANSITION, SPRINT_BOARD, UNBLOCKING_STATUSES, AUTOMATION_MOVES, LABEL_REPOS, SUB_TASK_SUMMARY, *ISSUE_TYPES)
|
||||
OPTIONAL = (CLONE_FOLDER, LANGUAGE, *JIRA_FINISH, START_TRANSITION, SPRINT_BOARD, UNBLOCKING_STATUSES, AUTOMATION_MOVES, PULL_OPEN_STATUS, PULL_MERGED_STATUS, LABEL_REPOS, SUB_TASK_SUMMARY, *ISSUE_TYPES)
|
||||
LISTED = f"The settings are {', '.join(SETTINGS)}, and optionally {listed(OPTIONAL, 'and')}."
|
||||
|
||||
|
||||
@@ -74,6 +78,9 @@ class DoEpicConfig:
|
||||
# The UNBLOCKING_STATUSES list; empty where the config has none.
|
||||
unblocking: tuple[str, ...] = ()
|
||||
automation_moves: bool = False
|
||||
# PULL_OPEN_STATUS and PULL_MERGED_STATUS; each None where the config doesn't name it.
|
||||
pull_open_status: str | None = None
|
||||
pull_merged_status: str | None = None
|
||||
# The SUB_TASK_SUMMARY template; None where the config has none.
|
||||
sub_task_summary: str | None = None
|
||||
finding_type: str = DEFAULT_ISSUE_TYPE
|
||||
@@ -120,6 +127,16 @@ def start_faults(values: dict[str, object]) -> list[str]:
|
||||
]
|
||||
|
||||
|
||||
def pull_status_faults(values: dict[str, object]) -> list[str]:
|
||||
"""What is wrong with the PULL_OPEN_STATUS and PULL_MERGED_STATUS settings in values."""
|
||||
merged, unblocking = name_of(values.get(PULL_MERGED_STATUS)), values.get(UNBLOCKING_STATUSES, [])
|
||||
listed_statuses = [status.casefold() for status in unblocking if isinstance(status, str)] if isinstance(unblocking, list) else []
|
||||
return [
|
||||
*(f"`{name}` is {values[name]!r}, not the name Jira shows, such as \"{example}\"" for name, example in ((PULL_OPEN_STATUS, "Code Review"), (PULL_MERGED_STATUS, "Release Ready")) if name in values and not name_of(values[name])),
|
||||
*([f"`{PULL_MERGED_STATUS}` is {merged!r}, so `{UNBLOCKING_STATUSES}` must list it: an issue at any other status reads as open, and its chunk would start again"] if merged and merged.casefold() not in listed_statuses else []),
|
||||
]
|
||||
|
||||
|
||||
def workflow_faults(values: dict[str, object]) -> list[str]:
|
||||
"""What is wrong with the UNBLOCKING_STATUSES list and the AUTOMATION_MOVES switch in values."""
|
||||
statuses, moves = values.get(UNBLOCKING_STATUSES, ["Done"]), values.get(AUTOMATION_MOVES, False)
|
||||
@@ -163,6 +180,7 @@ def load(home: pathlib.Path, ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfi
|
||||
*finish_faults(values),
|
||||
*workflow_faults(values),
|
||||
*start_faults(values),
|
||||
*pull_status_faults(values),
|
||||
*(summary_template_faults(values[SUB_TASK_SUMMARY]) if SUB_TASK_SUMMARY in values else []),
|
||||
*label_repo_faults(values.get(LABEL_REPOS, {})),
|
||||
*(f"`{name}` is {values[name]!r}, {fault}" for name, example in zip(ISSUE_TYPES, ("Feature", "Chore")) if name in values and (fault := type_fault(values[name], example))),
|
||||
@@ -181,4 +199,4 @@ def load(home: pathlib.Path, ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfi
|
||||
finding_type, review_type = (str(values.get(name, DEFAULT_ISSUE_TYPE)) for name in ISSUE_TYPES)
|
||||
board = values.get(SPRINT_BOARD)
|
||||
assert board is None or isinstance(board, int)
|
||||
return DoEpicConfig(folder, url, env_file, clone_folder, language, model, rule, finish_of(values), types.MappingProxyType(labels), tuple(statuses), values.get(AUTOMATION_MOVES) is True, template, finding_type, review_type, Start(name_of(values.get(START_TRANSITION)), board))
|
||||
return DoEpicConfig(folder, url, env_file, clone_folder, language, model, rule, finish_of(values), types.MappingProxyType(labels), tuple(statuses), values.get(AUTOMATION_MOVES) is True, name_of(values.get(PULL_OPEN_STATUS)), name_of(values.get(PULL_MERGED_STATUS)), template, finding_type, review_type, Start(name_of(values.get(START_TRANSITION)), board))
|
||||
|
||||
+13
-3
@@ -7,6 +7,7 @@ Once the epic holds issues and none is open, its finishing chunk runs, in a wind
|
||||
3. With every goal confirmed, `do-epic <EPIC-KEY> --close-epic` posts the summary on the epic and closes it.
|
||||
|
||||
The chunk starts again each time the epic holds no open issue, until the epic is closed. A repo is reviewed once per epic, as a release is: the issues filed after its review don't bring another."""
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
@@ -28,6 +29,13 @@ It files a release review of each repo the epic changed, as an issue labelled `{
|
||||
It closes the epic by the transition `jira-finish-transition` names, to the status `jira-finish-status` names."""
|
||||
|
||||
|
||||
def landed(issues: list[EpicIssue], merged_status: str | None) -> list[EpicIssue]:
|
||||
"""issues, each counted done where it has the status merged_status, which do-epic's `jira-pull-request-merged-status` names: its work has merged into the epic's working branch, and Jira counts it done only once a person has merged that branch into the default branch. The epic's release reviews and finishing come before that merge, so they can't wait for it (docs/decisions.md → `epic-branch: an epic's chunks branch off and merge into a working branch …`). None names no such status."""
|
||||
if merged_status is None:
|
||||
return issues
|
||||
return [dataclasses.replace(issue, done=True) if issue.status.casefold() == merged_status.casefold() else issue for issue in issues]
|
||||
|
||||
|
||||
def due(issues: list[EpicIssue]) -> bool:
|
||||
"""Whether the epic's finishing comes next: it holds an issue, and none is open."""
|
||||
return bool(issues) and not still_open(issues)
|
||||
@@ -64,24 +72,26 @@ def task(epic: str, issues: list[EpicIssue], team: LabelRepos, launcher: pathlib
|
||||
f"The chunk is finished once each issue is filed: {DRIVER} works them, and starts this chunk again once the epic holds no open issue."
|
||||
)
|
||||
return (
|
||||
f"{opening} Each repo it changed has had its release review. Three steps remain, in this order.\n\n"
|
||||
f"{opening} Each repo it changed has had its release review. Four steps remain, in this order.\n\n"
|
||||
"1. Ask the human to confirm each goal under the description's ## Goals: that an achieve goal is achieved, and that no defect stands against a maintain goal. Ask one goal per question, each with the evidence of what shipped. "
|
||||
"A goal is met only where the human confirms it: never take one as met from the evidence alone. Don't ask again about a goal a decision in the description records as confirmed.\n"
|
||||
"2. For a goal the human doesn't confirm, propose a set of items that would meet it, and ask the human to approve the set. File each item they approve. "
|
||||
f"Then the chunk is finished: {DRIVER} works the items, and starts this chunk again once the epic holds no open issue.\n"
|
||||
f"3. Once the human has confirmed every goal, write a summary in {language}, the epic's language, for the people who work the epic: what shipped in each repo, and each goal's evidence. "
|
||||
f"3. Once the human has confirmed every goal, open the epic's pull request in each repo it changed whose config sets `epic-branch`: in that repo's checkout, `project-config epic-branch` prints the setting, and fails where the config sets none. There, run `chunk-pr open-epic {epic} \"<title>\"`, which makes the epic's working branch level with the default branch and opens the pull request from it into the default branch. Never merge it: a person does. Name each such pull request in the summary.\n"
|
||||
f"4. Then write a summary in {language}, the epic's language, for the people who work the epic: what shipped in each repo, and each goal's evidence. "
|
||||
f"Post it and close the epic with `{launcher} {epic} {CLOSE}`, the summary on stdin. That is the chunk's very last step, and the chunk is finished once it succeeds.\n\n"
|
||||
f"{findings.instructions(epic, launcher, language, team)} Record each goal's confirmation as such a decision.\n\n"
|
||||
"The epic's issues, each done:\n\n" + "\n".join(f"- {issue.key}{f' ({repo})' if (repo := repo_of(issue, team)) else ''}: {issue.summary}" for issue in issues)
|
||||
)
|
||||
|
||||
|
||||
def closed(epic: str, store: EpicStore, team: LabelRepos, stdin: typing.TextIO) -> str | Failure:
|
||||
def closed(epic: str, store: EpicStore, team: LabelRepos, stdin: typing.TextIO, merged_status: str | None = None) -> str | Failure:
|
||||
"""Posts the summary piped in on the epic with the key epic and closes it, and answers the line to print; a Failure, with nothing posted, while the epic isn't ready to close."""
|
||||
# Whether the human confirmed each goal isn't checked here: a decision that records it is the worker's own text, so only the task and the judge, who reads the human's answers, can hold the worker to it.
|
||||
issues = store.read()
|
||||
if isinstance(issues, Failure):
|
||||
return Failure(f"cannot close the epic {epic}: {issues.reason}")
|
||||
issues = landed(issues, merged_status)
|
||||
already = store.closed()
|
||||
if already:
|
||||
return Failure(f"cannot close the epic {epic}: {already.reason if isinstance(already, Failure) else 'it is closed already'}")
|
||||
|
||||
@@ -6,6 +6,7 @@ import typing
|
||||
|
||||
from forge.reviews import ANSWERED, APPROVED, CHANGES_REQUESTED, review_decision, REVIEW_REQUIRED, waiting_threads
|
||||
from forge.pulls import CheckFailed, checks_now, open_pull, Pending, required_checks, unmergeable
|
||||
from git_cli.git_repo import CHUNK_BASE
|
||||
from failure import Failure
|
||||
from forge.commands import forge_of, Run
|
||||
|
||||
@@ -58,6 +59,9 @@ def gate(branch: str, checkout: str, at: typing.Callable[[str], Run], by_human:
|
||||
if failed is not None:
|
||||
return failed
|
||||
origin, head, base = (str(answer).strip() for answer in read)
|
||||
# A chunk of an epic that keeps a working branch merges into that branch, so its protection names the checks.
|
||||
epic_base = run(["git", "config", "--get", f"branch.{branch}.{CHUNK_BASE}"])
|
||||
base = base if isinstance(epic_base, Failure) or not epic_base.strip() else epic_base.strip()
|
||||
forge = forge_of(origin)
|
||||
pull = open_pull(forge, branch, head, run)
|
||||
if not isinstance(pull, str):
|
||||
|
||||
+48
-8
@@ -16,9 +16,10 @@ from do_epic.repo_pick import ClaudeWork, HumanTask, recorded, Repo
|
||||
from project_config.main import located as config_located
|
||||
from chunk_driver.project.records import CONSEQUENCE, read_records
|
||||
from agent_cycle.run import Cycle, run_cycle
|
||||
from do_epic.config import DoEpicConfig, load
|
||||
from do_epic.config import DoEpicConfig, load, PULL_MERGED_STATUS
|
||||
from loop_effects.effects import Effects, say
|
||||
from project_config.settings import Epic
|
||||
from git_cli import epic_branch
|
||||
from record_store.jira_description import EpicDescription
|
||||
from do_epic.backend.protocol import EpicIssue, EpicStore
|
||||
from do_epic.epic_record import EpicRecord
|
||||
@@ -33,11 +34,13 @@ from chunk_driver.this_loop import Loop
|
||||
from chunk_driver.project.model_choice import Models, overridden
|
||||
from loop_state.paths import Paths
|
||||
from chunk_driver.project.premises import read_premises
|
||||
from git_cli.git_repo import record_chunk_base
|
||||
from forge.commands import Run, runner
|
||||
from claude_code.session import session_named
|
||||
from model_routing.ladder_file import SHIPPED
|
||||
from agent_cycle.stop import Stop
|
||||
from agent_cycle.direct_message import tell
|
||||
from project_config import templates
|
||||
from agent_cycle import tmux
|
||||
|
||||
HELP = f"""usage: do-epic <EPIC-KEY> [--status | --dry-run]
|
||||
@@ -165,7 +168,7 @@ def epic_written(key: str, writes: findings.Write | None, paths: Paths, backend:
|
||||
if isinstance(config, Failure):
|
||||
return Stop(1, config.reason)
|
||||
store, record = backend(config, key)
|
||||
done = findings.written(key, writes, store, config.label_repos, record, stdin, paths.home / scheduler.STATE / key) if writes else finish.closed(key, store, config.label_repos, stdin)
|
||||
done = findings.written(key, writes, store, config.label_repos, record, stdin, paths.home / scheduler.STATE / key) if writes else finish.closed(key, store, config.label_repos, stdin, config.pull_merged_status)
|
||||
return Stop(1, done.reason) if isinstance(done, Failure) else Stop(0, done)
|
||||
|
||||
|
||||
@@ -227,7 +230,8 @@ def dry_run_printed(epic: EpicRun) -> Stop:
|
||||
|
||||
def chunks_started(epic: EpicRun, issues: list[EpicIssue], own: str | None, told: str = "") -> scheduler.Started | Failure:
|
||||
"""scheduler.start_chunks on the epic's issues, as read, in order of score, and its cap, read afresh; own is the issue of the chunk that asks, and told is the reason the planning just gave for stopping, which isn't said twice. Where no issue is open, the chunk to start is the epic's finishing, unless the epic is closed."""
|
||||
closed = finish.due(issues) and epic.store.closed()
|
||||
due = finish.due(finish.landed(issues, epic.config.pull_merged_status))
|
||||
closed = due and epic.store.closed()
|
||||
if isinstance(closed, Failure):
|
||||
return closed
|
||||
order = planning.start_order(planned_epic(epic), issues)
|
||||
@@ -238,7 +242,7 @@ def chunks_started(epic: EpicRun, issues: list[EpicIssue], own: str | None, told
|
||||
scheduled = scheduled_epic(epic, () if isinstance(order, Failure) else tuple(order))
|
||||
if isinstance(scheduled, Failure):
|
||||
return scheduled
|
||||
started = scheduler.start_chunks(scheduled, issues, finish.due(issues) and not closed, own, epic.effects.tmux)
|
||||
started = scheduler.start_chunks(scheduled, issues, due and not closed, own, epic.effects.tmux)
|
||||
return started if isinstance(started, Failure) else dataclasses.replace(started, closed=closed)
|
||||
|
||||
|
||||
@@ -309,6 +313,10 @@ def chunk_run(key: str, epic: EpicRun) -> Stop:
|
||||
return Stop(1, unmade.reason)
|
||||
if issue:
|
||||
issue_started(key, epic)
|
||||
# The epic's working branch the chunk merges into; None where its repo keeps none, as for a chunk without a repo.
|
||||
based = epic_based(key, root, epic) if repo is not None else None
|
||||
if isinstance(based, Stop):
|
||||
return based
|
||||
session = session_named(f"A {epic.key} do-epic {key}", epic.paths.claude_code_transcripts)
|
||||
loop = Loop(root=root, session=session, window=tmux.Window(epic.session, key, pane), paths=epic.paths, env=epic.env, launcher=epic.launcher, effects=epic.effects)
|
||||
run = ChunkRun()
|
||||
@@ -334,7 +342,24 @@ def chunk_run(key: str, epic: EpicRun) -> Stop:
|
||||
news = parked_through(repo, loop, epic, told=news, finished=isinstance(concluded.verdict, Finished)) if repo is not None else ""
|
||||
# A chunk that was parked has work again, whatever the judge ruled before its pull request passed the gate.
|
||||
if isinstance(concluded.verdict, Finished) and news == "":
|
||||
return handed_on(key, epic, repo is not None)
|
||||
return handed_on(key, epic, repo is not None, to_epic_branch=based is not None)
|
||||
|
||||
|
||||
def epic_based(key: str, root: str, epic: EpicRun) -> str | None | Stop:
|
||||
"""Readies the epic's working branch for the chunk called key, whose repo is checked out at root: the branch, or None where the repo's config sets no `epic-branch`. It makes the branch on origin, or brings it level with the default branch, and records it as the base of the chunk's branch. A default branch that doesn't merge into it cleanly stops the loop, since a person resolves the conflict (docs/decisions.md → `epic-branch: an epic's chunks branch off and merge into a working branch …`)."""
|
||||
config = config_located(root, epic.paths.home)
|
||||
if isinstance(config, Failure):
|
||||
return Stop(1, config.reason)
|
||||
if config.epic_branch is None:
|
||||
return None
|
||||
branch = templates.epic_branch(config.epic_branch, epic.key)
|
||||
default = epic.effects.git("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=root)
|
||||
level = default if isinstance(default, Failure) else epic_branch.levelled(branch, default.strip(), cwd=root, run=epic.effects.git)
|
||||
readied = level if isinstance(level, Failure) else record_chunk_base(key, branch, cwd=root, run=epic.effects.git)
|
||||
if isinstance(readied, Failure):
|
||||
return Stop(1, f"cannot ready the epic's working branch {branch} in {root} for {key}: {readied.reason}; once that is settled, run `do-epic {epic.key}` to start the chunk again")
|
||||
say(f"{str(level).rstrip('.')}; {key}'s pull request goes into {branch}", epic.effects, stdout=True)
|
||||
return branch
|
||||
|
||||
|
||||
def issue_started(key: str, epic: EpicRun) -> None:
|
||||
@@ -360,7 +385,8 @@ def parked_through(repo: str, loop: Loop, epic: EpicRun, told: str | None, finis
|
||||
config = config_located(loop.root, epic.paths.home)
|
||||
if isinstance(config, Failure):
|
||||
return Stop(1, config.reason)
|
||||
poll = Poll(key, repo, config.merge == "human", folder, loop, epic)
|
||||
# A pull request into an epic's working branch merges without a person, whatever `merge` says.
|
||||
poll = Poll(key, repo, config.merge == "human" and config.epic_branch is None, folder, loop, epic)
|
||||
if key in recorded_as:
|
||||
return resumed_news(poll, recorded_as[key].on, shown=None)
|
||||
entered = None if told is None else poll.first_gate(again=finished)
|
||||
@@ -375,6 +401,10 @@ def parked_through(repo: str, loop: Loop, epic: EpicRun, told: str | None, finis
|
||||
return "" if uncleaned in (told or "") else uncleaned
|
||||
if failed := poll.record(entered):
|
||||
return Stop(1, failed.reason)
|
||||
if config.epic_branch is not None and (status := epic.config.pull_open_status):
|
||||
# The team's automation moves an issue only from a pull request into the default branch.
|
||||
if isinstance(moved := epic.store.move_issue(key, status), Failure):
|
||||
say(f"{key} did not move to {status!r} though its pull request is open: {moved.reason}", epic.effects, stdout=True)
|
||||
tmux.park(loop.window, entered.on, epic.effects.tmux)
|
||||
# Once the window shows as parked, so the chunks that start count it as running nowhere.
|
||||
issues = epic.store.read()
|
||||
@@ -490,12 +520,21 @@ def folder_made(root: str) -> Failure | None:
|
||||
return None
|
||||
|
||||
|
||||
def handed_on(key: str, epic: EpicRun, in_repo: bool = False, humans: bool = False) -> Stop:
|
||||
"""The stop of a do-epic whose chunk finished. It first moves the chunk's issue to done (the epic's finishing has none), and its split item too where that was the last of the item's sub-tasks, so that no finished chunk starts again and what they block may start, then starts each chunk that may start now. Where the team's automation moves issues, others move two kinds of issue. The automation moves the issue of a chunk in a repo, which in_repo marks, from its pull request: the stop waits for that move (`moved_by_automation`). The human moves their own task, which humans marks: the stop moves and awaits nothing. A chunk without a repo has no pull request, so its issue moves to done as ever, and so does a split item, once Jira counts each of its sub-tasks done. Its window closes as it exits."""
|
||||
def handed_on(key: str, epic: EpicRun, in_repo: bool = False, humans: bool = False, to_epic_branch: bool = False) -> Stop:
|
||||
"""The stop of a do-epic whose chunk finished. It first moves the chunk's issue to done (the epic's finishing has none), and its split item too where that was the last of the item's sub-tasks, so that no finished chunk starts again and what they block may start, then starts each chunk that may start now. Where the team's automation moves issues, others move two kinds of issue. The automation moves the issue of a chunk in a repo, which in_repo marks, from its pull request: the stop waits for that move (`moved_by_automation`). The human moves their own task, which humans marks: the stop moves and awaits nothing. A chunk without a repo has no pull request, so its issue moves to done as ever, and so does a split item, once Jira counts each of its sub-tasks done. The automation doesn't see a pull request that merged into an epic's working branch, which to_epic_branch marks: the stop moves that chunk's issue to the status `jira-pull-request-merged-status` names. Where none is named, it moves the issue to done, or stops where the automation moves issues, since nothing would. Its window closes as it exits."""
|
||||
automated = epic.config.automation_moves
|
||||
# The epic's finishing has no issue to move: the epic is closed by `--close-epic`. Nor has a human's task where the human moves it: its window waited until it holds up no issue.
|
||||
if key == epic.key or (humans and automated):
|
||||
issues: list[EpicIssue] | Failure = epic.store.read()
|
||||
elif to_epic_branch and (status := epic.config.pull_merged_status):
|
||||
moved = epic.store.move_issue(key, status)
|
||||
if isinstance(moved, Failure):
|
||||
return Stop(1, f"the chunk finished, but its issue could not move to {status!r}: {moved.reason}; once it has that status in Jira, run `do-epic {epic.key}` to start the chunks it blocks")
|
||||
issues = epic.store.read()
|
||||
# A search may not show the move yet, so the issue counts as moved here whatever the read says.
|
||||
issues = issues if isinstance(issues, Failure) else [dataclasses.replace(each, status=status) if each.key == key else each for each in issues]
|
||||
elif to_epic_branch and automated:
|
||||
return Stop(1, f"the chunk finished, but its issue stays as it is: its pull request merged into the epic's working branch, where the team's automation moves no issue, and do-epic's config names no `{PULL_MERGED_STATUS}` to move it to. Move {key} in Jira, then run `do-epic {epic.key}` to start the chunks it blocks")
|
||||
elif in_repo and automated:
|
||||
issues = moved_by_automation(key, epic)
|
||||
else:
|
||||
@@ -590,6 +629,7 @@ def chunk_work(key: str, checkout: str | None, language: str, epic: EpicRun) ->
|
||||
issues = epic.store.read()
|
||||
if isinstance(issues, Failure):
|
||||
return Stop(1, issues.reason)
|
||||
issues = finish.landed(issues, epic.config.pull_merged_status)
|
||||
if not finish.due(issues):
|
||||
return EpicReopened()
|
||||
return finish.task(epic.key, issues, epic.config.label_repos, epic.launcher, language), None
|
||||
|
||||
@@ -157,6 +157,24 @@ class ConfigTest(unittest.TestCase):
|
||||
self.write(SETTINGS + f"{setting} = {value}\n")
|
||||
self.assertIn(f'`{setting}` is {shown}, not the name Jira shows, such as "{example}"', self.failure())
|
||||
|
||||
def test_reads_the_statuses_of_an_issue_whose_pull_request_into_an_epic_branch_opened_and_merged(self) -> None:
|
||||
self.write(SETTINGS)
|
||||
found = load(self.home)
|
||||
assert isinstance(found, DoEpicConfig), found
|
||||
self.assertEqual((found.pull_open_status, found.pull_merged_status), (None, None))
|
||||
self.write(SETTINGS + 'jira-unblocking-statuses = ["release ready"]\njira-pull-request-open-status = "Code Review"\njira-pull-request-merged-status = "Release Ready"\n')
|
||||
found = load(self.home)
|
||||
assert isinstance(found, DoEpicConfig), found
|
||||
self.assertEqual((found.pull_open_status, found.pull_merged_status), ("Code Review", "Release Ready"))
|
||||
|
||||
def test_refuses_a_pull_request_status_that_is_no_name_and_a_merged_one_that_does_not_unblock(self) -> None:
|
||||
self.write(SETTINGS + 'jira-pull-request-open-status = " "\njira-pull-request-merged-status = 5\n')
|
||||
self.assertIn("`jira-pull-request-open-status` is ' ', not the name Jira shows, such as \"Code Review\"; `jira-pull-request-merged-status` is 5, not the name Jira shows, such as \"Release Ready\"", self.failure())
|
||||
for unblocking in ("", 'jira-unblocking-statuses = ["Shipped"]\n'):
|
||||
with self.subTest(unblocking=unblocking):
|
||||
self.write(SETTINGS + unblocking + 'jira-pull-request-merged-status = "Release Ready"\n')
|
||||
self.assertIn("`jira-pull-request-merged-status` is 'Release Ready', so `jira-unblocking-statuses` must list it: an issue at any other status reads as open, and its chunk would start again", self.failure())
|
||||
|
||||
def test_refuses_unblocking_statuses_that_are_no_list_of_names_and_a_switch_that_is_no_boolean(self) -> None:
|
||||
for value in ('"Done"', '["Done", " "]', "[]", "[1]"):
|
||||
with self.subTest(value=value):
|
||||
|
||||
@@ -17,6 +17,7 @@ from chunk_driver.claims import LOCK
|
||||
from do_epic.backend.fake import MemoryEpic
|
||||
from loop_state.paths import paths_from
|
||||
from claude_code.session import session_named
|
||||
from do_epic.test_do_epic import SETTINGS
|
||||
|
||||
LAUNCHER = pathlib.Path("/b/do-epic")
|
||||
REVIEWED = [issue("ABC-20", "repo:api", done=True), issue("ABC-21", "do-epic-claude", done=True), issue("ABC-30", "repo:api", "do-epic-release-review", done=True)]
|
||||
@@ -34,6 +35,13 @@ class WhenTheFinishingIsDue(DoEpicTest):
|
||||
self.assertIs(finish.due(split), True)
|
||||
self.assertIs(finish.due([*split, issue("ABC-41", "repo:web", parent="ABC-20")]), False)
|
||||
|
||||
def test_an_issue_at_the_merged_status_counts_as_done_and_any_other_stays_as_it_is(self) -> None:
|
||||
issues = [issue("ABC-20", "repo:api", status="release ready"), issue("ABC-21", "repo:api", status="Code Review"), issue("ABC-22", done=True)]
|
||||
self.assertFalse(finish.due(issues))
|
||||
self.assertEqual([each.done for each in finish.landed(issues, "Release Ready")], [True, False, True])
|
||||
self.assertEqual(finish.landed(issues, None), issues)
|
||||
self.assertEqual(finish.unreviewed(finish.landed(issues[:1], "Release Ready"), {}), ["api"])
|
||||
|
||||
def test_a_repo_lacks_its_review_while_a_done_issue_names_it_and_no_review_does(self) -> None:
|
||||
done = [issue("ABC-20", "repo:web", done=True), issue("ABC-21", "repo:api", done=True), issue("ABC-22", "do-epic-claude", done=True), issue("ABC-23", "repo:docs")]
|
||||
self.assertEqual(finish.unreviewed(done, {}), ["api", "web"])
|
||||
@@ -72,6 +80,8 @@ class TheFinishingChunksTask(DoEpicTest):
|
||||
self.assertIn("ask the human to approve the set", task)
|
||||
self.assertIn("`/b/do-epic ABC-12 --close-epic`", task)
|
||||
self.assertIn("in Swedish", task)
|
||||
self.assertIn("3. Once the human has confirmed every goal, open the epic's pull request in each repo it changed whose config sets `epic-branch`: in that repo's checkout, `project-config epic-branch` prints the setting, and fails where the config sets none. There, run `chunk-pr open-epic ABC-12 \"<title>\"`", task)
|
||||
self.assertIn("Never merge it: a person does. Name each such pull request in the summary.\n4. Then write a summary", task)
|
||||
self.assertIn(findings.instructions("ABC-12", LAUNCHER, "Swedish", {}), task)
|
||||
self.assertIn("The epic's issues, each done:\n\n- ABC-20 (api): Do ABC-20\n- ABC-21: Do ABC-21\n- ABC-30 (api): Do ABC-30", task)
|
||||
self.assertNotIn("do-epic-release-review`", task)
|
||||
@@ -123,6 +133,13 @@ class ClosingTheEpic(DoEpicTest):
|
||||
store, _ = main.jira_backend(config, "ABC-12")
|
||||
self.assertEqual(store.finish, Finish("Mark as done", "Done")) # type: ignore[attr-defined]
|
||||
|
||||
def test_closes_an_epic_whose_open_issues_all_have_the_merged_status(self) -> None:
|
||||
(self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n', encoding="utf-8")
|
||||
self.issues.append(issue("ABC-31", "repo:api", status="Release Ready"))
|
||||
code, out, err = self.close()
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertIs(self.store.done, True)
|
||||
|
||||
def test_refuses_while_an_issue_is_open(self) -> None:
|
||||
self.issues.append(issue("ABC-31", "repo:api"))
|
||||
code, _, err = self.close()
|
||||
@@ -182,6 +199,14 @@ class TheFinishingChunk(DoEpicTest):
|
||||
self.assertEqual(self.started(fake), ["ABC-12"])
|
||||
self.assertIn(["/b/do-epic", "--chunk", "ABC-12", "ABC-12"], [args[-4:] for args in fake.tmux_calls])
|
||||
|
||||
def test_starts_once_each_open_issue_has_the_merged_status(self) -> None:
|
||||
(self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n', encoding="utf-8")
|
||||
self.issues = [issue("ABC-20", "do-epic-claude", status="Release Ready"), issue("ABC-21", "do-epic-claude", done=True)]
|
||||
fake = FakeEffects(on_terminal=False)
|
||||
code, out, err = self.run_main(["ABC-12"], fake)
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual(self.started(fake), ["ABC-12"])
|
||||
|
||||
def test_doesnt_start_while_an_issue_is_open_or_in_an_epic_without_issues(self) -> None:
|
||||
for issues in ([issue("ABC-20", "do-epic-claude", done=True), issue("ABC-21", "do-epic-human")], []):
|
||||
self.issues = issues
|
||||
|
||||
@@ -38,6 +38,7 @@ class Forge:
|
||||
"git remote": origin + "\n",
|
||||
"git rev-parse": HEAD + "\n",
|
||||
"git symbolic-ref": "origin/main\n",
|
||||
"git config": Failure("git config: unset"),
|
||||
"gh pr list": pulls,
|
||||
"gh pr view": json.dumps({"isDraft": draft, "reviewDecision": decision, "author": {"login": "worker"}, "reviews": list(reviews), "comments": list(comments), "mergeable": mergeable, "mergeStateStatus": merge_state}),
|
||||
"gh pr checks": json.dumps([{"bucket": bucket} for bucket in buckets]),
|
||||
@@ -120,6 +121,14 @@ class GateOfAChunk(unittest.TestCase):
|
||||
self.assertEqual(Forge(gitea, status='{"state": "pending", "total_count": 1}').gate(), Gate("/code/billing-ABC-21", "7", CHECKS))
|
||||
self.assertEqual(Forge(gitea).gate(), Open("pull request #7 passed its checks"))
|
||||
|
||||
def test_a_chunk_that_merges_into_an_epics_working_branch_reads_the_checks_that_branch_requires(self):
|
||||
forge = Forge("https://gitea.larvit.se/o/billing.git")
|
||||
forge.answers["git config"] = "ABC-12\n"
|
||||
forge.answers["tea api repos/{owner}/{repo}/branches/ABC-12"] = '{"enable_status_check": true, "status_check_contexts": ["epic-gate"]}'
|
||||
self.assertEqual(forge.gate(), Gate("/code/billing-ABC-21", "7", CHECKS))
|
||||
self.assertIn(["git", "config", "--get", "branch.ABC-21.chunk-base"], forge.commands)
|
||||
self.assertNotIn(["tea", "api", "repos/{owner}/{repo}/branches/main"], forge.commands)
|
||||
|
||||
def test_a_gitea_draft_awaits_nothing_though_its_checks_run(self):
|
||||
gitea = "https://gitea.larvit.se/o/billing.git"
|
||||
for title in ("WIP: Add x", "[wip] Add x"):
|
||||
|
||||
@@ -983,6 +983,90 @@ class AChunkWhosePullRequestWaitsOnAGate(DoEpicTest):
|
||||
self.assertIn(f"cannot remove {self.file}: Permission denied", err)
|
||||
|
||||
|
||||
class AnEpicsWorkingBranch(DoEpicTest):
|
||||
"""A chunk in a repo whose config sets `epic-branch`, so its pull request goes into the branch ABC-12."""
|
||||
|
||||
def setUp(self) -> None:
|
||||
super().setUp()
|
||||
self.repo_config = self.repo_chunk() / "config.toml"
|
||||
self.repo_config.write_text(self.repo_config.read_text(encoding="utf-8") + 'epic-branch = "{epic}"\nmerge = "human"\n', encoding="utf-8")
|
||||
self.checkout = str(self.home / "code/api")
|
||||
self.store = MemoryEpic("ABC-12", [self.issues[0], issue("ABC-22", "do-epic-claude", blockers=("ABC-20",))])
|
||||
self.backend = lambda config, key: (self.store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
|
||||
self.git_calls: list[tuple[tuple[str, ...], str | None]] = []
|
||||
|
||||
def settings(self, more: str) -> None:
|
||||
(self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + more, encoding="utf-8")
|
||||
|
||||
def with_git(self, fake: FakeEffects, **answers: str | Failure) -> FakeEffects:
|
||||
"""fake, whose git answers each command by its first word: as answers has it, else as a checkout whose origin has the branch ABC-12, which holds origin/main."""
|
||||
answered = {"symbolic-ref": "origin/main\n", "fetch": "", "rev-parse": "aaa\n", "rev-list": "0\n", "config": ""} | {name.replace("_", "-"): answer for name, answer in answers.items()}
|
||||
|
||||
def git(*args: str, cwd: str | None = None, **more: object) -> str | Failure:
|
||||
self.git_calls.append((args, cwd))
|
||||
return answered.get(args[0], Failure("no git"))
|
||||
fake.effects = lambda made=fake.effects(): dataclasses.replace(made, git=git) # type: ignore[method-assign]
|
||||
return fake
|
||||
|
||||
def test_a_chunk_that_starts_levels_the_branch_and_records_it_as_the_chunks_base(self) -> None:
|
||||
fake = self.with_git(FakeEffects())
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out):
|
||||
self.assertEqual(main.epic_based("ABC-20", self.checkout, self.epic_run(fake)), "ABC-12")
|
||||
self.assertEqual(self.git_calls, [(args, self.checkout) for args in (("symbolic-ref", "--short", "refs/remotes/origin/HEAD"), ("fetch", "--quiet", "origin"), ("rev-parse", "--quiet", "--verify", "refs/remotes/origin/ABC-12"), ("rev-list", "--count", "origin/ABC-12..origin/main"), ("config", "branch.ABC-20.chunk-base", "ABC-12"))])
|
||||
self.assertIn("origin/ABC-12 already holds origin/main; ABC-20's pull request goes into ABC-12\n", out.getvalue())
|
||||
|
||||
def test_a_repo_whose_config_sets_no_epic_branch_has_none_and_runs_no_git(self) -> None:
|
||||
self.repo_config.write_text(self.repo_config.read_text(encoding="utf-8").replace('epic-branch = "{epic}"\n', ""), encoding="utf-8")
|
||||
self.assertIsNone(main.epic_based("ABC-20", self.checkout, self.epic_run(self.with_git(FakeEffects()))))
|
||||
self.assertEqual(self.git_calls, [])
|
||||
|
||||
def test_a_default_branch_that_conflicts_stops_the_loop_for_a_person_and_records_no_base(self) -> None:
|
||||
stop = main.epic_based("ABC-20", self.checkout, self.epic_run(self.with_git(FakeEffects(), rev_list="1\n", merge_tree=Failure("CONFLICT"))))
|
||||
self.assertEqual(stop, main.Stop(1, f"cannot ready the epic's working branch ABC-12 in {self.checkout} for ABC-20: origin/main doesn't merge into origin/ABC-12 cleanly, so a person merges it: check ABC-12 out, run `git merge origin/main`, resolve the conflicts and push; once that is settled, run `do-epic ABC-12` to start the chunk again"))
|
||||
self.assertNotIn("config", [args[0] for args, _ in self.git_calls])
|
||||
|
||||
def test_a_checkout_that_names_no_default_branch_stops_before_the_branch_is_touched(self) -> None:
|
||||
stop = main.epic_based("ABC-20", self.checkout, self.epic_run(self.with_git(FakeEffects(), symbolic_ref=Failure("no origin/HEAD"))))
|
||||
self.assertIsInstance(stop, main.Stop)
|
||||
self.assertIn("no origin/HEAD", stop.reason)
|
||||
self.assertEqual(len(self.git_calls), 1)
|
||||
|
||||
def test_its_issue_moves_as_the_pull_request_opens_and_merges_and_no_person_merges_it(self) -> None:
|
||||
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-automation-moves-issues = true\njira-pull-request-open-status = "Code Review"\njira-pull-request-merged-status = "Release Ready"\n')
|
||||
self.forges = [awaiting(), awaiting(), awaiting(decision="APPROVED")]
|
||||
fake = self.with_git(FakeEffects(streams=[self.worker(), self.worker()], claude=[judged("finished"), judged("finished")], windows=PARKED_WINDOW))
|
||||
code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS)
|
||||
prompts = [what[what.index("-p") + 1] for seam, what in fake.calls if seam == "stream_claude"]
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual([write for write in self.store.writes if write.startswith("move ")], ["move ABC-20 to Code Review", "move ABC-20 to Release Ready"])
|
||||
self.assertEqual({each.key: (each.status, each.done) for each in self.store.issues}["ABC-20"], ("Release Ready", False))
|
||||
# Approved, the pull request awaits no person's merge, though the repo's config says `merge = "human"`.
|
||||
self.assertEqual(out.count("parked: "), 1)
|
||||
self.assertIn("parked: pull request #7 awaits an approval\n", out)
|
||||
self.assertIn("the chunk finished; started ABC-22\n", out)
|
||||
self.assertIn("The chunk's pull request goes into the epic's working branch `ABC-12`", prompts[0])
|
||||
|
||||
def test_without_a_merged_status_a_finished_chunk_stops_where_automation_moves_issues_and_is_done_where_it_doesnt(self) -> None:
|
||||
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-automation-moves-issues = true\n')
|
||||
stop = main.handed_on("ABC-20", self.epic_run(FakeEffects()), in_repo=True, to_epic_branch=True)
|
||||
self.assertEqual(stop, main.Stop(1, "the chunk finished, but its issue stays as it is: its pull request merged into the epic's working branch, where the team's automation moves no issue, and do-epic's config names no `jira-pull-request-merged-status` to move it to. Move ABC-20 in Jira, then run `do-epic ABC-12` to start the chunks it blocks"))
|
||||
self.assertEqual(self.store.writes, [])
|
||||
self.settings("")
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out):
|
||||
self.assertEqual(main.handed_on("ABC-20", self.epic_run(FakeEffects(windows="")), in_repo=True, to_epic_branch=True).code, 0)
|
||||
self.assertTrue(self.store.issues[0].done)
|
||||
|
||||
def test_an_issue_that_cannot_move_to_the_merged_status_stops_and_says_what_to_do(self) -> None:
|
||||
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n')
|
||||
self.store.fails = "Jira answered 503"
|
||||
stop = main.handed_on("ABC-20", self.epic_run(FakeEffects()), in_repo=True, to_epic_branch=True)
|
||||
self.assertEqual(stop.code, 1)
|
||||
self.assertTrue(stop.reason.startswith("the chunk finished, but its issue could not move to 'Release Ready': "), stop.reason)
|
||||
self.assertTrue(stop.reason.endswith("once it has that status in Jira, run `do-epic ABC-12` to start the chunks it blocks"), stop.reason)
|
||||
|
||||
|
||||
class TheStatus(DoEpicTest):
|
||||
def test_prints_what_each_open_issue_does_and_starts_nothing(self) -> None:
|
||||
self.issues = [issue("ABC-21", "repo:api"), issue("ABC-24", "repo:api"), issue("ABC-27")]
|
||||
|
||||
@@ -465,6 +465,26 @@ class TheFirstPrompt(unittest.TestCase):
|
||||
self.assertIn("leave the changelog as it is", told)
|
||||
self.assertNotIn("## Unreleased", told)
|
||||
|
||||
def test_a_repo_with_an_epic_branch_is_told_to_branch_off_it_and_that_the_merge_needs_no_person(self) -> None:
|
||||
config = dataclasses.replace(CONFIG, epic_branch="epic/{epic}", merge="human")
|
||||
task = chunk_prompt.task(issue("ABC-20"), "ABC-12", {}, "/code/api", pathlib.Path("/b/do-epic"), "Swedish", config)
|
||||
self.assertIn("The chunk's pull request goes into the epic's working branch `epic/ABC-12`, not into the default branch", task)
|
||||
self.assertIn("make the chunk's worktree and branch off `origin/epic/ABC-12`", task)
|
||||
self.assertIn("`chunk-pr merge` merges into `epic/ABC-12` without waiting for a person", task)
|
||||
self.assertNotIn("leaves the pull request ready for a person to merge", task)
|
||||
self.assertIn("Test each sibling repo at its branch `epic/ABC-12` where it has one, else at its default branch, and name in the chunk's summary each sibling that ran at its default branch.", task)
|
||||
self.assertNotIn("chunk-pr push", task)
|
||||
|
||||
def test_a_repo_whose_reviewer_is_asked_by_a_comment_is_told_to_push_with_chunk_pr(self) -> None:
|
||||
config = dataclasses.replace(CONFIG, epic_branch="{epic}", review_request_comment="@reviewbot review")
|
||||
task = chunk_prompt.task(issue("ABC-20"), "ABC-12", {}, "/code/api", pathlib.Path("/b/do-epic"), "Swedish", config)
|
||||
self.assertIn("Push each later commit to the open pull request with `chunk-pr push`, which asks the repo's auto-reviewer for a review of the new head, and wait for that review.", task)
|
||||
|
||||
def test_a_repo_without_an_epic_branch_is_told_nothing_of_one(self) -> None:
|
||||
task = chunk_prompt.task(issue("ABC-20"), "ABC-12", {}, "/code/api", pathlib.Path("/b/do-epic"), "Swedish", dataclasses.replace(CONFIG, merge="human"))
|
||||
self.assertNotIn("working branch", task)
|
||||
self.assertIn("leaves the pull request ready for a person to merge", task)
|
||||
|
||||
def test_an_answer_the_judge_quoted_names_the_epics_description_first(self) -> None:
|
||||
self.assertTrue(chunk_prompt.WORKER.answered("Q", "A", Route(Rung("off-the-ladder")), None, False).startswith("Your question: Q\n\nthe epic's description, "))
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Keep an epic's working branch on origin: made off the default branch by the epic's first chunk, and level with it before each chunk starts and before the epic's own pull request opens (docs/decisions.md → `epic-branch: an epic's chunks branch off and merge into a working branch …`)."""
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import Git, git
|
||||
|
||||
|
||||
def levelled(branch: str, default: str, cwd: str | None = None, timeout: float | None = None, run: Git = git) -> str | Failure:
|
||||
"""Brings origin's branch level with default, the default branch's ref, such as `origin/main`, and fetches it: what it did, as a sentence. Where origin has no such branch, it makes one at default.
|
||||
|
||||
It merges with a merge commit, never a rebase, since several chunks share the branch, and without a checkout, since no worktree has the branch checked out. A Failure where the two don't merge cleanly: a person resolves that, never the loop. A call to origin still running after timeout seconds fails."""
|
||||
fetched = run("fetch", "--quiet", "origin", cwd=cwd, timeout=timeout)
|
||||
if isinstance(fetched, Failure):
|
||||
return fetched
|
||||
ours = f"origin/{branch}"
|
||||
if isinstance(run("rev-parse", "--quiet", "--verify", f"refs/remotes/{ours}", cwd=cwd), Failure):
|
||||
return pushed(default, branch, cwd, timeout, run) or f"Made {ours} off {default}."
|
||||
behind = run("rev-list", "--count", f"{ours}..{default}", cwd=cwd)
|
||||
if isinstance(behind, Failure):
|
||||
return behind
|
||||
if behind.strip() == "0":
|
||||
return f"{ours} already holds {default}."
|
||||
# git 2.38 or later: merges two commits into a tree without a checkout.
|
||||
tree = run("merge-tree", "--write-tree", ours, default, cwd=cwd)
|
||||
if isinstance(tree, Failure):
|
||||
return Failure(f"{default} doesn't merge into {ours} cleanly, so a person merges it: check {branch} out, run `git merge {default}`, resolve the conflicts and push")
|
||||
commit = run("commit-tree", tree.strip(), "-p", ours, "-p", default, "-m", f"Merge remote-tracking branch '{default}' into {branch}", cwd=cwd)
|
||||
if isinstance(commit, Failure):
|
||||
return commit
|
||||
return pushed(commit.strip(), branch, cwd, timeout, run) or f"Merged {default} into {ours}."
|
||||
|
||||
|
||||
def pushed(commit: str, branch: str, cwd: str | None, timeout: float | None, run: Git) -> Failure | None:
|
||||
"""Pushes commit as origin's branch, without force, so a push that raced another's fails, and fetches it."""
|
||||
for args in (["push", "--quiet", "origin", f"{commit}:refs/heads/{branch}"], ["fetch", "--quiet", "origin"]):
|
||||
done = run(*args, cwd=cwd, timeout=timeout)
|
||||
if isinstance(done, Failure):
|
||||
return done
|
||||
return None
|
||||
+22
-1
@@ -23,6 +23,10 @@ GUARD_SETTINGS = [
|
||||
]
|
||||
|
||||
|
||||
# The key, under `branch.<a chunk's branch>` in a checkout's git config, that names the epic's working branch the chunk merges into (docs/decisions.md → `epic-branch: an epic's chunks branch off and merge into a working branch …`).
|
||||
CHUNK_BASE = "chunk-base"
|
||||
|
||||
|
||||
def git(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict", env: typing.Mapping[str, str] | None = None) -> str | Failure:
|
||||
"""What git printed, run in cwd, else in the current directory.
|
||||
|
||||
@@ -72,13 +76,15 @@ def default_branch(stale_ok: bool, timeout: float | None = None) -> tuple[str, s
|
||||
|
||||
|
||||
def default_ref(cwd: str | None = None, timeout: float | None = None, guarded: bool = False, run: Git = git) -> str | Failure:
|
||||
"""The default branch's ref as last fetched, read in cwd, else in the current directory: `origin/<branch>` with that remote, else the local main or master. run runs git.
|
||||
"""The ref the branch checked out merges into, as last fetched, read in cwd, else in the current directory. That is the default branch's: `origin/<branch>` with that remote, else the local main or master. On a chunk's branch that merges into an epic's working branch (`chunk_base`), it is `origin/<that branch>`, so each tool that measures a chunk against its base reads the chunk's own commits and not the epic's. run runs git.
|
||||
|
||||
Where the checkout records no default branch for origin, it asks origin, which fails after timeout seconds. Guarded, it runs git as `git` does with guarded, and fails there instead of asking origin."""
|
||||
remotes = run("remote", cwd=cwd, guarded=guarded)
|
||||
if isinstance(remotes, Failure):
|
||||
return remotes
|
||||
if "origin" in remotes.split():
|
||||
if base := chunk_base(cwd, guarded, run):
|
||||
return f"origin/{base}"
|
||||
recorded = run("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=cwd, guarded=guarded)
|
||||
if not isinstance(recorded, Failure):
|
||||
return recorded.strip()
|
||||
@@ -89,6 +95,21 @@ def default_ref(cwd: str | None = None, timeout: float | None = None, guarded: b
|
||||
return Failure("no origin remote, and no main or master branch to take as the default branch")
|
||||
|
||||
|
||||
def chunk_base(cwd: str | None = None, guarded: bool = False, run: Git = git) -> str | None:
|
||||
"""The epic's working branch that the branch checked out in cwd merges into, as `record_chunk_base` recorded it; None where none is recorded, as for every branch that merges into the default branch, and on a detached HEAD."""
|
||||
branch = run("symbolic-ref", "--quiet", "--short", "HEAD", cwd=cwd, guarded=guarded)
|
||||
if isinstance(branch, Failure):
|
||||
return None
|
||||
base = run("config", "--get", f"branch.{branch.strip()}.{CHUNK_BASE}", cwd=cwd, guarded=guarded)
|
||||
return None if isinstance(base, Failure) else base.strip() or None
|
||||
|
||||
|
||||
def record_chunk_base(branch: str, base: str, cwd: str | None = None, run: Git = git) -> Failure | None:
|
||||
"""Records in the checkout's git config that the chunk's branch merges into base, an epic's working branch. The branch need not exist yet, and deleting it removes the record."""
|
||||
recorded = run("config", f"branch.{branch}.{CHUNK_BASE}", base, cwd=cwd)
|
||||
return recorded if isinstance(recorded, Failure) else None
|
||||
|
||||
|
||||
def branch_titles(default: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False) -> list[str] | Failure:
|
||||
"""The titles of the branch's own commits since default, newest first, read in cwd, else in the current directory.
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from failure import Failure
|
||||
from git_cli import git_repo
|
||||
from git_cli.epic_branch import levelled
|
||||
|
||||
|
||||
def sh(cwd: pathlib.Path, *args: str) -> str:
|
||||
return subprocess.run(["git", "-c", "user.name=T", "-c", "user.email=t@example.com", *args], cwd=cwd, check=True, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
class Levelled(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(folder.cleanup)
|
||||
self.origin, self.clone = pathlib.Path(folder.name) / "origin.git", pathlib.Path(folder.name) / "clone"
|
||||
sh(pathlib.Path(folder.name), "init", "--quiet", "--bare", "--initial-branch=main", str(self.origin))
|
||||
sh(pathlib.Path(folder.name), "clone", "--quiet", str(self.origin), str(self.clone))
|
||||
sh(self.clone, "config", "user.name", "T")
|
||||
sh(self.clone, "config", "user.email", "t@example.com")
|
||||
self.commit("main", "a.txt", "one\n")
|
||||
|
||||
def commit(self, branch: str, file: str, text: str) -> None:
|
||||
"""Commits text as file on origin's branch, made off origin/main where origin has none."""
|
||||
sh(self.clone, "fetch", "--quiet", "origin")
|
||||
known = subprocess.run(["git", "rev-parse", "--quiet", "--verify", f"refs/remotes/origin/{branch}"], cwd=self.clone, capture_output=True).returncode == 0
|
||||
sh(self.clone, "checkout", "--quiet", "-B", "scratch", *([f"origin/{branch}"] if known else []))
|
||||
(self.clone / file).write_text(text)
|
||||
sh(self.clone, "add", file)
|
||||
sh(self.clone, "commit", "--quiet", "-m", f"{file} on {branch}")
|
||||
sh(self.clone, "push", "--quiet", "origin", f"HEAD:refs/heads/{branch}")
|
||||
sh(self.clone, "fetch", "--quiet", "origin")
|
||||
|
||||
def test_makes_the_branch_off_the_default_branch_where_origin_has_none(self) -> None:
|
||||
self.assertEqual(levelled("ABC-1", "origin/main", cwd=str(self.clone)), "Made origin/ABC-1 off origin/main.")
|
||||
self.assertEqual(sh(self.origin, "rev-parse", "ABC-1"), sh(self.origin, "rev-parse", "main"))
|
||||
self.assertEqual(sh(self.clone, "rev-parse", "origin/ABC-1"), sh(self.origin, "rev-parse", "main"), "fetched, so a worktree can branch off it")
|
||||
|
||||
def test_leaves_a_branch_that_holds_the_default_branch(self) -> None:
|
||||
self.commit("ABC-1", "b.txt", "epic\n")
|
||||
before = sh(self.origin, "rev-parse", "ABC-1")
|
||||
self.assertEqual(levelled("ABC-1", "origin/main", cwd=str(self.clone)), "origin/ABC-1 already holds origin/main.")
|
||||
self.assertEqual(sh(self.origin, "rev-parse", "ABC-1"), before)
|
||||
|
||||
def test_merges_a_moved_default_branch_in_with_a_merge_commit_and_no_checkout(self) -> None:
|
||||
self.commit("ABC-1", "b.txt", "epic\n")
|
||||
epic = sh(self.origin, "rev-parse", "ABC-1")
|
||||
self.commit("main", "c.txt", "main\n")
|
||||
checked_out = sh(self.clone, "rev-parse", "HEAD")
|
||||
self.assertEqual(levelled("ABC-1", "origin/main", cwd=str(self.clone)), "Merged origin/main into origin/ABC-1.")
|
||||
self.assertEqual(sh(self.origin, "rev-list", "--parents", "-n", "1", "ABC-1").split()[1:], [epic, sh(self.origin, "rev-parse", "main")])
|
||||
self.assertEqual(sh(self.origin, "ls-tree", "--name-only", "ABC-1").split(), ["a.txt", "b.txt", "c.txt"])
|
||||
self.assertEqual(sh(self.origin, "log", "-1", "--format=%s", "ABC-1"), "Merge remote-tracking branch 'origin/main' into ABC-1")
|
||||
self.assertEqual(sh(self.clone, "rev-parse", "origin/ABC-1"), sh(self.origin, "rev-parse", "ABC-1"))
|
||||
self.assertEqual(sh(self.clone, "rev-parse", "HEAD"), checked_out)
|
||||
|
||||
def test_a_conflict_fails_for_a_person_and_leaves_the_branch(self) -> None:
|
||||
self.commit("ABC-1", "a.txt", "epic\n")
|
||||
before = sh(self.origin, "rev-parse", "ABC-1")
|
||||
self.commit("main", "a.txt", "main\n")
|
||||
done = levelled("ABC-1", "origin/main", cwd=str(self.clone))
|
||||
assert isinstance(done, Failure), done
|
||||
self.assertEqual(done.reason, "origin/main doesn't merge into origin/ABC-1 cleanly, so a person merges it: check ABC-1 out, run `git merge origin/main`, resolve the conflicts and push")
|
||||
self.assertEqual(sh(self.origin, "rev-parse", "ABC-1"), before)
|
||||
|
||||
|
||||
class ChunkBase(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(folder.cleanup)
|
||||
self.clone = pathlib.Path(folder.name)
|
||||
sh(self.clone, "init", "--quiet", "--initial-branch=main")
|
||||
sh(self.clone, "remote", "add", "origin", "https://example.com/acme.git")
|
||||
sh(self.clone, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main")
|
||||
|
||||
def test_a_branch_with_a_recorded_base_measures_against_it_and_any_other_against_the_default_branch(self) -> None:
|
||||
self.assertIsNone(git_repo.record_chunk_base("ABC-2", "ABC-1", cwd=str(self.clone)))
|
||||
self.assertEqual(git_repo.default_ref(cwd=str(self.clone)), "origin/main", "main has no recorded base")
|
||||
sh(self.clone, "checkout", "--quiet", "-b", "ABC-2")
|
||||
self.assertEqual(git_repo.chunk_base(cwd=str(self.clone)), "ABC-1")
|
||||
self.assertEqual(git_repo.default_ref(cwd=str(self.clone)), "origin/ABC-1")
|
||||
self.assertEqual(git_repo.default_ref(cwd=str(self.clone), guarded=True), "origin/ABC-1")
|
||||
sh(self.clone, "checkout", "--quiet", "-b", "ABC-3")
|
||||
self.assertIsNone(git_repo.chunk_base(cwd=str(self.clone)))
|
||||
self.assertEqual(git_repo.default_ref(cwd=str(self.clone)), "origin/main")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -21,6 +21,9 @@ from plan_store.todo_md import plan_of
|
||||
from claude_code import session
|
||||
from agent_cycle import tmux
|
||||
|
||||
# What git answers as `default_ref` reads the default branch in a checkout on main: the remote, the branch checked out, no chunk base, and origin's default branch.
|
||||
ON_MAIN = ["origin\n", "main\n", Failure("no chunk base"), "origin/main\n"]
|
||||
|
||||
|
||||
class RouteSources(unittest.TestCase):
|
||||
def test_routes_on_the_plan_item_and_says_why_it_routes_on_the_projects_rung(self):
|
||||
@@ -45,7 +48,7 @@ class RouteSources(unittest.TestCase):
|
||||
transcript.parent.mkdir(parents=True)
|
||||
transcript.write_text("")
|
||||
unread = Failure("no git")
|
||||
fake = FakeEffects(git=["origin\n", "origin/main\n", unread, unread, unread, unread])
|
||||
fake = FakeEffects(git=[*ON_MAIN, unread, unread, unread, unread])
|
||||
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
||||
facts, held = chunk_start.chunk_start(a_loop(fake.effects(), root=root, session=opened, paths=paths.paths_from(folder.parents[1])))
|
||||
self.assertEqual((facts, held.plan), ("", plan_of(TODO)))
|
||||
@@ -70,7 +73,7 @@ class RouteSources(unittest.TestCase):
|
||||
|
||||
def test_reads_the_changelog_the_default_branch_holds_through_the_loops_git(self):
|
||||
def git(*args, **options):
|
||||
answers = {"remote": "origin\n", "symbolic-ref": "origin/main\n", "show": f"what {args[-1]} holds\n"}
|
||||
answers = {"remote": "origin\n", "symbolic-ref": "origin/main\n", "config": Failure("no chunk base"), "show": f"what {args[-1]} holds\n"}
|
||||
return answers.get(args[0], "1\n")
|
||||
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
@@ -105,21 +108,21 @@ class RouteSources(unittest.TestCase):
|
||||
def test_reads_a_plan_outside_the_checkout_as_it_stands_and_stops_without_a_config(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = configured(self, pathlib.Path(root))
|
||||
loop = a_loop(FakeEffects(git=["origin\n", "origin/main\n"] * 2).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
|
||||
loop = a_loop(FakeEffects(git=[*ON_MAIN] * 2).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
|
||||
config = folder / "config.toml"
|
||||
tracked = a_loop(FakeEffects(git=["origin\n", "origin/main\n", *[Failure("no git")] * 4]).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
|
||||
tracked = a_loop(FakeEffects(git=[*ON_MAIN, *[Failure("no git")] * 4]).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
|
||||
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
||||
chunk_start.fetched_plan(tracked)
|
||||
self.assertEqual(stderr.getvalue(), "", "a plan git tracks hides no release")
|
||||
config.write_text(config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"'))
|
||||
(folder / "todo.md").write_text(TODO)
|
||||
unread = Failure("no git")
|
||||
standing = a_loop(FakeEffects(git=["origin\n", "origin/main\n", unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
|
||||
standing = a_loop(FakeEffects(git=[*ON_MAIN, unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
|
||||
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
||||
held = chunk_start.fetched_plan(standing)
|
||||
self.assertEqual((held.plan, held.cut.todos_since, held.cut.changelog), (plan_of(TODO), [], ""), "the plan as it stands, whatever git answers")
|
||||
self.assertEqual(stderr.getvalue(), f"{STAMP} {UNSEEN_RELEASES}\n", "a release review loop-claude cannot call due is never skipped silently")
|
||||
quiet = a_loop(FakeEffects(git=["origin\n", "origin/main\n", unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
|
||||
quiet = a_loop(FakeEffects(git=[*ON_MAIN, unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
|
||||
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
||||
chunk_start.fetched_plan(quiet, announce=False)
|
||||
self.assertEqual(stderr.getvalue(), "", "said once per chunk, as it starts")
|
||||
|
||||
@@ -103,6 +103,20 @@ it is true.
|
||||
`chunk-pr merge` leaves the pull request ready and says it awaits a person's merge. `project-config merge`
|
||||
prints chunk or human; the full listing shows the setting only where it is human.
|
||||
|
||||
`epic-branch` is an optional setting: a template that names the working branch of the Jira epic `plan`
|
||||
names, with {epic} for the epic's key, such as `epic-branch = "{epic}"` or "epic/{epic}". Each chunk then
|
||||
branches off that branch, and `chunk-pr` opens its pull request into it and merges it there without a
|
||||
person, whatever `merge` and `wait-for-approval` say: those guard the default branch. `chunk-preflight`
|
||||
makes the branch on origin off the default branch, or merges the default branch into it, and stops where
|
||||
that merge conflicts, which a person resolves. `chunk-pr open-epic` opens the pull request from the branch
|
||||
into the default branch, which a person merges. Left out, each chunk merges into the default branch.
|
||||
|
||||
`review-request-comment` is an optional setting, one line of text: the comment that asks the project's
|
||||
auto-reviewer for a review, such as "@reviewbot review", for a reviewer that on its own reviews only
|
||||
pull requests into the default branch. `chunk-pr ready` and `chunk-pr push` post it on a pull request
|
||||
into the epic's working branch. It requires `epic-branch`. Left out, no comment is posted.
|
||||
Each of the two is printed with the others only where it is set.
|
||||
|
||||
`tooling-on-host` is an optional setting, true or false: whether the loop may run the project's language
|
||||
runtime, package manager, tests and task runner directly on the host, for a project with no container
|
||||
setup. Left out, it is false, and they run through the project's container setup.
|
||||
@@ -151,12 +165,12 @@ and its commits and pull request are titled "ABC-123 - …".
|
||||
|
||||
Exit 1, naming each fault on stderr, where no config names the checkout, or its config leaves out a
|
||||
setting, names an unknown one, misspells a path, a language or a template, sets `coding-conventions` to anything but a list of paths, sets `wait-for-approval` or
|
||||
`tooling-on-host` to anything but true or false, sets `merge` to anything but chunk or human, sets `notifier` to anything but mattermost or slack or
|
||||
`tooling-on-host` to anything but true or false, sets `merge` to anything but chunk or human, sets `epic-branch` to anything but a branch name with one {epic}, sets `review-request-comment` to anything but one line of text or without `epic-branch`, sets `notifier` to anything but mattermost or slack or
|
||||
without `env-file`, sets `jira-finish-transition` or `jira-finish-status` to anything but a name, without the other or
|
||||
without a `plan` in Jira, names a Jira `plan` and leaves out `jira-score-formula` or `jira-score-bar`, sets
|
||||
one of those two without a `plan` in Jira, sets the formula to one that doesn't parse or the bar to anything
|
||||
but a number, sets `readability-floor` to anything but a number
|
||||
from 1 to 10, sets `parallel-chunks` to anything but a whole number of 1 or more, or sets `jira-finding-type` to anything but a name or without a `plan` in Jira, and where `coding-conventions`, `env-file`, `jira-finish-transition`, `jira-finish-status`, `notifier` or `touch-predictions` is asked for and not set. No path setting has a default.
|
||||
from 1 to 10, sets `parallel-chunks` to anything but a whole number of 1 or more, or sets `jira-finding-type` to anything but a name or without a `plan` in Jira, and where `coding-conventions`, `env-file`, `epic-branch`, `jira-finish-transition`, `jira-finish-status`, `notifier`, `review-request-comment` or `touch-predictions` is asked for and not set. No path setting has a default.
|
||||
"""
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
@@ -50,6 +50,9 @@ LANGUAGE = "language"
|
||||
COMMIT_TITLE = "commit-title"
|
||||
PULL_REQUEST_TITLE = "pull-request-title"
|
||||
BRANCH = "branch"
|
||||
# Two optional settings. `epic-branch` names the working branch that an epic's chunks branch off and merge into, `{epic}` standing for the epic's key (docs/decisions.md → `epic-branch: an epic's chunks branch off and merge into a working branch …`). `review-request-comment` is the comment `chunk-pr` posts on a pull request into that branch, to ask a reviewer that reviews only pull requests into the default branch. Three readers, seated as the human who writes the config, a chunk's worker and one of a client's team, picked both spellings from four candidates each, 3-0: `merge-branch` and `working-branch` read as the chunk's own branch, and `base-branch` as replacing the default branch for the whole repo.
|
||||
EPIC_BRANCH = "epic-branch"
|
||||
REVIEW_REQUEST_COMMENT = "review-request-comment"
|
||||
# An optional path setting: main's help says what it places.
|
||||
TOUCH_PREDICTIONS = "touch-predictions"
|
||||
# An optional setting: a list of paths, each spelt as SPELLING says, to the files that hold the team's own coding conventions, which each reviewer agent larv-review launches reads. Three readers, seated as the human who writes a client's config, picked the spelling 2-1 from four candidates, over a bare `conventions`, which they confused with `principles` and `working-rules`.
|
||||
@@ -141,6 +144,10 @@ class ProjectConfig:
|
||||
commit_title: str = templates.TITLE
|
||||
pull_request_title: str = templates.TITLE
|
||||
branch: str = templates.BRANCH
|
||||
# The config's `epic-branch` template, or None where it sets none.
|
||||
epic_branch: str | None = None
|
||||
# The config's `review-request-comment`, or None where it sets none.
|
||||
review_request_comment: str | None = None
|
||||
# The config's `coding-conventions`, in its order; empty where it sets none.
|
||||
coding_conventions: tuple[pathlib.Path, ...] = ()
|
||||
# The epic whose child issues are the plan, where the config's `plan` names one.
|
||||
@@ -237,6 +244,7 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
|
||||
*(f"`{name}` is set, so `plan` must name a Jira epic" for name in JIRA_PLAN_ONLY if name in values and not epics["plan"]),
|
||||
*(f"`plan` names a Jira epic, so `{name}` must be set, as `project-config --help` shows" for name in JIRA_SCORE if epics["plan"] and name not in values),
|
||||
*finish_faults(values),
|
||||
*([f"`{REVIEW_REQUEST_COMMENT}` is set, so `{EPIC_BRANCH}` must be set: the comment goes on pull requests into that branch"] if REVIEW_REQUEST_COMMENT in values and EPIC_BRANCH not in values else []),
|
||||
*([f"`{JIRA_SCORE_FORMULA}` is {formula!r}: {fault}"] if JIRA_SCORE_FORMULA in values and (fault := formula_fault(formula)) else []),
|
||||
*([f"`{JIRA_SCORE_BAR}` is {bar!r}, not a bare number, such as `{JIRA_SCORE_BAR} = 1`"] if JIRA_SCORE_BAR in values and bar_of(bar) is None else []),
|
||||
]
|
||||
@@ -359,6 +367,11 @@ def language_fault(value: object) -> str | None:
|
||||
return None if named else 'not a language\'s English name in words of letters, such as "Swedish" or "Brazilian Portuguese"'
|
||||
|
||||
|
||||
def comment_fault(value: object) -> str | None:
|
||||
"""Why value is no comment to post on a pull request; None where it is one."""
|
||||
return None if isinstance(value, str) and value.strip() and "\n" not in value else 'not one line of text, such as "@coderabbitai review"'
|
||||
|
||||
|
||||
# Each one-value setting, in the order `project-config` lists them.
|
||||
SCALARS = (
|
||||
Scalar(WAIT_FOR_APPROVAL, "wait_for_approval", switch, lambda on: "true" if on else "false"),
|
||||
@@ -371,6 +384,8 @@ SCALARS = (
|
||||
Scalar(COMMIT_TITLE, "commit_title", text_read(templates.title_fault)),
|
||||
Scalar(PULL_REQUEST_TITLE, "pull_request_title", text_read(templates.title_fault)),
|
||||
Scalar(BRANCH, "branch", text_read(templates.branch_fault)),
|
||||
Scalar(EPIC_BRANCH, "epic_branch", text_read(templates.epic_branch_fault)),
|
||||
Scalar(REVIEW_REQUEST_COMMENT, "review_request_comment", text_read(comment_fault)),
|
||||
Scalar(JIRA_FINDING_TYPE, "jira_finding_type", text_read(type_fault)),
|
||||
)
|
||||
OPTIONAL = tuple(sorted({CODING_CONVENTIONS, ENV_FILE, TOUCH_PREDICTIONS, *JIRA_PLAN_ONLY, *(scalar.name for scalar in SCALARS)}))
|
||||
|
||||
@@ -6,6 +6,8 @@ import re
|
||||
|
||||
ID = "{id}"
|
||||
SUMMARY = "{summary}"
|
||||
# What an `epic-branch` template holds in place of the epic's key.
|
||||
EPIC = "{epic}"
|
||||
# What each setting holds where the config leaves it out: a bare summary, and the branch `CLAUDE.md` → "Git, commits, and PRs" names.
|
||||
TITLE = SUMMARY
|
||||
BRANCH = "item-{id}"
|
||||
@@ -40,13 +42,29 @@ def branch_fault(template: object) -> str | None:
|
||||
return f"not text such as \"feature/{ID}\""
|
||||
if template.count(ID) != 1 or SUMMARY in template:
|
||||
return f"without exactly one {ID}, or with a {SUMMARY}"
|
||||
branch = template.replace(ID, "1")
|
||||
parts = branch.split("/")
|
||||
if not BRANCH_TEXT.fullmatch(branch) or branch.startswith("-") or ".." in branch or any(not part or part.startswith(".") or part.endswith((".", ".lock")) for part in parts):
|
||||
if not git_accepts(template.replace(ID, "1")):
|
||||
return f"not a branch name git accepts, of letters, digits and . _ / - around {ID}"
|
||||
return None
|
||||
|
||||
|
||||
def git_accepts(branch: str) -> bool:
|
||||
return bool(BRANCH_TEXT.fullmatch(branch)) and not branch.startswith("-") and ".." not in branch and not any(not part or part.startswith(".") or part.endswith((".", ".lock")) for part in branch.split("/"))
|
||||
|
||||
|
||||
def epic_branch_fault(template: object) -> str | None:
|
||||
"""Why template is no `epic-branch` template; None where it is one. It needs the epic's key, or two epics would share a branch."""
|
||||
if not isinstance(template, str) or template.count(EPIC) != 1:
|
||||
return f"not text with exactly one {EPIC}, such as \"{EPIC}\" or \"epic/{EPIC}\""
|
||||
if not git_accepts(template.replace(EPIC, "ABC-1")):
|
||||
return f"not a branch name git accepts, of letters, digits and . _ / - around {EPIC}"
|
||||
return None
|
||||
|
||||
|
||||
def epic_branch(template: str, key: str) -> str:
|
||||
"""The branch template names for the epic with the key key."""
|
||||
return template.replace(EPIC, key)
|
||||
|
||||
|
||||
def stray_brace(template: str) -> str | None:
|
||||
stray = re.search(r"\{[^{}]*\}?|\}", PLACEHOLDER.sub("", template))
|
||||
return f"with {stray[0]}, which is neither {ID} nor {SUMMARY}" if stray else None
|
||||
|
||||
@@ -271,6 +271,24 @@ class LoadTest(ConfigCase):
|
||||
assert isinstance(named, ProjectConfig), named
|
||||
self.assertEqual(named.notifier, name)
|
||||
|
||||
def test_the_epic_branch_and_its_review_request_comment_are_optional(self) -> None:
|
||||
self.write("acme", CLIENT)
|
||||
left_out = load(self.checkout, self.checkout, self.home)
|
||||
assert isinstance(left_out, ProjectConfig), left_out
|
||||
self.assertEqual((left_out.epic_branch, left_out.review_request_comment), (None, None))
|
||||
(self.home / ".claude-projects" / "acme" / "config.toml").write_text(CLIENT + 'epic-branch = "epic/{epic}"\nreview-request-comment = "@coderabbitai review"\n')
|
||||
named = load(self.checkout, self.checkout, self.home)
|
||||
assert isinstance(named, ProjectConfig), named
|
||||
self.assertEqual((named.epic_branch, named.review_request_comment), ("epic/{epic}", "@coderabbitai review"))
|
||||
|
||||
def test_an_epic_branch_without_the_epic_or_a_comment_without_an_epic_branch_fails_naming_it(self) -> None:
|
||||
self.write("acme", CLIENT + 'epic-branch = "develop"\n')
|
||||
self.assertIn("`epic-branch` is 'develop', not text with exactly one {epic}", self.failure())
|
||||
(self.home / ".claude-projects" / "acme" / "config.toml").write_text(CLIENT + 'review-request-comment = "@coderabbitai review"\n')
|
||||
self.assertIn("`review-request-comment` is set, so `epic-branch` must be set", self.failure())
|
||||
(self.home / ".claude-projects" / "acme" / "config.toml").write_text(CLIENT + 'epic-branch = "{epic}"\nreview-request-comment = " "\n')
|
||||
self.assertIn("`review-request-comment` is ' ', not one line of text", self.failure())
|
||||
|
||||
def test_a_jira_plan_may_name_the_transition_and_status_that_finish_an_item(self) -> None:
|
||||
self.write("acme", JIRA_CLIENT)
|
||||
left_out = load(self.checkout, self.checkout, self.home)
|
||||
@@ -545,7 +563,7 @@ class LoadTest(ConfigCase):
|
||||
|
||||
def test_the_failure_for_a_misplaced_env_file_and_a_missing_setting_names_both_and_lists_every_setting(self) -> None:
|
||||
folder = self.write("acme", "".join(line + "\n" for line in CLIENT.splitlines() if not line.startswith("plan")) + 'env-file = "checkout:.env"\n')
|
||||
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, coding-conventions, commit-title, env-file, jira-finding-type, jira-finish-status, jira-finish-transition, jira-score-bar, jira-score-formula, language, merge, notifier, parallel-chunks, pull-request-title, readability-floor, tooling-on-host, touch-predictions and wait-for-approval.")
|
||||
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, coding-conventions, commit-title, env-file, epic-branch, jira-finding-type, jira-finish-status, jira-finish-transition, jira-score-bar, jira-score-formula, language, merge, notifier, parallel-chunks, pull-request-title, readability-floor, review-request-comment, tooling-on-host, touch-predictions and wait-for-approval.")
|
||||
|
||||
def test_two_configs_naming_one_checkout_fail_naming_both(self) -> None:
|
||||
self.write("acme", CLIENT)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import unittest
|
||||
|
||||
from project_config.templates import BARE, branch_fault, branch_fits, branch_of, fits, summary_of, title_fault, Titles
|
||||
from project_config.templates import BARE, branch_fault, branch_fits, branch_of, epic_branch, epic_branch_fault, fits, summary_of, title_fault, Titles
|
||||
|
||||
|
||||
class TitleTest(unittest.TestCase):
|
||||
@@ -31,6 +31,17 @@ class TitleTest(unittest.TestCase):
|
||||
with self.subTest(template):
|
||||
self.assertIsNotNone(branch_fault(template))
|
||||
|
||||
def test_an_epic_branch_template_holds_one_epic_and_names_a_branch_git_accepts(self) -> None:
|
||||
for template in ("{epic}", "epic/{epic}"):
|
||||
with self.subTest(template):
|
||||
self.assertIsNone(epic_branch_fault(template))
|
||||
for template in ("develop", "{epic}/{epic}", "{id}", "epic {epic}", "-{epic}", "{epic}.lock", 3):
|
||||
with self.subTest(template):
|
||||
self.assertIsNotNone(epic_branch_fault(template))
|
||||
|
||||
def test_fills_an_epic_branch_with_the_epics_key(self) -> None:
|
||||
self.assertEqual(epic_branch("epic/{epic}", "ABC-123"), "epic/ABC-123")
|
||||
|
||||
def test_fills_a_branch_with_the_items_id(self) -> None:
|
||||
self.assertEqual(branch_of("item-{id}", 357), "item-357")
|
||||
self.assertEqual(branch_of("feature/PAY-{id}", 357), "feature/PAY-357")
|
||||
|
||||
@@ -20,6 +20,7 @@ Each project principle states one rule that the decisions below apply; their ent
|
||||
- chunk-pr: the chunks of a project merge one at a time on a machine, each finishing its plan items in its turn, and a pull request that waits for an approval leaves the queue while it waits
|
||||
- deploy: this repo keeps no `AGENTS.md`, since `~/.claude` is its checkout; its principles and decision titles head `docs/decisions.md`, its working rules follow them there, and its `.claude/settings.json` excludes every `.claude/CLAUDE.md`, so a session in the clone loads only the clone's `CLAUDE.md`
|
||||
- do-epic: drives one Jira epic whose items span repos, or have none, ranked by the epic's goals, then code health, then each repo's goals, and closes the epic only once the human confirms every goal
|
||||
- epic-branch: an epic's chunks branch off and merge into a working branch its project's config names, without a person, and a person merges that branch into the default branch in one pull request
|
||||
- loop-claude: each verdict records the claude-config release and commit that ran it, the raw tokens each thread spent by model and kind since the previous outcome that recorded a spend, and the human's typed answer the judge quotes as reversing a choice the worker took on its own recommendation
|
||||
- loop-claude: each chunk runs in its own tmux window, of one tmux session per project, up to `parallel-chunks` at once, and needs tmux 3.2; its claude session is named after its window, its id derived from that name; a chunk's commit in the config's folder takes only the file it changed
|
||||
- machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available
|
||||
@@ -231,6 +232,20 @@ Valid while claude takes `--session-id` and resumes by it, and the human runs lo
|
||||
|
||||
`claude_reply` reads stream-json for every caller, so the judge's runs are streams too; the archive's `JudgeRun` stays as it was, since a judge has no tools and one turn. Valid while transcripts stay small enough to copy whole.
|
||||
|
||||
## epic-branch: an epic's chunks branch off and merge into a working branch its project's config names, without a person, and a person merges that branch into the default branch in one pull request
|
||||
|
||||
2026-11-20, lilleman's call in item 472. Serves goals 1 and 1.6: a team that keeps each merge into its default branch with a person was asked once per chunk, and reviewed an epic as many small pull requests. With `epic-branch` set, the loop asks once per epic, and the team keeps its rule. Valid while a team's no-merge rule covers its default and protected branches only.
|
||||
|
||||
- **The setting.** `epic-branch` in a project's config is a template with `{epic}` for the epic's key, such as `"{epic}"`. Left out, everything works as before. Under chunk-preflight the key is that of the Jira epic `plan` names, so a plan kept in a file has no epic branch. Under do-epic it is the key of the epic do-epic drives.
|
||||
- **A chunk's base is recorded in git.** `git config branch.<chunk's branch>.chunk-base <epic's branch>`, in the checkout's shared config (`git_repo.CHUNK_BASE`). `git_repo.default_ref` answers `origin/<epic's branch>` on such a branch, so each tool that measures a chunk against its base reads the chunk's own commits. Deleting the branch removes the record. A file in the worktree would have been a second writer of the chunk's state.
|
||||
- **The branch stays level by a merge commit, made without a checkout.** `epic_branch.levelled` makes the branch on origin off the default branch, or merges the default branch into it with `git merge-tree --write-tree` and `git commit-tree`, and pushes without force. That needs git 2.38. chunk-preflight runs it before it makes a chunk's worktree, do-epic as a chunk's window starts, and `chunk-pr open-epic` before it opens the epic's pull request. A conflict stops the chunk and asks a person to merge by hand: a resolution picks between two teams' changes, which is theirs to pick.
|
||||
- **The chunk merges without a person.** `chunk-pr merge` into an epic's branch ignores `merge = "human"` and `wait-for-approval`, and do-epic parks no such chunk on a person's merge. lilleman's call: the team's rule against merging without a go-ahead covers the default branch and protected branches. The pull request from the epic's branch into the default branch is opened ready and never merged by the loop.
|
||||
- **A review is asked for by a comment.** An auto-reviewer may review on its own only pull requests into the default branch. `review-request-comment` holds the comment that asks it, which `chunk-pr ready` and `chunk-pr push` post on a pull request into an epic's branch. The worker waits for the review as for any auto-reviewer.
|
||||
- **do-epic moves the issue itself.** A team's automation fires only for pull requests into the default branch. `jira-pull-request-open-status` names the status of an issue whose chunk parks with its pull request open, and `jira-pull-request-merged-status` the one once it has merged. The first move is made as the chunk parks, since that is where do-epic learns of the pull request; one that opens and merges within a single run of the worker skips it. Each setting names a status, and do-epic takes whichever transition leads there.
|
||||
- **An issue at the merged status counts as done for the epic's end.** The release reviews and the finishing chunk come before a person merges the epic's branch, and Jira counts the issues done only after. So `finish.landed` reads such an issue as done, wherever do-epic's config names the status. Without the setting, the finishing waits for Jira as before.
|
||||
- **Sibling repos.** A chunk's worker tests each sibling repo at its branch of the same name where it has one, else at its default branch, and its summary names each sibling that ran at the default branch. A team's shared test harness needs an option to pick the branch; that is the team's change.
|
||||
- **Spellings.** Three fresh readers, seated as those who write a project's config and run `chunk-pr`, picked each from three or four candidates: `epic-branch` 3-0, `review-request-comment` 3-0, `chunk-pr push` 3-0, `chunk-pr open-epic` 2-1 and `jira-pull-request-open-status` 2-1. `jira-pull-request-merged-status` is spelt to pair with the last.
|
||||
|
||||
## loop-claude: each verdict records the claude-config release and commit that ran it, the raw tokens each thread spent by model and kind since the previous outcome that recorded a spend, and the human's typed answer the judge quotes as reversing a choice the worker took on its own recommendation
|
||||
|
||||
2026-11-12, lilleman, todo item 305. Serves goals 1, 1.2 and 1.4. A change to the setup can be judged only by comparing chunks run before it with chunks run after, so each verdict, interrupt and quoted answer in loop-claude's archive records three things beside its judge lines.
|
||||
|
||||
@@ -3236,3 +3236,34 @@ Read most (opens and searches):
|
||||
- `bin/do_epic/test_issue_scores.py` 1
|
||||
- `bin/do_epic/test_repo_pick.py` 1
|
||||
- `bin/model_routing/ladder.py` 1
|
||||
|
||||
## Reading cost, chunk 4fb66d10f849, finished 2026-11-20T17:43:35Z
|
||||
|
||||
54949 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `workflow-bench/test_advisor_bench.py` 3
|
||||
- `bin/repo_checks/test_no_patched_globals.py` 2
|
||||
- `bin/repo_checks/test_trials_imports.py` 2
|
||||
- `bin/repo_checks/__init__.py` 1
|
||||
- `ci.sh` 1
|
||||
- `reviewer-merge-trials/analyze.py` 1
|
||||
- `workflow-bench/advisor_bench.py` 1
|
||||
|
||||
## Reading cost, chunk 79a2a453c4b8, finished 2026-11-20T18:02:46Z
|
||||
|
||||
248834 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `bin/do_epic/test_main.py` 14
|
||||
- `bin/do_epic/main.py` 6
|
||||
- `bin/do_epic/backend/jira.py` 5
|
||||
- `bin/do_epic/backend/test_jira.py` 5
|
||||
- `bin/do_epic/test_do_epic.py` 4
|
||||
- `README.md` 3
|
||||
- `bin/do_epic/backend/contract.py` 3
|
||||
- `bin/do_epic/config.py` 3
|
||||
- `bin/atlassian/jira.py` 2
|
||||
- `bin/do_epic/backend/fake.py` 2
|
||||
|
||||
@@ -204,7 +204,7 @@ Launch prose-reviewer with what the diff touched and every section this review c
|
||||
3. The forge's checks: `chunk-pr merge` waits for them to pass (§5 step 4). A red check is a finding.
|
||||
4. No CI configured → the gate is local tests only; note it in the summary.
|
||||
5. The local tests green → where §2 left the pull request unopened, open it with `~/.claude/bin/chunk-pr open '<final title>' '<summary>'` and mark it ready at once with `~/.claude/bin/chunk-pr ready`. Otherwise mark the PR ready with `~/.claude/bin/chunk-pr ready '<final title>'`, which sets the title as it marks the PR ready.
|
||||
6. **External auto-reviewer**, when the repo has one — its config file (`.coderabbit.yaml` and the like), or its comments on earlier PRs; none → skip it, say so. Marking the PR ready summons it, unless it reviewed the draft already. Wait up to **10 minutes** for its first review, checking about once a minute; nothing by then → note it in the summary and carry on, never waiting twice. Its rounds, §3 → "Round cap". Once it has reviewed, each later return here before its cap, after a fix re-entered per §3, waits up to **5 minutes** for its re-review of the new commit. Each of its findings, fixed or declined, ends with the setup change that `~/.claude/CLAUDE.md` → "Working loop", "Change the setup for each finding an outside reviewer raises on a PR, deterministic tools first" asks for.
|
||||
6. **External auto-reviewer**, when the repo has one — its config file (`.coderabbit.yaml` and the like), or its comments on earlier PRs; none → skip it, say so. Marking the PR ready summons it, unless it reviewed the draft already. On a pull request into an epic's working branch (`chunk-pr --help`), a reviewer that reviews only pull requests into the default branch is summoned by the project's `review-request-comment`, which `chunk-pr ready` posts: push each later commit there with `chunk-pr push`, which posts it again. Wait up to **10 minutes** for its first review, checking about once a minute; nothing by then → note it in the summary and carry on, never waiting twice. Its rounds, §3 → "Round cap". Once it has reviewed, each later return here before its cap, after a fix re-entered per §3, waits up to **5 minutes** for its re-review of the new commit. Each of its findings, fixed or declined, ends with the setup change that `~/.claude/CLAUDE.md` → "Working loop", "Change the setup for each finding an outside reviewer raises on a PR, deterministic tools first" asks for.
|
||||
|
||||
## 5. Goal alignment, then merge
|
||||
|
||||
|
||||
Reference in New Issue
Block a user