feat(ralph): unified slash commands /p /a /l /k cu legacy aliases
Restructurează comenzile Ralph într-un dispatcher unificat (_try_ralph_dispatch) care suportă atât comenzile noi scurte (/p /a /l /k) cât și aliasurile legacy (!propose !approve !status !stop). Pe Discord adaugă slash commands native cu autocomplete dinamic pentru pending (/a) și running (/k). Pe Telegram apar în meniul /. WhatsApp le parsează ca text plain. Activează cron jobs morning-report (08:30) și evening-report (21:00) și adaugă night-execute (23:00) pentru execuția autonomă a proiectelor aprobate. Foundation pentru W1 din planul "Echo Core conversational planning agent". Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -16,7 +16,14 @@ from src.claude_session import (
|
||||
VALID_MODELS,
|
||||
)
|
||||
from src.fast_commands import dispatch as fast_dispatch
|
||||
from src.router import route_message
|
||||
from src.router import (
|
||||
route_message,
|
||||
_ralph_propose,
|
||||
_ralph_approve,
|
||||
_ralph_status,
|
||||
_ralph_stop,
|
||||
_load_approved_tasks,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("echo-core.discord")
|
||||
_security_log = logging.getLogger("echo-core.security")
|
||||
@@ -150,6 +157,12 @@ def create_bot(config: Config) -> discord.Client:
|
||||
"`/heartbeat` — Health checks",
|
||||
"`/restart` — Restart bot (owner)",
|
||||
"",
|
||||
"**Ralph (autonomous projects)**",
|
||||
"`/p <slug> <description>` — Propose new project",
|
||||
"`/a [slug]` — Approve for tonight (autocomplete)",
|
||||
"`/l` — List projects status",
|
||||
"`/k <slug>` — Stop a running project (autocomplete)",
|
||||
"",
|
||||
"**Admin**",
|
||||
"`/setup` — Claim ownership",
|
||||
"`/channel add <alias>` — Register channel",
|
||||
@@ -886,6 +899,68 @@ def create_bot(config: Config) -> discord.Client:
|
||||
f"Error reading logs: {e}", ephemeral=True
|
||||
)
|
||||
|
||||
# --- Ralph commands (autonomous project execution) ---
|
||||
|
||||
async def _autocomplete_by_status(
|
||||
interaction: discord.Interaction, current: str, statuses: tuple[str, ...]
|
||||
) -> list[app_commands.Choice[str]]:
|
||||
try:
|
||||
data = _load_approved_tasks()
|
||||
except Exception:
|
||||
return []
|
||||
current_low = (current or "").lower()
|
||||
choices: list[app_commands.Choice[str]] = []
|
||||
for p in data.get("projects", []):
|
||||
if p.get("status") not in statuses:
|
||||
continue
|
||||
name = p.get("name", "")
|
||||
if current_low and current_low not in name.lower():
|
||||
continue
|
||||
desc = (p.get("description") or "").strip()
|
||||
label = f"{name} — {desc}"[:100] if desc else name
|
||||
choices.append(app_commands.Choice(name=label, value=name))
|
||||
if len(choices) >= 25:
|
||||
break
|
||||
return choices
|
||||
|
||||
async def _ralph_autocomplete_pending(
|
||||
interaction: discord.Interaction, current: str
|
||||
) -> list[app_commands.Choice[str]]:
|
||||
return await _autocomplete_by_status(interaction, current, ("pending",))
|
||||
|
||||
async def _ralph_autocomplete_running(
|
||||
interaction: discord.Interaction, current: str
|
||||
) -> list[app_commands.Choice[str]]:
|
||||
return await _autocomplete_by_status(interaction, current, ("running", "approved"))
|
||||
|
||||
@tree.command(name="p", description="Propose new Ralph project")
|
||||
@app_commands.describe(slug="Project slug (e.g. game-library)", description="Short description of what to do")
|
||||
async def ralph_p(
|
||||
interaction: discord.Interaction, slug: str, description: str
|
||||
) -> None:
|
||||
await interaction.response.send_message(_ralph_propose(slug, description))
|
||||
|
||||
@tree.command(name="a", description="Approve Ralph project for tonight (no slug = list pending)")
|
||||
@app_commands.describe(slug="Project slug to approve (leave empty to list pending)")
|
||||
@app_commands.autocomplete(slug=_ralph_autocomplete_pending)
|
||||
async def ralph_a(
|
||||
interaction: discord.Interaction, slug: str | None = None
|
||||
) -> None:
|
||||
slugs = [slug] if slug else []
|
||||
await interaction.response.send_message(_ralph_approve(slugs))
|
||||
|
||||
@tree.command(name="l", description="List Ralph projects status")
|
||||
async def ralph_l(interaction: discord.Interaction) -> None:
|
||||
await interaction.response.send_message(_ralph_status())
|
||||
|
||||
@tree.command(name="k", description="Stop a running Ralph project")
|
||||
@app_commands.describe(slug="Project slug to stop")
|
||||
@app_commands.autocomplete(slug=_ralph_autocomplete_running)
|
||||
async def ralph_k(
|
||||
interaction: discord.Interaction, slug: str
|
||||
) -> None:
|
||||
await interaction.response.send_message(_ralph_stop(slug))
|
||||
|
||||
# --- Events ---
|
||||
|
||||
@client.event
|
||||
|
||||
@@ -22,7 +22,13 @@ from src.claude_session import (
|
||||
VALID_MODELS,
|
||||
)
|
||||
from src.fast_commands import dispatch as fast_dispatch
|
||||
from src.router import route_message
|
||||
from src.router import (
|
||||
route_message,
|
||||
_ralph_propose,
|
||||
_ralph_approve,
|
||||
_ralph_status,
|
||||
_ralph_stop,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("echo-core.telegram")
|
||||
_security_log = logging.getLogger("echo-core.security")
|
||||
@@ -141,6 +147,12 @@ async def cmd_help(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
"/logs [N] — Log lines",
|
||||
"/doctor — Diagnostics",
|
||||
"/heartbeat — Health checks",
|
||||
"",
|
||||
"*Ralph (autonomous projects)*",
|
||||
"/p <slug> <descriere> — Propose new project",
|
||||
"/a [slug] — Approve for tonight (no slug = list pending)",
|
||||
"/l — List projects status",
|
||||
"/k <slug> — Stop a running project",
|
||||
]
|
||||
await update.message.reply_text("\n".join(lines), parse_mode="Markdown")
|
||||
|
||||
@@ -299,6 +311,52 @@ async def cmd_register(update: Update, context: ContextTypes.DEFAULT_TYPE) -> No
|
||||
)
|
||||
|
||||
|
||||
# --- Ralph commands (autonomous project execution) ---
|
||||
|
||||
|
||||
async def cmd_ralph_p(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
"""/p <slug> <descriere> — propune proiect Ralph."""
|
||||
args = list(context.args or [])
|
||||
if len(args) < 2:
|
||||
await update.message.reply_text(
|
||||
"Folosire: /p <slug> <descriere>\nEx: /p roa2web Homepage redesign cu hero section"
|
||||
)
|
||||
return
|
||||
slug = args[0]
|
||||
description = " ".join(args[1:])
|
||||
result = await asyncio.to_thread(_ralph_propose, slug, description)
|
||||
await update.message.reply_text(result)
|
||||
|
||||
|
||||
async def cmd_ralph_a(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
"""/a [slug] — aprobă proiect (fără arg = listă pending)."""
|
||||
args = list(context.args or [])
|
||||
slugs: list[str] = []
|
||||
if args:
|
||||
for a in args:
|
||||
slugs.extend(s.strip() for s in a.replace(",", " ").split() if s.strip())
|
||||
result = await asyncio.to_thread(_ralph_approve, slugs)
|
||||
await update.message.reply_text(result)
|
||||
|
||||
|
||||
async def cmd_ralph_l(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
"""/l — status proiecte Ralph."""
|
||||
args = list(context.args or [])
|
||||
filter_slug = args[0].lower() if args else None
|
||||
result = await asyncio.to_thread(_ralph_status, filter_slug)
|
||||
await update.message.reply_text(result)
|
||||
|
||||
|
||||
async def cmd_ralph_k(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
"""/k <slug> — oprește proiect Ralph."""
|
||||
args = list(context.args or [])
|
||||
if not args:
|
||||
await update.message.reply_text("Folosire: /k <slug>")
|
||||
return
|
||||
result = await asyncio.to_thread(_ralph_stop, args[0])
|
||||
await update.message.reply_text(result)
|
||||
|
||||
|
||||
# --- Fast command handlers ---
|
||||
|
||||
|
||||
@@ -529,6 +587,12 @@ def create_telegram_bot(config: Config, token: str) -> Application:
|
||||
app.add_handler(CommandHandler("register", cmd_register))
|
||||
app.add_handler(CallbackQueryHandler(callback_model, pattern="^model:"))
|
||||
|
||||
# Ralph commands
|
||||
app.add_handler(CommandHandler("p", cmd_ralph_p))
|
||||
app.add_handler(CommandHandler("a", cmd_ralph_a))
|
||||
app.add_handler(CommandHandler("l", cmd_ralph_l))
|
||||
app.add_handler(CommandHandler("k", cmd_ralph_k))
|
||||
|
||||
# Fast commands
|
||||
app.add_handler(CommandHandler("email", cmd_email))
|
||||
app.add_handler(CommandHandler("emailsend", cmd_emailsend))
|
||||
@@ -579,6 +643,10 @@ def create_telegram_bot(config: Config, token: str) -> Application:
|
||||
BotCommand("logs", "Show log lines"),
|
||||
BotCommand("doctor", "Diagnostics"),
|
||||
BotCommand("heartbeat", "Health checks"),
|
||||
BotCommand("p", "Ralph: propose new project"),
|
||||
BotCommand("a", "Ralph: approve project for tonight"),
|
||||
BotCommand("l", "Ralph: list projects status"),
|
||||
BotCommand("k", "Ralph: stop running project"),
|
||||
])
|
||||
|
||||
app.post_init = post_init
|
||||
|
||||
209
src/router.py
209
src/router.py
@@ -52,18 +52,10 @@ def route_message(
|
||||
"""
|
||||
text = text.strip()
|
||||
|
||||
# Ralph commands (!approve, !status, !stop, !propose)
|
||||
if text.lower().startswith("!approve ") or text.lower() == "!approve":
|
||||
return _ralph_approve(text), True
|
||||
|
||||
if text.lower() == "!status" or text.lower().startswith("!status "):
|
||||
return _ralph_status(text), True
|
||||
|
||||
if text.lower().startswith("!stop "):
|
||||
return _ralph_stop(text), True
|
||||
|
||||
if text.lower().startswith("!propose "):
|
||||
return _ralph_propose(text), True
|
||||
# Ralph commands — short form (/p /a /l /k) and legacy aliases (!propose !approve !status !stop)
|
||||
ralph_response = _try_ralph_dispatch(text)
|
||||
if ralph_response is not None:
|
||||
return ralph_response, True
|
||||
|
||||
# Text-based commands (not slash commands — these work in any adapter)
|
||||
if text.lower() == "/clear":
|
||||
@@ -168,81 +160,146 @@ def _save_approved_tasks(data: dict) -> None:
|
||||
APPROVED_TASKS_FILE.write_text(json.dumps(data, indent=2, ensure_ascii=False))
|
||||
|
||||
|
||||
def _ralph_approve(text: str) -> str:
|
||||
"""!approve P1,P2 sau !approve roa2web — aprobă proiecte pentru night-execute."""
|
||||
parts = text.split(None, 1)
|
||||
if len(parts) < 2:
|
||||
data = _load_approved_tasks()
|
||||
RALPH_CMDS = {
|
||||
"propose": ("/p", "!propose"),
|
||||
"approve": ("/a", "!approve"),
|
||||
"list": ("/l", "!status"),
|
||||
"stop": ("/k", "!stop"),
|
||||
}
|
||||
|
||||
|
||||
def _try_ralph_dispatch(text: str) -> str | None:
|
||||
"""Parse and dispatch Ralph commands. Returns response string or None if no match."""
|
||||
low = text.lower()
|
||||
first = low.split(None, 1)[0] if low else ""
|
||||
|
||||
if first in ("/p", "!propose"):
|
||||
parts = text.split(None, 2)
|
||||
if len(parts) < 3:
|
||||
return "Folosire: /p <slug> <descriere>\nEx: /p roa2web Homepage redesign cu hero section"
|
||||
return _ralph_propose(parts[1].strip(), parts[2].strip())
|
||||
|
||||
if first in ("/a", "!approve"):
|
||||
parts = text.split(None, 1)
|
||||
slugs = []
|
||||
if len(parts) > 1:
|
||||
slugs = [s.strip() for s in parts[1].replace(",", " ").split() if s.strip()]
|
||||
return _ralph_approve(slugs)
|
||||
|
||||
if first in ("/l", "!status"):
|
||||
parts = text.split(None, 1)
|
||||
filter_slug = parts[1].strip().lower() if len(parts) > 1 else None
|
||||
return _ralph_status(filter_slug)
|
||||
|
||||
if first in ("/k", "!stop"):
|
||||
parts = text.split(None, 1)
|
||||
if len(parts) < 2:
|
||||
return "Folosire: /k <slug>"
|
||||
return _ralph_stop(parts[1].strip())
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _ralph_propose(slug: str, description: str) -> str:
|
||||
"""Adaugă un proiect cu status pending în approved-tasks.json."""
|
||||
data = _load_approved_tasks()
|
||||
|
||||
for p in data["projects"]:
|
||||
if p["name"].lower() == slug.lower():
|
||||
return f"Proiectul '{slug}' există deja cu status: {p.get('status', 'unknown')}."
|
||||
|
||||
data["projects"].append({
|
||||
"name": slug,
|
||||
"description": description,
|
||||
"status": "pending",
|
||||
"proposed_at": datetime.now(timezone.utc).isoformat(),
|
||||
"approved_at": None,
|
||||
"started_at": None,
|
||||
"pid": None,
|
||||
})
|
||||
_save_approved_tasks(data)
|
||||
return f"📋 Adăugat: {slug}\n └ {description}\n\nAprobă cu: /a {slug}"
|
||||
|
||||
|
||||
def _ralph_approve(slugs: list[str]) -> str:
|
||||
"""Aprobă unul sau mai multe proiecte. Listă goală = listează pending."""
|
||||
data = _load_approved_tasks()
|
||||
|
||||
if not slugs:
|
||||
pending = [p for p in data["projects"] if p.get("status") == "pending"]
|
||||
if not pending:
|
||||
return "Niciun proiect pending. Folosește !propose <nume> <descriere> pentru a adăuga."
|
||||
lines = [f"Proiecte pending (aprobă cu !approve <nume>):"]
|
||||
return "Niciun proiect pending. Adaugă cu /p <slug> <descriere>."
|
||||
lines = ["📋 Proiecte pending (aprobă cu /a <slug>):"]
|
||||
for p in pending:
|
||||
lines.append(f" - {p['name']}: {p['description'][:60]}")
|
||||
lines.append(f" • {p['name']}")
|
||||
lines.append(f" └ {p['description'][:80]}")
|
||||
return "\n".join(lines)
|
||||
|
||||
names_raw = parts[1].strip()
|
||||
names = [n.strip() for n in names_raw.replace(",", " ").split() if n.strip()]
|
||||
approved_info: list[tuple[str, str]] = []
|
||||
not_found: list[str] = []
|
||||
|
||||
data = _load_approved_tasks()
|
||||
approved = []
|
||||
not_found = []
|
||||
|
||||
for name in names:
|
||||
for slug in slugs:
|
||||
found = False
|
||||
for p in data["projects"]:
|
||||
if p["name"].lower() == name.lower():
|
||||
if p["name"].lower() == slug.lower():
|
||||
p["status"] = "approved"
|
||||
p["approved_at"] = datetime.now(timezone.utc).isoformat()
|
||||
approved.append(p["name"])
|
||||
approved_info.append((p["name"], p.get("description", "")))
|
||||
found = True
|
||||
break
|
||||
if not found:
|
||||
not_found.append(name)
|
||||
not_found.append(slug)
|
||||
|
||||
if not_found:
|
||||
return f"Nu am găsit proiectele: {', '.join(not_found)}. Verifică !status pentru lista completă."
|
||||
return f"Nu am găsit: {', '.join(not_found)}. Verifică /l pentru lista completă."
|
||||
|
||||
_save_approved_tasks(data)
|
||||
names_str = ", ".join(approved)
|
||||
return f"✅ Aprobat pentru tonight: {names_str}\nNight-execute rulează la 23:00 și va implementa stories autonom."
|
||||
lines = ["✅ Aprobat pentru tonight:"]
|
||||
for name, desc in approved_info:
|
||||
lines.append(f" • {name}")
|
||||
lines.append(f" └ {desc[:80]}")
|
||||
lines.append("\nNight-execute rulează la 23:00 și implementează stories autonom.")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _ralph_status(text: str) -> str:
|
||||
"""!status sau !status <proiect> — status Ralph pentru proiecte."""
|
||||
parts = text.split(None, 1)
|
||||
filter_name = parts[1].strip().lower() if len(parts) > 1 else None
|
||||
|
||||
def _ralph_status(filter_slug: str | None = None) -> str:
|
||||
"""Status Ralph pentru proiecte. Optional filter pe slug."""
|
||||
data = _load_approved_tasks()
|
||||
projects = data.get("projects", [])
|
||||
|
||||
if filter_name:
|
||||
projects = [p for p in projects if filter_name in p["name"].lower()]
|
||||
if filter_slug:
|
||||
projects = [p for p in projects if filter_slug in p["name"].lower()]
|
||||
|
||||
if not projects:
|
||||
return "Niciun proiect în approved-tasks.json. Adaugă cu !propose."
|
||||
return "Niciun proiect. Adaugă cu /p <slug> <descriere>."
|
||||
|
||||
lines = ["📊 Status proiecte Ralph:"]
|
||||
status_labels = {
|
||||
"approved": "⏳ aștept 23:00",
|
||||
"pending": "📋 pending",
|
||||
"complete": "✅ complet",
|
||||
"failed": "❌ eșuat",
|
||||
"stopped": "⏹ oprit",
|
||||
}
|
||||
|
||||
lines = ["📊 Proiecte Ralph:"]
|
||||
for p in projects:
|
||||
status = p.get("status", "unknown")
|
||||
name = p["name"]
|
||||
desc = p.get("description", "")
|
||||
pid = p.get("pid")
|
||||
started = p.get("started_at", "")[:16] if p.get("started_at") else "-"
|
||||
started = p.get("started_at", "")[:16].replace("T", " ") if p.get("started_at") else "-"
|
||||
|
||||
# Verifică dacă procesul mai rulează
|
||||
if pid and status == "running":
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
running_indicator = f"🟢 PID {pid}"
|
||||
indicator = f"🟢 PID {pid}"
|
||||
except (ProcessLookupError, PermissionError):
|
||||
running_indicator = "🔴 PID mort"
|
||||
indicator = "🔴 PID mort"
|
||||
p["status"] = "stopped"
|
||||
_save_approved_tasks(data)
|
||||
else:
|
||||
running_indicator = {"approved": "⏳ aștept 23:00", "pending": "📋 pending",
|
||||
"complete": "✅ complet", "failed": "❌ eșuat", "stopped": "⏹ oprit"}.get(status, status)
|
||||
indicator = status_labels.get(status, status)
|
||||
|
||||
# Stories complete din prd.json
|
||||
prd_path = Path(f"/home/moltbot/workspace/{name}/scripts/ralph/prd.json")
|
||||
stories_info = ""
|
||||
if prd_path.exists():
|
||||
@@ -250,26 +307,24 @@ def _ralph_status(text: str) -> str:
|
||||
prd = json.loads(prd_path.read_text())
|
||||
total = len(prd.get("userStories", []))
|
||||
done = sum(1 for s in prd.get("userStories", []) if s.get("passes"))
|
||||
stories_info = f" | Stories: {done}/{total}"
|
||||
stories_info = f" | {done}/{total} stories"
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
lines.append(f" {name}: {running_indicator}{stories_info} | Start: {started}")
|
||||
lines.append(f"\n {name} {indicator}{stories_info} | Start: {started}")
|
||||
if desc:
|
||||
lines.append(f" └ {desc[:80]}")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _ralph_stop(text: str) -> str:
|
||||
"""!stop <proiect> — oprește Ralph loop pentru un proiect."""
|
||||
parts = text.split(None, 1)
|
||||
if len(parts) < 2:
|
||||
return "Folosire: !stop <nume-proiect>"
|
||||
|
||||
name = parts[1].strip()
|
||||
def _ralph_stop(slug: str) -> str:
|
||||
"""Oprește Ralph loop (SIGTERM) pentru un proiect."""
|
||||
data = _load_approved_tasks()
|
||||
|
||||
for p in data["projects"]:
|
||||
if p["name"].lower() == name.lower():
|
||||
if p["name"].lower() == slug.lower():
|
||||
desc = p.get("description", "")
|
||||
pid = p.get("pid")
|
||||
if pid:
|
||||
try:
|
||||
@@ -277,45 +332,17 @@ def _ralph_stop(text: str) -> str:
|
||||
p["status"] = "stopped"
|
||||
p["stopped_at"] = datetime.now(timezone.utc).isoformat()
|
||||
_save_approved_tasks(data)
|
||||
return f"⏹ Ralph oprit pentru {name} (PID {pid} terminat)."
|
||||
return f"⏹ Oprit: {p['name']} (PID {pid})\n └ {desc[:80]}"
|
||||
except ProcessLookupError:
|
||||
p["status"] = "stopped"
|
||||
_save_approved_tasks(data)
|
||||
return f"PID {pid} nu mai rula pentru {name}. Status actualizat."
|
||||
return f"PID {pid} nu mai rula pentru {p['name']}. Status actualizat."
|
||||
except PermissionError:
|
||||
return f"❌ Nu am permisiune să opresc PID {pid}."
|
||||
else:
|
||||
return f"{name} nu are un PID activ (status: {p.get('status', 'unknown')})."
|
||||
return f"{p['name']} nu are PID activ (status: {p.get('status', 'unknown')})."
|
||||
|
||||
return f"Proiect '{name}' nu găsit în approved-tasks.json."
|
||||
|
||||
|
||||
def _ralph_propose(text: str) -> str:
|
||||
"""!propose <nume> <descriere> — adaugă un proiect pentru aprobare."""
|
||||
parts = text.split(None, 2)
|
||||
if len(parts) < 3:
|
||||
return "Folosire: !propose <nume-proiect> <descriere scurtă>\nEx: !propose roa2web Homepage redesign cu hero section și animații"
|
||||
|
||||
name = parts[1].strip()
|
||||
description = parts[2].strip()
|
||||
|
||||
data = _load_approved_tasks()
|
||||
|
||||
for p in data["projects"]:
|
||||
if p["name"].lower() == name.lower():
|
||||
return f"Proiectul '{name}' există deja cu status: {p.get('status', 'unknown')}."
|
||||
|
||||
data["projects"].append({
|
||||
"name": name,
|
||||
"description": description,
|
||||
"status": "pending",
|
||||
"proposed_at": datetime.now(timezone.utc).isoformat(),
|
||||
"approved_at": None,
|
||||
"started_at": None,
|
||||
"pid": None
|
||||
})
|
||||
_save_approved_tasks(data)
|
||||
return f"📋 Adăugat: {name}\n{description}\n\nAprobă cu: !approve {name}"
|
||||
return f"Proiect '{slug}' nu găsit. Verifică /l pentru lista completă."
|
||||
|
||||
|
||||
def _get_channel_config(channel_id: str) -> dict | None:
|
||||
|
||||
Reference in New Issue
Block a user