diff --git a/bundlebees_plugin/beat.py b/bundlebees_plugin/beat.py index 3201bd5..07ac523 100644 --- a/bundlebees_plugin/beat.py +++ b/bundlebees_plugin/beat.py @@ -31,6 +31,7 @@ from typing import Any, Callable, Mapping from . import beat_reconciliation +from . import board_plan_orphans from . import board_stock from .security import scrub @@ -42,6 +43,8 @@ DUTY_MERGE = "merge_stream" #: Flag-gated: ready-column stocking is an observation, never an action. DUTY_STOCK = "stock_ready_column" +#: Plan/board drift: actionable cards with no slice, reported or folded. +DUTY_PLAN_ORPHANS = "board_plan_orphans" _MAX_TEXT = 300 @@ -81,6 +84,8 @@ def beat( merge_stream: Callable[[], Any] | None = None, processor: Any = None, branch_of: Callable[[Mapping[str, Any]], Any] | None = None, + plan_path: Any = None, + board_reader: Callable[[], Any] | None = None, now: Any = None, wait_s: float = 0.0, ) -> dict[str, Any]: @@ -117,6 +122,26 @@ def beat( if isinstance(outcome, Mapping) else {"status": "ok", "result": _clip(scrub(str(outcome)))} ) + if plan_path is not None: + try: + plan_result = board_plan_orphans.check( + Path(plan_path), board_reader=board_reader, fold=True + ) + except Exception as exc: # noqa: BLE001 - the beat outlives its duties + duties[DUTY_PLAN_ORPHANS] = { + "status": "error", + "reason": board_plan_orphans.REASON_PLAN_INVALID, + "reported": [], + "folded": [], + "error": _clip(scrub(f"{type(exc).__name__}: {exc}")), + } + else: + duties[DUTY_PLAN_ORPHANS] = { + "status": "ok" if plan_result.get("ok") else "error", + "reason": plan_result.get("reason"), + "reported": list(plan_result.get("reported") or []), + "folded": list(plan_result.get("folded") or []), + } # Flag-gated and observation-only: with BUNDLEBEES_BOARD_STOCK unset the # duty does not exist, so the report and the filesystem are unchanged. if board_stock.enabled(): @@ -166,4 +191,12 @@ def scout_tick( ) -__all__ = ["DUTY_MERGE", "DUTY_STOCK", "DUTY_SWEEP", "SCHEMA", "beat", "scout_tick"] +__all__ = [ + "DUTY_MERGE", + "DUTY_PLAN_ORPHANS", + "DUTY_STOCK", + "DUTY_SWEEP", + "SCHEMA", + "beat", + "scout_tick", +] diff --git a/bundlebees_plugin/board_plan_orphans.py b/bundlebees_plugin/board_plan_orphans.py new file mode 100644 index 0000000..bcb874b --- /dev/null +++ b/bundlebees_plugin/board_plan_orphans.py @@ -0,0 +1,409 @@ +"""Keep the board and the campaign plan in step. + +Every actionable board card is expected to have a plan slice. This module +reports the cards that do not, and can fold them into the plan as planned +slices under an ``orphans`` wave. It is report-only unless folding is asked +for, and folding is idempotent: a card referenced by a slice id or by a +slice's ``board_card`` is never folded twice. + +Two card shapes are deliberately not actionable: + +* terminal cards (``done``, ``cancelled``/``canceled``, ``archive``/``archived`` + and ``completed``), normalised case- and whitespace-insensitively; +* cards carrying a ``bundlebees-card-only`` marker line in their body, which + says the owner tracks that card outside the plan. + +The beat calls :func:`check` each tick. Everything it can fail on is a +structured reason, never an exception: an unreadable board, an unreadable plan +and an invalid plan all come back in the result. +""" + +from __future__ import annotations + +import copy +import json +import os +import tempfile +from pathlib import Path +from typing import Any, Callable, Mapping + +SCHEMA = "rizzstack.board-plan-orphans/1" + +CARD_ONLY_MARKER = "bundlebees-card-only" + +TERMINAL_STATUSES = frozenset( + { + "done", + "cancelled", + "canceled", + "archive", + "archived", + "completed", + } +) + +REASON_OK = "ok" +REASON_ORPHANS_REPORTED = "orphans_reported" +REASON_ORPHANS_FOLDED = "orphans_folded" +REASON_BOARD_UNREADABLE = "board_unreadable" +REASON_PLAN_UNREADABLE = "plan_unreadable" +REASON_PLAN_INVALID = "plan_invalid" +REASON_PLAN_UNWRITABLE = "plan_unwritable" + + +class BoardPlanError(Exception): + """A stable refusal name for a board or plan that cannot be processed.""" + + def __init__(self, code: str, message: str, fix: str = "") -> None: + super().__init__(message) + self.code = str(code) + self.message = str(message) + self.fix = str(fix) + + +def _mapping(value: Any) -> Mapping[str, Any] | None: + return value if isinstance(value, Mapping) else None + + +def _normal_status(value: Any) -> str: + return str(value if value is not None else "").strip().lower() + + +def actionable(card: Mapping[str, Any]) -> bool: + """True when a card is neither terminal nor card-only.""" + + if card_only(card): + return False + return _normal_status(card.get("status")) not in TERMINAL_STATUSES + + +def card_only(card: Mapping[str, Any]) -> bool: + """True when the body carries its own ``bundlebees-card-only`` marker line.""" + + body = card.get("body") + if not isinstance(body, str): + return False + for line in body.splitlines(): + stripped = line.strip() + if stripped == CARD_ONLY_MARKER: + return True + if stripped.startswith(CARD_ONLY_MARKER + ":"): + return True + if stripped.startswith(CARD_ONLY_MARKER + " "): + return True + return False + + +def parse_board_cards(payload: Any) -> list[dict[str, Any]]: + """Return the board's task list as normalised card mappings. + + A payload without a task list is unreadable; cards without a usable string + id are ignored because they cannot be reported or referenced by a slice. + """ + + body = _mapping(payload) + if body is None: + raise BoardPlanError(REASON_BOARD_UNREADABLE, "the board payload is not an object") + tasks = body.get("tasks") + if not isinstance(tasks, list): + raise BoardPlanError(REASON_BOARD_UNREADABLE, "the board payload has no task list") + + cards: list[dict[str, Any]] = [] + for raw in tasks: + item = _mapping(raw) + if item is None: + continue + card_id = item.get("id") + if not isinstance(card_id, str) or not card_id: + continue + card = dict(item) + card.setdefault("title", "") + card.setdefault("status", "") + card.setdefault("body", "") + card["card_only"] = card_only(card) + cards.append(card) + return cards + + +def _wave_slices(wave: Any) -> list[Any]: + if not isinstance(wave, Mapping): + raise BoardPlanError(REASON_PLAN_INVALID, "a wave is not an object") + if "slices" not in wave: + return [] + slices = wave.get("slices") + if not isinstance(slices, list): + raise BoardPlanError(REASON_PLAN_INVALID, "a wave's slices is not a list") + return slices + + +def flatten_plan_slices(plan: Any) -> list[dict[str, Any]]: + """Return every slice, all waves in order and the top-level list last.""" + + body = _mapping(plan) + if body is None: + raise BoardPlanError(REASON_PLAN_INVALID, "the plan is not an object") + + waves = body.get("waves", []) + if not isinstance(waves, list): + raise BoardPlanError(REASON_PLAN_INVALID, "the plan's waves is not a list") + + collected: list[dict[str, Any]] = [] + for wave in waves: + for item in _wave_slices(wave): + if not isinstance(item, Mapping): + raise BoardPlanError(REASON_PLAN_INVALID, "a slice is not an object") + collected.append(dict(item)) + + if "slices" in body: + top = body.get("slices") + if not isinstance(top, list): + raise BoardPlanError(REASON_PLAN_INVALID, "the plan's slices is not a list") + for item in top: + if not isinstance(item, Mapping): + raise BoardPlanError(REASON_PLAN_INVALID, "a slice is not an object") + collected.append(dict(item)) + return collected + + +def plan_references(plan: Any) -> set[str]: + """Collect every non-empty string slice id and board_card in the plan.""" + + references: set[str] = set() + for item in flatten_plan_slices(plan): + for key in ("id", "board_card"): + value = item.get(key) + if isinstance(value, str) and value: + references.add(value) + return references + + +def find_orphans(cards: Any, plan: Any) -> list[dict[str, Any]]: + """Return the actionable, unreferenced cards sorted by id.""" + + references = plan_references(plan) + orphans: list[dict[str, Any]] = [] + for raw in cards or []: + card = _mapping(raw) + if card is None: + continue + card_id = card.get("id") + if not isinstance(card_id, str) or not card_id: + continue + if card.get("card_only") is True or card_only(card): + continue + status = _normal_status(card.get("status")) + if status in TERMINAL_STATUSES: + continue + if card_id in references: + continue + title = card.get("title") + orphans.append( + { + "id": card_id, + "title": str(title) if title is not None else "", + "status": status, + "card_only": False, + } + ) + orphans.sort(key=lambda item: item["id"]) + return orphans + + +def _new_orphans_wave(waves: list[Any]) -> dict[str, Any]: + highest = 0 + for wave in waves: + if not isinstance(wave, Mapping): + continue + number = wave.get("wave") + if isinstance(number, (int, float)) and not isinstance(number, bool): + highest = max(highest, int(number)) + return {"wave": highest + 1, "name": "orphans", "status": "open", "slices": []} + + +def _folded_waves(folded_plan: dict[str, Any]) -> list[Any]: + waves = folded_plan.get("waves") + if waves is None: + waves = [] + folded_plan["waves"] = waves + return waves + + +def _orphans_target(waves: list[Any]) -> Any: + target = next( + ( + wave + for wave in waves + if isinstance(wave, Mapping) and wave.get("name") == "orphans" + ), + None, + ) + if target is None: + target = _new_orphans_wave(waves) + waves.append(target) + return target + + +def _orphans_slices(target: Any) -> list[Any]: + slices = target.get("slices") + if not isinstance(slices, list): + slices = [] + target["slices"] = slices + return slices + + +def _foldable_orphan(raw: Any, references: set[str]) -> Mapping[str, Any] | None: + orphan = _mapping(raw) + if orphan is None: + return None + card_id = orphan.get("id") + if not isinstance(card_id, str) or not card_id: + return None + if orphan.get("card_only") is True or card_only(orphan): + return None + if card_id in references: + return None + return orphan + + +def fold_orphans( + plan: Any, orphans: Any, *, repo: str = "" +) -> tuple[dict[str, Any], list[str]]: + """Deep-copy the plan and append one planned slice per unreferenced orphan.""" + + references = plan_references(plan) + folded_plan = copy.deepcopy(dict(plan)) + waves = _folded_waves(folded_plan) + slices = _orphans_slices(_orphans_target(waves)) + + folded: list[str] = [] + for raw in orphans or []: + orphan = _foldable_orphan(raw, references) + if orphan is None: + continue + card_id = orphan["id"] + title = orphan.get("title") + slices.append( + { + "id": card_id, + "board_card": card_id, + "title": str(title) if title is not None else "", + "status": "planned", + "repo": repo, + "note": f"folded from board card {card_id}", + } + ) + references.add(card_id) + folded.append(card_id) + return folded_plan, folded + + +def _result( + reason: str, + *, + reported: list[str] | None = None, + folded: list[str] | None = None, +) -> dict[str, Any]: + ok = reason in {REASON_OK, REASON_ORPHANS_REPORTED, REASON_ORPHANS_FOLDED} + return { + "schema": SCHEMA, + "ok": ok, + "reason": reason, + "reported": list(reported or []), + "folded": list(folded or []), + } + + +def _write_plan(path: Path, plan: Mapping[str, Any]) -> None: + fd, temporary = tempfile.mkstemp( + prefix=path.name + ".", suffix=".tmp", dir=str(path.parent) + ) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + json.dump(dict(plan), handle, indent=2, sort_keys=True) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + except Exception: + try: + os.unlink(temporary) + except OSError: + pass + raise + + +def _board_payload( + board_reader: Callable[[], Any] | None, board: Any +) -> Any: + if board_reader is not None: + try: + return board_reader() + except Exception: + return None + return board + + +def check( + plan_path: Any, + *, + board_reader: Callable[[], Any] | None = None, + fold: bool = False, + board: Any = None, + repo: str = "", + now: Any = None, +) -> dict[str, Any]: + """Report (and optionally fold) board cards that have no plan slice.""" + + path = Path(plan_path) + try: + plan = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError, TypeError): + return _result(REASON_PLAN_UNREADABLE) + + try: + flatten_plan_slices(plan) + except BoardPlanError: + return _result(REASON_PLAN_INVALID) + + payload = _board_payload(board_reader, board) + + try: + cards = parse_board_cards(payload) + except BoardPlanError: + return _result(REASON_BOARD_UNREADABLE) + + orphans = find_orphans(cards, plan) + reported = [orphan["id"] for orphan in orphans] + + if not fold: + reason = REASON_ORPHANS_REPORTED if reported else REASON_OK + return _result(reason, reported=reported) + + try: + folded_plan, folded = fold_orphans(plan, orphans, repo=repo) + except BoardPlanError: + return _result(REASON_PLAN_INVALID, reported=reported) + + if not folded: + return _result(REASON_OK, reported=reported) + + try: + _write_plan(path, folded_plan) + except OSError: + return _result(REASON_PLAN_UNWRITABLE, reported=reported) + + return _result(REASON_ORPHANS_FOLDED, reported=reported, folded=folded) + + +__all__ = [ + "BoardPlanError", + "CARD_ONLY_MARKER", + "SCHEMA", + "actionable", + "card_only", + "check", + "find_orphans", + "flatten_plan_slices", + "fold_orphans", + "parse_board_cards", + "plan_references", +] diff --git a/docs/heartbeat-lanes.md b/docs/heartbeat-lanes.md index e9d7442..99c78b5 100644 --- a/docs/heartbeat-lanes.md +++ b/docs/heartbeat-lanes.md @@ -29,6 +29,12 @@ It never verifies attempts, opens or merges PRs, deploys or restarts anything. W Cadence: every 30 minutes. Reconciles terminal attempts, drives the queue as a fallback, runs the merge stream (green at the exact head plus independent approval), proves deployments, and writes the beat record. It re-checks owner decisions but does not own them. +## Plan-orphan duty + +When the beat is given a `plan_path`, it also runs the board/plan sync check. Every board card whose normalised status is not terminal (`done`, `cancelled`/`canceled`, `archive`/`archived`, `completed`) is actionable; an actionable card with no slice whose `id` or `board_card` equals the card id is an orphan. The beat folds each orphan into the wave named `orphans` (or a new final wave), one `planned` slice per card, and writes the plan atomically. A second tick reports and folds nothing. + +A card whose body has its own line `bundlebees-card-only`, `bundlebees-card-only: ...` or `bundlebees-card-only ...` is owner-tracked outside the plan: it is never reported and never folded. Without a `plan_path` the duty does not exist and the beat report is unchanged. + ## Lanes and caps Complex, high-risk, cross-repo or failed-twice slices run on `k3.1-pro` (at most 6 running at once); docs, tests-only and low-risk slices run on the Nous lane (`nous:deepseek-v4.1-flash-1017`, then `nous:hy4-flash`); everything else uses `go:deepseek-v4.1-flash`. The launcher cap of 12 is shared with the rest of the stack; both lanes respect it and the run-level cap. diff --git a/tests/fixtures/board_plan_orphans/board_snapshot.json b/tests/fixtures/board_plan_orphans/board_snapshot.json new file mode 100644 index 0000000..8914862 --- /dev/null +++ b/tests/fixtures/board_plan_orphans/board_snapshot.json @@ -0,0 +1,134 @@ +{ + "tasks": [ + { + "id": "t_wa000001", + "title": "wave A follow-up one", + "status": "ready", + "body": "recorded card body scrubbed", + "assignee": null, + "priority": "high", + "created_at": "2026-11-24T22:10:00Z", + "project_id": null + }, + { + "id": "t_wa000002", + "title": "wave A follow-up two", + "status": "ready", + "body": "recorded card body scrubbed", + "assignee": null, + "priority": "high", + "created_at": "2026-11-24T22:11:00Z", + "project_id": null + }, + { + "id": "t_wa000003", + "title": "wave A follow-up three", + "status": "todo", + "body": "recorded card body scrubbed", + "assignee": null, + "priority": "medium", + "created_at": "2026-11-24T22:12:00Z", + "project_id": null + }, + { + "id": "t_wa000004", + "title": "wave A follow-up four", + "status": "blocked", + "body": "recorded card body scrubbed", + "assignee": null, + "priority": "medium", + "created_at": "2026-11-24T22:13:00Z", + "project_id": null + }, + { + "id": "t_wa000005", + "title": "wave A follow-up five", + "status": "review", + "body": "recorded card body scrubbed", + "assignee": null, + "priority": "low", + "created_at": "2026-11-24T22:14:00Z", + "project_id": null + }, + { + "id": "t_wa000006", + "title": "wave A follow-up six", + "status": "running", + "body": "recorded card body scrubbed", + "assignee": null, + "priority": "low", + "created_at": "2026-11-24T22:15:00Z", + "project_id": null + }, + { + "id": "t_wa000007", + "title": "wave A follow-up seven", + "status": "scheduled", + "body": "recorded card body scrubbed", + "assignee": null, + "priority": "low", + "created_at": "2026-11-24T22:16:00Z", + "project_id": null + }, + { + "id": "t_idref001", + "title": "referenced by a slice id", + "status": "ready", + "body": "recorded card body scrubbed", + "assignee": null, + "priority": "low", + "created_at": "2026-11-24T22:20:00Z", + "project_id": null + }, + { + "id": "t_ref000002", + "title": "referenced by a board card field", + "status": "todo", + "body": "recorded card body scrubbed", + "assignee": null, + "priority": "low", + "created_at": "2026-11-24T22:21:00Z", + "project_id": null + }, + { + "id": "t_done00001", + "title": "already done", + "status": "done", + "body": "recorded card body scrubbed", + "assignee": null, + "priority": "low", + "created_at": "2026-11-24T20:00:00Z", + "project_id": null + }, + { + "id": "t_canc00001", + "title": "cancelled by the owner", + "status": "cancelled", + "body": "recorded card body scrubbed", + "assignee": null, + "priority": "low", + "created_at": "2026-11-24T20:01:00Z", + "project_id": null + }, + { + "id": "t_arch00001", + "title": "archived card", + "status": "archive", + "body": "recorded card body scrubbed", + "assignee": null, + "priority": "low", + "created_at": "2026-11-24T20:02:00Z", + "project_id": null + }, + { + "id": "t_only00001", + "title": "owner tracks this outside the plan", + "status": "ready", + "body": "bundlebees-card-only: owner tracks this card outside the plan", + "assignee": null, + "priority": "low", + "created_at": "2026-11-24T22:30:00Z", + "project_id": null + } + ] +} diff --git a/tests/fixtures/board_plan_orphans/plan_snapshot.json b/tests/fixtures/board_plan_orphans/plan_snapshot.json new file mode 100644 index 0000000..1f10b9d --- /dev/null +++ b/tests/fixtures/board_plan_orphans/plan_snapshot.json @@ -0,0 +1,62 @@ +{ + "schema": "rizzstack.feature-batch/1", + "batch": "recorded-batch", + "objective": "recorded objective scrubbed", + "created_at": "2026-11-24T10:48:00Z", + "waves": [ + { + "wave": 1, + "name": "wave 1 - first pass", + "status": "closed", + "slices": [ + { + "id": "t_idref001", + "title": "referenced by a slice id", + "status": "merged", + "repo": "bundlebees", + "board_card": null, + "branch": "feat/recorded-one", + "attempt_id": null, + "note": "recorded note scrubbed" + }, + { + "id": "REF-TWO", + "title": "referenced by a board card field", + "status": "merged", + "repo": "bundlebees", + "board_card": "t_ref000002", + "branch": "feat/recorded-two", + "attempt_id": null, + "note": "recorded note scrubbed" + }, + { + "id": "PLAN-ONLY-ONE", + "title": "planned without a board card", + "status": "planned", + "repo": "bundlebees", + "board_card": null, + "branch": null, + "attempt_id": null, + "note": "recorded note scrubbed" + } + ] + }, + { + "wave": 9, + "name": "wave 9 - owner round", + "status": "in-progress", + "slices": [ + { + "id": "PLAN-ONLY-TWO", + "title": "another planned slice without a card", + "status": "planned", + "repo": "bundlebees", + "board_card": null, + "branch": null, + "attempt_id": null, + "note": "recorded note scrubbed" + } + ] + } + ] +} diff --git a/tests/test_board_plan_orphans.py b/tests/test_board_plan_orphans.py new file mode 100644 index 0000000..a058a86 --- /dev/null +++ b/tests/test_board_plan_orphans.py @@ -0,0 +1,494 @@ +"""RED tests for BOARD-PLAN-SYNC: every actionable board card has a plan slice. + +The board and plan payloads under ``tests/fixtures/board_plan_orphans/`` are +recorded shapes with every value scrubbed (no URLs, node ids, emails, names or +card bodies). The product module does not exist at this revision, so each +behavioural test imports it lazily: the RED run reports one failure per cited +node id instead of a single collection error. +""" + +from __future__ import annotations + +import json +import re +from pathlib import Path + +FIXTURES = Path(__file__).with_name("fixtures") / "board_plan_orphans" +BOARD_FIXTURE = FIXTURES / "board_snapshot.json" +PLAN_FIXTURE = FIXTURES / "plan_snapshot.json" + +WA_IDS = [f"t_wa{index:06d}" for index in range(1, 8)] +BODY_FILLER = "recorded card body scrubbed" + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _module(): + """Import the product module lazily so RED is per node id, not collection.""" + + from bundlebees_plugin import board_plan_orphans + + return board_plan_orphans + + +def _load(path: Path): + return json.loads(path.read_text(encoding="utf-8")) + + +def _board(): + return _load(BOARD_FIXTURE) + + +def _plan(): + return _load(PLAN_FIXTURE) + + +def _card(card_id, status="ready", body=BODY_FILLER, title=None): + return { + "id": card_id, + "title": title or f"card {card_id}", + "status": status, + "body": body, + } + + +def _payload(*cards): + return {"tasks": list(cards)} + + +def _plan_doc(*waves): + return {"schema": "rizzstack.feature-batch/1", "waves": list(waves)} + + +def _wave(number, *slices): + return { + "wave": number, + "name": f"wave {number}", + "status": "in-progress", + "slices": list(slices), + } + + +def _slice(slice_id, board_card=None): + return { + "id": slice_id, + "title": f"slice {slice_id}", + "status": "planned", + "repo": "bundlebees", + "board_card": board_card, + } + + +def _write(path: Path, plan): + path.write_text(json.dumps(plan, indent=1, sort_keys=True), encoding="utf-8") + return path + + +def _reported(module, plan, board): + return module.check(plan, board_reader=lambda: board, fold=False)["reported"] + + +# --------------------------------------------------------------------------- +# AC-001: report every actionable card no slice references +# --------------------------------------------------------------------------- + + +def test_the_recorded_board_snapshot_reports_exactly_the_seven_wave_a_cards(tmp_path): + module = _module() + result = module.check(_write(tmp_path / "plan.json", _plan()), board_reader=_board, fold=False) + assert result["reason"] == "orphans_reported" + assert result["ok"] is True + assert result["reported"] == WA_IDS + assert result["folded"] == [] + + +def test_a_slice_board_card_reference_keeps_its_card_out_of_the_report(tmp_path): + module = _module() + plan = _write(tmp_path / "plan.json", _plan_doc(_wave(1, _slice("REF-TWO", "t_ref000002")))) + assert _reported(module, plan, _payload(_card("t_ref000002"))) == [] + + +def test_a_slice_whose_id_is_the_card_id_references_the_card(tmp_path): + module = _module() + plan = _write(tmp_path / "plan.json", _plan_doc(_wave(1, _slice("t_idref001")))) + assert _reported(module, plan, _payload(_card("t_idref001"))) == [] + + +def test_done_cards_are_not_actionable(tmp_path): + module = _module() + plan = _write(tmp_path / "plan.json", _plan_doc()) + assert _reported(module, plan, _payload(_card("t_done", "done"))) == [] + + +def test_cancelled_and_archived_cards_are_not_actionable(tmp_path): + module = _module() + plan = _write(tmp_path / "plan.json", _plan_doc()) + board = _payload( + _card("t_cancelled", "cancelled"), + _card("t_canceled", "canceled"), + _card("t_archive", "archive"), + _card("t_archived", "archived"), + ) + assert _reported(module, plan, board) == [] + + +def test_a_card_with_a_status_outside_the_terminal_set_is_reported(tmp_path): + module = _module() + plan = _write(tmp_path / "plan.json", _plan_doc()) + assert _reported(module, plan, _payload(_card("t_odd", "waiting-on-someone"))) == ["t_odd"] + + +def test_a_body_that_names_a_slice_does_not_reference_the_card(tmp_path): + module = _module() + plan = _write(tmp_path / "plan.json", _plan_doc(_wave(1, _slice("PLAN-ONLY")))) + card = _card("t_body", "ready", body=f"Slice: PLAN-ONLY\n{BODY_FILLER}") + assert _reported(module, plan, _payload(card)) == ["t_body"] + + +# --------------------------------------------------------------------------- +# AC-002: the card-only marker is respected, never reported, never folded +# --------------------------------------------------------------------------- + + +def test_a_card_only_marker_line_keeps_the_card_out_of_the_report(tmp_path): + module = _module() + plan = _write(tmp_path / "plan.json", _plan_doc()) + card = _card("t_only", body="bundlebees-card-only: owner tracks this outside the plan") + assert module.card_only(card) is True + assert _reported(module, plan, _payload(card)) == [] + + +def test_the_card_only_marker_must_be_its_own_marker_line(tmp_path): + module = _module() + assert module.card_only(_card("t_near", body="note: bundlebees-card-only is handled elsewhere")) is False + assert module.card_only(_card("t_exact", body="bundlebees-card-only")) is True + assert module.card_only(_card("t_filler", body=BODY_FILLER)) is False + + +def test_the_recorded_card_only_card_is_not_reported(tmp_path): + module = _module() + result = module.check(_write(tmp_path / "plan.json", _plan()), board_reader=_board, fold=False) + assert "t_only00001" not in result["reported"] + + +def test_a_card_only_card_is_never_folded(tmp_path): + module = _module() + plan = _write(tmp_path / "plan.json", _plan_doc()) + board = _payload(_card("t_wa_only", body="bundlebees-card-only: tracked by the owner")) + result = module.check(plan, board_reader=lambda: board, fold=True) + assert result["reported"] == [] + assert result["folded"] == [] + assert module.plan_references(_load(plan)) == set() + + +# --------------------------------------------------------------------------- +# AC-003: flatten plan.json slices +# --------------------------------------------------------------------------- + + +def test_flatten_plan_slices_reads_every_wave_and_the_top_level_list(): + module = _module() + plan = { + "slices": [{"id": "TOP"}], + "waves": [ + {"wave": 1, "slices": [{"id": "W1"}]}, + {"wave": 2, "slices": [{"id": "W2"}]}, + {"wave": 3}, + ], + } + assert [item["id"] for item in module.flatten_plan_slices(plan)] == ["W1", "W2", "TOP"] + + +def test_flatten_plan_slices_refuses_a_plan_that_is_not_an_object(): + module = _module() + try: + module.flatten_plan_slices([]) + except module.BoardPlanError as exc: + assert exc.code == "plan_invalid" + else: + raise AssertionError("a plan that is not an object must be refused") + + +def test_flatten_plan_slices_refuses_waves_that_are_not_a_list(): + module = _module() + try: + module.flatten_plan_slices({"waves": {}}) + except module.BoardPlanError as exc: + assert exc.code == "plan_invalid" + else: + raise AssertionError("waves that are not a list must be refused") + + +def test_plan_references_collects_slice_ids_and_board_cards(): + module = _module() + plan = { + "waves": [ + {"slices": [{"id": "A", "board_card": "t_1"}, {"id": "B"}, {"board_card": "t_2"}]} + ] + } + assert module.plan_references(plan) == {"A", "t_1", "B", "t_2"} + + +# --------------------------------------------------------------------------- +# AC-004: folding is idempotent and never duplicates a slice +# --------------------------------------------------------------------------- + + +def test_folding_appends_one_planned_slice_per_orphan_under_the_orphans_wave(tmp_path): + module = _module() + plan = _write(tmp_path / "plan.json", _plan()) + before = len(module.flatten_plan_slices(_load(plan))) + result = module.check(plan, board_reader=_board, fold=True, repo="bundlebees") + assert result["folded"] == WA_IDS + after = _load(plan) + slices = module.flatten_plan_slices(after) + assert len(slices) == before + len(WA_IDS) + waves = [wave for wave in after["waves"] if wave.get("name") == "orphans"] + assert len(waves) == 1 + folded = {item["id"]: item for item in waves[0]["slices"]} + assert sorted(folded) == WA_IDS + for card_id in WA_IDS: + assert folded[card_id]["board_card"] == card_id + assert folded[card_id]["status"] == "planned" + assert folded[card_id]["repo"] == "bundlebees" + + +def test_folding_the_same_orphans_again_is_a_no_op(tmp_path): + module = _module() + plan = _plan() + orphans = module.find_orphans(module.parse_board_cards(_board()), plan) + first, folded_first = module.fold_orphans(plan, orphans, repo="bundlebees") + second, folded_second = module.fold_orphans(first, orphans, repo="bundlebees") + assert folded_first == WA_IDS + assert folded_second == [] + assert len(module.flatten_plan_slices(second)) == len(module.flatten_plan_slices(first)) + + +def test_a_second_check_after_folding_reports_zero(tmp_path): + module = _module() + plan = _write(tmp_path / "plan.json", _plan()) + first = module.check(plan, board_reader=_board, fold=True) + second = module.check(plan, board_reader=_board, fold=True) + assert first["reported"] == WA_IDS + assert second["reported"] == [] + assert second["folded"] == [] + assert second["reason"] == "ok" + + +def test_folding_an_already_present_card_creates_no_duplicate_slice(tmp_path): + module = _module() + plan = _plan_doc(_wave(1, _slice("EXISTING", "t_wa000001"))) + orphans = [{"id": "t_wa000001", "status": "ready", "title": "already referenced", "card_only": False}] + folded_plan, folded = module.fold_orphans(plan, orphans) + assert folded == [] + matches = [ + item + for item in module.flatten_plan_slices(folded_plan) + if item.get("board_card") == "t_wa000001" + ] + assert len(matches) == 1 + + +def test_folding_distinct_orphans_reuses_an_existing_orphans_wave(tmp_path): + module = _module() + pre_existing = _slice("ORPHAN-PREEXISTING", "t_old000001") + plan = _write( + tmp_path / "plan.json", + _plan_doc( + _wave(1, _slice("WAVE-ONE")), + {"wave": 2, "name": "orphans", "status": "open", "slices": [pre_existing]}, + ), + ) + board = _payload(_card("t_new00001"), _card("t_new00002", "todo")) + + first = module.check(plan, board_reader=lambda: board, fold=True, repo="bundlebees") + assert first["reported"] == ["t_new00001", "t_new00002"] + assert first["folded"] == ["t_new00001", "t_new00002"] + + after = _load(plan) + orphans_waves = [wave for wave in after["waves"] if wave.get("name") == "orphans"] + assert len(orphans_waves) == 1 + assert len(after["waves"]) == 2 + reused = orphans_waves[0] + assert reused["wave"] == 2 + assert reused["status"] == "open" + assert [item.get("id") for item in reused["slices"]] == [ + "ORPHAN-PREEXISTING", + "t_new00001", + "t_new00002", + ] + assert reused["slices"][0] == pre_existing + for card_id in ("t_new00001", "t_new00002"): + item = next(slice_ for slice_ in reused["slices"] if slice_.get("id") == card_id) + assert item["board_card"] == card_id + assert item["status"] == "planned" + assert item["repo"] == "bundlebees" + + second = module.check(plan, board_reader=lambda: board, fold=True, repo="bundlebees") + assert second["reported"] == [] + assert second["folded"] == [] + + again = _load(plan) + again_waves = [wave for wave in again["waves"] if wave.get("name") == "orphans"] + assert len(again_waves) == 1 + assert len(again["waves"]) == 2 + assert [item.get("id") for item in again_waves[0]["slices"]] == [ + "ORPHAN-PREEXISTING", + "t_new00001", + "t_new00002", + ] + + +# --------------------------------------------------------------------------- +# AC-005: the check is beat-callable, structured and fail-soft +# --------------------------------------------------------------------------- + + +def test_check_returns_reported_folded_and_reason(tmp_path): + module = _module() + plan = _write(tmp_path / "plan.json", _plan()) + report_only = module.check(plan, board_reader=_board, fold=False) + assert report_only["schema"] == module.SCHEMA + assert report_only["reported"] == WA_IDS + assert report_only["folded"] == [] + assert report_only["reason"] == "orphans_reported" + folded = module.check(plan, board_reader=_board, fold=True) + assert folded["reported"] == WA_IDS + assert folded["folded"] == WA_IDS + assert folded["reason"] == "orphans_folded" + + +def test_check_reports_a_clean_plan_as_ok(tmp_path): + module = _module() + plan = _write( + tmp_path / "plan.json", + _plan_doc(_wave(1, *[_slice(card_id, card_id) for card_id in WA_IDS])), + ) + board = _payload(*[_card(card_id) for card_id in WA_IDS]) + result = module.check(plan, board_reader=lambda: board) + assert result["ok"] is True + assert result["reason"] == "ok" + assert result["reported"] == [] + assert result["folded"] == [] + + +def test_an_unreadable_board_is_a_reason_not_an_exception(tmp_path): + module = _module() + plan = _write(tmp_path / "plan.json", _plan()) + + def boom(): + raise OSError("the board could not be read") + + result = module.check(plan, board_reader=boom) + assert result["ok"] is False + assert result["reason"] == "board_unreadable" + assert result["reported"] == [] + assert result["folded"] == [] + + +def test_a_board_payload_without_a_task_list_is_unreadable(tmp_path): + module = _module() + plan = _write(tmp_path / "plan.json", _plan()) + result = module.check(plan, board_reader=lambda: {"tasks": "not-a-list"}) + assert result["ok"] is False + assert result["reason"] == "board_unreadable" + assert result["reported"] == [] + + +def test_an_unreadable_plan_is_a_reason_not_an_exception(tmp_path): + module = _module() + result = module.check(tmp_path / "missing-plan.json", board_reader=_board) + assert result["ok"] is False + assert result["reason"] == "plan_unreadable" + assert result["reported"] == [] + assert result["folded"] == [] + + +def test_the_beat_runs_the_plan_orphan_duty(tmp_path): + from bundlebees_plugin import beat + + module = _module() + plan = _write(tmp_path / "plan.json", _plan()) + report = beat.beat( + tmp_path / "state", + launcher=[], + origin_branches=[], + open_prs=[], + plan_path=plan, + board_reader=_board, + ) + duty = report["duties"][beat.DUTY_PLAN_ORPHANS] + assert duty["status"] == "ok" + assert duty["reason"] == "orphans_folded" + assert duty["reported"] == WA_IDS + assert duty["folded"] == WA_IDS + + +def test_the_beat_reports_a_failing_check_as_a_duty_error_not_a_crash(tmp_path): + from bundlebees_plugin import beat + + module = _module() + plan = _write(tmp_path / "plan.json", _plan()) + + def boom(): + raise OSError("the board could not be read") + + report = beat.beat( + tmp_path / "state", + launcher=[], + origin_branches=[], + open_prs=[], + plan_path=plan, + board_reader=boom, + ) + duty = report["duties"][beat.DUTY_PLAN_ORPHANS] + assert duty["status"] == "error" + assert duty["reason"] == "board_unreadable" + assert report["status"] == "partial" + + +# --------------------------------------------------------------------------- +# AC-006 (regression): existing beat behaviour and the recorded fixtures +# --------------------------------------------------------------------------- + + +def test_the_beat_without_a_plan_path_keeps_its_existing_duties(tmp_path): + from bundlebees_plugin import beat + + report = beat.beat(tmp_path / "state", launcher=[], origin_branches=[], open_prs=[]) + assert report["status"] == "ok" + assert "board_plan_orphans" not in report["duties"] + + +def test_the_recorded_board_fixture_keeps_the_task_list_shape(): + payload = _board() + assert isinstance(payload["tasks"], list) + assert payload["tasks"] + for card in payload["tasks"]: + assert {"id", "title", "status", "body"} <= set(card) + + +def test_the_recorded_plan_fixture_keeps_the_waves_shape(): + plan = _plan() + assert plan["schema"] == "rizzstack.feature-batch/1" + assert isinstance(plan["waves"], list) + assert plan["waves"] + for wave in plan["waves"]: + assert {"wave", "name", "slices"} <= set(wave) + for item in wave["slices"]: + assert {"id", "status"} <= set(item) + + +def test_every_fixture_value_is_scrubbed(): + text = "\n".join(path.read_text(encoding="utf-8") for path in sorted(FIXTURES.glob("*.json"))) + assert "http://" not in text + assert "https://" not in text + assert "@" not in text + assert not re.search(r'"(?:node_id|email|author|author_name|login|user)"\s*:', text) + assert not re.search(r"\b(?:PR|I|R|MDEx|MDEy|kg|IC)_[A-Za-z0-9_-]{10,}\b", text) + for card in _board()["tasks"]: + body = card.get("body") + assert body == BODY_FILLER or body.startswith("bundlebees-card-only:")