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/__init__.py +12 -0
- rh/add.py +105 -0
- rh/cli.py +799 -0
- rh/config.py +308 -0
- rh/paths.py +96 -0
- rh/resume.py +186 -0
- rh/search.py +123 -0
- rh/skills/research-helper/SKILL.md +497 -0
- rh/tasks.py +221 -0
- rh/ui.py +128 -0
- rh/workflow.py +268 -0
- rh_cli-0.1.0.dist-info/METADATA +217 -0
- rh_cli-0.1.0.dist-info/RECORD +17 -0
- rh_cli-0.1.0.dist-info/WHEEL +5 -0
- rh_cli-0.1.0.dist-info/entry_points.txt +2 -0
- rh_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
- rh_cli-0.1.0.dist-info/top_level.txt +1 -0
rh/config.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
"""Config + storage model — maps SKILL.md §2 onto .rh/.
|
|
2
|
+
|
|
3
|
+
ENV.md holds the config block (human-readable, SKILL.md truth). .rh/env.json
|
|
4
|
+
mirrors it for machines. Anything below the config block (the Orchestrator's
|
|
5
|
+
environment notes) is preserved verbatim across `rh env set`.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import re
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from . import paths
|
|
14
|
+
from .tasks import TaskStore
|
|
15
|
+
|
|
16
|
+
DEFAULT_ENV: dict = {
|
|
17
|
+
"agents": {
|
|
18
|
+
"count": 1,
|
|
19
|
+
"backend": "none", # tmux | herdr | tuios | none
|
|
20
|
+
"cli": "", # agent binary rh resume spawns (user-named)
|
|
21
|
+
"roles": {
|
|
22
|
+
"orchestrator": {},
|
|
23
|
+
"literature": {},
|
|
24
|
+
"researcher": {},
|
|
25
|
+
"reviewer": {},
|
|
26
|
+
"critique": {},
|
|
27
|
+
"writer": {},
|
|
28
|
+
},
|
|
29
|
+
"planners": {"models": [{}, {}], "max_rounds": 0},
|
|
30
|
+
},
|
|
31
|
+
"literature": {
|
|
32
|
+
"ref_manager": "none", # zot | bibtex | none
|
|
33
|
+
"reading": "pdftotext", # lit | pdftotext | images
|
|
34
|
+
"paywall": "ask_user", # ask_user | skip
|
|
35
|
+
"search": "crw", # crw | agent-browser | obscura | <binary>
|
|
36
|
+
},
|
|
37
|
+
"project": {"slug": "", "git": False},
|
|
38
|
+
"gates": {"user_approves_plan": True, "critique_veto": True},
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
AGENT_BACKENDS = ("tmux", "herdr", "tuios", "none")
|
|
42
|
+
PAYWALL_POLICIES = ("ask_user", "skip")
|
|
43
|
+
|
|
44
|
+
# dotted key -> (type, choices, help) — drives `rh env set` and docs
|
|
45
|
+
ENV_SCHEMA: list[tuple[str, str, tuple, str]] = [
|
|
46
|
+
("agents.count", "int", (1, 2, 3, 4), "how many agents may run at once, 1..4"),
|
|
47
|
+
("agents.backend", "str", AGENT_BACKENDS, "tmux | herdr | tuios | none (serial); rh resume spawns this"),
|
|
48
|
+
("agents.cli", "str", (), "agent binary the harness spawns, e.g. opencode (rh resume)"),
|
|
49
|
+
("agents.roles.orchestrator", "dict", (), "provider+model, must be the model running this session"),
|
|
50
|
+
("agents.roles.literature", "dict", (), "provider+model for the Literature role"),
|
|
51
|
+
("agents.roles.researcher", "dict", (), "provider+model for the Researcher role"),
|
|
52
|
+
("agents.roles.reviewer", "dict", (), "provider+model for the Reviewer role"),
|
|
53
|
+
("agents.roles.critique", "dict", (), "provider+model for the Critique role"),
|
|
54
|
+
("agents.roles.writer", "dict", (), "provider+model for the Writer role"),
|
|
55
|
+
("agents.planners.models.0", "dict", (), "planner 1 model (must differ from planner 2)"),
|
|
56
|
+
("agents.planners.models.1", "dict", (), "planner 2 model"),
|
|
57
|
+
("agents.planners.max_rounds", "int", (0, 1, 2, 3, 5), "0 = cap at 3 rounds, then escalate"),
|
|
58
|
+
("literature.ref_manager", "str", (), "reference manager the user names (e.g. zot, bibtex, none)"),
|
|
59
|
+
("literature.reading", "str", (), "reader the user names (e.g. lit, pdftotext, images)"),
|
|
60
|
+
("literature.paywall", "str", PAYWALL_POLICIES, "ask_user | skip (proceed without paper)"),
|
|
61
|
+
("literature.search", "str", (), "search tool the user names (e.g. crw, agent-browser, any binary)"),
|
|
62
|
+
("project.slug", "str", (), "short kebab-case name"),
|
|
63
|
+
("project.git", "bool", (True, False), "true only if the project is already a repo"),
|
|
64
|
+
("gates.user_approves_plan", "bool", (True, False), "user approves PLAN.md before implementation"),
|
|
65
|
+
("gates.critique_veto", "bool", (True, False), "Critique can veto the critique gate"),
|
|
66
|
+
]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class ConfigError(RuntimeError):
|
|
70
|
+
pass
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def deep_merge(base: dict, override: dict) -> dict:
|
|
74
|
+
out = dict(base)
|
|
75
|
+
for k, v in override.items():
|
|
76
|
+
if k in out and isinstance(out[k], dict) and isinstance(v, dict):
|
|
77
|
+
out[k] = deep_merge(out[k], v)
|
|
78
|
+
else:
|
|
79
|
+
out[k] = v
|
|
80
|
+
return out
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def get_nested(d: dict, dotted: str):
|
|
84
|
+
cur = d
|
|
85
|
+
for part in dotted.split("."):
|
|
86
|
+
if isinstance(cur, list):
|
|
87
|
+
cur = cur[int(part)]
|
|
88
|
+
elif isinstance(cur, dict):
|
|
89
|
+
cur = cur[part]
|
|
90
|
+
else:
|
|
91
|
+
raise KeyError(dotted)
|
|
92
|
+
return cur
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def set_nested(d: dict, dotted: str, value) -> None:
|
|
96
|
+
parts = dotted.split(".")
|
|
97
|
+
cur = d
|
|
98
|
+
for part in parts[:-1]:
|
|
99
|
+
if isinstance(cur, list):
|
|
100
|
+
cur = cur[int(part)]
|
|
101
|
+
else:
|
|
102
|
+
nxt = cur.get(part)
|
|
103
|
+
if not isinstance(nxt, (dict, list)):
|
|
104
|
+
nxt = []
|
|
105
|
+
cur[part] = nxt
|
|
106
|
+
cur = nxt
|
|
107
|
+
last = parts[-1]
|
|
108
|
+
if isinstance(cur, list):
|
|
109
|
+
cur[int(last)] = value
|
|
110
|
+
else:
|
|
111
|
+
cur[last] = value
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def coerce_value(raw: str, kind: str):
|
|
115
|
+
raw = raw.strip()
|
|
116
|
+
if kind == "int":
|
|
117
|
+
return int(raw)
|
|
118
|
+
if kind == "bool":
|
|
119
|
+
if raw.lower() in ("true", "yes", "1", "on"):
|
|
120
|
+
return True
|
|
121
|
+
if raw.lower() in ("false", "no", "0", "off"):
|
|
122
|
+
return False
|
|
123
|
+
raise ValueError(f"expected true/false, got {raw!r}")
|
|
124
|
+
if kind == "dict":
|
|
125
|
+
try:
|
|
126
|
+
v = json.loads(raw)
|
|
127
|
+
except json.JSONDecodeError:
|
|
128
|
+
# allow "provider/model" shorthand
|
|
129
|
+
if "/" in raw:
|
|
130
|
+
provider, model = raw.split("/", 1)
|
|
131
|
+
return {"provider": provider, "model": model}
|
|
132
|
+
raise ValueError(f"expected JSON object or provider/model, got {raw!r}")
|
|
133
|
+
if not isinstance(v, dict):
|
|
134
|
+
raise ValueError(f"expected JSON object, got {raw!r}")
|
|
135
|
+
return v
|
|
136
|
+
return raw
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def validate(env: dict) -> list[str]:
|
|
140
|
+
"""Return list of problems (empty = valid)."""
|
|
141
|
+
problems = []
|
|
142
|
+
try:
|
|
143
|
+
count = env["agents"]["count"]
|
|
144
|
+
if count not in (1, 2, 3, 4):
|
|
145
|
+
problems.append(f"agents.count must be 1..4, got {count!r}")
|
|
146
|
+
except KeyError:
|
|
147
|
+
problems.append("agents.count is missing")
|
|
148
|
+
backend = env.get("agents", {}).get("backend")
|
|
149
|
+
if backend not in AGENT_BACKENDS:
|
|
150
|
+
problems.append(f"agents.backend must be one of {AGENT_BACKENDS}, got {backend!r}")
|
|
151
|
+
planners = env.get("agents", {}).get("planners", {}).get("models", [])
|
|
152
|
+
if len(planners) >= 2 and planners[0] and planners[1] and planners[0] == planners[1]:
|
|
153
|
+
problems.append("agents.planners.models must be two different models")
|
|
154
|
+
slug = env.get("project", {}).get("slug", "")
|
|
155
|
+
if slug and not re.fullmatch(r"[a-z0-9]+(-[a-z0-9]+)*", slug):
|
|
156
|
+
problems.append(f"project.slug must be kebab-case, got {slug!r}")
|
|
157
|
+
lit = env.get("literature", {})
|
|
158
|
+
# tool names are whatever the user names — never restricted to a known list
|
|
159
|
+
for key in ("ref_manager", "reading", "search"):
|
|
160
|
+
val = lit.get(key)
|
|
161
|
+
if not isinstance(val, str) or not val.strip():
|
|
162
|
+
problems.append(f"literature.{key} must be a non-empty tool/method name, got {val!r}")
|
|
163
|
+
paywall = lit.get("paywall")
|
|
164
|
+
if paywall not in PAYWALL_POLICIES:
|
|
165
|
+
problems.append(f"literature.paywall must be one of {PAYWALL_POLICIES}, got {paywall!r}")
|
|
166
|
+
orch = env.get("agents", {}).get("roles", {}).get("orchestrator", {})
|
|
167
|
+
if orch:
|
|
168
|
+
if not isinstance(orch, dict) or not orch:
|
|
169
|
+
problems.append("agents.roles.orchestrator must be a model object")
|
|
170
|
+
return problems
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
# --- ENV.md rendering/parsing -------------------------------------------------
|
|
174
|
+
|
|
175
|
+
ENV_FENCE = re.compile(r"```jsonc?\n(.*?)```", re.DOTALL)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def render_env_md(env: dict, tail: str = "") -> str:
|
|
179
|
+
"""Render ENV.md: config block (json) + whatever the Orchestrator wrote below it."""
|
|
180
|
+
block = json.dumps(env, indent=2, sort_keys=True)
|
|
181
|
+
lines = [
|
|
182
|
+
"# ENV — research-helper config",
|
|
183
|
+
"",
|
|
184
|
+
"```json",
|
|
185
|
+
block,
|
|
186
|
+
"```",
|
|
187
|
+
]
|
|
188
|
+
if tail.strip():
|
|
189
|
+
lines += ["", tail.strip()]
|
|
190
|
+
return "\n".join(lines) + "\n"
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _block_and_tail(path: Path) -> tuple[dict | None, str]:
|
|
194
|
+
"""Return (config block, text below it) from ENV.md."""
|
|
195
|
+
if not path.exists():
|
|
196
|
+
return None, ""
|
|
197
|
+
text = path.read_text(encoding="utf-8")
|
|
198
|
+
m = ENV_FENCE.search(text)
|
|
199
|
+
if not m:
|
|
200
|
+
return None, ""
|
|
201
|
+
try:
|
|
202
|
+
env = json.loads(m.group(1))
|
|
203
|
+
except json.JSONDecodeError:
|
|
204
|
+
return None, ""
|
|
205
|
+
return env, text[m.end():].strip("\n")
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def parse_env_md(path: Path) -> dict | None:
|
|
209
|
+
"""Extract the json config block from ENV.md. Returns None if absent."""
|
|
210
|
+
return _block_and_tail(path)[0]
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def load_tail(root: Path) -> str:
|
|
214
|
+
"""The Orchestrator's environment notes below the config block."""
|
|
215
|
+
return _block_and_tail(root / "ENV.md")[1]
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def load_env(root: Path) -> dict:
|
|
219
|
+
"""Load effective config: ENV.md block (truth) or .rh/env.json mirror or defaults."""
|
|
220
|
+
env_md = root / "ENV.md"
|
|
221
|
+
if env_md.exists():
|
|
222
|
+
parsed = parse_env_md(env_md)
|
|
223
|
+
if parsed is not None:
|
|
224
|
+
return deep_merge(DEFAULT_ENV, parsed)
|
|
225
|
+
mirror = paths.env_json(root)
|
|
226
|
+
if mirror.exists():
|
|
227
|
+
try:
|
|
228
|
+
return deep_merge(DEFAULT_ENV, json.loads(mirror.read_text()))
|
|
229
|
+
except json.JSONDecodeError:
|
|
230
|
+
pass
|
|
231
|
+
return deep_merge(DEFAULT_ENV, {})
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def save_env(root: Path, env: dict) -> None:
|
|
235
|
+
"""Write ENV.md config block (preserving the notes below it) + .rh/env.json mirror."""
|
|
236
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
237
|
+
_, tail = _block_and_tail(root / "ENV.md")
|
|
238
|
+
(root / "ENV.md").write_text(render_env_md(env, tail), encoding="utf-8")
|
|
239
|
+
mirror = paths.env_json(root)
|
|
240
|
+
mirror.parent.mkdir(parents=True, exist_ok=True)
|
|
241
|
+
mirror.write_text(json.dumps(env, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def config_complete(env: dict) -> bool:
|
|
245
|
+
"""Phase-0 exit gate (SKILL.md §3): the block parses and no validate() problems.
|
|
246
|
+
|
|
247
|
+
Never use this alone — defaults pass validation with no ENV.md on disk.
|
|
248
|
+
Gate on config_written() for "did the user actually configure the project".
|
|
249
|
+
"""
|
|
250
|
+
return not validate(env)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def config_written(root: Path) -> bool:
|
|
254
|
+
"""True only if ENV.md exists and holds a parseable config block.
|
|
255
|
+
|
|
256
|
+
This is the phase-0 exit gate: the block was written (rh env set / init),
|
|
257
|
+
so it is user-confirmed config, not silent defaults.
|
|
258
|
+
"""
|
|
259
|
+
return parse_env_md(root / "ENV.md") is not None
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def phase_gate(root: Path, env: dict | None = None) -> dict:
|
|
263
|
+
"""Hard-gate check per SKILL.md §3 — warns when the pipeline was skipped.
|
|
264
|
+
|
|
265
|
+
Returns {phase, ok, problems[], done[]}. done[i] is True only when phase i
|
|
266
|
+
is *verified* by an artifact (or the phase after it was entered). The rail
|
|
267
|
+
renders ✓ from done[], never from position alone.
|
|
268
|
+
"""
|
|
269
|
+
env = env if env is not None else load_env(root)
|
|
270
|
+
problems: list[str] = []
|
|
271
|
+
current = TaskStore(root).current_phase() if (paths.tasks_json(root)).exists() else 0
|
|
272
|
+
|
|
273
|
+
written = config_written(root)
|
|
274
|
+
if not written:
|
|
275
|
+
problems.append(
|
|
276
|
+
"phase 0 CONFIG unfinished — no ENV.md with a parseable config block "
|
|
277
|
+
"(run `rh env set KEY=VALUE ...`, then have the user confirm)"
|
|
278
|
+
)
|
|
279
|
+
elif not config_complete(env):
|
|
280
|
+
problems.append(f"phase 0 CONFIG invalid: {validate(env)}")
|
|
281
|
+
|
|
282
|
+
done = [False] * 10
|
|
283
|
+
done[0] = written and not validate(env)
|
|
284
|
+
problem = paths.artifact_path(root, "PROBLEM.md")
|
|
285
|
+
done[1] = problem.exists() and problem.stat().st_size > 0
|
|
286
|
+
if current >= 6 and not done[1]:
|
|
287
|
+
problems.append("phase 1 INTAKE artifact missing: PROBLEM.md")
|
|
288
|
+
done[2] = bool(load_tail(root).strip())
|
|
289
|
+
if current >= 6 and not done[2]:
|
|
290
|
+
problems.append("phase 2 ENVIRONMENT artifact missing: have the Orchestrator "
|
|
291
|
+
"interview the user and write the environment section in ENV.md")
|
|
292
|
+
lit = paths.artifact_path(root, "LITERATURE.md")
|
|
293
|
+
gaps = paths.artifact_path(root, "GAPS.md")
|
|
294
|
+
done[3] = (lit.exists() and lit.stat().st_size > 0) or (gaps.exists() and gaps.stat().st_size > 0)
|
|
295
|
+
if current >= 6 and not done[3]:
|
|
296
|
+
problems.append("phase 3 LITERATURE artifact missing: LITERATURE.md or GAPS.md (or user-agreed skip)")
|
|
297
|
+
plan = paths.artifact_path(root, "PLAN.md")
|
|
298
|
+
done[4] = plan.exists() and plan.stat().st_size > 0
|
|
299
|
+
if current >= 6 and not done[4]:
|
|
300
|
+
problems.append("phase 4 PLAN artifact missing: PLAN.md (two planners + user approval)")
|
|
301
|
+
status = paths.artifact_path(root, "STATUS.md")
|
|
302
|
+
done[5] = status.exists() and status.stat().st_size > 0
|
|
303
|
+
if current >= 6 and not done[5]:
|
|
304
|
+
problems.append("phase 5 STATE artifact missing: STATUS.md")
|
|
305
|
+
for i in range(6, 10):
|
|
306
|
+
done[i] = current > i
|
|
307
|
+
# later phases may mark earlier ones done only via artifacts (already handled)
|
|
308
|
+
return {"phase": current, "ok": not problems, "problems": problems, "done": done}
|
rh/paths.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Project root discovery + .rh/ layout.
|
|
2
|
+
|
|
3
|
+
Priority: explicit --root, RH_ROOT, cwd walk-up for `.rh/` or ENV.md, cwd.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
RH_DIR = ".rh"
|
|
11
|
+
|
|
12
|
+
# Files kept under .rh/ (clean workspace). src/, results/, papers/ stay at root.
|
|
13
|
+
RH_ARTIFACTS = {
|
|
14
|
+
"PROBLEM.md": "problem_md",
|
|
15
|
+
"ENV.md": "env_md",
|
|
16
|
+
"PLAN.md": "plan_md",
|
|
17
|
+
"STATUS.md": "status_md",
|
|
18
|
+
"LITERATURE.md": "literature_md",
|
|
19
|
+
"OUTPUT_LAYOUT.md": "output_layout_md",
|
|
20
|
+
"GAPS.md": "gaps_md",
|
|
21
|
+
"MANUSCRIPT.md": "manuscript_md",
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def find_project_root(start: Path | None = None) -> Path:
|
|
26
|
+
start = (start or Path.cwd()).resolve()
|
|
27
|
+
# walk up looking for .rh/ or ENV.md
|
|
28
|
+
cur = start
|
|
29
|
+
for parent in [cur, *cur.parents]:
|
|
30
|
+
if (parent / RH_DIR).is_dir() or (parent / "ENV.md").exists():
|
|
31
|
+
return parent
|
|
32
|
+
return start
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def resolve_root(cli_root: str | None = None) -> Path:
|
|
36
|
+
if cli_root:
|
|
37
|
+
return Path(cli_root).expanduser().resolve()
|
|
38
|
+
env = os.environ.get("RH_ROOT") or os.environ.get("RH_HOME")
|
|
39
|
+
if env:
|
|
40
|
+
return Path(env).expanduser().resolve()
|
|
41
|
+
return find_project_root()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def rh_dir(root: Path) -> Path:
|
|
45
|
+
return root / RH_DIR
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def ensure_layout(root: Path) -> Path:
|
|
49
|
+
"""Create .rh/ subfolders. Returns the .rh path."""
|
|
50
|
+
d = rh_dir(root)
|
|
51
|
+
for sub in ("logs", "papers", "notes", "tasks", "tmp"):
|
|
52
|
+
(d / sub).mkdir(parents=True, exist_ok=True)
|
|
53
|
+
(root / "src").mkdir(parents=True, exist_ok=True)
|
|
54
|
+
(root / "results").mkdir(parents=True, exist_ok=True)
|
|
55
|
+
(root / "papers").mkdir(parents=True, exist_ok=True)
|
|
56
|
+
return d
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def env_json(root: Path) -> Path:
|
|
60
|
+
return rh_dir(root) / "env.json"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def tasks_json(root: Path) -> Path:
|
|
64
|
+
return rh_dir(root) / "tasks.json"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def notes_dir(root: Path) -> Path:
|
|
68
|
+
return rh_dir(root) / "notes"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def logs_dir(root: Path) -> Path:
|
|
72
|
+
return rh_dir(root) / "logs"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def papers_dir(root: Path) -> Path:
|
|
76
|
+
# SKILL.md papers/ at root; keep both: rh papers/ is managed, root papers/ legacy
|
|
77
|
+
d = rh_dir(root) / "papers"
|
|
78
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
79
|
+
return d
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def artifact_path(root: Path, name: str) -> Path:
|
|
83
|
+
"""Where SKILL.md artifact `name` lives: .rh/<name> if root has .rh, else root/<name>.
|
|
84
|
+
|
|
85
|
+
Migration-safe: if the artifact already exists at root and not in .rh,
|
|
86
|
+
callers should read from root and write through to .rh (or keep both in
|
|
87
|
+
sync). Prefer .rh when initialized.
|
|
88
|
+
"""
|
|
89
|
+
in_rh = rh_dir(root) / name
|
|
90
|
+
legacy = root / name
|
|
91
|
+
if in_rh.exists():
|
|
92
|
+
return in_rh
|
|
93
|
+
if legacy.exists():
|
|
94
|
+
return legacy
|
|
95
|
+
# new artifacts go in .rh/ when initialized
|
|
96
|
+
return in_rh if rh_dir(root).exists() else legacy
|
rh/resume.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""`rh resume` — spawn a configured harness running the agent with a go-forward prompt.
|
|
2
|
+
|
|
3
|
+
Flow: load ENV.md config (phase-0 gate required) → pick harness backend
|
|
4
|
+
(config `agents.backend`, else interactive choice of installed: tmux/herdr/
|
|
5
|
+
tuios) → pick agent CLI (config `agents.cli`, else detected: opencode/claude/
|
|
6
|
+
codex/...) → build prompt from live project state → write .rh/resume-prompt.md
|
|
7
|
+
+ .rh/tmp/resume.sh → spawn pane → record spawn in STATUS.md.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import shlex
|
|
13
|
+
import shutil
|
|
14
|
+
import subprocess
|
|
15
|
+
from datetime import datetime, timezone
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from . import config, paths, ui
|
|
19
|
+
from .tasks import TaskStore, phase_name
|
|
20
|
+
|
|
21
|
+
HARNESS_BINS = {"tmux": "tmux", "herdr": "herdr", "tuios": "tuios"}
|
|
22
|
+
AGENT_CLIS = ("opencode", "claude", "codex", "gemini", "aider", "goose")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def detect_harnesses() -> list[str]:
|
|
26
|
+
return [name for name, binary in HARNESS_BINS.items() if shutil.which(binary)]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def detect_agent_clis() -> list[str]:
|
|
30
|
+
return [c for c in AGENT_CLIS if shutil.which(c)]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def choose_interactively(title: str, options: list[str], *, allow_none: bool = False) -> str | None:
|
|
34
|
+
"""Numbered in-CLI picker. Returns choice, or None when 'none' chosen."""
|
|
35
|
+
print(ui.colorize(f"? {title}", ui.BOLD))
|
|
36
|
+
shown = list(options) + (["none (print the prompt instead of spawning)"] if allow_none else [])
|
|
37
|
+
for i, opt in enumerate(shown, 1):
|
|
38
|
+
marker = ui.colorize(" (not on PATH)", ui.YELLOW) if opt.endswith("(not on PATH)") else ""
|
|
39
|
+
print(f" {i}) {opt}{marker}")
|
|
40
|
+
while True:
|
|
41
|
+
try:
|
|
42
|
+
raw = input(f" choice [1-{len(shown)}, enter=default 1]: ").strip()
|
|
43
|
+
except (EOFError, KeyboardInterrupt):
|
|
44
|
+
return None
|
|
45
|
+
if raw == "":
|
|
46
|
+
raw = "1"
|
|
47
|
+
if raw.isdigit() and 1 <= int(raw) <= len(shown):
|
|
48
|
+
pick = shown[int(raw) - 1]
|
|
49
|
+
if allow_none and pick.startswith("none"):
|
|
50
|
+
return None
|
|
51
|
+
return pick.split(" ")[0]
|
|
52
|
+
print(ui.colorize(" invalid choice", ui.RED))
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def next_tasks(store: TaskStore) -> list[dict]:
|
|
56
|
+
"""working first, then idle, ordered by phase then id."""
|
|
57
|
+
tasks = store.list()
|
|
58
|
+
prio = {"working": 0, "idle": 1, "complete": 2}
|
|
59
|
+
return sorted(tasks, key=lambda t: (prio.get(t["state"], 3), t["phase"], t["id"]))[:5]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def build_prompt(root: Path, env: dict, gate: dict, store: TaskStore, extra: str = "") -> str:
|
|
63
|
+
slug = env.get("project", {}).get("slug") or "untitled"
|
|
64
|
+
current = gate["phase"]
|
|
65
|
+
lines = [
|
|
66
|
+
f"You are the Orchestrator for the research project '{slug}' at {root}.",
|
|
67
|
+
"",
|
|
68
|
+
"Load the research-helper skill and follow it exactly — it is law, not advice",
|
|
69
|
+
"(SKILL.md §0 non-negotiables; ask before every state-changing action).",
|
|
70
|
+
"",
|
|
71
|
+
f"Current phase: {phase_name(current)}",
|
|
72
|
+
]
|
|
73
|
+
if gate["problems"]:
|
|
74
|
+
lines.append("Unmet gates (resolve these first, or ask the user to waive):")
|
|
75
|
+
lines += [f" - {p}" for p in gate["problems"]]
|
|
76
|
+
else:
|
|
77
|
+
lines.append("Gates: all satisfied for the current phase.")
|
|
78
|
+
tasks = next_tasks(store)
|
|
79
|
+
if tasks:
|
|
80
|
+
lines.append("Next tasks:")
|
|
81
|
+
lines += [f" - [{t['state']}] {t['id']} {t['title']}" for t in tasks]
|
|
82
|
+
else:
|
|
83
|
+
lines.append("No tasks on the board — mirror PLAN.md steps (`rh plan import`) or proceed by phase.")
|
|
84
|
+
lines += [
|
|
85
|
+
"",
|
|
86
|
+
"Start by re-reading, never caching (SKILL.md §0 rules 9 and 10):",
|
|
87
|
+
f" - {paths.artifact_path(root, 'ENV.md')} (config block + environment notes)",
|
|
88
|
+
f" - {paths.artifact_path(root, 'STATUS.md')}" if paths.artifact_path(root, "STATUS.md").exists() else " - STATUS.md (does not exist yet — create it in phase 5, not before)",
|
|
89
|
+
"",
|
|
90
|
+
"Then continue the pipeline from the current phase. Do not skip exit gates;",
|
|
91
|
+
"do not pick models (they live in the ENV.md config block).",
|
|
92
|
+
]
|
|
93
|
+
if extra:
|
|
94
|
+
lines += ["", "User instructions for this session:", extra]
|
|
95
|
+
return "\n".join(lines)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def write_launcher(root: Path, agent_cli: str, prompt_file: Path) -> Path:
|
|
99
|
+
script = paths.rh_dir(root) / "tmp" / "resume.sh"
|
|
100
|
+
script.parent.mkdir(parents=True, exist_ok=True)
|
|
101
|
+
script.write_text(
|
|
102
|
+
"#!/usr/bin/env bash\n"
|
|
103
|
+
f"cd {shlex.quote(str(root))}\n"
|
|
104
|
+
f"exec {agent_cli} \"$(cat {shlex.quote(str(prompt_file))})\"\n",
|
|
105
|
+
encoding="utf-8",
|
|
106
|
+
)
|
|
107
|
+
script.chmod(0o755)
|
|
108
|
+
return script
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def launch(backend: str, root: Path, script: Path, slug: str) -> tuple[bool, str]:
|
|
112
|
+
"""Spawn the pane. Returns (ok, detail)."""
|
|
113
|
+
name = f"rh-{slug}"
|
|
114
|
+
try:
|
|
115
|
+
if backend == "tmux":
|
|
116
|
+
if os.environ.get("TMUX"):
|
|
117
|
+
cmd = ["tmux", "new-window", "-c", str(root), "-n", name, "--", "bash", str(script)]
|
|
118
|
+
subprocess.run(cmd, check=True, timeout=15)
|
|
119
|
+
return True, f"tmux window '{name}' opened (inside tmux)"
|
|
120
|
+
session = name
|
|
121
|
+
subprocess.run(
|
|
122
|
+
["tmux", "new-session", "-d", "-s", session, "-c", str(root), "bash", str(script)],
|
|
123
|
+
check=True, timeout=15,
|
|
124
|
+
)
|
|
125
|
+
return True, f"detached tmux session '{session}' — attach: tmux attach -t {session}"
|
|
126
|
+
if backend == "herdr":
|
|
127
|
+
cmd = ["herdr", "tab", "create", "--cwd", str(root), "--label", name, "--", "bash", str(script)]
|
|
128
|
+
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=20)
|
|
129
|
+
if proc.returncode != 0:
|
|
130
|
+
return False, f"herdr tab create failed: {(proc.stderr or proc.stdout).strip()[:200]}"
|
|
131
|
+
return True, f"herdr tab '{name}' created"
|
|
132
|
+
if backend == "tuios":
|
|
133
|
+
session = os.environ.get("TUIOS_SESSION")
|
|
134
|
+
if not session:
|
|
135
|
+
return False, "tuios: not inside a tuios session ($TUIOS_SESSION unset); use tmux or herdr"
|
|
136
|
+
cmd = ["tuios", "new-window", "-s", session, name, "--no-focus", "--", "bash", str(script)]
|
|
137
|
+
subprocess.run(cmd, check=True, timeout=15)
|
|
138
|
+
return True, f"tuios window '{name}' opened in session {session}"
|
|
139
|
+
except FileNotFoundError as e:
|
|
140
|
+
return False, f"{backend} not found: {e.filename}"
|
|
141
|
+
except subprocess.CalledProcessError as e:
|
|
142
|
+
err = (getattr(e, "stderr", "") or "") or e.returncode
|
|
143
|
+
return False, f"{backend} exited {e.returncode}: {str(err)[:200]}"
|
|
144
|
+
except subprocess.TimeoutExpired:
|
|
145
|
+
return False, f"{backend} timed out"
|
|
146
|
+
return False, f"unknown backend {backend!r}"
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def resolve_backend(args_backend: str | None, env: dict, *, interactive: bool = True) -> tuple[str | None, bool]:
|
|
150
|
+
"""Returns (backend, changed).
|
|
151
|
+
|
|
152
|
+
Interactive whenever the config value is missing/default ('none') or not
|
|
153
|
+
installed — the user chooses in the CLI itself. Explicit --backend wins.
|
|
154
|
+
(None, True) with interactive=False means 'would ask' (dry-run).
|
|
155
|
+
"""
|
|
156
|
+
cfg = (env.get("agents", {}) or {}).get("backend", "")
|
|
157
|
+
installed = detect_harnesses()
|
|
158
|
+
pick = args_backend or cfg
|
|
159
|
+
if args_backend == "none":
|
|
160
|
+
return None, False
|
|
161
|
+
if pick and pick != "none" and pick in installed:
|
|
162
|
+
return pick, False
|
|
163
|
+
if not interactive:
|
|
164
|
+
return None, True
|
|
165
|
+
if not installed:
|
|
166
|
+
print(ui.colorize("No agent harness found (tmux/herdr/tuios). Printing the prompt instead.", ui.YELLOW))
|
|
167
|
+
return None, True
|
|
168
|
+
pick = choose_interactively("Which agent harness should rh spawn?", installed + (
|
|
169
|
+
[f"{b} (not on PATH)" for b in HARNESS_BINS if b not in installed]
|
|
170
|
+
), allow_none=True)
|
|
171
|
+
return pick, True
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def resolve_agent_cli(args_cli: str | None, env: dict, *, interactive: bool = True) -> tuple[str | None, bool]:
|
|
175
|
+
cfg = (env.get("agents", {}) or {}).get("cli", "")
|
|
176
|
+
installed = detect_agent_clis()
|
|
177
|
+
pick = args_cli or cfg
|
|
178
|
+
if pick and shutil.which(pick):
|
|
179
|
+
return pick, False
|
|
180
|
+
if not interactive:
|
|
181
|
+
return None, True
|
|
182
|
+
if not installed:
|
|
183
|
+
manual = input("No coding-agent CLI found (opencode/claude/codex/...). Enter command to run: ").strip()
|
|
184
|
+
return (manual or None), True
|
|
185
|
+
pick = choose_interactively("Which agent CLI should run the project?", installed, allow_none=True)
|
|
186
|
+
return pick, True
|