tickets: done_checkpoint still pauses on the run's last ticket under mark_done = "auto", so the run pauses twice where the guide promises a skip

未关闭
#968 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
3/5
预计耗时
1-2 天
新手友好度
68/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
python
领域
backend, testing

调研方向

Start in src/bmad_loop/tickets_engine.py at _schedule_complete() (around lines 995–998), then compare its end-of-run check with the ticket and epic boundary behavior in tests/test_tickets_engine.py. Run test_done_checkpoint_skipped_if_last and add coverage for the reported one-ticket epic case with mark_done = "auto"; done means the last ticket produces checkpoint-skip-last and only the expected epic boundary pause remains.

由索引模型根据 Issue 内容生成。

描述

Summary

docs/tickets-guide.md says the done_checkpoint pause is skipped "for the last ticket, at --max-stories, and on a graceful stop". Observed: when the run's last ticket (nothing else left in the tree) carries done_checkpoint and the default mark_done = "auto" marks it done, the run still pauses at story-checkpoint, and the resume then pauses again at epic-boundary for the epic that ticket finished. With the same tree under mark_done = "never" (the plan stays built) the skip fires and the run pauses once. The pinning unit test builds its tree with no epic table, which is why it passes. Every real v7 ticket belongs to an epic, so an operator who puts done_checkpoint on the last ticket gets two pauses in a row for one point in the run.

This is not the two-pause case tests/test_tickets_engine.py::test_ticket_epic_boundary_fires_at_pick_after_resume characterizes, where another epic's ticket (2.1) is still ready and the story-checkpoint pause is legitimate. There the next pick is a dispatch (candidates are considered before the end-of-tree closure halt, tickets_source.py:546-578 vs :654-663); here nothing is left to dispatch.

Environment

bmad-loop a5a8f097, Windows 11 Enterprise 10.0.26200, PowerShell 7.6.6 (SHELL unset), Python 3.13.2; repro through the real bmad-loop CLI with bmad-loop's MockAdapter serving the sessions; also reproduced end to end over psmux 3.4.0 with the generic adapter and a scripted (zero-token) pwsh build-auto. Linux oracle: same (Ubuntu under WSL, tmux 3.4, git 2.43.0).

Steps to reproduce

The repro is complete and runs from PowerShell 7 with SHELL removed. From a bmad-loop checkout at a5a8f097 after uv sync --all-extras, save the script below as repro.py in the checkout root and run:

Remove-Item Env:SHELL -ErrorAction SilentlyContinue
$env:PYTHONUTF8 = '1'; $env:PYTHONPATH = 'tests'
uv run python repro.py

The script builds a committed v7 project with one epic epic-cart holding one ticket 1.1 with done_checkpoint = true (the conftest v7 helpers), and drives the real bmad-loop run / resume CLI, one process per call. Every session is a scripted build-auto (no LLM): it resolves the ticket with the project's tickets.py find, writes the plan at built and commits its work. The positive control is the same project with [tickets] mark_done = "never".

# bmad-loop repro: run from a bmad-loop checkout (uv sync --all-extras), PowerShell 7:
#   Remove-Item Env:SHELL -ErrorAction SilentlyContinue; $env:PYTHONUTF8='1'; $env:PYTHONPATH='tests'; uv run python repro.py
import json, os, subprocess, sys, time
from pathlib import Path

from conftest import EntrySpec, EpicSpec, install_bmad_v7, install_build_auto_v7_skill, write_ticket_tree

ROOT = Path(os.environ.get("REPRO_ROOT") or Path(os.environ.get("TEMP", "/tmp")) / "bmad-loop-repro")
ROOT.mkdir(parents=True, exist_ok=True)
os.environ.pop("SHELL", None)
# Keep the user's global git config (signing, hooks, excludes) out of the sandbox,
# as the test suite's own fixtures do; every child below inherits this.
os.environ["GIT_CONFIG_GLOBAL"] = str(ROOT / "no-such-gitconfig")
os.environ["XDG_CONFIG_HOME"] = str(ROOT)


def git(root, *args):
    return subprocess.run(["git", "-C", str(root), *args], check=True, capture_output=True, text=True).stdout


def sandbox(name, entries, policy=""):
    """A committed v7 project (tracked store in the checkout), one epic `epic-cart`."""
    root = ROOT / name
    if root.exists():
        subprocess.run(["cmd", "/c", "rmdir", "/s", "/q", str(root)] if os.name == "nt" else ["rm", "-rf", str(root)])
    root.mkdir(parents=True)
    (root / "src.txt").write_text("original\n", encoding="utf-8")
    (root / ".gitignore").write_text(".bmad-loop/runs/\n_bmad/custom/*.user.toml\n", encoding="utf-8")
    git(root, "init", "-q", "-b", "main")
    git(root, "config", "user.email", "t@t")
    git(root, "config", "user.name", "t")
    write_ticket_tree(install_bmad_v7(root), (EpicSpec(1, "epic-cart", "Cart", tuple(entries)),))
    install_build_auto_v7_skill(root)
    (root / ".bmad-loop").mkdir()
    (root / ".bmad-loop" / "policy.toml").write_text(
        '[stories]\nsource = "tickets"\n\n[notify]\ndesktop = false\n\n' + policy, encoding="utf-8")
    git(root, "add", "-A")
    git(root, "commit", "-q", "-m", "sandbox")
    return root


