feat(treblo): validation durcie, usage unique, 5 outils, code 6 chiffres et tests (ticket nyora-2026-10-216-c)

This commit is contained in:
bolbol committed 2026-11-02 12:02:35 +01:00
1 parent 1d6c3a157d
commit a4cbda385c
4 files changed
+490 -31

No files matched your search

+167 -25
View File
@@ -3,6 +3,7 @@ import os
import json
import hmac
import uuid
import secrets
import logging
import hashlib
import datetime
@@ -46,6 +47,14 @@ def get_validations_path() -> str:
return local
return path
def get_envois_path() -> str:
path = "/app/data/envois.jsonl"
if not os.path.exists(os.path.dirname(path)):
local = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "envois.jsonl")
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"):
@@ -76,10 +85,17 @@ def get_bot_token(sphere: str) -> str:
def validate_sphere_access(requested_sphere: str) -> str:
req = requested_sphere.lower().strip()
auth = current_sphere_var.get()
if req != auth:
if auth and req != auth:
raise ValueError(f"Refus explicite : le jeton de la sphère {auth} ne peut pas agir sur la sphère {req}")
return req
def compute_empreinte(sphere: str, tags: Optional[List[str]], prompt: Optional[str], paroles: Optional[str]) -> str:
s_tags = sorted([str(t).strip() for t in (tags or []) if str(t).strip()])
p_prompt = (str(prompt).strip() if prompt else "")
p_paroles = (str(paroles).strip() if paroles else "")
canonical = f"{sphere.lower().strip()}|{','.join(s_tags)}|{p_prompt}|{p_paroles}"
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def treblo_balance(sphere: str) -> Dict[str, Any]:
key = get_api_key(sphere)
req = urllib.request.Request("https://api.treblo.com/v1/credits/balance", headers={"Authorization": f"Bearer {key}"})
@@ -156,6 +172,50 @@ def get_journal_entry(task_id: str) -> Optional[Dict[str, Any]]:
pass
return None
def log_envoi(task_id: str, sphere: str, message_id: int):
path = get_envois_path()
entry = {
"type": "apercu_mp3",
"task_id": task_id,
"sphere": sphere,
"message_id": int(message_id),
"date": datetime.datetime.now(datetime.timezone.utc).isoformat()
}
with open(path, "a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
def consume_approved_validation(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)
updated = False
consumed = False
for item in data.get("validations", []):
if item.get("sphere") == sphere and item.get("status") == "APPROVED":
match = (val_id and item.get("id") == val_id) or (not val_id and item.get("empreinte") == empreinte)
if match:
exp = datetime.datetime.fromisoformat(item.get("expires_at"))
if exp > now_dt:
item["status"] = "USED"
item["used_at"] = now_dt.isoformat()
consumed = True
updated = True
break
else:
item["status"] = "EXPIRED"
updated = True
if updated:
with open(v_path, "w", encoding="utf-8") as fw:
json.dump(data, fw, indent=2, ensure_ascii=False)
return consumed
except Exception as e:
logger.warning("Erreur lecture validations.json: %s", e)
return False
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):
@@ -166,19 +226,16 @@ def is_validation_approved(sphere: str, empreinte: str, val_id: Optional[str] =
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:
match = (val_id and item.get("id") == val_id) or (not val_id and item.get("empreinte") == empreinte)
if match:
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)
except Exception:
pass
return False
def record_pending_validation(sphere: str, val_id: str, empreinte: str, expires_iso: str, details: dict):
def record_pending_validation(sphere: str, val_id: str, empreinte: str, expires_iso: str = "", details: dict = None, code: Optional[str] = None):
v_path = get_validations_path()
data = {"validations": []}
if os.path.exists(v_path):
@@ -188,20 +245,25 @@ def record_pending_validation(sphere: str, val_id: str, empreinte: str, expires_
except Exception:
data = {"validations": []}
if not code:
code = f"{secrets.randbelow(1000000):06d}"
data.setdefault("validations", []).append({
"id": val_id,
"sphere": sphere,
"empreinte": empreinte,
"code": code,
"status": "PENDING",
"attempts": 0,
"created_at": datetime.datetime.now(TUNIS_TZ).isoformat(),
"expires_at": expires_iso,
"details": details
"details": details or {}
})
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):
def send_telegram_validation_request(sphere: str, val_id: str, code: 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:
@@ -218,8 +280,9 @@ def send_telegram_validation_request(sphere: str, val_id: str, tags: list, promp
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})"
f"• Réf : #{val_id}\n"
f"• Code : {code}\n\n"
f"Transmettre ce code à l'assistant pour autoriser la génération (expiration : {expires_str})"
)
url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
@@ -233,11 +296,11 @@ def send_telegram_validation_request(sphere: str, val_id: str, tags: list, promp
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):
def send_telegram_preview_mp3(sphere: str, mp3_path: str, task_id: str) -> Optional[int]:
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
return None
boundary = f"----TrebloBoundary{uuid.uuid4().hex}"
with open(mp3_path, "rb") as f:
@@ -259,9 +322,14 @@ def send_telegram_preview_mp3(sphere: str, mp3_path: str, task_id: str):
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"))
msg_id = data.get("result", {}).get("message_id")
logger.info("Aperçu MP3 envoyé à Telegram (message_id=%s)", msg_id)
if isinstance(msg_id, int):
log_envoi(task_id, sphere, msg_id)
return msg_id
except Exception as e:
logger.warning("Échec envoi aperçu MP3 Telegram: %s", e)
return None
@mcp.tool()
def solde(sphere: str) -> dict:
@@ -269,6 +337,77 @@ def solde(sphere: str) -> dict:
sp = validate_sphere_access(sphere)
return treblo_balance(sp)
@mcp.tool()
def valider(val_id: str, code: str) -> dict:
"""Valide une demande d'approbation préalable à la génération musicale à l'aide du code à 6 chiffres transmis à Nabil.
Approuve seulement si le code est exact, la demande non expirée (15 minutes) et non utilisée (3 essais max par demande)."""
val_id_clean = str(val_id).strip().lstrip("#")
code_input = str(code).strip()
v_path = get_validations_path()
if not os.path.exists(v_path):
raise ValueError("Aucune demande de validation trouvée")
with open(v_path, "r", encoding="utf-8") as f:
data = json.load(f)
target = None
for item in data.get("validations", []):
if item.get("id") == val_id_clean:
target = item
break
if not target:
raise ValueError(f"Demande de validation #{val_id_clean} introuvable")
st = target.get("status", "PENDING")
if st == "USED":
raise ValueError(f"Demande #{val_id_clean} déjà utilisée (consommée)")
if st in ("CANCELLED", "REJECTED"):
raise ValueError(f"Demande #{val_id_clean} déjà annulée ou rejetée")
if st == "EXPIRED":
raise ValueError(f"Demande #{val_id_clean} expirée")
now_dt = datetime.datetime.now(TUNIS_TZ)
exp = datetime.datetime.fromisoformat(target.get("expires_at"))
if now_dt >= exp:
target["status"] = "EXPIRED"
with open(v_path, "w", encoding="utf-8") as fw:
json.dump(data, fw, indent=2, ensure_ascii=False)
raise ValueError(f"Demande #{val_id_clean} expirée (délai de 15 minutes dépassé)")
attempts = target.get("attempts", 0)
if attempts >= 3:
target["status"] = "CANCELLED"
with open(v_path, "w", encoding="utf-8") as fw:
json.dump(data, fw, indent=2, ensure_ascii=False)
raise ValueError(f"Limite de 3 essais atteinte : la demande #{val_id_clean} est annulée.")
stored_code = str(target.get("code", "")).strip()
if not hmac.compare_digest(code_input, stored_code):
attempts += 1
target["attempts"] = attempts
if attempts >= 3:
target["status"] = "CANCELLED"
with open(v_path, "w", encoding="utf-8") as fw:
json.dump(data, fw, indent=2, ensure_ascii=False)
raise ValueError(f"Code incorrect. Limite de 3 essais atteinte : la demande #{val_id_clean} est annulée.")
else:
with open(v_path, "w", encoding="utf-8") as fw:
json.dump(data, fw, indent=2, ensure_ascii=False)
raise ValueError(f"Code incorrect pour la demande #{val_id_clean} ({3 - attempts} essai(s) restant(s)).")
target["status"] = "APPROVED"
target["approved_at"] = now_dt.isoformat()
with open(v_path, "w", encoding="utf-8") as fw:
json.dump(data, fw, indent=2, ensure_ascii=False)
return {
"status": "APPROVED",
"val_id": val_id_clean,
"sphere": target.get("sphere"),
"message": f"Demande #{val_id_clean} approuvée avec succès. Vous pouvez maintenant appeler generer."
}
@mcp.tool()
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.
@@ -294,12 +433,13 @@ 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()
empreinte = compute_empreinte(sp, tag_list, prompt, paroles)
# Contrôle de la validation humaine obligatoire (T2)
if not is_validation_approved(sp, empreinte, validation_id):
# Contrôle de la validation humaine obligatoire (usage unique)
clean_val_id = str(validation_id).strip().lstrip("#") if validation_id else None
if not consume_approved_validation(sp, empreinte, clean_val_id):
val_id = uuid.uuid4().hex[:8]
code = f"{secrets.randbelow(1000000):06d}"
now_tunis = datetime.datetime.now(TUNIS_TZ)
exp_dt = now_tunis + datetime.timedelta(minutes=15)
expires_iso = exp_dt.isoformat()
@@ -308,6 +448,7 @@ def generer(sphere: str, tags: Optional[List[str]] = None, paroles: Optional[str
send_telegram_validation_request(
sphere=sp,
val_id=val_id,
code=code,
tags=tag_list or [],
prompt=prompt or "",
paroles=paroles or "",
@@ -317,13 +458,14 @@ def generer(sphere: str, tags: Optional[List[str]] = None, paroles: Optional[str
sphere=sp,
val_id=val_id,
empreinte=empreinte,
code=code,
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"Refus : validation humaine requise par Telegram (demande non validée ou code non saisi). "
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."
f"Veuillez demander le code de validation à Nabil et utiliser l'outil valider(val_id='{val_id}', code=...) avant de relancer generer."
)
bal_avant = treblo_balance(sp)
@@ -537,7 +679,7 @@ 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)
# Relecture du solde réel après fin de tâche (T4)
# Relecture du solde réel après fin de tâche
credits_real = None
try:
bal = treblo_balance(sp)
@@ -547,7 +689,7 @@ def recuperer(task_id: str, sphere: str) -> dict:
update_journal_task(task_id, "SUCCESS", credits_apres=credits_real)
# Envoi de l'aperçu MP3 à Telegram (T3)
# Envoi de l'aperçu MP3 à Telegram et traçage dans envois.jsonl
if os.path.exists(mp3_file):
send_telegram_preview_mp3(sp, mp3_file, task_id)
@@ -598,7 +740,7 @@ class AuthAndSessionMiddleware(BaseHTTPMiddleware):
current_sphere_var.reset(token_cv)
async def health(request):
return JSONResponse({"status": "ok", "service": "treblo-mcp", "tools": 4})
return JSONResponse({"status": "ok", "service": "treblo-mcp", "tools": 5})
@asynccontextmanager
async def lifespan(app_instance):
+2 -2
View File
@@ -18,7 +18,7 @@ AUTH_HEADERS_NYORA = {
"Accept": "application/json, text/event-stream"
}
EXPECTED_TOOLS = {"generer", "statut", "recuperer", "solde"}
EXPECTED_TOOLS = {"generer", "recuperer", "solde", "statut", "valider"}
@pytest.fixture(scope="module")
def client():
@@ -31,7 +31,7 @@ def test_health(client):
data = r.json()
assert data.get("status") == "ok"
assert data.get("service") == "treblo-mcp"
assert data.get("tools") == 4
assert data.get("tools") == 5
def test_auth_rejection(client):
# Sans auth
+316
View File
@@ -0,0 +1,316 @@
# -*- coding: utf-8 -*-
import os
import json
import pytest
import datetime
from zoneinfo import ZoneInfo
from unittest.mock import MagicMock, patch
from cap_check import TUNIS_TZ, get_tunis_date, count_today
from main import (
compute_empreinte,
valider,
generer,
check_daily_cap,
update_journal_task,
get_journal_path,
get_validations_path,
current_sphere_var
)
@pytest.fixture(autouse=True)
def clean_env(monkeypatch, tmp_path):
# Fichiers temporaires pour isoler chaque test
j_file = str(tmp_path / "journal.jsonl")
v_file = str(tmp_path / "validations.json")
e_file = str(tmp_path / "envois.jsonl")
monkeypatch.setattr("main.get_journal_path", lambda: j_file)
monkeypatch.setattr("main.get_validations_path", lambda: v_file)
monkeypatch.setattr("main.get_envois_path", lambda: e_file)
# Variables d'environnement factices
monkeypatch.setenv("TREBLO_MCP_TOKEN_NYORA", "test_nyora_token_123456789012345678901234567890123456")
monkeypatch.setenv("TREBLO_MCP_TOKEN_PERSO", "test_perso_token_123456789012345678901234567890123456")
monkeypatch.setenv("TREBLO_KEY_NYORA", "test_nyora_key")
monkeypatch.setenv("TREBLO_KEY_PERSO", "test_perso_key")
monkeypatch.setenv("TELEGRAM_BOT_TOKEN_NYORA", "fake_bot_token")
monkeypatch.setenv("TELEGRAM_CHAT_ID", "2084513684")
# Neutraliser l'envoi réel de requêtes Telegram
monkeypatch.setattr("main.send_telegram_validation_request", lambda *args, **kwargs: None)
monkeypatch.setattr("main.send_telegram_preview_mp3", lambda *args, **kwargs: None)
def test_approbation_usage_unique(monkeypatch, tmp_path):
"""(a) Une approbation est à usage unique, consommée par la génération qu'elle autorise (statut USED), jamais réutilisable."""
v_file = str(tmp_path / "validations.json")
now_tunis = datetime.datetime.now(TUNIS_TZ)
exp = (now_tunis + datetime.timedelta(minutes=15)).isoformat()
emp = compute_empreinte("nyora", ["ambient"], "", "")
# Demande initiale approuvée
init_data = {
"validations": [
{
"id": "val_unique",
"sphere": "nyora",
"empreinte": emp,
"code": "123456",
"status": "APPROVED",
"attempts": 0,
"created_at": now_tunis.isoformat(),
"expires_at": exp,
"details": {"tags": ["ambient"], "prompt": "", "paroles": ""}
}
]
}
with open(v_file, "w", encoding="utf-8") as f:
json.dump(init_data, f)
token_cv = current_sphere_var.set("nyora")
try:
# Mock solde Treblo et appel API Treblo génération
monkeypatch.setattr("main.treblo_balance", lambda sp: {"sphere": sp, "total": 9200, "num_credits": 0, "num_credits_payg": 9200})
mock_resp = MagicMock()
mock_resp.read.return_value = json.dumps({"task_id": "task_unique_1", "status": "PENDING"}).encode("utf-8")
mock_resp.__enter__.return_value = mock_resp
monkeypatch.setattr("urllib.request.urlopen", lambda *args, **kwargs: mock_resp)
# 1er appel à generer : doit réussir et consommer l'approbation
res = generer(sphere="nyora", tags=["ambient"])
assert res.get("task_id") == "task_unique_1"
# Vérifier que le statut est passé à USED
with open(v_file, "r", encoding="utf-8") as f:
v_check = json.load(f)
assert v_check["validations"][0]["status"] == "USED"
# 2ème appel avec les mêmes paramètres : doit refuser car l'approbation est déjà consommée
with pytest.raises(ValueError) as exc:
generer(sphere="nyora", tags=["ambient"])
assert "validation humaine requise" in str(exc.value)
finally:
current_sphere_var.reset(token_cv)
def test_empreinte_inclut_tags():
"""(b) Empreinte = SHA-256 de (sphère, tags triés, prompt, paroles)."""
# Deux ensembles de tags différents donnent deux empreintes distinctes (même sans prompt ni paroles)
e1 = compute_empreinte("nyora", ["ambient"], "", "")
e2 = compute_empreinte("nyora", ["piano"], "", "")
assert e1 != e2
# L'ordre des tags ne change pas l'empreinte (tri canonique)
e_order1 = compute_empreinte("nyora", ["piano", "ambient"], "", "")
e_order2 = compute_empreinte("nyora", ["ambient", "piano"], "", "")
assert e_order1 == e_order2
# La sphère influence l'empreinte
e_perso = compute_empreinte("perso", ["ambient"], "", "")
assert e_perso != e1
# Prompt ou paroles modifient l'empreinte
e_prompt = compute_empreinte("nyora", ["ambient"], "un prompt jazz", "")
assert e_prompt != e1
def test_valider_code_incorrect_refuse(tmp_path):
"""(c) valider refuse si le code à 6 chiffres est incorrect."""
v_file = str(tmp_path / "validations.json")
now_tunis = datetime.datetime.now(TUNIS_TZ)
exp = (now_tunis + datetime.timedelta(minutes=15)).isoformat()
init_data = {
"validations": [
{
"id": "val_bad_code",
"sphere": "nyora",
"empreinte": "dummy_emp",
"code": "555666",
"status": "PENDING",
"attempts": 0,
"created_at": now_tunis.isoformat(),
"expires_at": exp,
"details": {}
}
]
}
with open(v_file, "w", encoding="utf-8") as f:
json.dump(init_data, f)
# Tentative avec un mauvais code
with pytest.raises(ValueError) as exc:
valider("val_bad_code", "000000")
assert "Code incorrect" in str(exc.value)
# Statut toujours PENDING, 1 essai comptabilisé
with open(v_file, "r", encoding="utf-8") as f:
data = json.load(f)
v = data["validations"][0]
assert v["status"] == "PENDING"
assert v["attempts"] == 1
def test_valider_code_limite_essais(tmp_path):
"""(d) Trois essais au plus par demande, puis la demande est annulée."""
v_file = str(tmp_path / "validations.json")
now_tunis = datetime.datetime.now(TUNIS_TZ)
exp = (now_tunis + datetime.timedelta(minutes=15)).isoformat()
init_data = {
"validations": [
{
"id": "val_3attempts",
"sphere": "nyora",
"empreinte": "dummy_emp",
"code": "789123",
"status": "PENDING",
"attempts": 0,
"created_at": now_tunis.isoformat(),
"expires_at": exp,
"details": {}
}
]
}
with open(v_file, "w", encoding="utf-8") as f:
json.dump(init_data, f)
# 1er échec
with pytest.raises(ValueError):
valider("val_3attempts", "111111")
# 2ème échec
with pytest.raises(ValueError):
valider("val_3attempts", "222222")
# 3ème échec -> déclenche l'annulation
with pytest.raises(ValueError) as exc3:
valider("val_3attempts", "333333")
assert "annulée" in str(exc3.value).lower()
# Vérification que le statut est CANCELLED
with open(v_file, "r", encoding="utf-8") as f:
data = json.load(f)
assert data["validations"][0]["status"] == "CANCELLED"
# Même avec le code exact, la demande annulée est refusée
with pytest.raises(ValueError) as exc_after:
valider("val_3attempts", "789123")
assert "annulée" in str(exc_after.value).lower()
def test_valider_expiration(tmp_path):
"""(e) Une demande de validation expirée (15 minutes) ne peut pas être validée."""
v_file = str(tmp_path / "validations.json")
now_tunis = datetime.datetime.now(TUNIS_TZ)
# Expirée il y a 5 minutes
exp = (now_tunis - datetime.timedelta(minutes=5)).isoformat()
init_data = {
"validations": [
{
"id": "val_expired",
"sphere": "nyora",
"empreinte": "dummy_emp",
"code": "123456",
"status": "PENDING",
"attempts": 0,
"created_at": (now_tunis - datetime.timedelta(minutes=20)).isoformat(),
"expires_at": exp,
"details": {}
}
]
}
with open(v_file, "w", encoding="utf-8") as f:
json.dump(init_data, f)
with pytest.raises(ValueError) as exc:
valider("val_expired", "123456")
assert "expirée" in str(exc.value).lower()
with open(v_file, "r", encoding="utf-8") as f:
data = json.load(f)
assert data["validations"][0]["status"] == "EXPIRED"
def test_generer_sans_validation_sans_debit(monkeypatch, tmp_path):
"""(f) Un appel generer sans validation préalable refuse la génération sans aucun débit."""
token_cv = current_sphere_var.set("nyora")
try:
# Mock solde Treblo
balance_called = {"val": False}
def fake_balance(sp):
balance_called["val"] = True
return {"sphere": sp, "total": 9200, "num_credits": 0, "num_credits_payg": 9200}
monkeypatch.setattr("main.treblo_balance", fake_balance)
# Aucune validation dans validations.json
with pytest.raises(ValueError) as exc:
generer(sphere="nyora", tags=["ambient", "chill"])
err_msg = str(exc.value)
assert "validation humaine requise" in err_msg.lower()
# Le message de refus envoyé à l'agent ne doit JAMAIS contenir le code à 6 chiffres
with open(str(tmp_path / "validations.json"), "r", encoding="utf-8") as f:
v_data = json.load(f)
assert len(v_data["validations"]) == 1
created_val = v_data["validations"][0]
code = created_val["code"]
assert len(code) == 6
assert code not in err_msg
# Aucun journal écrit
j_path = str(tmp_path / "journal.jsonl")
assert not os.path.exists(j_path) or os.path.getsize(j_path) == 0
finally:
current_sphere_var.reset(token_cv)
def test_plafond_jour_tunis(monkeypatch, tmp_path):
"""(g) Plafond journalier calculé en jour civil de Tunis."""
j_file = str(tmp_path / "journal.jsonl")
now_tunis = datetime.datetime.now(TUNIS_TZ)
today_tunis = now_tunis.strftime("%Y-%m-%d")
# Écrire 5 entrées horodatées aujourd'hui en heure de Tunis
entries = [
{"date": f"{today_tunis}T08:00:00+01:00", "sphere": "nyora", "statut": "SUCCESS"},
{"date": f"{today_tunis}T09:00:00+01:00", "sphere": "nyora", "statut": "SUCCESS"},
{"date": f"{today_tunis}T10:00:00+01:00", "sphere": "nyora", "statut": "SUCCESS"},
{"date": f"{today_tunis}T11:00:00+01:00", "sphere": "nyora", "statut": "SUCCESS"},
{"date": f"{today_tunis}T12:00:00+01:00", "sphere": "nyora", "statut": "SUCCESS"},
# Une entrée d'hier à Tunis (ne doit pas être comptée)
{"date": "2026-10-30T10:00:00+01:00", "sphere": "nyora", "statut": "SUCCESS"},
]
with open(j_file, "w", encoding="utf-8") as f:
for e in entries:
f.write(json.dumps(e) + "\n")
monkeypatch.setenv("TREBLO_DAILY_CAP", "5")
# Pour nyora : 5 aujourd'hui -> CAP_REFUSED
with pytest.raises(ValueError) as exc:
check_daily_cap("nyora")
assert "CAP_REFUSED" in str(exc.value)
# Pour perso : 0 aujourd'hui -> OK
check_daily_cap("perso")
def test_credits_apres_reel(tmp_path):
"""(h) Le journal consigne credits_apres avec le solde réel de l'API Treblo après exécution."""
j_file = str(tmp_path / "journal.jsonl")
task_id = "test_task_solde"
init_entry = {
"date": "2026-11-02T10:00:00Z",
"sphere": "nyora",
"task_id": task_id,
"statut": "PENDING",
"credits_avant": 9300,
"credits_apres": 9300
}
with open(j_file, "w", encoding="utf-8") as f:
f.write(json.dumps(init_entry) + "\n")
# Mise à jour avec le solde réel constaté après génération (débit de 100 crédits -> 9200)
update_journal_task(task_id, "SUCCESS", credits_apres=9200)
with open(j_file, "r", encoding="utf-8") as f:
line = f.readline().strip()
data = json.loads(line)
assert data["statut"] == "SUCCESS"
assert data["credits_apres"] == 9200
+5 -4
View File
@@ -1,6 +1,6 @@
#!/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)."""
"""CLI pour la gestion et l'audit de la validation humaine Treblo MCP (Ticket nyora-2026-10-216-b/c)."""
import os
import sys
import json
@@ -46,17 +46,18 @@ def list_validations():
def update_status(val_id: str, new_status: str):
data = load()
found = False
clean_id = val_id.strip().lstrip("#")
for v in data.get("validations", []):
if v.get("id") == val_id:
if v.get("id") == clean_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}.")
print(f"Demande #{clean_id} mise à jour avec le statut {new_status}.")
else:
print(f"Demande #{val_id} introuvable.")
print(f"Demande #{clean_id} introuvable.")
def main():
if len(sys.argv) < 2 or sys.argv[1] == "list":