kanban_pr_acceptance_store.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. """Persist acceptance with the same ownership snapshot as the terminal write."""
  2. from __future__ import annotations
  3. from hermes_cli.kanban_db_connect import write_txn
  4. from hermes_cli.kanban_pr_acceptance import _PR, collect_acceptance
  5. def _snapshot(conn, task_id):
  6. row = conn.execute("SELECT current_run_id, status, completion_contract FROM tasks WHERE id=?", (task_id,)).fetchone()
  7. return tuple(row) if row else None
  8. def prepare_acceptance(conn, task_id, expected_run_id, metadata):
  9. snapshot = _snapshot(conn, task_id)
  10. if snapshot is None:
  11. return False
  12. run_id, status, contract = snapshot
  13. if not contract or contract == "local-only":
  14. return None
  15. if status not in {"running", "ready", "blocked", "review"} or (expected_run_id is not None and run_id != expected_run_id):
  16. return False
  17. published_pr = metadata.get("published_pr") if isinstance(metadata, dict) else None
  18. match = _PR.fullmatch(published_pr) if isinstance(published_pr, str) else None
  19. # Publication binds once. Retrying cannot replace the task's PR with a green sibling.
  20. if match and contract == match[1]:
  21. with write_txn(conn):
  22. if _snapshot(conn, task_id) != snapshot:
  23. return False
  24. conn.execute("UPDATE tasks SET completion_contract=? WHERE id=?", (published_pr, task_id))
  25. snapshot = (run_id, status, published_pr)
  26. contract = published_pr
  27. # The assignee profile's gh login owns the repo: acceptance must not run as
  28. # the ambient login of whichever process completes the card (#122689).
  29. assignee = conn.execute("SELECT assignee FROM tasks WHERE id=?", (task_id,)).fetchone()["assignee"]
  30. return snapshot, collect_acceptance(contract, published_pr, assignee=assignee)
  31. def record_acceptance(conn, task_id, acceptance):
  32. """Called under complete_task's write_txn, before its terminal UPDATE."""
  33. from hermes_cli.kanban_db import _append_event
  34. snapshot, receipt = acceptance
  35. if _snapshot(conn, task_id) != snapshot:
  36. return False
  37. _append_event(conn, task_id, "pr_acceptance", receipt, run_id=snapshot[0])
  38. if not receipt["ok"]:
  39. detail = f"PR acceptance {receipt['classification']}: {receipt.get('detail', '')} {receipt['recovery']}"
  40. conn.execute("UPDATE tasks SET last_failure_error=? WHERE id=?", (detail, task_id))
  41. return receipt["ok"]