def tickets(cwd, *argv):
    return subprocess.run([sys.executable, "-I", "-B", "-X", "utf8", "_bmad/method/scripts/tickets.py",
                           "--project-root", str(cwd), *argv], cwd=cwd, check=True, capture_output=True, text=True)


def fake_session(spec):
    """A scripted bmad-build-auto (no LLM): resolves the ticket with tickets.py find,
    writes the plan, commits its own work. REPRO_FAIL=<ref> makes that ticket's attempt
    fail (plan with a body at in-progress, nothing committed); REPRO_PARK=<ref> parks it
    at awaiting-operator; REPRO_FOLLOWUP=1 adds followup_review_recommended to a dev result."""
    from bmad_loop.adapters.base import SessionResult
    cwd, ref = Path(spec.cwd), spec.env["BMAD_LOOP_STORY_KEY"]
    found = json.loads(tickets(cwd, "find", ref).stdout)
    plan, base = Path(found["plan"]), git(cwd, "rev-parse", "HEAD").strip()
    status = "built"
    if plan.is_file() and "status: built" in plan.read_text(encoding="utf-8"):
        pass  # a follow-up review pass: no change
    elif spec.role == "dev" and ref == os.environ.get("REPRO_FAIL"):
        status = "in-progress"
        with open(cwd / "src.txt", "a", encoding="utf-8") as f:
            f.write(f"half impl {ref}\n")
        plan.write_text(f"---\nticket: {found['id']}\nstatus: in-progress\nbaseline_revision: {base}\n---\n\n# plan\n\nwork\n", encoding="utf-8")
    else:
        if spec.role == "dev" and ref == os.environ.get("REPRO_PARK"):
            status = "awaiting-operator"
        with open(cwd / "src.txt", "a", encoding="utf-8") as f:
            f.write(f"impl {ref}\n")
        extra = "operator_actions:\n  - publish the DNS record\n" if status == "awaiting-operator" else ""
        plan.write_text(f"---\nticket: {found['id']}\nstatus: {status}\nbaseline_revision: {base}\n{extra}---\n\n# plan\n\nwork\n", encoding="utf-8")
        git(cwd, "add", "-A")
        git(cwd, "commit", "-q", "-m", f"build {ref}")
    result = {"workflow": "auto-dev", "spec_file": str(plan), "status": status}
    if spec.role == "dev" and os.environ.get("REPRO_FOLLOWUP"):
        result["followup_review_recommended"] = True
    return SessionResult(status="completed", result_json=result)


