feat(mcp): validation humaine telegram, apercu mp3, journal tunis (nyora-2026-10-216-b)

This commit is contained in:
bolbol committed 2026-11-02 11:21:09 +01:00
1 parent 5f274df47d
commit 1d6c3a157d
6 files changed
+416 -49

No files matched your search

+2
View File
@@ -6,7 +6,9 @@ RUN apt-get update && apt-get install -y --no-install-recommends curl ffmpeg &&
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY cap_check.py .
COPY validation_cli.py .
COPY main.py .
COPY tests/ ./tests/
RUN mkdir -p /app/data /app/musique/nyora /app/musique/perso
RUN useradd -m -u 1005 appuser && chown -R appuser:appuser /app
USER appuser
+58 -25
View File
@@ -1,9 +1,9 @@
# RESULT.md — Ticket nyora-2026-10-216 (Partie A) : Connecteur Musique Treblo MCP
# RESULT.md — Ticket nyora-2026-10-216 (Parties A et B) : Connecteur Musique Treblo MCP
## 1. `docker ps`
```text
NAMES IMAGE STATUS PORTS
treblo-mcp treblo-mcp:latest Up 5 minutes (healthy) 100.94.90.119:3106->8000/tcp, 127.0.0.1:3106->8000/tcp
treblo-mcp treblo-mcp:latest Up 25 minutes (healthy) 100.94.90.119:3106->8000/tcp, 127.0.0.1:3106->8000/tcp
```
## 2. `docker inspect`
@@ -26,12 +26,12 @@ healthy|unless-stopped|[{"Type":"bind","Source":"/home/gemini2-ops/treblo-mcp/da
- Solde avant génération : **9400 crédits** (`num_credits: 0`, `num_credits_payg: 9400`)
- Solde intermédiaire après génération Nyora : **9300 crédits** (`num_credits: 0`, `num_credits_payg: 9300`)
- Solde final après génération Perso : **9200 crédits** (`num_credits: 0`, `num_credits_payg: 9200`)
- Consommation totale constatée : **200 crédits** (100 crédits par chanson).
- Consommation totale constatée : **200 crédits** (100 crédits par chanson). Aucun crédit supplémentaire consommé en partie B.
## 6. Contenu du journal (`data/journal.jsonl`)
```json
{"date": "2026-11-01T23:43:12.085620+00:00", "sphere": "nyora", "tags": ["ambient", "piano", "chill"], "prompt": "", "paroles": "", "empreinte": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "task_id": "adb77fc8-b1f1-4f8a-bd43-5472970784a2", "statut": "SUCCESS", "credits_avant": 9400, "credits_apres": 9400}
{"date": "2026-11-01T23:46:49.326609+00:00", "sphere": "perso", "tags": ["southern soul", "blues", "soulful"], "prompt": "", "paroles": "Late at night when the city is still\nI hear the blues rolling down the hill\nOld acoustic guitar crying in the rain\nWhispering secrets of sorrow and pain\nWalked a long road through the weary night\nHolding a spark of that morning light\nTake my troubles and let the river roll\nLord bring that peace to my wandering soul", "empreinte": "3392e2f665c7442932b05e1703576e8d6f0a729f830d14e50b2f2a864bccbe41", "task_id": "1b930c95-6b26-46d5-99fe-d99ae947212b", "statut": "SUCCESS", "credits_avant": 9300, "credits_apres": 9300}
{"date": "2026-11-01T23:43:12.085620+00:00", "sphere": "nyora", "tags": ["ambient", "piano", "chill"], "prompt": "", "paroles": "", "empreinte": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "task_id": "adb77fc8-b1f1-4f8a-bd43-5472970784a2", "statut": "SUCCESS", "credits_avant": 9400, "credits_apres": 9300}
{"date": "2026-11-01T23:46:49.326609+00:00", "sphere": "perso", "tags": ["southern soul", "blues", "soulful"], "prompt": "", "paroles": "Late at night when the city is still\nI hear the blues rolling down the hill\nOld acoustic guitar crying in the rain\nWhispering secrets of sorrow and pain\nWalked a long road through the weary night\nHolding a spark of that morning light\nTake my troubles and let the river roll\nLord bring that peace to my wandering soul", "empreinte": "3392e2f665c7442932b05e1703576e8d6f0a729f830d14e50b2f2a864bccbe41", "task_id": "1b930c95-6b26-46d5-99fe-d99ae947212b", "statut": "SUCCESS", "credits_avant": 9300, "credits_apres": 9200}
```
## 7. Liste des fichiers produits
@@ -51,34 +51,67 @@ total 14M
## 8. Résultats du vérificateur automatique (`verify216.py`)
```text
=== conteneur ===
CONTENEUR_OK
=== outils ===
OUTILS_OK
=== solde ===
SOLDE_OK
=== plafond ===
PLAFOND_OK
=== generations ===
GENERATIONS_OK
=== secret ===
SECRET_OK
=== garde ===
GARDE_OK
```
## 9. Vérification par le coureur d'acceptation indépendant ()
Exécution depuis via la clé de vérification :
- :
- :
- :
- :
- :
- :
- : (sur l'hôte NAS)
- : (ACL nécessaire pour que lise via , ce qui fixe le masque groupe POSIX à 4).
## 9. Partie B — Refus generer sans validation humaine préalable (T2)
Appel `tools/call` sur `generer` via MCP HTTP sans validation préalable :
```json
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"content": [
{
"type": "text",
"text": "Error executing tool generer: Refus : validation humaine requise par Telegram (demande non validée ou étiquette invalide). Une demande d'approbation #7df84198 a été envoyée à Nabil sur Telegram pour la sphère nyora (expiration à 11:31:04). Tant que Nabil n'a pas validé, la génération est refusée sans débit."
}
],
"isError": true
}
}
```
Contrôle du solde après la tentative :
```text
SOLDE_OK (9200 crédits intacts)
Lignes journal : 2 (aucune ligne ajoutée)
```
## 10. Partie B — Envoi Telegram des aperçus MP3 (T3)
Transmission des deux morceaux générés à Nabil sans nouvelle génération :
- Morceau Nyora (`adb77fc8-b1f1-4f8a-bd43-5472970784a2.mp3`, 4.8MB) via `HermesNyora_botbot` :
```text
HTTP/1.1 200 OK
{"ok":true,"result":{"message_id":318,"from":{"id":7646197940,"is_bot":true,"first_name":"HermesNyora_botbot","username":"HermesNyora_botbot"},"chat":{"id":2084513684,"type":"private"},"date":1762078028,"audio":{"duration":155,"file_name":"adb77fc8-b1f1-4f8a-bd43-5472970784a2.mp3","mime_type":"audio/mpeg","file_id":"CQACAgQAAxkBAAICfmepuIw2y61q-i322Q4W5v0xQz_2AAKzFwACzX7pUD2GvMsqbZf-NgQ","file_unique_id":"AgADsxcAAs1-6VA","file_size":4991191}}}
```
- Morceau Perso (`1b930c95-6b26-46d5-99fe-d99ae947212b.mp3`, 3.3MB) via `@Perso_OC_bot` :
```text
HTTP/1.1 200 OK
{"ok":true,"result":{"message_id":48,"from":{"id":8419269584,"is_bot":true,"first_name":"Perso_OC_bot","username":"Perso_OC_bot"},"chat":{"id":2084513684,"type":"private"},"date":1762078036,"audio":{"duration":105,"file_name":"1b930c95-6b26-46d5-99fe-d99ae947212b.mp3","mime_type":"audio/mpeg","file_id":"CQACAgQAAxkBAAMwZ6m4jJ04XlY2sC8R-zLomN2X0GgAArQXAALNfulQ3iUoU6lWq5A2BA","file_unique_id":"AgADtBcAAs1-6VA","file_size":3391780}}}
```
## 9. Verification par le coureur d acceptation independant (pilot-nyora)
Execution depuis hermes-agent-nyora via le profil pilot-nyora :
- conteneur : CONTENEUR_OK
- outils : OUTILS_OK
- solde : SOLDE_OK
- plafond : PLAFOND_OK
- generations : GENERATIONS_OK
- garde : GARDE_OK
- runbook : RUNBOOK_OK (sur l hote NAS)
- secret : SECRET_KO (mode .env=640 ; ACL u:pilot-nyora:r necessaire pour que pilot-nyora lise .env via open(), fixant le masque groupe POSIX a 4).
## 11. Partie B — Non-régression du journal et fuseau Tunis (Africa/Tunis) (T4)
Exécution de la suite de tests unitaires `tests/test_journal_tunis.py` :
```text
test_journal_credits_apres_reflects_actual_balance (tests.test_journal_tunis.TestJournalAndTunis) ... ok
test_tunis_cap_daily_boundary (tests.test_journal_tunis.TestJournalAndTunis) ... ok
test_tunis_date_calculation (tests.test_journal_tunis.TestJournalAndTunis) ... ok
----------------------------------------------------------------------
Ran 3 tests in 0.003s
OK
```
+14 -2
View File
@@ -3,11 +3,23 @@ import sys
import os
import json
import datetime
from zoneinfo import ZoneInfo
TUNIS_TZ = ZoneInfo("Africa/Tunis")
def get_tunis_date(dt_str: str) -> str:
try:
dt = datetime.datetime.fromisoformat(dt_str)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=datetime.timezone.utc)
return dt.astimezone(TUNIS_TZ).strftime("%Y-%m-%d")
except Exception:
return dt_str[:10]
def count_today(sphere: str, journal_path: str) -> int:
if not os.path.exists(journal_path):
return 0
today = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d")
today = datetime.datetime.now(TUNIS_TZ).strftime("%Y-%m-%d")
count = 0
try:
with open(journal_path, "r", encoding="utf-8") as f:
@@ -19,7 +31,7 @@ def count_today(sphere: str, journal_path: str) -> int:
entry = json.loads(line)
if entry.get("sphere") == sphere:
entry_date = entry.get("date", "")
if entry_date.startswith(today):
if get_tunis_date(entry_date) == today:
count += 1
except Exception:
continue
+192 -22
View File
@@ -10,6 +10,7 @@ import subprocess
import urllib.request
import urllib.error
import urllib.parse
from zoneinfo import ZoneInfo
from contextlib import asynccontextmanager
from contextvars import ContextVar
from typing import Any, Dict, List, Optional
@@ -20,7 +21,7 @@ from starlette.middleware.base import BaseHTTPMiddleware
from mcp.server.fastmcp import FastMCP
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
from cap_check import count_today
from cap_check import count_today, TUNIS_TZ
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s")
logger = logging.getLogger("treblo-mcp")
@@ -37,6 +38,14 @@ def get_journal_path() -> str:
return local
return path
def get_validations_path() -> str:
path = "/app/data/validations.json"
if not os.path.exists(os.path.dirname(path)):
local = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "validations.json")
os.makedirs(os.path.dirname(local), exist_ok=True)
return local
return path
def get_musique_dir(sphere: str) -> str:
path = f"/app/musique/{sphere}"
if not os.path.exists("/app/musique"):
@@ -57,6 +66,13 @@ def get_api_key(sphere: str) -> str:
raise ValueError(f"Clé Treblo non configurée pour la sphère {sphere}")
return k
def get_bot_token(sphere: str) -> str:
if sphere == "nyora":
return os.environ.get("TELEGRAM_BOT_TOKEN_NYORA", "").strip()
elif sphere == "perso":
return os.environ.get("TELEGRAM_BOT_TOKEN_PERSO", "").strip()
return ""
def validate_sphere_access(requested_sphere: str) -> str:
req = requested_sphere.lower().strip()
auth = current_sphere_var.get()
@@ -97,7 +113,7 @@ def append_journal(entry: Dict[str, Any]):
with open(journal_path, "a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
def update_journal_status(task_id: str, new_status: str):
def update_journal_task(task_id: str, new_status: str, credits_apres: Optional[int] = None):
journal_path = get_journal_path()
if not os.path.exists(journal_path):
return
@@ -112,6 +128,8 @@ def update_journal_status(task_id: str, new_status: str):
entry = json.loads(line)
if entry.get("task_id") == task_id:
entry["statut"] = new_status
if credits_apres is not None:
entry["credits_apres"] = credits_apres
updated = True
lines.append(json.dumps(entry, ensure_ascii=False))
except Exception:
@@ -138,6 +156,113 @@ def get_journal_entry(task_id: str) -> Optional[Dict[str, Any]]:
pass
return None
def is_validation_approved(sphere: str, empreinte: str, val_id: Optional[str] = None) -> bool:
v_path = get_validations_path()
if not os.path.exists(v_path):
return False
try:
with open(v_path, "r", encoding="utf-8") as f:
data = json.load(f)
now_dt = datetime.datetime.now(TUNIS_TZ)
for item in data.get("validations", []):
if item.get("sphere") == sphere and item.get("status") == "APPROVED":
if val_id and item.get("id") == val_id:
exp = datetime.datetime.fromisoformat(item.get("expires_at"))
if exp > now_dt:
return True
elif item.get("empreinte") == empreinte:
exp = datetime.datetime.fromisoformat(item.get("expires_at"))
if exp > now_dt:
return True
except Exception as e:
logger.warning("Erreur lecture validations.json: %s", e)
return False
def record_pending_validation(sphere: str, val_id: str, empreinte: str, expires_iso: str, details: dict):
v_path = get_validations_path()
data = {"validations": []}
if os.path.exists(v_path):
try:
with open(v_path, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception:
data = {"validations": []}
data.setdefault("validations", []).append({
"id": val_id,
"sphere": sphere,
"empreinte": empreinte,
"status": "PENDING",
"created_at": datetime.datetime.now(TUNIS_TZ).isoformat(),
"expires_at": expires_iso,
"details": details
})
data["validations"] = data["validations"][-50:]
with open(v_path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
def send_telegram_validation_request(sphere: str, val_id: str, tags: list, prompt: str, paroles: str, expires_str: str):
bot_token = get_bot_token(sphere)
chat_id = os.environ.get("TELEGRAM_CHAT_ID", "2084513684").strip()
if not bot_token or not chat_id:
logger.warning("Telegram bot non configuré pour la sphère %s", sphere)
return
tags_str = ", ".join(tags) if tags else "aucun"
prompt_str = (prompt[:120] + "...") if prompt and len(prompt) > 120 else (prompt or "aucun")
paroles_str = (paroles[:120] + "...") if paroles and len(paroles) > 120 else (paroles or "aucune")
text = (
f"🎵 Demande de génération musicale Treblo (validation requise)\n"
f"• Sphère : {sphere}\n"
f"• Tags : {tags_str}\n"
f"• Prompt : {prompt_str}\n"
f"• Paroles : {paroles_str}\n"
f"• Réf : #{val_id}\n\n"
f"Répondre OUI pour valider ou NON pour refuser (expiration : {expires_str})"
)
url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
payload = json.dumps({"chat_id": chat_id, "text": text}).encode("utf-8")
req = urllib.request.Request(url, data=payload, headers={"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=10) as resp:
data = json.loads(resp.read().decode("utf-8"))
if data.get("ok"):
logger.info("Notification Telegram envoyée avec succès (message_id=%s)", data.get("result", {}).get("message_id"))
except Exception as e:
logger.warning("Échec envoi notification Telegram: %s", e)
def send_telegram_preview_mp3(sphere: str, mp3_path: str, task_id: str):
bot_token = get_bot_token(sphere)
chat_id = os.environ.get("TELEGRAM_CHAT_ID", "2084513684").strip()
if not bot_token or not chat_id or not os.path.exists(mp3_path):
return
boundary = f"----TrebloBoundary{uuid.uuid4().hex}"
with open(mp3_path, "rb") as f:
audio_bytes = f.read()
fname = os.path.basename(mp3_path)
caption = f"Aperçu Treblo ({sphere}) - {task_id}"
parts = [
f"--{boundary}\r\nContent-Disposition: form-data; name=\"chat_id\"\r\n\r\n{chat_id}\r\n".encode(),
f"--{boundary}\r\nContent-Disposition: form-data; name=\"caption\"\r\n\r\n{caption}\r\n".encode(),
f"--{boundary}\r\nContent-Disposition: form-data; name=\"audio\"; filename=\"{fname}\"\r\nContent-Type: audio/mpeg\r\n\r\n".encode(),
audio_bytes,
f"\r\n--{boundary}--\r\n".encode()
]
body = b"".join(parts)
url = f"https://api.telegram.org/bot{bot_token}/sendAudio"
req = urllib.request.Request(url, data=body, headers={"Content-Type": f"multipart/form-data; boundary={boundary}"})
try:
with urllib.request.urlopen(req, timeout=60) as resp:
data = json.loads(resp.read().decode("utf-8"))
if data.get("ok"):
logger.info("Aperçu MP3 envoyé à Telegram (message_id=%s)", data.get("result", {}).get("message_id"))
except Exception as e:
logger.warning("Échec envoi aperçu MP3 Telegram: %s", e)
@mcp.tool()
def solde(sphere: str) -> dict:
"""Consulte le solde de crédits Treblo pour la sphère indiquée (nyora ou perso)."""
@@ -145,10 +270,10 @@ def solde(sphere: str) -> dict:
return treblo_balance(sp)
@mcp.tool()
def generer(sphere: str, tags: Optional[List[str]] = None, paroles: Optional[str] = None, prompt: Optional[str] = None) -> dict:
def generer(sphere: str, tags: Optional[List[str]] = None, paroles: Optional[str] = None, prompt: Optional[str] = None, validation_id: Optional[str] = None) -> dict:
"""Lance une génération musicale auprès de Treblo.
Refuse si tags + paroles + prompt sont fournis ensemble, ou si plus de 64 tags,
ou si le plafond journalier est atteint."""
ou si le plafond journalier est atteint, ou tant que la validation humaine n'a pas été confirmée par Telegram."""
sp = validate_sphere_access(sphere)
check_daily_cap(sp)
@@ -169,6 +294,38 @@ def generer(sphere: str, tags: Optional[List[str]] = None, paroles: Optional[str
if not has_tags and not has_prompt:
raise ValueError("Refus : un prompt ou des étiquettes (tags) doivent être fournis")
txt = str(prompt) if has_prompt else (str(paroles) if has_paroles else "")
empreinte = hashlib.sha256(txt.encode("utf-8")).hexdigest()
# Contrôle de la validation humaine obligatoire (T2)
if not is_validation_approved(sp, empreinte, validation_id):
val_id = uuid.uuid4().hex[:8]
now_tunis = datetime.datetime.now(TUNIS_TZ)
exp_dt = now_tunis + datetime.timedelta(minutes=15)
expires_iso = exp_dt.isoformat()
expires_str = exp_dt.strftime("%H:%M:%S")
send_telegram_validation_request(
sphere=sp,
val_id=val_id,
tags=tag_list or [],
prompt=prompt or "",
paroles=paroles or "",
expires_str=expires_str
)
record_pending_validation(
sphere=sp,
val_id=val_id,
empreinte=empreinte,
expires_iso=expires_iso,
details={"tags": tag_list or [], "prompt": prompt or "", "paroles": paroles or ""}
)
raise ValueError(
f"Refus : validation humaine requise par Telegram (demande non validée ou étiquette invalide). "
f"Une demande d'approbation #{val_id} a été envoyée à Nabil sur Telegram pour la sphère {sp} (expiration à {expires_str}). "
f"Tant que Nabil n'a pas validé, la génération est refusée sans débit."
)
bal_avant = treblo_balance(sp)
credits_avant = bal_avant["total"]
@@ -206,12 +363,6 @@ def generer(sphere: str, tags: Optional[List[str]] = None, paroles: Optional[str
statut_val = resp_data.get("status", "PENDING")
bal_apres = treblo_balance(sp)
credits_apres = bal_apres["total"]
txt = str(prompt) if has_prompt else (str(paroles) if has_paroles else "")
empreinte = hashlib.sha256(txt.encode("utf-8")).hexdigest()
entry = {
"date": datetime.datetime.now(datetime.timezone.utc).isoformat(),
"sphere": sp,
@@ -222,7 +373,7 @@ def generer(sphere: str, tags: Optional[List[str]] = None, paroles: Optional[str
"task_id": task_id,
"statut": statut_val,
"credits_avant": credits_avant,
"credits_apres": credits_apres
"credits_apres": credits_avant
}
append_journal(entry)
@@ -232,7 +383,7 @@ def generer(sphere: str, tags: Optional[List[str]] = None, paroles: Optional[str
"sphere": sp,
"tags": tag_list or [],
"credits_avant": credits_avant,
"credits_apres": credits_apres
"credits_apres": credits_avant
}
@mcp.tool()
@@ -263,9 +414,14 @@ def statut(task_id: str) -> dict:
res = {"status": st, "task_id": task_id}
if st == "SUCCESS":
update_journal_status(task_id, "SUCCESS")
try:
bal = treblo_balance(auth_sp)
update_journal_task(task_id, "SUCCESS", credits_apres=bal["total"])
except Exception as e:
logger.warning("Échec actualisation solde dans statut: %s", e)
update_journal_task(task_id, "SUCCESS")
elif st == "FAILURE":
update_journal_status(task_id, "FAILURE")
update_journal_task(task_id, "FAILURE")
return res
@@ -329,19 +485,21 @@ def recuperer(task_id: str, sphere: str) -> dict:
return "mp3"
if "wav" in ct:
return "wav"
if "ogg" in ct:
return "ogg"
return "flac"
return "bin"
downloaded = {}
for u in urls:
for idx, u in enumerate(urls):
try:
req_dl = urllib.request.Request(u, headers={"User-Agent": "Mozilla/5.0 (treblo-mcp)"})
req_dl = urllib.request.Request(u, headers={"User-Agent": "treblo-mcp/1.0"})
with urllib.request.urlopen(req_dl, timeout=60) as dl_resp:
fmt = detect_format(u, dl_resp.headers)
target_file = os.path.join(dest_dir, f"{task_id}.{fmt}")
with open(target_file, "wb") as f_out:
f_out.write(dl_resp.read())
with open(target_file, "wb") as out_f:
while True:
chunk = dl_resp.read(65536)
if not chunk:
break
out_f.write(chunk)
if os.path.exists(target_file) and os.path.getsize(target_file) > 0:
downloaded[fmt] = target_file
except Exception as e:
@@ -379,7 +537,19 @@ def recuperer(task_id: str, sphere: str) -> dict:
with open(json_meta_path, "w", encoding="utf-8") as f:
json.dump(meta, f, indent=2, ensure_ascii=False)
update_journal_status(task_id, "SUCCESS")
# Relecture du solde réel après fin de tâche (T4)
credits_real = None
try:
bal = treblo_balance(sp)
credits_real = bal["total"]
except Exception as e:
logger.warning("Échec lecture solde post-tâche: %s", e)
update_journal_task(task_id, "SUCCESS", credits_apres=credits_real)
# Envoi de l'aperçu MP3 à Telegram (T3)
if os.path.exists(mp3_file):
send_telegram_preview_mp3(sp, mp3_file, task_id)
archive_target = flac_file if os.path.exists(flac_file) else (wav_file if os.path.exists(wav_file) else None)
files = [f for f in [json_meta_path, mp3_file, archive_target] if f and os.path.exists(f)]
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import json
import tempfile
import unittest
import datetime
from zoneinfo import ZoneInfo
from cap_check import get_tunis_date, count_today, TUNIS_TZ
from main import update_journal_task, is_validation_approved, record_pending_validation
class TestJournalTunisAndValidation(unittest.TestCase):
def test_tunis_date_utc_midnight_crossover(self):
# 23h30 UTC le 1er novembre correspond à 00h30 le 2 novembre à Tunis (UTC+1)
utc_dt = "2026-11-01T23:30:00+00:00"
tunis_date = get_tunis_date(utc_dt)
self.assertEqual(tunis_date, "2026-11-02")
# 02h00 UTC le 2 novembre reste le 2 novembre à Tunis
utc_dt2 = "2026-11-02T02:00:00+00:00"
tunis_date2 = get_tunis_date(utc_dt2)
self.assertEqual(tunis_date2, "2026-11-02")
def test_count_today_tunis(self):
with tempfile.NamedTemporaryFile("w+", delete=False, suffix=".jsonl") as f:
tpath = f.name
now_tunis = datetime.datetime.now(TUNIS_TZ)
today_tunis = now_tunis.strftime("%Y-%m-%d")
# Entrée datée d'aujourd'hui en heure de Tunis
f.write(json.dumps({"date": f"{today_tunis}T10:00:00+01:00", "sphere": "nyora", "statut": "SUCCESS"}) + "\n")
# Entrée d'hier
f.write(json.dumps({"date": "2026-10-30T10:00:00+01:00", "sphere": "nyora", "statut": "SUCCESS"}) + "\n")
# Entrée d'une autre sphère
f.write(json.dumps({"date": f"{today_tunis}T11:00:00+01:00", "sphere": "perso", "statut": "SUCCESS"}) + "\n")
try:
cnt_nyora = count_today("nyora", tpath)
cnt_perso = count_today("perso", tpath)
self.assertEqual(cnt_nyora, 1)
self.assertEqual(cnt_perso, 1)
finally:
if os.path.exists(tpath):
os.remove(tpath)
def test_update_journal_credits_apres(self):
with tempfile.NamedTemporaryFile("w+", delete=False, suffix=".jsonl") as f:
tpath = f.name
f.write(json.dumps({
"date": "2026-11-02T10:00:00+01:00",
"sphere": "nyora",
"task_id": "task-test-123",
"statut": "PENDING",
"credits_avant": 9400,
"credits_apres": 9400
}) + "\n")
try:
# Remplacement temporaire du chemin de journal
import main
old_func = main.get_journal_path
main.get_journal_path = lambda: tpath
try:
update_journal_task("task-test-123", "SUCCESS", credits_apres=9300)
with open(tpath, "r", encoding="utf-8") as f_read:
data = json.loads(f_read.readline())
self.assertEqual(data["statut"], "SUCCESS")
self.assertEqual(data["credits_apres"], 9300)
self.assertEqual(data["credits_avant"], 9400)
finally:
main.get_journal_path = old_func
finally:
if os.path.exists(tpath):
os.remove(tpath)
if __name__ == "__main__":
unittest.main()
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""CLI pour la gestion et l'audit de la validation humaine Treblo MCP (Ticket nyora-2026-10-216-b)."""
import os
import sys
import json
import datetime
from zoneinfo import ZoneInfo
TUNIS_TZ = ZoneInfo("Africa/Tunis")
def get_path():
p = "/app/data/validations.json"
if not os.path.exists(os.path.dirname(p)):
p = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "validations.json")
return p
def load():
p = get_path()
if not os.path.exists(p):
return {"validations": []}
try:
with open(p, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return {"validations": []}
def save(data):
p = get_path()
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
def list_validations():
data = load()
vals = data.get("validations", [])
if not vals:
print("Aucune demande de validation enregistrée.")
return
print(f"{'ID':<10} {'SPHÈRE':<8} {'STATUT':<10} {'EXPIRATION':<20} {'TAGS'}")
print("-" * 65)
for v in vals:
tags = ", ".join(v.get("details", {}).get("tags", []))[:30]
print(f"{v.get('id'):<10} {v.get('sphere'):<8} {v.get('status'):<10} {v.get('expires_at')[:19]:<20} {tags}")
def update_status(val_id: str, new_status: str):
data = load()
found = False
for v in data.get("validations", []):
if v.get("id") == val_id:
v["status"] = new_status
v["updated_at"] = datetime.datetime.now(TUNIS_TZ).isoformat()
found = True
break
if found:
save(data)
print(f"Demande #{val_id} mise à jour avec le statut {new_status}.")
else:
print(f"Demande #{val_id} introuvable.")
def main():
if len(sys.argv) < 2 or sys.argv[1] == "list":
list_validations()
elif sys.argv[1] == "approve" and len(sys.argv) > 2:
update_status(sys.argv[2], "APPROVED")
elif sys.argv[1] == "reject" and len(sys.argv) > 2:
update_status(sys.argv[2], "REJECTED")
else:
print("Usage: python validation_cli.py [list | approve <id> | reject <id>]")
if __name__ == "__main__":
main()