kanban_workflow.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. """Kanban board workflow: the one definition of board columns and manual moves.
  2. Groundwork for user-defined columns and workflow per board (issue #54818). Target
  3. model: ``tasks.status`` holds a board-defined column key.
  4. Phase 0 (this module) holds only what is consumed or checked today: the column list
  5. (order, label, CLI icon, drag target) and the manual move matrix. The scattered status
  6. copies (``VALID_STATUSES``, ``BOARD_COLUMNS``, the agent-tool enum, CLI icons) derive
  7. from it, and ``tests/plugins/test_kanban_workflow_matrix.py`` pins ``manual`` to the live
  8. dashboard API in both directions.
  9. Kernel semantics are deliberately NOT modelled here — neither what a column means to
  10. the dispatcher (claimable, terminal, parent gate) nor kernel-driven transitions (~20
  11. conditional status writes: block routing, crash/reclaim return, parent reopen, import).
  12. Both are designed together with the kernel switch, so this module never publishes a
  13. partial contract.
  14. Pure data + stdlib only: ``kanban_db`` imports this module, never the reverse.
  15. """
  16. from __future__ import annotations
  17. from dataclasses import dataclass
  18. from types import MappingProxyType
  19. from typing import Iterator, Mapping, Optional
  20. # ``archived`` is outside every workflow: a filter toggle, never a board column.
  21. ARCHIVED = "archived"
  22. @dataclass(frozen=True)
  23. class Column:
  24. """One board column. ``key`` is stable (stored in ``tasks.status``); ``label`` is display-only."""
  25. key: str
  26. label: str
  27. icon: str = "?" # single-glyph CLI marker
  28. # Offered as a drag/menu target in board UIs. False for columns a card normally
  29. # reaches only through a verb with extra input (reviewer, wake time) or the kernel.
  30. drag_target: bool = True
  31. @dataclass(frozen=True)
  32. class Workflow:
  33. """Columns (board order) and the manual move allow-list."""
  34. columns: tuple[Column, ...]
  35. # Manual moves (drag, PATCH status) a human may request: ``src -> {dst}``. Archiving
  36. # (dst) is always allowed and not listed; ``archived`` may appear as a source (restore). Allowed != guaranteed: verbs still apply their own
  37. # gates (parents open, completion evidence).
  38. manual: Mapping[str, frozenset[str]]
  39. def __iter__(self) -> Iterator[Column]:
  40. return iter(self.columns)
  41. def keys(self) -> tuple[str, ...]:
  42. """Column keys in board order (never includes ``archived``)."""
  43. return tuple(c.key for c in self.columns)
  44. def column(self, key: str) -> Optional[Column]:
  45. return next((c for c in self.columns if c.key == key), None)
  46. def _require(self, key: str) -> Column:
  47. col = self.column(key)
  48. if col is None:
  49. raise ValueError(f"unknown kanban workflow column {key!r}")
  50. return col
  51. def can_move(self, src: str, dst: str) -> bool:
  52. """True when a human may request ``src -> dst``. Archiving is always allowed;
  53. ``archived`` is a valid source (restore). ``src == dst`` is not a move."""
  54. if src != ARCHIVED:
  55. self._require(src)
  56. if src == dst:
  57. return False
  58. if dst == ARCHIVED:
  59. return True
  60. self._require(dst)
  61. return dst in self.manual.get(src, frozenset())
  62. def to_dict(self) -> dict:
  63. """JSON shape served by the dashboard's ``GET /workflow``. ``manual`` keys are the
  64. column keys plus ``archived`` (restore source), which is never a column."""
  65. return {
  66. "columns": [
  67. {"key": c.key, "label": c.label, "icon": c.icon, "drag_target": c.drag_target}
  68. for c in self.columns
  69. ],
  70. "manual": {src: sorted(dsts) for src, dsts in self.manual.items()},
  71. "archived": ARCHIVED,
  72. }
  73. def validate(self) -> None:
  74. """Raise ``ValueError`` on an inconsistent workflow (duplicate or unknown keys)."""
  75. keys = self.keys()
  76. if len(set(keys)) != len(keys):
  77. raise ValueError(f"duplicate column keys: {keys}")
  78. if ARCHIVED in keys:
  79. raise ValueError(f"{ARCHIVED!r} is reserved and cannot be a column")
  80. known = set(keys)
  81. for src, dsts in self.manual.items():
  82. if src not in known | {ARCHIVED} or not set(dsts) <= known:
  83. raise ValueError(f"manual moves from {src!r} reference unknown columns")
  84. def _frozen_manual(table: Mapping[str, tuple[str, ...]]) -> Mapping[str, frozenset[str]]:
  85. return MappingProxyType({src: frozenset(dsts) for src, dsts in table.items()})
  86. # Today's board, written down. Column order = dashboard order. ``drag_target=False``
  87. # mirrors the desktop's LOCKED_COLUMNS (review needs a reviewer, scheduled a wake time,
  88. # running is kernel-only). The manual table is the measured PATCH /tasks/{id} matrix on
  89. # a parentless task; ``test_kanban_workflow_matrix.py`` re-measures it against the live API.
  90. DEFAULT_WORKFLOW = Workflow(
  91. columns=(
  92. Column("triage", "Triage", "◇"),
  93. Column("todo", "Todo", "◻"),
  94. Column("scheduled", "Scheduled", "⏱", drag_target=False),
  95. Column("ready", "Ready", "▶"),
  96. Column("running", "Running", "●", drag_target=False),
  97. Column("blocked", "Blocked", "⊘"),
  98. Column("review", "Review", "◎", drag_target=False),
  99. Column("done", "Done", "✓"),
  100. ),
  101. manual=_frozen_manual({
  102. "triage": ("todo", "ready"),
  103. "todo": ("triage", "scheduled", "ready"),
  104. "scheduled": ("triage", "todo", "ready"),
  105. "ready": ("triage", "todo", "scheduled", "blocked", "review", "done"),
  106. "running": ("triage", "todo", "scheduled", "ready", "blocked", "review", "done"),
  107. "blocked": ("triage", "todo", "scheduled", "ready", "done"),
  108. # Known quirk kept for zero behavior change: review -> todo lands in ``ready``
  109. # (reopen_review_task ignores the requested target). Phase 1 fixes it.
  110. "review": ("triage", "todo", "ready", "done"),
  111. "done": ("triage", "todo", "ready"),
  112. ARCHIVED: ("triage", "todo", "ready"), # restore from the archive filter
  113. }),
  114. )
  115. DEFAULT_WORKFLOW.validate()
  116. # Every value ``tasks.status`` can hold under the default workflow.
  117. DEFAULT_STATUSES = frozenset(DEFAULT_WORKFLOW.keys()) | {ARCHIVED}