rh-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
rh/tasks.py ADDED
@@ -0,0 +1,221 @@
1
+ """Task board — openspec-inspired but single-file (.rh/tasks.json).
2
+
3
+ Avoids spec bloat: one JSON file, phases + steps + subtasks, states
4
+ idle | working | complete. PLAN.md steps are mirrored here so `rh tasks`
5
+ and `rh status` have a machine-readable source.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ import uuid
12
+ from datetime import datetime, timezone
13
+ from pathlib import Path
14
+
15
+ from . import paths
16
+
17
+ TASK_STATES = ("idle", "working", "complete")
18
+ PHASES = [
19
+ (0, "CONFIG"),
20
+ (1, "INTAKE"),
21
+ (2, "ENVIRONMENT"),
22
+ (3, "LITERATURE"),
23
+ (4, "PLAN"),
24
+ (5, "STATE"),
25
+ (6, "IMPLEMENT"),
26
+ (7, "CRITIQUE"),
27
+ (8, "MANUSCRIPT"),
28
+ (9, "CLOSE"),
29
+ ]
30
+
31
+
32
+ def now_iso() -> str:
33
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
34
+
35
+
36
+ def phase_name(phase: int) -> str:
37
+ name = dict(PHASES).get(phase, "?")
38
+ return f"{phase} {name}"
39
+
40
+
41
+ class TaskStore:
42
+ def __init__(self, root: Path):
43
+ self.root = root
44
+ self.file = paths.tasks_json(root)
45
+
46
+ def load(self) -> dict:
47
+ if not self.file.exists():
48
+ return {"version": 1, "project_slug": "", "current_phase": 0, "tasks": []}
49
+ try:
50
+ data = json.loads(self.file.read_text(encoding="utf-8"))
51
+ except json.JSONDecodeError:
52
+ return {"version": 1, "project_slug": "", "current_phase": 0, "tasks": []}
53
+ data.setdefault("tasks", [])
54
+ data.setdefault("current_phase", 0)
55
+ return data
56
+
57
+ def save(self, data: dict) -> None:
58
+ self.file.parent.mkdir(parents=True, exist_ok=True)
59
+ self.file.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n")
60
+
61
+ # -- CRUD -----------------------------------------------------------------
62
+ def add(
63
+ self,
64
+ title: str,
65
+ *,
66
+ task_id: str | None = None,
67
+ phase: int = 6,
68
+ owner: str = "researcher",
69
+ state: str = "idle",
70
+ deliverable: str = "",
71
+ verify: str = "",
72
+ depends_on: list[str] | None = None,
73
+ risk: str = "",
74
+ kind: str = "build",
75
+ timebox: str = "",
76
+ subtasks: list[str] | None = None,
77
+ ) -> dict:
78
+ data = self.load()
79
+ task_id = task_id or f"T-{uuid.uuid4().hex[:6]}"
80
+ if any(t["id"] == task_id for t in data["tasks"]):
81
+ raise ValueError(f"task {task_id} already exists")
82
+ if state not in TASK_STATES:
83
+ raise ValueError(f"state must be one of {TASK_STATES}")
84
+ task = {
85
+ "id": task_id,
86
+ "title": title,
87
+ "phase": phase,
88
+ "phase_name": phase_name(phase),
89
+ "owner": owner,
90
+ "state": state,
91
+ "deliverable": deliverable,
92
+ "verify": verify,
93
+ "depends_on": depends_on or [],
94
+ "risk": risk,
95
+ "kind": kind,
96
+ "timebox": timebox,
97
+ "subtasks": [
98
+ {"id": f"{task_id}.{i+1}", "title": s, "state": "idle"}
99
+ for i, s in enumerate(subtasks or [])
100
+ ],
101
+ "created_at": now_iso(),
102
+ "updated_at": now_iso(),
103
+ }
104
+ data["tasks"].append(task)
105
+ self.save(data)
106
+ return task
107
+
108
+ def get(self, task_id: str) -> dict | None:
109
+ for t in self.load()["tasks"]:
110
+ if t["id"] == task_id:
111
+ return t
112
+ for st in t.get("subtasks", []):
113
+ if st["id"] == task_id:
114
+ return {**st, "parent": t["id"], "subtask": True}
115
+ return None
116
+
117
+ def set_state(self, task_id: str, state: str) -> dict:
118
+ if state not in TASK_STATES:
119
+ raise ValueError(f"state must be one of {TASK_STATES}, got {state!r}")
120
+ data = self.load()
121
+ for t in data["tasks"]:
122
+ if t["id"] == task_id:
123
+ t["state"] = state
124
+ t["updated_at"] = now_iso()
125
+ self.save(data)
126
+ return t
127
+ for st in t.get("subtasks", []):
128
+ if st["id"] == task_id:
129
+ st["state"] = state
130
+ self.save(data)
131
+ return st
132
+ raise KeyError(f"no task {task_id}")
133
+
134
+ def list(self, *, phase: int | None = None, state: str | None = None) -> list[dict]:
135
+ data = self.load()
136
+ out = data["tasks"]
137
+ if phase is not None:
138
+ out = [t for t in out if t["phase"] == phase]
139
+ if state:
140
+ out = [t for t in out if t["state"] == state]
141
+ return out
142
+
143
+ def set_phase(self, phase: int) -> None:
144
+ data = self.load()
145
+ data["current_phase"] = phase
146
+ self.save(data)
147
+
148
+ def current_phase(self) -> int:
149
+ return int(self.load().get("current_phase", 0))
150
+
151
+ def summary(self) -> dict:
152
+ data = self.load()
153
+ tasks = data["tasks"]
154
+ total = len(tasks)
155
+ complete = sum(1 for t in tasks if t["state"] == "complete")
156
+ working = sum(1 for t in tasks if t["state"] == "working")
157
+ subtasks_total = sum(len(t.get("subtasks", [])) for t in tasks)
158
+ subtasks_complete = sum(
159
+ 1 for t in tasks for s in t.get("subtasks", []) if s["state"] == "complete"
160
+ )
161
+ return {
162
+ "total": total,
163
+ "complete": complete,
164
+ "working": working,
165
+ "idle": total - complete - working,
166
+ "subtasks_total": subtasks_total,
167
+ "subtasks_complete": subtasks_complete,
168
+ "current_phase": int(data.get("current_phase", 0)),
169
+ "pct": round(100 * complete / total) if total else 0,
170
+ }
171
+
172
+
173
+ # --- PLAN.md <-> tasks import -------------------------------------------------
174
+
175
+ PLAN_STEP = re.compile(r"^###\s+(S\d+|T-\S+)\s*[—\-]\s*(.+)$", re.MULTILINE)
176
+
177
+
178
+ def import_plan_md(root: Path, dry_run: bool = False) -> list[dict]:
179
+ """Parse PLAN.md steps (SKILL.md §8 template) into tasks."""
180
+ plan = paths.artifact_path(root, "PLAN.md")
181
+ if not plan.exists():
182
+ return []
183
+ text = plan.read_text(encoding="utf-8")
184
+ store = TaskStore(root)
185
+ existing = {t["id"] for t in store.load()["tasks"]}
186
+ added = []
187
+ for m in PLAN_STEP.finditer(text):
188
+ step_id, title = m.group(1), m.group(2).strip()
189
+ if step_id in existing:
190
+ continue
191
+ owner, deliverable, verify, kind, timebox = "researcher", "", "", "build", ""
192
+ owner_m = re.search(rf"###\s+{re.escape(step_id)}.*?owner:\s*(\w+)", text, re.DOTALL)
193
+ if owner_m:
194
+ owner = owner_m.group(1)
195
+ del_m = re.search(rf"###\s+{re.escape(step_id)}.*?deliverable:\s*(.+)", text)
196
+ if del_m:
197
+ deliverable = del_m.group(1).strip()
198
+ ver_m = re.search(rf"###\s+{re.escape(step_id)}.*?verify:\s*`([^`]+)`", text)
199
+ if ver_m:
200
+ verify = ver_m.group(1)
201
+ kind_m = re.search(rf"###\s+{re.escape(step_id)}.*?\|\s*(build|spike)", text)
202
+ if kind_m:
203
+ kind = kind_m.group(1)
204
+ tb_m = re.search(rf"###\s+{re.escape(step_id)}.*?timebox:\s*(\S+)", text)
205
+ if tb_m:
206
+ timebox = tb_m.group(1)
207
+ if dry_run:
208
+ added.append({"id": step_id, "title": title, "owner": owner})
209
+ else:
210
+ added.append(
211
+ store.add(
212
+ title,
213
+ task_id=step_id,
214
+ owner=owner,
215
+ deliverable=deliverable,
216
+ verify=verify,
217
+ kind=kind,
218
+ timebox=timebox,
219
+ )
220
+ )
221
+ return added
rh/ui.py ADDED
@@ -0,0 +1,128 @@
1
+ """Terminal UI on top of `rich` — tables, progress bars, banners, phase rail.
2
+
3
+ rich is a hard dependency (see pyproject). Its Console runs with `markup=False`
4
+ so user data (titles, paths, prompts) is never parsed as markup; inline colour
5
+ stays plain ANSI and is dropped automatically when stdout is not a TTY.
6
+ Use --json on any command for machine-readable output.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import sys
12
+
13
+ from rich import box
14
+ from rich.console import Console
15
+ from rich.rule import Rule
16
+ from rich.table import Table as RichTable
17
+ from rich.text import Text
18
+
19
+ # --- ANSI (inline text only) --------------------------------------------------
20
+ RESET = "\033[0m"
21
+ BOLD = "\033[1m"
22
+ DIM = "\033[2m"
23
+ GREEN = "\033[32m"
24
+ CYAN = "\033[36m"
25
+ YELLOW = "\033[33m"
26
+ RED = "\033[31m"
27
+ MAGENTA = "\033[35m"
28
+ BLUE = "\033[34m"
29
+
30
+ _TTY = sys.stdout.isatty()
31
+
32
+
33
+ def colorize(text: str, color: str) -> str:
34
+ if not _TTY:
35
+ return text
36
+ return f"{color}{text}{RESET}"
37
+
38
+
39
+ def _render(renderable, *, width: int | None = None) -> str:
40
+ """Render a rich object to a string so it composes inside f-strings."""
41
+ console = Console(force_terminal=_TTY, no_color=not _TTY, highlight=False,
42
+ emoji=False, markup=False, width=width)
43
+ with console.capture() as cap:
44
+ console.print(renderable)
45
+ return cap.get().rstrip("\n")
46
+
47
+
48
+ def bar(pct: int, width: int = 20) -> str:
49
+ # distinct glyphs so the bar still reads when piped (rich's ProgressBar
50
+ # relies on colour alone and drops its empty track without a colour system)
51
+ pct = max(0, min(100, int(pct)))
52
+ filled = width * pct // 100
53
+ t = Text()
54
+ t.append("█" * filled, style="cyan")
55
+ t.append("░" * (width - filled), style="dim")
56
+ return f"{_render(t)} {pct}%"
57
+
58
+
59
+ def table(headers: list[str], rows: list[list[str]]) -> str:
60
+ rt = RichTable(
61
+ box=box.SIMPLE_HEAVY, # thick rule under the header only
62
+ header_style="bold cyan",
63
+ pad_edge=False,
64
+ padding=(0, 1),
65
+ show_header=True,
66
+ show_edge=False,
67
+ )
68
+ for h in headers:
69
+ rt.add_column(h, overflow="fold")
70
+ for row in rows:
71
+ rt.add_row(*[str(c) for c in row])
72
+ # piped output has no terminal width to fold against: render wide instead
73
+ return _render(rt, width=None if _TTY else 160)
74
+
75
+
76
+ def state_color(state: str) -> str:
77
+ return {"complete": GREEN, "working": CYAN, "idle": DIM}.get(state, "")
78
+
79
+
80
+ def state_label(state: str) -> str:
81
+ dot = {"complete": "●", "working": "◐", "idle": "○"}.get(state, "?")
82
+ return colorize(f"{dot} {state}", state_color(state))
83
+
84
+
85
+ def phase_rail(current: int, *, done: list[bool] | None = None) -> str:
86
+ """Rail where ✓ means *verified by an artifact/gate*, never just position.
87
+
88
+ done[i] is computed by config.phase_gate(). Phases claimed past but unmet
89
+ render as `⚠x` in yellow, so a jumped-to phase can never look earned.
90
+ """
91
+ names = ["C", "I", "E", "L", "P", "S", "M", "K", "W", "✕"]
92
+ rail = Text()
93
+ for i, label in enumerate(names):
94
+ if i:
95
+ rail.append(" → ", style="dim")
96
+ if done is not None:
97
+ if done[i] and i != current:
98
+ rail.append(f"✓{label}", style="green")
99
+ elif i == current:
100
+ rail.append(f"[{label}]", style="bold cyan")
101
+ elif i < current:
102
+ rail.append(f"⚠{label}", style="yellow")
103
+ else:
104
+ rail.append(label, style="dim")
105
+ else:
106
+ # no gate data: never fake ✓ — show position only
107
+ if i == current:
108
+ rail.append(f"[{label}]", style="bold cyan")
109
+ elif i < current:
110
+ rail.append(f"?{label}", style="yellow")
111
+ else:
112
+ rail.append(label, style="dim")
113
+ legend = ("0 CONFIG → 1 INTAKE → 2 ENVIRONMENT → 3 LITERATURE → 4 PLAN → "
114
+ "5 STATE → 6 IMPLEMENT → 7 CRITIQUE → 8 MANUSCRIPT → 9 CLOSE")
115
+ head = Text("FLOW", style="bold")
116
+ # legend stays a plain line: rich would wrap it on narrow terminals
117
+ return f"{_render(head)}\n{_render(rail)}\n{colorize(legend, DIM)}"
118
+
119
+
120
+ def banner(title: str, subtitle: str = "") -> str:
121
+ out = [_render(Rule(Text(title, style="bold"), align="left", style="grey37"))]
122
+ if subtitle:
123
+ out.append(colorize(subtitle, DIM))
124
+ return "\n".join(out)
125
+
126
+
127
+ def json_out(obj) -> None:
128
+ print(json.dumps(obj, indent=2))
rh/workflow.py ADDED
@@ -0,0 +1,268 @@
1
+ """Workflow diagram — mermaid source + CLI rendering.
2
+
3
+ Uses `mmdr` / `beautiful-mermaid` when installed; otherwise renders an
4
+ ASCII rail and tells the user how to get diagrams. Shows current phase.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import shutil
9
+ import subprocess
10
+ from pathlib import Path
11
+
12
+ from . import ui
13
+
14
+ FLIP = {0: "CONFIG", 1: "INTAKE", 2: "ENVIRONMENT", 3: "LITERATURE", 4: "PLAN",
15
+ 5: "STATE", 6: "IMPLEMENT", 7: "CRITIQUE", 8: "MANUSCRIPT", 9: "CLOSE"}
16
+
17
+ MERMAID_TEMPLATE = """%%{init: {'theme': 'dark', 'background': 'transparent'}}%%
18
+ flowchart LR
19
+ C["0 CONFIG<br/>ENV.md"]:::done
20
+ I["1 INTAKE<br/>PROBLEM.md"]:::done
21
+ E["2 ENVIRONMENT<br/>ENV.md tools"]:::done
22
+ L["3 LITERATURE<br/>papers/ GAPS.md"]:::done
23
+ P["4 PLAN<br/>PLAN.md"]:::done
24
+ S["5 STATE<br/>STATUS.md"]:::done
25
+ M["6 IMPLEMENT<br/>src/ results/"]:::done
26
+ K["7 CRITIQUE"]:::done
27
+ W["8 MANUSCRIPT"]:::done
28
+ X["9 CLOSE"]:::done
29
+ C --> I --> E --> L --> P --> S --> M --> K --> W --> X
30
+ K -. "blocking → replan" .-> P
31
+ K -. "fix" .-> M
32
+ classDef done fill:#151923,stroke:#3b82f6,color:#e5e7eb;
33
+ classDef current fill:#1d4ed8,stroke:#93c5fd,color:#fff,stroke-width:3px;
34
+ classDef todo fill:#0b0f17,stroke:#374151,color:#6b7280;
35
+ """
36
+
37
+
38
+ def mermaid_for_phase(current: int, done: list[bool] | None = None, direction: str = "LR") -> str:
39
+ lines = []
40
+ for i in (0, 1, 2, 3, 4, 5, 6, 7, 8, 9):
41
+ if i < current:
42
+ cls = "done"
43
+ elif i == current:
44
+ cls = "current"
45
+ else:
46
+ cls = "todo"
47
+ lines.append(cls)
48
+ # build graph: first mark all todo, then override
49
+ src = MERMAID_TEMPLATE
50
+ if direction != "LR":
51
+ src = src.replace("flowchart LR", f"flowchart {direction}")
52
+ # re-apply per-phase mapping by line surgery
53
+ node_ids = ["C", "I", "E", "L", "P", "S", "M", "K", "W", "X"]
54
+ import re
55
+ out_lines = []
56
+ for line in src.splitlines():
57
+ if line.strip().startswith(("C[", "I[", "E[", "L[", "P[", "S[", "M[", "K[", "W[", "X[")):
58
+ nid = line.strip()[0]
59
+ idx = node_ids.index(nid)
60
+ if done is not None:
61
+ if done[idx] and idx != current:
62
+ cls = "done"
63
+ elif idx == current:
64
+ cls = "current"
65
+ elif idx < current:
66
+ cls = "unmet"
67
+ else:
68
+ cls = "todo"
69
+ else:
70
+ if idx < current:
71
+ cls = "done"
72
+ elif idx == current:
73
+ cls = "current"
74
+ else:
75
+ cls = "todo"
76
+ line = re.sub(r":::\w+", f":::{cls}", line)
77
+ out_lines.append(line)
78
+ if done is not None and any(i < current and not done[i] for i in range(10)):
79
+ out_lines.append(" classDef unmet fill:#3b2f10,stroke:#f59e0b,color:#fbbf24,stroke-dasharray: 5 5;")
80
+ return "\n".join(out_lines) + "\n"
81
+
82
+
83
+ def render_flow(current: int, done: list[bool] | None = None) -> str:
84
+ """ASCII flow diagram. ✓/☑ only from verified gate state, never position."""
85
+ nodes = []
86
+ for i in range(10):
87
+ label = f"{i} {FLIP[i]}"
88
+ if done is not None:
89
+ if done[i] and i != current:
90
+ nodes.append(ui.colorize(f"☑ {label}", ui.GREEN))
91
+ elif i == current:
92
+ nodes.append(ui.colorize(f"▶ {label}", ui.BOLD))
93
+ elif i < current:
94
+ nodes.append(ui.colorize(f"⚠ {label}", ui.YELLOW))
95
+ else:
96
+ nodes.append(ui.colorize(f"○ {label}", ui.DIM))
97
+ else:
98
+ if i == current:
99
+ nodes.append(ui.colorize(f"▶ {label}", ui.BOLD))
100
+ elif i < current:
101
+ nodes.append(ui.colorize(f"? {label}", ui.YELLOW))
102
+ else:
103
+ nodes.append(ui.colorize(f"○ {label}", ui.DIM))
104
+ lines = [
105
+ " " + " ".join(nodes[0:5]),
106
+ " " + " ↓".join([""] * 2),
107
+ " " + " ".join(nodes[5:10]),
108
+ ui.colorize(" replan: CRITIQUE → PLAN (4) / IMPLEMENT (6)", ui.DIM),
109
+ ui.colorize(" gates: user_approves_plan (4) · critique_veto (7)", ui.DIM),
110
+ ]
111
+ return "\n".join(lines)
112
+
113
+
114
+ def diagram_tools() -> list[str]:
115
+ return [t for t in ("mmdr", "beautiful-mermaid") if shutil.which(t)]
116
+
117
+
118
+ # ASCII-native mermaid renderers, best first. Each entry: binary -> argv prefix.
119
+ # All read a .mmd file (or stdin) and print box-drawing/ASCII art.
120
+ # ONLY binaries already installed on the machine are used — the CLI never
121
+ # downloads or installs anything (npx -y would silently fetch packages;
122
+ # that's the user's choice, offered as an install option below, not ours).
123
+ ASCII_TOOLS: dict[str, list[str]] = {
124
+ "bm": ["bm", "ascii", None, "--padding-y", "0"],
125
+ "mermaid-ascii": ["mermaid-ascii", "-f", None, "-y", "2"], # AlexanderGrooff/mermaid-ascii (Go)
126
+ "mermansi": ["mermansi", "--file", None, "--concise"],
127
+ "mermaid2term": ["mermaid2term", None],
128
+ "merx": ["merx", "render", None, "--ascii"],
129
+ "ma": ["ma", None],
130
+ }
131
+
132
+ # Options the CLI merely *suggests* when no renderer is installed — the user
133
+ # decides which to run, if any. The npx variants change nothing globally:
134
+ # they download to the npm cache on first run. Never executed automatically.
135
+ ASCII_TOOL_INSTALL = {
136
+ "bm": "npm i -g beautiful-mermaid-cli",
137
+ "mermaid-ascii": "go install github.com/AlexanderGrooff/mermaid-ascii@latest (or releases page)",
138
+ "mermansi": "cargo install mermansi",
139
+ "mermaid2term": "npm i -g mermaid2term",
140
+ "merx": "npm i -g @wuwe1/merx",
141
+ "ma": "cargo install --git https://github.com/Sixeight/ma",
142
+ }
143
+ ASCII_NO_INSTALL = {
144
+ "bm": "npx -y beautiful-mermaid-cli ascii workflow.mmd # no global install; downloads to the npm cache",
145
+ "mermaid2term": "npx -y mermaid2term workflow.mmd # no global install; downloads to the npm cache",
146
+ }
147
+
148
+
149
+ def ascii_tools() -> list[str]:
150
+ found = []
151
+ for t, argv in ASCII_TOOLS.items():
152
+ if shutil.which(argv[0]):
153
+ found.append(t)
154
+ return found
155
+
156
+
157
+ def mermaid_for_tasks(tasks: list[dict], *, direction: str = "TD") -> str:
158
+ """Mermaid DAG of the PROJECT's plan steps (Orchestrator/Researcher's PLAN.md).
159
+
160
+ Nodes = board tasks, edges = depends_on. State classes: complete/working/
161
+ idle. Dependencies that are not on the board are skipped (noted in output
162
+ by the caller). The SKILL.md phase pipeline is constant — this is the
163
+ per-project workflow.
164
+ """
165
+ ids = {t["id"] for t in tasks}
166
+ lines = [f"flowchart {direction}", "%%{init: {'theme': 'dark'}}%%" if False else ""]
167
+ lines = [f"flowchart {direction}"]
168
+ for t in tasks:
169
+ cls = {"complete": "done", "working": "working", "idle": "todo"}.get(t["state"], "todo")
170
+ label = (t.get("title") or t["id"]).replace('"', "'").replace("\n", " ")
171
+ extra = []
172
+ if t.get("deliverable"):
173
+ extra.append(t["deliverable"])
174
+ if t.get("kind") == "spike":
175
+ extra.append("spike")
176
+ text = f"{t['id']} {label}" + (f"<br/>{extra[0]}" if extra else "")
177
+ lines.append(f' {t["id"]}["{text}"]:::{cls}')
178
+ for t in tasks:
179
+ for dep in t.get("depends_on", []):
180
+ if dep in ids:
181
+ lines.append(f' {dep} --> {t["id"]}')
182
+ lines += [
183
+ " classDef done fill:#14532d,stroke:#22c55e,color:#dcfce7;",
184
+ " classDef working fill:#1d4ed8,stroke:#93c5fd,color:#fff,stroke-width:3px;",
185
+ " classDef todo fill:#0b0f17,stroke:#374151,color:#6b7280;",
186
+ ]
187
+ return "\n".join(lines) + "\n"
188
+
189
+
190
+ def render_ascii(root: Path, mermaid_src: str) -> tuple[str | None, str | None]:
191
+ """Render mermaid source as terminal art via the best installed tool.
192
+
193
+ Returns (art, tool). art is None when no tool works. The transient .mmd
194
+ lives in .rh/tmp/; the caller owns any saved artifact.
195
+ """
196
+ tools = ascii_tools()
197
+ if not tools:
198
+ return None, None
199
+ from . import paths
200
+ tmp = paths.rh_dir(root) / "tmp" / "workflow-ascii.mmd"
201
+ tmp.parent.mkdir(parents=True, exist_ok=True)
202
+ tmp.write_text(mermaid_src, encoding="utf-8")
203
+ for tool in tools:
204
+ argv = [str(tmp) if part is None else part for part in ASCII_TOOLS[tool]]
205
+ try:
206
+ proc = subprocess.run(argv, capture_output=True, text=True, timeout=30)
207
+ except (subprocess.TimeoutExpired, OSError):
208
+ continue
209
+ if proc.returncode == 0 and proc.stdout.strip():
210
+ return proc.stdout.rstrip(), tool
211
+ return None, tools[0]
212
+
213
+
214
+ def render_via(tool: str, mermaid: str) -> str | None:
215
+ try:
216
+ proc = subprocess.run([tool], input=mermaid, capture_output=True, text=True, timeout=10)
217
+ return proc.stdout if proc.returncode == 0 else None
218
+ except (subprocess.TimeoutExpired, OSError):
219
+ return None
220
+
221
+
222
+ def write_mermaid(root: Path, current: int, done: list[bool] | None = None,
223
+ direction: str = "LR", name: str = "workflow.mmd") -> Path:
224
+ from . import paths
225
+ out = paths.rh_dir(root) / name
226
+ out.parent.mkdir(parents=True, exist_ok=True)
227
+ out.write_text(mermaid_for_phase(current, done, direction), encoding="utf-8")
228
+ return out
229
+
230
+
231
+ def render_image(root: Path, mermaid_src: str, *, fmt: str = "svg",
232
+ out_name: str = "workflow") -> tuple[Path | None, str]:
233
+ """Render mermaid source to an svg/png artifact with mmdr (file->file).
234
+
235
+ The transient .mmd goes to .rh/tmp/ — the CLI NEVER writes
236
+ .rh/workflow.mmd, that file belongs to the agent alone.
237
+ Returns (image_path, message).
238
+ """
239
+ from . import paths
240
+ tools = diagram_tools()
241
+ if not tools:
242
+ return None, "no renderer installed (mmdr / beautiful-mermaid)"
243
+ rh = paths.rh_dir(root)
244
+ mmd = rh / "tmp" / f"{out_name}.mmd"
245
+ mmd.parent.mkdir(parents=True, exist_ok=True)
246
+ mmd.write_text(mermaid_src, encoding="utf-8")
247
+ out = rh / f"{out_name}.{fmt}"
248
+ tool = tools[0]
249
+ try:
250
+ if tool == "mmdr":
251
+ proc = subprocess.run(
252
+ ["mmdr", "-i", str(mmd), "-o", str(out), "-e", fmt, "-t", "dark"],
253
+ capture_output=True, text=True, timeout=30,
254
+ )
255
+ else: # beautiful-mermaid: pipe source in, binary out
256
+ proc = subprocess.run(
257
+ [tool, "-e", fmt] if fmt != "svg" else [tool],
258
+ input=mermaid_src, capture_output=True, timeout=30,
259
+ )
260
+ if proc.returncode == 0:
261
+ out.write_bytes(proc.stdout if isinstance(proc.stdout, bytes) else proc.stdout.encode())
262
+ if proc.returncode != 0:
263
+ return None, f"{tool} failed: {(proc.stderr or proc.stdout or '')[:200]}".strip()
264
+ if not out.exists() or out.stat().st_size == 0:
265
+ return None, f"{tool} produced no output"
266
+ return out, f"rendered with {tool}"
267
+ except (subprocess.TimeoutExpired, OSError) as e:
268
+ return None, f"{tool} error: {e}"