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/cli.py ADDED
@@ -0,0 +1,799 @@
1
+ """`rh` entry point.
2
+
3
+ Commands:
4
+ rh init [--root DIR] [--slug NAME] [--clean]
5
+ rh env show | rh env set KEY=VALUE ... | rh env list
6
+ rh add {note|literature|layout|gaps|problem|plan|status|manuscript} <heading|DOI> [-m BODY] [--file NAME]
7
+ rh add log --role ROLE --title TITLE [-m BODY]
8
+ rh add task TITLE [--id ID] [--phase N] [--owner ROLE] [--state S] [--verify CMD] [--deliverable FILE] [--subtask TEXT ...]
9
+ rh search <query> [--max N]
10
+ rh task set <id> {idle|working|complete}
11
+ rh task list [--phase N] [--state S]
12
+ rh tasks [--phase N]
13
+ rh status [--json]
14
+ rh workflow [--mermaid] [--write]
15
+ rh phase <0-9>
16
+ rh plan import [--dry-run]
17
+ rh skill install [--dest DIR] [--force]
18
+ rh describe # AI-friendly map: phases, layout, env schema (decisions you must surface)
19
+
20
+ Global flags: --root DIR, --json (machine-readable).
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import json
26
+ import sys
27
+ from pathlib import Path
28
+
29
+ from . import __version__, add as add_mod, config, paths, resume as resume_mod, search as search_mod, tasks as tasks_mod, ui, workflow
30
+
31
+
32
+ def with_root(fn):
33
+ def wrapper(args):
34
+ root = paths.resolve_root(getattr(args, "root", None))
35
+ return fn(args, root)
36
+ wrapper.__name__ = fn.__name__
37
+ return wrapper
38
+
39
+
40
+ @with_root
41
+ def cmd_init(args, root: Path):
42
+ if args.clean and root.exists():
43
+ import shutil
44
+ shutil.rmtree(root / ".rh", ignore_errors=True)
45
+ d = paths.ensure_layout(root)
46
+ tasks_mod.TaskStore(root).load() # ensure tasks.json shape exists lazily
47
+ if args.slug:
48
+ env = config.load_env(root)
49
+ env["project"]["slug"] = args.slug
50
+ config.save_env(root, env)
51
+ (d / ".gitkeep").write_text("") if not (d / ".gitkeep").exists() else None
52
+ if getattr(args, "json", False):
53
+ ui.json_out({"root": str(root), "rh_dir": str(d), "initialized": True})
54
+ return 0
55
+ print(ui.banner("rh init", f"{root}"))
56
+ print(f" {ui.colorize('✓', ui.GREEN)} created {d}/")
57
+ for sub in ("logs/", "papers/", "notes/", "tasks/"):
58
+ print(f" {ui.colorize('✓', ui.GREEN)} .rh/{sub}")
59
+ print(f" {ui.colorize('✓', ui.GREEN)} src/ results/ papers/ at root")
60
+ print()
61
+ print(f"Next: {ui.colorize('rh env set project.slug=<name>', ui.CYAN)} "
62
+ f"· {ui.colorize('rh env show', ui.CYAN)}")
63
+ return 0
64
+
65
+
66
+ def _env_value(value) -> str:
67
+ """One-line display for a config value (dicts become provider/model)."""
68
+ if isinstance(value, dict):
69
+ if not value:
70
+ return "—"
71
+ if set(value) == {"provider", "model"}:
72
+ return f"{value['provider']}/{value['model']}"
73
+ return json.dumps(value, sort_keys=True)
74
+ if isinstance(value, bool):
75
+ return "true" if value else "false"
76
+ if isinstance(value, list):
77
+ return ", ".join(str(v) for v in value) or "—"
78
+ return str(value) if value not in ("", None) else "—"
79
+
80
+
81
+ def _safe_nested(env: dict, key: str):
82
+ """Config value by dotted key, or None when the stored shape is malformed."""
83
+ try:
84
+ return config.get_nested(env, key)
85
+ except (KeyError, IndexError, ValueError):
86
+ return None
87
+
88
+
89
+ @with_root
90
+ def cmd_env_show(args, root: Path):
91
+ env = config.load_env(root)
92
+ if getattr(args, "json", False):
93
+ ui.json_out(env)
94
+ return 0
95
+ problems = config.validate(env)
96
+ print(ui.banner("ENV — current environment"))
97
+ rows = [[key, _env_value(_safe_nested(env, key))]
98
+ for key, _kind, _choices, _help in config.ENV_SCHEMA]
99
+ print(ui.table(["key", "value"], rows))
100
+ tail = config.load_tail(root)
101
+ if tail.strip():
102
+ print()
103
+ print(ui.colorize("Environment notes (from ENV.md)", ui.DIM))
104
+ print(tail)
105
+ if problems:
106
+ print()
107
+ print(ui.colorize("⚠ config problems:", ui.YELLOW))
108
+ for p in problems:
109
+ print(f" - {p}")
110
+ else:
111
+ print()
112
+ print(ui.colorize("✓ config valid", ui.GREEN))
113
+ return 0
114
+
115
+
116
+ @with_root
117
+ def cmd_env_list(args, root: Path):
118
+ if getattr(args, "json", False):
119
+ for key, kind, choices, help_text in config.ENV_SCHEMA:
120
+ ui.json_out({"key": key, "kind": kind, "choices": list(choices), "help": help_text})
121
+ return 0
122
+ rows = [[key, kind, " ".join(str(c) for c in choices) or "—", help_text]
123
+ for key, kind, choices, help_text in config.ENV_SCHEMA]
124
+ print(ui.table(["key", "kind", "choices", "help"], rows))
125
+ print(f"\n{ui.colorize('Set:', ui.DIM)} rh env set agents.count=2 agents.backend=tmux ...")
126
+ return 0
127
+
128
+
129
+ @with_root
130
+ def cmd_env_set(args, root: Path):
131
+ env = config.load_env(root)
132
+ if not args.pairs:
133
+ # interactive-ish: show what's settable
134
+ print("Usage: rh env set KEY=VALUE [KEY=VALUE ...]")
135
+ print("Keys:")
136
+ for key, kind, choices, _ in config.ENV_SCHEMA:
137
+ print(f" {key} ({kind}{choices})")
138
+ return 2
139
+ for pair in args.pairs:
140
+ if "=" not in pair:
141
+ print(f"⚠ skipping {pair!r}: missing '='", file=sys.stderr)
142
+ continue
143
+ key, raw = pair.split("=", 1)
144
+ key = key.strip()
145
+ spec = next((s for s in config.ENV_SCHEMA if s[0] == key), None)
146
+ if spec is None:
147
+ print(f"⚠ unknown key {key!r} — see `rh env list`", file=sys.stderr)
148
+ continue
149
+ kind = spec[1]
150
+ try:
151
+ value = config.coerce_value(raw, kind)
152
+ except ValueError as e:
153
+ print(f"⚠ {key}: {e}", file=sys.stderr)
154
+ continue
155
+ try:
156
+ config.set_nested(env, key, value)
157
+ except (KeyError, IndexError, ValueError) as e:
158
+ print(f"⚠ {key}: {e}", file=sys.stderr)
159
+ continue
160
+ problems = config.validate(env)
161
+ if problems:
162
+ print(ui.colorize("Config problems (will still write):", ui.YELLOW))
163
+ for p in problems:
164
+ print(f" - {p}")
165
+ print()
166
+ config.save_env(root, env)
167
+ if getattr(args, "json", False):
168
+ ui.json_out(env)
169
+ return 0
170
+ print(ui.colorize("✓ wrote ENV.md + .rh/env.json", ui.GREEN))
171
+ print(json.dumps(env, indent=2))
172
+ return 0
173
+
174
+
175
+ @with_root
176
+ def cmd_add(args, root: Path):
177
+ paths.ensure_layout(root)
178
+ body = args.message or "TODO: fill in"
179
+ if args.target == "note":
180
+ target, result = add_mod.add_note(root, args.heading, body, file=args.file)
181
+ elif args.target == "log":
182
+ if not args.role or not args.title:
183
+ print("rh add log requires --role and --title", file=sys.stderr)
184
+ return 2
185
+ target = add_mod.add_log(root, args.role, args.title, body)
186
+ result = "created"
187
+ elif args.target == "task":
188
+ store = tasks_mod.TaskStore(root)
189
+ phase = args.phase if args.phase is not None else store.current_phase()
190
+ deps = [d.strip() for d in (args.depends_on or "").split(",") if d.strip()]
191
+ task = store.add(
192
+ args.heading, task_id=args.id, phase=phase, owner=args.owner,
193
+ state=args.state, deliverable=args.deliverable, verify=args.verify,
194
+ depends_on=deps, kind=args.kind,
195
+ )
196
+ print(ui.colorize(f"✓ task {task['id']} ({task['state']}, {tasks_mod.phase_name(phase)})", ui.GREEN))
197
+ return 0
198
+ else:
199
+ target, result = add_mod.add_text(root, args.target, args.heading, body)
200
+ if getattr(args, "json", False):
201
+ ui.json_out({"target": str(target), "result": result})
202
+ return 0
203
+ print(ui.colorize(f"✓ {result} {target}", ui.GREEN))
204
+ return 0
205
+
206
+
207
+ @with_root
208
+ def cmd_search(args, root: Path):
209
+ hits, engine = search_mod.search(root, args.query, max_hits=args.max)
210
+ if getattr(args, "json", False):
211
+ ui.json_out([{"path": str(h.path.relative_to(root)) if h.path.is_relative_to(root) else str(h.path), "line": h.line_no, "text": h.line.strip()} for h in hits])
212
+ return 0
213
+ print(ui.banner(f"Search: {args.query}", f"engine: {engine} · {len(hits)} hits · root: {root}"))
214
+ if not hits:
215
+ print(ui.colorize("No matches. Try `rh search <different term>` or check .rh/ exists.", ui.YELLOW))
216
+ for h in hits:
217
+ print(h.render(root))
218
+ print()
219
+ return 0
220
+
221
+
222
+ @with_root
223
+ def cmd_task_set(args, root: Path):
224
+ store = tasks_mod.TaskStore(root)
225
+ try:
226
+ task = store.set_state(args.id, args.state)
227
+ except (KeyError, ValueError) as e:
228
+ print(f"✗ {e}", file=sys.stderr)
229
+ return 1
230
+ if getattr(args, "json", False):
231
+ ui.json_out(task)
232
+ return 0
233
+ print(f"{ui.state_label(args.state)} {task['id']} — {task.get('title', args.id)}")
234
+ return 0
235
+
236
+
237
+ @with_root
238
+ def cmd_task_list(args, root: Path):
239
+ store = tasks_mod.TaskStore(root)
240
+ tasks = store.list(phase=args.phase, state=args.state)
241
+ if getattr(args, "json", False):
242
+ ui.json_out(tasks)
243
+ return 0
244
+ if not tasks:
245
+ print(ui.colorize("No tasks. `rh plan import` (from PLAN.md) or `rh add task \"...\"`.", ui.DIM))
246
+ return 0
247
+ rows = []
248
+ for t in tasks:
249
+ rows.append([
250
+ t["id"], ui.state_label(t["state"]), tasks_mod.phase_name(t["phase"]),
251
+ t["owner"], (t["title"] or "")[:44], (t.get("deliverable") or "")[:24],
252
+ ])
253
+ print(ui.table(["id", "state", "phase", "owner", "title", "deliverable"], rows))
254
+ return 0
255
+
256
+
257
+ def group_tasks(tasks):
258
+ """openspec-style grouping: Draft (no tasks) / Active / Complete."""
259
+ draft = [t for t in tasks if t["state"] == "idle" and not any(s["state"] != "idle" for s in t.get("subtasks", []))]
260
+ active = [t for t in tasks if t["state"] == "working"]
261
+ complete = [t for t in tasks if t["state"] == "complete"]
262
+ remaining = [t for t in tasks if t not in draft and t not in active and t not in complete]
263
+ return {"draft": draft, "active": active, "complete": complete, "remaining": remaining}
264
+
265
+
266
+ @with_root
267
+ def cmd_tasks(args, root: Path):
268
+ store = tasks_mod.TaskStore(root)
269
+ env = config.load_env(root)
270
+ current = store.current_phase()
271
+ summary = store.summary()
272
+ tasks = store.list(phase=args.phase)
273
+ groups = group_tasks(tasks)
274
+ # phase gate (SKILL.md §3): warnings when the pipeline is skipped
275
+ gate = config.phase_gate(root, env)
276
+ if getattr(args, "json", False):
277
+ ui.json_out({
278
+ "summary": summary,
279
+ "tasks": tasks,
280
+ "groups": {k: [t["id"] for t in v] for k, v in groups.items()},
281
+ "gate": gate,
282
+ })
283
+ return 0
284
+ print(ui.banner("Tasks"))
285
+ print(f"{ui.bar(summary['pct'])} {summary['complete']}/{summary['total']} complete · "
286
+ f"{summary['working']} working · {summary['idle']} idle")
287
+ if summary["subtasks_total"]:
288
+ sc = summary["subtasks_complete"]
289
+ st = summary["subtasks_total"]
290
+ print(f"{ui.colorize('Subtasks:', ui.DIM)} {sc}/{st} {ui.bar(round(100*sc/st), width=14)}")
291
+ print(ui.phase_rail(current, done=gate["done"]))
292
+ print()
293
+ if gate["problems"]:
294
+ for p in gate["problems"]:
295
+ print(ui.colorize(f"⚠ {p}", ui.YELLOW))
296
+ print(ui.colorize(" (SKILL.md §3 hard gates: resolve these or ask the user to waive.)", ui.DIM))
297
+ print()
298
+ if not tasks:
299
+ print(ui.colorize("No tasks yet — `rh plan import` or `rh add task \"...\"`.", ui.DIM))
300
+ return 0
301
+ # openspec view style: grouped lanes, one row per task, [x]/[ ] checklist
302
+ for label, items in (("Draft", groups["draft"]), ("Active", groups["active"]),
303
+ ("Complete", groups["complete"]), ("Remaining", groups["remaining"])):
304
+ if not items:
305
+ continue
306
+ print(ui.colorize(f"── {label} ({len(items)}) ──", ui.BOLD))
307
+ for t in items:
308
+ box = "[x]" if t["state"] == "complete" else "[ ]" if t["state"] == "idle" else "[~]"
309
+ box = ui.colorize(box, ui.state_color(t["state"]))
310
+ sub = ""
311
+ if t.get("subtasks"):
312
+ sd = sum(1 for s in t["subtasks"] if s["state"] == "complete")
313
+ stot = len(t["subtasks"])
314
+ sub = f" [{sd}/{stot} subtasks]"
315
+ print(f" {box} {ui.colorize(t['id'], ui.CYAN):8} {t['title']}{sub}")
316
+ print()
317
+ # flat table for scripting detail
318
+ rows = [[t["id"], ui.state_label(t["state"]), tasks_mod.phase_name(t["phase"]), (t["title"] or "")[:42]] for t in tasks]
319
+ print(ui.table(["id", "state", "phase", "title"], rows))
320
+ return 0
321
+
322
+
323
+ @with_root
324
+ def cmd_status(args, root: Path):
325
+ env = config.load_env(root)
326
+ store = tasks_mod.TaskStore(root)
327
+ summary = store.summary()
328
+ gate = config.phase_gate(root, env)
329
+ if getattr(args, "json", False):
330
+ ui.json_out({
331
+ "root": str(root),
332
+ "slug": env.get("project", {}).get("slug", ""),
333
+ "phase": summary["current_phase"],
334
+ "phase_name": tasks_mod.phase_name(summary["current_phase"]),
335
+ "summary": summary,
336
+ "agents": env.get("agents", {}),
337
+ "gate": gate,
338
+ "initialized": (root / ".rh").exists(),
339
+ })
340
+ return 0
341
+ slug = env.get("project", {}).get("slug") or "untitled"
342
+ print(ui.banner(f"{slug} — status", str(root)))
343
+ # openspec status style: header line + progress + artifact checklist
344
+ print(f"Project: {slug} · Phase: {tasks_mod.phase_name(summary['current_phase'])}")
345
+ print(f"Progress: {summary['complete']}/{summary['total']} steps complete {ui.bar(summary['pct'], width=16)}")
346
+ print(f"Changes (task lanes):")
347
+ print(f" [x] Draft (idle) {len([t for t in store.list() if t['state']=='idle'])}")
348
+ print(f" [~] Active (working) {summary['working']}")
349
+ print(f" [x] Complete {summary['complete']}")
350
+ print()
351
+ if gate["problems"]:
352
+ for p in gate["problems"]:
353
+ print(ui.colorize(f"⚠ {p}", ui.YELLOW))
354
+ print(ui.colorize(" (SKILL.md §3 hard gates: resolve these or ask the user to waive.)", ui.DIM))
355
+ print()
356
+ print(ui.phase_rail(summary["current_phase"], done=gate["done"]))
357
+ print()
358
+ print(f"{ui.bar(summary['pct'], width=24)} {summary['complete']}/{summary['total']} steps · "
359
+ f"{summary['working']} working · {summary['idle']} idle")
360
+ print()
361
+ # tasks grouped by phase
362
+ by_phase: dict[int, list[dict]] = {}
363
+ for t in store.list():
364
+ by_phase.setdefault(t["phase"], []).append(t)
365
+ if not by_phase:
366
+ print(ui.colorize("No tasks — `rh plan import` will mirror PLAN.md steps here.", ui.DIM))
367
+ for phase in sorted(by_phase):
368
+ tasks = by_phase[phase]
369
+ done = sum(1 for t in tasks if t["state"] == "complete")
370
+ bar_pct = round(100 * done / len(tasks)) if tasks else 0
371
+ print(f"{ui.colorize(tasks_mod.phase_name(phase), ui.BOLD)} {ui.bar(bar_pct, width=14)} ({done}/{len(tasks)})")
372
+ for t in tasks:
373
+ sub = ""
374
+ if t.get("subtasks"):
375
+ sd = sum(1 for s in t["subtasks"] if s["state"] == "complete")
376
+ sub = f" [{sd}/{len(t['subtasks'])} subtasks]"
377
+ print(f" {ui.state_label(t['state'])} {t['id']} {t['title']}{sub}")
378
+ # agents
379
+ agents = env.get("agents", {})
380
+ print()
381
+ print(ui.colorize(f"agents: count={agents.get('count')} backend={agents.get('backend')}", ui.DIM))
382
+ roles = agents.get("roles", {})
383
+ for role, model in roles.items():
384
+ if model:
385
+ print(f" {ui.colorize(f'{role:14}', ui.DIM)} {model}")
386
+ return 0
387
+
388
+
389
+ @with_root
390
+ def cmd_workflow(args, root: Path):
391
+ """View the PROJECT's workflow diagram — agent-authored, CLI-rendered.
392
+
393
+ The Orchestrator/Researcher authors .rh/workflow.mmd (the PLAN step DAG,
394
+ adapted to the renderers available: `rh workflow --tools` lists them).
395
+ rh only ever *displays* it: ASCII in the terminal when the file exists,
396
+ nothing invented when it doesn't. `--example` prints a starter the agent
397
+ can save; `--phases` uses the constant SKILL.md pipeline as the starter.
398
+ """
399
+ store = tasks_mod.TaskStore(root)
400
+ current = store.current_phase()
401
+ gate = config.phase_gate(root)
402
+ src_file = paths.rh_dir(root) / "workflow.mmd"
403
+
404
+ # --json: machine contract — no UI chrome, only the object
405
+ if getattr(args, "json", False):
406
+ if args.tools:
407
+ ui.json_out({"ascii_tools": workflow.ascii_tools(), "diagram_tools": workflow.diagram_tools()})
408
+ return 0
409
+ if getattr(args, "example", False):
410
+ src = (workflow.mermaid_for_phase(current, done=gate["done"])
411
+ if args.phases else workflow.mermaid_for_tasks(store.list()))
412
+ ui.json_out({"example": src})
413
+ return 0
414
+ if not src_file.exists():
415
+ ui.json_out({"has_workflow": False, "workflow_file": str(src_file),
416
+ "ascii_tools": workflow.ascii_tools(), "diagram_tools": workflow.diagram_tools()})
417
+ return 0
418
+ src = src_file.read_text(encoding="utf-8")
419
+ art, tool = (None, None)
420
+ if not args.no_render:
421
+ art, tool = workflow.render_ascii(root, src)
422
+ rendered = None
423
+ fmt = "png" if args.png else "svg"
424
+ if (args.png or args.svg) and workflow.diagram_tools():
425
+ img, _ = workflow.render_image(root, src, fmt=fmt, out_name="workflow")
426
+ rendered = str(img) if img else None
427
+ ui.json_out({
428
+ "has_workflow": True, "workflow_file": str(src_file),
429
+ "current_phase": current, "gate": gate,
430
+ "ascii_tool": tool, "ascii_ok": art is not None, "rendered": rendered,
431
+ })
432
+ return 0
433
+
434
+ # pure-output modes first: everything below adds UI chrome around them
435
+ if args.tools:
436
+ print(ui.colorize("Renderers available:", ui.BOLD))
437
+ at = workflow.ascii_tools()
438
+ print(f" ascii (in-terminal): {at or 'none — ' + ' | '.join(workflow.ASCII_TOOL_INSTALL.values())}")
439
+ print(f" svg/png (files): {workflow.diagram_tools() or 'none — cargo install mmdr'}")
440
+ return 0
441
+ if getattr(args, "example", False):
442
+ if args.phases:
443
+ print(workflow.mermaid_for_phase(current, done=gate["done"]))
444
+ else:
445
+ print(workflow.mermaid_for_tasks(store.list()))
446
+ return 0
447
+
448
+ print(ui.banner("Workflow"))
449
+ print(ui.colorize("Phase pipeline (SKILL.md §3, constant):", ui.DIM))
450
+ print(ui.phase_rail(current, done=gate["done"]))
451
+ print()
452
+
453
+ if not src_file.exists():
454
+ print(ui.colorize("⏳ workflow diagram: still pending.", ui.YELLOW))
455
+ print(ui.colorize(" The Orchestrator or Researcher authors .rh/workflow.mmd (the PLAN.md step DAG,", ui.DIM))
456
+ print(ui.colorize(" adapted to the installed renderers) — rh only displays it, it never creates it.", ui.DIM))
457
+ return 0
458
+ src = src_file.read_text(encoding="utf-8")
459
+
460
+ art, tool = (None, None)
461
+ if not args.no_render:
462
+ art, tool = workflow.render_ascii(root, src)
463
+ if art:
464
+ print(f"{ui.colorize('Diagram', ui.BOLD)} {ui.colorize(f'(via {tool})', ui.DIM)}")
465
+ print(art)
466
+ print()
467
+ elif not args.no_render:
468
+ installed = workflow.ascii_tools()
469
+ if installed:
470
+ print(ui.colorize(f"⚠ ascii render failed via {installed[0]} — check the .mmd syntax", ui.YELLOW))
471
+ else:
472
+ print(ui.colorize("No ASCII renderer installed — nothing downloaded without your say-so.", ui.YELLOW))
473
+ print(ui.colorize(" Options (install one, or run the npx form yourself — it fetches into the npm cache):", ui.DIM))
474
+ for line in workflow.ASCII_TOOL_INSTALL.values():
475
+ print(f" · {line}")
476
+ for line in workflow.ASCII_NO_INSTALL.values():
477
+ print(f" · {line}")
478
+ fmt = "png" if args.png else "svg"
479
+ if (args.png or args.svg) and workflow.diagram_tools():
480
+ img, msg = workflow.render_image(root, src, fmt=fmt, out_name="workflow")
481
+ if img:
482
+ print(ui.colorize(f"✓ {msg}: {img}", ui.GREEN))
483
+ else:
484
+ print(ui.colorize(f"⚠ {msg}", ui.YELLOW))
485
+ return 0
486
+
487
+
488
+ # Hard prerequisites to ENTER a phase (SKILL.md §3 exit gates). Absent keys =
489
+ # no hard requirement (e.g. LITERATURE may be user-agreed skipped).
490
+ REQUIRED_BEFORE = {1: (0,), 2: (1,), 3: (2,), 5: (4,), 6: (0, 1, 2, 4)}
491
+
492
+
493
+ @with_root
494
+ def cmd_phase_set(args, root: Path):
495
+ store = tasks_mod.TaskStore(root)
496
+ current = store.current_phase()
497
+ gate = config.phase_gate(root)
498
+ if args.phase > current and not args.force:
499
+ # hard gate (SKILL.md §3): do not enter the next phase with an unmet gate
500
+ unmet = [i for i in REQUIRED_BEFORE.get(args.phase, ()) if not gate["done"][i]]
501
+ if unmet:
502
+ names = ", ".join(tasks_mod.phase_name(i) for i in unmet)
503
+ print(ui.colorize(f"✗ refusing to enter {tasks_mod.phase_name(args.phase)} — unmet exit gates: {names}", ui.RED), file=sys.stderr)
504
+ for i in unmet:
505
+ hint = {
506
+ 0: "`rh env set KEY=VALUE ...` then have the user confirm ENV.md",
507
+ 1: "write PROBLEM.md (six sections, user approved)",
508
+ 2: "have the Orchestrator interview the user and write the environment section in ENV.md",
509
+ 4: "write PLAN.md (two planners + user approval)",
510
+ }.get(i, "complete the phase artifact")
511
+ print(f" - {tasks_mod.phase_name(i)}: {hint}", file=sys.stderr)
512
+ print(ui.colorize(" or re-run with --force and record the waiver in STATUS.md (SKILL.md §0 rule 11)", ui.DIM), file=sys.stderr)
513
+ return 1
514
+ store.set_phase(args.phase)
515
+ # soft warnings: gates that may be user-agreed skips
516
+ soft = [i for i in range(args.phase) if i not in REQUIRED_BEFORE.get(args.phase, ()) and not gate["done"][i] and i >= current]
517
+ if soft and not args.force:
518
+ names = ", ".join(tasks_mod.phase_name(i) for i in soft)
519
+ print(ui.colorize(f"⚠ skipping ahead past {names} without artifacts — if user-agreed, note the waiver in STATUS.md (§0 rule 11)", ui.YELLOW), file=sys.stderr)
520
+ if getattr(args, "json", False):
521
+ ui.json_out({"phase": args.phase, "phase_name": tasks_mod.phase_name(args.phase), "forced": args.force, "gate": gate})
522
+ return 0
523
+ print(ui.colorize(f"✓ phase → {tasks_mod.phase_name(args.phase)}", ui.GREEN))
524
+ return 0
525
+
526
+
527
+ @with_root
528
+ def cmd_plan_import(args, root: Path):
529
+ added = tasks_mod.import_plan_md(root, dry_run=args.dry_run)
530
+ if getattr(args, "json", False):
531
+ ui.json_out(added)
532
+ return 0
533
+ if not added:
534
+ print(ui.colorize("No new steps in PLAN.md (already imported or no PLAN.md).", ui.DIM))
535
+ for t in added:
536
+ print(f" {ui.colorize('✓', ui.GREEN)} {t['id']} — {t['title']}")
537
+ return 0
538
+
539
+
540
+ @with_root
541
+ def cmd_describe(args, root: Path):
542
+ from . import tasks as task_mod
543
+ info = {
544
+ "version": __version__,
545
+ "root": str(root),
546
+ "layout": {
547
+ ".rh/logs/": "SKILL.md §7 event logs",
548
+ ".rh/papers/": "managed PDFs",
549
+ ".rh/notes/": "rh add note files (heading-structured)",
550
+ ".rh/tasks.json": "machine-readable board (idle|working|complete)",
551
+ ".rh/env.json": "machine mirror of ENV.md config block",
552
+ "src/": "implementation",
553
+ "results/": "produced numbers + generating script",
554
+ "papers/": "unmanaged PDFs",
555
+ "ENV.md": "config block + Orchestrator-written environment notes (§2)",
556
+ "PLAN.md": "approved steps (§4 template)",
557
+ "STATUS.md": "truth (§5)",
558
+ "LITERATURE.md": "paper takes with DOI (§3)",
559
+ "OUTPUT_LAYOUT.md": "output skeleton + comparable-paper patterns (§3)",
560
+ },
561
+ "phases": [{"id": i, "name": n} for i, n in task_mod.PHASES],
562
+ "task_states": list(task_mod.TASK_STATES),
563
+ "env_keys": [
564
+ {"key": k, "kind": kind, "choices": list(choices), "help": h}
565
+ for k, kind, choices, h in config.ENV_SCHEMA
566
+ ],
567
+ "add_targets": list(add_mod.ADD_TARGETS),
568
+ "agent_budget": {
569
+ "1": "Orchestrator wears all hats",
570
+ "2": "Researcher separate",
571
+ "3": "Researcher + Critique separate",
572
+ "4": "Researcher + Critique + Reviewer separate",
573
+ },
574
+ }
575
+ if getattr(args, "json", False):
576
+ ui.json_out(info)
577
+ return 0
578
+ print(ui.banner("rh describe — the map AI agents read"))
579
+ print(f"{ui.colorize('Root:', ui.DIM)} {root}")
580
+ print(f"{ui.colorize('Layout:', ui.BOLD)}")
581
+ for k, v in info["layout"].items():
582
+ print(f" {ui.colorize(f'{k:24}', ui.CYAN)} {v}")
583
+ print(f"\n{ui.colorize('Phases:', ui.BOLD)}")
584
+ for p in info["phases"]:
585
+ print(f" {p['id']} {p['name']}")
586
+ print(f"\n{ui.colorize('Env keys (rh env set KEY=VALUE):', ui.BOLD)}")
587
+ for e in info["env_keys"]:
588
+ print(f" {e['key']} ({e['kind']}{e['choices']}) — {e['help']}")
589
+ print(f"\n{ui.colorize('Add targets:', ui.BOLD)} {info['add_targets']}")
590
+ print(f"\n{ui.colorize('Agent budget:', ui.BOLD)}")
591
+ for k, v in info["agent_budget"].items():
592
+ print(f" count={k} → {v}")
593
+ return 0
594
+
595
+
596
+ @with_root
597
+ def cmd_resume(args, root: Path):
598
+ """Spawn a configured harness with a go-forward prompt (rh resume / rh -r)."""
599
+ if not paths.rh_dir(root).exists():
600
+ print(ui.colorize(f"✗ not initialized: {root} has no .rh/ — run `rh init` first", ui.RED), file=sys.stderr)
601
+ return 1
602
+ env = config.load_env(root)
603
+ gate = config.phase_gate(root, env)
604
+ if not gate["done"][0]:
605
+ print(ui.colorize("✗ phase 0 CONFIG unfinished — a harness can only resume a configured project:", ui.RED), file=sys.stderr)
606
+ print(" `rh env set KEY=VALUE ...` (see `rh env list`), then confirm ENV.md", file=sys.stderr)
607
+ return 1
608
+ dry = getattr(args, "dry_run", False)
609
+ backend, backend_changed = resume_mod.resolve_backend(getattr(args, "backend", None), env, interactive=not dry)
610
+ agent_cli, cli_changed = None, False
611
+ if backend:
612
+ agent_cli, cli_changed = resume_mod.resolve_agent_cli(getattr(args, "cli", None), env, interactive=not dry)
613
+ if not agent_cli:
614
+ print(ui.colorize("✗ no agent CLI chosen — nothing to spawn", ui.RED), file=sys.stderr)
615
+ return 1
616
+ if dry and (backend_changed or cli_changed):
617
+ if not backend:
618
+ print(ui.colorize(f"[dry-run] harness not configured — a real run would ask here. Detected: {resume_mod.detect_harnesses() or 'none'}", ui.YELLOW))
619
+ if not agent_cli:
620
+ print(ui.colorize(f"[dry-run] agent CLI not configured — a real run would ask here. Detected: {resume_mod.detect_agent_clis() or 'none'}", ui.YELLOW))
621
+ # persist interactive picks so next resume is zero-touch ("configured harness")
622
+ if backend_changed or cli_changed:
623
+ env.setdefault("agents", {})
624
+ env["agents"]["backend"] = backend or "none"
625
+ if agent_cli:
626
+ env["agents"]["cli"] = agent_cli
627
+ config.save_env(root, env)
628
+ print(ui.colorize(f"✓ saved to ENV.md: agents.backend={backend or 'none'}"
629
+ + (f" agents.cli={agent_cli}" if agent_cli else ""), ui.GREEN))
630
+ store = tasks_mod.TaskStore(root)
631
+ prompt = resume_mod.build_prompt(root, env, gate, store, extra=getattr(args, "prompt", None) or "")
632
+ prompt_file = paths.rh_dir(root) / "resume-prompt.md"
633
+ prompt_file.parent.mkdir(parents=True, exist_ok=True)
634
+ prompt_file.write_text(prompt + "\n", encoding="utf-8")
635
+ slug = env.get("project", {}).get("slug") or "untitled"
636
+ if getattr(args, "json", False):
637
+ ui.json_out({
638
+ "root": str(root), "backend": backend, "agent_cli": agent_cli,
639
+ "prompt_file": str(prompt_file), "prompt": prompt,
640
+ "gate": gate, "spawned": False,
641
+ })
642
+ return 0
643
+ print(ui.banner(f"rh resume — {slug}", f"backend: {backend or 'none (prompt only)'} · agent: {agent_cli or '—'}"))
644
+ print(prompt)
645
+ if getattr(args, "dry_run", False) or not backend:
646
+ if not backend:
647
+ print()
648
+ print(ui.colorize(f"prompt written to {prompt_file} — paste it into your agent, or install tmux/herdr/tuios.", ui.YELLOW))
649
+ return 0
650
+ script = resume_mod.write_launcher(root, agent_cli, prompt_file)
651
+ ok, detail = resume_mod.launch(backend, root, script, slug)
652
+ if ok:
653
+ print(ui.colorize(f"✓ {detail}", ui.GREEN))
654
+ print(ui.colorize(" the agent opens as the Orchestrator (skill in prompt); pane/spawn bookkeeping is its job, not rh's.", ui.DIM))
655
+ return 0
656
+ print(ui.colorize(f"✗ {detail}", ui.RED), file=sys.stderr)
657
+ print(ui.colorize(f" prompt ready at {prompt_file}; launcher at {script}", ui.DIM), file=sys.stderr)
658
+ return 1
659
+
660
+
661
+ def cmd_skill_install(args):
662
+ """Copy the bundled research-helper skill into a user skills directory."""
663
+ from importlib import resources
664
+
665
+ dest = (Path(args.dest).expanduser() if args.dest
666
+ else Path.home() / ".agents" / "skills" / "research-helper")
667
+ src = resources.files("rh").joinpath("skills", "research-helper")
668
+ if not src.is_dir():
669
+ print("✗ this build does not bundle the skill", file=sys.stderr)
670
+ return 1
671
+ if dest.exists() and any(dest.iterdir()) and not args.force:
672
+ print(f"✗ {dest} already exists — pass --force to overwrite", file=sys.stderr)
673
+ return 1
674
+ dest.mkdir(parents=True, exist_ok=True)
675
+ files = 0
676
+ for entry in src.iterdir():
677
+ if entry.is_file():
678
+ (dest / entry.name).write_bytes(entry.read_bytes())
679
+ files += 1
680
+ if getattr(args, "json", False):
681
+ ui.json_out({"installed": str(dest), "files": files})
682
+ return 0
683
+ print(ui.colorize(f"✓ installed skill to {dest}", ui.GREEN))
684
+ print(ui.colorize(" pi and other Agent Skills clients discover ~/.agents/skills/", ui.DIM))
685
+ return 0
686
+
687
+
688
+ def build_parser():
689
+ common = argparse.ArgumentParser(add_help=False)
690
+ common.add_argument("--root", default=argparse.SUPPRESS, help="project root (default: walk up for .rh/ or ENV.md, else cwd)")
691
+ common.add_argument("--json", action="store_true", default=argparse.SUPPRESS, help="machine-readable JSON output")
692
+ p = argparse.ArgumentParser(prog="rh", description="research-helper CLI — orchestrate a research project end to end", parents=[common])
693
+ p.add_argument("--version", action="version", version=f"rh {__version__}")
694
+ p.add_argument("-r", "--resume", action="store_true", help="shortcut for `rh resume` (spawn harness + go-forward prompt)")
695
+ sub = p.add_subparsers(dest="cmd", required=False)
696
+
697
+ s = sub.add_parser("init", help="create .rh/ layout", parents=[common])
698
+ s.add_argument("--slug", default=None)
699
+ s.add_argument("--clean", action="store_true")
700
+ s.set_defaults(func=cmd_init)
701
+
702
+ s = sub.add_parser("env", help="environment config", parents=[common])
703
+ esub = s.add_subparsers(dest="e", required=True)
704
+ esub.add_parser("show", parents=[common]).set_defaults(func=cmd_env_show)
705
+ esub.add_parser("list", parents=[common]).set_defaults(func=cmd_env_list)
706
+ sp = esub.add_parser("set", parents=[common]); sp.add_argument("pairs", nargs="*", metavar="KEY=VALUE"); sp.set_defaults(func=cmd_env_set)
707
+
708
+ s = sub.add_parser("add", help="append under heading/DOI", parents=[common])
709
+ s.add_argument("target", choices=list(add_mod.ADD_TARGETS))
710
+ s.add_argument("heading", help="heading or DOI")
711
+ s.add_argument("-m", "--message", default=None)
712
+ s.add_argument("--file", default=None, help="note filename (md)")
713
+ s.add_argument("--role", default=None)
714
+ s.add_argument("--title", default=None)
715
+ s.add_argument("--id", default=None)
716
+ s.add_argument("--phase", type=int, default=None, help="default: current project phase")
717
+ s.add_argument("--owner", default="researcher")
718
+ s.add_argument("--state", default="idle", choices=list(tasks_mod.TASK_STATES))
719
+ s.add_argument("--deliverable", default="")
720
+ s.add_argument("--verify", default="")
721
+ s.add_argument("--depends-on", dest="depends_on", default="", help="comma-separated task ids this depends on")
722
+ s.add_argument("--kind", default="build", choices=["build", "spike"])
723
+ s.set_defaults(func=cmd_add)
724
+
725
+ s = sub.add_parser("search", help="local search (rg or python)", parents=[common])
726
+ s.add_argument("query")
727
+ s.add_argument("--max", type=int, default=40)
728
+ s.set_defaults(func=cmd_search)
729
+
730
+ s = sub.add_parser("task", help="task board", parents=[common])
731
+ tsub = s.add_subparsers(dest="t", required=True)
732
+ ts = tsub.add_parser("set", parents=[common]); ts.add_argument("id"); ts.add_argument("state", choices=list(tasks_mod.TASK_STATES)); ts.set_defaults(func=cmd_task_set)
733
+ tl = tsub.add_parser("list", parents=[common]); tl.add_argument("--phase", type=int, default=None); tl.add_argument("--state", default=None, choices=list(tasks_mod.TASK_STATES)); tl.set_defaults(func=cmd_task_list)
734
+
735
+ s = sub.add_parser("tasks", help="task board + progress", parents=[common])
736
+ s.add_argument("--phase", type=int, default=None)
737
+ s.set_defaults(func=cmd_tasks)
738
+
739
+ s = sub.add_parser("status", help="project status", parents=[common])
740
+ s.set_defaults(func=cmd_status)
741
+
742
+ s = sub.add_parser("workflow", help="display the agent-authored .rh/workflow.mmd (ascii in-terminal)", parents=[common])
743
+ s.add_argument("--example", action="store_true", help="print a starter mermaid source (from the task board) the agent can save as .rh/workflow.mmd")
744
+ s.add_argument("--phases", action="store_true", help="with --example: use the constant SKILL.md phase pipeline")
745
+ s.add_argument("--tools", action="store_true", help="list installed renderers")
746
+ s.add_argument("--png", action="store_true", help="render png from workflow.mmd")
747
+ s.add_argument("--svg", action="store_true", help="render svg from workflow.mmd")
748
+ s.add_argument("--no-render", action="store_true", help="skip ascii display")
749
+ s.set_defaults(func=cmd_workflow)
750
+
751
+ s = sub.add_parser("phase", help="set current phase: rh phase <0-9> (gated; --force to override)")
752
+ s.add_argument("set", choices=["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"])
753
+ s.add_argument("--force", action="store_true", help="jump despite unmet gates (waiver goes in STATUS.md)")
754
+ s.set_defaults(func=cmd_phase_set)
755
+
756
+ s = sub.add_parser("plan", help="PLAN.md integration", parents=[common])
757
+ psub = s.add_subparsers(dest="pl", required=True)
758
+ pi = psub.add_parser("import", parents=[common]); pi.add_argument("--dry-run", action="store_true"); pi.set_defaults(func=cmd_plan_import)
759
+
760
+ s = sub.add_parser("describe", help="AI map of the tool", parents=[common])
761
+ s.set_defaults(func=cmd_describe)
762
+
763
+ s = sub.add_parser("resume", help="spawn a configured harness with a go-forward prompt", parents=[common])
764
+ s.add_argument("--backend", default=None, help="tmux | herdr | tuios (default: config agents.backend, else ask)")
765
+ s.add_argument("--cli", dest="cli", default=None, help="agent binary, e.g. opencode (default: config agents.cli, else ask)")
766
+ s.add_argument("--prompt", default=None, help="extra user instructions appended to the go-forward prompt")
767
+ s.add_argument("--dry-run", action="store_true", help="show prompt + choices without spawning")
768
+ s.set_defaults(func=cmd_resume)
769
+
770
+ s = sub.add_parser("skill", help="install the bundled agent skill", parents=[common])
771
+ ssub = s.add_subparsers(dest="sk", required=True)
772
+ si = ssub.add_parser("install", parents=[common])
773
+ si.add_argument("--dest", default=None, help="destination dir (default: ~/.agents/skills/research-helper)")
774
+ si.add_argument("--force", action="store_true", help="overwrite an existing skill dir")
775
+ si.set_defaults(func=cmd_skill_install)
776
+
777
+ return p
778
+
779
+
780
+ KNOWN_CMDS = {"init", "env", "add", "search", "task", "tasks", "status", "workflow", "phase", "plan", "describe", "resume", "skill"}
781
+
782
+
783
+ def main(argv=None) -> int:
784
+ argv = list(sys.argv[1:] if argv is None else argv)
785
+ # `rh -r [flags...]` (no subcommand) → `rh resume [flags...]`
786
+ if not (set(argv) & KNOWN_CMDS) and ("-r" in argv or "--resume" in argv):
787
+ argv = ["resume", *[a for a in argv if a not in ("-r", "--resume")]]
788
+ args = build_parser().parse_args(argv)
789
+ if args.cmd is None:
790
+ build_parser().print_help()
791
+ return 2
792
+ # `rh phase N` → phase int
793
+ if args.cmd == "phase" and args.set is not None:
794
+ args.phase = int(args.set)
795
+ return args.func(args)
796
+
797
+
798
+ if __name__ == "__main__":
799
+ raise SystemExit(main())