kanban_db_boards.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. """Board metadata (``board.json``) and board lifecycle management for the Kanban DB:
  2. read/write of per-board display metadata, board creation/discovery/archival, and the
  3. ``board.json``-as-identity-marker rule.
  4. Split out of ``hermes_cli.kanban_db``; origin-resident helpers are reached
  5. late-bound via ``_kb`` (import-cycle breaking) so monkeypatching
  6. ``kanban_db.<name>`` keeps working.
  7. """
  8. from __future__ import annotations
  9. import json
  10. import time
  11. from typing import Any
  12. from typing import Optional
  13. from pathlib import Path
  14. def _dir_holds_board(d: Path) -> bool:
  15. # ``board.json`` is the identity marker: archive/hard-delete both leave the
  16. # directory without it, and a stale ``connect(board=slug)`` used to leave a
  17. # ``kanban.db``-only stub that resurfaced in the board list as an empty
  18. # active board (#43243). Discovery must therefore require the metadata
  19. # file; a DB-only directory is a stub to ignore, never a board.
  20. return (d / "board.json").exists()
  21. def board_metadata_path(board: Optional[str] = None) -> Path:
  22. """``board.json`` path — display metadata only; the directory slug is the identity."""
  23. return _kb.board_dir(_kb._slug_or_default(board)) / "board.json"
  24. def _default_board_display_name(slug: str) -> str:
  25. """``atm10-server`` -> ``Atm10 Server``."""
  26. return " ".join(part.capitalize() for part in slug.replace("_", "-").split("-") if part) or slug
  27. def read_board_metadata(board: Optional[str] = None) -> dict:
  28. """``board.json`` merged over defaults, plus ``slug`` and ``db_path``. Never
  29. raises — a missing/malformed file yields the synthesized entry."""
  30. slug = _kb._slug_or_default(board)
  31. meta: dict[str, Any] = {
  32. "slug": slug,
  33. "name": _default_board_display_name(slug),
  34. "description": "",
  35. "icon": "",
  36. "color": "",
  37. "default_workdir": None,
  38. # Project scope: new tasks inherit it (deterministic worktree + branch).
  39. "project_id": None,
  40. "created_at": None,
  41. "archived": False,
  42. }
  43. try:
  44. p = board_metadata_path(slug)
  45. if p.exists():
  46. raw = json.loads(p.read_text(encoding="utf-8-sig"))
  47. if isinstance(raw, dict):
  48. # Never let the metadata file claim a different slug than
  49. # its directory — trust the filesystem.
  50. raw["slug"] = slug
  51. meta.update(raw)
  52. except (OSError, json.JSONDecodeError):
  53. pass
  54. meta["db_path"] = str(_kb.kanban_db_path(slug))
  55. return meta
  56. def write_board_metadata(
  57. board: Optional[str], *, name: Optional[str] = None, description: Optional[str] = None,
  58. icon: Optional[str] = None, color: Optional[str] = None, archived: Optional[bool] = None,
  59. default_workdir: Optional[str] = None, project_id: Optional[str] = None,
  60. ) -> dict:
  61. """Create/update ``board.json``; unmentioned fields are preserved, ``created_at``
  62. set on first write. ``project_id``/``default_workdir``: ``None`` = unchanged,
  63. "" = clear (``project_id`` is not validated here)."""
  64. _kb._assert_not_delegated_child_mutation()
  65. slug = _kb._slug_or_default(board)
  66. meta = read_board_metadata(slug)
  67. # db_path is derived on every read; never persist it into board.json.
  68. meta.pop("db_path", None)
  69. if name is not None:
  70. meta["name"] = str(name).strip() or _default_board_display_name(slug)
  71. for key, value in (("description", description), ("icon", icon), ("color", color)):
  72. if value is not None:
  73. meta[key] = str(value)
  74. if archived is not None:
  75. meta["archived"] = bool(archived)
  76. for key, value in (("default_workdir", default_workdir), ("project_id", project_id)):
  77. if value is not None:
  78. meta[key] = str(value) if value else None
  79. if not meta.get("created_at"):
  80. meta["created_at"] = int(time.time())
  81. path = board_metadata_path(slug)
  82. path.parent.mkdir(parents=True, exist_ok=True)
  83. path.write_text(
  84. json.dumps(meta, indent=2, ensure_ascii=False) + "\n", encoding="utf-8",
  85. )
  86. meta["db_path"] = str(_kb.kanban_db_path(slug))
  87. return meta
  88. def create_board(
  89. slug: str, *, name: Optional[str] = None, description: Optional[str] = None,
  90. icon: Optional[str] = None, color: Optional[str] = None, default_workdir: Optional[str] = None,
  91. project_id: Optional[str] = None,
  92. ) -> dict:
  93. """Create board dir + DB + metadata (``mkdir -p`` semantics: existing board returns its metadata)."""
  94. normed = _kb._require_slug(slug)
  95. # Explicit creation clears any archived tombstone at this slug (left by
  96. # remove_board(archive=True)) — otherwise _kb.init_db() below would rightly
  97. # refuse to recreate the archived board's DB (#43243).
  98. meta = write_board_metadata(
  99. normed, name=name, description=description, icon=icon, color=color,
  100. default_workdir=default_workdir, project_id=project_id, archived=False,
  101. )
  102. # Touch the DB so list_boards() sees it immediately.
  103. _kb.init_db(board=normed)
  104. return meta
  105. def list_boards(*, include_archived: bool = True) -> list[dict]:
  106. """Metadata for every board: ``default`` first (always present), then
  107. ``boards/<slug>/`` dirs holding a ``kanban.db`` or ``board.json``, sorted."""
  108. entries = [read_board_metadata(_kb.DEFAULT_BOARD)]
  109. seen = {_kb.DEFAULT_BOARD}
  110. root = _kb.boards_root()
  111. if root.is_dir():
  112. for child in sorted(root.iterdir(), key=lambda p: p.name.lower()):
  113. if not child.is_dir():
  114. continue
  115. try:
  116. normed = _kb._normalize_board_slug(child.name) # skip junk dirs, don't raise
  117. except ValueError:
  118. continue
  119. if not normed or normed in seen or not _dir_holds_board(child):
  120. continue
  121. meta = read_board_metadata(normed)
  122. if meta.get("archived") and not include_archived:
  123. continue
  124. entries.append(meta)
  125. seen.add(normed)
  126. return entries
  127. def remove_board(slug: str, *, archive: bool = True) -> dict:
  128. """Archive (to ``boards/_archived/<slug>-<ts>/``) or delete a board;
  129. ``default`` cannot be removed. Returns ``{"slug", "action", "new_path"}``."""
  130. _kb._assert_not_delegated_child_mutation()
  131. normed = _kb._require_slug(slug)
  132. if normed == _kb.DEFAULT_BOARD:
  133. raise ValueError("the 'default' board cannot be removed")
  134. d = _kb.board_dir(normed)
  135. if not d.exists():
  136. raise ValueError(f"board {normed!r} does not exist")
  137. # If the user removed the currently-active board, revert to default.
  138. if _kb.get_current_board() == normed:
  139. _kb.clear_current_board()
  140. # A concurrent connect() after the rename recreates an empty DB file; drop
  141. # the init cache first so the schema pass re-runs on it.
  142. _kb._INITIALIZED_PATHS.discard(str((d / "kanban.db").resolve()))
  143. if archive:
  144. # Capture display metadata before the move so the tombstone below keeps
  145. # the user's board name instead of falling back to a title-cased slug.
  146. prior_meta = read_board_metadata(normed)
  147. archive_root = _kb.boards_root() / "_archived"
  148. archive_root.mkdir(parents=True, exist_ok=True)
  149. ts = int(time.time())
  150. target = archive_root / f"{normed}-{ts}"
  151. suffix = 1
  152. while target.exists(): # rapid double-archive
  153. target = archive_root / f"{normed}-{ts}-{suffix}"
  154. suffix += 1
  155. d.rename(target)
  156. # Leave an ``archived`` tombstone at the original slug. Stale dashboard
  157. # tabs / gateway pollers can keep calling connect(board=slug) after the
  158. # archive; without a marker the resurrect-guard cannot tell an archived
  159. # slug from a brand-new one and an empty board would reappear (#43243).
  160. write_board_metadata(
  161. normed,
  162. name=prior_meta.get("name"),
  163. description=prior_meta.get("description"),
  164. icon=prior_meta.get("icon"),
  165. color=prior_meta.get("color"),
  166. default_workdir=prior_meta.get("default_workdir"),
  167. project_id=prior_meta.get("project_id"),
  168. archived=True,
  169. )
  170. return {"slug": normed, "action": "archived", "new_path": str(target)}
  171. import shutil
  172. shutil.rmtree(d)
  173. return {"slug": normed, "action": "deleted", "new_path": ""}
  174. # Late-bound origin namespace (see module docstring); imported LAST so this
  175. # module is fully populated before ``kanban_db`` imports from it.
  176. from hermes_cli import kanban_db as _kb