|
| 1 | +"""Handoff health checks shared by CLI doctors.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import json |
| 5 | +import sys |
| 6 | +from dataclasses import dataclass |
| 7 | +from pathlib import Path |
| 8 | +from typing import Any |
| 9 | + |
| 10 | +OK = "ok" |
| 11 | +WARN = "warn" |
| 12 | +FAIL = "fail" |
| 13 | + |
| 14 | +WRITER_INBOXES = (".claude/memory-handoffs", ".codex/memory-handoffs") |
| 15 | +IGNORED_HANDOFF_NAMES = {"TEMPLATE.md"} |
| 16 | + |
| 17 | + |
| 18 | +@dataclass(frozen=True) |
| 19 | +class WatchedInbox: |
| 20 | + root: Path |
| 21 | + inbox: str |
| 22 | + |
| 23 | + |
| 24 | +@dataclass(frozen=True) |
| 25 | +class InboxHealth: |
| 26 | + inbox: str |
| 27 | + path: Path |
| 28 | + exists: bool |
| 29 | + pending: int |
| 30 | + processed: int |
| 31 | + watched: bool |
| 32 | + |
| 33 | + def as_dict(self) -> dict[str, Any]: |
| 34 | + return { |
| 35 | + "inbox": self.inbox, |
| 36 | + "path": str(self.path), |
| 37 | + "exists": self.exists, |
| 38 | + "pending": self.pending, |
| 39 | + "processed": self.processed, |
| 40 | + "watched": self.watched, |
| 41 | + } |
| 42 | + |
| 43 | + |
| 44 | +@dataclass(frozen=True) |
| 45 | +class HandoffHealth: |
| 46 | + target: Path |
| 47 | + sources_path: Path | None |
| 48 | + sources_loaded: bool |
| 49 | + inboxes: tuple[InboxHealth, ...] |
| 50 | + warnings: tuple[str, ...] |
| 51 | + failures: tuple[str, ...] |
| 52 | + |
| 53 | + def as_dict(self) -> dict[str, Any]: |
| 54 | + return { |
| 55 | + "target": str(self.target), |
| 56 | + "sources_path": str(self.sources_path) if self.sources_path else None, |
| 57 | + "sources_loaded": self.sources_loaded, |
| 58 | + "inboxes": [inbox.as_dict() for inbox in self.inboxes], |
| 59 | + "warnings": list(self.warnings), |
| 60 | + "failures": list(self.failures), |
| 61 | + } |
| 62 | + |
| 63 | + |
| 64 | +def default_sources_path(target: Path) -> Path: |
| 65 | + return target / ".brigade" / "handoff-sources.json" |
| 66 | + |
| 67 | + |
| 68 | +def inspect(target: Path, sources: Path | None = None) -> HandoffHealth: |
| 69 | + target = target.expanduser().resolve() |
| 70 | + sources_path = sources.expanduser().resolve() if sources is not None else default_sources_path(target) |
| 71 | + watched: tuple[WatchedInbox, ...] = () |
| 72 | + failures: list[str] = [] |
| 73 | + sources_loaded = False |
| 74 | + |
| 75 | + if sources_path.is_file(): |
| 76 | + try: |
| 77 | + watched = _load_sources(target, sources_path) |
| 78 | + except ValueError as exc: |
| 79 | + failures.append(f"invalid handoff source config {sources_path}: {exc}") |
| 80 | + else: |
| 81 | + sources_loaded = True |
| 82 | + elif sources is not None: |
| 83 | + failures.append(f"handoff source config not found: {sources_path}") |
| 84 | + sources_path = sources_path |
| 85 | + else: |
| 86 | + sources_path = None |
| 87 | + |
| 88 | + inboxes = tuple(_inspect_inbox(target, rel, watched) for rel in WRITER_INBOXES) |
| 89 | + warnings: list[str] = [] |
| 90 | + pending_total = sum(inbox.pending for inbox in inboxes) |
| 91 | + if pending_total and not sources_loaded and not failures: |
| 92 | + warnings.append( |
| 93 | + "pending handoffs exist but no .brigade/handoff-sources.json is configured" |
| 94 | + ) |
| 95 | + for inbox in inboxes: |
| 96 | + if inbox.pending and not inbox.watched: |
| 97 | + warnings.append( |
| 98 | + f"{inbox.inbox} has {inbox.pending} pending handoff" |
| 99 | + f"{'s' if inbox.pending != 1 else ''} but is not watched by the source config" |
| 100 | + ) |
| 101 | + |
| 102 | + return HandoffHealth( |
| 103 | + target=target, |
| 104 | + sources_path=sources_path, |
| 105 | + sources_loaded=sources_loaded, |
| 106 | + inboxes=inboxes, |
| 107 | + warnings=tuple(warnings), |
| 108 | + failures=tuple(failures), |
| 109 | + ) |
| 110 | + |
| 111 | + |
| 112 | +def doctor_checks(target: Path, sources: Path | None = None) -> list[tuple[str, str, str]]: |
| 113 | + health = inspect(target, sources=sources) |
| 114 | + checks: list[tuple[str, str, str]] = [] |
| 115 | + if health.failures: |
| 116 | + for failure in health.failures: |
| 117 | + checks.append((FAIL, "handoff_sources", failure)) |
| 118 | + elif health.sources_loaded: |
| 119 | + checks.append((OK, "handoff_sources", str(health.sources_path))) |
| 120 | + else: |
| 121 | + pending_total = sum(inbox.pending for inbox in health.inboxes) |
| 122 | + level = WARN if pending_total else OK |
| 123 | + checks.append((level, "handoff_sources", "not configured; no pending handoffs" if not pending_total else "not configured")) |
| 124 | + |
| 125 | + for inbox in health.inboxes: |
| 126 | + if inbox.pending and not inbox.watched: |
| 127 | + level = WARN |
| 128 | + elif not inbox.exists: |
| 129 | + level = OK |
| 130 | + else: |
| 131 | + level = OK |
| 132 | + watched = "yes" if inbox.watched else "no" |
| 133 | + exists = "yes" if inbox.exists else "no" |
| 134 | + detail = ( |
| 135 | + f"{inbox.path} " |
| 136 | + f"(exists={exists}, pending={inbox.pending}, processed={inbox.processed}, watched={watched})" |
| 137 | + ) |
| 138 | + checks.append((level, f"handoff_watch: {inbox.inbox}", detail)) |
| 139 | + |
| 140 | + for warning in health.warnings: |
| 141 | + checks.append((WARN, "handoff_warning", warning)) |
| 142 | + return checks |
| 143 | + |
| 144 | + |
| 145 | +def doctor(*, target: Path, sources: Path | None = None, json_output: bool = False) -> int: |
| 146 | + if not target.expanduser().exists(): |
| 147 | + print(f"error: target does not exist: {target}", file=sys.stderr) |
| 148 | + return 2 |
| 149 | + health = inspect(target, sources=sources) |
| 150 | + if json_output: |
| 151 | + print(json.dumps(health.as_dict(), indent=2, sort_keys=True)) |
| 152 | + else: |
| 153 | + print(f"handoff doctor: {health.target}") |
| 154 | + print(f"sources: {health.sources_path if health.sources_path else '(not configured)'}") |
| 155 | + for status, name, detail in doctor_checks(health.target, sources=health.sources_path): |
| 156 | + print(f"[{status}] {name}: {detail}") |
| 157 | + return 1 if health.failures else 0 |
| 158 | + |
| 159 | + |
| 160 | +def _load_sources(target: Path, sources_path: Path) -> tuple[WatchedInbox, ...]: |
| 161 | + try: |
| 162 | + payload = json.loads(sources_path.read_text()) |
| 163 | + except json.JSONDecodeError as exc: |
| 164 | + raise ValueError(f"invalid JSON: {exc}") from exc |
| 165 | + if not isinstance(payload, dict): |
| 166 | + raise ValueError("root must be a JSON object") |
| 167 | + sources = payload.get("sources") |
| 168 | + if not isinstance(sources, list): |
| 169 | + raise ValueError("sources must be a list") |
| 170 | + |
| 171 | + watched: list[WatchedInbox] = [] |
| 172 | + for index, entry in enumerate(sources): |
| 173 | + if isinstance(entry, str): |
| 174 | + root_value = entry |
| 175 | + inbox_values = list(WRITER_INBOXES) |
| 176 | + elif isinstance(entry, dict): |
| 177 | + root_value = entry.get("root", ".") |
| 178 | + inbox_values = entry.get("inboxes", list(WRITER_INBOXES)) |
| 179 | + else: |
| 180 | + raise ValueError(f"sources[{index}] must be an object or string") |
| 181 | + if not isinstance(root_value, str) or not root_value.strip(): |
| 182 | + raise ValueError(f"sources[{index}].root must be a non-empty string") |
| 183 | + if not isinstance(inbox_values, list) or not all(isinstance(item, str) for item in inbox_values): |
| 184 | + raise ValueError(f"sources[{index}].inboxes must be a list of strings") |
| 185 | + root = _resolve_source_root(target, root_value) |
| 186 | + for inbox in inbox_values: |
| 187 | + normalized = _normalize_inbox(inbox) |
| 188 | + if normalized: |
| 189 | + watched.append(WatchedInbox(root=root, inbox=normalized)) |
| 190 | + return tuple(watched) |
| 191 | + |
| 192 | + |
| 193 | +def _resolve_source_root(target: Path, value: str) -> Path: |
| 194 | + path = Path(value).expanduser() |
| 195 | + if not path.is_absolute(): |
| 196 | + path = target / path |
| 197 | + return path.resolve() |
| 198 | + |
| 199 | + |
| 200 | +def _normalize_inbox(value: str) -> str: |
| 201 | + normalized = value.strip().replace("\\", "/").strip("/") |
| 202 | + if normalized.startswith("./"): |
| 203 | + normalized = normalized[2:] |
| 204 | + return normalized |
| 205 | + |
| 206 | + |
| 207 | +def _inspect_inbox(target: Path, rel: str, watched: tuple[WatchedInbox, ...]) -> InboxHealth: |
| 208 | + path = target / rel |
| 209 | + return InboxHealth( |
| 210 | + inbox=rel, |
| 211 | + path=path, |
| 212 | + exists=path.is_dir(), |
| 213 | + pending=_count_pending(path), |
| 214 | + processed=_count_processed(path), |
| 215 | + watched=_is_watched(target, rel, watched), |
| 216 | + ) |
| 217 | + |
| 218 | + |
| 219 | +def _count_pending(path: Path) -> int: |
| 220 | + if not path.is_dir(): |
| 221 | + return 0 |
| 222 | + count = 0 |
| 223 | + for candidate in path.glob("*.md"): |
| 224 | + if not candidate.is_file(): |
| 225 | + continue |
| 226 | + if candidate.name.startswith(".") or candidate.name in IGNORED_HANDOFF_NAMES: |
| 227 | + continue |
| 228 | + count += 1 |
| 229 | + return count |
| 230 | + |
| 231 | + |
| 232 | +def _count_processed(path: Path) -> int: |
| 233 | + processed = path / "processed" |
| 234 | + if not processed.is_dir(): |
| 235 | + return 0 |
| 236 | + return len([candidate for candidate in processed.glob("*.md") if candidate.is_file()]) |
| 237 | + |
| 238 | + |
| 239 | +def _is_watched(target: Path, rel: str, watched: tuple[WatchedInbox, ...]) -> bool: |
| 240 | + resolved_target = target.resolve() |
| 241 | + normalized = _normalize_inbox(rel) |
| 242 | + return any(item.root == resolved_target and item.inbox == normalized for item in watched) |
0 commit comments