Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 104 additions & 17 deletions scripts/lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -3975,14 +3975,93 @@ def close_prompt(
return None, ""


def close_registries(root: Path, slug: str) -> "list[str]":
"""The registry files still carrying a `## <slug>` section for this task."""
_ISSUE_HEADER_RE = re.compile(r"^Issue:\s*(\S+)", re.M)


def _issue_key(value: "str | None") -> str:
"""An issue URL as the registries compare it: first token, no trailing `/`."""
words = (value or "").split()
return words[0].rstrip("/") if words else ""


def prompt_issue(prompt: "Path | None") -> str:
"""The prompt's `Issue:` header, else ""."""
if prompt is None:
return ""
try:
m = _ISSUE_HEADER_RE.search(prompt.read_text(errors="replace"))
except OSError:
return ""
return _issue_key(m.group(1)) if m else ""


def close_registries(
root: Path,
slug: str,
prompt: "Path | None" = None,
issue: "str | None" = None,
) -> "list[tuple[str, str]]":
"""(registry file, `## heading` slug) for each registry still carrying this
task's section.

Matched in order, per file: the heading by slug; else the one row whose
`prompt:` resolves to the task's prompt file; else the one row whose
`issue:` is the task's issue (`issue`, else the prompt's `Issue:` header).
A `prompt:` or `issue:` match counts only when exactly one row matches —
two candidates are a human's to tell apart (PyAutoBrain#661: after shift
2026-11-16-pm, rows whose heading was not the slug were left behind)."""
want = safe_name(slug)
return [
reg
for reg in REGISTRY_FILES
if want in {safe_name(s) for s in ledger_slugs(root / reg)}
]
target = prompt.resolve() if prompt is not None else None
issue_key = _issue_key(issue) or prompt_issue(prompt)

def _other_prompt(fields: dict) -> bool:
"""The row's `prompt:` names a file other than this task's, whether
that file still exists or not."""
raw = (fields.get("prompt") or "").split()
if not raw:
return False
resolved = _prompt_of(fields)
if resolved is not None:
return resolved != target
return target is None or Path(raw[0]).name != target.name

def _prompt_of(fields: dict) -> "Path | None":
raw = (fields.get("prompt") or "").split()
if not raw:
return None
resolved, _ = resolve_prompt(root, raw[0])
return resolved.resolve() if resolved is not None else None

out: "list[tuple[str, str]]" = []
unmatched: "list[tuple[str, list]]" = []
for reg in REGISTRY_FILES:
entries = registry_entries(root / reg)
by_slug = [h for h, _ in entries if safe_name(h) == want]
if by_slug:
out.append((reg, by_slug[0]))
continue
if target is not None:
by_prompt = [h for h, f in entries if _prompt_of(f) == target]
if len(by_prompt) == 1:
out.append((reg, by_prompt[0]))
continue
if by_prompt:
continue # ambiguous: never guess
unmatched.append((reg, entries))
# The issue is the last resort (#661 review): issues are shared (an epic's
# phases, a follow-up), so it is used only when the task's own row matched
# by slug or prompt in no registry, and never takes a row whose `prompt:`
# resolves to another prompt file.
if issue_key and not out:
for reg, entries in unmatched:
by_issue = [
h for h, f in entries
if _issue_key(f.get("issue")) == issue_key
and not _other_prompt(f)
]
if len(by_issue) == 1:
out.append((reg, by_issue[0]))
return out


def close_references(root: Path, slug: str, rel: str) -> "list[str]":
Expand Down Expand Up @@ -4092,7 +4171,7 @@ def cmd_close(args) -> int:
return 1

rel = _rel(root, prompt)
registries = close_registries(root, args.slug)
registries = close_registries(root, args.slug, prompt, getattr(args, "issue", None))
task_cell, why = close_shadow_task(args)
row = None
actor_cell = None
Expand Down Expand Up @@ -4132,8 +4211,9 @@ def cmd_close(args) -> int:
print(f"close: {args.slug}")
print(f" record: {dest.relative_to(root)} (folds {rel}, found via {how})")
print(f" remove: {rel}")
for reg in registries:
print(f" registry: {reg} — drop the `## {slug}` entry")
for reg, heading in registries:
found = "" if safe_name(heading) == slug else " (matched by prompt path or issue)"
print(f" registry: {reg} — drop the `## {heading}` entry{found}")
if not registries:
print(
" registry: no entry in " + "/".join(REGISTRY_FILES) + " — nothing to drop"
Expand Down Expand Up @@ -4167,7 +4247,7 @@ def cmd_close(args) -> int:
dest.relative_to(root).as_posix(),
rel,
INDEX_MD.relative_to(root).as_posix(),
*registries,
*(reg for reg, _ in registries),
*([_rel(root, log)] if row is not None else []),
*(["queue.md"] if queue_moved else []),
*(["questions.md"] if questions_moved else []),
Expand All @@ -4190,13 +4270,14 @@ def cmd_close(args) -> int:
rc = cmd_record(rec)
if rc != 0:
return rc
# `record` prunes active.md; the pointers a task may also hold elsewhere
# are this verb's to drop.
for reg in registries:
if reg == "active.md":
# `record` prunes active.md by slug; a row matched by prompt path or
# issue (#661), and the pointers a task may also hold elsewhere, are this
# verb's to drop — each by the heading it matched.
for reg, heading in registries:
if reg == "active.md" and safe_name(heading) == slug:
continue
if _prune_ledger_section(root / reg, args.slug):
print(f"{reg}: removed section {slug!r}")
if _prune_ledger_section(root / reg, heading):
print(f"{reg}: removed section {safe_name(heading)!r}")

if queue_moved:
queue_md.write_text(queue_new, encoding="utf-8")
Expand Down Expand Up @@ -4311,6 +4392,12 @@ def main() -> int:
"repo-relative path OR a bare filename (unlike "
"`record --prompt`, draft/ prompts resolve too)",
)
cl.add_argument(
"--issue",
help="the task's issue URL: finds its registry row when the row's "
"heading is not the slug and its `prompt:` does not name the prompt "
"(default: the prompt's `Issue:` header)",
)
cl.add_argument(
"--pr",
nargs="+",
Expand Down
124 changes: 124 additions & 0 deletions tests/test_lifecycle_close.py
Original file line number Diff line number Diff line change
Expand Up @@ -568,3 +568,127 @@ def test_queue_retire_text_creates_the_footer_when_missing():
assert moved == ["A"]
assert out.endswith("## Retired\n\n### A\n- shipped-as: complete/2026/01/a.md\n"
"- note: retired by `lifecycle.py close`\n")


# --------------------------------------------------------------------------- #
# the active.md row when its heading is not the slug (PyAutoBrain#661)
#
# After shift 2026-11-16-pm, `/prm` found no row to drop for two tasks whose
# `active.md` heading was not their slug; the rows were removed by hand. The
# row is matched by slug, then by its `prompt:` resolving to the task's prompt,
# then by its `issue:` — each only when exactly one row matches.
# --------------------------------------------------------------------------- #
ISSUE_URL = "https://github.com/ExampleOrg/Flywheel/issues/7"


def _retitled(root: Path, *, prompt_line: bool, issue_line: bool) -> None:
"""active.md's sprocket row, under a heading that is not its slug."""
(root / "active.md").write_text(
"# Active\n\n"
"## torque-rebaseline-epic-row (M3 phase 2)\n"
"- status: library-dev\n"
+ ("- prompt: active/sprocket_calibration.md\n" if prompt_line else "")
+ (f"- issue: {ISSUE_URL}\n" if issue_line else "")
+ "\n"
"## widget-alignment\n"
"- status: library-dev\n"
"- prompt: active/widget_alignment.md\n"
"- issue: https://github.com/ExampleOrg/Flywheel/issues/8\n"
)


def test_close_drops_active_row_by_prompt_path(tmp_path, monkeypatch, capsys):
root = _mind(tmp_path)
_retitled(root, prompt_line=True, issue_line=False)
_at(monkeypatch, root)
assert lifecycle.cmd_close(_args(root)) == 0
out = capsys.readouterr().out
assert "active.md — drop the `## torque-rebaseline-epic-row` entry" in out
assert lifecycle.cmd_close(_args(root, apply=True)) == 0
active = (root / "active.md").read_text()
assert "torque-rebaseline-epic-row" not in active
assert "## widget-alignment" in active # the bystander stays


def _no_parked_row(root: Path) -> None:
"""parked.md without the task's slug row: a slug match in any registry
means the issue fallback is never needed (#661 review)."""
(root / "parked.md").write_text("# Parked\n")


def test_close_drops_active_row_by_issue_url(tmp_path, monkeypatch, capsys):
root = _mind(tmp_path)
_retitled(root, prompt_line=False, issue_line=True)
_no_parked_row(root)
_at(monkeypatch, root)
assert lifecycle.cmd_close(_args(root, issue=ISSUE_URL, apply=True)) == 0
out = capsys.readouterr().out
assert "torque-rebaseline-epic-row" in out
active = (root / "active.md").read_text()
assert "torque-rebaseline-epic-row" not in active
assert "## widget-alignment" in active


def test_close_reads_the_issue_from_the_prompts_header(tmp_path, monkeypatch):
root = _mind(tmp_path)
_retitled(root, prompt_line=False, issue_line=True)
_no_parked_row(root)
prompt = root / "active" / "sprocket_calibration.md"
prompt.write_text(prompt.read_text().replace(
"\n\nRe-measure", f"\n\nIssue: {ISSUE_URL}\n\nRe-measure"))
_at(monkeypatch, root)
assert lifecycle.cmd_close(_args(root, apply=True)) == 0
assert "torque-rebaseline-epic-row" not in (root / "active.md").read_text()


def test_close_drops_nothing_when_two_rows_match_the_issue(tmp_path, monkeypatch,
capsys):
root = _mind(tmp_path)
_retitled(root, prompt_line=False, issue_line=True)
# Two rows on the issue, neither naming another prompt: never guess.
(root / "active.md").write_text((root / "active.md").read_text().replace(
"issues/8", "issues/7").replace("- prompt: active/widget_alignment.md\n", ""))
_no_parked_row(root)
_at(monkeypatch, root)
assert lifecycle.cmd_close(_args(root, issue=ISSUE_URL, apply=True)) == 0
active = (root / "active.md").read_text()
assert "torque-rebaseline-epic-row" in active and "widget-alignment" in active


def test_close_never_drops_a_sibling_row_that_shares_the_issue(tmp_path, monkeypatch):
"""The next phase of an epic shares the task's issue but has its own
prompt: the issue fallback must not take it for the closed task's row,
and is not used at all once the task's own row matched elsewhere."""
root = _mind(tmp_path) # own row matches by slug in active.md
(root / "active" / "phase3.md").write_text(f"# phase 3\n\nIssue: {ISSUE_URL}\n\nbody\n")
(root / "planned.md").write_text(
"# Planned\n\n## phase3-followup\n- prompt: active/phase3.md\n"
f"- issue: {ISSUE_URL}\n")
_at(monkeypatch, root)
assert lifecycle.cmd_close(_args(root, issue=ISSUE_URL, apply=True)) == 0
assert "## phase3-followup" in (root / "planned.md").read_text()


def test_the_issue_fallback_skips_a_row_with_another_prompt(tmp_path, monkeypatch):
root = _mind(tmp_path)
_retitled(root, prompt_line=False, issue_line=True)
_no_parked_row(root)
(root / "active" / "phase3.md").write_text("# phase 3\n")
(root / "active.md").write_text((root / "active.md").read_text().replace(
"- status: library-dev\n- issue:",
"- status: library-dev\n- prompt: active/phase3.md\n- issue:"))
_at(monkeypatch, root)
assert lifecycle.cmd_close(_args(root, issue=ISSUE_URL, apply=True)) == 0
assert "torque-rebaseline-epic-row" in (root / "active.md").read_text()


def test_the_issue_fallback_skips_a_row_naming_a_missing_other_prompt(tmp_path, monkeypatch):
root = _mind(tmp_path)
_retitled(root, prompt_line=False, issue_line=True)
_no_parked_row(root)
(root / "active.md").write_text((root / "active.md").read_text().replace(
"- status: library-dev\n- issue:",
"- status: library-dev\n- prompt: active/phase3_gone.md\n- issue:"))
_at(monkeypatch, root)
assert lifecycle.cmd_close(_args(root, issue=ISSUE_URL, apply=True)) == 0
assert "torque-rebaseline-epic-row" in (root / "active.md").read_text()
Loading