def bmad_loop(root, *argv, env=None, background=False):
    """One real `bmad-loop` CLI call, in its own process, with every session role served
    by `fake_session` through bmad-loop's MockAdapter (so nothing spawns an agent)."""
    cmd = [sys.executable, __file__, "--child", argv[0], "--project", str(root), *argv[1:]]
    e = dict(os.environ, **(env or {}))
    if background:
        return subprocess.Popen(cmd, env=e, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    p = subprocess.run(cmd, env=e, capture_output=True, text=True)
    print(f"$ bmad-loop {' '.join(argv)}  -> rc={p.returncode}")
    print("  " + (p.stdout + p.stderr).strip().replace("\n", "\n  "))
    return p.returncode


def run_dir(root):
    return sorted((root / ".bmad-loop" / "runs").iterdir())[-1]


def state(root):
    return json.loads((run_dir(root) / "state.json").read_text(encoding="utf-8"))


def journal(root, *kinds):
    rows = [json.loads(x) for x in (run_dir(root) / "journal.jsonl").read_text(encoding="utf-8").splitlines()]
    return [r for r in rows if r["kind"] in kinds]


if len(sys.argv) > 1 and sys.argv[1] == "--child":
    from bmad_loop import cli
    from bmad_loop.adapters.mock import MockAdapter
    adapter = MockAdapter([fake_session] * 20)
    cli._make_adapters = lambda *a, **k: {role: adapter for role in cli.ROLES}
    sys.exit(cli.main(sys.argv[2:]))


# --- done_checkpoint on the last ticket of an epic -----------------------------------
for mark_done in ("auto", "never"):  # "never" is the positive control
    root = sandbox(f"dc-{mark_done}", [EntrySpec(1, "Cart model", done_checkpoint=True)],
                   f'[review]\nenabled = false\n\n[tickets]\nmark_done = "{mark_done}"\n')
    print(f"\n### mark_done = {mark_done}")
    bmad_loop(root, "run")
    print("paused_stage after run:", state(root)["paused_stage"])
    print("journal:", [r["kind"] for r in journal(root, "checkpoint-pause", "checkpoint-skip-last")])
    if state(root)["paused_stage"] == "story-checkpoint":
        bmad_loop(root, "resume", run_dir(root).name)
        print("paused_stage after resume:", state(root)["paused_stage"])

Output (Windows, PowerShell 7.6.6; identical in 7 runs, run ids shown as <run>, the run <run> starting and summary lines trimmed):

### mark_done = auto
$ bmad-loop run  -> rc=0
  PAUSED: story checkpoint for 1.1: review, then resume
paused_stage after run: story-checkpoint
journal: ['checkpoint-pause']
$ bmad-loop resume <run>  -> rc=0
  PAUSED: close epic-cart with bmad-ticket (closure check; retrospective verdict: unknown) — then `bmad-loop resume <run>`
paused_stage after resume: epic-boundary

### mark_done = never
$ bmad-loop run  -> rc=0
  PAUSED: close epic-cart with bmad-ticket (closure check; retrospective verdict: unknown) — then `bmad-loop resume <run>`
paused_stage after run: epic-boundary
journal: ['checkpoint-skip-last']

The same two pauses appear end to end over psmux with the generic adapter (the scaffold of tests/test_tickets_e2e.py with its bash fake ported to pwsh, one ticket with done_checkpoint): after run, status --json reads paused_stage = story-checkpoint, one checkpoint-pause, no checkpoint-skip-last; after resume, epic-boundary (2/2).

Expected vs actual

actual expected (docs/tickets-guide.md, done_checkpoint bullet)
the run's last ticket (one epic, one ticket), mark_done = "auto" checkpoint-pause → story-checkpoint; resume → epic-boundary (two pauses) "It skips the pause for the last ticket": checkpoint-skip-last, one pause (epic-boundary)
same, mark_done = "never" checkpoint-skip-last, one pause as documented

Linux

The same one-ticket mock-adapter scenario, run as a separate script in a git archive a5a8f097 copy under WSL (Ubuntu, tmux 3.4, git 2.43.0, Python 3.13.2), verbatim except the run id:

===== TRIGGER mark_done=auto =====
   stdout| PAUSED: story checkpoint for 1.1: review, then resume
-- after run: finished=False paused_stage=story-checkpoint paused_key=1.1 sessions=1
   stdout| PAUSED: close epic-cart with bmad-ticket (closure check; retrospective verdict: unknown) — then `bmad-loop resume <run>`
-- after resume 1: finished=False paused_stage=epic-boundary paused_key=epic-cart sessions=1
RESULT TRIGGER mark_done=auto: pauses_before_settled_or_epic=2 skip_last=0 story_ckpt_pauses=1 sessions=1
===== CONTROL mark_done=never =====
-- after run: finished=False paused_stage=epic-boundary paused_key=epic-cart sessions=1
RESULT CONTROL mark_done=never: pauses_before_settled_or_epic=1 skip_last=1 story_ckpt_pauses=0 sessions=1

The existing unit test tests/test_tickets_engine.py::test_done_checkpoint_skipped_if_last passes on the same copy (1 passed): it builds its fake tree with no epic table (fake_status_view(..., epics=())), so the pick after the last ticket is Skip.

Source

src/bmad_loop/tickets_engine.py:995-998 (a5a8f097):

    def _schedule_complete(self) -> bool:
        """Whether the next pick would end the run. A tree that cannot be read
        answers False, so a done_checkpoint still fires."""
        return isinstance(self._tickets_source.decide(self._phases()), Skip)

src/bmad_loop/checkpoints.py:305: if self._schedule_complete() or self._max_stories_reached() or graceful: → checkpoint-skip-last, else the story-checkpoint pause.

src/bmad_loop/tickets_source.py:654-663 (source-derived): once no candidate is left and every ticket of an open epic is done, decide_pick returns Halt(HALT_AWAITING_CLOSURE, ...) ("every ticket of epic-cart is done; close epic-cart"), not Skip. Under mark_done = "auto" the last ticket is done when _after_story runs, so _schedule_complete answers False. Under "never" the plan stays built, the epic is not "every ticket done", and the pick is Skip.

Observed with a scratch copy of the module in which _schedule_complete also answers True for Halt(awaiting-closure): the trigger journals checkpoint-skip-last and pauses once, at epic-boundary.

Suggested fix

Not validated: in _schedule_complete, also treat the end-of-tree awaiting-closure halt (tickets_source.py:654-663, row is None: no ticket left at all) as "nothing left to dispatch", since the epic-boundary pause follows anyway. Keep the arm at :601-610 (a blocked ticket waits on that epic's closure) and any dispatch pausing, so the characterized case above is unchanged. Or narrow the guide to say the skip applies only when no epic closure follows.

主要语言
Python
星标
196
派生
78
平均合并
9 小时 24 分钟
30 天内合并 PR
44

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

bmad-code-org/bmad-loop 的其他 Issue

查看 bmad-code-org/bmad-loop 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。